text:
package com.vishnus1224.teamworkapidemo.datastore;

import com.vishnus1224.rxjavateamworkclient.client.LatestActivityApiClient;
import com.vishnus1224.rxjavateamworkclient.model.LatestActivityResponse;
import com.vishnus1224.rxjavateamworkclient.model.LatestActivityResponseWrapper;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.net.UnknownHostException;
import java.util.List;

import rx.Observable;
import rx.observers.TestSubscriber;

import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Created by vishnu on 07/09/16.
 */
public class LatestActivityCloudDataStoreTest {

    @Mock
    private LatestActivityApiClient latestActivityApiClient;

    private LatestActivityCloudDataStore latestActivityCloudDataStore;

    @Before
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);

        latestActivityCloudDataStore = new LatestActivityCloudDataStore(latestActivityApiClient);

    }

    @Test
    public void testGetAllItems() throws Exception {

        when(latestActivityApiClient.getLatestActivity()).thenReturn(Observable.<LatestActivityResponseWrapper>empty());

        Observable<List<LatestActivityResponse>> observable = latestActivityCloudDataStore.getAllItems();

        TestSubscriber testSubscriber = new TestSubscriber();

        observable.subscribe(testSubscriber);

        testSubscriber.assertCompleted();
        testSubscriber.assertNoErrors();

        verify(latestActivityApiClient).getLatestActivity();

    }

    @Test
    public void testGetAllItemsThrowsUnknownHostException() throws Exception {

        when(latestActivityApiClient.getLatestActivity()).thenReturn(Observable.<LatestActivityResponseWrapper>error(new UnknownHostException()));

        Observable<List<LatestActivityResponse>> observable = latestActivityCloudDataStore.getAllItems();

        TestSubscriber testSubscriber = new TestSubscriber();

        observable.subscribe(testSubscriber);

        testSubscriber.assertError(UnknownHostException.class);
        testSubscriber.assertTerminalEvent();

        verify(latestActivityApiClient).getLatestActivity();

    }
}


text:
require(['html5Upload'], function (html5Upload) {
    if (html5Upload.fileApiSupported()) {
        var exportsModel = {
            processing: ko.observable(false),
            exports: ko.observableArray([])
        };

        function addExport(exportedFile) {
            var viewModel = {
                exportUrl: ko.observable(exportedFile.export_url),
                filename: ko.observable(exportedFile.filename)
            };
            exportsModel.exports.push(viewModel);
        }

        html5Upload.initialize({
            uploadUrl: '/projects',
            dropContainer: document.getElementById('dragndropimage'),
            inputField: document.getElementById('upload-input'),
            key: 'project',
            onFileAdded: function(file) {
                console.log(file);
                exportsModel.processing(true);
                file.on({
                    onCompleted: function(res) {
                        exportsModel.processing(false);
                        res = JSON.parse(res);
                        console.log(res);
                        if(res.exports) {
                            res.exports.forEach(addExport);
                        }
                    }
                });
            }
        });

        ko.applyBindings(exportsModel);
    }
});

redpajama_set_name: RedPajamaGithub


text:
an http authentication API for the Go programming language. Integrates with 3rd party auth providers to add security to your web application.

	go get github.com/dchest/authcookie
    go get github.com/bradrydzewski/go.auth

Python's Tornado framework, specifically their auth module, was the main inspiration for this library.

**THIS LIBRARY IS BEING ACTIVELY DEVELOPED. THE API IS CHANGING WEEKLY.**

## Providers
The following auth providers are supported:

* Github OAuth 2.0 [demo](https://github.com/bradrydzewski/go.auth/tree/master/examples/github)
* Google OAuth 2.0 [demo](https://github.com/bradrydzewski/go.auth/tree/master/examples/google)
* Google OpenId 2.0 [demo](https://github.com/bradrydzewski/go.auth/tree/master/examples/openid)
* Twitter OAuth 1.0a [demo](https://github.com/bradrydzewski/go.auth/tree/master/examples/twitter)
* Bitbucket OAuth 1.0a [demo](https://github.com/bradrydzewski/go.auth/tree/master/examples/bitbucket)

See the [multi-provider](https://github.com/bradrydzewski/go.auth/tree/master/examples/multiple) demo application to provide your users multiple login options.

We plan to add support for the following providers:

* Facebook
* LinkedIn

# Sample Code
Example program using the Github OAuth auth provider:

```go
// Set the default authentication configuration parameters
auth.Config.CookieSecret         = []byte("asdfasdfasfasdfasdfafsd")
auth.Config.LoginRedirect        = "/auth/login" // send user here to login
auth.Config.LoginSuccessRedirect = "/private"    // send user here post-login
auth.Config.CookieSecure         = false         // for local-testing only

// Create your login handler
githubHandler := auth.Github(githubAccessKey, githubSecretKey)
http.Handle("/auth/login", githubHandler)

// Example of a public http handler
http.HandleFunc("/public", Public)

// Example of a secured http handler
http.HandleFunc("/private", auth.SecureFunc(Private))
```

It is important to note that we have set `auth.Config.CookieSecure` to false
because we are testing locally, without using SSL. In production this flag should
ALWAYS be set to true and used in conjunction with SSL.

## User data
The `auth.SecureFunc` wraps a standard `http.HandlerFunc` and injects the username
into the http request's `r.URL.User.Username()` field:

```go
func Private(w http.ResponseWriter, r *http.Request) {
	user := r.URL.User.Username()
}
```

If you want additional user data you must implement our custom handler, and wrap
it with the `auth.SecureUserFunc`. This adds an additional `User` parameter to
your method signature that provides the full set of available user data:

```go
func Private(w http.ResponseWriter, r *http.Request, u auth.User) {
	username := u.Id()
	fullname := u.Name()
	avatar := u.Picture()
	email := u.Email()
	...
}

http.HandleFunc("/foo", auth.SecureUserFunc(Private))
```

# Configuration
`go.auth` uses the following default parameters which can be configured:

 Variable
 Description
 Default Value

 auth.Config.CookieName
 name of the secure cookie
 "UID"

 auth.Config.CookieSecret
 key used to encrypt the cookie value
 nil

 auth.Config.CookieSecure
 set the cookie's secure flag (true/false)
 true

 auth.Config.CookieHttpOnly
 set the cookie's HttpOnly flag (true/false)
 true

 auth.Config.CookieExp
 amount of time before cookie expires
 time.Hour * 24 * 14

 auth.Config.LoginRedirect
 where to re-direct a user that is not authenticated
 "/auth/login"

 auth.Config.LoginSuccessRedirect
 where to re-direct a user once authenticated
 "/"

Example:

```go
auth.Config.LoginRedirect = "/auth/login/google"
```


text:
/*
Package pfsutil provides utility functions that wrap a pfs.APIClient
to make the calling code slightly cleaner.
*/
package pfsutil

import (
	"io"
	"io/ioutil"

	"go.pedge.io/proto/stream"

	"github.com/pachyderm/pachyderm/src/pfs"
	"golang.org/x/net/context"
)

const chunkSize = 4096

func CreateRepo(apiClient pfs.APIClient, repoName string) error {
	_, err := apiClient.CreateRepo(
		context.Background(),
		&pfs.CreateRepoRequest{
			Repo: &pfs.Repo{
				Name: repoName,
			},
		},
	)
	return err
}

func InspectRepo(apiClient pfs.APIClient, repoName string) (*pfs.RepoInfo, error) {
	repoInfo, err := apiClient.InspectRepo(
		context.Background(),
		&pfs.InspectRepoRequest{
			Repo: &pfs.Repo{
				Name: repoName,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return repoInfo, nil
}

func ListRepo(apiClient pfs.APIClient) ([]*pfs.RepoInfo, error) {
	repoInfos, err := apiClient.ListRepo(
		context.Background(),
		&pfs.ListRepoRequest{},
	)
	if err != nil {
		return nil, err
	}
	return repoInfos.RepoInfo, nil
}

func DeleteRepo(apiClient pfs.APIClient, repoName string) error {
	_, err := apiClient.DeleteRepo(
		context.Background(),
		&pfs.DeleteRepoRequest{
			Repo: &pfs.Repo{
				Name: repoName,
			},
		},
	)
	return err
}

func StartCommit(apiClient pfs.APIClient, repoName string, parentCommit string) (*pfs.Commit, error) {
	commit, err := apiClient.StartCommit(
		context.Background(),
		&pfs.StartCommitRequest{
			Parent: &pfs.Commit{
				Repo: &pfs.Repo{
					Name: repoName,
				},
				Id: parentCommit,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return commit, nil
}

func FinishCommit(apiClient pfs.APIClient, repoName string, commitID string) error {
	_, err := apiClient.FinishCommit(
		context.Background(),
		&pfs.FinishCommitRequest{
			Commit: &pfs.Commit{
				Repo: &pfs.Repo{
					Name: repoName,
				},
				Id: commitID,
			},
		},
	)
	return err
}

func InspectCommit(apiClient pfs.APIClient, repoName string, commitID string) (*pfs.CommitInfo, error) {
	commitInfo, err := apiClient.InspectCommit(
		context.Background(),
		&pfs.InspectCommitRequest{
			Commit: &pfs.Commit{
				Repo: &pfs.Repo{
					Name: repoName,
				},
				Id: commitID,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return commitInfo, nil
}

func ListCommit(apiClient pfs.APIClient, repoName string) ([]*pfs.CommitInfo, error) {
	commitInfos, err := apiClient.ListCommit(
		context.Background(),
		&pfs.ListCommitRequest{
			Repo: &pfs.Repo{
				Name: repoName,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return commitInfos.CommitInfo, nil
}

func DeleteCommit(apiClient pfs.APIClient, repoName string, commitID string) error {
	_, err := apiClient.DeleteCommit(
		context.Background(),
		&pfs.DeleteCommitRequest{
			Commit: &pfs.Commit{
				Repo: &pfs.Repo{
					Name: repoName,
				},
				Id: commitID,
			},
		},
	)
	return err
}

func PutBlock(apiClient pfs.APIClient, repoName string, commitID string, path string, reader io.Reader) (*pfs.Block, error) {
	value, err := ioutil.ReadAll(reader)
	if err != nil {
		return nil, err
	}
	return apiClient.PutBlock(
		context.Background(),
		&pfs.PutBlockRequest{
			File: &pfs.File{
				Commit: &pfs.Commit{
					Repo: &pfs.Repo{
						Name: repoName,
					},
					Id: commitID,
				},
				Path: path,
			},
			Value: value,
		},
	)
}

func GetBlock(apiClient pfs.APIClient, hash string, writer io.Writer) error {
	apiGetBlockClient, err := apiClient.GetBlock(
		context.Background(),
		&pfs.GetBlockRequest{
			Block: &pfs.Block{
				Hash: hash,
			},
		},
	)
	if err != nil {
		return err
	}
	if err := protostream.WriteFromStreamingBytesClient(apiGetBlockClient, writer); err != nil {
		return err
	}
	return nil
}

func InspectBlock(apiClient pfs.APIClient, hash string) (*pfs.BlockInfo, error) {
	blockInfo, err := apiClient.InspectBlock(
		context.Background(),
		&pfs.InspectBlockRequest{
			Block: &pfs.Block{
				Hash: hash,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return blockInfo, nil
}

func ListBlock(apiClient pfs.APIClient, shard uint64, modulus uint64) ([]*pfs.BlockInfo, error) {
	blockInfos, err := apiClient.ListBlock(
		context.Background(),
		&pfs.ListBlockRequest{
			Shard: &pfs.Shard{
				Number: shard,
				Modulo: modulus,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return blockInfos.BlockInfo, nil
}

func PutFile(apiClient pfs.APIClient, repoName string, commitID string, path string, offset int64, reader io.Reader) (_ int, retErr error) {
	putFileClient, err := apiClient.PutFile(context.Background())
	if err != nil {
		return 0, err
	}
	defer func() {
		if _, err := putFileClient.CloseAndRecv(); err != nil && retErr != nil {
			retErr = err
		}
	}()
	request := pfs.PutFileRequest{
		File: &pfs.File{
			Commit: &pfs.Commit{
				Repo: &pfs.Repo{
					Name: repoName,
				},
				Id: commitID,
			},
			Path: path,
		},
		FileType:    pfs.FileType_FILE_TYPE_REGULAR,
		OffsetBytes: offset,
	}
	var size int
	for {
		value := make([]byte, chunkSize)
		iSize, err := reader.Read(value)
		if err != nil {
			if err == io.EOF {
				break
			}
			return 0, err
		}
		request.Value = value[0:iSize]
		size += iSize
		if err := putFileClient.Send(&request); err != nil {
			return 0, err
		}
	}
	if err != nil && err != io.EOF {
		return 0, err
	}
	return size, err
}

func GetFile(apiClient pfs.APIClient, repoName string, commitID string, path string, offset int64, size int64, writer io.Writer) error {
	apiGetFileClient, err := apiClient.GetFile(
		context.Background(),
		&pfs.GetFileRequest{
			File: &pfs.File{
				Commit: &pfs.Commit{
					Repo: &pfs.Repo{
						Name: repoName,
					},
					Id: commitID,
				},
				Path: path,
			},
			OffsetBytes: offset,
			SizeBytes:   size,
		},
	)
	if err != nil {
		return err
	}
	if err := protostream.WriteFromStreamingBytesClient(apiGetFileClient, writer); err != nil {
		return err
	}
	return nil
}

func InspectFile(apiClient pfs.APIClient, repoName string, commitID string, path string) (*pfs.FileInfo, error) {
	fileInfo, err := apiClient.InspectFile(
		context.Background(),
		&pfs.InspectFileRequest{
			File: &pfs.File{
				Commit: &pfs.Commit{
					Repo: &pfs.Repo{
						Name: repoName,
					},
					Id: commitID,
				},
				Path: path,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return fileInfo, nil
}

func ListFile(apiClient pfs.APIClient, repoName string, commitID string, path string, shard uint64, modulus uint64) ([]*pfs.FileInfo, error) {
	fileInfos, err := apiClient.ListFile(
		context.Background(),
		&pfs.ListFileRequest{
			File: &pfs.File{
				Commit: &pfs.Commit{
					Repo: &pfs.Repo{
						Name: repoName,
					},
					Id: commitID,
				},
				Path: path,
			},
			Shard: &pfs.Shard{
				Number: shard,
				Modulo: modulus,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return fileInfos.FileInfo, nil
}

func ListChange(apiClient pfs.APIClient, repoName string, commitID string, path string, shard uint64, modulus uint64) ([]*pfs.Change, error) {
	changes, err := apiClient.ListChange(
		context.Background(),
		&pfs.ListChangeRequest{
			File: &pfs.File{
				Commit: &pfs.Commit{
					Repo: &pfs.Repo{
						Name: repoName,
					},
					Id: commitID,
				},
				Path: path,
			},
			Shard: &pfs.Shard{
				Number: shard,
				Modulo: modulus,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	return changes.Change, nil
}

func DeleteFile(apiClient pfs.APIClient, repoName string, commitID string, path string) error {
	_, err := apiClient.DeleteFile(
		context.Background(),
		&pfs.DeleteFileRequest{
			File: &pfs.File{
				Commit: &pfs.Commit{
					Repo: &pfs.Repo{
						Name: repoName,
					},
					Id: commitID,
				},
				Path: path,
			},
		},
	)
	return err
}

func MakeDirectory(apiClient pfs.APIClient, repoName string, commitID string, path string) (retErr error) {
	putFileClient, err := apiClient.PutFile(context.Background())
	if err != nil {
		return err
	}
	defer func() {
		if _, err := putFileClient.CloseAndRecv(); err != nil && retErr != nil {
			retErr = err
		}
	}()
	return putFileClient.Send(
		&pfs.PutFileRequest{
			File: &pfs.File{
				Commit: &pfs.Commit{
					Repo: &pfs.Repo{
						Name: repoName,
					},
					Id: commitID,
				},
				Path: path,
			},
			FileType: pfs.FileType_FILE_TYPE_DIR,
		},
	)
}

func InspectServer(clusterAPIClient pfs.ClusterAPIClient, serverID string) (*pfs.ServerInfo, error) {
	return clusterAPIClient.InspectServer(
		context.Background(),
		&pfs.InspectServerRequest{
			Server: &pfs.Server{
				Id: serverID,
			},
		},
	)
}

func ListServer(clusterAPIClient pfs.ClusterAPIClient) ([]*pfs.ServerInfo, error) {
	serverInfos, err := clusterAPIClient.ListServer(
		context.Background(),
		&pfs.ListServerRequest{},
	)
	if err != nil {
		return nil, err
	}
	return serverInfos.ServerInfo, nil
}

func PullDiff(replicaAPIClient pfs.ReplicaAPIClient, repoName string, commitID string, shard uint64, writer io.Writer) error {
	apiPullDiffClient, err := replicaAPIClient.PullDiff(
		context.Background(),
		&pfs.PullDiffRequest{
			Commit: &pfs.Commit{
				Repo: &pfs.Repo{
					Name: repoName,
				},
				Id: commitID,
			},
			Shard: shard,
		},
	)
	if err != nil {
		return err
	}
	if err := protostream.WriteFromStreamingBytesClient(apiPullDiffClient, writer); err != nil {
		return err
	}
	return nil
}

func PushDiff(replicaAPIClient pfs.ReplicaAPIClient, repoName string, commitID string, shard uint64, reader io.Reader) (retErr error) {
	pushDiffClient, err := replicaAPIClient.PushDiff(context.Background())
	if err != nil {
		return err
	}
	defer func() {
		if _, err := pushDiffClient.CloseAndRecv(); err != nil && retErr != nil {
			retErr = err
		}
	}()
	request := pfs.PushDiffRequest{
		Commit: &pfs.Commit{
			Repo: &pfs.Repo{
				Name: repoName,
			},
			Id: commitID,
		},
		Shard: shard,
	}
	for {
		value := make([]byte, chunkSize)
		size, err := reader.Read(value)
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		request.Value = value[0:size]
		if err = pushDiffClient.Send(&request); err != nil {
			return err
		}
	}
	return nil
}


text:
require "drip/resource"

module Drip
  class Campaign < Resource
    def self.resource_name
      "campaign"
    end
  end
end


text:
define(['marionette'], function(Marionette) {

  function goTo(route) {
    var that = this,
      args = arguments;
    $(window).scrollTop() !== 0 && window.scrollTo(0, 0),
    require(["controllers/" + route], function(fn) {
      fn.apply(that, args);
    });
  }

  var Controller = Marionette.Object.extend({
    initialize: function(options) {
      this.app = options.app;
    },
    home: function() {
      goTo.call(this, "home");
    }
  });
  return Controller;
});


text:
package pkg

import (
	"sync"
)

//SenderCollection is a collection of Senders
type SenderCollection struct {
	procs  []*Sender
	config *Config

	m sync.Mutex
}

//NewSenderCollection create SenderCollection of Senders
func NewSenderCollection(config *Config) *SenderCollection {
	subProcesses := new(SenderCollection)

	processes := []*Sender{}
	for _, f := range config.Filters {
		sp, err := NewSender(f, config)
		checkOrFail(err)
		processes = append(processes, sp)
	}

	subProcesses.procs = processes
	subProcesses.config = config
	subProcesses.resetData()
	return subProcesses
}

func (s *SenderCollection) resetData() {
	for _, proc := range s.procs {
		proc.resetData()
	}
}

//appendData appends RowEntry to every filter instance from config
func (s *SenderCollection) appendData(row *RowEntry) {
	s.m.Lock()
	var wg sync.WaitGroup
	wg.Add(len(s.procs))
	for _, proc := range s.procs {
		go func(proc *Sender) {
			defer wg.Done()
			proc.appendIfOk(row)
		}(proc)
	}
	wg.Wait()
	s.m.Unlock()
}

func (s *SenderCollection) sendStats() {
	s.m.Lock()
	var wg sync.WaitGroup
	wg.Add(len(s.procs))

	for _, proc := range s.procs {
		go func(proc *Sender) {
			defer wg.Done()
			proc.sendStats()
		}(proc)
	}
	wg.Wait()

	s.resetData()
	s.m.Unlock()
}


text:
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {HomeComponent} from './home.component';
import {AppRoutingModule} from '../routing/app-routing.module';
import {Router} from '@angular/router';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let router: Router;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent],
      imports: [AppRoutingModule, NoopAnimationsModule],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.autoDetectChanges(true);
    router = TestBed.get(Router);
    fixture.ngZone.run(() => router.initialNavigation());
  });

  it('should create the component', () => {
    expect(component).toBeTruthy();
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="menu_flash" type="id" />
    <item name="menu_ring" type="id" />
    <item name="menu_auto_focus" type="id" />
    <item name="menu_camera_selector" type="id" />
    <item name="menu_about" type="id" />
    <item name="menu_problem_scanning" type="id" />
    <item name="analysis_tag_config" type="id" />
</resources>


text:
from supriya import AddAction
from supriya.commands.Request import Request
from supriya.enums import RequestId
from supriya.realtime.Node import Node
from supriya.realtime.Synth import Synth

class SynthNewRequest(Request):
    """
    A /s_new request.

    ::

        >>> import supriya.commands
        >>> import supriya.realtime
        >>> request = supriya.commands.SynthNewRequest(
        ...     add_action=supriya.AddAction.ADD_TO_TAIL,
        ...     node_id=1001,
        ...     synthdef='test',
        ...     target_node_id=1000,
        ...     frequency=443,
        ...     phase=0.2
        ...     )
        >>> request
        SynthNewRequest(
            add_action=AddAction.ADD_TO_TAIL,
            frequency=443,
            node_id=1001,
            phase=0.2,
            synthdef='test',
            target_node_id=1000,
            )

    ::

        >>> message = request.to_osc()
        >>> message
        OscMessage(9, 'test', 1001, 1, 1000, 'frequency', 443, 'phase', 0.2)

    ::

        >>> message.address == supriya.RequestId.SYNTH_NEW
        True

    """

    ### CLASS VARIABLES ###

    __slots__ = ("_add_action", "_node_id", "_synthdef", "_target_node_id", "_kwargs")

    request_id = RequestId.SYNTH_NEW

    ### INITIALIZER ###

    def __init__(
        self,
        add_action=None,
        node_id=None,
        synthdef=None,
        target_node_id=None,
        **kwargs,
    ):
        import supriya.realtime
        import supriya.synthdefs

        Request.__init__(self)
        self._add_action = AddAction.from_expr(add_action)
        self._node_id = node_id
        prototype = (str, supriya.synthdefs.SynthDef)
        assert isinstance(synthdef, prototype)
        self._synthdef = synthdef
        self._target_node_id = target_node_id
        self._kwargs = tuple(sorted(kwargs.items()))

    ### PRIVATE METHODS ###

    def _apply_local(self, server):
        if isinstance(self.node_id, Synth):
            node_id = None
            synth = self.node_id
        else:
            node_id = self.node_id
            synth = Synth(synthdef=self.synthdef, **dict(self.kwargs))
        if isinstance(self.target_node_id, Node):
            target_node = self.target_node_id
        else:
            target_node = server._nodes[self.target_node_id]
        synth._register_with_local_server(
            node_id=node_id,
            node_id_is_permanent=synth.node_id_is_permanent,
            server=server,
        )
        target_node._move_node(add_action=self.add_action, node=synth)

    ### PUBLIC METHODS ###

    def to_osc(self, *, with_placeholders=False, with_request_name=False):
        import supriya.synthdefs

        if with_request_name:
            request_id = self.request_name
        else:
            request_id = int(self.request_id)
        synthdef = self.synthdef
        if isinstance(synthdef, supriya.synthdefs.SynthDef):
            synthdef = synthdef.actual_name
        node_id = self._sanitize_node_id(self.node_id, with_placeholders)
        add_action = int(self.add_action)
        target_node_id = self._sanitize_node_id(self.target_node_id, with_placeholders)
        if not isinstance(target_node_id, int) and with_placeholders:
            target_node_id = -1
        contents = [request_id, synthdef, node_id, add_action, target_node_id]
        for key, value in self._kwargs:
            contents.append(key)
            contents.append(value)
        message = supriya.osc.OscMessage(*contents)
        return message

    ### PUBLIC PROPERTIES ###

    @property
    def add_action(self):
        return self._add_action

    @property
    def kwargs(self):
        return self._kwargs

    @property
    def node_id(self):
        return self._node_id

    @property
    def response_patterns(self):
        return ["/n_go", int(self.node_id)], None

    @property
    def synthdef(self):
        return self._synthdef

    @property
    def target_node_id(self):
        return self._target_node_id


text:
/* 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.
 */

package org.activiti.explorer.ui.content.email;

import org.activiti.engine.task.Attachment;
import org.activiti.explorer.I18nManager;
import org.activiti.explorer.Messages;
import org.activiti.explorer.ui.Images;
import org.activiti.explorer.ui.content.GenericAttachmentRenderer;

import com.vaadin.terminal.Resource;
import com.vaadin.ui.Component;

/**
 * @author Frederik Heremans
 */
public class EmailAttachmentRenderer extends GenericAttachmentRenderer {

  public static final String EMAIL_TYPE = "email";

  public boolean canRenderAttachment(String type) {
    return EMAIL_TYPE.equals(type);
  }

  public String getName(I18nManager i18nManager) {
    return i18nManager.getMessage(Messages.RELATED_CONTENT_TYPE_EMAIL);
  }

  public Resource getImage(Attachment attachment) {
    return Images.IMAP;
  }

  public Component getDetailComponent(Attachment attachment) {
    return new EmailDetailPanel(attachment);
  }

}


text:
layout: post
title:  "Binary Tree 3 - Construct Binary Tree"
date:   2016-03-25 14:30:00
tags: [algorithm, leetcode, binary tree, Construct Binary Tree]
categories: Algorithm
---

### 1. [Construct Binary Tree from Preorder and Inorder Traversal - Hard Leetcode 105](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
Given preorder and inorder traversal of a tree, construct the binary tree.
{% highlight C++ %}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
  if(preorder.size() == 0 || inorder.size() == 0)
      return NULL;
  return buildTreeCore(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1);
}
// 定义下面的接口:不需要copy两个vector, 直接用上边的每次赋值新的vector到参数里
TreeNode *buildTreeCore(vector<int> &preorder, vector<int> &inorder,
                        int preBeg, int preEnd, int inBeg, int inEnd) {
  if(preBeg > preEnd || inBeg > inEnd)
    return NULL;    // 终止条件
  int rootval = preorder[preBeg];
  TreeNode *root = new TreeNode(rootval);    //建立root节点
  int i, len=0;  // 注意,这里是根据len截取inorder和preorder!!!
  // 在in中找root,另,注意len的求法!不等于i
  for(i=inBeg; inorder[i] != rootval && i <= inEnd; i++)
    len++;
  if(i > inEnd) return NULL;    //输入错误,无法建立树
  // 把这些index搞对
  root->left = buildTreeCore(preorder, inorder, preBeg+1, preBeg+len, inBeg, inBeg+len-1);
  root->right = buildTreeCore(preorder, inorder, preBeg+len+1, preEnd, inBeg+len+1, inEnd);
  return root;
}
{% endhighlight %}

### 2. [Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)
{% highlight C++ %}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
  if(postorder.size() == 0 || inorder.size() == 0)
    return NULL;
  return buildTreeCore(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
}
TreeNode *buildTreeCore(vector<int> &inorder, vector<int> &postorder,
                        int inBeg, int inEnd, int postBeg, int postEnd) {
  if(postBeg > postEnd || inBeg > inEnd)
    return NULL;    //终止条件
  int rootval = postorder[postEnd];   //主要就这3行不同
  TreeNode *root = new TreeNode(rootval);    //建立root节点
  int i, len=0;
  for(i=inBeg; inorder[i] != rootval && i <= inEnd; i++) //在in中找root,另,注意len的求法!不等于i
    len++;
  if(i > inEnd) return NULL;    //输入错误,无法建立树

  root->left = buildTreeCore(inorder, postorder, inBeg, inBeg+len-1, postBeg, postBeg+len-1); //把这些搞对!
  root->right = buildTreeCore(inorder, postorder, inBeg+len+1, inEnd, postBeg+len, postEnd-1);
  return root;
}
{% endhighlight %}

### 3. [Binary Tree Serialization](http://www.lintcode.com/en/problem/binary-tree-serialization/)
```
Assume we have a binary tree below:
    _30_
    /   \
  10    20
  /    /  \
 50   45  35
Using pre-order traversal, the algorithm should write the following to a file:
30 10 50 # # # 20 45 # # 35 # #
```
{% highlight C++ %}
void writeBinaryTree(BinaryTree *p, ostream &out) {
  if (!p) {
    out << "# ";
  } else {
    out << p->data << " ";
    writeBinaryTree(p->left, out);
    writeBinaryTree(p->right, out);
  }
}
// lintcode,返回string
string serialize(TreeNode *root) {
  if(root == NULL)
    return "#";
  string res(to_string(root->val));
  res += ",";
  res += serialize(root->left);
  res += serialize(root->right);
  return res;
}
{% endhighlight %}
Deserializing a Binary Tree:
We read tokens one at a time using pre-order traversal.
If the token is a sentinel, we ignore it.
If the token is a number, we insert it to the current node, and traverse to its left child, then its right child.
{% highlight C++ %}
void readBinaryTree(BinaryTree *&p, ifstream &fin) {
  int token;
  bool isNumber;
  if (!readNextToken(token, fin, isNumber))
    return;
  if (isNumber) {
    p = new BinaryTree(token);
    readBinaryTree(p->left, fin);
    readBinaryTree(p->right, fin);
  }
}
// lintcode,输入string
TreeNode *deserialize(string &data) {
  if(data.empty() || data[0] == '#') {
    data = data.substr(1, data.size() - 1); // 不能忘记步进更新string!
    return NULL;
  }
  int k = data.find(",");
  string val = data.substr(0, k);
  TreeNode *node = new TreeNode(stoi(val));
  data = data.substr(k+1, data.size() - k - 1);
  node->left = deserialize(data);  // data必须是引用&,因为要返回这一步的处理结果
  node->right = deserialize(data);
  return node;
}
{% endhighlight %}

### 4. 已知前序遍历,后续遍历,求能够构造多少种二叉树 - Hard
[Solution](http://xinpeng.me/?p=767)

采用递归的思路,前序序列的第一个节点和后续遍历的最后一个节点必然为相同的根节点,否则出错

然后枚举左子树的各种长度,看能否构造出相应的右子树

![preorderpostorder](/res/preorderpostorder.png)
{% highlight C++ %}
int count(vector<int>& preorder, int s1, vector<int>& postorder, int s2, int len) {
    if (len == 0) {
        return 1;
    }
    if(preorder[s1] != postorder[s2+len-1]) {
        return 0;
    }
    int res = 0;
    for (int i = 0; i < len; i++) { // 左子树的各种长度
        int left = count(preorder, s1 + 1, postorder, s2, i);
        int right = count(preorder, s1 + i + 1, postorder, s2 + i, len - i - 1);
        res += left * right;
    }
    return res;
}
int countValidTrees(vector<int>& preorder, vector<int>& postorder) {
    if(preorder.size() != postorder.size())
        return 0;
    return count(preorder, 0, postorder, 0, preorder.size());
}
{% endhighlight %}


text:
// @formatter:off

package com.spike.giantdataanalysis.benchmark.tools.jmh.samples;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class JMHSample_17_SyncIterations {

    /*
     * This is the another thing that is enabled in JMH by default.
     *
     * Suppose we have this simple benchmark.
     */

    private double src;

    @Benchmark
    public double test() {
        double s = src;
        for (int i = 0; i < 1000; i++) {
            s = Math.sin(s);
        }
        return s;
    }

    /*
     * It turns out if you run the benchmark with multiple threads,
     * the way you start and stop the worker threads seriously affects
     * performance.
     *
     * The natural way would be to park all the threads on some sort
     * of barrier, and the let them go "at once". However, that does
     * not work: there are no guarantees the worker threads will start
     * at the same time, meaning other worker threads are working
     * in better conditions, skewing the result.
     *
     * The better solution would be to introduce bogus iterations,
     * ramp up the threads executing the iterations, and then atomically
     * shift the system to measuring stuff. The same thing can be done
     * during the rampdown. This sounds complicated, but JMH already
     * handles that for you.
     *
     * MARK 'bogus iterations' 同时运行迭代
     */

    /*
     * ============================== HOW TO RUN THIS TEST: ====================================
     *
     * You will need to oversubscribe the system to make this effect
     * clearly visible; however, this effect can also be shown on the
     * unsaturated systems.*
     *
     * Note the performance of -si false version is more flaky, even
     * though it is "better". This is the false improvement, granted by
     * some of the threads executing in solo. The -si true version more stable
     * and coherent.
     *
     * -si true is enabled by default.
     *
     * Say, $CPU is the number of CPUs on your machine.
     *
     * You can run this test with:
     *
     * a) Via the command line:
     *    $ mvn clean install
     *    $ java -jar target/benchmarks.jar JMHSample_17 \
     *        -w 1s -r 1s -f 1 -t ${CPU*16} -si {true|false}
     *    (we requested shorter warmup/measurement iterations, single fork,
     *     lots of threads, and changeable "synchronize iterations" option)
     *
     * b) Via the Java API:
     *    (see the JMH homepage for possible caveats when running from IDE:
     *      http://openjdk.java.net/projects/code-tools/jmh/)
     */

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(JMHSample_17_SyncIterations.class.getSimpleName())
                .warmupTime(TimeValue.seconds(1))
                .measurementTime(TimeValue.seconds(1))
                .threads(Runtime.getRuntime().availableProcessors()*16)
                .forks(1)
                .syncIterations(true) // try to switch to "false" // MARK true: 同时运行迭代
                .build();

        new Runner(opt).run();
    }

}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/wearables/goggles/shared_rebreather.iff"
	result.attribute_template_id = 11
	result.stfName("wearables_name","rebreather")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
#include <inviwo/qt/widgets/inviwoqtutils.h>
#include <inviwo/core/util/logcentral.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QLocale>
#include <warn/pop>
#include <ios>
#include <exception>

namespace inviwo {

namespace utilqt {

std::locale getCurrentStdLocale() {
    std::locale loc;
    try {
        // use the system locale provided by Qt

#ifdef WIN32
        // need to change locale given by Qt from underscore to hyphenated ("sv_SE" to "sv-SE")
        // although std::locale should only accept locales with underscore, e.g. "sv_SE"
        std::string localeName(QLocale::system().name().replace('_', '-').toStdString());
#else
        std::string localeName(QLocale::system().name().toStdString());
#endif
        loc = std::locale(localeName.c_str());
    }
    catch (std::exception &e) {
        LogWarnCustom("getStdLocale", "Locale could not be set. " << e.what());
    }
    return loc;
}

std::ios_base& localizeStream(std::ios_base& stream) {
    stream.imbue(getCurrentStdLocale());
    return stream;
}

QString toLocalQString(const std::string& input) {
   return QString::fromLocal8Bit(input.c_str());
}

IVW_QTWIDGETS_API QString toQString(const std::string& input) {
   return QString::fromUtf8(input.c_str());
}

IVW_QTWIDGETS_API QPointF toQPoint(dvec2 v) {
    return QPointF(v.x, v.y);
}

IVW_QTWIDGETS_API QPoint toQPoint(ivec2 v) {
    return QPoint(v.x, v.y);
}

IVW_QTWIDGETS_API dvec2 toGLM(QPointF v) {
    return dvec2(v.x(), v.y());
}

IVW_QTWIDGETS_API ivec2 toGLM(QPoint v) {
    return ivec2(v.x(), v.y());
}

IVW_QTWIDGETS_API dvec2 toGLM(QSizeF v) {
    return dvec2(v.width(), v.height());
}

IVW_QTWIDGETS_API ivec2 toGLM(QSize v) {
    return ivec2(v.width(), v.height());
}

IVW_QTWIDGETS_API QSizeF toQSize(dvec2 v) {
    return QSizeF(v.x, v.y);
}

IVW_QTWIDGETS_API QSize toQSize(ivec2 v) {
    return QSize(v.x, v.y);
}

} // namespace utilqt

}  // namespace


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#ifndef status_models_TYPES_H
#define status_models_TYPES_H

#include <iosfwd>

#include <thrift/Thrift.h>
#include <thrift/TApplicationException.h>
#include <thrift/protocol/TProtocol.h>
#include <thrift/transport/TTransport.h>

#include <thrift/cxxfunctional.h>

namespace apache { namespace airavata { namespace model { namespace status {

struct ExperimentState {
  enum type {
    CREATED = 0,
    VALIDATED = 1,
    SCHEDULED = 2,
    LAUNCHED = 3,
    EXECUTING = 4,
    CANCELING = 5,
    CANCELED = 6,
    COMPLETED = 7,
    FAILED = 8
  };
};

extern const std::map<int, const char*> _ExperimentState_VALUES_TO_NAMES;

struct TaskState {
  enum type {
    CREATED = 0,
    EXECUTING = 1,
    COMPLETED = 2,
    FAILED = 3,
    CANCELED = 4
  };
};

extern const std::map<int, const char*> _TaskState_VALUES_TO_NAMES;

struct ProcessState {
  enum type {
    CREATED = 0,
    VALIDATED = 1,
    PRE_PROCESSING = 2,
    CONFIGURING_WORKSPACE = 3,
    INPUT_DATA_STAGING = 4,
    EXECUTING = 5,
    MONITORING = 6,
    OUTPUT_DATA_STAGING = 7,
    POST_PROCESSING = 8,
    COMPLETED = 9,
    FAILED = 10,
    CANCELLING = 11,
    CANCELED = 12
  };
};

extern const std::map<int, const char*> _ProcessState_VALUES_TO_NAMES;

struct JobState {
  enum type {
    SUBMITTED = 0,
    QUEUED = 1,
    ACTIVE = 2,
    COMPLETE = 3,
    CANCELED = 4,
    FAILED = 5,
    SUSPENDED = 6,
    UNKNOWN = 7
  };
};

extern const std::map<int, const char*> _JobState_VALUES_TO_NAMES;

class ExperimentStatus;

class ProcessStatus;

class TaskStatus;

class JobStatus;

typedef struct _ExperimentStatus__isset {
  _ExperimentStatus__isset() : timeOfStateChange(false), reason(false) {}
  bool timeOfStateChange :1;
  bool reason :1;
} _ExperimentStatus__isset;

class ExperimentStatus {
 public:

  static const char* ascii_fingerprint; // = "CDBB2A55999EF5954D567AC5CF6F0786";
  static const uint8_t binary_fingerprint[16]; // = {0xCD,0xBB,0x2A,0x55,0x99,0x9E,0xF5,0x95,0x4D,0x56,0x7A,0xC5,0xCF,0x6F,0x07,0x86};

  ExperimentStatus(const ExperimentStatus&);
  ExperimentStatus& operator=(const ExperimentStatus&);
  ExperimentStatus() : state((ExperimentState::type)0), timeOfStateChange(0), reason() {
  }

  virtual ~ExperimentStatus() throw();
  ExperimentState::type state;
  int64_t timeOfStateChange;
  std::string reason;

  _ExperimentStatus__isset __isset;

  void __set_state(const ExperimentState::type val);

  void __set_timeOfStateChange(const int64_t val);

  void __set_reason(const std::string& val);

  bool operator == (const ExperimentStatus & rhs) const
  {
    if (!(state == rhs.state))
      return false;
    if (__isset.timeOfStateChange != rhs.__isset.timeOfStateChange)
      return false;
    else if (__isset.timeOfStateChange && !(timeOfStateChange == rhs.timeOfStateChange))
      return false;
    if (__isset.reason != rhs.__isset.reason)
      return false;
    else if (__isset.reason && !(reason == rhs.reason))
      return false;
    return true;
  }
  bool operator != (const ExperimentStatus &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const ExperimentStatus & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  friend std::ostream& operator<<(std::ostream& out, const ExperimentStatus& obj);
};

void swap(ExperimentStatus &a, ExperimentStatus &b);

typedef struct _ProcessStatus__isset {
  _ProcessStatus__isset() : timeOfStateChange(false), reason(false) {}
  bool timeOfStateChange :1;
  bool reason :1;
} _ProcessStatus__isset;

class ProcessStatus {
 public:

  static const char* ascii_fingerprint; // = "CDBB2A55999EF5954D567AC5CF6F0786";
  static const uint8_t binary_fingerprint[16]; // = {0xCD,0xBB,0x2A,0x55,0x99,0x9E,0xF5,0x95,0x4D,0x56,0x7A,0xC5,0xCF,0x6F,0x07,0x86};

  ProcessStatus(const ProcessStatus&);
  ProcessStatus& operator=(const ProcessStatus&);
  ProcessStatus() : state((ProcessState::type)0), timeOfStateChange(0), reason() {
  }

  virtual ~ProcessStatus() throw();
  ProcessState::type state;
  int64_t timeOfStateChange;
  std::string reason;

  _ProcessStatus__isset __isset;

  void __set_state(const ProcessState::type val);

  void __set_timeOfStateChange(const int64_t val);

  void __set_reason(const std::string& val);

  bool operator == (const ProcessStatus & rhs) const
  {
    if (!(state == rhs.state))
      return false;
    if (__isset.timeOfStateChange != rhs.__isset.timeOfStateChange)
      return false;
    else if (__isset.timeOfStateChange && !(timeOfStateChange == rhs.timeOfStateChange))
      return false;
    if (__isset.reason != rhs.__isset.reason)
      return false;
    else if (__isset.reason && !(reason == rhs.reason))
      return false;
    return true;
  }
  bool operator != (const ProcessStatus &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const ProcessStatus & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  friend std::ostream& operator<<(std::ostream& out, const ProcessStatus& obj);
};

void swap(ProcessStatus &a, ProcessStatus &b);

typedef struct _TaskStatus__isset {
  _TaskStatus__isset() : timeOfStateChange(false), reason(false) {}
  bool timeOfStateChange :1;
  bool reason :1;
} _TaskStatus__isset;

class TaskStatus {
 public:

  static const char* ascii_fingerprint; // = "CDBB2A55999EF5954D567AC5CF6F0786";
  static const uint8_t binary_fingerprint[16]; // = {0xCD,0xBB,0x2A,0x55,0x99,0x9E,0xF5,0x95,0x4D,0x56,0x7A,0xC5,0xCF,0x6F,0x07,0x86};

  TaskStatus(const TaskStatus&);
  TaskStatus& operator=(const TaskStatus&);
  TaskStatus() : state((TaskState::type)0), timeOfStateChange(0), reason() {
  }

  virtual ~TaskStatus() throw();
  TaskState::type state;
  int64_t timeOfStateChange;
  std::string reason;

  _TaskStatus__isset __isset;

  void __set_state(const TaskState::type val);

  void __set_timeOfStateChange(const int64_t val);

  void __set_reason(const std::string& val);

  bool operator == (const TaskStatus & rhs) const
  {
    if (!(state == rhs.state))
      return false;
    if (__isset.timeOfStateChange != rhs.__isset.timeOfStateChange)
      return false;
    else if (__isset.timeOfStateChange && !(timeOfStateChange == rhs.timeOfStateChange))
      return false;
    if (__isset.reason != rhs.__isset.reason)
      return false;
    else if (__isset.reason && !(reason == rhs.reason))
      return false;
    return true;
  }
  bool operator != (const TaskStatus &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const TaskStatus & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  friend std::ostream& operator<<(std::ostream& out, const TaskStatus& obj);
};

void swap(TaskStatus &a, TaskStatus &b);

typedef struct _JobStatus__isset {
  _JobStatus__isset() : timeOfStateChange(false), reason(false) {}
  bool timeOfStateChange :1;
  bool reason :1;
} _JobStatus__isset;

class JobStatus {
 public:

  static const char* ascii_fingerprint; // = "CDBB2A55999EF5954D567AC5CF6F0786";
  static const uint8_t binary_fingerprint[16]; // = {0xCD,0xBB,0x2A,0x55,0x99,0x9E,0xF5,0x95,0x4D,0x56,0x7A,0xC5,0xCF,0x6F,0x07,0x86};

  JobStatus(const JobStatus&);
  JobStatus& operator=(const JobStatus&);
  JobStatus() : jobState((JobState::type)0), timeOfStateChange(0), reason() {
  }

  virtual ~JobStatus() throw();
  JobState::type jobState;
  int64_t timeOfStateChange;
  std::string reason;

  _JobStatus__isset __isset;

  void __set_jobState(const JobState::type val);

  void __set_timeOfStateChange(const int64_t val);

  void __set_reason(const std::string& val);

  bool operator == (const JobStatus & rhs) const
  {
    if (!(jobState == rhs.jobState))
      return false;
    if (__isset.timeOfStateChange != rhs.__isset.timeOfStateChange)
      return false;
    else if (__isset.timeOfStateChange && !(timeOfStateChange == rhs.timeOfStateChange))
      return false;
    if (__isset.reason != rhs.__isset.reason)
      return false;
    else if (__isset.reason && !(reason == rhs.reason))
      return false;
    return true;
  }
  bool operator != (const JobStatus &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const JobStatus & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  friend std::ostream& operator<<(std::ostream& out, const JobStatus& obj);
};

void swap(JobStatus &a, JobStatus &b);

}}}} // namespace

#endif


text:
use option::{Option, None, Some};
use ops::Drop;

/// A native mutex suitable for storing in statics (that is, it has
/// the `destroy` method rather than a destructor).
///
/// Prefer the `NativeMutex` type where possible, since that does not
/// require manual deallocation.
pub struct StaticNativeMutex {
    inner: imp::Mutex,
}

/// A native mutex with a destructor for clean-up.
///
/// See `StaticNativeMutex` for a version that is suitable for storing in
/// statics.
pub struct NativeMutex {
    inner: StaticNativeMutex
}

/// Automatically unlocks the mutex that it was created from on
/// destruction.
///
/// Using this makes lock-based code resilient to unwinding/task
/// failure, because the lock will be automatically unlocked even
/// then.
#[must_use]
pub struct LockGuard<'a> {
    lock: &'a StaticNativeMutex
}

pub static NATIVE_MUTEX_INIT: StaticNativeMutex = StaticNativeMutex {
    inner: imp::MUTEX_INIT,
};

impl StaticNativeMutex {
    /// Creates a new mutex.
    ///
    /// Note that a mutex created in this way needs to be explicit
    /// freed with a call to `destroy` or it will leak.
    /// Also it is important to avoid locking until mutex has stopped moving
    pub unsafe fn new() -> StaticNativeMutex {
        StaticNativeMutex { inner: imp::Mutex::new() }
    }

    /// Acquires this lock. This assumes that the current thread does not
    /// already hold the lock.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
    /// static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
    /// unsafe {
    ///     let _guard = LOCK.lock();
    ///     // critical section...
    /// } // automatically unlocked in `_guard`'s destructor
    /// ```
    pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
        self.inner.lock();

        LockGuard { lock: self }
    }

    /// Attempts to acquire the lock. The value returned is `Some` if
    /// the attempt succeeded.
    pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
        if self.inner.trylock() {
            Some(LockGuard { lock: self })
        } else {
            None
        }
    }

    /// Acquire the lock without creating a `LockGuard`.
    ///
    /// These needs to be paired with a call to `.unlock_noguard`. Prefer using
    /// `.lock`.
    pub unsafe fn lock_noguard(&self) { self.inner.lock() }

    /// Attempts to acquire the lock without creating a
    /// `LockGuard`. The value returned is whether the lock was
    /// acquired or not.
    ///
    /// If `true` is returned, this needs to be paired with a call to
    /// `.unlock_noguard`. Prefer using `.trylock`.
    pub unsafe fn trylock_noguard(&self) -> bool {
        self.inner.trylock()
    }

    /// Unlocks the lock. This assumes that the current thread already holds the
    /// lock.
    pub unsafe fn unlock_noguard(&self) { self.inner.unlock() }

    /// Block on the internal condition variable.
    ///
    /// This function assumes that the lock is already held. Prefer
    /// using `LockGuard.wait` since that guarantees that the lock is
    /// held.
    pub unsafe fn wait_noguard(&self) { self.inner.wait() }

    /// Signals a thread in `wait` to wake up
    pub unsafe fn signal_noguard(&self) { self.inner.signal() }

    /// This function is especially unsafe because there are no guarantees made
    /// that no other thread is currently holding the lock or waiting on the
    /// condition variable contained inside.
    pub unsafe fn destroy(&self) { self.inner.destroy() }
}

impl NativeMutex {
    /// Creates a new mutex.
    ///
    /// The user must be careful to ensure the mutex is not locked when its is
    /// being destroyed.
    /// Also it is important to avoid locking until mutex has stopped moving
    pub unsafe fn new() -> NativeMutex {
        NativeMutex { inner: StaticNativeMutex::new() }
    }

    /// Acquires this lock. This assumes that the current thread does not
    /// already hold the lock.
    ///
    /// # Example
    /// ```rust
    /// use std::unstable::mutex::NativeMutex;
    /// unsafe {
    ///     let mut lock = NativeMutex::new();
    ///
    ///     {
    ///         let _guard = lock.lock();
    ///         // critical section...
    ///     } // automatically unlocked in `_guard`'s destructor
    /// }
    /// ```
    pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
        self.inner.lock()
    }

    /// Attempts to acquire the lock. The value returned is `Some` if
    /// the attempt succeeded.
    pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
        self.inner.trylock()
    }

    /// Acquire the lock without creating a `LockGuard`.
    ///
    /// These needs to be paired with a call to `.unlock_noguard`. Prefer using
    /// `.lock`.
    pub unsafe fn lock_noguard(&self) { self.inner.lock_noguard() }

    /// Attempts to acquire the lock without creating a
    /// `LockGuard`. The value returned is whether the lock was
    /// acquired or not.
    ///
    /// If `true` is returned, this needs to be paired with a call to
    /// `.unlock_noguard`. Prefer using `.trylock`.
    pub unsafe fn trylock_noguard(&self) -> bool {
        self.inner.trylock_noguard()
    }

    /// Unlocks the lock. This assumes that the current thread already holds the
    /// lock.
    pub unsafe fn unlock_noguard(&self) { self.inner.unlock_noguard() }

    /// Block on the internal condition variable.
    ///
    /// This function assumes that the lock is already held. Prefer
    /// using `LockGuard.wait` since that guarantees that the lock is
    /// held.
    pub unsafe fn wait_noguard(&self) { self.inner.wait_noguard() }

    /// Signals a thread in `wait` to wake up
    pub unsafe fn signal_noguard(&self) { self.inner.signal_noguard() }
}

impl Drop for NativeMutex {
    fn drop(&mut self) {
        unsafe {self.inner.destroy()}
    }
}

impl<'a> LockGuard<'a> {
    /// Block on the internal condition variable.
    pub unsafe fn wait(&self) {
        self.lock.wait_noguard()
    }

    /// Signals a thread in `wait` to wake up.
    pub unsafe fn signal(&self) {
        self.lock.signal_noguard()
    }
}

#[unsafe_destructor]
impl<'a> Drop for LockGuard<'a> {
    fn drop(&mut self) {
        unsafe {self.lock.unlock_noguard()}
    }
}

#[cfg(unix)]
mod imp {
    use libc;
    use self::os::{PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER,
                   pthread_mutex_t, pthread_cond_t};
    use ty::Unsafe;
    use kinds::marker;

    type pthread_mutexattr_t = libc::c_void;
    type pthread_condattr_t = libc::c_void;

    #[cfg(target_os = "freebsd")]
    mod os {
        use libc;

        pub type pthread_mutex_t = *libc::c_void;
        pub type pthread_cond_t = *libc::c_void;

        pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t =
            0 as pthread_mutex_t;
        pub static PTHREAD_COND_INITIALIZER: pthread_cond_t =
            0 as pthread_cond_t;
    }

    #[cfg(target_os = "macos")]
    mod os {
        use libc;

        #[cfg(target_arch = "x86_64")]
        static __PTHREAD_MUTEX_SIZE__: uint = 56;
        #[cfg(target_arch = "x86_64")]
        static __PTHREAD_COND_SIZE__: uint = 40;
        #[cfg(target_arch = "x86")]
        static __PTHREAD_MUTEX_SIZE__: uint = 40;
        #[cfg(target_arch = "x86")]
        static __PTHREAD_COND_SIZE__: uint = 24;

        static _PTHREAD_MUTEX_SIG_init: libc::c_long = 0x32AAABA7;
        static _PTHREAD_COND_SIG_init: libc::c_long = 0x3CB0B1BB;

        pub struct pthread_mutex_t {
            __sig: libc::c_long,
            __opaque: [u8, ..__PTHREAD_MUTEX_SIZE__],
        }
        pub struct pthread_cond_t {
            __sig: libc::c_long,
            __opaque: [u8, ..__PTHREAD_COND_SIZE__],
        }

        pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
            __sig: _PTHREAD_MUTEX_SIG_init,
            __opaque: [0, ..__PTHREAD_MUTEX_SIZE__],
        };
        pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
            __sig: _PTHREAD_COND_SIG_init,
            __opaque: [0, ..__PTHREAD_COND_SIZE__],
        };
    }

    #[cfg(target_os = "linux")]
    mod os {
        use libc;

        // minus 8 because we have an 'align' field
        #[cfg(target_arch = "x86_64")]
        static __SIZEOF_PTHREAD_MUTEX_T: uint = 40 - 8;
        #[cfg(target_arch = "x86")]
        static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
        #[cfg(target_arch = "arm")]
        static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
        #[cfg(target_arch = "mips")]
        static __SIZEOF_PTHREAD_MUTEX_T: uint = 24 - 8;
        #[cfg(target_arch = "x86_64")]
        static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
        #[cfg(target_arch = "x86")]
        static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
        #[cfg(target_arch = "arm")]
        static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;
        #[cfg(target_arch = "mips")]
        static __SIZEOF_PTHREAD_COND_T: uint = 48 - 8;

        pub struct pthread_mutex_t {
            __align: libc::c_longlong,
            size: [u8, ..__SIZEOF_PTHREAD_MUTEX_T],
        }
        pub struct pthread_cond_t {
            __align: libc::c_longlong,
            size: [u8, ..__SIZEOF_PTHREAD_COND_T],
        }

        pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
            __align: 0,
            size: [0, ..__SIZEOF_PTHREAD_MUTEX_T],
        };
        pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
            __align: 0,
            size: [0, ..__SIZEOF_PTHREAD_COND_T],
        };
    }
    #[cfg(target_os = "android")]
    mod os {
        use libc;

        pub struct pthread_mutex_t { value: libc::c_int }
        pub struct pthread_cond_t { value: libc::c_int }

        pub static PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t {
            value: 0,
        };
        pub static PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t {
            value: 0,
        };
    }

    pub struct Mutex {
        lock: Unsafe<pthread_mutex_t>,
        cond: Unsafe<pthread_cond_t>,
    }

    pub static MUTEX_INIT: Mutex = Mutex {
        lock: Unsafe {
            value: PTHREAD_MUTEX_INITIALIZER,
            marker1: marker::InvariantType,
        },
        cond: Unsafe {
            value: PTHREAD_COND_INITIALIZER,
            marker1: marker::InvariantType,
        },
    };

    impl Mutex {
        pub unsafe fn new() -> Mutex {
            // As mutex might be moved and address is changing it
            // is better to avoid initialization of potentially
            // opaque OS data before it landed
            let m = Mutex {
                lock: Unsafe::new(PTHREAD_MUTEX_INITIALIZER),
                cond: Unsafe::new(PTHREAD_COND_INITIALIZER),
            };

            return m;
        }

        pub unsafe fn lock(&self) { pthread_mutex_lock(self.lock.get()); }
        pub unsafe fn unlock(&self) { pthread_mutex_unlock(self.lock.get()); }
        pub unsafe fn signal(&self) { pthread_cond_signal(self.cond.get()); }
        pub unsafe fn wait(&self) {
            pthread_cond_wait(self.cond.get(), self.lock.get());
        }
        pub unsafe fn trylock(&self) -> bool {
            pthread_mutex_trylock(self.lock.get()) == 0
        }
        pub unsafe fn destroy(&self) {
            pthread_mutex_destroy(self.lock.get());
            pthread_cond_destroy(self.cond.get());
        }
    }

    extern {
        fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> libc::c_int;
        fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> libc::c_int;
        fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> libc::c_int;
        fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> libc::c_int;
        fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> libc::c_int;

        fn pthread_cond_wait(cond: *mut pthread_cond_t,
                             lock: *mut pthread_mutex_t) -> libc::c_int;
        fn pthread_cond_signal(cond: *mut pthread_cond_t) -> libc::c_int;
    }
}

#[cfg(windows)]
mod imp {
    use rt::libc_heap::malloc_raw;
    use libc::{HANDLE, BOOL, LPSECURITY_ATTRIBUTES, c_void, DWORD, LPCSTR};
    use libc;
    use ptr;
    use sync::atomics;

    type LPCRITICAL_SECTION = *mut c_void;
    static SPIN_COUNT: DWORD = 4000;
    #[cfg(target_arch = "x86")]
    static CRIT_SECTION_SIZE: uint = 24;
    #[cfg(target_arch = "x86_64")]
    static CRIT_SECTION_SIZE: uint = 40;

    pub struct Mutex {
        // pointers for the lock/cond handles, atomically updated
        lock: atomics::AtomicUint,
        cond: atomics::AtomicUint,
    }

    pub static MUTEX_INIT: Mutex = Mutex {
        lock: atomics::INIT_ATOMIC_UINT,
        cond: atomics::INIT_ATOMIC_UINT,
    };

    impl Mutex {
        pub unsafe fn new() -> Mutex {
            Mutex {
                lock: atomics::AtomicUint::new(init_lock()),
                cond: atomics::AtomicUint::new(init_cond()),
            }
        }
        pub unsafe fn lock(&self) {
            EnterCriticalSection(self.getlock() as LPCRITICAL_SECTION)
        }
        pub unsafe fn trylock(&self) -> bool {
            TryEnterCriticalSection(self.getlock() as LPCRITICAL_SECTION) != 0
        }
        pub unsafe fn unlock(&self) {
            LeaveCriticalSection(self.getlock() as LPCRITICAL_SECTION)
        }

        pub unsafe fn wait(&self) {
            self.unlock();
            WaitForSingleObject(self.getcond() as HANDLE, libc::INFINITE);
            self.lock();
        }

        pub unsafe fn signal(&self) {
            assert!(SetEvent(self.getcond() as HANDLE) != 0);
        }

        /// This function is especially unsafe because there are no guarantees made
        /// that no other thread is currently holding the lock or waiting on the
        /// condition variable contained inside.
        pub unsafe fn destroy(&self) {
            let lock = self.lock.swap(0, atomics::SeqCst);
            let cond = self.cond.swap(0, atomics::SeqCst);
            if lock != 0 { free_lock(lock) }
            if cond != 0 { free_cond(cond) }
        }

        unsafe fn getlock(&self) -> *mut c_void {
            match self.lock.load(atomics::SeqCst) {
                0 => {}
                n => return n as *mut c_void
            }
            let lock = init_lock();
            match self.lock.compare_and_swap(0, lock, atomics::SeqCst) {
                0 => return lock as *mut c_void,
                _ => {}
            }
            free_lock(lock);
            return self.lock.load(atomics::SeqCst) as *mut c_void;
        }

        unsafe fn getcond(&self) -> *mut c_void {
            match self.cond.load(atomics::SeqCst) {
                0 => {}
                n => return n as *mut c_void
            }
            let cond = init_cond();
            match self.cond.compare_and_swap(0, cond, atomics::SeqCst) {
                0 => return cond as *mut c_void,
                _ => {}
            }
            free_cond(cond);
            return self.cond.load(atomics::SeqCst) as *mut c_void;
        }
    }

    pub unsafe fn init_lock() -> uint {
        let block = malloc_raw(CRIT_SECTION_SIZE as uint) as *mut c_void;
        InitializeCriticalSectionAndSpinCount(block, SPIN_COUNT);
        return block as uint;
    }

    pub unsafe fn init_cond() -> uint {
        return CreateEventA(ptr::mut_null(), libc::FALSE, libc::FALSE,
                            ptr::null()) as uint;
    }

    pub unsafe fn free_lock(h: uint) {
        DeleteCriticalSection(h as LPCRITICAL_SECTION);
        libc::free(h as *mut c_void);
    }

    pub unsafe fn free_cond(h: uint) {
        let block = h as HANDLE;
        libc::CloseHandle(block);
    }

    #[allow(non_snake_case_functions)]
    extern "system" {
        fn CreateEventA(lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
                        bManualReset: BOOL,
                        bInitialState: BOOL,
                        lpName: LPCSTR) -> HANDLE;
        fn InitializeCriticalSectionAndSpinCount(
                        lpCriticalSection: LPCRITICAL_SECTION,
                        dwSpinCount: DWORD) -> BOOL;
        fn DeleteCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
        fn EnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
        fn LeaveCriticalSection(lpCriticalSection: LPCRITICAL_SECTION);
        fn TryEnterCriticalSection(lpCriticalSection: LPCRITICAL_SECTION) -> BOOL;
        fn SetEvent(hEvent: HANDLE) -> BOOL;
        fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
    }
}

#[cfg(test)]
mod test {
    use prelude::*;

    use mem::drop;
    use super::{StaticNativeMutex, NATIVE_MUTEX_INIT};
    use rt::thread::Thread;

    #[test]
    fn smoke_lock() {
        static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
        unsafe {
            let _guard = lock.lock();
        }
    }

    #[test]
    fn smoke_cond() {
        static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
        unsafe {
            let guard = lock.lock();
            let t = Thread::start(proc() {
                let guard = lock.lock();
                guard.signal();
            });
            guard.wait();
            drop(guard);

            t.join();
        }
    }

    #[test]
    fn smoke_lock_noguard() {
        static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
        unsafe {
            lock.lock_noguard();
            lock.unlock_noguard();
        }
    }

    #[test]
    fn smoke_cond_noguard() {
        static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
        unsafe {
            lock.lock_noguard();
            let t = Thread::start(proc() {
                lock.lock_noguard();
                lock.signal_noguard();
                lock.unlock_noguard();
            });
            lock.wait_noguard();
            lock.unlock_noguard();

            t.join();
        }
    }

    #[test]
    fn destroy_immediately() {
        unsafe {
            let m = StaticNativeMutex::new();
            m.destroy();
        }
    }
}


text:
using System.Diagnostics;

namespace System.Reflection.Metadata
{
    /// <summary>
    /// Scope of local variables and constants. Stored in debug metadata.
    /// </summary>
    /// <remarks>
    /// See https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#localscope-table-0x32.
    /// </remarks>
    public readonly struct LocalScope
    {
        private readonly MetadataReader _reader;

        // Workaround: JIT doesn't generate good code for nested structures, so use RowId.
        private readonly int _rowId;

        internal LocalScope(MetadataReader reader, LocalScopeHandle handle)
        {
            Debug.Assert(reader != null);
            Debug.Assert(!handle.IsNil);

            _reader = reader;
            _rowId = handle.RowId;
        }

        private LocalScopeHandle Handle => LocalScopeHandle.FromRowId(_rowId);

        public MethodDefinitionHandle Method => _reader.LocalScopeTable.GetMethod(_rowId);
        public ImportScopeHandle ImportScope => _reader.LocalScopeTable.GetImportScope(Handle);
        public int StartOffset => _reader.LocalScopeTable.GetStartOffset(_rowId);
        public int Length => _reader.LocalScopeTable.GetLength(_rowId);
        public int EndOffset => _reader.LocalScopeTable.GetEndOffset(_rowId);

        public LocalVariableHandleCollection GetLocalVariables()
        {
            return new LocalVariableHandleCollection(_reader, Handle);
        }

        public LocalConstantHandleCollection GetLocalConstants()
        {
            return new LocalConstantHandleCollection(_reader, Handle);
        }

        public LocalScopeHandleCollection.ChildrenEnumerator GetChildren()
        {
            return new LocalScopeHandleCollection.ChildrenEnumerator(_reader, _rowId);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NServiceBus;
using SenecaActMessages;

namespace SenecaNServiceBus
{
    class SenecaActHandler : IHandleMessages<ICommand>
    {
        IBus bus;

        public SenecaActHandler(IBus bus)
        {
            this.bus = bus;
        }

        public void Handle(ICommand command)
        {
           bus.Send(command);
        }
    }
}


text:
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.naive_bayes import H2ONaiveBayesEstimator

def nb_init_err():

  print "Importing iris_wheader.csv data...\n"
  iris = h2o.upload_file(pyunit_utils.locate("smalldata/iris/iris_wheader.csv"))
  iris.describe

  print "Laplace smoothing parameter is negative"

  try:
    H2ONaiveBayesEstimator(laplace=-1).train(x=range(4), y=4, training_frame=iris)
    assert False, "Expected naive bayes algo to fail on negative laplace training parameter"
  except:
    pass

  print "Minimum standard deviation is zero"
  try:
    H2ONaiveBayesEstimator().train(x=range(4), y=4, training_frame=iris, min_sdev=0)
    assert False, "Expected naive bayes algo to fail on min_sdev = 0"
  except:
    pass

  print "Response column is not categorical"
  try:
    H2ONaiveBayesEstimator().train(x=range(3), y=3, min_sdev=0)
    assert False, "Expected naive bayes algo to fail on response not categorical"
  except:
    pass

if __name__ == "__main__":
  pyunit_utils.standalone_test(nb_init_err)
else:
  nb_init_err()


text:
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var __decorate = this && this.__decorate || function (decorators, target, key, desc) {
    var c = arguments.length,
        r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
        d;
    if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
        if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    }return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = this && this.__metadata || function (k, v) {
    if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = this && this.__param || function (paramIndex, decorator) {
    return function (target, key) {
        decorator(target, key, paramIndex);
    };
};
import { Component, Optional, ElementRef, ViewEncapsulation } from '@angular/core';
import { NgControl } from '@angular/common';
import { Config } from '../../config/config';
import { Content } from '../content/content';
import { Form } from '../../util/form';
import { InputBase } from './input-base';
import { App } from '../app/app';
import { Item } from '../item/item';
import { NativeInput, NextInput } from './native-input';
import { NavController } from '../nav/nav-controller';
import { Platform } from '../../platform/platform';
/**
 * @name Input
 * @description
 *
 * `ion-input` is meant for text type inputs only, such as `text`,
 * `password`, `email`, `number`, `search`, `tel`, and `url`. Ionic
 * still uses an actual `<input type="text">` HTML element within the
 * component, however, with Ionic wrapping the native HTML input
 * element it's able to better handle the user experience and
 * interactivity.
 *
 * Similarily, `<ion-textarea>` should be used in place of `<textarea>`.
 *
 * An `ion-input` is **not** used for non-text type inputs, such as a
 * `checkbox`, `radio`, `toggle`, `range`, `select`, etc.
 *
 * @property [type] - The HTML input type (text, password, email, number, search, tel, or url)
 * @property [clearInput] - A clear icon will appear in the input when there is a value. Clicking it clears the input.
 *
 * @usage
 * ```html
 * <ion-list>
 *   <ion-item>
 *     <ion-label primary>Inline Label</ion-label>
 *     <ion-input placeholder="Text Input"></ion-input>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label primary fixed>Fixed Label</ion-label>
 *     <ion-input type="tel" placeholder="Tel Input"></ion-input>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-input type="number" placeholder="Number Input with no label"></ion-input>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label primary stacked>Stacked Label</ion-label>
 *     <ion-input type="email" placeholder="Email Input"></ion-input>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label primary stacked>Stacked Label</ion-label>
 *     <ion-input type="password" placeholder="Password Input"></ion-input>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-label primary floating>Floating Label</ion-label>
 *     <ion-input></ion-input>
 *   </ion-item>
 *
 *   <ion-item>
 *     <ion-input placeholder="Clear Input" clearInput></ion-input>
 *   </ion-item>
 * </ion-list>
 * ```
 *
 * @demo /docs/v2/demos/input/
 */
export var TextInput = function (_InputBase) {
    _inherits(TextInput, _InputBase);

    function TextInput(config, form, item, app, platform, elementRef, scrollView, nav, ngControl) {
        _classCallCheck(this, TextInput);

        return _possibleConstructorReturn(this, Object.getPrototypeOf(TextInput).call(this, config, form, item, app, platform, elementRef, scrollView, nav, ngControl));
    }
    /**
     * @private
     */

    _createClass(TextInput, [{
        key: "inputBlurred",
        value: function inputBlurred(ev) {
            this.blur.emit(ev);
        }
        /**
         * @private
         */

    }, {
        key: "inputFocused",
        value: function inputFocused(ev) {
            this.focus.emit(ev);
        }
        /**
         * @private
         */

    }, {
        key: "clearTextInput",
        value: function clearTextInput() {
            console.debug('Should clear input');
            this._value = '';
            this.onChange(this._value);
            this.writeValue(this._value);
        }
    }]);

    return TextInput;
}(InputBase);
TextInput = __decorate([Component({
    selector: 'ion-input',
    template: '<input [type]="type" [(ngModel)]="_value" (blur)="inputBlurred($event)" (focus)="inputFocused($event)" [placeholder]="placeholder" class="text-input">' + '<input [type]="type" aria-hidden="true" next-input *ngIf="_useAssist">' + '<button clear [hidden]="!clearInput" type="button" class="text-input-clear-icon" (click)="clearTextInput()" (mousedown)="clearTextInput()"></button>' + '

',
    directives: [NextInput, NativeInput],
    encapsulation: ViewEncapsulation.None
}), __param(2, Optional()), __param(6, Optional()), __param(7, Optional()), __param(8, Optional()), __metadata('design:paramtypes', [typeof (_a = typeof Config !== 'undefined' && Config) === 'function' && _a || Object, typeof (_b = typeof Form !== 'undefined' && Form) === 'function' && _b || Object, typeof (_c = typeof Item !== 'undefined' && Item) === 'function' && _c || Object, typeof (_d = typeof App !== 'undefined' && App) === 'function' && _d || Object, typeof (_e = typeof Platform !== 'undefined' && Platform) === 'function' && _e || Object, typeof (_f = typeof ElementRef !== 'undefined' && ElementRef) === 'function' && _f || Object, typeof (_g = typeof Content !== 'undefined' && Content) === 'function' && _g || Object, typeof (_h = typeof NavController !== 'undefined' && NavController) === 'function' && _h || Object, typeof (_j = typeof NgControl !== 'undefined' && NgControl) === 'function' && _j || Object])], TextInput);
/**
 * @name TextArea
 * @description
 *
 * `ion-textarea` is is used for multi-line text inputs. Ionic still
 * uses an actual `<textarea>` HTML element within the component;
 * however, with Ionic wrapping the native HTML text area element, Ionic
 * is able to better handle the user experience and interactivity.
 *
 * Not that `<ion-textarea>` must load its value from the `value` or
 * `[(ngModel)]` attribute. Unlike the native `<textarea>` element,
 * `<ion-textarea>` does not support loading its value from the
 * textarea's inner content.
 *
 * When requiring only a single-line text input, we recommend using
 * `<ion-input>` instead.
 *
 * @usage
 * ```html
 *  <ion-item>
 *    <ion-label>Comments</ion-label>
 *    <ion-textarea></ion-textarea>
 *  </ion-item>
 *
 *  <ion-item>
 *    <ion-label stacked>Message</ion-label>
 *    <ion-textarea [(ngModel)]="msg"></ion-textarea>
 *  </ion-item>
 *
 *  <ion-item>
 *    <ion-label floating>Description</ion-label>
 *    <ion-textarea></ion-textarea>
 *  </ion-item>
 * ```
 *
 * @demo /docs/v2/demos/textarea/
 */
export var TextArea = function (_InputBase2) {
    _inherits(TextArea, _InputBase2);

    function TextArea(config, form, item, app, platform, elementRef, scrollView, nav, ngControl) {
        _classCallCheck(this, TextArea);

        return _possibleConstructorReturn(this, Object.getPrototypeOf(TextArea).call(this, config, form, item, app, platform, elementRef, scrollView, nav, ngControl));
    }
    /**
     * @private
     */

    _createClass(TextArea, [{
        key: "ngOnInit",
        value: function ngOnInit() {
            _get(Object.getPrototypeOf(TextArea.prototype), "ngOnInit", this).call(this);
            if (this._item) {
                this._item.setCssClass('item-textarea', true);
            }
        }
        /**
         * @private
         */

    }, {
        key: "inputBlurred",
        value: function inputBlurred(ev) {
            this.blur.emit(ev);
        }
        /**
         * @private
         */

    }, {
        key: "inputFocused",
        value: function inputFocused(ev) {
            this.focus.emit(ev);
        }
    }]);

    return TextArea;
}(InputBase);
TextArea = __decorate([Component({
    selector: 'ion-textarea',
    template: '<textarea [(ngModel)]="_value" (blur)="inputBlurred($event)" (focus)="inputFocused($event)" [placeholder]="placeholder" class="text-input"></textarea>' + '<input type="text" aria-hidden="true" next-input *ngIf="_useAssist">' + '

',
    directives: [NextInput, NativeInput],
    encapsulation: ViewEncapsulation.None
}), __param(2, Optional()), __param(6, Optional()), __param(7, Optional()), __param(8, Optional()), __metadata('design:paramtypes', [typeof (_k = typeof Config !== 'undefined' && Config) === 'function' && _k || Object, typeof (_l = typeof Form !== 'undefined' && Form) === 'function' && _l || Object, typeof (_m = typeof Item !== 'undefined' && Item) === 'function' && _m || Object, typeof (_o = typeof App !== 'undefined' && App) === 'function' && _o || Object, typeof (_p = typeof Platform !== 'undefined' && Platform) === 'function' && _p || Object, typeof (_q = typeof ElementRef !== 'undefined' && ElementRef) === 'function' && _q || Object, typeof (_r = typeof Content !== 'undefined' && Content) === 'function' && _r || Object, typeof (_s = typeof NavController !== 'undefined' && NavController) === 'function' && _s || Object, typeof (_t = typeof NgControl !== 'undefined' && NgControl) === 'function' && _t || Object])], TextArea);
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;


text:
package util

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
	"context"

	"github.com/fagongzi/log"
	"github.com/fagongzi/util/task"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/common/expfmt"
	"github.com/prometheus/common/model"
)

const contentTypeHeader = "Content-Type"

// MetricCfg is the metric configuration.
type MetricCfg struct {
	Job          string
	Instance     string
	Address      string
	DurationSync time.Duration
}

// NewMetricCfg returns metric cfg
func NewMetricCfg(job, instance, address string, durationSync time.Duration) *MetricCfg {
	return &MetricCfg{
		Job:          job,
		Instance:     instance,
		Address:      address,
		DurationSync: durationSync,
	}
}

// InitMetric init the metric
func InitMetric(runner *task.Runner, cfg *MetricCfg) {
	if nil == cfg || cfg.DurationSync == 0 || len(cfg.Address) == 0 {
		log.Info("metric: disable prometheus push client")
		return
	}

	log.Info("metric: start prometheus push client")

	runner.RunCancelableTask(func(ctx context.Context) {
		t := time.NewTicker(cfg.DurationSync)
		defer t.Stop()

		for {
			select {
			case <-ctx.Done():
				log.Info("stop: prometheus push client stopped")
				t.Stop()
				return
			case <-t.C:
				err := doPush(cfg.Job, instanceGroupingKey(cfg.Instance), cfg.Address, prometheus.DefaultGatherer, "PUT")

				if err != nil {
					log.Errorf("metric: could not push metrics to prometheus pushgateway: errors:\n%+v", err)
				}
			}
		}
	})
}

// instanceGroupingKey returns a label map with the only entry
// {instance="<instance>"}. If instance is empty, use hostname instead.
func instanceGroupingKey(instance string) map[string]string {
	if instance == "" {
		var err error
		if instance, err = os.Hostname(); err != nil {
			instance = "unknown"
		}
	}
	return map[string]string{"instance": instance}
}

func doPush(job string, grouping map[string]string, pushURL string, g prometheus.Gatherer, method string) error {
	if !strings.Contains(pushURL, "://") {
		pushURL = "http://" + pushURL
	}
	if strings.HasSuffix(pushURL, "/") {
		pushURL = pushURL[:len(pushURL)-1]
	}

	if strings.Contains(job, "/") {
		return fmt.Errorf("job contains '/': %s", job)
	}
	urlComponents := []string{url.QueryEscape(job)}
	for ln, lv := range grouping {
		if !model.LabelName(ln).IsValid() {
			return fmt.Errorf("grouping label has invalid name: %s", ln)
		}
		if strings.Contains(lv, "/") {
			return fmt.Errorf("value of grouping label %s contains '/': %s", ln, lv)
		}
		urlComponents = append(urlComponents, ln, lv)
	}
	pushURL = fmt.Sprintf("%s/metrics/job/%s", pushURL, strings.Join(urlComponents, "/"))

	mfs, err := g.Gather()
	if err != nil {
		return err
	}
	buf := &bytes.Buffer{}
	enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim)
	// Check for pre-existing grouping labels:
	for _, mf := range mfs {
		for _, m := range mf.GetMetric() {
			for _, l := range m.GetLabel() {
				if l.GetName() == "job" {
					return fmt.Errorf("pushed metric %s (%s) already contains a job label", mf.GetName(), m)
				}
				if _, ok := grouping[l.GetName()]; ok {
					return fmt.Errorf(
						"pushed metric %s (%s) already contains grouping label %s",
						mf.GetName(), m, l.GetName(),
					)
				}
			}
		}
		enc.Encode(mf)
	}
	req, err := http.NewRequest(method, pushURL, buf)
	if err != nil {
		return err
	}
	req.Header.Set(contentTypeHeader, string(expfmt.FmtProtoDelim))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 202 {
		body, _ := ioutil.ReadAll(resp.Body) // Ignore any further error as this is for an error message only.
		return fmt.Errorf("unexpected status code %d while pushing to %s: %s", resp.StatusCode, pushURL, body)
	}
	return nil
}


text:
<projectskin>
    <skin name="android_slider_left_skin" value="sliderLeft"/>
    <skin name="textfield_skin_focus" value="tbxFocus"/>
    <skin name="textarea2_skin" value="txt2Normal"/>
    <skin name="imagegallery2_skin" value="gal2Normal"/>
    <skin name="richtext_skin" value="richNormal"/>
    <skin name="himgstrip2_skin" value="hStrip2Normal"/>
    <skin name="datagrid_alternate_skin" value="dgRow"/>
    <skin name="textfield_skin" value="tbxNormal"/>
    <skin name="datagrid_header_skin" value="dgHead"/>
    <skin name="segment2_widget_skin" value="sknSegKonyThemeRowNormal"/>
    <skin name="camera_skin" value="camNormal"/>
    <skin name="segment_sec_skin_focus" value="segHeader"/>
    <skin name="label_skin" value="sknLblKonyThemeNormal"/>
    <skin name="calendar_skin" value="sknCalKonyThemeNormal"/>
    <skin name="bb_slider_left_skin_key" value="sliderLeft"/>
    <skin name="form_skin" value="sknFrmKonyThemeNormal"/>
    <skin name="checkboxgroup_skin" value="cbxNormal"/>
    <skin name="line_skin" value="lineNormal"/>
    <skin name="himgstrip_skin_focus" value="hStripFocus"/>
    <skin name="row_skin" value="No Skin"/>
    <skin name="himgstrip2_skin_focus" value="hStrip2Focus"/>
    <skin name="phone_skin_focus" value="phoneFocus"/>
    <skin name="imagegallery2_skin_focus" value="gal2Focus"/>
    <skin name="listbox_skin_focus" value="sknListboxKonyThemeFocus"/>
    <skin name="himgstrip_skin" value="hStripNormal"/>
    <skin name="android_form_title_skin" value="titleBar"/>
    <skin name="bb_form_title_skin" value="titleBar"/>
    <skin name="phone_skin" value="phoneNormal"/>
    <skin name="datagrid_row_skin_focus" value="dgFocus"/>
    <skin name="calendar_skin_focus" value="sknCalKonyThemeFocus"/>
    <skin name="textarea2_skin_focus" value="txt2Focus"/>
    <skin name="imagegallery_skin_focus" value="galFocus"/>
    <skin name="textarea_skin_focus" value="txtFocus"/>
    <skin name="tabpane_inactive_skin" value="tabInactive"/>
    <skin name="listbox_skin" value="sknListboxKonyThemeNormal"/>
    <skin name="segment_skin_focus" value="segFocus"/>
    <skin name="datagrid_row_skin" value="dgRow"/>
    <skin name="segment2_row_skin" value="sknSegKonyThemeRowNormal"/>
    <skin name="combobox_skin_focus" value="cboxFocus"/>
    <skin name="combobox_skin" value="cboxNormal"/>
    <skin name="segment2_row_focus_skin" value="seg2Focus"/>
    <skin name="segment2_secheader_skin" value="seg2Header"/>
    <skin name="android_slider_right_skin" value="sliderRight"/>
    <skin name="segment_skin" value="segNormal"/>
    <skin name="tabpane_active_focus_skin" value="tabFocus"/>
    <skin name="bb_slider_right_skin_key" value="sliderRight"/>
    <skin name="button_skin" value="sknBtnKonyThemeNormal"/>
    <skin name="textbox2_skin_focus" value="tbx2Focus"/>
    <skin name="textarea_skin" value="txtNormal"/>
    <skin name="button_skin_focus" value="sknBtnKonyThemeFocus"/>
    <skin name="radiobuttongroup_skin_focus" value="radioFocus"/>
    <skin name="tabpane_active_skin" value="tabActive"/>
    <skin name="popup_skin" value="sknPopupKonyThemeNormal"/>
    <skin name="camera_skin_focus" value="camFocus"/>
    <skin name="winmob_slider_right_skin" value="sliderRight"/>
    <skin name="winmob_slider_left_skin" value="sliderLeft"/>
    <skin name="checkboxgroup_skin_focus" value="cbxFocus"/>
    <skin name="imagegallery_skin" value="galNormal"/>
    <skin name="radiobuttongroup_skin" value="radioNormal"/>
    <skin name="textbox2_skin" value="tbx2Normal"/>
</projectskin>


text:
require 'catmother/binary_helpers'
require 'catmother/opcode_groups/branch'

module CatMother
  module Opcode
    class If_icmpge
      MNEMONIC = "if_icmpge"
      OPCODE = 0xa2
      OPERANDS = 2
      POPS = 2
      PUSHES = 0
      SHORT_DESCRIPTION = "Branch if int comparison succeeds (>=)"
      DESCRIPTION = ""

      include CatMother::OpcodeGroup::Branch

      def initialize(io, pc)
        parse_operands(io, pc)
      end
    end
  end
end


text:
% DEMBRENDAN1 Use the GP-LVM to model the Frey face data with back constraints.

% FGPLVM

% Fix seeds
randn('seed', 1e5);
rand('seed', 1e5);

dataSetName = 'brendan';
experimentNo = 1;

% load data
[Y, lbls] = lvmLoadData(dataSetName);

% Set up model
options = fgplvmOptions('fitc');
options.optimiser = 'conjgrad';
options.back = 'kbr';
options.backOptions = kbrOptions(Y);
options.backOptions.kern = kernCreate(Y, 'rbf');
options.backOptions.kern.inverseWidth = 0.00001;

latentDim = 2;
d = size(Y, 2);

model = fgplvmCreate(latentDim, d, Y, options);

% Optimise the model.
iters = 1000;
display = 1;

model = fgplvmOptimise(model, display, iters);

% Save the results.
capName = dataSetName;;
capName(1) = upper(capName(1));
save(['dem' capName num2str(experimentNo) '.mat'], 'model');

if exist('printDiagram') & printDiagram
  fgplvmPrintPlot(model, lbls, capName, experimentNo);
end

% Load the results and display dynamically.
fgplvmResultsDynamic(dataSetName, experimentNo, 'image', [20 28], 1, 0, 1)

% compute the nearest neighbours errors in latent space.
errors = fgplvmNearestNeighbour(model, lbls);


text:
class CreateJoinTableUserSkill < ActiveRecord::Migration
  def change
    create_table :skills_users do |t|
      t.belongs_to :user
      t.belongs_to :skill
      t.datetime :doable_on, :reliable_on, :refined_on

      t.timestamps
    end
  end
end


text:
package com.atlassian.jira.plugins.dvcs.scheduler;

import com.atlassian.event.api.EventPublisher;
import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.event.events.PluginEnabledEvent;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static com.atlassian.jira.plugins.dvcs.scheduler.SchedulerLauncher.SchedulerLauncherJob;
import static com.atlassian.jira.plugins.dvcs.util.DvcsConstants.PLUGIN_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class SchedulerLauncherTest
{
    private SchedulerLauncher schedulerLauncher;

    @Mock private EventPublisher mockEventPublisher;
    @Mock private PluginEnabledEvent mockPluginEnabledEvent;
    @Mock private SchedulerLauncherJob mockJob;

    @BeforeMethod
    public void setUp() throws Exception
    {
        MockitoAnnotations.initMocks(this);

        mockPluginEnabledEventWithPluginKey(mockPluginEnabledEvent, PLUGIN_KEY);

        schedulerLauncher = new SchedulerLauncher(mockEventPublisher);
    }

    @Test
    public void partialEventsShouldNotTriggerJob1() throws Exception
    {
        // Invoke
        schedulerLauncher.runWhenReady(mockJob);
        schedulerLauncher.onStart();

        // Check
        verify(mockJob, never()).run();
    }

    @Test
    public void partialEventsShouldNotTriggerJob2() throws Exception
    {
        // Invoke
        schedulerLauncher.runWhenReady(mockJob);
        schedulerLauncher.onPluginEnabled(mockPluginEnabledEvent);

        // Check
        verify(mockJob, never()).run();
    }

    @Test
    public void pluginEnabledEventWithNonMatchingPluginKeyShouldNotTriggerJob() throws Exception
    {
        // Invoke
        schedulerLauncher.runWhenReady(mockJob);
        schedulerLauncher.onStart();

        PluginEnabledEvent eventWithDifferentPluginKey = mock(PluginEnabledEvent.class);
        mockPluginEnabledEventWithPluginKey(eventWithDifferentPluginKey, "some-other-key");
        schedulerLauncher.onPluginEnabled(eventWithDifferentPluginKey);

        // Check
        verify(mockJob, never()).run();

        // This should be the last event required. If this doesn't cause mockJob to run, this test is broken,
        // because it's not running above on account of a different missing event.
        schedulerLauncher.onPluginEnabled(mockPluginEnabledEvent);

        // Check
        verify(mockJob).run();
    }

    @Test
    public void allEventsShouldTriggerJob() throws Exception
    {
        // Invoke
        schedulerLauncher.runWhenReady(mockJob);
        triggerAllEvents();

        // Check
        verify(mockJob).run();
        verify(mockEventPublisher).unregister(schedulerLauncher);
    }

    @Test
    public void allEventsShouldTriggerMultipleJobs() throws Exception
    {
        // Invoke
        SchedulerLauncherJob mockJob2 = mock(SchedulerLauncherJob.class);
        SchedulerLauncherJob mockJob3 = mock(SchedulerLauncherJob.class);
        schedulerLauncher.runWhenReady(mockJob);
        schedulerLauncher.runWhenReady(mockJob2);
        schedulerLauncher.runWhenReady(mockJob3);

        triggerAllEvents();

        // Check
        verify(mockJob).run();
        verify(mockJob2).run();
        verify(mockJob3).run();
    }

    @Test
    public void jobAddedAfterAllEventsShouldRun() throws Exception
    {
        // Invoke
        triggerAllEvents();

        schedulerLauncher.runWhenReady(mockJob);

        // Check
        verify(mockJob).run();
    }

    @Test
    public void jobAddedBeforeAndAfterAllEventsShouldAllRun() throws Exception
    {
        // Invoke
        SchedulerLauncherJob mockJob2 = mock(SchedulerLauncherJob.class);
        schedulerLauncher.runWhenReady(mockJob);

        triggerAllEvents();

        schedulerLauncher.runWhenReady(mockJob2);

        // Check
        verify(mockJob).run();
        verify(mockJob2).run();
    }

    private Plugin mockPluginWithKey(final String pluginKey)
    {
        Plugin mockPlugin = mock(Plugin.class);
        when(mockPlugin.getKey()).thenReturn(pluginKey);

        return mockPlugin;
    }

    private void mockPluginEnabledEventWithPluginKey(final PluginEnabledEvent mockPluginEnabledEvent, final String pluginKey)
    {
        Plugin mockPlugin = mockPluginWithKey(pluginKey);
        when(mockPluginEnabledEvent.getPlugin()).thenReturn(mockPlugin);
    }

    private void triggerAllEvents()
    {
        schedulerLauncher.onStart();
        schedulerLauncher.onPluginEnabled(mockPluginEnabledEvent);
    }
}


text:
package pl.asie.charset.lib.recipe;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;

public class RecipeObjectItemStack implements IRecipeObject {
    private final ItemStack target;

    public RecipeObjectItemStack(Block block) {
        target = new ItemStack(block, 1, OreDictionary.WILDCARD_VALUE);
    }

    public RecipeObjectItemStack(Item item) {
        target = new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE);
    }

    public RecipeObjectItemStack(ItemStack stack) {
        target = stack;
    }

    @Override
    public boolean matches(ItemStack stack) {
        return OreDictionary.itemMatches(target, stack, false);
    }

    @Override
    public Object preview() {
        return target;
    }
}


text:
package org.huihoo.ofbiz.smart.entity;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.huihoo.ofbiz.smart.base.util.Log;

public class ModelDelegator {
  private static final String tag = ModelDelegator.class.getName();

  public static <T extends Model> T create(Class<T> clazz, Object... namesAndValues) {
    try {
      Constructor<T> c = clazz.getDeclaredConstructor();
      c.setAccessible(true);
      T model = c.newInstance(clazz).set(namesAndValues);
      model.save();
      return model;
    } catch (InstantiationException e) {
      Log.e(e, tag, e.getMessage());
      throw new EntityException(e);
    } catch (IllegalAccessException e) {
      Log.e(e, tag, e.getMessage());
      throw new EntityException(e);
    } catch (IllegalArgumentException e) {
      Log.e(e, tag, e.getMessage());
      throw new EntityException(e);
    } catch (InvocationTargetException e) {
      Log.e(e, tag, e.getMessage());
      throw new EntityException(e);
    } catch (NoSuchMethodException e) {
      Log.e(e, tag, e.getMessage());
      throw new EntityException(e);
    } catch (SecurityException e) {
      Log.e(e, tag, e.getMessage());
      throw new EntityException(e);
    }
  }
}


text:
import { StatsCollection } from './StatsCollection';
import { RepoInfo } from '../RepoInfo';

export class StatsManager {
  private static collections_: { [k: string]: StatsCollection } = {};
  private static reporters_: { [k: string]: any } = {};

  static getCollection(repoInfo: RepoInfo): StatsCollection {
    const hashString = repoInfo.toString();

    if (!this.collections_[hashString]) {
      this.collections_[hashString] = new StatsCollection();
    }

    return this.collections_[hashString];
  }

  static getOrCreateReporter<T>(
    repoInfo: RepoInfo,
    creatorFunction: () => T
  ): T {
    const hashString = repoInfo.toString();

    if (!this.reporters_[hashString]) {
      this.reporters_[hashString] = creatorFunction();
    }

    return this.reporters_[hashString];
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syn. Fung. (Oslo) 20: 36 (2005)

#### Original name
Corticium chrysocreas Berk. & M.A. Curtis, 1873

### Remarks
null


text:
package pl.com.softproject.przelewy24.model;

public enum Currency {

    PLN, EUR, GBP, CZK;

}