text:
package rest

import (
	"fmt"
	"net/http"
	"testing"

	sgbucket "github.com/couchbase/sg-bucket"
	"github.com/couchbase/sync_gateway/base"
	"github.com/couchbase/sync_gateway/channels"
	"github.com/couchbase/sync_gateway/db"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestDesignDocs(t *testing.T) {
	rt := NewRestTester(t, nil)
	defer rt.Close()

	response := rt.SendRequest(http.MethodGet, "/db/_design/foo", "")
	assertStatus(t, response, http.StatusForbidden)
	response = rt.SendRequest(http.MethodPut, "/db/_design/foo", `{}`)
	assertStatus(t, response, http.StatusForbidden)
	response = rt.SendRequest(http.MethodDelete, "/db/_design/foo", "")
	assertStatus(t, response, http.StatusForbidden)

	response = rt.SendAdminRequest(http.MethodGet, "/db/_design/foo", "")
	assertStatus(t, response, http.StatusNotFound)
	response = rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendAdminRequest(http.MethodGet, "/db/_design/foo", "")

	assertStatus(t, response, http.StatusOK)
	response = rt.SendAdminRequest(http.MethodGet, "/db/_design%2ffoo", "")
	assertStatus(t, response, http.StatusOK)
	response = rt.SendAdminRequest(http.MethodGet, "/db/_design%2Ffoo", "")
	assertStatus(t, response, http.StatusOK)
	response = rt.SendAdminRequest(http.MethodDelete, "/db/_design/foo", "")
	assertStatus(t, response, http.StatusOK)

	response = rt.SendAdminRequest(http.MethodPut, fmt.Sprintf("/db/_design/%s", db.DesignDocSyncGateway()), "{}")
	assertStatus(t, response, http.StatusForbidden)
	response = rt.SendAdminRequest(http.MethodGet, fmt.Sprintf("/db/_design/%s", db.DesignDocSyncGateway()), "")
	assertStatus(t, response, http.StatusOK)
}

func TestViewQuery(t *testing.T) {
	rt := NewRestTester(t, nil)
	defer rt.Close()

	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views":{"bar": {"map": "function(doc) {emit(doc.key, doc.value);}"}}}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc1", `{"key":10, "value":"ten"}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc2", `{"key":7, "value":"seven"}`)
	assertStatus(t, response, http.StatusCreated)

	// The wait is needed here because the query does not have stale=false.
	// TODO: update the query to use stale=false and remove the wait
	result, err := rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/bar")
	assert.NoError(t, err, "Got unexpected error")
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: "seven"}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: 10.0, Value: "ten"}, result.Rows[1])

	result, err = rt.WaitForNAdminViewResults(1, "/db/_design/foo/_view/bar?limit=1")
	require.Len(t, result.Rows, 1)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: "seven"}, result.Rows[0])

	result, err = rt.WaitForNAdminViewResults(1, "/db/_design/foo/_view/bar?endkey=9")
	require.Len(t, result.Rows, 1)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: "seven"}, result.Rows[0])

	if base.UnitTestUrlIsWalrus() {
		// include_docs=true only works with walrus as documented here:
		// https://forums.couchbase.com/t/do-the-viewquery-options-omit-include-docs-on-purpose/12399
		result, err = rt.WaitForNAdminViewResults(1, "/db/_design/foo/_view/bar?include_docs=true&endkey=9")
		require.Len(t, result.Rows, 1)
		assert.Equal(t, map[string]interface{}{"key": 7.0, "value": "seven"}, *result.Rows[0].Doc)
	}

}

//Tests #1109, wh ere design doc contains multiple views
func TestViewQueryMultipleViews(t *testing.T) {
	rt := NewRestTester(t, nil)
	defer rt.Close()

	//Define three views
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views": {"by_fname": {"map": "function (doc, meta) { emit(doc.fname, null); }"},"by_lname": {"map": "function (doc, meta) { emit(doc.lname, null); }"},"by_age": {"map": "function (doc, meta) { emit(doc.age, null); }"}}}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc1", `{"fname": "Alice", "lname":"Ten", "age":10}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc2", `{"fname": "Bob", "lname":"Seven", "age":7}`)
	assertStatus(t, response, http.StatusCreated)

	result, err := rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/by_age")
	assert.NoError(t, err, "Unexpected error")
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: interface{}(nil)}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: 10.0, Value: interface{}(nil)}, result.Rows[1])

	result, err = rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/by_fname")
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: "Alice", Value: interface{}(nil)}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: "Bob", Value: interface{}(nil)}, result.Rows[1])

	result, err = rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/by_lname")
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: "Seven", Value: interface{}(nil)}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: "Ten", Value: interface{}(nil)}, result.Rows[1])
}

func TestViewQueryWithParams(t *testing.T) {
	rt := NewRestTester(t, nil)
	defer rt.Close()

	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foodoc", `{"views": {"foobarview": {"map": "function(doc, meta) {if (doc.value == \"foo\") {emit(doc.key, null);}}"}}}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc1", `{"value": "foo", "key": "test1"}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc2", `{"value": "foo", "key": "test2"}`)
	assertStatus(t, response, http.StatusCreated)

	result, err := rt.WaitForNAdminViewResults(2, `/db/_design/foodoc/_view/foobarview?conflicts=true&descending=false&endkey="test2"&endkey_docid=doc2&end_key_doc_id=doc2&startkey="test1"&startkey_docid=doc1`)
	assert.NoError(t, err, "Unexpected error")
	require.Len(t, result.Rows, 2)
	assert.Contains(t, result.Rows, &sgbucket.ViewRow{ID: "doc1", Key: "test1", Value: interface{}(nil)})
	assert.Contains(t, result.Rows, &sgbucket.ViewRow{ID: "doc2", Key: "test2", Value: interface{}(nil)})

	result, err = rt.WaitForNAdminViewResults(2, `/db/_design/foodoc/_view/foobarview?conflicts=true&descending=false&conflicts=true&descending=false&keys=["test1", "test2"]`)
	assert.NoError(t, err, "Unexpected error")
	require.Len(t, result.Rows, 2)
	assert.Contains(t, result.Rows, &sgbucket.ViewRow{ID: "doc1", Key: "test1", Value: interface{}(nil)})
	assert.Contains(t, result.Rows, &sgbucket.ViewRow{ID: "doc2", Key: "test2", Value: interface{}(nil)})
}

func TestViewQueryUserAccess(t *testing.T) {
	rt := NewRestTester(t, nil)
	defer rt.Close()

	rt.ServerContext().Database("db").SetUserViewsEnabled(true)
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views":{"bar": {"map":"function (doc, meta) { if (doc.type != 'type1') { return; } if (doc.state == 'state1' || doc.state == 'state2' || doc.state == 'state3') { emit(doc.state, meta.id); }}"}}}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc1", `{"type":"type1", "state":"state1"}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc2", `{"type":"type1", "state":"state2"}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc3", `{"type":"type2", "state":"state2"}`)
	assertStatus(t, response, http.StatusCreated)

	result, err := rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/bar?stale=false")
	assert.NoError(t, err, "Unexpected error in WaitForNAdminViewResults")
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: "state1", Value: "doc1"}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: "state2", Value: "doc2"}, result.Rows[1])

	result, err = rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/bar?stale=false")
	assert.NoError(t, err, "Unexpected error in WaitForNAdminViewResults")

	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: "state1", Value: "doc1"}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: "state2", Value: "doc2"}, result.Rows[1])

	// Create a user:
	a := rt.ServerContext().Database("db").Authenticator()
	password := "123456"
	testUser, _ := a.NewUser("testUser", password, channels.SetOf(t, "*"))
	assert.NoError(t, a.Save(testUser))

	result, err = rt.WaitForNUserViewResults(2, "/db/_design/foo/_view/bar?stale=false", testUser, password)
	assert.NoError(t, err, "Unexpected error in WaitForNUserViewResults")

	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: "state1", Value: "doc1"}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: "state2", Value: "doc2"}, result.Rows[1])

	// Disable user view access, retry
	rt.ServerContext().Database("db").SetUserViewsEnabled(false)
	request, _ := http.NewRequest(http.MethodGet, "/db/_design/foo/_view/bar?stale=false", nil)
	request.SetBasicAuth(testUser.Name(), password)
	userResponse := rt.Send(request)
	assertStatus(t, userResponse, http.StatusForbidden)
}

func TestViewQueryMultipleViewsInterfaceValues(t *testing.T) {
	// TODO: Waiting for a fix for couchbaselabs/Walrus #13
	// Currently fails against walrus bucket as '_sync' property will exist in doc object if it is emitted in the map function
	t.Skip("WARNING: TEST DISABLED")

	rt := NewRestTester(t, nil)
	defer rt.Close()

	//Define three views
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views": {"by_fname": {"map": "function (doc, meta) { emit(doc.fname, null); }"},"by_lname": {"map": "function (doc, meta) { emit(doc.lname, null); }"},"by_age": {"map": "function (doc, meta) { emit(doc.age, doc); }"}}}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc1", `{"fname": "Alice", "lname":"Ten", "age":10}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc2", `{"fname": "Bob", "lname":"Seven", "age":7}`)
	assertStatus(t, response, http.StatusCreated)

	response = rt.SendAdminRequest(http.MethodGet, "/db/_design/foo/_view/by_age", ``)
	assertStatus(t, response, http.StatusOK)
	var result sgbucket.ViewResult
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: 7.0, Value: interface{}(nil)}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: 10.0, Value: interface{}(nil)}, result.Rows[1])

	response = rt.SendAdminRequest(http.MethodGet, "/db/_design/foo/_view/by_fname", ``)
	assertStatus(t, response, http.StatusOK)
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: "Alice", Value: interface{}(nil)}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: "Bob", Value: interface{}(nil)}, result.Rows[1])

	response = rt.SendAdminRequest(http.MethodGet, "/db/_design/foo/_view/by_lname", ``)
	assertStatus(t, response, http.StatusOK)
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 2)
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc2", Key: "Seven", Value: interface{}(nil)}, result.Rows[0])
	assert.Equal(t, &sgbucket.ViewRow{ID: "doc1", Key: "Ten", Value: interface{}(nil)}, result.Rows[1])
}

func TestUserViewQuery(t *testing.T) {
	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	a := rt.ServerContext().Database("db").Authenticator()
	rt.ServerContext().Database("db").SetUserViewsEnabled(true)

	// Create a view:
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views":{"bar": {"map": "function(doc) {emit(doc.key, doc.value);}"}}}`)
	assertStatus(t, response, http.StatusCreated)

	// Create docs:
	response = rt.SendRequest(http.MethodPut, "/db/doc1", `{"key":10, "value":"ten", "channel":"W"}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendRequest(http.MethodPut, "/db/doc2", `{"key":7, "value":"seven", "channel":"Q"}`)
	assertStatus(t, response, http.StatusCreated)

	// Create a user:
	password := "123456"
	quinn, _ := a.NewUser("quinn", password, channels.SetOf(t, "Q", "q"))
	assert.NoError(t, a.Save(quinn))

	// Have the user query the view:
	result, err := rt.WaitForNUserViewResults(1, "/db/_design/foo/_view/bar?include_docs=true", quinn, password)
	assert.NoError(t, err, "Unexpected error")
	require.Len(t, result.Rows, 1)
	assert.Equal(t, 1, result.TotalRows)
	row := result.Rows[0]
	assert.Equal(t, float64(7), row.Key)
	assert.Equal(t, "seven", row.Value)

	if base.UnitTestUrlIsWalrus() {
		// include_docs=true only works with walrus as documented here:
		// https://forums.couchbase.com/t/do-the-viewquery-options-omit-include-docs-on-purpose/12399
		assert.Equal(t, map[string]interface{}{"key": 7.0, "value": "seven", "channel": "Q"}, *row.Doc)
	}

	// Admin should see both rows:
	result, err = rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/bar")
	assert.NoError(t, err, "Unexpected error")
	require.Len(t, result.Rows, 2)
	row = result.Rows[0]
	assert.Equal(t, float64(7), row.Key)
	assert.Equal(t, "seven", row.Value)

	if base.UnitTestUrlIsWalrus() {
		// include_docs=true only works with walrus as documented here:
		// https://forums.couchbase.com/t/do-the-viewquery-options-omit-include-docs-on-purpose/12399
		assert.Equal(t, map[string]interface{}{"key": 7.0, "value": "seven", "channel": "Q"}, *row.Doc)
	}

	row = result.Rows[1]
	assert.Equal(t, float64(10), row.Key)
	assert.Equal(t, "ten", row.Value)

	if base.UnitTestUrlIsWalrus() {
		// include_docs=true only works with walrus as documented here:
		// https://forums.couchbase.com/t/do-the-viewquery-options-omit-include-docs-on-purpose/12399
		assert.Equal(t, map[string]interface{}{"key": 10.0, "value": "ten", "channel": "W"}, *row.Doc)
	}

	// Make sure users are not allowed to query internal views:
	request, _ := http.NewRequest(http.MethodGet, "/db/_design/sync_gateway/_view/access", nil)
	request.SetBasicAuth(quinn.Name(), password)
	response = rt.Send(request)
	assertStatus(t, response, http.StatusForbidden)
}

// This includes a fix for #857
func TestAdminReduceViewQuery(t *testing.T) {
	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Create a view with a reduce:
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views":{"bar": {"map": "function(doc) {emit(doc.key, doc.value);}", "reduce": "_count"}}}`)
	assertStatus(t, response, http.StatusCreated)

	for i := 0; i < 9; i++ {
		// Create docs:
		response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", i), `{"key":0, "value":"0", "channel":"W"}`)
		assertStatus(t, response, http.StatusCreated)

	}
	response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", 10), `{"key":1, "value":"0", "channel":"W"}`)
	assertStatus(t, response, http.StatusCreated)

	var result sgbucket.ViewResult

	// Admin view query:
	result, err := rt.WaitForNAdminViewResults(1, "/db/_design/foo/_view/bar?reduce=true")
	assert.NoError(t, err, "Unexpected error")

	// we should get 1 row with the reduce result
	require.Len(t, result.Rows, 1)
	row := result.Rows[0]
	value := row.Value.(float64)
	assert.True(t, value == 10)

	// todo support group reduce, see #955
	// // test group=true
	// response = rt.sendAdminRequest("GET", "/db/_design/foo/_view/bar?reduce=true&group=true", ``)
	// assertStatus(t, response, 200)
	// base.JSONUnmarshal(response.Body.Bytes(), &result)
	// // we should get 2 rows with the reduce result
	// goassert.Equals(t, len(result.Rows), 2)
	// row = result.Rows[0]
	// value = row.Value.(float64)
	// goassert.True(t, value == 9)
	// row = result.Rows[1]
	// value = row.Value.(float64)
	// goassert.True(t, value == 1)
}

func TestAdminReduceSumQuery(t *testing.T) {
	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Create a view with a reduce:
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"options":{"raw":true},"views":{"bar": {"map": "function(doc) {if (doc.key && doc.value) emit(doc.key, doc.value);}", "reduce": "_sum"}}}`)
	assertStatus(t, response, http.StatusCreated)

	for i := 0; i < 9; i++ {
		// Create docs:
		response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", i), `{"key":"A", "value":1}`)
		assertStatus(t, response, http.StatusCreated)

	}
	response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", 10), `{"key":"B", "value":99}`)
	assertStatus(t, response, http.StatusCreated)

	var result sgbucket.ViewResult

	// Admin view query:
	result, err := rt.WaitForNAdminViewResults(1, "/db/_design/foo/_view/bar?reduce=true")
	assert.NoError(t, err, "Unexpected error")

	// we should get 1 row with the reduce result
	require.Len(t, result.Rows, 1)
	row := result.Rows[0]
	value := row.Value.(float64)
	assert.Equal(t, 108.0, value)
}

func TestAdminGroupReduceSumQuery(t *testing.T) {
	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Create a view with a reduce:
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"options":{"raw":true},"views":{"bar": {"map": "function(doc) {if (doc.key && doc.value) emit(doc.key, doc.value);}", "reduce": "_sum"}}}`)
	assertStatus(t, response, http.StatusCreated)

	for i := 0; i < 9; i++ {
		// Create docs:
		response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", i), `{"key":"A", "value":1}`)
		assertStatus(t, response, http.StatusCreated)

	}
	response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", 10), `{"key":"B", "value":99}`)
	assertStatus(t, response, http.StatusCreated)

	var result sgbucket.ViewResult

	// Admin view query:
	result, err := rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/bar?reduce=true&group=true")
	assert.NoError(t, err, "Unexpected error")

	// we should get 2 row with the reduce result
	require.Len(t, result.Rows, 2)
	row := result.Rows[1]
	value := row.Value.(float64)
	assert.Equal(t, 99.0, value)
}

// Reproduces SG #3344.  Original issue only reproducible against Couchbase server (non-walrus)
func TestViewQueryWithKeys(t *testing.T) {

	if base.UnitTestUrlIsWalrus() {
		t.Skip("Walrus does not support the 'keys' view parameter")
	}

	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Create a view
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views":{"bar": {"map": "function(doc) {emit(doc.key, doc.value);}"}}}`)
	assertStatus(t, response, http.StatusCreated)
	assert.NoError(t, rt.WaitForViewAvailable("/db/_design/foo/_view/bar"), "Error waiting for view availability")

	// Create a doc
	response = rt.SendAdminRequest(http.MethodPut, "/db/query_with_keys", `{"key":"channel_a", "value":99}`)
	assertStatus(t, response, http.StatusCreated)

	// Admin view query:
	viewUrlPath := "/db/_design/foo/_view/bar?keys=%5B%22channel_a%22%5D&stale=false"
	response = rt.SendAdminRequest(http.MethodGet, viewUrlPath, ``)
	assertStatus(t, response, http.StatusOK) // Query string was parsed properly

	var result sgbucket.ViewResult
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 1)

	// Ensure that query for non-existent keys returns no rows
	viewUrlPath = "/db/_design/foo/_view/bar?keys=%5B%22channel_b%22%5D&stale=false"
	response = rt.SendAdminRequest(http.MethodGet, viewUrlPath, ``)
	assertStatus(t, response, http.StatusOK) // Query string was parsed properly

	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 0)
}

func TestViewQueryWithCompositeKeys(t *testing.T) {

	if base.UnitTestUrlIsWalrus() {
		t.Skip("Walrus does not support the 'keys' view parameter")
	}

	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Create a view
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views":{"composite_key_test": {"map": "function(doc) {emit([doc.key, doc.seq], doc.value);}"}}}`)
	assertStatus(t, response, http.StatusCreated)
	assert.NoError(t, rt.WaitForViewAvailable("/db/_design/foo/_view/composite_key_test"), "Error waiting for view availability")

	// Create a doc
	response = rt.SendAdminRequest(http.MethodPut, "/db/doc_composite_key", `{"key":"channel_a", "seq":55, "value":99}`)
	assertStatus(t, response, http.StatusCreated)

	// Admin view query:
	//   keys:[["channel_a", 55]]
	viewUrlPath := "/db/_design/foo/_view/composite_key_test?keys=%5B%5B%22channel_a%22%2C%2055%5D%5D&stale=false"
	response = rt.SendAdminRequest(http.MethodGet, viewUrlPath, ``)
	assertStatus(t, response, http.StatusOK)
	var result sgbucket.ViewResult
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 1)

	// Ensure that a query for non-existent key returns no rows
	viewUrlPath = "/db/_design/foo/_view/composite_key_test?keys=%5B%5B%22channel_b%22%2C%2055%5D%5D&stale=false"
	response = rt.SendAdminRequest(http.MethodGet, viewUrlPath, ``)
	assertStatus(t, response, http.StatusOK)

	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 0)
}

func TestViewQueryWithIntKeys(t *testing.T) {

	if base.UnitTestUrlIsWalrus() {
		t.Skip("Walrus does not support the 'keys' view parameter")
	}

	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Create a view
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"views":{"int_key_test": {"map": "function(doc) {emit(doc.seq, doc.value);}"}}}`)
	assertStatus(t, response, http.StatusCreated)
	assert.NoError(t, rt.WaitForViewAvailable("/db/_design/foo/_view/int_key_test"), "Error waiting for view availability")

	// Create a doc
	response = rt.SendAdminRequest(http.MethodPut, "/db/doc_int_key", `{"key":"channel_a", "seq":55, "value":99}`)
	assertStatus(t, response, http.StatusCreated)

	// Admin view query:
	//   keys:[55,65]
	viewUrlPath := "/db/_design/foo/_view/int_key_test?keys=%5B55,65%5D&stale=false"
	response = rt.SendAdminRequest(http.MethodGet, viewUrlPath, ``)
	assertStatus(t, response, http.StatusOK)
	var result sgbucket.ViewResult
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 1)

	// Ensure that a query for non-existent key returns no rows
	//   keys:[65,75]
	viewUrlPath = "/db/_design/foo/_view/int_key_test?keys=%5B65,75%5D&stale=false"
	response = rt.SendAdminRequest(http.MethodGet, viewUrlPath, ``)
	assertStatus(t, response, http.StatusOK)

	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &result))
	require.Len(t, result.Rows, 0)
}

func TestAdminGroupLevelReduceSumQuery(t *testing.T) {
	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Create a view with a reduce:
	response := rt.SendAdminRequest(http.MethodPut, "/db/_design/foo", `{"options":{"raw":true},"views":{"bar": {"map": "function(doc) {if (doc.key && doc.value) emit(doc.key, doc.value);}", "reduce": "_sum"}}}`)
	assertStatus(t, response, http.StatusCreated)

	for i := 0; i < 9; i++ {
		// Create docs:
		response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", i), fmt.Sprintf(`{"key":["A",{},%v], "value":1}`, i))
		assertStatus(t, response, http.StatusCreated)

	}
	response = rt.SendRequest(http.MethodPut, fmt.Sprintf("/db/doc%v", 10), `{"key":["B",4,1], "value":99}`)
	assertStatus(t, response, http.StatusCreated)

	var result sgbucket.ViewResult

	// Admin view query:
	result, err := rt.WaitForNAdminViewResults(2, "/db/_design/foo/_view/bar?reduce=true&group_level=2")
	assert.NoError(t, err, "Unexpected error")

	// we should get 2 row with the reduce result
	require.Len(t, result.Rows, 2)
	row := result.Rows[1]
	value := row.Value.(float64)
	assert.Equal(t, 99.0, value)
}

func TestPostInstallCleanup(t *testing.T) {
	rtConfig := RestTesterConfig{SyncFn: `function(doc) {channel(doc.channel)}`}
	rt := NewRestTester(t, &rtConfig)
	defer rt.Close()

	// Cleanup existing design docs
	_, err := rt.GetDatabase().RemoveObsoleteDesignDocs(false)
	require.NoError(t, err)

	bucket := rt.Bucket()
	mapFunction := `function (doc, meta) { emit(); }`
	// Create design docs in obsolete format
	err = bucket.PutDDoc(db.DesignDocSyncGatewayPrefix, sgbucket.DesignDoc{
		Views: sgbucket.ViewMap{
			"channels": sgbucket.ViewDef{Map: mapFunction},
		},
	})
	assert.NoError(t, err, "Unable to create design doc (DesignDocSyncGatewayPrefix)")

	err = bucket.PutDDoc(db.DesignDocSyncHousekeepingPrefix, sgbucket.DesignDoc{
		Views: sgbucket.ViewMap{
			"all_docs": sgbucket.ViewDef{Map: mapFunction},
		},
	})
	assert.NoError(t, err, "Unable to create design doc (DesignDocSyncHousekeepingPrefix)")

	// Run post-upgrade in preview mode
	var postUpgradeResponse PostUpgradeResponse
	response := rt.SendAdminRequest(http.MethodPost, "/_post_upgrade?preview=true", "")
	assertStatus(t, response, http.StatusOK)
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &postUpgradeResponse), "Error unmarshalling post_upgrade response")
	assert.True(t, postUpgradeResponse.Preview)
	require.Lenf(t, postUpgradeResponse.Result["db"].RemovedDDocs, 2, "Response: %#v", postUpgradeResponse)

	// Run post-upgrade in non-preview mode
	postUpgradeResponse = PostUpgradeResponse{}
	response = rt.SendAdminRequest(http.MethodPost, "/_post_upgrade", "")
	assertStatus(t, response, http.StatusOK)
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &postUpgradeResponse), "Error unmarshalling post_upgrade response")
	assert.False(t, postUpgradeResponse.Preview)
	require.Len(t, postUpgradeResponse.Result["db"].RemovedDDocs, 2)

	// Run post-upgrade in preview mode again, expect no results for database
	postUpgradeResponse = PostUpgradeResponse{}
	response = rt.SendAdminRequest(http.MethodPost, "/_post_upgrade?preview=true", "")
	assertStatus(t, response, http.StatusOK)
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &postUpgradeResponse), "Error unmarshalling post_upgrade response")
	assert.True(t, postUpgradeResponse.Preview)
	require.Len(t, postUpgradeResponse.Result["db"].RemovedDDocs, 0)

	// Run post-upgrade in non-preview mode again, expect no results for database
	postUpgradeResponse = PostUpgradeResponse{}
	response = rt.SendAdminRequest(http.MethodPost, "/_post_upgrade", "")
	assertStatus(t, response, http.StatusOK)
	assert.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &postUpgradeResponse), "Error unmarshalling post_upgrade response")
	assert.False(t, postUpgradeResponse.Preview)
	require.Len(t, postUpgradeResponse.Result["db"].RemovedDDocs, 0)
}

func TestViewQueryWrappers(t *testing.T) {
	rt := NewRestTester(t, nil)
	defer rt.Close()

	rt.ServerContext().Database("db").SetUserViewsEnabled(true)

	response := rt.SendAdminRequest(http.MethodPut, "/db/admindoc", `{"value":"foo"}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendAdminRequest(http.MethodPut, "/db/admindoc2", `{"value":"foo"}`)
	assertStatus(t, response, http.StatusCreated)
	response = rt.SendAdminRequest(http.MethodPut, "/db/userdoc", `{"value":"foo", "channels": ["userchannel"]}`)
	assertStatus(t, response, http.StatusCreated)

	response = rt.SendAdminRequest(http.MethodPut, "/db/_design/foodoc", `{"views": {"foobarview": {"map": "function(doc, meta) {if (doc.value == \"foo\") {emit(doc.key, null);}}"}}}`)
	assert.Equal(t, http.StatusCreated, response.Code)

	result, err := rt.WaitForNAdminViewResults(3, "/db/_design/foodoc/_view/foobarview")
	assert.NoError(t, err)
	assert.Equal(t, 3, result.Len())

	a := rt.ServerContext().Database("db").Authenticator()
	testUser, err := a.NewUser("testUser", "password", channels.SetOf(t, "userchannel"))
	assert.NoError(t, err)
	err = a.Save(testUser)
	assert.NoError(t, err)

	result, err = rt.WaitForNUserViewResults(1, "/db/_design/foodoc/_view/foobarview", testUser, "password")
	assert.NoError(t, err)
	assert.Equal(t, 1, result.Len())
	assert.Equal(t, "userdoc", result.Rows[0].ID)
}

func TestViewQueryWithXattrAndNonXattr(t *testing.T) {

	if base.UnitTestUrlIsWalrus() {
		t.Skip("Test doesn't work with Walrus")
	}

	if !base.TestUseXattrs() {
		t.Skip("Test requires xattrs to be enabled")
	}

	rtConfig := &RestTesterConfig{
		SyncFn: `function(doc, oldDoc) { channel(doc.channels) }`,
		DatabaseConfig: &DbConfig{
			AutoImport: false,
		},
	}
	rt := NewRestTester(t, rtConfig)
	defer rt.Close()

	response := rt.SendAdminRequest("PUT", "/db/doc1", `{"value":"foo"}`)
	assertStatus(t, response, http.StatusCreated)

	//Document with sync data in body
	body := `{"_sync": { "rev": "1-fc2cf22c5e5007bd966869ebfe9e276a", "sequence": 2, "recent_sequences": [ 2 ], "history": { "revs": [ "1-fc2cf22c5e5007bd966869ebfe9e276a" ], "parents": [ -1], "channels": [ null ] }, "cas": "","value_crc32c": "", "time_saved": "2019-04-10T12:40:04.490083+01:00" }, "value": "foo"}`
	ok, err := rt.Bucket().Add("doc2", 0, []byte(body))
	assert.True(t, ok)
	assert.NoError(t, err)

	//Should handle the case where there is no sync data
	body = `{"value": "foo"}`
	ok, err = rt.Bucket().Add("doc3", 0, []byte(body))
	assert.True(t, ok)
	assert.NoError(t, err)

	//Document with sync data in xattr
	response = rt.SendAdminRequest("PUT", "/db/_design/foodoc", `{"views": {"foobarview": {"map": "function(doc, meta) {if (doc.value == \"foo\") {emit(doc.key, null);}}"}}}`)
	assert.Equal(t, 201, response.Code)

	result, err := rt.WaitForNAdminViewResults(2, "/db/_design/foodoc/_view/foobarview")
	assert.NoError(t, err)
	require.Equal(t, 2, len(result.Rows))
	assert.Contains(t, "doc1", result.Rows[0].ID)
	assert.Contains(t, "doc2", result.Rows[1].ID)
}


text:
class RawFile
{
public:
    RawFile(const std::string & filePath);
    virtual ~RawFile();

    const char * data() const;
    size_t size() const;

    bool isValid() const;
    const std::string & filePath() const;

    // Note: this is intentionally not implemented - but fixes MSVC12 C4512 warning
    RawFile & operator=(const RawFile & rawFile);

protected:
    bool readFile();
    void readRawData(std::ifstream & ifs);

protected:
    const std::string m_filePath;
    std::vector<char> m_data;

    bool m_valid;

};

redpajama_set_name: RedPajamaGithub


text:
Ext.define('<%= @bundle %>.view.<%= singular_name %>.<%= class_name %>List', {

	extend : 'Base.abstract.entity.ReportGridView',

	xtype : '<%= @bundle.downcase %>_<%= singular_name %>_list',

	store : Ext.create('Ext.data.Store', {

		<%= Hatio::Generators::ReportViewUtil.generateStore(@domain, @out_params) %>,

		autoLoad : false,

		remoteFilter : true,

		// TODO url : shoot.json, method : post
		proxy : {
			type : 'ajax',
			url : <%= @service_url %>,
			format : 'json',
			reader : {
				type : 'json'
			}
		}
	}),

	<%= Hatio::Generators::ReportViewUtil.generateColumns(@domain, @out_params) %>
});


text:
using UnityEngine;
using System;
using System.Collections.Generic;

public class PortalBehaviour : MonoBehaviour {

    public Transform Exit;
    public Color Background = Color.clear;

    [Range(0, 20)]
    public int Recursion = 5;

    [Range(0.1f, 2f)]
    public float ResolutionScale = 0.9f;

    public Cascade[] DistanceResolutionCascades = new Cascade[] {
        new Cascade(0.5f, 1.0f),
        new Cascade(1.0f, 0.9f),
        new Cascade(2.0f, 0.8f),
        new Cascade(5.0f, 0.7f),
        new Cascade(10.0f, 0.6f),
        new Cascade(100.0f, 0.5f),
    };

    public float[] RecursionResolutionMultipliers = new float[] {
        0.8f,
        0.6f,
        0.4f
    };

    public float MaxPortalRenderDistance = 100;
    public float MaxRecursionRenderDistance = 50;

    [Range(0.0f, 2.0f)]
    public float MaskScale = 1.1f;

    [Range(128, 2048)]
    public int MinRenderTargetWidth = 256;

    [Range(128, 2048)]
    public int MinRenderTargetHeight = 256;

    [Range(128, 4096)]
    public int MaxRenderTargetWidth = 2048;

    [Range(128, 4096)]
    public int MaxRenderTargetHeight = 2048;

    static int total = 0;
    static bool hideInHierarchy = true;
    int layer;

    PortalMainViewingCameraBehaviour mainViewingCamera;
    PortalCameraHeadBehaviour[] portalCameras;
    List<Camera> portalLeftEyesCache;
    List<Camera> portalRightEyesCache;
    List<GameObject> cameraBackgrounds;
    GameObject cameraCutout;
    GameObject outsides;
    GameObject insides;
    PortalTeleporterBehaviour teleporter;
    PortalControllerBehaviour controller;

    public static int TotalPortals {
        get { return total; }
    }

    public static bool HideInHierarchy {
        get { return hideInHierarchy; }
    }

    public int Layer {
        get { return layer; }
    }

    public PortalMainViewingCameraBehaviour MainViewingCamera {
        get { return mainViewingCamera; }
    }

    public PortalCameraHeadBehaviour[] PortalCameras {
        get { return portalCameras; }
    }

    public List<GameObject> CameraBackgrounds {
        get { return cameraBackgrounds; }
    }

    public GameObject CameraCutout {
        get { return cameraCutout; }
    }

    public GameObject Outsides {
        get { return outsides; }
    }

    public GameObject Insides {
        get { return insides; }
    }

    public PortalTeleporterBehaviour Teleporter {
        get { return teleporter; }
    }

    public PortalControllerBehaviour Controller {
        get { return controller; }
    }

    void Awake() {
        layer = total++;

        mainViewingCamera = GetMainViewingCamera();
        portalCameras = new PortalCameraHeadBehaviour[Recursion];
        portalLeftEyesCache = new List<Camera>();
        portalRightEyesCache = new List<Camera>();
        cameraBackgrounds = new List<GameObject>();

        for (int i = 0; i < portalCameras.Length; i++) {
            Transform viewer = i == 0 ? mainViewingCamera.transform : portalCameras[i - 1].transform;
            int depth = portalCameras.Length - i - 1;

            PortalCameraHeadBehaviour camera = PortalCameraHeadBehaviour.Create(this, viewer, i, depth);
            camera.hideFlags = hideInHierarchy ? HideFlags.None : HideFlags.HideAndDontSave;
            portalCameras[i] = camera;

            portalLeftEyesCache.Add(camera.LeftEye.EyeCamera);
            portalRightEyesCache.Add(camera.RightEye.EyeCamera);

            GameObject background = PortalCameraHeadBehaviour.CreateCameraBackgroundMask(this, camera.transform);
            background.hideFlags = hideInHierarchy ? HideFlags.None : HideFlags.HideAndDontSave;
            cameraBackgrounds.Add(background);
        }

        cameraCutout = PortalCameraHeadBehaviour.CreateCameraCutoutMask(this, PortalCameras[0].transform);
        cameraCutout.hideFlags = hideInHierarchy ? HideFlags.None : HideFlags.HideAndDontSave;

        outsides = PortalChromeBehaviour.CreateOutsidesGameObject(this);
        outsides.hideFlags = hideInHierarchy ? HideFlags.None : HideFlags.HideAndDontSave;

        insides = PortalChromeBehaviour.CreateInsidesGameObject(this);
        insides.hideFlags = hideInHierarchy ? HideFlags.None : HideFlags.HideAndDontSave;

        teleporter = PortalTeleporterBehaviour.Create(this);
        teleporter.hideFlags = hideInHierarchy ? HideFlags.None : HideFlags.HideAndDontSave;

        controller = PortalControllerBehaviour.Create(this);
        controller.hideFlags = hideInHierarchy ? HideFlags.None : HideFlags.HideAndDontSave;
    }

    public PortalMainViewingCameraBehaviour GetMainViewingCamera() {
        PortalMainViewingCameraBehaviour behaviour = Camera.main.GetComponent<PortalMainViewingCameraBehaviour>();
        if (behaviour == null) {
            behaviour = Camera.main.gameObject.AddComponent<PortalMainViewingCameraBehaviour>();
        }
        return behaviour;
    }

    public bool IsFirstPortalCameraToRender(Camera camera) {
        return portalLeftEyesCache.FindLast(c => c.isActiveAndEnabled) == camera;
    }

    public bool IsPortalCameraForLeftEye(Camera camera) {
        return portalLeftEyesCache.Contains(camera);
    }

    public bool IsPortalCameraForRightEye(Camera camera) {
        return portalRightEyesCache.Contains(camera);
    }

    public int IndexOfCurrentPortalCamera() {
        return Camera.current.GetComponent<PortalCameraForEyeBehaviour>().Index;
    }

    public static GameObject CreateGameObject(string name, Transform exit = null) {
        GameObject container = new GameObject(name);
        PortalBehaviour behaviour = container.AddComponent<PortalBehaviour>();
        behaviour.Exit = exit;
        return container;
    }

    public static GameObject[] CreatePair() {
        GameObject first = CreateGameObject("PortalA");
        GameObject second = CreateGameObject("PortalB");

        first.GetComponent<PortalBehaviour>().Exit = second.transform;
        second.GetComponent<PortalBehaviour>().Exit = first.transform;

        return new GameObject[] { first, second };
    }
}


text:
[![Godoc](https://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://godoc.org/github.com/coreos/etcd/clientv3)

`etcd/clientv3` is the official Go etcd client for v3.

## Install

```bash
go get github.com/coreos/etcd/clientv3
```

## Get started

Create client using `clientv3.New`:

```go
cli, err := clientv3.New(clientv3.Config{
	Endpoints:   []string{"localhost:2379", "localhost:22379", "localhost:32379"},
	DialTimeout: 5 * time.Second,
})
if err != nil {
	// handle error!
}
defer cli.Close()
```

etcd v3 uses [`gRPC`](http://www.grpc.io) for remote procedure calls. And `clientv3` uses
[`grpc-go`](https://github.com/grpc/grpc-go) to connect to etcd. Make sure to close the client after using it.
If the client is not closed, the connection will have leaky goroutines. To specify client request timeout,
pass `context.WithTimeout` to APIs:

```go
ctx, cancel := context.WithTimeout(context.Background(), timeout)
resp, err := cli.Put(ctx, "sample_key", "sample_value")
cancel()
if err != nil {
    // handle error!
}
// use the response
```

For full compatibility, it is recommended to vendor builds using etcd's vendored packages, using tools like `golang/dep`, as in [vendor directories](https://golang.org/cmd/go/#hdr-Vendor_Directories).

## Error Handling

etcd client returns 2 types of errors:

1. context error: canceled or deadline exceeded.
2. gRPC error: see [api/v3rpc/rpctypes](https://godoc.org/github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes).

Here is the example code to handle client errors:

```go
resp, err := cli.Put(ctx, "", "")
if err != nil {
	switch err {
	case context.Canceled:
		log.Fatalf("ctx is canceled by another routine: %v", err)
	case context.DeadlineExceeded:
		log.Fatalf("ctx is attached with a deadline is exceeded: %v", err)
	case rpctypes.ErrEmptyKey:
		log.Fatalf("client-side error: %v", err)
	default:
		log.Fatalf("bad cluster endpoints, which are not etcd servers: %v", err)
	}
}
```

## Metrics

The etcd client optionally exposes RPC metrics through [go-grpc-prometheus](https://github.com/grpc-ecosystem/go-grpc-prometheus). See the [examples](https://github.com/coreos/etcd/blob/master/clientv3/example_metrics_test.go).

## Namespacing

The [namespace](https://godoc.org/github.com/coreos/etcd/clientv3/namespace) package provides `clientv3` interface wrappers to transparently isolate client requests to a user-defined prefix.

## Request size limit

Client request size limit is configurable via `clientv3.Config.MaxCallSendMsgSize` and `MaxCallRecvMsgSize` in bytes. If none given, client request send limit defaults to 2 MiB including gRPC overhead bytes. And receive limit defaults to `math.MaxInt32`.

## Examples

More code examples can be found at [GoDoc](https://godoc.org/github.com/coreos/etcd/clientv3).


text:
<?php namespace Ipunkt\Subscriptions\Subscription\Events;

use Ipunkt\Subscriptions\Subscription\Period;

/**
 * Class SubscriptionWasPaid
 *
 * Event will be fired when a subscription was paid (a period was paid)
 *
 * @package Ipunkt\Subscriptions\Subscription\Events
 */
class SubscriptionWasPaid
{
	/**
	 * paid period
	 *
	 * @var \Ipunkt\Subscriptions\Subscription\Period
	 */
	public $period;

	/**
	 * paid subscription
	 *
	 * @var \Ipunkt\Subscriptions\Subscription\Subscription
	 */
	public $subscription;

	/**
	 * @param \Ipunkt\Subscriptions\Subscription\Period $period
	 */
	public function __construct(Period $period)
	{
		$this->period = $period;
		$this->subscription = $period->subscription;
	}
}


text:
<!doctype html>
<html>
  <head>
    <title>Current Resource FSM</title>
  </head>
  <body>
    <img id="fsmimg"/>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>

      String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
      };

      var socket = io();
      socket.on('fsm image', function(msg){
        if (msg.endsWith('.png')) {
          $("#fsmimg").attr('src','http://localhost:3333/fsmimages/' + msg);
        }
      });

    </script>
  </body>
</html>


text:
package org.jeewx.api.coupon.manage.model;

/**
 * 门票。
 *
 * @author mcl
 * @version v1.0
 */
public class ScenicTicket {
	// 基本的卡券数据,见下表,所有卡券通用
	private BaseInfo base_info;
	// 票类型,例如平日全票,套票等
	private String ticket_class;
	// 导览图url。
	private String guide_url;

	public BaseInfo getBase_info() {
		return base_info;
	}

	public void setBase_info(BaseInfo base_info) {
		this.base_info = base_info;
	}

	public String getTicket_class() {
		return ticket_class;
	}

	public void setTicket_class(String ticket_class) {
		this.ticket_class = ticket_class;
	}

	public String getGuide_url() {
		return guide_url;
	}

	public void setGuide_url(String guide_url) {
		this.guide_url = guide_url;
	}

}


text:
<?php
    //test ke server
    //user
    $name = 'izinusahasaranaperdagangan';
    $redirect_uri = 'http://usahasarana.pplbandung.biz.tm/login_callback';
    $client_id = 'rcQHD0QUT8xxg8Aj';
    $client_secret = 'LRWXgkS867lPcs26';
    $login = 'http://dukcapil.pplbandung.biz.tm/oauth/authorize?client_id=rcQHD0QUT8xxg8Aj&redirect_uri=http://usahasarana.pplbandung.biz.tm/login_callback&response_type=code';

    //admin
    $name_admin = 'izinusahasaranaperdaganganadmin';
    $redirect_uri_admin = 'http://usahasarana.pplbandung.biz.tm/login_callback_admin';
    $client_id_admin = 'kr2iEByIos7y3GVP';
    $client_secret_admin = 'CW4tabGeFdgN9fJM';
    $login_admin = 'http://dukcapil.pplbandung.biz.tm/oauth/authorize?client_id=kr2iEByIos7y3GVP&redirect_uri=http://usahasarana.pplbandung.biz.tm/login_callback_admin&response_type=code';

    //test ke localhost
    //user
    $name_local = 'saranaperdaganganlocalhost';
    $client_id_local = 'ulP9hlsW74ahy2ND';
    $redirect_uri_local = 'http://localhost:8000/login_callback';
    $client_secret_local = 'JDPqeCpwEFUY6F4Q';
    $login_local = 'http://dukcapil.pplbandung.biz.tm/oauth/authorize?client_id=ulP9hlsW74ahy2ND&redirect_uri=http://localhost:8000/login_callback&response_type=code';

    //admin
    $name_local_admin = 'saranaperdaganganlocalhostadmin';
    $redirect_uri_local_admin = 'http://localhost:8000/login_callback_admin';
    $client_id_local_admin = 'c4Im8zC52L6PR3gW';
    $client_secret_local_admin = 'LUeTMC9YWlg5Y3UH';
    $login_local_admin = 'http://dukcapil.pplbandung.biz.tm/oauth/authorize?client_id=c4Im8zC52L6PR3gW&redirect_uri=http://localhost:8000/login_callback_admin&response_type=code';
?>


text: A simple css template for recreating the text user interfaces of yesteryear on the web.


text: MumineenCalendar::Application.config.session_store :cookie_store, key: '_mumineen_calendar_session'


text:
#ifndef _INTLTESTDECIMALFORMATAPI
#define _INTLTESTDECIMALFORMATAPI

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

#include "unicode/unistr.h"
#include "intltest.h"

class IntlTestDecimalFormatAPI: public IntlTest {
    void runIndexedTest( int32_t index, UBool exec, const char* &name, char* par = NULL );

public:
    /**
     * Tests basic functionality of various API functions for DecimalFormat
     **/
    void testAPI(/*char *par*/);
    void testRounding(/*char *par*/);
    void testRoundingInc(/*char *par*/);
    void TestCurrencyPluralInfo();
    void TestScale();
    void TestFixedDecimal();
private:
    /*Helper functions */
    void verify(const UnicodeString& message, const UnicodeString& got, double expected);
    void verifyString(const UnicodeString& message, const UnicodeString& got, UnicodeString& expected);
};

#endif /* #if !UCONFIG_NO_FORMATTING */

#endif


text:
describe("MySQL.Communication", function() {

    var target;

    beforeEach(function() {
        target = new MySQL.Communication();
    });

    it("can connect", function() {
        target.setSocketImpl({
            connect: function(host, port, callback) {
                expect("host1").toEqual(host);
                expect(1234).toEqual(port);
                callback("result1");
            }
        });
        target.connect("host1", 1234, function(actual) {
            expect("result1").toEqual(actual);
        });
    });

    it("can disconnect", function() {
        target.setSocketImpl({
            disconnect: function(callback) {
                callback("result1");
            }
        });
        target.disconnect(function(actual) {
            expect("result1").toEqual(actual);
        });
    });

    it("can check whether is connected", function() {
        target.setSocketImpl({
            isConnected: function() {
                return true;
            }
        });
        expect(true).toEqual(target.isConnected());
    });

    it("can read packet", function() {
        target.setSocketImpl({
            read: function(length, callback, fatalCallback) {
                var data;
                if (length == 3) {
                    data = new Uint8Array([0x05, 0, 0]);
                    callback({
                        resultCode: 0,
                        data: data
                    });
                } else if (length == 1) {
                    data = new Uint8Array([0x01]);
                    callback({
                        resultCode: 0,
                        data: data
                    });
                } else {
                    data = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90]);
                    callback({
                        resultCode: 0,
                        data: data
                    });
                }
            }
        });
        target.readPacket(function(actual) {
            expect(5).toEqual(actual.dataLength);
            expect(1).toEqual(actual.sequenceNumber);
            var expected = [0x12, 0x34, 0x56, 0x78, 0x90];
            var actualArray = new Uint8Array(actual.data);
            for (var i = 0; i < expected.length; i++) {
                expect(expected[i]).toEqual(actualArray[i]);
            }
        }, function(){});
    });

    it("can read plural packets", function() {
        var SocketImplMock = function() {
            this.data = [
                0x01, 0, 0, 0, 0x41,
                0x02, 0, 0, 0x01, 0x41, 0x42,
                0x03, 0, 0, 0x02, 0x41, 0x42, 0x43
            ];
            this.pos = 0;
        };
        SocketImplMock.prototype.read = function(length, callback, fatalCallback) {
            var slice = this.data.slice(this.pos, this.pos + length);
            var array = new Uint8Array(slice);
            this.pos += length;
            callback({resultCode: 0, data: array.buffer});
        };
        target.setSocketImpl(new SocketImplMock());
        target.readPluralPackets(3, function(actual) {
            expect(3).toEqual(actual.length);
            var expected = [0x41];
            var actualArray = new Uint8Array(actual[0].data);
            for (var i = 0; i < expected.length; i++) {
                expect(expected[i]).toEqual(actualArray[i]);
            }
            expected = [0x41, 0x42];
            actualArray = new Uint8Array(actual[1].data);
            for (i = 0; i < expected.length; i++) {
                expect(expected[i]).toEqual(actualArray[i]);
            }
            expected = [0x41, 0x42, 0x43];
            actualArray = new Uint8Array(actual[2].data);
            for (i = 0; i < expected.length; i++) {
                expect(expected[i]).toEqual(actualArray[i]);
            }
        }, function() {});
    });

    it("can write packet", function() {
        var socketImpl = {
            write: function(packet, callback, errorCallback) {
                expect(3).toEqual(packet.dataLength);
                expect(2).toEqual(packet.sequenceNumber);
                var expected = [0x41, 0x42, 0x43];
                var actualArray = new Uint8Array(packet.data);
                for (var i = 0; i < expected.length; i++) {
                    expect(expected[i]).toEqual(actualArray[i]);
                }
                callback(5);
            }
        };
        target.setSocketImpl(socketImpl);
        var data = new Uint8Array([0x41, 0x42, 0x43]);
        var packet = new MySQL.Packet(2, data.buffer);
        target.writePacket(packet, function(result) {
            expect(5).toEqual(result);
        }, function() {});
    });

    it("can increase sequence number", function() {
        target.incrementSequenceNumber(5);
        expect(6).toEqual(target.nextSequenceNumber);
        target.incrementSequenceNumber(255);
        expect(0).toEqual(target.nextSequenceNumber);
    });

    it("can create packet", function() {
        var data = new Uint8Array([0x41, 0x42, 0x43]);
        target.nextSequenceNumber = 255;
        var actual = target.createPacket(data.buffer);
        expect(255).toEqual(actual.sequenceNumber);
        expect(3).toEqual(actual.dataLength);
        var actualArray = new Uint8Array(actual.data);
        for (var i = 0; i < data.length; i++) {
            expect(data[i]).toEqual(actualArray[i]);
        }
    });

    it("can reset sequence number", function() {
        target.nextSequenceNumber = 100;
        target.resetSequenceNumber();
        expect(0).toEqual(target.nextSequenceNumber);
    });

    it("can establish TLS", function() {
        var socketImpl = {
            establishTls: function(ca, checkCN, callback, fatalCallback) {
                expect("ca1").toEqual(ca);
                expect(true).toEqual(checkCN);
                callback();
            }
        };
        target.setSocketImpl(socketImpl);
        target.establishTls("ca1", true, function() {}, function() {});
    });

});


text:
package com.amazonaws.services.managedblockchain.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.managedblockchain.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * NodeFabricAttributesMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class NodeFabricAttributesMarshaller {

    private static final MarshallingInfo<String> PEERENDPOINT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PeerEndpoint").build();
    private static final MarshallingInfo<String> PEEREVENTENDPOINT_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PeerEventEndpoint").build();

    private static final NodeFabricAttributesMarshaller instance = new NodeFabricAttributesMarshaller();

    public static NodeFabricAttributesMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(NodeFabricAttributes nodeFabricAttributes, ProtocolMarshaller protocolMarshaller) {

        if (nodeFabricAttributes == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(nodeFabricAttributes.getPeerEndpoint(), PEERENDPOINT_BINDING);
            protocolMarshaller.marshall(nodeFabricAttributes.getPeerEventEndpoint(), PEEREVENTENDPOINT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
#rdfstore-js [![Build Status](https://travis-ci.org/antoniogarrote/rdfstore-js.svg?branch=master)](https://travis-ci.org/antoniogarrote/rdfstore-js) [![Join the chat at https://gitter.im/antoniogarrote/rdfstore-js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/antoniogarrote/rdfstore-js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## Important Note

Many features present in versions 0.8.X have been removed in the 0.9.X. Some of them, will be added in the next versions, other like the MongoDB backend will be discarded.
Please read this README file carefully to find the current set of features.

## Table of Contents

- [Introduction](#introduction)
- [Documentation](#documentation)
- [SPARQL support](#sparql-support)
- [Installation](#installation)
- [Building](#building)
- [Tests](#tests)
- [API](#api)
	- [Store creation](#store-creation)
	- [Query execution](#query-execution)
	- [Construct queries RDF Interfaces API](#construct-queries-rdf-interfaces-api)
	- [Loading remote graphs](#loading-remote-graphs)
	- [High level interface](#high-level-interface)
	- [RDF Interface API](#rdf-interface-api)
	- [Default Prefixes](#default-prefixes)
	- [JSON-LD Support](#json-ld-support)
	- [Events API](#events-api)
	- [Custom Filter Functions](#custom-filter-functions)
	- [Persistence](#persistence)
- [Dependencies](#dependencies)
- [Frontend](#frontend)
- [Contributing](#contributing)
- [Author](#author)
- [License](#license)

## Introduction

rdfstore-js is a pure Javascript implementation of a RDF graph store with support for the SPARQL query and data manipulation language.
```javascript
var rdfstore = require('rdfstore');

rdfstore.create(function(err, store) {
  store.execute('LOAD <http://dbpedia.org/resource/Tim_Berners-Lee> INTO GRAPH <http://example.org/people>', function() {

	store.setPrefix('dbp', 'http://dbpedia.org/resource/');

	store.node(store.rdf.resolve('dbp:Tim_Berners-Lee'),  "http://example.org/people", function(err, graph) {

	  var peopleGraph = graph.filter(store.rdf.filters.type(store.rdf.resolve("foaf:Person")));

	  store.execute('PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\
					 PREFIX foaf: <http://xmlns.com/foaf/0.1/>\
					 PREFIX : <http://example.org/>\
					 SELECT ?s FROM NAMED :people { GRAPH ?g { ?s rdf:type foaf:Person } }',
					 function(err, results) {

					   console.log(peopleGraph.toArray()[0].subject.valueOf() === results[0].s.value);

					 });
	});

  });
});
```

rdfstore-js can be executed in a web browser or can be included as a library in a node.js application. It can also be executed as a stand-alone SPARQL end-point accepting SPARQL RDF Protocol HTTP requests. Go to the bottom of this page to find some application examples using the library.

The current implementation is far from complete but it already passes all the test cases for the SPARQL 1.0 query language and supports data manipulation operations from the SPARQL 1.1/Update version of the language.

Some other features included in the library are the following:

- SPARQL 1.0 support
- SPARQL 1.1/Update support
- Partial SPARQL 1.1 query support
- JSON-LD parser
- Turtle/N3 parser
- W3C RDF Interfaces API
- RDF graph events API
- Custom filter functions
- Browser persistence using IndexedDB

## Documentation

Documentation for the store can be found [here](http://antoniogarrote.github.com/rdfstore-js/doc/index.html).

## SPARQL support

rdfstore-js supports at the moment SPARQL 1.0 and most of SPARQL 1.1/Update.
Only some parts of SPARQL 1.1 query have been implemented yet.

This is a list of the different kind of queries currently implemented:

- SELECT queries
- UNION, OPTIONAL clauses
- NAMED GRAPH identifiers
- LIMIT, OFFSET
- ORDER BY clauses
- SPARQL 1.0 filters and builtin functions
- variable aliases
- variable aggregation: MAX, MIN, COUNT, AVG, SUM functions
- GROUP BY clauses
- DISTINCT query modifier
- CONSTRUCT queries
- ASK queries
- INSERT DATA queries
- DELETE DATA queries
- DELETE WHERE queries
- WITH/DELETE/INSERT/WHERE queries
- LOAD queries
- CREATE GRAPH clauses
- DROP DEFAULT/NAMED/ALL/GRAPH clauses
- CLEAR DEFAULT/NAMED/ALL/Graph clauses
- FILTER EXISTS / NOT EXISTS operators
- BIND
- FILTER IN / NOT IN operators

##Installation

The library can be installed using NPM:

```bash
$ npm install rdfstore
```

The library can also be installed via bower using a global module:

```bash
$ bower install rdfstore
```

##Building

Before running the build script, you must install JavaScript dependencies with [npm](https://npmjs.org/doc/install.html) (`npm` is shipped with [node](http://nodejs.org/download/)):

```bash
$ npm install
```

The library can be built using gulp:

```bash
$ gulp
```

The browser version can be built using the 'browser' gulp target:

```bash
$ gulp browser
```

## Tests

To execute the whole test suite of the library, including the DAWG
test cases for SPARQL 1.0 and the test cases for SPARQL 1.1
implemented at the moment, a gulp target can be executed:

```bash
$ gulp specs
```

Additionally, there are some smoke tests for both browser versions that can be found ithe 'spec/browser'' directory.

## API

This is a small overview of the rdfstore-js API.

###Store creation

```javascript
//nodejs only
var rdfstore = require('rdfstore');

// in the browser the rdfstore object
// is already defined

// alt 1
rdfstore.create(function(err, store) {
  // the new store is ready
});

// alt 2
new rdfstore.Store(function(err, store) {
  // the new store is ready
});
```

###Query execution

```javascript
// simple query execution
store.execute("SELECT * { ?s ?p ?o }", function(err, results){
  if(!err) {
	// process results
	if(results[0].s.token === 'uri') {
	  console.log(results[0].s.value);
	}
  }
});

// execution with an explicit default and named graph

var defaultGraph = [{'token':'uri', 'value': graph1}, {'token':'uri', 'value': graph2}, ...];
var namedGraphs  = [{'token':'uri', 'value': graph3}, {'token':'uri', 'value': graph4}, ...];

store.executeWithEnvironment("SELECT * { ?s ?p ?o }",defaultGraph,
  namedGraphs, function(err, results) {
  if(err) {
	// process results
  }
});
```

###Construct queries RDF Interfaces API

```javascript
var query = "CONSTRUCT { <http://example.org/people/Alice> ?p ?o } \
			 WHERE { <http://example.org/people/Alice> ?p ?o  }";

store.execute(query, function(err, graph){
  if(graph.some(store.rdf.filters.p(store.rdf.resolve('foaf:name')))) {
	nameTriples = graph.match(null,
							  store.rdf.createNamedNode(rdf.resolve('foaf:name')),
							  null);

	nameTriples.forEach(function(triple) {
	  console.log(triple.object.valueOf());
	});
  }
});
```

###Loading remote graphs

rdfstore-js will try to retrieve remote RDF resources across the network when a 'LOAD' SPARQL query is executed.
The node.js build of the library will use regular TCP sockets and perform proper content negotiation. It will also follow a limited number of redirections.
The browser build, will try to perform an AJAX request to retrieve the resource using the correct HTTP headers. Nevertheless, this implementation is subjected to the limitations of the Same Domain Policy implemented in current browsers that prevents cross domain requests. Redirections, even for the same domain, may also fail due to the browser removing the 'Accept' HTTP header of the original request.
rdfstore-js relies in on the jQuery Javascript library to peform cross-browser AJAX requests. This library must be linked in order to exeucte 'LOAD' requests in the browser.

```javascript
store.execute('LOAD <http://dbpedialite.org/titles/Lisp_%28programming_language%29>\
			   INTO GRAPH <lisp>', function(err){
  if(err) {
	var query = 'PREFIX foaf:<http://xmlns.com/foaf/0.1/> SELECT ?o \
				 FROM NAMED <lisp> { GRAPH <lisp> { ?s foaf:page ?o} }';
	store.execute(query, function(err, results) {
	  // process results
	});
  }
})
```

###High level interface

The following interface is a convenience API to work with Javascript code instead of using SPARQL query strings. It is built on top of the RDF Interfaces W3C API.

```javascript
/* retrieving a whole graph as JS Interafce API graph object */

store.graph(graphUri, function(err, graph){
  // process graph
});

/* Exporting a graph to N3 (this function is not part of W3C's API)*/
store.graph(graphUri, function(err, graph){
  var serialized = graph.toNT();
});

/* retrieving a single node in the graph as a JS Interface API graph object */

store.node(subjectUri, function(err, node) {
  //process node
});

store.node(subjectUri, graphUri, function(err, node) {
  //process node
});

/* inserting a JS Interface API graph object into the store */

// inserted in the default graph
store.insert(graph, function(err) {}) ;

// inserted in graphUri
store.insert(graph, graphUri, function(err) {}) ;

/* deleting a JS Interface API graph object into the store */

// deleted from the default graph
store.delete(graph, function(err){});

// deleted from graphUri
store.delete(graph, graphUri, function(err){});

/* clearing a graph */

// clears the default graph
store.clear(function(err){});

// clears a named graph
store.clear(graphUri, function(err){});

/* Parsing and loading a graph */

// loading local data
store.load("text/turtle", turtleString, function(err, results) {});

// loading remote data
store.load('remote', remoteGraphUri, function(err, results) {});

/* Registering a parser for a new media type */

// The parser object must implement a 'parse' function
// accepting the data to parse and a callback function.

store.registerParser("application/rdf+xml", rdXmlParser);
```

###RDF Interface API

The store object includes a 'rdf' object implementing a RDF environment as described in the [RDF Interfaces 1.0](http://www.w3.org/TR/rdf-interfaces/) W3C's working draft.
This object can be used to access to the full RDF Interfaces 1.0 API.

```javascript
var graph = store.rdf.createGraph();
graph.addAction(rdf.createAction(store.rdf.filters.p(store.rdf.resolve("foaf:name")),
								 function(triple){ var name = triple.object.valueOf();
												   var name = name.slice(0,1).toUpperCase()
												   + name.slice(1, name.length);
												   triple.object = store.rdf.createNamedNode(name);
												   return triple;}));

store.rdf.setPrefix("ex", "http://example.org/people/");
graph.add(store.rdf.createTriple( store.rdf.createNamedNode(store.rdf.resolve("ex:Alice")),
								  store.rdf.createNamedNode(store.rdf.resolve("foaf:name")),
								  store.rdf.createLiteral("alice") ));

var triples = graph.match(null, store.rdf.createNamedNode(store.rdf.resolve("foaf:name")), null).toArray();

console.log("worked? "+(triples[0].object.valueOf() === 'Alice'));
```

###Default Prefixes

Default RDF name-spaces can be specified using the *registerDefaultNamespace*. These names will be included automatically in all queries. If the same name-space is specified by the client in the query string the new prefix will shadow the default one.
A collection of common name-spaces like rdf, rdfs, foaf, etc. can be automatically registered using the *registerDefaultProfileNamespace* function.

```javascript
new Store({name:'test', overwrite:true}, function(err,store){
	store.execute('INSERT DATA {  <http://example/person1> <http://xmlns.com/foaf/0.1/name> "Celia" }', function(err){

	   store.registerDefaultProfileNamespaces();

	   store.execute('SELECT * { ?s foaf:name ?name }', function(err,results) {
		   test.ok(results.length === 1);
		   test.ok(results[0].name.value === "Celia");
	   });
	});
});
```

###JSON-LD Support

rdfstore-js implements parsers for Turtle and JSON-LD. The specification of JSON-LD is still an ongoing effort. You may expect to find some inconsistencies between this implementation and the actual specification.

```javascript
		jsonld = {
		  "@context":
		  {
			 "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
			 "xsd": "http://www.w3.org/2001/XMLSchema#",
			 "name": "http://xmlns.com/foaf/0.1/name",
			 "age": {"@id": "http://xmlns.com/foaf/0.1/age", "@type": "xsd:integer" },
			 "homepage": {"@id": "http://xmlns.com/foaf/0.1/homepage", "@type": "xsd:anyURI" },
			 "ex": "http://example.org/people/"
		  },
		  "@id": "ex:john_smith",
		  "name": "John Smith",
		  "age": "41",
		  "homepage": "http://example.org/home/"
		};

store.setPrefix("ex", "http://example.org/people/");

store.load("application/ld+json", jsonld, "ex:test", function(err,results) {
  store.node("ex:john_smith", "ex:test", function(err, graph) {
	// process graph here
  });
});
```

###Events API

rdfstore-js implements an experimental events API that allows clients to observe changes in the RDF graph and receive notifications when parts of this graph changes.
The two main event functions are *subscribe* that makes possible to set up a callback function that will be invoked each time triples matching a certain pattern passed as an argument are added or removed, and the function *startObservingNode* that will be invoked with the modified version of the node each time triples are added or removed from the node.

```javascript
var cb = function(event, triples){
  // it will receive a notifications where a triple matching
  // the pattern s:http://example/boogk, p:*, o:*, g:*
  // is inserted or removed.
  if(event === 'added') {
	console.log(triples.length+" triples have been added");
  } else if(event === 'deleted') {
	console.log(triples.length+" triples have been deleted");
  }
}

store.subscribe("http://example/book",null,null,null,cb);

// .. do something;

// stop receiving notifications
store.unsubscribe(cb);
```

The main difference between both methods is that *subscribe* receives the triples that have changed meanwhile *startObservingNode* receives alway the whole node with its updated triples. *startObservingNode* receives the node as a RDF Interface graph object.

```javascript
var cb = function(node){
  // it will receive the updated version of the node each
  // time it is modified.
  // If the node does not exist, the graph received will
  // not contain triples.
  console.log("The node has now "+node.toArray().length+" nodes");
}

// if only tow arguments are passed, the default graph will be used.
// A graph uri can be passed as an optional second argument.
store.startObservingNode("http://example/book",cb);

// .. do something;

// stop receiving notifications
store.stopObservingNode(cb);
```

In the same way, there are *startObservingQuery* and *stopObservingQuery* functions that makes possible to set up callbacks for whole SPARQL queries.
The store will try to be smart and not perform unnecessary evaluations of these query after quad insertion/deletions. Nevertheless too broad queries must be used carefully with the events API.

###Custom Filter Functions

Custom filter function can be registered into the store using the *registerCustomFunction* function. This function receives two argument, the name of the custom function and the associated implementation. This functions will be available in a SPARQL query using the prefix *custom*.
You can also use a full URI to identify the function that is going to be registered.
The function implementation will receive two arguments, an object linking to the store query filters engine and a list with the actual arguments. Arguments will consist of literal or URIs objects. Results from the function must also be literal or URI objects.

The query filters engine can be used to access auxiliary function to transform literals into JavaScript types using the *effectiveTypeValue* function, boolean values using the *effectiveBooleanValue*, to build boolean literal objects (*ebvTrue*, *ebvFalse*) or return an error with the *ebvError*. Documentation and source code for the *QueryFilters* object n the 'js-query-engine' module can be consulted to find information about additional helper functions.

The following test shows a simple examples of how custom functions can be invoked:

```javascript
new Store({name:'test', overwrite:true}, function(err,store) {
	store.load(
		'text/n3',
		'@prefix test: <http://test.com/> .\
		 test:A test:prop 5.\
		 test:B test:prop 4.\
		 test:C test:prop 1.\
		 test:D test:prop 3.',
		function(err) {

			var invoked = false;
            // instead of 'my_addition_check' a full URI can be used 'http://test.com/my_fns/my_addition_check'
			store.registerCustomFunction('my_addition_check', function(engine,args) {
		// equivalent to var v1 = parseInt(args[0].value), v2 = parseInt(args[1].value);

		var v1 = engine.effectiveTypeValue(args[0]);
		var v2 = engine.effectiveTypeValue(args[1]);

		// equivalent to return {token: 'literal', type:"http://www.w3.org/2001/XMLSchema#boolean", value:(v1+v2<5)};

		return engine.ebvBoolean(v1+v2<5);
	});

	   store.execute(
				'PREFIX test: <http://test.com/> \
				 SELECT * { ?x test:prop ?v1 .\
							?y test:prop ?v2 .\
							filter(custom:my_addition_check(?v1,?v2)) }',
				function(err) {
				   test.ok(results.length === 3);
		   for(var i=0; i<results.length; i++) {
			test.ok(parseInt(results[i].v1.value) + parseInt(results[i].v2.value) < 5 );
		}
		test.done()
		}
	);
  });
});
```

###Persistence

The store can be persisted in the browser using IndexedDB as the backend. In order to make the store persistent,
the 'persistent' flag must be set to true in the store creation options.
Additionally, a 'name' option can also be passed for the store. Different persistent instances of the store can be
opened using different names.

###Controlling the frequency of function yielding

Performance of the store can be improved by reducing the frequency the 'nexTick' mechanism is used to cancel the the calls stack.
You can reduce this frequency by invoking the `yieldFrequency` function on the Store object and passing a bigger number:

``` javascript
var rdfstore = require('rdfstore')
rdfstore.Store.yieldFrequency(200); // will only yield after 200 invocations of nextTick

```
If the number is too big a number can produce stack overflow errors during execution. If you find this problem, reduce the value provided for `yieldFrequency`.

##Dependencies

The library include dependencies to two semantic-web libraries for
parsing:

- [N3.js library](https://github.com/RubenVerborgh/N3.js/), developed
  by Ruben Verborgh and released under the MIT license.

- [jsonld](https://github.com/digitalbazaar/jsonld.js), developed by Digital Bazaar and released under the New BSD license.

##Frontend

A stand-along frontend for the store built using electron has been added in version 0.9.7.
You can build the frontend running the command:

```bash
$ gulp frontend
```

The file will be added under the releases directory.

##Contributing

rdfstore-js is still at the beginning of its development. If you take a look at the library and find a way to improve it, please ping us. We'll be very greatful for any bug report or pull-request.

## Author

Antonio Garrote, email:antoniogarrote@gmail.com, twitter:@antoniogarrote.

## License

Licensed under the [MIT License](http://opensource.org/licenses/MIT), copyright Antonio Garrote 2011-2015


text:
import { Emulators } from "./types";

export const DEFAULT_PORTS: { [s in Emulators]: number } = {
  ui: 4000,
  hub: 4400,
  logging: 4500,
  hosting: 5000,
  functions: 5001,
  extensions: 5001, // The Extensions Emulator runs on the same port as the Functions Emulator
  firestore: 8080,
  pubsub: 8085,
  database: 9000,
  auth: 9099,
  storage: 9199,
  eventarc: 9299,
};

export const FIND_AVAILBLE_PORT_BY_DEFAULT: Record<Emulators, boolean> = {
  ui: true,
  hub: true,
  logging: true,
  hosting: true,
  functions: false,
  firestore: false,
  database: false,
  pubsub: false,
  auth: false,
  storage: false,
  extensions: false,
  eventarc: true,
};

export const EMULATOR_DESCRIPTION: Record<Emulators, string> = {
  ui: "Emulator UI",
  hub: "emulator hub",
  logging: "Logging Emulator",
  hosting: "Hosting Emulator",
  functions: "Functions Emulator",
  firestore: "Firestore Emulator",
  database: "Database Emulator",
  pubsub: "Pub/Sub Emulator",
  auth: "Authentication Emulator",
  storage: "Storage Emulator",
  extensions: "Extensions Emulator",
  eventarc: "Eventarc Emulator",
};

export const DEFAULT_HOST = "localhost";

export class Constants {
  // GCP projects cannot start with 'demo' so we use 'demo-' as a prefix to denote
  // an intentionally fake project.
  static FAKE_PROJECT_ID_PREFIX = "demo-";
  static FAKE_PROJECT_NUMBER = "0";

  static DEFAULT_DATABASE_EMULATOR_NAMESPACE = "fake-server";

  // Environment variable to override SDK/CLI to point at the Firestore emulator.
  static FIRESTORE_EMULATOR_HOST = "FIRESTORE_EMULATOR_HOST";

  // Alternative (deprecated) env var for Firestore Emulator.
  static FIRESTORE_EMULATOR_ENV_ALT = "FIREBASE_FIRESTORE_EMULATOR_ADDRESS";

  // Environment variable to override SDK/CLI to point at the Realtime Database emulator.
  static FIREBASE_DATABASE_EMULATOR_HOST = "FIREBASE_DATABASE_EMULATOR_HOST";

  // Environment variable to override SDK/CLI to point at the Firebase Auth emulator.
  static FIREBASE_AUTH_EMULATOR_HOST = "FIREBASE_AUTH_EMULATOR_HOST";

  // Environment variable to override SDK/CLI to point at the Firebase Storage emulator.
  static FIREBASE_STORAGE_EMULATOR_HOST = "FIREBASE_STORAGE_EMULATOR_HOST";

  // Environment variable to override SDK/CLI to point at the Firebase Storage emulator
  // for firebase-admin <= 9.6.0. Unlike the FIREBASE_STORAGE_EMULATOR_HOST variable
  // this one must start with 'http://'.
  static CLOUD_STORAGE_EMULATOR_HOST = "STORAGE_EMULATOR_HOST";

  // Environment variable to discover the eventarc emulator.
  static PUBSUB_EMULATOR_HOST = "PUBSUB_EMULATOR_HOST";

  // Environment variable to discover the eventarc emulator.
  static CLOUD_EVENTARC_EMULATOR_HOST = "CLOUD_EVENTARC_EMULATOR_HOST";

  // Environment variable to discover the Emulator HUB
  static FIREBASE_EMULATOR_HUB = "FIREBASE_EMULATOR_HUB";
  static FIREBASE_GA_SESSION = "FIREBASE_GA_SESSION";

  static SERVICE_FIRESTORE = "firestore.googleapis.com";
  static SERVICE_REALTIME_DATABASE = "firebaseio.com";
  static SERVICE_PUBSUB = "pubsub.googleapis.com";
  static SERVICE_EVENTARC = "eventarc.googleapis.com";
  // Note: the service name below are here solely for logging purposes.
  // There is not an emulator available for these.
  static SERVICE_ANALYTICS = "app-measurement.com";
  static SERVICE_AUTH = "firebaseauth.googleapis.com";
  static SERVICE_CRASHLYTICS = "fabric.io";
  static SERVICE_REMOTE_CONFIG = "firebaseremoteconfig.googleapis.com";
  static SERVICE_STORAGE = "storage.googleapis.com";
  static SERVICE_TEST_LAB = "testing.googleapis.com";

  static getServiceName(service: string): string {
    switch (service) {
      case this.SERVICE_FIRESTORE:
        return "firestore";
      case this.SERVICE_REALTIME_DATABASE:
        return "database";
      case this.SERVICE_PUBSUB:
        return "pubsub";
      case this.SERVICE_ANALYTICS:
        return "analytics";
      case this.SERVICE_AUTH:
        return "auth";
      case this.SERVICE_CRASHLYTICS:
        return "crashlytics";
      case this.SERVICE_REMOTE_CONFIG:
        return "remote config";
      case this.SERVICE_STORAGE:
        return "storage";
      case this.SERVICE_TEST_LAB:
        return "test lab";
      case this.SERVICE_EVENTARC:
        return "eventarc";
      default:
        return service;
    }
  }

  static getDefaultHost(): string {
    return DEFAULT_HOST;
  }

  static getDefaultPort(emulator: Emulators): number {
    return DEFAULT_PORTS[emulator];
  }

  static description(name: Emulators): string {
    return EMULATOR_DESCRIPTION[name];
  }

  static isDemoProject(projectId?: string): boolean {
    return !!projectId && projectId.startsWith(this.FAKE_PROJECT_ID_PREFIX);
  }
}


text:
package ch.isbsib.sparql.bed;

import static ch.isbsib.sparql.bed.VCFFileStoreSchema.FILE;
import static ch.isbsib.sparql.bed.VCFFileStoreSchema.INDEX;

import org.openrdf.model.Graph;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.util.GraphUtil;
import org.openrdf.model.util.GraphUtilException;
import org.openrdf.sail.config.SailConfigException;
import org.openrdf.sail.config.SailImplConfigBase;

public class VCFFileConfig extends SailImplConfigBase {

    private String file;
    private String index;

	public VCFFileConfig() {
		super(VCFFileStoreFactory.SAIL_TYPE);
	}

    public String getFile() {
   		return file;
   	}
    public String getIndex() {
   		return index;
   	}

	@Override
	public void parse(Graph graph, Resource implNode)
			throws SailConfigException {
		super.parse(graph, implNode);

		try {
            Literal persistValue = GraphUtil.getOptionalObjectLiteral(graph,
         					implNode, FILE);
            Literal persistValue2 = GraphUtil.getOptionalObjectLiteral(graph,
         					implNode, INDEX);
			if (persistValue != null) {
				try {
                    setFile((persistValue).stringValue());
                    setIndex((persistValue2).stringValue());
				} catch (IllegalArgumentException e) {
					throw new SailConfigException("Boolean value required for "
							+ FILE + " property, found " + persistValue);
				}
			}
		} catch (GraphUtilException e) {
			throw new SailConfigException(e.getMessage(), e);
		}
	}

	private void setFile(String stringValue) {
		this.file = stringValue;

	}

    private void setIndex(String stringValue) {
   		this.index = stringValue;

   	}
	@Override
	public Resource export(Graph graph)
	{
		Resource implNode = super.export(graph);

		if (this.file != null) {
            graph.add(implNode, FILE, graph.getValueFactory().createLiteral(file));
            graph.add(implNode, INDEX, graph.getValueFactory().createLiteral(index));
		}

		return implNode;
	}
}


text:
constexpr int MAX_OSPATH = 260;

constexpr char* DEMO_HEADER_ID = "HL2DEMO";
constexpr int DEMO_PROTOCOL = 3;

constexpr int NETCHANNEL_MAX_SIZE = 96000;

// Demo messages
enum DemoCommandType : byte
{
	// PAZER: added
	dem_invalid = 0,

	// it's a startup message, process as fast as possible
	dem_signon = 1,
	// it's a normal network packet that we stored off
	dem_packet,
	// sync client clock to demo tick
	dem_synctick,
	// console command
	dem_consolecmd,
	// user input command
	dem_usercmd,
	// network data tables
	dem_datatables,
	// end of time.
	dem_stop,

	dem_stringtables,

	// Last command
	dem_lastcmd = dem_stringtables
};

struct demoheader_t
{
	char	demofilestamp[8];						// Should be HL2DEMO
	int		demoprotocol;							// Should be DEMO_PROTOCOL
	int		networkprotocol;						// Should be PROTOCOL_VERSION
	char	servername[MAX_OSPATH];					// Name of server
	char	clientname[MAX_OSPATH];					// Name of client who recorded the game
	char	mapname[MAX_OSPATH];					// Name of map
	char	gamedirectory[MAX_OSPATH];				// Name of game directory (com_gamedir)
	float	playback_time;							// Time of track
	int     playback_ticks;							// # of ticks in track
	int     playback_frames;						// # of frames in track
	int		signonlength;							// length of sigondata in bytes
};

enum DemoCommandFlags
{
	FDEMO_NORMAL = 0,
	FDEMO_USE_ORIGIN2 = (1 << 0),
	FDEMO_USE_ANGLES2 = (1 << 1),
	FDEMO_NOINTERP = (1 << 2),	// don't interpolate between this an last view

	FDEMO_PAZER_FAKE_TICK = (1 << 3),

	FDEMO_PAZER_REQUIRES_ANGLE_INTERP = (1 << 4),
	FDEMO_PAZER_REQUIRES_ORIGIN_INTERP = (1 << 5),
};

struct democmdinfo_t
{
	// Default constructor
	democmdinfo_t()
	{
		flags = FDEMO_NORMAL;

		viewOrigin[0] = viewOrigin[1] = viewOrigin[2] = 0;
		viewAngles[0] = viewAngles[1] = viewAngles[2] = 0;
		localViewAngles[0] = localViewAngles[1] = localViewAngles[2] = 0;

		viewOrigin2[0] = viewOrigin2[1] = viewOrigin2[2] = 0;
		viewAngles2[0] = viewAngles2[1] = viewAngles2[2] = 0;
		localViewAngles2[0] = localViewAngles2[1] = localViewAngles2[2] = 0;
	}

	int			flags;

	// original origin/viewangles
	float		viewOrigin[3];
	float		viewAngles[3];
	float		localViewAngles[3];

	// Resampled origin/viewangles
	float		viewOrigin2[3];
	float		viewAngles2[3];
	float		localViewAngles2[3];
};


text:
package org.apache.aries.jndi.url;

import org.osgi.framework.BundleContext;

import javax.naming.ConfigurationException;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.spi.ObjectFactory;
import java.util.Hashtable;

/**
 * A factory for the aries JNDI context
 */
public class OsgiURLContextFactory implements ObjectFactory {

    private BundleContext callerContext;

    public OsgiURLContextFactory(BundleContext callerContext) {
        this.callerContext = callerContext;
    }

    public Object getObjectInstance(Object obj,
                                    Name name,
                                    Context nameCtx,
                                    Hashtable<?, ?> environment) throws Exception {
        if (obj == null) {
            return new ServiceRegistryContext(callerContext, environment);
        } else if (obj instanceof String) {
            return findAny(environment, (String) obj);
        } else if (obj instanceof String[]) {
            return findAny(environment, (String[]) obj);
        } else {
            return null;
        }
    }

    /**
     * Try each URL until either lookup succeeds or they all fail
     */
    private Object findAny(Hashtable<?, ?> environment, String... urls)
            throws ConfigurationException, NamingException {
        if (urls.length == 0) {
            throw new ConfigurationException("0");
        }
        Context context = new ServiceRegistryContext(callerContext, environment);
        try {
            NamingException ne = null;
            for (int i = 0; i < urls.length; i++) {
                try {
                    return context.lookup(urls[i]);
                } catch (NamingException e) {
                    ne = e;
                }
            }
            throw ne;
        } finally {
            context.close();
        }
    }

}


text:
'use strict';
/**
 * Utility functions common to graph plotters.
 */
class GraphUtils {
  /**
   * Attaches a zoom listener to the chart and rescales the
   * axes based on mouse scroll and click events.
   * @param {boolean} shouldScale.x
   * Set to true if the x axis should be rescaled.
   * @param {boolean} shouldScale.y
   * Set to true if the y axis should be rescaled.
   * @param {Object} chart The chart to draw on.
   * @param {Object} chartDimensions
   * The width, height and margins of the chart.
   * @param {function(Object, Object):} redraw Given the x and y axes scales
   * this should redraw the graph based on the new scales.
   * @param {Object} axes Provides the axis drawings, scales and generators
   * in the format:
   * {
   *   x: {
   *     generator: Object,
   *     scale: Object,
   *     drawing: Object,
   *   },
   *   y: {
   *     generator: Object,
   *     scale: Object,
   *     drawing: Object,
   *   },
   * }
   * If an axis is set to true in shouldScale it's corresponding information
   * must be provided in axes. Otherwise, it may be omitted.
   */
  static createZoom(shouldScale, chart, chartDimensions, redraw, axes) {
    const transformLinePlot = (xAxisScale, yAxisScale) => {
      if (xAxisScale) {
        axes.x.generator.scale(xAxisScale);
        axes.x.drawing.call(axes.x.generator);
      }
      if (yAxisScale) {
        axes.y.generator.scale(yAxisScale);
        axes.y.drawing.call(axes.y.generator);
      }
      redraw(xAxisScale, yAxisScale);
    };

    const setUpZoom = (zoom) => {
      const onZoom = () => {
        const transform = d3.event.transform;
        const transformedScaleForYAxis = shouldScale.y ?
          transform.rescaleY(axes.y.scale) : undefined;
        const transformedScaleForXAxis = shouldScale.x ?
          transform.rescaleX(axes.x.scale) : undefined;
        transformLinePlot(
            transformedScaleForXAxis, transformedScaleForYAxis);
      };
      zoom.on('zoom', onZoom).scaleExtent([1, Infinity]);
      // The following invisible rectangle is there just to catch
      // mouse events for zooming. It's not possible to listen on
      // the chart itself because it is a g element (which does not
      // capture mouse events).
      chart.append('rect')
          .attr('width', chartDimensions.width)
          .attr('height', chartDimensions.height)
          .attr('class', 'zoom-listener')
          .style('opacity', 0)
          .call(zoom);
    };

    const setUpZoomReset = (zoom) => {
      // Gives some padding between the x-axis and the reset button.
      const padding = 10;
      const resetButton = chart.append('svg')
          .attr('width', '10em')
          .attr('height', '2em')
          .attr('x', `${chartDimensions.width + padding}px`)
          .attr('y', `${chartDimensions.height}px`)
          .attr('cursor', 'pointer');
      // Styling for the button.
      resetButton.append('rect')
          .attr('rx', '5px')
          .attr('ry', '5px')
          .attr('width', '100%')
          .attr('height', '100%')
          .attr('fill', '#1b39a8');
      resetButton.append('text')
          .text('RESET CHART')
          .attr('x', '50%')
          .attr('y', '50%')
          .attr('fill', 'white')
          .attr('text-anchor', 'middle')
          .attr('dominant-baseline', 'middle');
      resetButton
          .on('mouseover', () => {
            resetButton.attr('opacity', '0.5');
          })
          .on('mouseout', () => {
            resetButton.attr('opacity', '1');
          })
          .on('click', () => {
            resetButton.attr('opacity', '1');
            chart.select('.zoom-listener')
                .call(zoom.transform, d3.zoomIdentity);
            const originalXAxisScale = shouldScale.x ?
              axes.x.scale : undefined;
            const originalYAxisScale = shouldScale.y ?
              axes.y.scale : undefined;
            transformLinePlot(
                originalXAxisScale, originalYAxisScale);
          });
    };
    const zoom = d3.zoom();
    setUpZoom(zoom);
    setUpZoomReset(zoom
    );
  }

  /**
   * Utility function for converting text which may contain invalid
   * characters for CSS classes/selectors into something safe to
   * use in class names and retrieve using selectors.
   * @return {function(string): string} Retrieves a unique class name
   * mapped to the supplied key.
   */
  static getClassNameSuffixFactory() {
    let nextUniqueClassName = 0;
    const keyToClassName = {};
    return (key) => {
      if (keyToClassName[key] === undefined) {
        keyToClassName[key] = nextUniqueClassName++;
      }
      return keyToClassName[key].toString();
    };
  }

  static useTraceCallback(selection, graph, key, radius, className) {
    selection
        .on('click', datum => {
          graph.interactiveCallbackForSelectedDatum(key, datum.id);
        })
        .on('mouseover', (datum, datumIndex) => {
          const zoomOnHoverScaleFactor = 2;
          d3.selectAll(`.${className}`)
              .filter((d, i) => i === datumIndex)
              .attr('r', radius * zoomOnHoverScaleFactor);
        })
        .on('mouseout', (datum, datumIndex) => {
          d3.selectAll(`.${className}`)
              .filter((d, i) => i === datumIndex)
              .attr('r', radius);
        })
        .append('title')
        .text('click to view trace');
    return selection;
  }
}


text:
require 'spec_helper'
require 'rack'

def dummy_rack_app
  lambda{|env| [200, {"Content-Type" => "text/html"}, ["dummy_rack_app body"]] }
end

describe Dragonfly::Middleware do

  def make_request(app, url)
    Rack::MockRequest.new(app).get(url)
  end

  before(:each) do
    @stack = Rack::Builder.new do
      use Dragonfly::Middleware, :images
      run dummy_rack_app
    end
  end

  it "should pass through if the app returns X-Cascade: pass" do
    Dragonfly[:images].should_receive(:call).and_return(
      [404, {"Content-Type" => 'text/plain', 'X-Cascade' => 'pass'}, ['Not found']]
    )
    response = make_request(@stack, '/media/hello.png?howare=you')
    response.body.should == 'dummy_rack_app body'
    response.status.should == 200
  end

  it "should return a 404 if the app returns a 404" do
    Dragonfly[:images].should_receive(:call).and_return(
      [404, {"Content-Type" => 'text/plain'}, ['Not found']]
    )
    response = make_request(@stack, '/media/hello.png?howare=you')
    response.status.should == 404
  end

  it "should return as per the dragonfly app if the app returns a 200" do
    Dragonfly[:images].should_receive(:call).and_return(
      [200, {"Content-Type" => 'text/plain'}, ['ABCD']]
    )
    response = make_request(@stack, '/media/hello.png?howare=you')
    response.status.should == 200
    response.body.should == 'ABCD'
  end

end


text:
<colgroup>
<col>
<col>
</colgroup>

United Kingdom

 	£ million (2014 prices)3

Opening Balance as at 31 March 2013	7,254

Additions to stock

Natural growth	325

New planting & restocking (reclassification)	124

Total additions to stock	448

Reductions in stock

Removals1	186

Fellings residues1	21

Natural losses	2

Catastrophic losses2

Reclassifications	-

Total reduction in stocks	208

Revaluation	-

Closing balance as at 31 March 2014	7,494

Notes:
1. The data for removals and fellings relate to calendar years. For simplicity, it is assumed that felling activity is similar throughout the year and that the figures for financial years are similar to those for calendar years.
2. No data are currently available on catastrophic losses, although such losses are expected to be very small.
3. Components may not sum to totals due to rounding

Sources: National Forest Inventory (Forestry Commission, 2011);  Woodland Area, Planting & Restocking - 2015 edition (Forestry Commission, 2015); UK Wood Production and Trade: 2014 provisional figures (Forestry Commission, 2015);50-year forecast of softwood timber availability (Forestry Commission, 2014); 50-year forecast of hardwood timber availability (Forestry Commission, 2014); Timber Price Indices: Data to March 2015 (Forestry Commission, 2015). ONS calculations


text:
import { JsonValue } from '../../json';
import { JobDescription, JobHandler } from './api';
export declare namespace strategy {
    type JobStrategy<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue> = (handler: JobHandler<A, I, O>, options?: Partial<Readonly<JobDescription>>) => JobHandler<A, I, O>;
    /**
     * Creates a JobStrategy that serializes every call. This strategy can be mixed between jobs.
     */
    function serialize<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(): JobStrategy<A, I, O>;
    /**
     * Creates a JobStrategy that will always reuse a running job, and restart it if the job ended.
     * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it
     *        is.
     */
    function reuse<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(replayMessages?: boolean): JobStrategy<A, I, O>;
    /**
     * Creates a JobStrategy that will reuse a running job if the argument matches.
     * @param replayMessages Replay ALL messages if a job is reused, otherwise just hook up where it
     *        is.
     */
    function memoize<A extends JsonValue = JsonValue, I extends JsonValue = JsonValue, O extends JsonValue = JsonValue>(replayMessages?: boolean): JobStrategy<A, I, O>;
}


text:
#pragma once

#include <render_pipeline/rpcore/render_stage.hpp>

namespace rpcore {

/** This stage computes the ambient term. */
class RENDER_PIPELINE_DECL AmbientStage : public RenderStage
{
public:
    AmbientStage(RenderPipeline& pipeline): RenderStage(pipeline, "AmbientStage") {}

    static RequireType& get_global_required_inputs() { return required_inputs_; }
    static RequireType& get_global_required_pipes() { return required_pipes_; }

    RequireType& get_required_inputs() const final { return required_inputs_; }
    RequireType& get_required_pipes() const final { return required_pipes_; }
    ProduceType get_produced_pipes() const final;

    RENDER_PIPELINE_STAGE_DOWNCAST();

    void create() final;
    void reload_shaders() final;

private:
    std::string get_plugin_id() const final;

    static RequireType required_inputs_;
    static RequireType required_pipes_;

    bool stereo_mode_ = false;
    RenderTarget* target_;
};

}


text:
let eventSource = new EventSource("/news/sse");
eventSource.onmessage = (e) => {
    let li = document.createElement("li");
    li.innerText = e.data;
    document.getElementById("news").appendChild(li);
}


text:
/* spi.c - SPI test source file */

/*
 * Copyright (c) 2015 Intel Corporation.
 *
 * 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.
 */

#include <zephyr.h>

#if defined(CONFIG_STDOUT_CONSOLE)
#include <stdio.h>
#define PRINT printf
#else
#include <misc/printk.h>
#define PRINT printk
#endif

#include <nanokernel.h>
#include <arch/cpu.h>

#include <string.h>
#include <spi.h>
#ifdef CONFIG_SPI_INTEL
#include <spi/spi_intel.h>
#define SPI_DRV_NAME CONFIG_SPI_INTEL_PORT_1_DRV_NAME
#define SPI_SLAVE 0
#else
#define SPI_MAX_CLK_FREQ_250KHZ 131
#define SPI_DRV_NAME CONFIG_SPI_DW_PORT_0_DRV_NAME
#define SPI_SLAVE 2
#endif

unsigned char wbuf[16] = "Hello";
unsigned char rbuf[16] = {};

static void print_buf_hex(unsigned char *b, uint32_t len)
{
	for (; len > 0; len--) {
		PRINT("0x%x ", *(b++));
	}

	PRINT("\n");
}

struct spi_config spi_conf = {
	.config = SPI_MODE_CPOL | SPI_MODE_CPHA | (8 << 4),
	.max_sys_freq = SPI_MAX_CLK_FREQ_250KHZ,
};

static void _spi_show(struct spi_config *spi_conf)
{
	PRINT("SPI Configuration:\n");
	PRINT("\tbits per word: %u\n", SPI_WORD_SIZE_GET(spi_conf->config));
	PRINT("\tMode: %u\n", SPI_MODE(spi_conf->config));
	PRINT("\tMax speed Hz: 0x%X\n", spi_conf->max_sys_freq);
}

void main(void)
{
	struct device *spi;

	PRINT("==== SPI Test Application ====\n");

	spi = device_get_binding(SPI_DRV_NAME);

	PRINT("Running...\n");

	spi_configure(spi, &spi_conf);
	spi_slave_select(spi, SPI_SLAVE);

	_spi_show(&spi_conf);

	PRINT("Writing...\n");
	spi_write(spi, (uint8_t *) wbuf, 6);

	PRINT("SPI sent: %s\n", wbuf);
	print_buf_hex(rbuf, 6);

	strcpy(wbuf, "So what then?");
	spi_transceive(spi, wbuf, 14, rbuf, 16);

	PRINT("SPI transceived: %s\n", rbuf);
	print_buf_hex(rbuf, 6);
}


text:
package com.herokuapp.directto.client;

import com.herokuapp.directto.client.models.Pipeline;
import org.junit.Test;

import java.util.Collection;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * @author Ryan Brainard
 */
public class PipelineInfoTest extends DirectToHerokuClientBaseTest {

    @Test
    public void testGetPipelineNames() throws Exception {
        final Collection<String> pipelineNames = client.getPipelineNames();
        assertTrue(pipelineNames.contains(WAR_PIPELINE));
        assertTrue(pipelineNames.contains(FATJAR_PIPELINE));
    }

    @Test
    public void testGetPipeline() throws Exception {
        final Pipeline pipeline = client.getPipeline(WAR_PIPELINE);
        assertEquals(WAR_PIPELINE, pipeline.getName());
        assertEquals("POST", pipeline.getCall().getMethod());
        assertEquals("/direct/<your app>/war", pipeline.getCall().getUrl());
        assertEquals("Directly deploy a war that will be executed with tomcat runner", pipeline.getManifest().getDescription());
        assertEquals("The war file to be deployed alongside tomcat runner", pipeline.getManifest().getRequiredFileInfo().get("war"));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true">

	<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d (%F:%L) %-5p %c - %m%n" />
		</layout>
	</appender>
	<root>
		<priority value="info" />
		<appender-ref ref="stdout" />
	</root>
</log4j:configuration>