text:
package azureblob

import (
	"context"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"
	"testing"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"

	"github.com/google/go-cmp/cmp"
	"gocloud.dev/blob"
	"gocloud.dev/blob/driver"
	"gocloud.dev/blob/drivertest"
	"gocloud.dev/internal/testing/setup"
)

// Prerequisites for -record mode
// 1. Sign-in to your Azure Subscription at http://portal.azure.com.
//
// 2. Create a Storage Account.
//
// 3. Locate the Access Key (Primary or Secondary) under your Storage Account > Settings > Access Keys.
//
// 4. Set the environment variables AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_KEY to
//    the storage account name and your access key.
//
// 5. Create a container in your Storage Account > Blob. Update the bucketName
// constant to your container name.
//
// Here is a step-by-step walkthrough using the Azure Portal
// https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal
//
// 5. Run the tests with -record.

const (
	bucketName  = "go-cloud-bucket"
	accountName = "gocloudblobtests"
)

type harness struct {
	svcClient  *azblob.ServiceClient
	closer     func()
	httpClient *http.Client
}

func newHarness(ctx context.Context, t *testing.T) (drivertest.Harness, error) {
	var key string
	if *setup.Record {
		name := os.Getenv("AZURE_STORAGE_ACCOUNT")
		if name != accountName {
			t.Fatalf("Please update the accountName constant to match your settings file so future records work (%q vs %q)", name, accountName)
		}
		key = os.Getenv("AZURE_STORAGE_KEY")
	} else {
		// In replay mode, we use fake credentials.
		key = base64.StdEncoding.EncodeToString([]byte("FAKECREDS"))
	}
	credential, err := azblob.NewSharedKeyCredential(accountName, key)
	if err != nil {
		return nil, err
	}
	httpClient, done := setup.NewAzureTestBlobClient(ctx, t)
	// Hack to work around the fact that SignedURLs for PUTs are not fully
	// portable; they require a "x-ms-blob-type" header. Intercept all
	// requests, and insert that header where needed.
	httpClient.Transport = &requestInterceptor{httpClient.Transport}
	clientOptions := azblob.ClientOptions{
		Transport: httpClient,
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net", accountName)
	svcClient, err := azblob.NewServiceClientWithSharedKey(serviceURL, credential, &clientOptions)
	if err != nil {
		return nil, err
	}
	return &harness{svcClient: svcClient, closer: done, httpClient: httpClient}, nil
}

// requestInterceptor implements a hack for the lack of portability for
// SignedURLs for PUT. It adds the required "x-ms-blob-type" header where
// Azure requires it.
type requestInterceptor struct {
	base http.RoundTripper
}

func (ri *requestInterceptor) RoundTrip(req *http.Request) (*http.Response, error) {
	if req.Method == http.MethodPut && strings.Contains(req.URL.Path, "blob-for-signing") {
		reqClone := *req
		reqClone.Header.Add("x-ms-blob-type", "BlockBlob")
		req = &reqClone
	}
	return ri.base.RoundTrip(req)
}

func (h *harness) HTTPClient() *http.Client {
	return h.httpClient
}

func (h *harness) MakeDriver(ctx context.Context) (driver.Bucket, error) {
	return openBucket(ctx, h.svcClient, bucketName, nil)
}

func (h *harness) MakeDriverForNonexistentBucket(ctx context.Context) (driver.Bucket, error) {
	return openBucket(ctx, h.svcClient, "bucket-does-not-exist", nil)
}

func (h *harness) Close() {
	h.closer()
}

func TestConformance(t *testing.T) {
	// See setup instructions above for more details.
	drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyContentLanguage{}})
}

func BenchmarkAzureblob(b *testing.B) {
	name := os.Getenv("AZURE_STORAGE_ACCOUNT")
	key := os.Getenv("AZURE_STORAGE_KEY")
	credential, err := azblob.NewSharedKeyCredential(name, key)
	if err != nil {
		b.Fatal(err)
	}
	serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
	svcClient, err := azblob.NewServiceClientWithSharedKey(serviceURL, credential, nil)
	if err != nil {
		b.Fatal(err)
	}
	bkt, err := OpenBucket(context.Background(), svcClient, bucketName, nil)
	if err != nil {
		b.Fatal(err)
	}
	drivertest.RunBenchmarks(b, bkt)
}

var language = "nl"

// verifyContentLanguage uses As to access the underlying Azure types and
// read/write the ContentLanguage field.
type verifyContentLanguage struct{}

func (verifyContentLanguage) Name() string {
	return "verify ContentLanguage can be written and read through As"
}

func (verifyContentLanguage) BucketCheck(b *blob.Bucket) error {
	var u *azblob.ContainerClient
	if !b.As(&u) {
		return errors.New("Bucket.As failed")
	}
	return nil
}

func (verifyContentLanguage) ErrorCheck(b *blob.Bucket, err error) error {
	var to1 *azblob.StorageError
	var to2 *azcore.ResponseError
	var to3 *azblob.InternalError
	if !b.ErrorAs(err, &to1) && !b.ErrorAs(err, &to2) && !b.ErrorAs(err, &to3) {
		return errors.New("Bucket.ErrorAs failed")
	}
	return nil
}

func (verifyContentLanguage) BeforeRead(as func(interface{}) bool) error {
	var u *azblob.BlobDownloadOptions
	if !as(&u) {
		return fmt.Errorf("BeforeRead As failed to get %T", u)
	}
	return nil
}

func (verifyContentLanguage) BeforeWrite(as func(interface{}) bool) error {
	var azOpts *azblob.UploadStreamOptions
	if !as(&azOpts) {
		return errors.New("Writer.As failed")
	}
	azOpts.HTTPHeaders.BlobContentLanguage = &language
	return nil
}

func (verifyContentLanguage) BeforeCopy(as func(interface{}) bool) error {
	var co *azblob.BlobStartCopyOptions
	if !as(&co) {
		return errors.New("BeforeCopy.As failed")
	}
	return nil
}

func (verifyContentLanguage) BeforeList(as func(interface{}) bool) error {
	var azOpts *azblob.ContainerListBlobsHierarchyOptions
	if !as(&azOpts) {
		return errors.New("BeforeList.As failed")
	}
	return nil
}

func (verifyContentLanguage) BeforeSign(as func(interface{}) bool) error {
	var azOpts *azblob.BlobSASPermissions
	if !as(&azOpts) {
		return errors.New("BeforeSign.As failed")
	}
	return nil
}

func (verifyContentLanguage) AttributesCheck(attrs *blob.Attributes) error {
	var resp azblob.BlobGetPropertiesResponse
	if !attrs.As(&resp) {
		return errors.New("Attributes.As returned false")
	}
	if got := *resp.ContentLanguage; got != language {
		return fmt.Errorf("got %q want %q", got, language)
	}
	return nil
}

func (verifyContentLanguage) ReaderCheck(r *blob.Reader) error {
	var resp azblob.BlobDownloadResponse
	if !r.As(&resp) {
		return errors.New("Reader.As returned false")
	}
	if got := *resp.ContentLanguage; got != language {
		return fmt.Errorf("got %q want %q", got, language)
	}
	return nil
}

func (verifyContentLanguage) ListObjectCheck(o *blob.ListObject) error {
	if o.IsDir {
		var prefix azblob.BlobPrefix
		if !o.As(&prefix) {
			return errors.New("ListObject.As for directory returned false")
		}
		return nil
	}
	var item azblob.BlobItemInternal
	if !o.As(&item) {
		return errors.New("ListObject.As for object returned false")
	}
	if got := *item.Properties.ContentLanguage; got != language {
		return fmt.Errorf("got %q want %q", got, language)
	}
	return nil
}

func TestOpenBucket(t *testing.T) {
	tests := []struct {
		description   string
		nilClient     bool
		accountName   string
		containerName string
		want          string
		wantErr       bool
	}{
		{
			description:   "nil client results in error",
			nilClient:     true,
			accountName:   "myaccount",
			containerName: "foo",
			wantErr:       true,
		},
		{
			description: "empty container name results in error",
			accountName: "myaccount",
			wantErr:     true,
		},
		{
			description:   "success",
			accountName:   "myaccount",
			containerName: "foo",
			want:          "foo",
		},
	}

	ctx := context.Background()
	for _, test := range tests {
		t.Run(test.description, func(t *testing.T) {
			var svcClient *azblob.ServiceClient
			var err error
			if !test.nilClient {
				svcClient, err = azblob.NewServiceClientWithNoCredential("", nil)
				if err != nil {
					t.Fatal(err)
				}
			}
			// Create portable type.
			b, err := OpenBucket(ctx, svcClient, test.containerName, nil)
			if b != nil {
				defer b.Close()
			}
			if (err != nil) != test.wantErr {
				t.Errorf("got err %v want error %v", err, test.wantErr)
			}
		})
	}
}

func TestOpenerFromEnv(t *testing.T) {
	tests := []struct {
		accountName      string
		accountKey       string
		sasToken         string
		connectionString string
		domain           string
		protocol         string
		isCDN            bool
		isLocalEmulator  bool

		want     *credInfoT
		wantOpts *ServiceURLOptions
	}{
		{
			// Shared key.
			accountName: "myaccount",
			accountKey:  "fakecreds",
			want: &credInfoT{
				CredType:    credTypeSharedKey,
				AccountName: "myaccount",
				AccountKey:  "fakecreds",
			},
			wantOpts: &ServiceURLOptions{
				AccountName: "myaccount",
			},
		},
		{
			// SAS Token.
			accountName: "myaccount",
			sasToken:    "a-sas-token",
			want: &credInfoT{
				CredType:    credTypeSASViaNone,
				AccountName: "myaccount",
			},
			wantOpts: &ServiceURLOptions{
				AccountName: "myaccount",
				SASToken:    "a-sas-token",
			},
		},
		{
			// Connection string.
			accountName:      "myaccount",
			connectionString: "a-connection-string",
			want: &credInfoT{
				CredType:         credTypeConnectionString,
				AccountName:      "myaccount",
				ConnectionString: "a-connection-string",
			},
			wantOpts: &ServiceURLOptions{
				AccountName: "myaccount",
			},
		},
		{
			// Default.
			accountName: "anotheraccount",
			want: &credInfoT{
				CredType:    credTypeDefault,
				AccountName: "anotheraccount",
			},
			wantOpts: &ServiceURLOptions{
				AccountName: "anotheraccount",
			},
		},
		{
			// Setting protocol and domain.
			accountName: "myaccount",
			protocol:    "http",
			domain:      "foo.bar.com",
			want: &credInfoT{
				CredType:    credTypeDefault,
				AccountName: "myaccount",
			},
			wantOpts: &ServiceURLOptions{
				AccountName:   "myaccount",
				Protocol:      "http",
				StorageDomain: "foo.bar.com",
			},
		},
		{
			// Local emulator.
			accountName:     "myaccount",
			isLocalEmulator: true,
			want: &credInfoT{
				CredType:    credTypeDefault,
				AccountName: "myaccount",
			},
			wantOpts: &ServiceURLOptions{
				AccountName:     "myaccount",
				IsLocalEmulator: true,
			},
		},
	}
	for _, test := range tests {
		os.Setenv("AZURE_STORAGE_ACCOUNT", test.accountName)
		os.Setenv("AZURE_STORAGE_KEY", test.accountKey)
		os.Setenv("AZURE_STORAGE_SAS_TOKEN", test.sasToken)
		os.Setenv("AZURE_STORAGE_CONNECTION_STRING", test.connectionString)
		os.Setenv("AZURE_STORAGE_DOMAIN", test.domain)
		os.Setenv("AZURE_STORAGE_PROTOCOL", test.protocol)
		if test.isCDN {
			os.Setenv("AZURE_STORAGE_IS_CDN", "true")
		} else {
			os.Setenv("AZURE_STORAGE_IS_CDN", "")
		}
		if test.isLocalEmulator {
			os.Setenv("AZURE_STORAGE_IS_LOCAL_EMULATOR", "true")
		} else {
			os.Setenv("AZURE_STORAGE_IS_LOCAL_EMULATOR", "")
		}

		got := newCredInfoFromEnv()
		if diff := cmp.Diff(got, test.want); diff != "" {
			t.Errorf("unexpected diff in credInfo: %s", diff)
		}
		gotOpts := NewDefaultServiceURLOptions()
		if diff := cmp.Diff(gotOpts, test.wantOpts); diff != "" {
			t.Errorf("unexpected diff in Options: %s", diff)
		}

	}
}

func TestNewServiceURL(t *testing.T) {
	tests := []struct {
		opts             ServiceURLOptions
		query            url.Values
		want             ServiceURL
		wantErrOverrides bool
		wantErrURL       bool
	}{
		{
			// Unknown query parameter.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
			},
			query: url.Values{
				"foo": {"bar"},
			},
			wantErrOverrides: true,
		},
		{
			// Duplicate query parameter.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
			},
			query: url.Values{
				"domain": {"blob.core.usgovcloudapi.net", "blob.core.windows.net"},
			},
			wantErrOverrides: true,
		},
		{
			// Missing account name.
			opts:       ServiceURLOptions{},
			wantErrURL: true,
		},
		{
			// Account name set in the query
			opts: ServiceURLOptions{},
			query: url.Values{
				"storage_account": {"testaccount"},
			},
			want: "https://testaccount.blob.core.windows.net",
		},
		{
			// Basic working case.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
			},
			want: "https://myaccount.blob.core.windows.net",
		},
		{
			// SASToken.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
				SASToken:    "my-sas-token",
			},
			want: "https://myaccount.blob.core.windows.net?my-sas-token",
		},
		{
			// Setting domain from ServiceURLOptions.
			opts: ServiceURLOptions{
				AccountName:   "myaccount",
				StorageDomain: "blob.core.usgovcloudapi.net",
			},
			want: "https://myaccount.blob.core.usgovcloudapi.net",
		},
		{
			// Setting domain from the URL.
			opts: ServiceURLOptions{
				AccountName:   "myaccount",
				StorageDomain: "overridden",
			},
			query: url.Values{
				"domain": {"blob.core.usgovcloudapi.net"},
			},
			want: "https://myaccount.blob.core.usgovcloudapi.net",
		},
		{
			// Setting protocol from ServiceURLOptions.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
				Protocol:    "http",
			},
			want: "http://myaccount.blob.core.windows.net",
		},
		{
			// Setting protocol from the URL.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
				Protocol:    "https",
			},
			query: url.Values{
				"protocol": {"http"},
			},
			want: "http://myaccount.blob.core.windows.net",
		},
		{
			// Setting IsCDN from ServiceURLOptions.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
				IsCDN:       true,
			},
			want: "https://blob.core.windows.net",
		},
		{
			// Setting IsCDN from the URL.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
			},
			query: url.Values{
				"cdn": {"true"},
			},
			want: "https://blob.core.windows.net",
		},
		{
			// Local emulator, implicit from domain.
			opts: ServiceURLOptions{
				AccountName:   "myaccount",
				Protocol:      "http",
				StorageDomain: "localhost:10001",
			},
			want: "http://localhost:10001/myaccount",
		},
		{
			// Local emulator, implicit from domain through URL parameter.
			opts: ServiceURLOptions{
				AccountName: "myaccount",
			},
			query: url.Values{
				"protocol": {"http"},
				"domain":   {"127.0.0.1:10001"},
			},
			want: "http://127.0.0.1:10001/myaccount",
		},
		{
			// Local emulator, explicit through ServiceURLOptions.
			opts: ServiceURLOptions{
				AccountName:     "myaccount",
				StorageDomain:   "mylocalemulator",
				IsLocalEmulator: true,
			},
			want: "https://mylocalemulator/myaccount",
		},
		{
			// Local emulator, explicit through URL parameter.
			opts: ServiceURLOptions{
				AccountName:   "myaccount",
				StorageDomain: "mylocalemulator",
			},
			query: url.Values{
				"localemu": {"true"},
			},
			want: "https://mylocalemulator/myaccount",
		},
	}

	for _, test := range tests {
		opts, err := test.opts.withOverrides(test.query)
		if (err != nil) != test.wantErrOverrides {
			t.Fatalf("withOverrides got err %v want error %v", err, test.wantErrOverrides)
		}
		if err != nil {
			continue
		}
		got, err := NewServiceURL(opts)
		if (err != nil) != test.wantErrURL {
			t.Errorf("NewServiceURL got err %v want error %v", err, test.wantErrURL)
		}
		if got != test.want {
			t.Errorf("got %q want %q", got, test.want)
		}
	}
}

func TestOpenBucketFromURL(t *testing.T) {
	prevAccount := os.Getenv("AZURE_STORAGE_ACCOUNT")
	prevKey := os.Getenv("AZURE_STORAGE_KEY")
	os.Setenv("AZURE_STORAGE_ACCOUNT", "my-account")
	os.Setenv("AZURE_STORAGE_KEY", "bXlrZXk=") // mykey base64 encoded
	defer func() {
		os.Setenv("AZURE_STORAGE_ACCOUNT", prevAccount)
		os.Setenv("AZURE_STORAGE_KEY", prevKey)
	}()

	tests := []struct {
		URL     string
		WantErr bool
	}{
		// OK.
		{"azblob://mybucket", false},
		// With storage domain.
		{"azblob://mybucket?domain=blob.core.usgovcloudapi.net", false},
		// With duplicate storage domain.
		{"azblob://mybucket?domain=blob.core.usgovcloudapi.net&domain=blob.core.windows.net", true},
		// With protocol.
		{"azblob://mybucket?protocol=http", false},
		// With invalid protocol.
		{"azblob://mybucket?protocol=ftp", true},
		// With Account.
		{"azblob://mybucket?storage_account=test", false},
		// With CDN.
		{"azblob://mybucket?cdn=true", false},
		// With invalid CDN.
		{"azblob://mybucket?cdn=42", true},
		// With local emulator.
		{"azblob://mybucket?localemu=true", false},
		// With invalid local emulator.
		{"azblob://mybucket?localemu=42", true},
		// Invalid parameter.
		{"azblob://mybucket?param=value", true},
	}

	ctx := context.Background()
	for _, test := range tests {
		b, err := blob.OpenBucket(ctx, test.URL)
		if b != nil {
			defer b.Close()
		}
		if (err != nil) != test.WantErr {
			t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr)
		}
	}
}


text:
shared_examples 'hiding tenant column for non admin user' do |expected_result|
  before do
    allow(controller).to receive(:render)
    login_as FactoryBot.create(user_type)
  end

  subject do
    expect(controller).to receive(:get_db_view).and_return(report)
    controller.send(:report_data)
    controller.send(:view_to_hash, assigns(:view))
  end

  let(:first_row) { subject[:rows][0][:cells].map { |x| x[:text] }.compact }
  let(:headers) { subject[:head].map { |x| x[:text] }.compact }
  let(:result_array) { expected_result.keys.map { |column| record.send(column) } }

  context "when not admin" do
    let(:user_type) { :user }

    it "renders show_list and does not include hidden column(hidden by display method)" do
      expect(headers).to match_array(expected_result.values)
      expect(first_row).to match_array(result_array)
    end
  end

  context "when admin" do
    let(:user_type) { :user_admin }

    it "renders show_list and includes all columns" do
      expect(headers).to match_array(expected_result.values + ['Tenant'])
      expect(first_row).to match_array(result_array + [record.tenant.name])
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
class CommonDocumentsController < InheritedResources::Base
  belongs_to_subjects :optional => true

  before_filter :profile_subject!, :only => :index

  load_and_authorize_resource :except => :index

  def show
    path = resource.file.path(params[:style])

    respond_to do |format|
      format.all {
        send_file path,
                  :filename => resource.file_file_name,
                  :type => resource.file_content_type,
                  :disposition => "inline"
      }
    end
  end

  def destroy
    @post_activity = resource.post_activity

    destroy!
  end

  private

  def collection
    @activities = profile_subject.wall(:profile,
                                       :for => current_subject,
                                       :object_type => Array(self.class.index_object_type)).
                                  page(params[:page]).
                                  per(params[:per])
  end

  class << self
    def index_object_type
      controller_name.classify
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Amanitopsis bingensis Beeli

### Remarks
null


text:
'''
   Copyright 2015 University of Auckland

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   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.
'''
import sys
import os.path
from subprocess import PIPE, Popen
from threading  import Thread
from tempfile import NamedTemporaryFile, mkdtemp

from opencmiss.neon.core.simulations.local import LocalSimulation
from opencmiss.neon.core.serializers.identifiervalue import IdentifierValue
from opencmiss.neon.settings.mainsettings import EXTERNAL_DATA_DIR

try:
    from Queue import Queue
except ImportError:
    from queue import Queue  # python 3.x

ON_POSIX = 'posix' in sys.builtin_module_names

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        queue.put(line)
    out.close()

class Ventilation(LocalSimulation):

    def __init__(self):
        super(Ventilation, self).__init__()
        self.setName('Ventilation Simulation')
        self.setSerializer(IdentifierValue())
        self._file_handles = {}
        self._dir_handles = {}
        self._output_filenames = {}

    def getOutputFilenames(self):
        return self._output_filenames

    def setup(self):
        file_input_outputs = self._parameters['file_input_outputs']

        output_file_keys = ['terminal_exnode', 'tree_exnode', 'tree_exelem', 'ventilation_exelem', 'radius_exelem']
        output_filenames = {}

        for key in output_file_keys:
            filename = file_input_outputs[key]
            if filename:
                output_filenames[key] = filename
            else:
                out_file_handle = NamedTemporaryFile(prefix='ventilation_{0}_'.format(key), delete=False)
                output_filenames[key] = out_file_handle.name
                out_file_handle.close()

        terminal_file = output_filenames['terminal_exnode']

        self._dir_handles['root'] = mkdtemp(prefix='neon_')
        param_dir = os.path.join(self._dir_handles['root'], 'Parameters')
        self._dir_handles['para'] = param_dir
        os.mkdir(param_dir)

        geometry_flow = {}
        geometry_flow['exnode'] = "'{0}'".format(terminal_file)
        geometry_flow['flowexelem'] = "'{0}'".format(output_filenames['ventilation_exelem'])
        geometry_flow['flowradiusexelem'] = "'{0}'".format(output_filenames['radius_exelem'])
        self._file_handles['geo_main'] = os.path.join(self._dir_handles['para'], 'geometry_evaluate_flow.txt')
        with open(self._file_handles['geo_main'], 'w') as f:
            string = self._serializer.serialize(geometry_flow)
            f.write(string)

        self._output_filenames = output_filenames

        inbuilt_tree_ipelem = os.path.join(EXTERNAL_DATA_DIR, self._parameters['name'], 'Geom', 'tree.ipelem')
        tree_ipelem = inbuilt_tree_ipelem if file_input_outputs['tree_inbuilt'] or not file_input_outputs['tree_ipelem'] else file_input_outputs['tree_ipelem']
        inbuilt_tree_ipnode = os.path.join(EXTERNAL_DATA_DIR, self._parameters['name'], 'Geom', 'tree.ipnode')
        tree_ipnode = inbuilt_tree_ipnode if file_input_outputs['tree_inbuilt'] or not file_input_outputs['tree_ipnode'] else file_input_outputs['tree_ipnode']
        inbuilt_tree_ipfiel = os.path.join(EXTERNAL_DATA_DIR, self._parameters['name'], 'Geom', 'tree.ipfiel')
        tree_ipfiel = inbuilt_tree_ipfiel if file_input_outputs['tree_inbuilt'] or not file_input_outputs['tree_ipfield'] else file_input_outputs['tree_ipfield']
        inbuilt_tree_ipmesh = os.path.join(EXTERNAL_DATA_DIR, self._parameters['name'], 'Geom', 'tree.ipmesh')
        tree_ipmesh = inbuilt_tree_ipmesh if file_input_outputs['tree_inbuilt'] or not file_input_outputs['tree_ipmesh'] else file_input_outputs['tree_ipmesh']

        geometry_main = {}
        geometry_main['ipelem'] = "'{0}'".format(tree_ipelem)
        geometry_main['ipnode'] = "'{0}'".format(tree_ipnode)
        geometry_main['ipfiel'] = "'{0}'".format(tree_ipfiel)
        geometry_main['ipmesh'] = "'{0}'".format(tree_ipmesh)
        geometry_main['exnode'] = "'{0}'".format(output_filenames['tree_exnode'])
        geometry_main['exelem'] = "'{0}'".format(output_filenames['tree_exelem'])

        self._file_handles['geo_flow'] = os.path.join(self._dir_handles['para'], 'geometry_main.txt')
        with open(self._file_handles['geo_flow'], 'w') as f:
            string = self._serializer.serialize(geometry_main)
            f.write(string)

        self._file_handles['par_main'] = os.path.join(self._dir_handles['para'], 'params_main.txt')
        with open(self._file_handles['par_main'], 'w') as f:
            string = self._serializer.serialize(self._parameters['main_parameters'])
            f.write(string)

        self._file_handles['par_flow'] = os.path.join(self._dir_handles['para'], 'params_evaluate_flow.txt')
        with open(self._file_handles['par_flow'], 'w') as f:
            string = self._serializer.serialize(self._parameters['flow_parameters'])
            f.write(string)

    def execute(self):
        p = Popen([self._executable], cwd=self._dir_handles['root'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
        q = Queue()
        t = Thread(target=enqueue_output, args=(p.stdout, q))
        t.daemon = True  # thread dies with the program
        t.start()

        return t, q

    def cleanup(self):
        os.remove(self._file_handles['geo_main'])
        os.remove(self._file_handles['geo_flow'])
        os.remove(self._file_handles['par_main'])
        os.remove(self._file_handles['par_flow'])
        os.rmdir(self._dir_handles['para'])
        os.rmdir(self._dir_handles['root'])

    def validate(self):
        return True


text:
document.addEventListener('DOMContentLoaded',onLoad);

var AudioContext = window.AudioContext || window.webkitAudioContext;
var piano;
var padHitEventName = "mousedown";
var padReleaseEventName = "mouseup";

function onLoad() {

    try {
        document.createEvent("TouchEvent");
        padHitEventName = "touchstart";
        padReleaseEventName = "touchend";
    }
    catch(ex) {
        // alert('Touch is not supported in this browser');
    }

    if(!AudioContext) {
        window.alert("WebAudio is not supported");
    }
    else {
        piano = new TunedInstrument();
        piano.loadVoice("sounds/AccGuitar.wav",48);

        // var audioCtx = new AudioContext();
        // var oscillator = audioCtx.createOscillator();
        // oscillator.type = 'sine';
        // // sine wave — other values are 'square', 'sawtooth', 'triangle' and 'custom'
        // oscillator.frequency.value = 2500; // value in hertz
        // // oscillator.start(0);

        // // var gainNode = audioCtx.createGain();

        // // oscillator.connect(gainNode);
        // // gainNode.connect(audioCtx.destination);

        var elems = document.querySelectorAll('.key');
        elems.forEach( function(elem){
            //console.log(elem.dataset.notenumber);
            if(elem.dataset.notenumber) {
                elem.addEventListener(padHitEventName,onPianoKeyDown);
                if(padHitEventName !== 'mouseup') {
                    elem.addEventListener(padReleaseEventName,onPianoKeyUp);
                }
            }
        });
    }
}

function onPianoKeyDown(evt) {
    if(evt.type == "mousedown") {
        evt.currentTarget.addEventListener('mouseup',onPianoKeyUp);
    }
    piano.noteOn(parseInt(evt.currentTarget.dataset.notenumber) + 24);
}

function onPianoKeyUp(evt) {
    if(evt.type == "mouseup") {
        evt.currentTarget.removeEventListener('mouseup',onPianoKeyUp);
    }
    piano.noteOff(parseInt(evt.currentTarget.dataset.notenumber) + 24);
}


text:
package com.matrobot.gha.insights.classifier;

/**
 * Just assume that all are negative examples
 */
public class BinaryStaticClassifier implements IBinaryClassifier {

	@Override
	public double classify(double[] featureVector) {
		return 0;
	}

}


text: @layout Name="_SiteLayout"


text:
package com.fcdream.dress.kenny.speech;

import android.text.TextUtils;

import com.fcdream.dress.kenny.speech.baidu.BaiduSpeech;
import com.fcdream.dress.kenny.speech.baidu.BaiduSpeechSynthesizer;

/**
 * Created by shmdu on 2017/8/28.
 */

public class SpeechFactory {

    public static final String TYPE_BAIDU = "type_baidu";
    public static final String TYPE_IFLY = "type_ifly";

    public static BaseSpeech createSpeech(String type) {
        if (TextUtils.equals(TYPE_BAIDU, type)) {
            return new BaiduSpeech();
        }
        return null;
    }

    public static BaseSpeechSynthesizer createSpeechSynthesizer(String type) {
        if (TextUtils.equals(TYPE_BAIDU, type)) {
            return BaiduSpeechSynthesizer.getInstance();
        }
        return null;
    }
}


text:
import setup, { getEslintRcFilename } from '../src/setup';

jest.mock('fs', () => ({
  readdir: jest.fn().mockResolvedValue(Promise.resolve(['.eslintrc.js'])),
}));

test('setup should throw for unknown linter', () => {
  // @ts-expect-error invalid test data
  expect(() => setup({ linter: 'o/' })).toThrow();
});

test('getEslintRcFilename should return .eslintrc file with correct extension', async () => {
  const filename = await getEslintRcFilename();
  expect(filename).toBe('.eslintrc.js');
});


text:
using System.Reflection;
using System.Runtime.InteropServices;
using SquishIt.NSass;
using WebActivatorEx;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SquishIt.NSass")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SquishIt.NSass")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a910b261-e806-488c-b313-42a3455926cc")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

[assembly: PreApplicationStartMethod(typeof(Bootstrap), "Initialize")]


text:
/*
	The following program estimates Pi using the Bailey-Borwein-Plouffe (BBP) formula.

	Pi = Sum(k = 0, inf)[(1/(16^k)) * [(4/(8k + 1)) - (2/(8k + 4)) - (1/(8k + 5)) - (1/(8k + 6))]
*/
#include <iostream>
#include <chrono>
#include <iomanip>
#include <cmath>

long double getPiDigit(long long iteration)
{
	long double baseSixteenMultipler = 1./pow(16, iteration);
	long double firstTerm = 4./(8 * iteration + 1);
	long double secondTerm = 2./(8 * iteration + 4);
	long double thirdTerm = 1./(8 * iteration + 5);
	long double fourthTerm = 1./(8 * iteration + 6);
	return baseSixteenMultipler * (firstTerm - secondTerm - thirdTerm - fourthTerm);
}

int main()
{
	long long iterations = 0;
	long double pi = 0;
	std::cout << "Please enter the desired number of iterations for estimating Pi." << std::endl;
	std::cin >> iterations;

	auto start = std::chrono::high_resolution_clock::now();
	for (long long i = 0; i < iterations; i++)
		pi += getPiDigit(i);
	auto stop = std::chrono::high_resolution_clock::now();

	std::cout << "Number of iterations: " << iterations << "." << std::endl;
	std::cout << std::setprecision(16) << "Approximate value of Pi is " << pi << "." << std::endl;
	auto diff = std::chrono::duration_cast<std::chrono::seconds>(stop - start);
	std::cout << "\nTime taken is " << diff.count() << " seconds." << std::endl;
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.background_task_scheduler.internal;

import android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.test.InstrumentationRegistry;

import androidx.test.filters.SmallTest;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.BaseJUnit4ClassRunner;
import org.chromium.base.test.util.MinAndroidSdkLevel;
import org.chromium.components.background_task_scheduler.TaskIds;
import org.chromium.components.background_task_scheduler.TaskInfo;

import java.util.concurrent.TimeUnit;

/**
 * Tests for {@link BackgroundTaskSchedulerJobService}.
 */
@RunWith(BaseJUnit4ClassRunner.class)
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
@MinAndroidSdkLevel(Build.VERSION_CODES.LOLLIPOP_MR1)
public class BackgroundTaskSchedulerJobServiceTest {
    private static final long CLOCK_TIME_MS = 1415926535000L;
    private static final long TIME_50_MIN_TO_MS = TimeUnit.MINUTES.toMillis(50);
    private static final long TIME_100_MIN_TO_MS = TimeUnit.MINUTES.toMillis(100);
    private static final long TIME_200_MIN_TO_MS = TimeUnit.MINUTES.toMillis(200);
    private static final long END_TIME_WITH_DEADLINE_MS =
            TIME_200_MIN_TO_MS + BackgroundTaskSchedulerJobService.DEADLINE_DELTA_MS;

    private BackgroundTaskSchedulerJobService.Clock mClock = () -> CLOCK_TIME_MS;

    @Before
    public void setUp() {
        BackgroundTaskSchedulerJobService.setClockForTesting(mClock);
    }

    @Test
    @SmallTest
    public void testOneOffTaskWithDeadline() {
        TaskInfo.TimingInfo timingInfo =
                TaskInfo.OneOffInfo.create().setWindowEndTimeMs(TIME_200_MIN_TO_MS).build();
        TaskInfo oneOffTask = TaskInfo.createTask(TaskIds.TEST, timingInfo).build();
        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(), oneOffTask);
        Assert.assertEquals(oneOffTask.getTaskId(), jobInfo.getId());
        Assert.assertFalse(jobInfo.isPeriodic());
        Assert.assertEquals(TIME_200_MIN_TO_MS, jobInfo.getMaxExecutionDelayMillis());
    }

    @Test
    @SmallTest
    public void testOneOffTaskWithDeadlineAndExpiration() {
        TaskInfo.TimingInfo timingInfo = TaskInfo.OneOffInfo.create()
                                                 .setWindowEndTimeMs(TIME_200_MIN_TO_MS)
                                                 .setExpiresAfterWindowEndTime(true)
                                                 .build();
        TaskInfo oneOffTask = TaskInfo.createTask(TaskIds.TEST, timingInfo).build();
        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(), oneOffTask);
        Assert.assertEquals(END_TIME_WITH_DEADLINE_MS, jobInfo.getMaxExecutionDelayMillis());
        Assert.assertEquals(CLOCK_TIME_MS,
                jobInfo.getExtras().getLong(BackgroundTaskSchedulerGcmNetworkManager
                                                    .BACKGROUND_TASK_SCHEDULE_TIME_KEY));
        Assert.assertEquals(TIME_200_MIN_TO_MS,
                jobInfo.getExtras().getLong(
                        BackgroundTaskSchedulerGcmNetworkManager.BACKGROUND_TASK_END_TIME_KEY));
    }

    @Test
    @SmallTest
    public void testOneOffTaskWithWindow() {
        TaskInfo.TimingInfo timingInfo = TaskInfo.OneOffInfo.create()
                                                 .setWindowStartTimeMs(TIME_100_MIN_TO_MS)
                                                 .setWindowEndTimeMs(TIME_200_MIN_TO_MS)
                                                 .build();
        TaskInfo oneOffTask = TaskInfo.createTask(TaskIds.TEST, timingInfo).build();
        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(), oneOffTask);
        Assert.assertEquals(oneOffTask.getTaskId(), jobInfo.getId());
        Assert.assertFalse(jobInfo.isPeriodic());
        Assert.assertEquals(TIME_100_MIN_TO_MS, jobInfo.getMinLatencyMillis());
        Assert.assertEquals(TIME_200_MIN_TO_MS, jobInfo.getMaxExecutionDelayMillis());
    }

    @Test
    @SmallTest
    public void testOneOffTaskWithWindowAndExpiration() {
        TaskInfo.TimingInfo timingInfo = TaskInfo.OneOffInfo.create()
                                                 .setWindowStartTimeMs(TIME_100_MIN_TO_MS)
                                                 .setWindowEndTimeMs(TIME_200_MIN_TO_MS)
                                                 .setExpiresAfterWindowEndTime(true)
                                                 .build();
        TaskInfo oneOffTask = TaskInfo.createTask(TaskIds.TEST, timingInfo).build();
        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(), oneOffTask);
        Assert.assertEquals(
                oneOffTask.getOneOffInfo().getWindowStartTimeMs(), jobInfo.getMinLatencyMillis());
        Assert.assertEquals(END_TIME_WITH_DEADLINE_MS, jobInfo.getMaxExecutionDelayMillis());
        Assert.assertEquals(CLOCK_TIME_MS,
                jobInfo.getExtras().getLong(BackgroundTaskSchedulerGcmNetworkManager
                                                    .BACKGROUND_TASK_SCHEDULE_TIME_KEY));
        Assert.assertEquals(TIME_200_MIN_TO_MS,
                jobInfo.getExtras().getLong(
                        BackgroundTaskSchedulerGcmNetworkManager.BACKGROUND_TASK_END_TIME_KEY));
    }

    @Test
    @SmallTest
    public void testPeriodicTaskWithoutFlex() {
        TaskInfo.TimingInfo timingInfo =
                TaskInfo.PeriodicInfo.create().setIntervalMs(TIME_200_MIN_TO_MS).build();
        TaskInfo periodicTask = TaskInfo.createTask(TaskIds.TEST, timingInfo).build();
        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(), periodicTask);
        Assert.assertEquals(periodicTask.getTaskId(), jobInfo.getId());
        Assert.assertTrue(jobInfo.isPeriodic());
        Assert.assertEquals(TIME_200_MIN_TO_MS, jobInfo.getIntervalMillis());
    }

    @Test
    @SmallTest
    public void testPeriodicTaskWithFlex() {
        TaskInfo.TimingInfo timingInfo = TaskInfo.PeriodicInfo.create()
                                                 .setIntervalMs(TIME_200_MIN_TO_MS)
                                                 .setFlexMs(TIME_50_MIN_TO_MS)
                                                 .build();
        TaskInfo periodicTask = TaskInfo.createTask(TaskIds.TEST, timingInfo).build();
        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(), periodicTask);
        Assert.assertEquals(TIME_200_MIN_TO_MS, jobInfo.getIntervalMillis());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Assert.assertEquals(TIME_50_MIN_TO_MS, jobInfo.getFlexMillis());
        }
    }

    @Test
    @SmallTest
    public void testTaskInfoWithExtras() {
        Bundle taskExtras = new Bundle();
        taskExtras.putString("foo", "bar");
        taskExtras.putBoolean("bools", true);
        taskExtras.putLong("longs", 1342543L);
        TaskInfo.TimingInfo timingInfo =
                TaskInfo.OneOffInfo.create().setWindowEndTimeMs(TIME_200_MIN_TO_MS).build();
        TaskInfo oneOffTask =
                TaskInfo.createTask(TaskIds.TEST, timingInfo).setExtras(taskExtras).build();
        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(), oneOffTask);
        Assert.assertEquals(oneOffTask.getTaskId(), jobInfo.getId());
        PersistableBundle jobExtras = jobInfo.getExtras();
        PersistableBundle persistableBundle = jobExtras.getPersistableBundle(
                BackgroundTaskSchedulerJobService.BACKGROUND_TASK_EXTRAS_KEY);
        Assert.assertEquals(taskExtras.keySet().size(), persistableBundle.keySet().size());
        Assert.assertEquals(taskExtras.getString("foo"), persistableBundle.getString("foo"));
        Assert.assertEquals(taskExtras.getBoolean("bools"), persistableBundle.getBoolean("bools"));
        Assert.assertEquals(taskExtras.getLong("longs"), persistableBundle.getLong("longs"));
    }

    @Test
    @SmallTest
    public void testTaskInfoWithManyConstraints() {
        TaskInfo.TimingInfo timingInfo =
                TaskInfo.OneOffInfo.create().setWindowEndTimeMs(TIME_200_MIN_TO_MS).build();
        TaskInfo.Builder taskBuilder = TaskInfo.createTask(TaskIds.TEST, timingInfo);

        JobInfo jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(),
                taskBuilder.setIsPersisted(true).build());
        Assert.assertTrue(jobInfo.isPersisted());

        jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(),
                taskBuilder.setRequiredNetworkType(TaskInfo.NetworkType.UNMETERED).build());
        Assert.assertEquals(JobInfo.NETWORK_TYPE_UNMETERED, jobInfo.getNetworkType());

        jobInfo = BackgroundTaskSchedulerJobService.createJobInfoFromTaskInfo(
                InstrumentationRegistry.getTargetContext(),
                taskBuilder.setRequiresCharging(true).build());
        Assert.assertTrue(jobInfo.isRequireCharging());
    }
}


text:
package utp

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net"
	"runtime"
	"sync"
	"testing"
	"time"

	_ "github.com/anacrolix/envpprof"
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/anacrolix/missinggo"
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/bradfitz/iter"
	"github.com/stretchr/testify/require"
)

func init() {
	log.SetFlags(log.Flags() | log.Lshortfile)
}

func TestUTPPingPong(t *testing.T) {
	defer goroutineLeakCheck(t)()
	s, err := NewSocket("udp", "localhost:0")
	require.NoError(t, err)
	defer s.Close()
	pingerClosed := make(chan struct{})
	go func() {
		defer close(pingerClosed)
		b, err := Dial(s.Addr().String())
		require.NoError(t, err)
		defer b.Close()
		n, err := b.Write([]byte("ping"))
		require.NoError(t, err)
		require.EqualValues(t, 4, n)
		buf := make([]byte, 4)
		b.Read(buf)
		require.EqualValues(t, "pong", buf)
		log.Printf("got pong")
	}()
	a, err := s.Accept()
	require.NoError(t, err)
	defer a.Close()
	log.Printf("accepted %s", a)
	buf := make([]byte, 42)
	n, err := a.Read(buf)
	require.NoError(t, err)
	require.EqualValues(t, "ping", buf[:n])
	log.Print("got ping")
	n, err = a.Write([]byte("pong"))
	require.NoError(t, err)
	require.Equal(t, 4, n)
	log.Print("waiting for pinger to close")
	<-pingerClosed
}

func goroutineLeakCheck(t testing.TB) func() {
	if !testing.Verbose() {
		return func() {}
	}
	numStart := runtime.NumGoroutine()
	return func() {
		var numNow int
		for range iter.N(1) {
			numNow = runtime.NumGoroutine()
			if numNow == numStart {
				return
			}
			time.Sleep(10 * time.Millisecond)
		}
		// I'd print stacks, or treat this as fatal, but I think
		// runtime.NumGoroutine is including system routines for which we are
		// not provided the stacks, and are spawned unpredictably.
		t.Logf("have %d goroutines, started with %d", numNow, numStart)
	}
}

func TestDialTimeout(t *testing.T) {
	defer goroutineLeakCheck(t)()
	s, _ := NewSocket("udp", "localhost:0")
	defer s.Close()
	conn, err := DialTimeout(s.Addr().String(), 10*time.Millisecond)
	if err == nil {
		conn.Close()
		t.Fatal("expected timeout")
	}
	t.Log(err)
}

func TestMinMaxHeaderType(t *testing.T) {
	require.Equal(t, stSyn, stMax)
}

func TestUTPRawConn(t *testing.T) {
	l, err := NewSocket("udp", "")
	require.NoError(t, err)
	defer l.Close()
	go func() {
		for {
			_, err := l.Accept()
			if err != nil {
				break
			}
		}
	}()
	// Connect a UTP peer to see if the RawConn will still work.
	log.Print("dialing")
	utpPeer := func() net.Conn {
		s, _ := NewSocket("udp", "")
		defer s.Close()
		ret, err := s.Dial(fmt.Sprintf("localhost:%d", missinggo.AddrPort(l.Addr())))
		require.NoError(t, err)
		return ret
	}()
	log.Print("dial returned")
	if err != nil {
		t.Fatalf("error dialing utp listener: %s", err)
	}
	defer utpPeer.Close()
	peer, err := net.ListenPacket("udp", ":0")
	if err != nil {
		t.Fatal(err)
	}
	defer peer.Close()

	msgsReceived := 0
	const N = 5000 // How many messages to send.
	readerStopped := make(chan struct{})
	// The reader goroutine.
	go func() {
		defer close(readerStopped)
		b := make([]byte, 500)
		for i := 0; i < N; i++ {
			n, _, err := l.ReadFrom(b)
			if err != nil {
				t.Fatalf("error reading from raw conn: %s", err)
			}
			msgsReceived++
			var d int
			fmt.Sscan(string(b[:n]), &d)
			if d != i {
				log.Printf("got wrong number: expected %d, got %d", i, d)
			}
		}
	}()
	udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("localhost:%d", missinggo.AddrPort(l.Addr())))
	if err != nil {
		t.Fatal(err)
	}
	for i := 0; i < N; i++ {
		_, err := peer.WriteTo([]byte(fmt.Sprintf("%d", i)), udpAddr)
		if err != nil {
			t.Fatal(err)
		}
		time.Sleep(time.Microsecond)
	}
	select {
	case <-readerStopped:
	case <-time.After(time.Second):
		t.Fatal("reader timed out")
	}
	if msgsReceived != N {
		t.Fatalf("messages received: %d", msgsReceived)
	}
}

func TestConnReadDeadline(t *testing.T) {
	ls, _ := NewSocket("udp", "localhost:0")
	ds, _ := NewSocket("udp", "localhost:0")
	dcReadErr := make(chan error)
	go func() {
		c, _ := ds.Dial(ls.Addr().String())
		defer c.Close()
		_, err := c.Read(nil)
		dcReadErr <- err
	}()
	c, _ := ls.Accept()
	dl := time.Now().Add(time.Millisecond)
	c.SetReadDeadline(dl)
	_, err := c.Read(nil)
	require.Equal(t, errTimeout, err)
	// The deadline has passed.
	if !time.Now().After(dl) {
		t.FailNow()
	}
	// Returns timeout on subsequent read.
	_, err = c.Read(nil)
	require.Equal(t, errTimeout, err)
	// Disable the deadline.
	c.SetReadDeadline(time.Time{})
	readReturned := make(chan struct{})
	go func() {
		c.Read(nil)
		close(readReturned)
	}()
	select {
	case <-readReturned:
		// Read returned but shouldn't have.
		t.FailNow()
	case <-time.After(time.Millisecond):
	}
	c.Close()
	select {
	case <-readReturned:
	case <-time.After(time.Millisecond):
		t.Fatal("read should return after Conn is closed")
	}
	if err := <-dcReadErr; err != io.EOF {
		t.Fatalf("dial conn read returned %s", err)
	}
}

func connectSelfLots(n int, t testing.TB) {
	defer goroutineLeakCheck(t)()
	s, err := NewSocket("udp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	go func() {
		for range iter.N(n) {
			c, err := s.Accept()
			if err != nil {
				log.Fatal(err)
			}
			defer c.Close()
		}
	}()
	dialErr := make(chan error)
	connCh := make(chan net.Conn)
	dialSema := make(chan struct{}, backlog)
	for range iter.N(n) {
		go func() {
			dialSema <- struct{}{}
			c, err := s.Dial(s.Addr().String())
			<-dialSema
			if err != nil {
				dialErr <- err
				return
			}
			connCh <- c
		}()
	}
	conns := make([]net.Conn, 0, n)
	for range iter.N(n) {
		select {
		case c := <-connCh:
			conns = append(conns, c)
		case err := <-dialErr:
			t.Fatal(err)
		}
	}
	for _, c := range conns {
		if c != nil {
			c.Close()
		}
	}
	s.mu.Lock()
	for len(s.conns) != 0 {
		// log.Print(len(s.conns))
		s.event.Wait()
	}
	s.mu.Unlock()
	s.Close()
}

// Connect to ourself heaps.
func TestConnectSelf(t *testing.T) {
	// A rough guess says that at worst, I can only have 0x10000/3 connections
	// to the same socket, due to fragmentation in the assigned connection
	// IDs.
	connectSelfLots(0x1000, t)
}

func BenchmarkConnectSelf(b *testing.B) {
	for range iter.N(b.N) {
		connectSelfLots(2, b)
	}
}

func BenchmarkNewCloseSocket(b *testing.B) {
	for range iter.N(b.N) {
		s, err := NewSocket("udp", "localhost:0")
		if err != nil {
			b.Fatal(err)
		}
		err = s.Close()
		if err != nil {
			b.Fatal(err)
		}
	}
}

func TestRejectDialBacklogFilled(t *testing.T) {
	s, err := NewSocket("udp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	errChan := make(chan error, 1)
	dial := func() {
		_, err := s.Dial(s.Addr().String())
		if err != nil {
			errChan <- err
		}
	}
	// Fill the backlog.
	for range iter.N(backlog + 1) {
		go dial()
	}
	s.mu.Lock()
	for len(s.backlog) < backlog {
		s.event.Wait()
	}
	s.mu.Unlock()
	select {
	case <-errChan:
		t.FailNow()
	default:
	}
	// One more connection should cause a dial attempt to get reset.
	go dial()
	err = <-errChan
	if err.Error() != "peer reset" {
		t.FailNow()
	}
	s.Close()
}

// Make sure that we can reset AfterFunc timers, so we don't have to create
// brand new ones everytime they fire. Specifically for the Conn resend timer.
func TestResetAfterFuncTimer(t *testing.T) {
	fired := make(chan struct{})
	timer := time.AfterFunc(time.Millisecond, func() {
		fired <- struct{}{}
	})
	<-fired
	if timer.Reset(time.Millisecond) {
		// The timer should have expired
		t.FailNow()
	}
	<-fired
}

func connPair() (initer, accepted net.Conn) {
	s, err := NewSocket("udp", "localhost:0")
	if err != nil {
		panic(err)
	}
	defer s.Close()
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		var err error
		initer, err = Dial(s.Addr().String())
		if err != nil {
			panic(err)
		}
	}()
	accepted, err = s.Accept()
	if err != nil {
		panic(err)
	}
	wg.Wait()
	return
}

// Check that peer sending FIN doesn't cause unread data to be dropped in a
// receiver.
func TestReadFinishedConn(t *testing.T) {
	a, b := connPair()
	defer a.Close()
	defer b.Close()
	mu.Lock()
	originalAPDC := artificialPacketDropChance
	artificialPacketDropChance = 1
	mu.Unlock()
	n, err := a.Write([]byte("hello"))
	require.Equal(t, 5, n)
	require.NoError(t, err)
	n, err = a.Write([]byte("world"))
	require.Equal(t, 5, n)
	require.NoError(t, err)
	mu.Lock()
	artificialPacketDropChance = originalAPDC
	mu.Unlock()
	a.Close()
	all, err := ioutil.ReadAll(b)
	require.NoError(t, err)
	require.EqualValues(t, "helloworld", all)
}

func TestCloseDetachesQuickly(t *testing.T) {
	s, _ := NewSocket("udp", "localhost:0")
	defer s.Close()
	go func() {
		a, _ := s.Dial(s.Addr().String())
		log.Print("close a")
		a.Close()
		log.Print("closed a")
	}()
	b, _ := s.Accept()
	b.Close()
	s.mu.Lock()
	for len(s.conns) != 0 {
		log.Print(len(s.conns))
		s.event.Wait()
	}
	s.mu.Unlock()
}


text:
package org.optaplanner.constraint.streams.common;

/**
 * Determines the behavior of joins and conditional propagation
 * based on whether they are coming off of a constraint stream started by
 * either {@link org.optaplanner.core.api.score.stream.ConstraintFactory#from(Class)}
 * or {@link org.optaplanner.core.api.score.stream.ConstraintFactory#forEach(Class)}
 * family of methods.
 *
 *

 * For classes which are not planning entities, all of their instances are always retrieved.
 * For classes which are planning entities,
 * the difference in behavior depends on whether they use nullable planning variables.
 * (See {@link org.optaplanner.core.api.domain.variable.PlanningVariable}.)
 */
public enum RetrievalSemantics {

    /**
     * Joins do not include entities with null planning variables,
     * unless specifically requested by join(forEachIncludingNullVars(...)).
     * Conditional propagation does not include null planning variables,
     * unless specifically requested using a *IncludingNullVars() method overload.
     *
     *

     * Applies when the stream comes off of a {@link org.optaplanner.core.api.score.stream.ConstraintFactory#forEach(Class)}
     * family of methods.
     */
    STANDARD,
    /**
     * Joins include entities with null planning variables if these variables are nullable.
     * Conditional propagation always includes entities with null planning variables,
     * regardless of whether their planning variables are nullable.
     *
     *

     * Applies when the stream comes off of a {@link org.optaplanner.core.api.score.stream.ConstraintFactory#from(Class)}
     * family of methods.
     *
     * @deprecated this semantics is deprecated and kept around for backward compatibility reasons. It will be removed in 9.0
     *             together with the from() family of methods, along with this entire enum.
     */
    @Deprecated(forRemoval = true)
    LEGACY
}


text:
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de'

from scipy import random
from neuronlayer import NeuronLayer
from pybrain.tools.functions import expln, explnPrime
from pybrain.structure.parametercontainer import ParameterContainer

class GaussianLayer(NeuronLayer, ParameterContainer):
    """ A layer implementing a gaussian interpretation of the input. The mean is
    the input, the sigmas are stored in the module parameters."""

    def __init__(self, dim, name=None):
        NeuronLayer.__init__(self, dim, name)
        # initialize sigmas to 0
        ParameterContainer.__init__(self, dim, stdParams = 0)
        # if autoalpha is set to True, alpha_sigma = alpha_mu = alpha*sigma^2
        self.autoalpha = False
        self.enabled = True

    def setSigma(self, sigma):
        """Wrapper method to set the sigmas (the parameters of the module) to a
        certain value. """
        assert len(sigma) == self.indim
        self._params *= 0
        self._params += sigma

    def _forwardImplementation(self, inbuf, outbuf):
        if not self.enabled:
            outbuf[:] = inbuf
        else:
            outbuf[:] = random.normal(inbuf, expln(self.params))

    def _backwardImplementation(self, outerr, inerr, outbuf, inbuf):
        expln_params = expln(self.params)
        self._derivs += ((outbuf - inbuf)**2 - expln_params**2) / expln_params * explnPrime(self.params)
        inerr[:] = (outbuf - inbuf)

        if not self.autoalpha:
            inerr /= expln_params**2
            self._derivs /= expln_params**2


text:
module ResourceDSL
  module ActsAsStat

    def acts_as_stats_actions
      # must be used as last DSL for resource

      action_item :truncate_stats, only: [:show, :edit] do
        dropdown_menu 'Statistics' do

          if can?(:manage, resource) && active_admin_config.member_actions.detect{|element|  element.name ==  :truncate_long_time_stats  }.present?
            item 'Truncate long time stats', action: :truncate_long_time_stats, id: resource.id
          end

          if can?(:manage, resource) && active_admin_config.member_actions.detect{|element|  element.name ==  :truncate_short_window_stats  }.present?
            item 'Truncate short window stats', action: :truncate_short_window_stats, id: resource.id
          end

        end
      end

    end

    def acts_as_stat

      sidebar 'Long time stats', only: [:show, :edit] do
        if resource.statistic.nil?
          div do
            'No data'
          end
        else
          div class: :stats_table do
            attributes_table_for resource.statistic do
              row :created_at
              row :updated_at
              row :calls
              row :calls_success
              row :calls_fail
              row :total_duration
              row :asr
              row :acd
              row :locked_at
              row :unlocked_at
            end
          end
        end
      end

      member_action :truncate_long_time_stats do
        #todo  cancan support   ?
        if can? :manage, resource
          resource = active_admin_config.resource_class.find(params[:id])
          resource.statistic.destroy if resource.statistic
          flash[:notice] = "#{active_admin_config.resource_label}'s statistic was successfully truncated"
        end
        redirect_to(:back)
      end

    end

    def acts_as_quality_stat

      member_action :truncate_short_window_stats do
        #todo  cancan support   ?
        if can? :manage, resource
          resource = active_admin_config.resource_class.find(params[:id])
          resource.quality_stats.delete_all if resource.quality_stats
          flash[:notice] = "#{active_admin_config.resource_label}'s statistic was successfully truncated"
        end
        redirect_to(:back)
      end

      sidebar 'Short window stats', only: [:show, :edit] do
        data = resource.quality_stats.total
        if data.count==0
          div do
            'No data'
          end
        else
          div class: :stats_table do
            attributes_table_for data do
              row :window do |t|
                strong do
                  text_node t.w
                  text_node ' h.'
                end
              end
              row :count do |t|
                strong do
                  text_node t.count
                end
              end
              row :short_count do |t|
                strong do
                  text_node t.short_count
                end
              end
              row :duration do |t|
                strong do
                  text_node t.duration
                  text_node ' min.'
                end
              end
              row :acd do |t|
                strong do
                  text_node t.acd
                  text_node ' min.'
                end
              end
              row :asr do |t|
                strong do
                  text_node t.asr
                end
              end
              row :max_pdd do |t|
                strong do
                  text_node t.max_pdd
                  text_node ' sec.'
                end
              end
              row :min_pdd do |t|
                strong do
                  text_node t.min_pdd
                  text_node ' sec.'
                end
              end
            end
          end
        end
      end

    end

  end
end


text:
[![Build Status](https://secure.travis-ci.org/mattdbridges/validates_formatting_of.png)](http://travis-ci.org/mattdbridges/validates_formatting_of)
[![Dependency Status](https://gemnasium.com/mattdbridges/validates_formatting_of.png?travis)](https://gemnasium.com/mattdbridges/validates_formatting_of)
[![Code Climate](https://codeclimate.com/github/mattdbridges/validates_formatting_of.png)](https://codeclimate.com/github/mattdbridges/validates_formatting_of)

# Validates Formatting Of

The `validates_formatting_of` gem adds several convenient methods to validate things such as emails, urls, and phone numbers in a Rails application.

# Supported Ruby Versions

* 1.9.3
* 2.0.0
* 2.1.0
* 2.2.0

# Installation

To install `validates_formatting_of`, add the following to your `Gemfile`:

    gem 'validates_formatting_of'

Then bundle install:

    bundle install

# Usage

Using `validates_formatting_of` is as simple as using Rails' built-in validation methods in models.

```ruby
class User < ActiveRecord::Base
  validates_formatting_of :email
end
```

If the name of the column is identical to the validation method you would use, it auto-selects that validation method. Thus, this is a shortcut for the following:

```ruby
class User < ActiveRecord::Base
  validates_formatting_of :email, :using => :email
end
```

This call will ensure that the user-provided email is a valid email. This way, you will not need to find or write your own regex to validate. All of that logic is contained within `validates_formatting_of`.

# Rails validation options still available

You can still add the following options when using `validates_formatting_of`:

* `:allow_nil`
* `:allow_blank`
* `:on`
* `:if`
* `:unless`
* You can also specify the `:message` option to use a custom validation message.

# Share your Validations

Say, for example, you have identical plain-old regex validations for different columns or even on different models entirely. You can easily alleviate this problem by simply adding the validation(s) in an initializer file.

While very unrealistic, these examples should serve their purpose in demonstrating this ability.

```ruby
# config/initializers/validates_formatting_of.rb
ValidatesFormattingOf::Method.add :loweralpha, /[a-z]/, "must be lowercase and no spaces"
ValidatesFormattingOf::Method.add :upperalpha, /[A-Z]/, "must be uppercase and no spaces"
ValidatesFormattingOf::Method.add :weak_password, /[a-zA-Z0-9]{8,}/, "must contain only letters and numbers and be at least 8 characters long".
```

Keep in mind, since this gem is only ActiveModel-dependent, you should be able to do this in whatever non-Rails application classes you have that include `ActiveModel::Validations` in some way (and that extend the `ValidatesFormattingOf::ModelAdditons` module).

# Built-in Validations

`validates_formatting_of` has the following built-in validations:

```ruby
class ExampleModel < ActiveRecord::Base
  validates_formatting_of :email, :using => :email      # Email
  validates_formatting_of :first_name, :using => :alpha # Letters
  validates_formatting_of :website, :using => :url      # URLs
  validates_formatting_of :text, :using => :alphanum    # Alpha-numeric
  validates_formatting_of :zipcode, :using => :us_zip   # US Zip Code
  validates_formatting_of :phone, :using => :us_phone   # US Phone Numbers
  validates_formatting_of :ip, :using => :ip_address_v4 # IPv4
  validates_formatting_of :ssn, :using => :ssn          # Social Security Numbers
  validates_formatting_of :color, :using => :hex_color  # Hexadecimal Colors
  validates_formatting_of :amount, :using => :dollars   # Dollars

  # Credit Card (Visa, Mastercard, Discover, and American Express)
  validates_formatting_of :cc, :using => :credit_card
end
```

**Note**: If you use `client_side_validations` then you need to use the following validation method:

```ruby
class User < ActiveRecord::Base
  validates_formatting_of :email, :using => :simple_email
end
```

### Plain Old Ruby Objects

If you are not using ActiveRecord or want to use it on some other type of object, this is the least you need to get validations running.

```ruby
class User
  include ActiveModel::Validations
  extend ValidatesFormattingOf::ModelAdditions

  attr_accessor :email

  validates_formatting_of :email, :using => :email
end
```

# Over-writable

If, for any reason, you want to overwrite the regex specified in the gem, you can using the `:with` option just like in ActiveModel's built-in `validates_format_of`.

```ruby
class Person < ActiveRecord::Base
  validates_formatting_of :first_name, :with => /[A-Z]/i
end
```

# Development and Contribution

To add a simple regex validation, all that is necessary is to add a single line to the `ValidatesFormattingOf::Method` module in the `lib/method.rb` file (with a line or two of documentation explaining it's use).

For example:

```ruby
module ValidatesFormattingOf::Method
  # This :validation_name method is for example purposes only.
  # You can use this in production, but it would require a value of 'example regex' to pass.
  add :validation_name, %r{example regex}iux, "is a message for validation method :validation_name"
end
```

1. Fork it
2. Make it awesome (with passing tests)
3. Create a new Pull Request.

# Have Ideas?

Do you use a particular pattern on a regular basis that isn't here or you would like to contribute? For now, [create a new issue](https://github.com/mattdbridges/validates_formatting_of/issues/new) in the issue tracker. I would be more than happy to consider adding it to the project.


text:
package darks.orm.core.data.xml;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import darks.orm.app.QueryEnumType;
import darks.orm.util.StringHelper.ParamFlag;

public class DMLQueryData implements Cloneable
{

    private ConcurrentMap<String, String> sqlMap = new ConcurrentHashMap<String, String>();

    private ConcurrentMap<Integer, String> sqlConstituteMap = new ConcurrentHashMap<Integer, String>();

    private static final String DEFAULT_KEY = "0000";

    private static final int INIT_BUFFER_SIZE = 256;

    private static final int INIT_HASH_VALUE = 2;

    private static final int HASH_VALUE_PARAM = 32;

    public enum DMLQueryDataType
    {
        Simple, Select, Constitute
    };

    private String resultType;

    private Class<?> resultClass;

    private boolean autoCascade;

    private String alias;

    private String attribute;

    private QueryEnumType queryType;

    private DMLQueryDataType queryDataType;

    private AspectData aspectData;

    private ParamFlag valuesParam;

    private ParamFlag pageParam;

    private ParamFlag pageSizeParam;

    public DMLQueryData()
    {

    }

    public DMLQueryData(String resultType, boolean autoCascade, String alias, String attribute,
        QueryEnumType queryType, DMLQueryDataType queryDataType)
    {
        this.resultType = resultType;
        this.autoCascade = autoCascade;
        this.alias = alias;
        this.attribute = attribute;
        this.queryType = queryType;
        this.queryDataType = queryDataType;
    }

    public void setSQL(String sql)
    {
        sqlMap.put(DEFAULT_KEY, sql);
    }

    public void addSQL(String key, String sql)
    {
        sqlMap.put(key, sql);
    }

    public String getSql()
    {
        return getSql(DEFAULT_KEY);
    }

    public String getSql(String key)
    {
        if (key == null)
            return null;
        if (key.indexOf("@") < 0)
        {
            key = key.replace(",", "@");
        }
        if (sqlMap.containsKey(key))
        {
            return sqlMap.get(key);
        }
        return null;
    }

    public String getSql(Object[] values)
    {
        String key = null;
        if (queryDataType == DMLQueryDataType.Simple || values == null)
        {
            key = DEFAULT_KEY;
            return getSql(key);
        }
        else if (queryDataType == DMLQueryDataType.Constitute)
        {
            return getConstituteSql(values);
        }
        else if (queryDataType == DMLQueryDataType.Select)
        {
            return getSelectSql(values);
        }
        return getSql(key);
    }

    public String getConstituteSql(Object[] values)
    {
        int key = hash(values);
        String sql = sqlConstituteMap.get(key);
        if (sql != null)
        {
            return sql;
        }
        sql = getSql(DEFAULT_KEY);
        StringBuffer buf = new StringBuffer(INIT_BUFFER_SIZE);
        buf.append(sql);
        for (Object val : values)
        {
            if (val == null)
                continue;
            sql = getSql(String.valueOf(val));
            if (sql == null)
                continue;
            if (!sql.startsWith(" "))
                buf.append(" ");
            buf.append(sql);
        }
        sql = buf.toString();
        sqlConstituteMap.put(key, sql);
        return sql;
    }

    public String getSelectSql(Object[] values)
    {
        String key = null;
        StringBuffer buf = new StringBuffer();
        if (values != null)
        {
            for (Object val : values)
            {
                buf.append(val);
                buf.append("@");
            }
        }
        if (buf.length() > 0)
            buf.deleteCharAt(buf.length() - 1);
        key = buf.toString();
        return getSql(key);
    }

    private int hash(Object[] values)
    {
        int result = INIT_HASH_VALUE;
        return getObjectsHashCode(result, values);
    }

    private int getObjectHashCode(Object obj, int ret)
    {
        int result = HASH_VALUE_PARAM * ret;
        if (obj == null)
            return result;
        if (obj instanceof Boolean)
        {
            boolean bln = (Boolean)obj;
            result = result + (bln ? 0 : 1);
        }
        else if (obj instanceof Byte || obj instanceof Character || obj instanceof Short || obj instanceof Integer)
        {
            result = result + (Integer)obj;
        }
        else if (obj instanceof Long)
        {
            long along = (Long)obj;
            result = result + (int)(along ^ (along >>> 32));
            ;
        }
        else if (obj instanceof Float)
        {
            float afloat = (Float)obj;
            result = result + Float.floatToIntBits(afloat);
        }
        else if (obj instanceof Double)
        {
            double adouble = (Double)obj;
            long tolong = Double.doubleToLongBits(adouble);
            result = result + (int)(tolong ^ (tolong >>> 32));
        }
        else
        {
            result = result + obj.hashCode();
        }
        return result;
    }

    private int getObjectsHashCode(int result, Object[] objs)
    {
        if (objs == null)
            return HASH_VALUE_PARAM * result;
        for (int i = 0; i < objs.length; i++)
        {
            result = getObjectHashCode(objs[i], result);
        }
        return result;
    }

    public ConcurrentMap<String, String> getSqls()
    {
        return sqlMap;
    }

    public ConcurrentMap<String, String> getSqlMap()
    {
        return sqlMap;
    }

    public void setSqlMap(ConcurrentMap<String, String> sqlMap)
    {
        this.sqlMap = sqlMap;
    }

    public String getResultType()
    {
        return resultType;
    }

    public void setResultType(String resultType)
    {
        this.resultType = resultType;
    }

    public boolean isAutoCascade()
    {
        return autoCascade;
    }

    public void setAutoCascade(boolean autoCascade)
    {
        this.autoCascade = autoCascade;
    }

    public String getAlias()
    {
        return alias;
    }

    public void setAlias(String alias)
    {
        this.alias = alias;
    }

    public String getAttribute()
    {
        return attribute;
    }

    public void setAttribute(String attribute)
    {
        this.attribute = attribute;
    }

    public QueryEnumType getQueryType()
    {
        return queryType;
    }

    public void setQueryType(QueryEnumType queryType)
    {
        this.queryType = queryType;
    }

    public DMLQueryDataType getQueryDataType()
    {
        return queryDataType;
    }

    public void setQueryDataType(DMLQueryDataType queryDataType)
    {
        this.queryDataType = queryDataType;
    }

    public Class<?> getResultClass()
    {
        return resultClass;
    }

    public void setResultClass(Class<?> resultClass)
    {
        this.resultClass = resultClass;
    }

    public AspectData getAspectData()
    {
        return aspectData;
    }

    public void setAspectData(AspectData aspectData)
    {
        this.aspectData = aspectData;
    }

	public ParamFlag getValuesParam()
	{
		return valuesParam;
	}

	public void setValuesParam(ParamFlag valuesParam)
	{
		this.valuesParam = valuesParam;
	}

	public ParamFlag getPageParam()
	{
		return pageParam;
	}

	public void setPageParam(ParamFlag pageParam)
	{
		this.pageParam = pageParam;
	}

	public ParamFlag getPageSizeParam()
	{
		return pageSizeParam;
	}

	public void setPageSizeParam(ParamFlag pageSizeParam)
	{
		this.pageSizeParam = pageSizeParam;
	}

	public DMLQueryData clone()
    {
        try
        {
            return (DMLQueryData)super.clone();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}


text:
<?php

namespace Deimos\Flow;

class Lexer
{

    /**
     * @var Configure $configure
     */
    protected $configure;

    /**
     * @var array
     */
    protected $data = [

        // if
        LexerConst::T_IF           => Extension\TIF\TIF::class,
        LexerConst::T_ELSEIF       => Extension\TIF\TELSEIF::class,
        LexerConst::T_ELSE         => Extension\TIF\TELSE::class,
        LexerConst::T_END_IF       => Extension\TIF\TEndIF::class,

        // for
        LexerConst::T_FOR          => Extension\TFor\TFor::class,
        LexerConst::T_END_FOR      => Extension\TFor\TEndFor::class,

        // while
        LexerConst::T_WHILE        => Extension\TWhile\TWhile::class,
        LexerConst::T_END_WHILE    => Extension\TWhile\TEndWhile::class,

        // foreach
        LexerConst::T_FOREACH      => Extension\TForeach\TForeach::class,
        LexerConst::T_FOREACH_ELSE => Extension\TForeach\TElseForeach::class,
        LexerConst::T_END_FOREACH  => Extension\TForeach\TEndForeach::class,

        // operators
        LexerConst::T_CONTINUE     => Extension\TSimple\TContinue::class,
        LexerConst::T_BREAK        => Extension\TSimple\TBreak::class,

        // PHP
        LexerConst::T_PHP          => Extension\TPHP\TPHP::class,
        LexerConst::T_END_PHP      => Extension\TPHP\TEndPHP::class,

        // ASSIGN
        LexerConst::T_ASSIGN       => Extension\TSimple\TAssign::class,

        // variable
        LexerConst::T_VARIABLE     => Extension\TSimple\TVariable::class,

        // include
        LexerConst::T_INCLUDE      => Extension\TSimple\TInclude::class,

        // extends
        LexerConst::T_EXTENDS      => Extension\TSimple\TExtends::class,

        // partial
        LexerConst::T_PARTIAL      => Extension\TSimple\TPartial::class,

        // block
        LexerConst::T_BLOCK_START  => Extension\TBlock\TBlockStart::class,
        LexerConst::T_BLOCK_END    => Extension\TBlock\TEndBlock::class,

        // try|catch|finally
        LexerConst::T_TRY          => Extension\TTry\TTry::class,
        LexerConst::T_CATCH        => Extension\TTry\TCatch::class,
        LexerConst::T_FINALLY      => Extension\TTry\TFinally::class,
        LexerConst::T_END_TRY      => Extension\TTry\TEndTry::class,

    ];

    /**
     * Lexer constructor.
     *
     * @param Configure $configure
     */
    public function __construct(Configure $configure)
    {
        $this->configure = $configure;
    }

    /**
     * @param $key
     *
     * @return mixed
     *
     * @throws \InvalidArgumentException
     */
    public function get($key)
    {
        if (!isset($this->data[$key]))
        {
            throw new \InvalidArgumentException('Config key "' . $key . '" not found!');
        }

        return $this->data[$key];
    }

}


text:
import requests
from bs4 import BeautifulSoup
import csv
import re
import time

url = 'http://www.nrc.gov/reactors/operating/list-power-reactor-units.html'

web_page = requests.get(url)
web_page.encoding = 'UTF-8'
soup = BeautifulSoup(web_page.text, 'html.parser')

reactor_table = soup.find('table')

# We'll send stuff to a different file.
csv_file = open('reactors_more.csv', 'wb')
output = csv.writer(csv_file)
# Add the two new fields we'll grab from the detail page to the header row.
output.writerow(['NAME', 'LINK', 'DOCKET', 'TYPE', 'LOCATION', 'OWNER', 'REGION', 'MWT', 'CONTAINMENT'])

for row in reactor_table.find_all('tr')[1:]:
    cell = row.find_all('td')
    name = cell[0].contents[0].string
    link = cell[0].contents[0].get('href')
    docket = cell[0].contents[2].strip()
    type = cell[1].string
    location = cell[2].string.encode('utf8')
    owner = cell[3].contents[0].encode('utf8')
    region = cell[4].string

    # Let's get the reactor's detail page and get a quick note about it.
    print 'Fetching detail from '+link
    detail_page = requests.get('http://www.nrc.gov'+link)

    # Use pattern matching to find the text after 'Licensed MwT:'
    # '(?i)licensed mwt:\s*(.*)<' decoded:
    # (?i) = ignore case
    # \s* = spaces may exist
    # () = the text we care about
    # .* = all characters, including text, numbers and punctuation
    mwt_search = re.search('(?i)licensed mwt:\s*(.*)<', detail_page.text)
    # Send the match to a variable.
    mwt = mwt_search.group(1).strip()

    # Do the same thing for the text after 'Containment Type:'
    # '(?i)containment type:\s*(.*?)\s*<'
    containment_search = re.search('(?i)containment type:\s*(.*?)\s*<', detail_page.text)
    containment = containment_search.group(1).strip()

    # Add these two new fields to the csv.writer's output.
    output.writerow([name, link, docket, type, location, owner, region, mwt, containment])

    # Let's slow down how quickly we're sending these requests for detail pages.
    time.sleep(2)

csv_file.close()
print 'All done!'


text:
package com.metrink.metric.io;

import java.util.List;

import com.metrink.metric.Metric;

/**
 * Writes {@link Metric}s to a source.
 */
public interface MetricWriter {
    /**
     * Initializes the reader once during startup.
     */
    public void init();

    /**
     * Shuts down the system reader during shutdown.
     */
    public void shutdown();

    /**
     * Writes the {@link Metric}s to the source.
     * @param metrics the {@link Metric}s to write.
     */
    public void writeMetrics(List<Metric> metrics);

    /**
     * Deletes all of the {@link Metric}s before a given time.
     * @param before the timestamp which to delete {@link Metric}s before.
     * @return the number of {@link Metric}s removed.
     */
    public int deleteMetrics(long before);

}


text:
using System;
using System.IO;

namespace db_cola.Driver
{
    public class Script
    {
	    private string _content;
	    private readonly string _fullFilePath;

	    public enum QueryItem
	    {
	        Database = 1,
	        Username = 2
	    }

	    public Script(string a_FilePath)
	    {
	        _fullFilePath = a_FilePath;
	        SetContent();
	    }

	    private void SetContent()
	    {
	        _content = File.ReadAllText(_fullFilePath);
	    }

	    public string GetFileName()
	    {
	        return Path.GetFileName(_fullFilePath);
	    }

	    public string[] Parse()
	    {
	        //divide into GO groups to avoid errors
	        var content = _content;

	        content = content.Replace("go\r\n", "GO\r\n");
	        content = content.Replace("go\t", "GO\t");
	        content = content.Replace("\ngo", "\nGO");

	        return content.Split(new[] { "GO\r\n", "GO\t", "\nGO" }, StringSplitOptions.RemoveEmptyEntries);
	    }

	    public void CustomizeQueryItem(QueryItem a_ItemToCustomize, string a_NewItemContent)
	    {
	        switch (a_ItemToCustomize)
	        {
		    case QueryItem.Database:
		        _content = _content.Replace("Broker_DB", a_NewItemContent);
	            _content = _content.Replace("BrokerProgram", a_NewItemContent);
		        break;
		    case QueryItem.Username:
                _content = _content.Replace("BrkWebUser", a_NewItemContent);
                _content = _content.Replace("BrkProgramUser", a_NewItemContent);
		        break;
	        }
	    }
    }
}


text:
using std::inserter;
using std::function;
using std::move;
using std::runtime_error;
using std::set;
using std::set_difference;
using std::string;
using std::tie;
using std::vector;

namespace tcframe {

struct TestSuite {
    friend class TestSuiteBuilder;

private:
    vector<TestGroup> testGroups_;

public:
    TestSuite() = default;

    explicit TestSuite(vector<TestGroup> testGroups)
            : testGroups_(move(testGroups)) {}

    const vector<TestGroup>& testGroups() const {
        return testGroups_;
    }

    bool operator==(const TestSuite& o) const {
        return tie(testGroups_) == tie(o.testGroups_);
    }
};

class TestSuiteBuilder {
private:
    string slug_;
    set<int> definedSubtaskIds_;
    function<void()> beforeClosure_ = []{};
    function<void()> afterClosure_ = []{};

    set<int>* curSubtaskIds_ = nullptr;

    int curOfficialTestGroupId_ = TestGroup::MAIN_ID;
    bool hasCurOfficialTestGroup_ = false;
    set<int> curOfficialSubtaskIds_ = {Subtask::MAIN_ID};
    vector<TestGroup> curOfficialTestGroups_;
    vector<TestCase> curOfficialTestCases_;

    bool hasCurSampleTestCase_ = false;
    set<int> curSampleSubtaskIds_ = {Subtask::MAIN_ID};
    vector<TestCase> curSampleTestCases_;
    optional<vector<string>> curSampleInputLines_;
    optional<vector<string>> curSampleOutputLines_;

public:
    TestSuiteBuilder& setSlug(string slug) {
        slug_ = move(slug);
        return *this;
    }

    TestSuiteBuilder& setDefinedSubtaskIds(set<int> definedSubtaskIds) {
        definedSubtaskIds_ = move(definedSubtaskIds);
        return *this;
    }

    TestSuiteBuilder& setBeforeClosure(function<void()> beforeClosure) {
        beforeClosure_ = move(beforeClosure);
        return *this;
    }

    TestSuiteBuilder& setAfterClosure(function<void()> afterClosure) {
        afterClosure_ = move(afterClosure);
        return *this;
    }

    TestSuiteBuilder& newSampleTestCase() {
        if (hasCurSampleTestCase_) {
            addCurrentSampleTestCase();
        }

        hasCurSampleTestCase_ = true;
        curSampleSubtaskIds_ = {};
        curSubtaskIds_ = &curSampleSubtaskIds_;
        curSampleInputLines_ = {};
        curSampleOutputLines_ = {};

        return *this;
    }

    TestSuiteBuilder& newTestGroup() {
        if (hasCurOfficialTestGroup_) {
            addCurrentOfficialTestGroup();
        } else {
            curOfficialTestGroupId_ = 0;
        }

        hasCurOfficialTestGroup_ = true;
        curOfficialTestGroupId_++;
        curOfficialSubtaskIds_ = {};
        curSubtaskIds_ = &curOfficialSubtaskIds_;
        curOfficialTestCases_.clear();

        return *this;
    }

    TestSuiteBuilder& Subtasks(set<int> subtaskIds) {
        set<int> undefinedSubtaskIds;
        set_difference(
                subtaskIds.begin(),
                subtaskIds.end(),
                definedSubtaskIds_.begin(),
                definedSubtaskIds_.end(),
                inserter(undefinedSubtaskIds, undefinedSubtaskIds.begin()));

        if (!undefinedSubtaskIds.empty()) {
            throw runtime_error(
                    "The following subtasks are referenced but not defined: " +
                    StringUtils::setToString(undefinedSubtaskIds));
        }

        *curSubtaskIds_ = subtaskIds;
        return *this;
    }

    TestSuiteBuilder& Input(vector<string> lines) {
        curSampleInputLines_ = optional<vector<string>>(move(lines));
        return *this;
    }

    TestSuiteBuilder& Output(vector<string> lines) {
        curSampleOutputLines_ = optional<vector<string>>(move(lines));
        return *this;
    }

    TestSuiteBuilder& addOfficialTestCase(function<void()> clozure, string description) {
        // Note: GCC will be angry at you if the parameter name is "closure".
        // https://bugs.archlinux.org/task/35803

        curOfficialTestCases_.push_back(TestCaseBuilder()
                .setName(TestCase::createName(
                        TestGroup::createName(slug_, curOfficialTestGroupId_),
                        (int) curOfficialTestCases_.size() + 1))
                .setSubtaskIds(curOfficialSubtaskIds_)
                .setDescription(move(description))
                .setData(new OfficialTestCaseData([=]{
                    beforeClosure_();
                    clozure();
                    afterClosure_();}))
                .build());

        return *this;
    }

    TestSuite build() {
        if (hasCurSampleTestCase_ && curSampleInputLines_) {
            addCurrentSampleTestCase();
        }
        if (!curOfficialTestCases_.empty()) {
            addCurrentOfficialTestGroup();
        }

        vector<TestGroup> testGroups;
        testGroups.emplace_back(TestGroup::SAMPLE_ID, curSampleTestCases_);
        for (auto testGroup : curOfficialTestGroups_) {
            testGroups.push_back(testGroup);
        }

        return TestSuite(testGroups);
    }

private:
    void addCurrentSampleTestCase() {
        if (!curSampleInputLines_) {
            // TODO: throw exception
        }

        SampleTestCaseData* data;

        string input;
        for (const string& line : curSampleInputLines_.value()) {
            input += line + "\n";
        }

        if (curSampleOutputLines_) {
            string output;
            for (const string& line : curSampleOutputLines_.value()) {
                output += line + "\n";
            }
            data = new SampleTestCaseData(input, output);
        } else {
            data = new SampleTestCaseData(input);
        }

        curSampleTestCases_.push_back(TestCaseBuilder()
                .setName(TestCase::createName(
                        TestGroup::createName(slug_, TestGroup::SAMPLE_ID),
                        (int) curSampleTestCases_.size() + 1))
                .setSubtaskIds(curSampleSubtaskIds_)
                .setData(data)
                .build());
    }

    void addCurrentOfficialTestGroup() {
        curOfficialTestGroups_.emplace_back(curOfficialTestGroupId_, curOfficialTestCases_);
    }
};

}


text:
title: Lubanga - Thomas Lubanga Dyilo - Sentencing
published: true
event_date: 2012-07-10T00:00:00.000Z
action: Sentencing
case: the-prosecutor-v-lubanga
accused: thomas-lubanga-dyilo
youtube_id: ZRtqgGzFfds
slug: lubanga-events-thomas-lubanga-dyilo-sentencing
---

[Decision](https://www.icc-cpi.int/Pages/record.aspx?docNo=ICC-01/04-01/06-2901) of the sentence
<br>[Press release](https://www.icc-cpi.int/Pages/item.aspx?name=pr824)


text:
1. Add a ZST_SmartTile component to any GameObject
2. Add sprites to the Sprites_* fields
3. Set the dimensions of the sprites† in the Side Length in Pixels field
5. Profit.

†n.b. this may be different than the image file dimensions, if you have some buffer alpha around the edges, like all the sample sprites in this package.

### HOW TO MAKE A SMART TILE (detailed)

1. Create an Empty GameObject in your scene. This will be your Smart Tile! Yay!

2. Add a ZST_SmartTile component to it. When you do this, a ZST_SnapToGrid component will be added *auto-magically*, though this component will be hidden in the Inspector, as you will control snap in step 5, when you set tile dimensions.

3. In the Inspector, with the Smart Tile selected, click the arrows on the left to expand Sprites_center, Sprites_side, Sprites_corner Convex, and Sprites_corner Concave. These lists will contain choices the Smart Tile will use to create different edge pieces. See the example sprites in the Sprites/ folder to see what they look like.

4. For each set of sprites, set the number of sprites you'd like the list to contain in the Size field, hit "Enter," and then add the sprites you'd like.  See the example prefabs for reference.

5. If your tile is not the default 100 x 100 pixels, set its value in the Side Length in Pixels field.

5. Add any other components you'd like to your Smart Tile, like a BoxCollider2D perhaps, and then turn your Smart Tile into a Prefab by dragging it from the Hierarchy Panel into the Project Panel.

6. Copy the Smart Tile or drag in some copies of the Prefab and watch the tiles magically adjust! Wooooah!

7. Make MOAR!

8. Once you have a configuration you like, select all your Smart Tiles, and press the "Reroll Sprite" button in the Inspector and watch your tiles become 🌈*diverse*🌈

9. Profit, of course.

### Q & A

**Q:** How do I make tiles different sizes?
**A:** Changing the Side Length in Pixels field to match the dimensions of your art will do the trick! In the previous version, this feature was… eh… I was bad at implementing things… but now it's fixed. Yay! n.b. Set the value to the dimensions of your _art_, which is not always the file size. The grass tiles are all 256 x 256 pixels, but the actual art is 100 x 100 pixels, with some art that hangs off the edge to make the seams prettier, so the value we use for those prefabs is 100.

**Q:** Diversity's great and all, but can I just make some tiles be the way I want them?
**A:** YES! If you give a list of tiles only ONE option, that tile will always use it. Say you always want your convex corners to be a particular sprite. Then you would make Sprites_cornerConvex be of size 1 and only accept that one sprite.

**Q:** I want to modify a property of the Sprite, but I can't! Everything is RUINED! How can I do this thing I want to do???
**A:** Each Smart Sprite is actually suuuper seeekritly made of 4 sprites arranged in a grid, but they're hidden! If you need to dig in there for any reason, you can click the "Show Children" button to unhide the children.  You can click it again ("Hide Children") to hide them.

**Q:** What's that Quadrants thing at the bottom...?
**A:** Yeah, don't touch that. It's just used to save data about your tile between scenes. If you really want, you can change it, but doing so overrides a lot of the automatic stuff, so... probably you don't want to actually do that?

**Q:** How come the BoxCollider2d don't change size? Is that a bug?
**A:** You mean on the prefabs that come with the package? Nah, not a bug. Those don't change size automatically, as it's not expected that all your tiles are gonna have BoxColliders2D, so the script doesn't do that. Maybe you want to use circles to improve performance, or… no colliders for even better performance! If you're making something custom, it's really up to you, and I definitely recommend starting from scratch rather than building from an existing prefab, since it's about as many steps to do it from scratch as it is to change an existing prefab :).

**Q:** I found a bug! What do I do??
**A:** Report it to zbarryte@alum.mit.edu! I'll try and fix it if I can!

**Q:** I have a question. Whom can I ask?
**A:** Email zbarryte@alum.mit.edu! I'd love to answer it if I can!

**Q:** This tool is a terrible piece of garbage, and the developer is probably also a terrible piece of (human) gargabe. To whom can I complain?
**A:** TOO BAD

### QUESTIONS? SUGGESTION?

Email zbarryte@alum.mit.edu


text:
echo "Connect the sixaxis"
read a
#sudo systemctl start bluetooth
sudo sixpair

if [[ $? == 0 ]]; then
  echo "Connected. Remove the sixpair from the usb"
elif
  echo "Failed..."
fi


text:
/**
 * Automatically generated file. DO NOT MODIFY
 */
package cn.smssdk.test;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "cn.smssdk.test";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = -1;
  public static final String VERSION_NAME = "";
}


text:
<?php

namespace app\modules\admin\controllers;

use Yii;

use app\models\Order;
use app\models\OrderSearch;
use app\models\OrderItem;
use app\models\OrderHistory;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * OrderController implements the CRUD actions for Order model.
 */
class OrderController extends Controller
{
    public $layout = 'admin-theme';
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'create', 'update', 'view', 'delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all Order models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Order model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $order_item = OrderItem::findOne($id);
        return $this->render('view', [
            'model' => $this->findModel($id),
            'order_item' =>$order_item
        ]);
    }

    /**
     * Creates a new Order model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Order();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Order model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $status = $model->status;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if ($model->status !== $status){
               $order_history = new OrderHistory();
               $order_history->status = $model->status;
               $order_history->order_id = $model->id;
               $order_history->author = Yii::$app->user->identity->username;
               $order_history->save();
            }
            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Order model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Order model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Order the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Order::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}