text:
package common

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"regexp"
	"strconv"
)

var sequenceRe = regexp.MustCompile("([a-fA-F0-9]+)\\.([a-fA-F0-9]+)\\.([a-fA-F0-9]+)")
var networkByteOrder = binary.BigEndian

/*
A Sequence represents a unique position in the list of changes. It consists
of a postgres LSN that represents when a transaction was committed, and a
index into the list of changes in that transaction.
*/
type Sequence struct {
	LSN   uint64
	Index uint32
}

/*
MakeSequence makes a new sequence from an LSN and an index.
*/
func MakeSequence(lsn uint64, index uint32) Sequence {
	return Sequence{
		LSN:   lsn,
		Index: index,
	}
}

/*
ParseSequence parses a stringified sequence.
*/
func ParseSequence(s string) (Sequence, error) {
	parsed := sequenceRe.FindStringSubmatch(s)
	if parsed == nil {
		return Sequence{}, errors.New("Invalid sequence string")
	}

	l1, err := strconv.ParseUint(parsed[1], 16, 32)
	if err != nil {
		return Sequence{}, fmt.Errorf("Invalid sequence: %s", err)
	}

	l2, err := strconv.ParseUint(parsed[2], 16, 32)
	if err != nil {
		return Sequence{}, fmt.Errorf("Invalid sequence: %s", err)
	}
	ix, err := strconv.ParseUint(parsed[3], 16, 32)
	if err != nil {
		return Sequence{}, fmt.Errorf("Invalid sequence: %s", err)
	}

	return Sequence{
		LSN:   (l1 << 32) | l2,
		Index: uint32(ix),
	}, nil
}

/*
ParseSequenceBytes parses bytes written using Bytes().
As a convenience, an empty sequence parses to the default
value for the Sequence type.
*/
func ParseSequenceBytes(b []byte) (Sequence, error) {
	if len(b) == 0 {
		return Sequence{}, nil
	}
	if len(b) != 12 {
		return Sequence{}, errors.New("Invalid byte sequence")
	}

	buf := bytes.NewBuffer(b)

	var lsn uint64
	err := binary.Read(buf, networkByteOrder, &lsn)
	if err != nil {
		return Sequence{}, fmt.Errorf("Invalid byte sequence: %s", err)
	}

	var ix uint32
	err = binary.Read(buf, networkByteOrder, &ix)
	if err != nil {
		return Sequence{}, fmt.Errorf("Invalid byte sequence: %s", err)
	}

	return Sequence{
		LSN:   lsn,
		Index: ix,
	}, nil
}

/*
String turns the sequence into the canonical string form, which looks
like this: "XXX.YYY.ZZZ," where each component is a hexadecimal number.
This is different from the standard Postgres format, which includes a
slash in the first part, in that it doesn't need URL encoding.
*/
func (s Sequence) String() string {
	return strconv.FormatUint(s.LSN>>32, 16) + "." +
		strconv.FormatUint(s.LSN&0xffffffff, 16) + "." +
		strconv.FormatUint(uint64(s.Index), 16)
}

/*
Bytes turns the sequence into an array of 12 bytes, in "network" (aka
big-endian) byte order.
*/
func (s Sequence) Bytes() []byte {
	buf := &bytes.Buffer{}
	binary.Write(buf, networkByteOrder, s.LSN)
	binary.Write(buf, networkByteOrder, s.Index)
	return buf.Bytes()
}

/*
Compare returns if the current sequence is less than, greater to, or
equal to the specified sequence.
*/
func (s Sequence) Compare(o Sequence) int {
	if s.LSN < o.LSN {
		return -1
	}
	if s.LSN > o.LSN {
		return 1
	}
	if s.Index < o.Index {
		return -1
	}
	if s.Index > o.Index {
		return 1
	}
	return 0
}


text:
  <form id="loginForm" name="login" target="frame" method="post" action="<%=helpdeskAction%>">
      <input type="hidden" name="username" value="<%=helpdeskUsername%>" />
      <input type="hidden" name="password" value="<%=helpdeskPassword%>" />
      <input id='submit' type='submit' name='op' value='Login' style='display: none'/>
  </form>

redpajama_set_name: RedPajamaGithub


text:
from django.conf import settings
from django.test import TestCase

from frigg.builds.models import Build, Project
from frigg.deployments.models import PRDeployment

class PRDeploymentManagerTests(TestCase):
    def setUp(self):
        project = Project.objects.create(owner='frigg', name='frigg-hq')
        build = Build.objects.create(project=project, build_number=1)
        PRDeployment.objects.create(build=build, image='ubuntu')
        self.build = Build.objects.create(project=project, build_number=2)

    def test_create_should_not_override_port_in_kwargs(self):
        deployment = PRDeployment.objects.create(build=self.build, image='ubuntu', port=50000)
        self.assertEqual(deployment.port, 50000)

    def test_create_should_set_port_if_not_in_kwargs(self):
        deployment = PRDeployment.objects.create(build=self.build, image='ubuntu')
        self.assertEqual(deployment.port, 49153)

    def test_create_should_set_port_to_49152_if_it_is_to_high(self):
        deployment = PRDeployment.objects.create(build=self.build, image='ubuntu', port=65536)
        self.assertEqual(deployment.port, 49152)

    def test_create_should_set_port_to_49152_if_it_is_to_low(self):
        deployment = PRDeployment.objects.create(build=self.build, image='ubuntu', port=49151)
        self.assertEqual(deployment.port, 49152)

    def test_create_with_image(self):
        deployment = PRDeployment.objects.create(build=self.build, image='ubuntu', port=49151)
        self.assertEqual(deployment.queue_object['image'], 'ubuntu')

    def test_create_without_image_should_fallback_to_default(self):
        deployment = PRDeployment.objects.create(build=self.build, port=49151)
        self.assertEqual(deployment.queue_object['image'], settings.FRIGG_PREVIEW_IMAGE)


text:
using JoinRpg.DataModel;

namespace JoinRpg.Services.Interfaces;

public interface IAccommodationInviteService
{/*
    Task<AccommodationInvite> CreateAccommodationInvite(int projectId,
        int senderClaimId,
        int receiverClaimId,
        int accommodationRequestId);
        */
    Task<IEnumerable<AccommodationInvite?>?> CreateAccommodationInviteToGroupOrClaim(int projectId,
        int senderClaimId,
        string receiverClaimOrAccommodationRequestId,
        int accommodationRequestId,
        string accommodationRequestPrefix);

    Task<AccommodationInvite?> CancelOrDeclineAccommodationInvite(int inviteId,
        AccommodationRequest.InviteState newState);

    Task<AccommodationInvite?> AcceptAccommodationInvite(int projectId,
        int inviteId);

    Task DeclineAllClaimInvites(int claimId);
}


text:
cask 'malwarebytes-anti-malware' do
  version '1.1.3.72'
  sha256 '9ef3c6e40b7995e6b9d1b4724881e21f8b4028c5199f346215cb8afb148a925e'

  # mbamupdates.com is the official download host per the vendor homepage
  url "https://data-cdn.mbamupdates.com/v1/mbam-mac/data/mbam-mac-#{version}.zip"
  appcast 'https://data-cdn.mbamupdates.com/v1/mbam-mac/updates.xml',
          checkpoint: '8bd67ab2c2f0959f571a2d5be0ada2627eedf81a73dad618b26360a1d9eab3df'
  name 'Malwarebytes Anti-Malware for Mac'
  name 'AdwareMedic'
  homepage 'https://www.malwarebytes.org/antimalware/mac/'
  license :gratis

  depends_on macos: '>= :lion'

  app 'Malwarebytes Anti-Malware.app'

  zap delete: [
                '~/Library/Preferences/com.malwarebytes.antimalware.plist',
                '~/Library/Caches/com.malwarebytes.antimalware',
                '~/Library/Application Support/com.malwarebytes.antimalware',
                '~/Library/Saved Application State/com.malwarebytes.antimalware.savedState',
              ]
end


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))

describe QueueStick::Worker do
  describe "process" do
    it "should raise NotImplementedError at the base class" do
      lambda {
        worker = QueueStick::Worker.new
        worker.process("my message")
      }.should raise_error(NotImplementedError)
    end
  end

  describe "shell_run" do
    before(:all) do
      @worker = QueueStick::Worker.new
    end

    it "should raise an error if a process fails" do
      lambda {
        @worker.shell_run("ls -l /fds8aufj92njkdsajfdslafjdsafdsa 2>/dev/null")
      }.should raise_error(QueueStick::Worker::ShellCommandError)
    end

    it "should not raise an error if a process doesn't fail" do
      lambda {
        @worker.shell_run("ls -l /")
      }.should_not raise_error
    end

    it "should return its output" do
      result = @worker.shell_run("ls -l /")
      result.should_not be_empty
      result.should =~ /bin/  # is this a bad assumption?
    end
  end

  describe "run_loop" do
    class RunLoopTestWorker < QueueStick::Worker
    end

    before(:each) do
      @message = QueueStick::MockMessage.new("foo")
      @worker = RunLoopTestWorker.new
      @worker.should_receive(:get_message_from_queue).
        any_number_of_times.
        and_return(@message)
    end

    it "should not raise an error if #process raises an error/exception" do
      @worker.should_receive(:process).and_raise(Exception)
      @worker.should_receive(:recover).and_return(true)

      lambda {
        @worker.run_loop
      }.should_not raise_error
    end

    it "should not raise an error if both #process and #recover raise an error/exception" do
      @worker.should_receive(:process).and_raise(Exception)
      @worker.should_receive(:recover).and_raise(Exception)

      lambda {
        @worker.run_loop
      }.should_not raise_error
    end

    it "should put itself to sleep and return if there are no queue messages" do
      worker = QueueStick::MockWorker.new
      worker.should_receive(:get_message_from_queue).and_return(nil)
      worker.should_not_receive(:process)

      t = Thread.new(worker) do |w|
        w.run_loop
      end

      # wait for sleep
      while !t.stop?
      end

      t.status.should == 'sleep'
      t.kill
    end

    it "should automatically increment messages_processed on each loop" do
      worker = QueueStick::MockWorker.new
      worker.run_loop
      worker.counter(:messages_processed).counts[0].should == 1
      worker.run_loop
      worker.counter(:messages_processed).counts[0].should == 2
    end

    it "should automatically increment errors_caught on each error loop" do
      worker = QueueStick::MockWorker.new
      worker.should_receive(:process).twice.and_raise(ArgumentError)
      worker.counter(:errors_caught).counts[0].should == 0
      worker.run_loop
      worker.counter(:errors_caught).counts[0].should == 1
      worker.run_loop
      worker.counter(:errors_caught).counts[0].should == 2
    end

    it "should call delete_message_from_queue if process succeeds" do
      @worker.should_receive(:process).and_return(true)
      @worker.should_receive(:delete_message_from_queue).and_return(true)
      @worker.run_loop
    end

    it "should not call delete_message_from_queue if process fails" do
      @worker.should_receive(:process).and_raise(Exception)
      @worker.should_receive(:recover).with(anything).and_return(true)
      @worker.should_not_receive(:delete_message_from_queue)
      @worker.run_loop
    end

    it "should terminate after a run if the current thread's :shutdown variable is set" do
      worker = QueueStick::MockWorker.new
      thread = Thread.new do
        worker.run_loop while true
      end
      thread[:shutdown] = true

      thread.join
      thread.should_not be_alive
    end

    it "should log errors when process fails" do
      @worker.should_receive(:process).and_raise(Exception)
      @worker.should_receive(:recover).and_return(true)
      @worker.run_loop

      @worker.errors.should have(1).thing
    end

    it "should not log any more errors than MAX_ERRORS" do
      @worker.should_receive(:process).at_least(:once).and_raise(Exception)
      @worker.should_receive(:recover).at_least(:once).and_return(true)

      (QueueStick::Worker::MAX_ERRORS*2).times { @worker.run_loop }
      @worker.errors.should have(QueueStick::Worker::MAX_ERRORS).things
    end
  end

  describe "counter" do
    it "should return a counter that has been defined on the class" do
      worker = QueueStick::Worker.new
      counter = worker.counter(:messages_processed)
      counter.should be_an_instance_of(QueueStick::BlendedCounter)
    end

    it "should not return a counter if it hasn't been defined for the class" do
      worker = QueueStick::Worker.new
      worker.counter(:not_a_counter).should be_nil
    end
  end

  describe "recover" do
    it "should raise NotImplementedError at the base class" do
      lambda {
        worker = QueueStick::Worker.new
        worker.recover(:foo)
      }.should raise_error(NotImplementedError)
    end
  end

  describe "self.counter" do
    it "should define a counter that the class keeps track of" do
      class WorkerE < QueueStick::Worker
        counter :how_many_times_did_chewie_think_with_his_stomach
      end

      WorkerE.counters.should include(:how_many_times_did_chewie_think_with_his_stomach)
    end

    it "should always have a counter to keep track of number of messages processed" do
      QueueStick::Worker.counters.should include(:messages_processed)
      class WorkerF < QueueStick::Worker
      end
      WorkerF.counters.should include(:messages_processed)
    end

    it "should always have a counter to keep track of errors caught" do
      QueueStick::Worker.counters.should include(:errors_caught)
      class WorkerG < QueueStick::Worker
      end
      WorkerG.counters.should include(:errors_caught)
    end

    it "should not add the same counter twice" do
      QueueStick::Worker.counter :c1
      QueueStick::Worker.counter :c1

      c1s = QueueStick::Worker.counters.select { |c| c == :c1 }
      c1s.should have(1).thing
    end
  end

  describe "delete_message_from_queue" do
    it "should raise a NotImplementedError" do
      lambda {
        QueueStick::Worker.new.delete_message_from_queue(nil)
      }.should raise_error(NotImplementedError)
    end
  end

  describe "get_message_from_queue" do
    it "should raise a NotImplementedError" do
      lambda {
        QueueStick::Worker.new.get_message_from_queue
      }.should raise_error(NotImplementedError)
    end
  end
end


text:
layout: docs
title: Extending WireMock
toc_rank: 110
redirect_from: "/extending-wiremock.html"
description: Extending WireMock via custom code.
---

## Registering Extensions

You can register the extension programmatically via its class name,
class or an instance:

```java
new WireMockServer(wireMockConfig()
  .extensions("com.mycorp.BodyContentTransformer", "com.mycorp.HeaderMangler"));

new WireMockServer(wireMockConfig()
  .extensions(BodyContentTransformer.class, HeaderMangler.class));

new WireMockServer(wireMockConfig()
  .extensions(new BodyContentTransformer(), new HeaderMangler()));
```

See [Running as a Standalone Process](/docs/running-standalone/) for details on running with extensions from the command line.

## Transforming Responses

Sometimes, returning wholly static responses to stub requests isn't
practical e.g. when there are transaction IDs being passed between
request/responses, dates that must be current. Via WireMock's extension
mechanism it is possible to dynamically modify responses, allowing
header re-writing and templated responses amongst other things.

There are two ways to dynamically transform output from WireMock.
WireMock stub mappings consist in part of a `ResponseDefinition`. This
is essentially a description that WireMock (sometimes) combines with
other information when producing the final response. A basic
`ResponseDefinition` closely resembles an actual response in that it has
status, headers and body fields, but it can also indicate to WireMock
that the actual response should be the result of a proxy request to
another system or a fault of some kind.

`ResponseDefinition` objects are "rendered" by WireMock into a
`Response`, and it is possible to interject either before or after this
process when writing an extension, meaning you can either transform the
`ResponseDefinition` prior to rendering, or the rendered `Response`
afterwards.

Parameters
----------

Transformer extensions can have parameters passed to them on a per-stub
basis via a `Parameters` object passed to their primary method.
`Parameters` derives from Java's `Map` and can be therefore arbitrarily
deeply nested. Only types compatible with JSON (strings, numbers,
booleans, maps and lists) can be used.

Response definition transformation
----------------------------------

To transform `ResponseDefinition`, extend the
`ResponseDefinitionTransformer` class:

```java
public static class ExampleTransformer extends ResponseDefinitionTransformer {

        @Override
        public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) {
            return new ResponseDefinitionBuilder()
                    .withHeader("MyHeader", "Transformed")
                    .withStatus(200)
                    .withBody("Transformed body")
                    .build();
        }

        @Override
        public String getName() {
            return "example";
        }
    }
```

Transformer classes must have a no-args constructor unless you only
intend to register them via an instance as described below.

### Supplying parameters

Parameters are supplied on a per stub mapping basis:

```java
stubFor(get(urlEqualTo("/transform")).willReturn(
        aResponse()
                .withTransformerParameter("newValue", 66)
                .withTransformerParameter("inner", ImmutableMap.of("thing", "value")))); // ImmutableMap is from Guava, but any Map will do
```

or:

```json
{
    "request" : {
        "url" : "/transform",
        "method" : "GET"
    },
    "response" : {
        "status" : 200,
        "transformerParameters" : {
            "newValue" : 66,
            "inner" : {
                "thing" : "value"
            }
        }
    }
}
```

### Non-global transformations

By default transformations will be applied globally. If you only want
them to apply in certain cases you can refer to make them non-global by
adding this to your transformer class:

```java
@Override
public boolean applyGlobally() {
    return false;
}
```

Then you add the transformation to specific stubs via its name:

```java
stubFor(get(urlEqualTo("/local-transform")).willReturn(aResponse()
        .withStatus(200)
        .withBody("Original body")
        .withTransformers("my-transformer", "other-transformer")));
```

or:

```json
{
    "request": {
        "method": "GET",
        "url": "/local-transform"
    },
    "response": {
        "status": 200,
        "body": "Original body",
        "transformers": ["my-transformer", "other-transformer"]
    }
}
```

The Java API also has a convenience method for adding transformers and
parameters in one call:

```java
stubFor(get(urlEqualTo("/transform")).willReturn(
        aResponse()
                .withTransformer("body-transformer", "newValue", 66)));
```

### Response transformation

A response transformer extension class is identical to
`ResponseDefinitionTransformer` with the exception that it takes a
`Response` in its transform method's parameter list and returns a
`Response`.

```java
public static class StubResponseTransformerWithParams extends ResponseTransformer {

        @Override
        public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
            return Response.Builder.like(response)
                    .but().body(parameters.getString("name") + ", "
                            + parameters.getInt("number") + ", "
                            + parameters.getBoolean("flag"))
                    .build();
        }

        @Override
        public String getName() {
            return "stub-transformer-with-params";
        }
}
```

## Custom Request Matchers

If WireMock's standard set of request matching strategies isn't
sufficient, you can register one or more request matcher classes
containing your own logic.

Custom matchers can be attached directly to stubs via the Java API when
using the local admin interface (by calling `stubFor(...)` on
`WireMockServer` or `WireMockRule`). They can also be added via the
extension mechanism and used with individual stubs by referring to them
by name as described above for response transformers.

As with response transformers, per stub mapping parameters can be passed
to matchers.

To add a matcher directly to a stub mapping:

```java
wireMockServer.stubFor(requestMatching(new RequestMatcherExtension() {
    @Override
    public MatchResult match(Request request, Parameters parameters) {
        return MatchResult.of(request.getBody().length > 2048);
    }
}).willReturn(aResponse().withStatus(422)));
```

In Java 8 and above this can be achieved using a lambda:

```java
wireMockServer.stubFor(requestMatching(request ->
    MatchResult.of(request.getBody().length > 2048);
).willReturn(aResponse().withStatus(422)));
```

To create a matcher to be referred to by name, create a class extending
`RequestMatcher` and register it as an extension as per the instructions
at the top of this page e.g.

```java
public class BodyLengthMatcher extends RequestMatcherExtension {

    @Override
    public String getName() {
        return "body-too-long";
    }

    @Override
    public MatchResult match(Request request, Parameters parameters) {
        int maxLength = parameters.getInt("maxLength");
        return MatchResult.of(request.getBody().length > maxLength);
    }
}
```

Then define a stub with it:

```java
stubFor(requestMatching("body-too-long", Parameters.one("maxLemgth", 2048))
        .willReturn(aResponse().withStatus(422)));
```

or via JSON:

```json
{
    "request" : {
        "customMatcher" : {
            "name" : "body-too-long",
            "parameters" : {
                "maxLemgth" : 2048
            }
        }
    },
    "response" : {
        "status" : 422
    }
}
```

## Post-serve actions

You can add behaviour that runs after a response has been completely served by extending `PostServeAction` and registering
as an extension (see above for details).

`PostServeAction` has two template methods either or both of which can be overridden depending on desired behaviour.
To add per-stub behaviour override `doAction(...)`. Overriding `doGlobalAction(...)` will add the behaviour globally.

## Admin API extensions

Additional API routes under WireMock's `/__admin` endpoint can be configured by implementing `AdminApiExtension`.

## Listening for requests

If you're using the JUnit rule or you've started `WireMockServer`
programmatically, you can register listeners to be called when a request
is received.

e.g. with the JUnit rule:

```java
List<Request> requests = new ArrayList<Request>();
rule.addMockServiceRequestListener(new RequestListener() {
     @Override
     public void requestReceived(Request request, Response response) {
         requests.add(LoggedRequest.createFrom(request));
     }
});

for (Request request: requests) {
    assertThat(request.getUrl(), containsString("docId=92837592847"));
}
```

## Listening for raw traffic

If you would like to observe raw HTTP traffic to and from Jetty
for debugging purposes you can use a ```WiremockNetworkTrafficListener```.

One scenario where it can be useful is where Jetty
alters the response from Wiremock before sending it to the client.
(An example of that is where Jetty appends a --gzip postfix to the ETag response header
if the response is gzipped.)
Using a ```RequestListener``` in this case would not show those alterations.

To output all raw traffic to console use ```ConsoleNotifyingWiremockNetworkTrafficListener```, for example:

```java
new WireMockServer(wireMockConfig()
    .networkTrafficListener(new ConsoleNotifyingWiremockNetworkTrafficListener()));
```

If you would like to collect the traffic
and for example add it to your acceptance test's output,
you can use the ```CollectingNetworkTrafficListener```.


text:
package m_etcd

import (
	"path"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"github.com/coreos/go-etcd/etcd"
	"github.com/lytics/metafora"
)

/*
	Running the Integration Test:
	#if you don't have etcd install use this script to set it up:
	sudo bash ./scripts/docker_run_etcd.sh

ETCDTESTS=1 go test -v ./...
*/

func TestCoordinatorFirstNodeJoiner(t *testing.T) {
	coordinator1, client := setupEtcd(t)
	defer coordinator1.Close()
	if err := coordinator1.Init(newCtx(t, "coordinator1")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}

	const sorted = false
	const recursive = false
	_, err := client.Get(namespace+"/tasks", sorted, recursive)
	if err != nil && strings.Contains(err.Error(), "Key not found") {
		t.Fatalf("The tasks path wasn't created when the first node joined: path[%s]", namespace+"/tasks")
	} else if err != nil {
		t.Fatalf("Unknown error trying to test: err: %s", err.Error())
	}

	//TODO test for node path too...
}

// Ensure that Watch() picks up new tasks and returns them.
//
func TestCoordinatorTC1(t *testing.T) {
	coordinator1, client := setupEtcd(t)
	if err := coordinator1.Init(newCtx(t, "coordinator1")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	defer coordinator1.Close()

	watchRes := make(chan string)
	task001 := "test-task0001"
	taskPath := path.Join(namespace, TasksPath, task001)

	go func() {
		//Watch blocks, so we need to test it in its own go routine.
		taskId, err := coordinator1.Watch()
		if err != nil {
			t.Fatalf("coordinator1.Watch() returned an err: %v", err)
		}
		t.Logf("We got a task id from the coordinator1.Watch() res:%s", taskId)

		watchRes <- taskId
	}()

	client.CreateDir(taskPath, 5)

	select {
	case taskId := <-watchRes:
		if taskId != task001 {
			t.Fatalf("coordinator1.Watch() test failed: We received the incorrect taskId.  Got [%s] Expected[%s]", taskId, task001)
		}
	case <-time.After(time.Second * 5):
		t.Fatalf("coordinator1.Watch() test failed: The testcase timed out after 5 seconds.")
	}
}

//   Submit a task while a coordinator is actively watching for tasks.
//
func TestCoordinatorTC2(t *testing.T) {
	coordinator1, client := setupEtcd(t)
	if err := coordinator1.Init(newCtx(t, "coordinator1")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	defer coordinator1.Close()

	result := make(chan error, 1)
	testTasks := []string{"test-claiming-task0001", "test-claiming-task0002", "test-claiming-task0003"}

	mclient := NewClient(namespace, client)

	go func() {
		//Watch blocks, so we need to test it in its own go routine.
		taskId, err := coordinator1.Watch()
		if err != nil {
			result <- err
			return
			t.Fatalf("coordinator1.Watch() returned an err: %v", err)
		}

		t.Logf("We got a task id from the coordinator1.Watch() res: %s", taskId)

		if ok := coordinator1.Claim(taskId); !ok {
			result <- err
			return
			t.Fatal("coordinator1.Claim() unable to claim the task")
		}

		result <- nil
	}()

	time.Sleep(24 * time.Millisecond)
	err := mclient.SubmitTask(testTasks[0])
	if err != nil {
		t.Fatalf("Error submitting a task to metafora via the client.  Error:\n%v", err)
	}

	select {
	case res := <-result:
		if res != nil {
			t.Fatalf("Background test checker failed so the test failed: %v", res)
		}
	case <-time.After(time.Second * 5):
		t.Fatalf("Test failed: The testcase timed out after 5 seconds.")
	}
}

//   1) Submit two tasks between calls to coordinator.Watch() to make sure the
//   coordinator picks up tasks made between requests to Watch().
//
//   2) Try claiming the same taskId twice.
//
func TestCoordinatorTC3(t *testing.T) {
	coordinator1, client := setupEtcd(t)
	if err := coordinator1.Init(newCtx(t, "coordinator1")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	defer coordinator1.Close()
	coordinator2 := NewEtcdCoordinator("node2", namespace, client).(*EtcdCoordinator)
	if err := coordinator2.Init(newCtx(t, "coordinator2")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	defer coordinator2.Close()

	test_finished := make(chan bool)
	testTasks := []string{"test-claiming-task0001", "test-claiming-task0002", "test-claiming-task0003"}

	mclient := NewClient(namespace, client)

	startATaskWatcher := func() {
		//Watch blocks, so we need to test it in its own go routine.
		taskId, err := coordinator1.Watch()
		if err != nil {
			t.Fatalf("coordinator1.Watch() returned an err: %v", err)
		}

		_, err = coordinator2.Watch() //coordinator2 should also pickup this task
		if err != nil {
			t.Fatalf("coordinator2.Watch() returned an err: %v", err)
		}

		t.Logf("We got a task id from the coordinator1.Watch() res: %s", taskId)

		if ok := coordinator1.Claim(taskId); !ok {
			t.Fatal("coordinator1.Claim() unable to claim the task")
		}

		//Try to claim the task in a second coordinator.  Should fail
		if ok := coordinator2.Claim(taskId); ok {
			t.Fatal("coordinator1.Claim() unable to claim the task")
		}

		test_finished <- true
	}

	err := mclient.SubmitTask(testTasks[1])
	if err != nil {
		t.Fatalf("Error submitting a task to metafora via the client. Error:\n%v", err)
	}
	err = mclient.SubmitTask(testTasks[2])
	if err != nil {
		t.Fatalf("Error submitting a task to metafora via the client. Error:\n%v", err)
	}

	go startATaskWatcher()
	select {
	case res := <-test_finished:
		if !res {
			t.Fatalf("Background test checker failed so the test failed.")
		}
	case <-time.After(time.Second * 5):
		t.Fatalf("Test failed: The testcase timed out after 5 seconds.")
	}
	go startATaskWatcher()
	select {
	case res := <-test_finished:
		if !res {
			t.Fatalf("Background test checker failed so the test failed.")
		}
	case <-time.After(time.Second * 5):
		t.Fatalf("Test failed: The testcase timed out after 5 seconds.")
	}
}

// Submit a task before any coordinators are active.  Then start a coordinator to
// ensure the tasks are picked up by the new coordinator
//
// Then call coordinator.Release() on the task to make sure a coordinator picks it
// up again.
func TestCoordinatorTC4(t *testing.T) {
	coordinator1, client := setupEtcd(t)

	watchOk := make(chan bool)
	task := "testtask4"

	mclient := NewClient(namespace, client)

	err := mclient.SubmitTask(task)
	if err != nil {
		t.Fatalf("Error submitting a task to metafora via the client. Error:\n%v", err)
	}

	// Don't start up the coordinator until after the metafora client has submitted work.
	if err := coordinator1.Init(newCtx(t, "coordinator1")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	defer coordinator1.Close()

	coord1Watch := func() {
		//Watch blocks, so we need to test it in its own go routine.
		taskId, err := coordinator1.Watch()
		if err != nil {
			t.Fatalf("coordinator1.Watch() returned an err: %v", err)
		}

		t.Logf("Task from the coordinator1.Watch(): %s", taskId)

		if ok := coordinator1.Claim(taskId); !ok {
			t.Fatal("coordinator1.Claim() unable to claim the task")
		}

		watchOk <- true
	}

	go coord1Watch()
	select {
	case <-watchOk:
	case <-time.After(time.Second * 5):
		t.Fatalf("Test failed: The testcase timed out after 5 seconds.")
	}

	//Testcase2 test releasing a task,  Since coordinator1 is still running
	// it should be able to pick up the task again.
	t.Logf("Releasing %s", task)
	coordinator1.Release(task)

	t.Log("Watching again")
	go coord1Watch()
	select {
	case <-watchOk:
	case <-time.After(time.Second * 5):
		t.Fatalf("Test failed: The testcase timed out after 5 seconds.")
	}
}

// Test that Watch() picks up new tasks and returns them.
// Then Claim() the task and make sure we are able to claim it.
//     Calling Claim() should also trigger a scheduled refresh of the claim before it's ttl
// Test after (ClaimTTL + 1 second) that the claim is still around.
// Then add a second coordinator and kill the first one.  The second coordinator
// should pick up the work from the dead first one.
func TestClaimRefreshExpire(t *testing.T) {
	coordinator1, client := setupEtcd(t)
	coordinator1.ClaimTTL = 3
	defer coordinator1.Close()
	if err := coordinator1.Init(newCtx(t, "coordinator1")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	coord1ResultChannel := make(chan string)

	mclient := NewClient(namespace, client)
	task := "testclaimrefreshexpire"

	go func() {
		//Watch blocks, so we need to test it in its own go routine.
		taskId, err := coordinator1.Watch()
		if err != nil {
			t.Fatalf("coordinator1.Watch() returned an err: %v", err)
		}
		t.Logf("We got a task id from the coordinator1.Watch() res:%s", taskId)

		coordinator1.Claim(taskId)
		coord1ResultChannel <- taskId
	}()

	err := mclient.SubmitTask(task)
	if err != nil {
		t.Fatalf("Error submitting a task to metafora via the client. Error:\n%v", err)
	}

	// Step 1: Make sure we picked up and claimed the task before moving on...
	select {
	case taskId := <-coord1ResultChannel:
		if taskId != task {
			t.Fatalf("coordinator1.Watch() test failed: We received the incorrect taskId.  Got [%s] Expected[%s]", taskId, task)
		}
	case <-time.After(time.Second * 5):
		t.Fatalf("coordinator1.Watch() test failed: The testcase timed out after 5 seconds.")
	}

	// Start a second coordinator and make sure it can't claim our task.
	coordinator2 := NewEtcdCoordinator("node2", namespace, client).(*EtcdCoordinator)
	coordinator2.ClaimTTL = 3
	defer coordinator2.Close()
	if err := coordinator2.Init(newCtx(t, "coordinator2")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	coord2ResultChannel := make(chan string)
	go func() {
		taskId, err := coordinator2.Watch()
		if err != nil {
			t.Fatalf("coordinator2.Watch() returned an err: %v", err)
		}
		t.Logf("We got a task id from the coordinator2.Watch() res:%s", taskId)
		coordinator2.Claim(taskId)
		coord2ResultChannel <- taskId
	}()

	// make sure we still have the claim after 2 seconds
	select {
	case taskId := <-coord2ResultChannel:
		t.Fatalf("coordinator2.Watch() test failed: We received a taskId when we shouldn't have.  Got [%s]", taskId)
	case <-time.After(5 * time.Second):
	}

	// This should shut down coordinator1's task watcher and refresher, so that all its tasks are returned
	// and coordinator2 should pick them up.
	t.Log("Coordinator1 trying to shutdown coordinator1. ")
	go func() {
		// The only way to tell when coord.Close() finishes is by waiting for a Watch()
		// to exit.
		coordinator1.Watch()
		coord1ResultChannel <- ""
	}()
	coordinator1.Close()
	<-coord1ResultChannel
	t.Log("Coordinator1 was closed, so its tasks should shortly become available again. ")

	// Now that coordinator1 is shutdown coordinator2 should recover its tasks.
	select {
	case taskId := <-coord2ResultChannel:
		if taskId != task {
			t.Fatalf("coordinator2.Watch() test failed: We received the incorrect taskId.  Got [%s] Expected[%s]", taskId, task)
		}
	case <-time.After(time.Second * 5):
		t.Fatalf("coordinator2.Watch() test failed: The testcase timed out before coordinator2 recovered coordinator1's tasks.")
	}
}

// TestNodeCleanup ensures the coordinator properly cleans up its node entry
// upon exit.
func TestNodeCleanup(t *testing.T) {
	c1, client := setupEtcd(t)
	if err := c1.Init(newCtx(t, "coordinator1")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	c2 := NewEtcdCoordinator("node2", namespace, client).(*EtcdCoordinator)
	if err := c2.Init(newCtx(t, "coordinator2")); err != nil {
		t.Fatalf("Unexpected error initialzing coordinator: %v", err)
	}
	defer c1.Close()
	defer c2.Close()

	// Make sure node directories were created
	resp, err := client.Get(namespace+"/nodes/"+nodeID, false, false)
	if err != nil {
		t.Fatalf("Error retrieving node key from etcd: %v", err)
	}
	if !resp.Node.Dir {
		t.Error(resp.Node.Key + " isn't a directory!")
	}

	resp, err = client.Get(namespace+"/nodes/node2", false, false)
	if err != nil {
		t.Fatalf("Error retrieving node key from etcd: %v", err)
	}
	if !resp.Node.Dir {
		t.Error(resp.Node.Key + " isn't a directory!")
	}

	// Shutdown one and make sure its node directory is gone
	c1.Close()

	resp, err = client.Get(namespace+"/nodes/"+nodeID, false, false)
	if err != nil {
		if eerr, ok := err.(*etcd.EtcdError); !ok {
			t.Errorf("Unexpected error %T retrieving node key from etcd: %v", err, err)
		} else {
			if eerr.ErrorCode != EcodeKeyNotFound {
				t.Errorf("Expected error code %d but found %v", eerr.ErrorCode, err)
			}
			// error code was ok! (100)
		}
	} else {
		t.Errorf("Expected Not Found error, but directory still exists!")
	}

	// Make sure c2 is untouched
	resp, err = client.Get(namespace+"/nodes/node2", false, false)
	if err != nil {
		t.Fatalf("Error retrieving node key from etcd: %v", err)
	}
	if !resp.Node.Dir {
		t.Error(resp.Node.Key + " isn't a directory!")
	}
}

// TestNodeRefresher ensures the node refresher properly updates the TTL on the
// node directory in etcd and shuts down the entire consumer on error.
func TestNodeRefresher(t *testing.T) {
	// make -race happy by using atomic to fiddle with ttl
	orig := atomic.LoadUint64(&DefaultNodePathTTL)
	atomic.StoreUint64(&DefaultNodePathTTL, 3)
	defer atomic.StoreUint64(&DefaultNodePathTTL, orig)

	coord, client := setupEtcd(t)
	bal := &metafora.DumbBalancer{}
	hf := metafora.HandlerFunc(nil) // we won't be handling any tasks
	consumer, err := metafora.NewConsumer(coord, hf, bal)
	if err != nil {
		t.Fatalf("Error creating consumer: %+v", err)
	}

	defer consumer.Shutdown()
	runDone := make(chan struct{})
	go func() {
		consumer.Run()
		close(runDone)
	}()

	nodePath := path.Join(namespace, "nodes", coord.NodeID)
	ttl := int64(-1)
	deadline := time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		resp, _ := client.Get(nodePath, false, false)
		if resp != nil && resp.Node.Dir {
			ttl = resp.Node.TTL
			break
		}
		time.Sleep(250 * time.Millisecond)
	}
	if ttl == -1 {
		t.Fatalf("Node path %s not found.", nodePath)
	}
	if ttl < 1 || ttl > 3 {
		t.Fatalf("Expected TTL to be between 1 and 3, found: %d", ttl)
	}

	// Let it refresh once to make sure that works
	time.Sleep(time.Duration(ttl) * time.Second)
	ttl = -1
	deadline = time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		resp, _ := client.Get(nodePath, false, false)
		if resp != nil && resp.Node.Dir {
			ttl = resp.Node.TTL
			break
		}
		time.Sleep(250 * time.Millisecond)
	}
	if ttl == -1 {
		t.Fatalf("Node path %s not found.", nodePath)
	}

	// Now remove the node out from underneath the refresher to cause it to fail
	if _, err := client.Delete(nodePath, true); err != nil {
		t.Fatalf("Unexpected error deleting %s: %+v", nodePath, err)
	}

	select {
	case <-runDone:
		// success! run exited
	case <-time.After(5 * time.Second):
		t.Fatal("Consumer didn't exit even though node directory disappeared!")
	}
}


text:
using System;

internal class Program
{
	private static int Main()
	{
		int iErrorCount = 0;
		String tstr = null;
		try{
			S<int> i = new S<int>();
			tstr = i.ToString();
			System.Console.WriteLine(tstr);
			if( tstr != "Program+S`1[System.Int32]" )
			{
				Console.WriteLine( "Err_01: Expected type: Program+S`1[System.Int32]" );
				Console.WriteLine( "Err_01: Actualy get type: " + tstr );
				iErrorCount++;
			}
			S<object> o = new S<object>();
			tstr = o.ToString();
			System.Console.WriteLine(tstr);
			if( tstr != "Program+S`1[System.Object]" )
			{
				Console.WriteLine( "Err_02: Expected type:  Program+S`1[System.Object]" );
				Console.WriteLine( "Err_02: Actualy get type: " + tstr );
				iErrorCount++;
			}

			S<string> s = new S<string>();
			tstr = s.ToString();
			System.Console.WriteLine(tstr);
			if( tstr != "Program+S`1[System.String]" )
			{
				Console.WriteLine( "Err_01: Expected type:  Program+S`1[System.String]" );
				Console.WriteLine( "Err_01: Actualy get type: " + tstr );
				iErrorCount++;
			}
			S<Program> p = new S<Program>();
			tstr = p.ToString();
			System.Console.WriteLine(tstr);
			if( tstr != "Program+S`1[Program]" )
			{
				Console.WriteLine( "Err_01: Expected type:  Program+S`1[Program]" );
				Console.WriteLine( "Err_01: Actualy get type: " + tstr );
				iErrorCount++;
			}
		}catch( Exception e)
		{
			Console.WriteLine( "Unexpected: " + e );
			iErrorCount++;
		}
		if( iErrorCount > 0 )
		{
			Console.WriteLine( "Test Failed" );
			return 101;
		}
		else {
			Console.WriteLine( "Test passed" );
			return 100;
		}

	}

	public struct S<T>
	{
#pragma warning disable 0414
		public static S<T> Foo = new S<T>();
#pragma warning restore 0414

	}
}


text:
nl=8
size=128

echo nl=$nl
echo size=$size

#compile 2mm
chpl --fast 2mm.chpl -o 2mm

echo 'Cyclic (C)'
./2mm -nl $nl --dist=C --size=$size --messages --timeit

echo 'Cyclic with modulo unrolling (CM) aggregation minimum = 4'
./2mm -nl $nl --dist=CM --size=$size --correct --messages --timeit --minimumForAggregation=4

echo 'Cyclic with modulo unrolling (CM) aggregation minimum = 16'
./2mm -nl $nl --dist=CM --size=$size --correct --messages --timeit --minimumForAggregation=16

echo 'Cyclic with modulo unrolling (CM) aggregation minimum = 100'
./2mm -nl $nl --dist=CM --size=$size --correct --messages --timeit --minimumForAggregation=100

echo 'Cyclic with modulo unrolling (CM) aggregation minimum = 1000000'
./2mm -nl $nl --dist=CM --size=$size --correct --messages --timeit --minimumForAggregation=1000000

echo 'Block (B)'
./2mm -nl $nl --dist=B --size=$size --messages --timeit

echo 'No distribution (NONE)'
./2mm -nl $nl --dist=NONE --size=$size --timeit


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "eval/eval/regex_match_step.h"

#include <memory>
#include <utility>

#include "absl/status/status.h"
#include "eval/eval/expression_step_base.h"
#include "re2/re2.h"

namespace google::api::expr::runtime {

namespace {

inline constexpr int kNumRegexMatchArguments = 2;

class RegexMatchStep final : public ExpressionStepBase {
 public:
  RegexMatchStep(int64_t expr_id, std::shared_ptr<const RE2> re2)
      : ExpressionStepBase(expr_id, /*comes_from_ast=*/true),
        re2_(std::move(re2)) {}

  absl::Status Evaluate(ExecutionFrame* frame) const override {
    if (!frame->value_stack().HasEnough(kNumRegexMatchArguments)) {
      return absl::Status(absl::StatusCode::kInternal,
                          "Insufficient arguments supplied for regular "
                          "expression match");
    }
    auto input_args = frame->value_stack().GetSpan(kNumRegexMatchArguments);
    const auto& subject = input_args[0];
    const auto& pattern = input_args[1];
    if (!subject.IsString()) {
      return absl::Status(absl::StatusCode::kInternal,
                          "First argument for regular "
                          "expression match must be a string");
    }
    if (!pattern.IsString()) {
      return absl::Status(absl::StatusCode::kInternal,
                          "Second argument for regular "
                          "expression match must be a string");
    }
    if (re2_->pattern() != pattern.StringOrDie().value()) {
      return absl::Status(
          absl::StatusCode::kInternal,
          "Original pattern and supplied pattern are not the same");
    }
    bool match = RE2::PartialMatch(re2::StringPiece(subject.StringOrDie().value().data(), subject.StringOrDie().value().size()), *re2_);
    frame->value_stack().Pop(kNumRegexMatchArguments);
    frame->value_stack().Push(CelValue::CreateBool(match));
    return absl::OkStatus();
  }

 private:
  const std::shared_ptr<const RE2> re2_;
};

}  // namespace

absl::StatusOr<std::unique_ptr<ExpressionStep>> CreateRegexMatchStep(
    std::shared_ptr<const RE2> re2, int64_t expr_id) {
  return std::make_unique<RegexMatchStep>(expr_id, std::move(re2));
}

}  // namespace google::api::expr::runtime


text:
package com.palantir.atlasdb.keyvalue.api.cache;

import com.palantir.atlasdb.keyvalue.api.watch.StartTimestamp;
import com.palantir.lock.watch.CommitUpdate;
import com.palantir.logsafe.Preconditions;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.exceptions.SafeIllegalStateException;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.concurrent.ThreadSafe;
import org.immutables.value.Value;

@ThreadSafe
final class CacheStoreImpl implements CacheStore {
    private static final SafeLogger log = SafeLoggerFactory.get(CacheStoreImpl.class);

    private final int maxCacheCount;
    private final SnapshotStore snapshotStore;
    private final Map<StartTimestamp, Caches> cacheMap;
    private final double validationProbability;
    private final Runnable failureCallback;
    private final CacheMetrics metrics;

    CacheStoreImpl(
            SnapshotStore snapshotStore,
            double validationProbability,
            Runnable failureCallback,
            CacheMetrics metrics,
            int maxCacheCount) {
        this.snapshotStore = snapshotStore;
        this.failureCallback = failureCallback;
        this.metrics = metrics;
        this.maxCacheCount = maxCacheCount;
        this.cacheMap = new ConcurrentHashMap<>();
        this.validationProbability = validationProbability;
        metrics.setTransactionCacheInstanceCountGauge(cacheMap::size);
    }

    @Override
    public void createCache(StartTimestamp timestamp) {
        validateStateSize();

        cacheMap.computeIfAbsent(timestamp, key -> snapshotStore
                .getSnapshot(key)
                .map(snapshot -> TransactionScopedCacheImpl.create(snapshot, metrics))
                .map(newCache ->
                        ValidatingTransactionScopedCache.create(newCache, validationProbability, failureCallback))
                .map(Caches::create)
                .orElse(null));
    }

    @Override
    public TransactionScopedCache getCache(StartTimestamp timestamp) {
        return getCacheInternal(timestamp).map(Caches::mainCache).orElseGet(NoOpTransactionScopedCache::create);
    }

    @Override
    public void removeCache(StartTimestamp timestamp) {
        cacheMap.remove(timestamp);
    }

    @Override
    public void reset() {
        cacheMap.clear();
    }

    @Override
    public void createReadOnlyCache(StartTimestamp timestamp, CommitUpdate commitUpdate) {
        cacheMap.computeIfPresent(timestamp, (_startTs, cache) -> cache.withReadOnlyCache(commitUpdate));
    }

    @Override
    public TransactionScopedCache getReadOnlyCache(StartTimestamp timestamp) {
        return getCacheInternal(timestamp)
                .flatMap(Caches::readOnlyCache)
                .orElseGet(() -> NoOpTransactionScopedCache.create().createReadOnlyCache(CommitUpdate.invalidateAll()));
    }

    private void validateStateSize() {
        if (cacheMap.size() > maxCacheCount) {
            log.warn(
                    "Transaction cache store has exceeded maximum concurrent caches. This likely indicates a memory"
                            + " leak",
                    SafeArg.of("cacheMapSize", cacheMap.size()),
                    SafeArg.of("maxCacheCount", maxCacheCount),
                    SafeArg.of("earliestTimestamp", cacheMap.keySet().stream().min(Comparator.naturalOrder())));
            throw new SafeIllegalStateException(
                    "Exceeded maximum concurrent caches; transaction can be retried, but with caching disabled");
        }
    }

    private Optional<Caches> getCacheInternal(StartTimestamp timestamp) {
        return Optional.ofNullable(cacheMap.get(timestamp));
    }

    @Value.Immutable
    interface Caches {
        TransactionScopedCache mainCache();

        Optional<TransactionScopedCache> readOnlyCache();

        static Caches create(TransactionScopedCache mainCache) {
            return ImmutableCaches.builder().mainCache(mainCache).build();
        }

        default Caches withReadOnlyCache(CommitUpdate commitUpdate) {
            Preconditions.checkState(!readOnlyCache().isPresent(), "Read-only cache is already present");
            return ImmutableCaches.builder()
                    .from(this)
                    .readOnlyCache(mainCache().createReadOnlyCache(commitUpdate))
                    .build();
        }
    }
}