text:
package gerrit_test

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strings"
	"testing"

	"github.com/andygrunwald/go-gerrit"
)

const (
	// testGerritInstanceURL is a test instance url that won`t be called
	testGerritInstanceURL = "https://go-review.googlesource.com/"
)

var (
	// testMux is the HTTP request multiplexer used with the test server.
	testMux *http.ServeMux

	// testClient is the gerrit client being tested.
	testClient *gerrit.Client

	// testServer is a test HTTP server used to provide mock API responses.
	testServer *httptest.Server
)

type testValues map[string]string

// setup sets up a test HTTP server along with a gerrit.Client that is configured to talk to that test server.
// Tests should register handlers on mux which provide mock responses for the API method being tested.
func setup() {
	// Test server
	testMux = http.NewServeMux()
	testServer = httptest.NewServer(testMux)

	// gerrit client configured to use test server
	testClient, _ = gerrit.NewClient(testServer.URL, nil)
}

// teardown closes the test HTTP server.
func teardown() {
	testServer.Close()
}

// makedigestheader takes the incoming request and produces a string
// which can be used for the WWW-Authenticate header.
func makedigestheader(request *http.Request) string {
	return fmt.Sprintf(
		`Digest realm="Gerrit Code Review", domain="http://%s/", qop="auth", nonce="fakevaluefortesting"`,
		request.Host)
}

// writeresponse writes the requested value to the provided response writer and sets
// the http code
func writeresponse(t *testing.T, writer http.ResponseWriter, value interface{}, code int) {
	writer.WriteHeader(code)

	unmarshalled, err := json.Marshal(value)
	if err != nil {
		t.Error(err.Error())
		return
	}

	data := []byte(`)]}'` + "\n" + string(unmarshalled))
	if _, err := writer.Write(data); err != nil {
		t.Error(err.Error())
		return
	}
}

func testMethod(t *testing.T, r *http.Request, want string) {
	if got := r.Method; got != want {
		t.Errorf("Request method: %v, want %v", got, want)
	}
}

func testRequestURL(t *testing.T, r *http.Request, want string) { // nolint: unparam
	if got := r.URL.String(); got != want {
		t.Errorf("Request URL: %v, want %v", got, want)
	}
}

func testFormValues(t *testing.T, r *http.Request, values testValues) {
	want := url.Values{}
	for k, v := range values {
		want.Add(k, v)
	}

	if err := r.ParseForm(); err != nil {
		t.Error(err)
	}
	if got := r.Form; !reflect.DeepEqual(got, want) {
		t.Errorf("Request parameters: %v, want %v", got, want)
	}
}

func testQueryValues(t *testing.T, r *http.Request, values testValues) {
	want := url.Values{}
	for k, v := range values {
		want.Add(k, v)
	}

	if got := r.URL.Query(); !reflect.DeepEqual(got, want) {
		t.Errorf("Request parameters: %v, want %v", got, want)
	}
}

func TestNewClient_NoGerritInstance(t *testing.T) {
	mockData := []string{"", "://not-existing"}
	for _, data := range mockData {
		c, err := gerrit.NewClient(data, nil)
		if c != nil {
			t.Errorf("NewClient return is not nil. Expected no client. Go %+v", c)
		}
		if err == nil {
			t.Error("No error occured by empty Gerrit Instance. Expected one.")
		}
	}
}

func TestNewClient_Services(t *testing.T) {
	c, err := gerrit.NewClient("https://gerrit-review.googlesource.com/", nil)
	if err != nil {
		t.Errorf("An error occured. Expected nil. Got %+v.", err)
	}

	if c.Authentication == nil {
		t.Error("No AuthenticationService found.")
	}
	if c.Access == nil {
		t.Error("No AccessService found.")
	}
	if c.Accounts == nil {
		t.Error("No AccountsService found.")
	}
	if c.Changes == nil {
		t.Error("No ChangesService found.")
	}
	if c.Config == nil {
		t.Error("No ConfigService found.")
	}
	if c.Groups == nil {
		t.Error("No GroupsService found.")
	}
	if c.Plugins == nil {
		t.Error("No PluginsService found.")
	}
	if c.Projects == nil {
		t.Error("No ProjectsService found.")
	}
}

func TestNewClient_TestErrNoInstanceGiven(t *testing.T) {
	_, err := gerrit.NewClient("", nil)
	if err != gerrit.ErrNoInstanceGiven {
		t.Error("Expected `ErrNoInstanceGiven`")
	}
}

func TestNewClient_NoCredentials(t *testing.T) {
	client, err := gerrit.NewClient("http://localhost/", nil)
	if err != nil {
		t.Errorf("Unexpected error: %s", err.Error())
	}
	if client.Authentication.HasAuth() {
		t.Error("Expected HasAuth() to return false")
	}
}

func TestNewClient_UsernameWithoutPassword(t *testing.T) {
	_, err := gerrit.NewClient("http://foo@localhost/", nil)
	if err != gerrit.ErrUserProvidedWithoutPassword {
		t.Error("Expected ErrUserProvidedWithoutPassword")
	}
}

func TestNewClient_AuthenticationFailed(t *testing.T) {
	setup()
	defer teardown()

	testMux.HandleFunc("/a/accounts/self", func(w http.ResponseWriter, r *http.Request) {
		writeresponse(t, w, nil, http.StatusUnauthorized)
	})

	serverURL := fmt.Sprintf("http://admin:secret@%s/", testServer.Listener.Addr().String())
	client, err := gerrit.NewClient(serverURL, nil)
	if err != gerrit.ErrAuthenticationFailed {
		t.Error(err)
	}
	if client.Authentication.HasAuth() {
		t.Error("Expected HasAuth() == false")
	}
}

func TestNewClient_DigestAuth(t *testing.T) {
	setup()
	defer teardown()

	account := gerrit.AccountInfo{
		AccountID: 100000,
		Name:      "test",
		Email:     "test@localhost",
		Username:  "test"}
	hits := 0

	testMux.HandleFunc("/a/accounts/self", func(w http.ResponseWriter, r *http.Request) {
		hits++
		switch hits {
		case 1:
			w.Header().Set("WWW-Authenticate", makedigestheader(r))
			writeresponse(t, w, nil, http.StatusUnauthorized)
		case 2:
			// go-gerrit should set Authorization in response to a `WWW-Authenticate` header
			if !strings.Contains(r.Header.Get("Authorization"), `username="admin"`) {
				t.Error(`Missing username="admin"`)
			}
			writeresponse(t, w, account, http.StatusOK)
		case 3:
			t.Error("Did not expect another request")
		}
	})

	serverURL := fmt.Sprintf("http://admin:secret@%s/", testServer.Listener.Addr().String())
	client, err := gerrit.NewClient(serverURL, nil)
	if err != nil {
		t.Error(err)
	}
	if !client.Authentication.HasDigestAuth() {
		t.Error("Expected HasDigestAuth() == true")
	}
}

func TestNewClient_BasicAuth(t *testing.T) {
	setup()
	defer teardown()

	account := gerrit.AccountInfo{
		AccountID: 100000,
		Name:      "test",
		Email:     "test@localhost",
		Username:  "test"}
	hits := 0

	testMux.HandleFunc("/a/accounts/self", func(w http.ResponseWriter, r *http.Request) {
		hits++
		switch hits {
		case 1:
			writeresponse(t, w, nil, http.StatusUnauthorized)
		case 2:
			// The second request should be a basic auth request if the first request, which is for
			// digest based auth, fails.
			if !strings.HasPrefix(r.Header.Get("Authorization"), "Basic ") {
				t.Error("Missing 'Basic ' prefix")
			}
			writeresponse(t, w, account, http.StatusOK)
		case 3:
			t.Error("Did not expect another request")
		}
	})

	serverURL := fmt.Sprintf("http://admin:secret@%s/", testServer.Listener.Addr().String())
	client, err := gerrit.NewClient(serverURL, nil)
	if err != nil {
		t.Error(err)
	}
	if !client.Authentication.HasBasicAuth() {
		t.Error("Expected HasBasicAuth() == true")
	}
}

func TestNewClient_ReParseURL(t *testing.T) {
	urls := map[string][]string{
		"http://admin:ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg@127.0.0.1:5000/": {
			"http://127.0.0.1:5000/", "admin", "ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg",
		},
		"http://admin:ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg@127.0.0.1:5000/foo": {
			"http://127.0.0.1:5000/foo", "admin", "ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg",
		},
		"http://admin:ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg@127.0.0.1:5000": {
			"http://127.0.0.1:5000", "admin", "ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg",
		},
		"https://admin:foo/bar@localhost:5": {
			"https://localhost:5", "admin", "foo/bar",
		},
	}
	for input, expectations := range urls {
		submatches := gerrit.ReParseURL.FindAllStringSubmatch(input, -1)
		submatch := submatches[0]
		username := submatch[2]
		password := submatch[3]
		endpoint := fmt.Sprintf(
			"%s://%s:%s%s", submatch[1], submatch[4], submatch[5], submatch[6])
		if endpoint != expectations[0] {
			t.Errorf("%s != %s", expectations[0], endpoint)
		}
		if username != expectations[1] {
			t.Errorf("%s != %s", expectations[1], username)
		}
		if password != expectations[2] {
			t.Errorf("%s != %s", expectations[2], password)
		}

	}
}

func TestNewClient_BasicAuth_PasswordWithSlashes(t *testing.T) {
	setup()
	defer teardown()

	account := gerrit.AccountInfo{
		AccountID: 100000,
		Name:      "test",
		Email:     "test@localhost",
		Username:  "test"}
	hits := 0

	testMux.HandleFunc("/a/accounts/self", func(w http.ResponseWriter, r *http.Request) {
		hits++
		switch hits {
		case 1:
			writeresponse(t, w, nil, http.StatusUnauthorized)
		case 2:
			// The second request should be a basic auth request if the first request, which is for
			// digest based auth, fails.
			if !strings.HasPrefix(r.Header.Get("Authorization"), "Basic ") {
				t.Error("Missing 'Basic ' prefix")
			}
			writeresponse(t, w, account, http.StatusOK)
		case 3:
			t.Error("Did not expect another request")
		}
	})

	serverURL := fmt.Sprintf(
		"http://admin:ZOSOKjgV/kgEkN0bzPJp+oGeJLqpXykqWFJpon/Ckg@%s",
		testServer.Listener.Addr().String())
	client, err := gerrit.NewClient(serverURL, nil)
	if err != nil {
		t.Error(err)
	}
	if !client.Authentication.HasAuth() {
		t.Error("Expected HasAuth() == true")
	}
}

func TestNewClient_CookieAuth(t *testing.T) {
	setup()
	defer teardown()

	account := gerrit.AccountInfo{
		AccountID: 100000,
		Name:      "test",
		Email:     "test@localhost",
		Username:  "test"}
	hits := 0

	testMux.HandleFunc("/a/accounts/self", func(w http.ResponseWriter, r *http.Request) {
		hits++
		switch hits {
		case 1:
			writeresponse(t, w, nil, http.StatusUnauthorized)
		case 2:
			writeresponse(t, w, nil, http.StatusUnauthorized)
		case 3:
			if r.Header.Get("Cookie") != "admin=secret" {
				t.Error("Expected cookie to equal 'admin=secret")
			}

			writeresponse(t, w, account, http.StatusOK)
		case 4:
			t.Error("Did not expect another request")
		}
	})

	serverURL := fmt.Sprintf("http://admin:secret@%s/", testServer.Listener.Addr().String())
	client, err := gerrit.NewClient(serverURL, nil)
	if err != nil {
		t.Error(err)
	}
	if !client.Authentication.HasCookieAuth() {
		t.Error("Expected HasCookieAuth() == true")
	}
}

func TestNewRequest(t *testing.T) {
	c, err := gerrit.NewClient(testGerritInstanceURL, nil)
	if err != nil {
		t.Errorf("An error occured. Expected nil. Got %+v.", err)
	}

	inURL, outURL := "/foo", testGerritInstanceURL+"foo"
	inBody, outBody := &gerrit.PermissionRuleInfo{Action: "ALLOW", Force: true, Min: 0, Max: 0}, `{"action":"ALLOW","force":true,"min":0,"max":0}`+"\n"
	req, _ := c.NewRequest("GET", inURL, inBody)

	// Test that relative URL was expanded
	if got, want := req.URL.String(), outURL; got != want {
		t.Errorf("NewRequest(%q) URL is %v, want %v", inURL, got, want)
	}

	// Test that body was JSON encoded
	body, _ := io.ReadAll(req.Body)
	if got, want := string(body), outBody; got != want {
		t.Errorf("NewRequest Body is %v, want %v", got, want)
	}
}

func TestNewRawPutRequest(t *testing.T) {
	c, err := gerrit.NewClient(testGerritInstanceURL, nil)
	if err != nil {
		t.Errorf("An error occured. Expected nil. Got %+v.", err)
	}

	inURL, outURL := "/foo", testGerritInstanceURL+"foo"
	req, _ := c.NewRawPutRequest(inURL, "test raw PUT contents")

	// Test that relative URL was expanded
	if got, want := req.URL.String(), outURL; got != want {
		t.Errorf("NewRequest(%q) URL is %v, want %v", inURL, got, want)
	}

	// Test that body was JSON encoded
	body, _ := io.ReadAll(req.Body)
	if got, want := string(body), "test raw PUT contents"; got != want {
		t.Errorf("NewRequest Body is %v, want %v", got, want)
	}
}

func testURLParseError(t *testing.T, err error) {
	if err == nil {
		t.Errorf("Expected error to be returned")
	}
	if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
		t.Errorf("Expected URL parse error, got %+v", err)
	}
}

func TestNewRequest_BadURL(t *testing.T) {
	c, err := gerrit.NewClient(testGerritInstanceURL, nil)
	if err != nil {
		t.Errorf("An error occured. Expected nil. Got %+v.", err)
	}
	_, err = c.NewRequest("GET", ":", nil)
	testURLParseError(t, err)
}

// If a nil body is passed to gerrit.NewRequest, make sure that nil is also passed to http.NewRequest.
// In most cases, passing an io.Reader that returns no content is fine,
// since there is no difference between an HTTP request body that is an empty string versus one that is not set at all.
// However in certain cases, intermediate systems may treat these differently resulting in subtle errors.
func TestNewRequest_EmptyBody(t *testing.T) {
	c, err := gerrit.NewClient(testGerritInstanceURL, nil)
	if err != nil {
		t.Errorf("An error occured. Expected nil. Got %+v.", err)
	}
	req, err := c.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatalf("NewRequest returned unexpected error: %v", err)
	}
	if req.Body != nil {
		t.Fatalf("constructed request contains a non-nil Body")
	}
}

func TestDo(t *testing.T) {
	setup()
	defer teardown()

	type foo struct {
		A string
	}

	testMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if m := "GET"; m != r.Method {
			t.Errorf("Request method = %v, want %v", r.Method, m)
		}
		fmt.Fprint(w, `)]}'`+"\n"+`{"A":"a"}`)
	})

	req, err := testClient.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	body := new(foo)
	if _, err := testClient.Do(req, body); err != nil {
		t.Error(err)
	}

	want := &foo{"a"}
	if !reflect.DeepEqual(body, want) {
		t.Errorf("Response body = %v, want %v", body, want)
	}
}

func TestDo_ioWriter(t *testing.T) {
	setup()
	defer teardown()
	content := `)]}'` + "\n" + `{"A":"a"}`

	testMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if m := "GET"; m != r.Method {
			t.Errorf("Request method = %v, want %v", r.Method, m)
		}
		fmt.Fprint(w, content)
	})

	req, err := testClient.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	var buf []byte
	actual := bytes.NewBuffer(buf)
	if _, err := testClient.Do(req, actual); err != nil {
		t.Error(err)
	}

	expected := []byte(content)
	if !reflect.DeepEqual(actual.Bytes(), expected) {
		t.Errorf("Response body = %v, want %v", actual, string(expected))
	}
}

func TestDo_HTTPError(t *testing.T) {
	setup()
	defer teardown()

	testMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "Bad Request", 400)
	})

	req, _ := testClient.NewRequest("GET", "/", nil)
	_, err := testClient.Do(req, nil)

	if err == nil {
		t.Error("Expected HTTP 400 error.")
	}
}

// Test handling of an error caused by the internal http client's Do() function.
// A redirect loop is pretty unlikely to occur within the Gerrit API, but does allow us to exercise the right code path.
func TestDo_RedirectLoop(t *testing.T) {
	setup()
	defer teardown()

	testMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/", http.StatusFound)
	})

	req, _ := testClient.NewRequest("GET", "/", nil)
	_, err := testClient.Do(req, nil)

	if err == nil {
		t.Error("Expected error to be returned.")
	}
	if err, ok := err.(*url.Error); !ok {
		t.Errorf("Expected a URL error; got %#v.", err)
	}
}

func TestRemoveMagicPrefixLine(t *testing.T) {
	mockData := []struct {
		Current, Expected []byte
	}{
		{[]byte(`{"A":"a"}`), []byte(`{"A":"a"}`)},
		{[]byte(`)]}'` + "\n" + `{"A":"a"}`), []byte(`{"A":"a"}`)},
	}
	for _, mock := range mockData {
		body := gerrit.RemoveMagicPrefixLine(mock.Current)
		if !reflect.DeepEqual(body, mock.Expected) {
			t.Errorf("Response body = %v, want %v", body, mock.Expected)
		}
	}
}

func TestRemoveMagicPrefixLineDoesNothingWithoutPrefix(t *testing.T) {
	mockData := []struct {
		Current, Expected []byte
	}{
		{[]byte(`{"A":"a"}`), []byte(`{"A":"a"}`)},
		{[]byte(`{"A":"a"}`), []byte(`{"A":"a"}`)},
	}
	for _, mock := range mockData {
		body := gerrit.RemoveMagicPrefixLine(mock.Current)
		if !reflect.DeepEqual(body, mock.Expected) {
			t.Errorf("Response body = %v, want %v", body, mock.Expected)
		}
	}
}

func TestNewClientFailsOnDeadConnection(t *testing.T) {
	setup()
	serverURL := fmt.Sprintf("http://admin:secret@%s/", testServer.Listener.Addr().String())
	teardown() // Closes the server
	_, err := gerrit.NewClient(serverURL, nil)
	if err == nil {
		t.Fatal("Expected err to not be nil")
	}
	if !strings.Contains(err.Error(), "connection refused") {
		t.Fatalf("Unexpected error. 'connected refused' not found in %s", err.Error())
	}
}


text:
namespace flutter {

typedef CanvasPathMeasure PathMeasure;

IMPLEMENT_WRAPPERTYPEINFO(ui, PathMeasure);

void CanvasPathMeasure::Create(Dart_Handle wrapper,
                               const CanvasPath* path,
                               bool forceClosed) {
  UIDartState::ThrowIfUIOperationsProhibited();
  fml::RefPtr<CanvasPathMeasure> pathMeasure =
      fml::MakeRefCounted<CanvasPathMeasure>();
  if (path) {
    const SkPath skPath = path->path();
    SkScalar resScale = 1;
    pathMeasure->path_measure_ =
        std::make_unique<SkContourMeasureIter>(skPath, forceClosed, resScale);
  } else {
    pathMeasure->path_measure_ = std::make_unique<SkContourMeasureIter>();
  }
  pathMeasure->AssociateWithDartWrapper(wrapper);
}

CanvasPathMeasure::CanvasPathMeasure() {}

CanvasPathMeasure::~CanvasPathMeasure() {}

void CanvasPathMeasure::setPath(const CanvasPath* path, bool isClosed) {
  const SkPath& skPath = path->path();
  path_measure_->reset(skPath, isClosed);
}

float CanvasPathMeasure::getLength(int contour_index) {
  if (static_cast<std::vector<sk_sp<SkContourMeasure>>::size_type>(
          contour_index) < measures_.size()) {
    return measures_[contour_index]->length();
  }
  return -1;
}

tonic::Float32List CanvasPathMeasure::getPosTan(int contour_index,
                                                float distance) {
  tonic::Float32List posTan(Dart_NewTypedData(Dart_TypedData_kFloat32, 5));
  posTan[0] = 0;  // dart code will check for this for failure
  if (static_cast<std::vector<sk_sp<SkContourMeasure>>::size_type>(
          contour_index) >= measures_.size()) {
    return posTan;
  }

  SkPoint pos;
  SkVector tan;
  bool success = measures_[contour_index]->getPosTan(distance, &pos, &tan);

  if (success) {
    posTan[0] = 1;  // dart code will check for this for success
    posTan[1] = pos.x();
    posTan[2] = pos.y();
    posTan[3] = tan.x();
    posTan[4] = tan.y();
  }

  return posTan;
}

void CanvasPathMeasure::getSegment(Dart_Handle path_handle,
                                   int contour_index,
                                   float start_d,
                                   float stop_d,
                                   bool start_with_move_to) {
  if (static_cast<std::vector<sk_sp<SkContourMeasure>>::size_type>(
          contour_index) >= measures_.size()) {
    CanvasPath::Create(path_handle);
  }
  SkPath dst;
  bool success = measures_[contour_index]->getSegment(start_d, stop_d, &dst,
                                                      start_with_move_to);
  if (!success) {
    CanvasPath::Create(path_handle);
  } else {
    CanvasPath::CreateFrom(path_handle, dst);
  }
}

bool CanvasPathMeasure::isClosed(int contour_index) {
  if (static_cast<std::vector<sk_sp<SkContourMeasure>>::size_type>(
          contour_index) < measures_.size()) {
    return measures_[contour_index]->isClosed();
  }
  return false;
}

bool CanvasPathMeasure::nextContour() {
  auto measure = path_measure_->next();
  if (measure) {
    measures_.push_back(std::move(measure));
    return true;
  }
  return false;
}

}  // namespace flutter

redpajama_set_name: RedPajamaGithub


text:
namespace TestStack.ConventionTests.Reporting
{
    using System.Text;
    using TestStack.ConventionTests.Internal;

    public class CsvReporter : ITestResultProcessor
    {
        public string Process(IConventionFormatContext context, ConventionResult result)
        {
            var formatter = new DefaultFormatter(result.DataType);
            var message = new StringBuilder();
            message.AppendLine(string.Join(",", formatter.DesribeType()));
            foreach (var item in result.Data)
            {
                message.AppendLine(string.Join(",", formatter.DesribeItem(item, context)));
            }
            return message.ToString();
        }

        public string RecommendedFileExtension { get { return "csv"; } }
    }
}


text:
package com.alachisoft.tayzgrid.config;

import com.alachisoft.tayzgrid.config.dom.CacheServerConfig;
import com.alachisoft.tayzgrid.config.dom.ConfigConverter;
import com.alachisoft.tayzgrid.common.configuration.ConfigurationBuilder;
import com.alachisoft.tayzgrid.runtime.exceptions.ConfigurationException;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlConfigReader extends ConfigReader
{
    private String _cacheId = "";
    private String _configFileName;
    private String _configSection;

    private static final char[] _trimChars = new char[] { ' ', '\t', '\r', '\n', '\'', '"' };

    public XmlConfigReader(String configFileName, String configSection)
    {
        _configFileName = configFileName;
        _configSection = configSection;
    }

    public final String getConfigFileName()
    {
        return _configFileName;
    }

    public final String getConfigSection()
    {
        return _configSection;
    }

    @Override
    public java.util.HashMap getProperties()
    {
        try
        {
            return GetProperties(_configFileName, _configSection);
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    public final java.util.ArrayList getPropertiesList() throws ConfigurationException
    {
        return GetAllProperties(_configFileName, _configSection);
    }

    public final String ToPropertiesString()
    {
        return ConfigReader.ToPropertiesString(getProperties());
    }

    protected final java.util.Hashtable GetAttributesOfNode(Node navigator)
    {
        java.util.Hashtable attributes = new java.util.Hashtable();
        for (int i = 0; i< navigator.getAttributes().getLength(); i++){
            attributes.put(navigator.getAttributes().item(i).getNodeName(), navigator.getAttributes().item(i).getNodeValue());
        }
        return attributes;
    }

    protected java.util.Hashtable BuildHashtable(java.util.Hashtable properties, Node navigator)
    {
         String name = navigator.getNodeName().toLowerCase();
        NodeList childNavigator = navigator.getChildNodes();
        if (!(childNavigator.getLength() > 0)) {
            if (navigator.getNodeType() == Node.ELEMENT_NODE) {
                properties.put(name, navigator.getNodeValue().trim());
            }
        }

        for (int i = 0; i < childNavigator.getLength(); i++) {
            java.util.Hashtable attributes = GetAttributesOfNode(childNavigator.item(i));

            java.util.Hashtable subproperties = BuildHashtable(new java.util.Hashtable(), childNavigator.item(0));
            if (attributes.containsKey("id")) {
                String id = attributes.get("id").toString();
                subproperties.put("id", id);
                subproperties.put("type", name);
                name = id.toLowerCase();
            }
            properties.put(name, subproperties);
        }
        return properties;
    }

    protected java.util.Hashtable BuildHashtable2(java.util.Hashtable properties, Node navigator)
    {

        int count = 0;
        do
        {
            String name = navigator.getNodeName().toLowerCase();
            NodeList  childNavigator = navigator.getChildNodes();
            java.util.Hashtable attributes = GetAttributesOfNode(childNavigator.item(0));//childNavigator.Current

            java.util.Hashtable subprops = new java.util.Hashtable();
            Iterator attribEnum = attributes.entrySet().iterator();
            while (attribEnum.hasNext())
            {
                Map.Entry pair = (Map.Entry)attribEnum.next();
                subprops.put(pair.getKey(), pair.getValue());
            }

            if (attributes.containsKey("id"))
            {
                String id = attributes.get("id").toString();
                subprops.put("type", name);

                if ( ! id.equals("internal-cache"))
                {
                    _cacheId = id;
                }
                name = id.toLowerCase();
            }

            if (childNavigator.getLength() > count)
            {
                count ++;
                java.util.Hashtable subproperties = BuildHashtable2(subprops, childNavigator.item(count));
                if (name.toLowerCase().equals("cache"))
                {
                    subproperties.put("class", _cacheId);
                    subproperties.put("name", _cacheId);
                }
                if ( ! name.equals(""))
                {
                    properties.put(name, subproperties);
                }
            }
            else
            {
                if ( ! name.equals(""))
                {
                    properties.put(name, subprops);
                }
            }
        }
        while (navigator.hasAttributes());
        navigator = navigator.getParentNode();
        return properties;
    }

    public final java.util.HashMap GetProperties(String fileName, String configSection) throws ConfigurationException
    {
        java.util.HashMap properties = new java.util.HashMap();
        try
        {
            tangible.RefObject<java.util.HashMap> tempRef_properties = new tangible.RefObject<java.util.HashMap>(properties);
            LoadConfig(fileName, tempRef_properties);
            properties = tempRef_properties.argvalue;
            return (java.util.HashMap)properties.get(configSection);
        }
        catch(Exception e)
        {
            throw new ConfigurationException("Specified config section '" + configSection + "' not found in file '" + fileName + "'. If it is a cache, it must be registered properly on this machine. --- " +  e.toString());
        }
    }

    private static com.alachisoft.tayzgrid.config.dom.CacheServerConfig[] LoadConfig(String fileName) throws ConfigurationException, Exception
    {
        ConfigurationBuilder builder = new ConfigurationBuilder(fileName);
        try
        {
            builder.RegisterRootConfigurationObject(com.alachisoft.tayzgrid.config.newdom.CacheServerConfig.class);
        }
        catch (Exception exception)
        {
            throw new ConfigurationException(exception.getMessage(), exception);
        }

        try
        {
            builder.ReadConfiguration();
        }
        catch (Exception exc)
        {
            throw new ConfigurationException(exc.getMessage(), exc.getCause());
        }
        com.alachisoft.tayzgrid.config.newdom.CacheServerConfig[] caches = new com.alachisoft.tayzgrid.config.newdom.CacheServerConfig[builder.getConfiguration().length];
        System.arraycopy(builder.getConfiguration(), 0, caches, 0, builder.getConfiguration().length);

        return convertToOldDom(caches);
    }

    //Changes for New Dom compatibility with Old Dom [Numan Hanif]
    private static com.alachisoft.tayzgrid.config.dom.CacheServerConfig[] convertToOldDom(com.alachisoft.tayzgrid.config.newdom.CacheServerConfig[] newCacheConfigsList) throws Exception {
        com.alachisoft.tayzgrid.config.dom.CacheServerConfig[] oldCacheConfigsList = new CacheServerConfig[newCacheConfigsList.length];

        for (int index = 0; index < newCacheConfigsList.length; index++)
        {
            oldCacheConfigsList[index]=com.alachisoft.tayzgrid.config.newdom.DomHelper.convertToOldDom(newCacheConfigsList[index]);
        }
        return oldCacheConfigsList;

    }

    private static void LoadConfig(String fileName, tangible.RefObject<java.util.HashMap> properties) throws ConfigurationException, Exception
    {
        ConfigurationBuilder builder = new ConfigurationBuilder(fileName);
        try
        {
            builder.RegisterRootConfigurationObject(com.alachisoft.tayzgrid.config.newdom.CacheServerConfig.class);
        }
        catch (Exception exception)
        {
            throw new ConfigurationException(exception.getMessage(), exception);
        }
        try
        {
            builder.ReadConfiguration();
        }
        catch (Exception exc)
        {
            throw new ConfigurationException(exc.getMessage(), exc.getCause());
        }
        com.alachisoft.tayzgrid.config.newdom.CacheServerConfig[] caches = new com.alachisoft.tayzgrid.config.newdom.CacheServerConfig[builder.getConfiguration().length];
        System.arraycopy(builder.getConfiguration(), 0, caches, 0, builder.getConfiguration().length);
        //Changes for New Dom compatibility with Old Dom [Numan Hanif]
        properties.argvalue = ConfigConverter.ToHashMap(convertToOldDom(caches));
    }

    public final java.util.Hashtable GetProperties(String fileName, String configSection, String partId) throws ConfigurationException
    {
        java.util.HashMap properties = new java.util.HashMap();
        try
        {
            tangible.RefObject<java.util.HashMap> tempRef_properties = new tangible.RefObject<java.util.HashMap>(properties);
            LoadConfig(fileName, tempRef_properties);
            properties = tempRef_properties.argvalue;
            return (java.util.Hashtable)properties.get(configSection);
        }
        catch (Exception e)
        {
            throw new ConfigurationException("Specified config section '" + configSection + "' not found in file '" + fileName + "'. If it is a cache, it must be registered properly on this machine. --- " +  e.toString());
        }
    }

    public final java.util.Hashtable GetProperties2(String fileName, String configSection, String partId) throws ConfigurationException
    {
        java.util.Hashtable properties = new java.util.Hashtable();
        try
        {

            File fXmlFile = new File("c:\\file.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            Node i = (Node) doc.getElementsByTagName("/configuration/cache-config");
            while (i.hasChildNodes())
            {
                Element element;
                if (i.getNodeType() == Node.ELEMENT_NODE)
                {
                    element = (Element) i;

                    String name = getTagValue("name", element).toLowerCase();
                    if (name.compareTo(configSection.toLowerCase()) != 0)
                    {
                        continue;
                    }

                    if (i.hasChildNodes())
                    {
                        java.util.Hashtable section = new java.util.Hashtable();

                        BuildHashtable2(section, i.getNextSibling());

                        section.put("name", getTagValue("name", element));
                        section.put("inproc", getTagValue("inproc", element));

                        properties.put(getTagValue("name", element).toLowerCase(), section);
                    }
                }
            }
            return properties;
        }
        catch (Exception e)
        {
            throw new ConfigurationException("Error occured while reading configuration", e);
        }
    }

    private static String getTagValue(String sTag, Element eElement) {
	NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

        Node nValue = (Node) nlList.item(0);

	return nValue.getNodeValue();
  }

    public final CacheServerConfig GetConfigDom() throws ConfigurationException
    {
        try
        {
            CacheServerConfig[] configs = LoadConfig(this._configFileName);
            CacheServerConfig configDom = null;
            if (configs != null)
            {
                for (CacheServerConfig config : configs)
                {
                    if (config.getName() != null && config.getName().toLowerCase().equals(this._configSection.toLowerCase()))
                    {
                        configDom = config;
                        break;
                    }
                }
            }

            if (configDom != null)
            {
                return configDom;
            }
        }
        catch (Exception e)
        {
            throw new ConfigurationException("Error occured while reading configuration", e);
        }
        throw new ConfigurationException("Specified config section '" + this._configSection + "' not found in file '" + this._configFileName + "'. If it is a cache, it must be registered properly on this machine.");
    }

    public final java.util.ArrayList GetAllProperties(String fileName, String configSection) throws ConfigurationException
    {
        java.util.ArrayList propsList = new java.util.ArrayList();
        java.util.HashMap properties = new java.util.HashMap();

        try
        {
            tangible.RefObject<java.util.HashMap> tempRef_properties = new tangible.RefObject<java.util.HashMap>(properties);
            LoadConfig(fileName, tempRef_properties);
            properties = tempRef_properties.argvalue;
            if (properties.containsKey(configSection.toLowerCase()))
            {
                propsList.add(properties.get(configSection.toLowerCase()));
            }
            return propsList;
        }
        catch (Exception e)
        {
            throw new ConfigurationException("Specified config section '" + configSection + "' not found in file '" + fileName + "'. If it is a cache, it must be registered properly on this machine. --- " +  e.toString());
        }
    }

    public final java.util.ArrayList GetAllProperties2(String fileName, String configSection) throws ConfigurationException
    {
        java.util.ArrayList propsList = new java.util.ArrayList();
        java.util.Hashtable properties = new java.util.Hashtable();

        try
        {

            File fXmlFile = new File("c:\\file.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            Node i = (Node) doc.getElementsByTagName("/configuration/cache-config");
            while (i.hasAttributes())
            {
                if (i.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element element = (Element) i;
                    if (getTagValue("name", element) == null)
                    {
                        continue;
                    }

                    String name = getTagValue("name",element).toLowerCase();
                    if (name.compareTo(configSection.toLowerCase()) != 0)
                    {
                        continue;
                    }

                    if (i.hasChildNodes())
                    {
                        java.util.Hashtable section = new java.util.Hashtable();

                        BuildHashtable2(section, i.getNextSibling());

                        section.put("name", getTagValue("name", element));
                        section.put("inproc", getTagValue("inproc", element));

                        Object tempVar = section.clone();
                        propsList.add((java.util.Hashtable) ((tempVar instanceof java.util.Hashtable) ? tempVar : null));
                    }
                }
            }
            return propsList;
        }
        catch (Exception e)
        {
            throw new ConfigurationException("Specified config section '" + configSection + "' not found in file '" + fileName + "'. If it is a cache, it must be registered properly on this machine. --- " +  e.toString());
        }
    }

    public final java.util.Map GetProperties(String fileName) throws ConfigurationException
    {
        java.util.HashMap properties = new java.util.HashMap();
        try
        {
            tangible.RefObject<java.util.HashMap> tempRef_properties = new tangible.RefObject<java.util.HashMap>(properties);
            LoadConfig(fileName, tempRef_properties);
            properties = tempRef_properties.argvalue;
            return properties;
        }
        catch(Exception e)
        {
            throw new ConfigurationException("Error occured while reading configuration", e);
        }
    }

    public final java.util.Map GetProperties2(String fileName)throws ConfigurationException
    {
        java.util.Hashtable properties = new java.util.Hashtable();
        try
        {

            File fXmlFile = new File("c:\\file.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            Node i = (Node) doc.getElementsByTagName("/configuration/cache-config");

            while(i.hasChildNodes())
            {
                if (i.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element element = (Element) i;
                    if (i.hasChildNodes())
                    {
                        java.util.Hashtable section = new java.util.Hashtable();

                        BuildHashtable2(section, i.getNextSibling());

                        section.put("name", getTagValue("name", element));
                        section.put("inproc", getTagValue("inproc", element));

                        properties.put(getTagValue("name", element).toLowerCase(), section);
                    }
                }
            }
            return properties;
        }
        catch (Exception e)
        {
            throw new ConfigurationException("Error occured while reading configuration", e);
        }
    }
}


text:
using System;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace AwesomeLogger.Subscriptions.Api.Infrastructure.Filters
{
    public class AuthorizeBearerAttribute : Attribute, IAuthenticationFilter
    {
        public AuthorizeBearerAttribute(string token)
        {
            Token = token;
        }

        public string Token { get; set; }

        public bool AllowMultiple
        {
            get { return true; }
        }

        public virtual Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            var authorization = context.Request.Headers.Authorization;
            if (authorization == null)
            {
                return Task.FromResult(0);
            }

            if (string.Equals(authorization.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase) &&
                authorization.Parameter == Token)
            {
                context.Principal = new GenericPrincipal(new GenericIdentity(Token), null);
            }

            return Task.FromResult(0);
        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            return Task.FromResult(0);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="PES Marigold">

    <title>Proyecto Marigold</title>

   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
   <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

Vivir en un hotel

Algunas consideraciones prácticas.

Ventajas

Vivir en un hotel significa, que no hay que:

comprar en el súper, ni cocinar, ni bajar la basura.

lavar los platos, sartenes y cacerolas, aunque sea usando los lavavajillas.

limpiar baños ni ventanas, ni fregar y barrer ni pasar el aspirador.

lavar las sábanas y la ropa, ni planchar.

hay que llamar al lampista, o al electricista ni al carpintero para mantenimiento.

subirse a una escalera para cambiar la bombilla fundida.

pintar el pisito cada cuantos años, o comprar nuevas cortinas.

reponer el microondas ni la calefacción, ni la TV ni el acondicionador de aire.

controlar las facturas de la luz, agua, gas y teléfono.

hipotecarse, ni hacer contratos de alquiler, ni juntas de vecinos, ni derramas.

amueblar el piso, ni comprar electrodomésticos.

Etc, etc, etc ...

Y además:

De haber 30-40 contratos de ADSL se pasa a uno sólo, pero de alta velocidad.

De haber 30-40 hornos, microondas, aspiradores, etc se pasan a uno o dos sólo, pero industriales.

De haber 10-20 coches se pasa a tres o cuatro sólo, pero compartidos.

Etc, etc, etc ...

Y encima:

La intimidad está garantizada, pero siempre estarás acompañado si lo deseas.

La seguridad ante robos o atracos es mucho más eficiente.

Si te indispones, siempre tienes alguien que se preocupe por tí.

Se pueden contratar seguros médicos en muchas mejores condiciones.

Etc, etc, etc ...

Sólo pertenecer a la cooperativa y pagar las cuotas que se acuerden, cuando se entre a vivir al hotel
elegido. No es gratis ni mucho más barato que otras opciones (no es el objetivo), pero para un joven
que quiere emanciparse, puede ser una alternativa a alquilar una habitación en un piso compartido.

Además se pueden potenciar asociaciones como guifi.net, por una internet más libre, o Som Energia, para impulsar el empleo de energías alternativas.

Inicio

Anterior

Siguiente

Links

Capitalismo

Peak Oil

Decrecimiento

© Marigold 2015

Sé parte del proyecto. Envía un e-mail a: info@marigold.es

Para obtener un borrador del proyecto en PDF, pincha aquí


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';

import i18n from '../lib/i18n';
import filterCollection from '../lib/filter_collection';

import LoginTopBar from '../containers/LoginTopBar';
import UserPhoto from '../components/UserPhoto';
import PublicFooter from '../components/PublicFooter';
import CollectiveCard from '../components/CollectiveCard';
import SponsoredCard from '../components/SponsoredCard';
import Markdown from '../components/Markdown';
import ContentEditable from '../components/ContentEditable';
import notify from '../actions/notification/notify';
import Notification from './Notification';

import uploadImage from '../actions/images/upload';
import updateUser from '../actions/users/update';
import validateSchema from '../actions/form/validate_schema';
import profileSchema from '../joi_schemas/profile';
import appendProfileForm from '../actions/form/append_profile';

import { prettyLink } from '../lib/utils';

export class ProfilePage extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  saveUser(attribute) {
  const {
      profile,
      updateUser,
      profileForm,
      validateSchema,
      appendProfileForm,
      notify,
    } = this.props;
    appendProfileForm(attribute);
    return validateSchema(profileForm.attributes, profileSchema)
      .then(() => updateUser(profile.id, attribute))
      .catch(({message}) => notify('error', message));
  }

  render() {

    const { profile, i18n, profileForm } = this.props;
    const belongsTo = filterCollection(profile.groups, { role: 'MEMBER' });
    const backing = filterCollection(profile.groups, { role: 'BACKER' });
    const isEmpty = belongsTo.length === backing.length && backing.length === 0;

    const sponsorshipRequirements = `We are supporting the open source community. If you have an open source project, [create an open collective](https://opencollective.com/opensource/apply) and apply to receive sponsorship.`; // Markdown string
    const isSponsoring = [
      'digitalocean', 'auth0', 'saucelabs',
      'pubnub', 'idonethis', 'gitlab'
    ].indexOf(profile.username) !== -1;

    return (

        <Notification {...this.props} autoclose/>
        <LoginTopBar />
        <UserPhoto
          editable={profile.canEditUser}
          onChange={(avatar) => this.saveUser({avatar})}
          user={{ avatar: profile.avatar }}
          addBadge={!profile.isOrganization}
          className={`mx-auto ${profile.isOrganization ? 'organization' : ''}`}
          {...this.props}
        />
        {!profile.isOrganization &&
Hello I'm
}
        {profile.isOrganization &&
Hello We are
}

        <ContentEditable
              className='line2 ContentEditable-name'
              html={profile.name}
              disabled={!profile.canEditUser}
              onChange={event => this.saveUser({name: event.target.value})}
              placeholder={i18n.getString('defaultName')} />

          {profile.canEditUser &&
            <ContentEditable
                  className='ContentEditable-username'
                  html={profile.username}
                  disabled={false}
                  multiline={false}
                  onChange={event => this.saveUser({username: event.target.value})}
                  />
          }

          <ContentEditable
                className='ContentEditable-website'
                html={profile.canEditUser ? profile.website : prettyLink(profile.website)}
                disabled={!profile.canEditUser}
                multiline={false}
                onChange={event => this.saveUser({website: event.target.value})}
                placeholder={i18n.getString('defaultWebsite')} />
          <ContentEditable
                className='ContentEditable-twitterHandle'
                html={profile.canEditUser ? profile.twitterHandle : profile.twitterHandle ? `<a href="https://twitter.com/${profile.twitterHandle}" target="_blank">@${profile.twitterHandle}</a>` : ''}
                disabled={!profile.canEditUser}
                multiline={false}
                onChange={event => this.saveUser({twitterHandle: event.target.value})}
                placeholder={i18n.getString('defaultTwitterHandle')} />

        <ContentEditable
              className='line3 ContentEditable-description'
              html={profile.description}
              format='markdown'
              disabled={!profile.canEditUser}
              onChange={event => this.saveUser({description: event.target.value})}
              placeholder={i18n.getString('defaultDescription')}
              style={{textAlign: 'center'}} />

        {(profile.longDescription || profile.canEditUser) && (
            <Markdown
              value={ (profileForm.attributes.longDescription === '' || profileForm.attributes.longDescription) ? profileForm.attributes.longDescription : profile.longDescription }
              canEdit={profile.canEditUser}
              onChange={longDescription => this.saveUser({ longDescription }) }
              className='line3 longDescription ContentEditable-long-description'
              placeholder={i18n.getString('defaultProfileLongDescription')}
              />
        )}

        {belongsTo.length ? (

{i18n.getString('proudMember')}

              {belongsTo.map((group, index) => <CollectiveCard
                index={index}
                i18n={i18n}
                isCollectiveOnProfile={true}
                group={group}
                />
              )}

          ) : null
        }
        {backing.length ? (

{profile.isOrganization ? i18n.getString('WeAreProudSupporters') : i18n.getString('IamAProudSupporter')}

              {backing.map((group, index) => {
                // When sponsored amount & tier exists the `SponsoredCard` will be rendered
                if (group.myTier) {
                  return (
                    <SponsoredCard tier={group.myTier} index={index} i18n={i18n} group={group} />
                  )
                } else {
                  return <CollectiveCard isCollectiveOnProfile={true} index={index} i18n={i18n} group={group} />
                }
              })}

          ) : null
        }

        {profile.isOrganization && isSponsoring && (

We are receiving sponsorship applications

                <Markdown value={ sponsorshipRequirements } />

              <a href={`mailto:info+${profile.username}@opencollective.com`}>

apply for sponsorship

        )}

        {!profile.isOrganization && (
          <div style={{textAlign: 'center', margin: `${isEmpty ? 0 : 48}px auto 78px auto`, opacity: '.4'}} >
            {isEmpty ? (

This Profile page is so empty you might find a ghost

              ) : null
            }
            <svg width='36px' height='36px' className='-light-blue align-middle mr1'>
              <use xlinkHref='#svg-isotype'/>
            </svg>

        )}
        <PublicFooter />

    )
  }
}

export default connect(mapStateToProps, {
  uploadImage,
  validateSchema,
  appendProfileForm,
  notify,
  updateUser
})(ProfilePage);

function mapStateToProps({form}) {

  const profileForm = form.profile;

  return {
    i18n: i18n('en'),
    profileForm
  };
}


text:
from tests.testcase import CoverageReporterTestCase

class MinimumTest(CoverageReporterTestCase):

    def test_minimum(self):
        data = self.create_coverage_data({'foo.py' : {'missing' : 20},
                                          'bar.py' : {'missing' : 10 }})
        filter = self.load_plugin('minimum')
        filter.minimum_missing = 15
        assert(filter.report_path('foo.py', data))
        assert(not filter.report_path('bar.py', data))


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Age Calculator Exercise</title>

Age Calculator

Enter your age in years and find out how many days you've been alive.


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/chat_file_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/chat_file_pressed" android:state_selected="true"/>
    <item android:drawable="@drawable/chat_file_normal"/>

</selector>


text:
package com.navercorp.pinpoint.plugin.log4j2;

import com.navercorp.pinpoint.pluginit.utils.AgentPath;
import com.navercorp.pinpoint.test.plugin.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@PinpointConfig("pinpoint-spring-bean-test.config")
@JvmVersion(8)
@Dependency({"org.apache.logging.log4j:log4j-core:[2.17.1,]", "com.lmax:disruptor:[3.4.4]"})
@JvmArgument({"-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector", "-DtestLoggerEnable=false"})
public class Log4j2ForAsyncLoggerIT extends Log4j2TestBase {

    @Test
    public void test() {
        Logger logger = LogManager.getLogger();

        final String location = getLoggerJarLocation(logger);
        final String testVersion = getTestVersion();
        System.out.println("Log4j2 jar location:" + location);
        Assert.assertTrue("test version is not " + getTestVersion(), location.contains("/" + testVersion + "/"));

        logger.error("for log4j2 plugin async logger test");
        Assert.assertNotNull("txId", ThreadContext.get("PtxId"));
        Assert.assertNotNull("spanId", ThreadContext.get("PspanId"));
    }

}


text:
extern "C" {
#endif

#define SNF_NONE 0
typedef unsigned char byte;

#ifdef __cplusplus
}
#endif  // extern "C"

#endif // _SNIFFLE_GLOBAL_H


text:
var clockInterval;
var clockRunning = false;
var stopwatchInterval;
var stopwatchRunning = false;
var showStopwatch = false;
var stopwatchCentis = 0;

var zeroPad2 = function(n) {
    return (n < 10) ? ("0" + n) : n;
}

var incClock = function() {
        var now = $.format.date(new Date(), 'HH:mm:ss');
        $('.clock').text(now);
}

var startClock = function() {
    if (!clockRunning) {
        incClock();
        clockInterval = setInterval(function() {
            incClock();
        }, 1000);
        clockRunning = true;
    }
};

var stopClock = function() {
    clearInterval(clockInterval);
    clockRunning = false;
}

var displayStopwatch = function() {
    var centis = stopwatchCentis % 100;
    var seconds = Math.floor(stopwatchCentis / 100) % 60;
    var minutes = Math.floor(stopwatchCentis / 6000) % 60;
    var hours = Math.floor(stopwatchCentis / 360000);
    $('.clock').text((hours) + ':' + zeroPad2(minutes) + ':' + zeroPad2(seconds) + ':' + zeroPad2(centis));
}

var incStopwatch = function() {
    if (showStopwatch) {
        displayStopwatch();
    }
    stopwatchCentis++;
}

var startStopwatch = function() {
    stopClock();
    showStopwatch = true;
    if (!stopwatchRunning) {
        incStopwatch();
        stopwatchInterval = setInterval(function() {
            incStopwatch();
        }, 10);
        stopwatchRunning = true;
    }
}
var stopStopwatch = function() {
    clearInterval(stopwatchInterval);
    stopwatchRunning = false;
}

var clearStopwatch = function() {
    stopStopwatch();
    stopwatchCentis = 0;
    $('.clock').text('0:00:00:00');

}

$(function() {
    startClock();

    $('.stopwatch-button').click(function() {
        $('.stopwatch-controls').fadeIn();
        stopClock();
        displayStopwatch();
        showStopwatch = true;
    })
    $('.clock-button').click(function() {
        showStopwatch = false;
        $('.stopwatch-controls').fadeOut();
        startClock();
    })
    $('.sw-start').mousedown(function() {
        startStopwatch();
    })
    $('.sw-stop').mousedown(function() {
        stopStopwatch();
    })
    $('.sw-clear').mousedown(function() {
        clearStopwatch();
    })

}); // document ready function


text:
import { Injectable } from '@angular/core';
import { Action } from '@ngrx/store';

@Injectable()
export class CandidateActions {
    public static LOAD_CANDIDATES = '[Candidates] Load Candidates';
    public static LOAD_CANDIDATES_SUCCESS = '[Candidates] Load Candidates Success';
    public static GET_CANDIDATE = '[Candidate] Get Candidate';
    public static GET_CANDIDATE_SUCCESS = '[Candidate] Get Candidate Success';
    public static RESET_BLANK_CANDIDATE = '[Candidate] Reset Blank Candidate';
    public static ADD_CANDIDATE = '[Candidate] Add Candidate';
    public static ADD_CANDIDATE_SUCCESS = '[Candidate] Add Candidate Success';
    public static UPDATE_CANDIDATE = '[Candidate] Update Candidate';
    public static UPDATE_CANDIDATE_SUCCESS = '[Candidate] Update Candidate Success';

    public loadCandidates(): Action {
        return {
            type: CandidateActions.LOAD_CANDIDATES
        };
    }
    public loadCandidatesSuccess(candidates): Action {
        return {
            type: CandidateActions.LOAD_CANDIDATES_SUCCESS,
            payload: candidates
        };
    }
    public getCandidate(_id): Action {
        return {
            type: CandidateActions.GET_CANDIDATE,
            payload: _id
        };
    }

    public getCandidateSuccess(candidate): Action {
        return {
            type: CandidateActions.GET_CANDIDATE_SUCCESS,
            payload: candidate
        };
    }
    public resetBlankCandidate(): Action {
        return {
            type: CandidateActions.RESET_BLANK_CANDIDATE
        };
    }
    public addCandidate(candidate): Action {
        return {
            type: CandidateActions.ADD_CANDIDATE,
            payload: candidate
        };
    }
    public addCandidateSuccess(candidate): Action {
        return {
            type: CandidateActions.ADD_CANDIDATE_SUCCESS,
            payload: candidate
        };
    }
    public updateCandidate(candidate): Action {
        return {
            type: CandidateActions.UPDATE_CANDIDATE,
            payload: candidate
        };
    }
    public updateCandidateSuccess(candidate): Action {
        return {
            type: CandidateActions.UPDATE_CANDIDATE_SUCCESS,
            payload: candidate
        };
    }

}


text:
#include "cbtCylinderShape.h"

cbtCylinderShape::cbtCylinderShape(const cbtVector3& halfExtents)
	: cbtConvexInternalShape(),
	  m_upAxis(1)
{
	cbtVector3 margin(getMargin(), getMargin(), getMargin());
	m_implicitShapeDimensions = (halfExtents * m_localScaling) - margin;

	setSafeMargin(halfExtents);

	m_shapeType = CYLINDER_SHAPE_PROXYTYPE;
}

cbtCylinderShapeX::cbtCylinderShapeX(const cbtVector3& halfExtents)
	: cbtCylinderShape(halfExtents)
{
	m_upAxis = 0;
}

cbtCylinderShapeZ::cbtCylinderShapeZ(const cbtVector3& halfExtents)
	: cbtCylinderShape(halfExtents)
{
	m_upAxis = 2;
}

void cbtCylinderShape::getAabb(const cbtTransform& t, cbtVector3& aabbMin, cbtVector3& aabbMax) const
{
	cbtTransformAabb(getHalfExtentsWithoutMargin(), getMargin(), t, aabbMin, aabbMax);
}

void cbtCylinderShape::calculateLocalInertia(cbtScalar mass, cbtVector3& inertia) const
{
//Until Bullet 2.77 a box approximation was used, so uncomment this if you need backwards compatibility
//#define USE_BOX_INERTIA_APPROXIMATION 1
#ifndef USE_BOX_INERTIA_APPROXIMATION

	/*
	cylinder is defined as following:
	*
	* - principle axis aligned along y by default, radius in x, z-value not used
	* - for cbtCylinderShapeX: principle axis aligned along x, radius in y direction, z-value not used
	* - for cbtCylinderShapeZ: principle axis aligned along z, radius in x direction, y-value not used
	*
	*/

	cbtScalar radius2;                                    // square of cylinder radius
	cbtScalar height2;                                    // square of cylinder height
	cbtVector3 halfExtents = getHalfExtentsWithMargin();  // get cylinder dimension
	cbtScalar div12 = mass / 12.f;
	cbtScalar div4 = mass / 4.f;
	cbtScalar div2 = mass / 2.f;
	int idxRadius, idxHeight;

	switch (m_upAxis)  // get indices of radius and height of cylinder
	{
		case 0:  // cylinder is aligned along x
			idxRadius = 1;
			idxHeight = 0;
			break;
		case 2:  // cylinder is aligned along z
			idxRadius = 0;
			idxHeight = 2;
			break;
		default:  // cylinder is aligned along y
			idxRadius = 0;
			idxHeight = 1;
	}

	// calculate squares
	radius2 = halfExtents[idxRadius] * halfExtents[idxRadius];
	height2 = cbtScalar(4.) * halfExtents[idxHeight] * halfExtents[idxHeight];

	// calculate tensor terms
	cbtScalar t1 = div12 * height2 + div4 * radius2;
	cbtScalar t2 = div2 * radius2;

	switch (m_upAxis)  // set diagonal elements of inertia tensor
	{
		case 0:  // cylinder is aligned along x
			inertia.setValue(t2, t1, t1);
			break;
		case 2:  // cylinder is aligned along z
			inertia.setValue(t1, t1, t2);
			break;
		default:  // cylinder is aligned along y
			inertia.setValue(t1, t2, t1);
	}
#else   //USE_BOX_INERTIA_APPROXIMATION
	//approximation of box shape
	cbtVector3 halfExtents = getHalfExtentsWithMargin();

	cbtScalar lx = cbtScalar(2.) * (halfExtents.x());
	cbtScalar ly = cbtScalar(2.) * (halfExtents.y());
	cbtScalar lz = cbtScalar(2.) * (halfExtents.z());

	inertia.setValue(mass / (cbtScalar(12.0)) * (ly * ly + lz * lz),
					 mass / (cbtScalar(12.0)) * (lx * lx + lz * lz),
					 mass / (cbtScalar(12.0)) * (lx * lx + ly * ly));
#endif  //USE_BOX_INERTIA_APPROXIMATION
}

SIMD_FORCE_INLINE cbtVector3 CylinderLocalSupportX(const cbtVector3& halfExtents, const cbtVector3& v)
{
	const int cylinderUpAxis = 0;
	const int XX = 1;
	const int YY = 0;
	const int ZZ = 2;

	//mapping depends on how cylinder local orientation is
	// extents of the cylinder is: X,Y is for radius, and Z for height

	cbtScalar radius = halfExtents[XX];
	cbtScalar halfHeight = halfExtents[cylinderUpAxis];

	cbtVector3 tmp;
	cbtScalar d;

	cbtScalar s = cbtSqrt(v[XX] * v[XX] + v[ZZ] * v[ZZ]);
	if (s != cbtScalar(0.0))
	{
		d = radius / s;
		tmp[XX] = v[XX] * d;
		tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
		tmp[ZZ] = v[ZZ] * d;
		return tmp;
	}
	else
	{
		tmp[XX] = radius;
		tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
		tmp[ZZ] = cbtScalar(0.0);
		return tmp;
	}
}

inline cbtVector3 CylinderLocalSupportY(const cbtVector3& halfExtents, const cbtVector3& v)
{
	const int cylinderUpAxis = 1;
	const int XX = 0;
	const int YY = 1;
	const int ZZ = 2;

	cbtScalar radius = halfExtents[XX];
	cbtScalar halfHeight = halfExtents[cylinderUpAxis];

	cbtVector3 tmp;
	cbtScalar d;

	cbtScalar s = cbtSqrt(v[XX] * v[XX] + v[ZZ] * v[ZZ]);
	if (s != cbtScalar(0.0))
	{
		d = radius / s;
		tmp[XX] = v[XX] * d;
		tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
		tmp[ZZ] = v[ZZ] * d;
		return tmp;
	}
	else
	{
		tmp[XX] = radius;
		tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
		tmp[ZZ] = cbtScalar(0.0);
		return tmp;
	}
}

inline cbtVector3 CylinderLocalSupportZ(const cbtVector3& halfExtents, const cbtVector3& v)
{
	const int cylinderUpAxis = 2;
	const int XX = 0;
	const int YY = 2;
	const int ZZ = 1;

	//mapping depends on how cylinder local orientation is
	// extents of the cylinder is: X,Y is for radius, and Z for height

	cbtScalar radius = halfExtents[XX];
	cbtScalar halfHeight = halfExtents[cylinderUpAxis];

	cbtVector3 tmp;
	cbtScalar d;

	cbtScalar s = cbtSqrt(v[XX] * v[XX] + v[ZZ] * v[ZZ]);
	if (s != cbtScalar(0.0))
	{
		d = radius / s;
		tmp[XX] = v[XX] * d;
		tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
		tmp[ZZ] = v[ZZ] * d;
		return tmp;
	}
	else
	{
		tmp[XX] = radius;
		tmp[YY] = v[YY] < 0.0 ? -halfHeight : halfHeight;
		tmp[ZZ] = cbtScalar(0.0);
		return tmp;
	}
}

cbtVector3 cbtCylinderShapeX::localGetSupportingVertexWithoutMargin(const cbtVector3& vec) const
{
	return CylinderLocalSupportX(getHalfExtentsWithoutMargin(), vec);
}

cbtVector3 cbtCylinderShapeZ::localGetSupportingVertexWithoutMargin(const cbtVector3& vec) const
{
	return CylinderLocalSupportZ(getHalfExtentsWithoutMargin(), vec);
}
cbtVector3 cbtCylinderShape::localGetSupportingVertexWithoutMargin(const cbtVector3& vec) const
{
	return CylinderLocalSupportY(getHalfExtentsWithoutMargin(), vec);
}

void cbtCylinderShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const cbtVector3* vectors, cbtVector3* supportVerticesOut, int numVectors) const
{
	for (int i = 0; i < numVectors; i++)
	{
		supportVerticesOut[i] = CylinderLocalSupportY(getHalfExtentsWithoutMargin(), vectors[i]);
	}
}

void cbtCylinderShapeZ::batchedUnitVectorGetSupportingVertexWithoutMargin(const cbtVector3* vectors, cbtVector3* supportVerticesOut, int numVectors) const
{
	for (int i = 0; i < numVectors; i++)
	{
		supportVerticesOut[i] = CylinderLocalSupportZ(getHalfExtentsWithoutMargin(), vectors[i]);
	}
}

void cbtCylinderShapeX::batchedUnitVectorGetSupportingVertexWithoutMargin(const cbtVector3* vectors, cbtVector3* supportVerticesOut, int numVectors) const
{
	for (int i = 0; i < numVectors; i++)
	{
		supportVerticesOut[i] = CylinderLocalSupportX(getHalfExtentsWithoutMargin(), vectors[i]);
	}
}


text:
. ./cmd.sh ## You'll want to change cmd.sh to something that will work on your system.
           ## This relates to the queue.
. path.sh

# Set paths to various datasets
swbd=/path/to/LDC97S62
fisher_dirs="/path/to/LDC2004T19/fe_03_p1_tran/ /path/to/LDC2005T19/fe_03_p2_tran/" # Set to "" if you don't have the fisher corpus
eval2000_dirs="/path/to/LDC2002S09/hub5e_00 /path/to/LDC2002T43"

# CMU Rocks
#fisher_dirs="/data/ASR5/babel/ymiao/Install/LDC/LDC2004T19/fe_03_p1_tran/ /data/ASR5/babel/ymiao/Install/LDC/LDC2005T19/fe_03_p2_tran/"
#eval2000_dirs="/data/ASR4/babel/ymiao/CTS/LDC2002S09/hub5e_00 /data/ASR4/babel/ymiao/CTS/LDC2002T43"

echo =====================================================================
echo "             Data Preparation and FST Construction                 "
echo =====================================================================
# Use the same datap prepatation script from Kaldi
local/swbd1_data_prep.sh $swbd  || exit 1;

# Construct the phoneme-based lexicon
local/swbd1_prepare_phn_dict.sh || exit 1;

# Compile the lexicon and token FSTs
utils/ctc_compile_dict_token.sh data/local/dict_phn data/local/lang_phn_tmp data/lang_phn || exit 1;

# Train and compile LMs.
local/swbd1_train_lms.sh data/local/train/text data/local/dict_phn/lexicon.txt data/local/lm $fisher_dirs || exit 1;

# Compile the language-model FST and the final decoding graph TLG.fst
local/swbd1_decode_graph.sh data/lang_phn data/local/dict_phn/lexicon.txt || exit 1;

# Data preparation for the eval2000 set
local/eval2000_data_prep.sh $eval2000_dirs

echo =====================================================================
echo "                    FBank Feature Generation                       "
echo =====================================================================
fbankdir=fbank

# Generate the fbank features; by default 40-dimensional fbanks on each frame
steps/make_fbank.sh --cmd "$train_cmd" --nj 32 data/train exp/make_fbank/train $fbankdir || exit 1;
utils/fix_data_dir.sh data/train || exit;
steps/compute_cmvn_stats.sh data/train exp/make_fbank/train $fbankdir || exit 1;

steps/make_fbank.sh --cmd "$train_cmd" --nj 10 data/eval2000 exp/make_fbank/eval2000 $fbankdir || exit 1;
utils/fix_data_dir.sh data/eval2000 || exit;
steps/compute_cmvn_stats.sh data/eval2000 exp/make_fbank/eval2000 $fbankdir || exit 1;

# Use the first 4k sentences as dev set, around 5 hours
utils/subset_data_dir.sh --first data/train 4000 data/train_dev
n=$[`cat data/train/segments | wc -l` - 4000]
utils/subset_data_dir.sh --last data/train $n data/train_nodev

# Create a smaller training set by selecting the first 100k utterances, around 110 hours
utils/subset_data_dir.sh --first data/train_nodev 100000 data/train_100k
local/remove_dup_utts.sh 200 data/train_100k data/train_100k_nodup

# Finally the full training set, around 286 hours
local/remove_dup_utts.sh 300 data/train_nodev data/train_nodup

echo =====================================================================
echo "                Network Training with the 110-Hour Set             "
echo =====================================================================
# Specify network structure and generate the network topology
input_feat_dim=120   # dimension of the input features; we will use 40-dimensional fbanks with deltas and double deltas
lstm_layer_num=4     # number of LSTM layers
lstm_cell_dim=320    # number of memory cells in every LSTM layer

dir=exp_110h/train_phn_l${lstm_layer_num}_c${lstm_cell_dim}
mkdir -p $dir

target_num=`cat data/lang_phn/units.txt | wc -l`; target_num=$[$target_num+1]; #  #targets = #labels + 1 (the blank)

# Output the network topology
utils/model_topo.py --input-feat-dim $input_feat_dim --lstm-layer-num $lstm_layer_num \
  --lstm-cell-dim $lstm_cell_dim --target-num $target_num \
  --fgate-bias-init 1.0 > $dir/nnet.proto || exit 1;

# Label sequences; simply convert words into their label indices
utils/prep_ctc_trans.py data/lang_phn/lexicon_numbers.txt data/train_100k_nodup/text "<unk>" | gzip -c - > $dir/labels.tr.gz
utils/prep_ctc_trans.py data/lang_phn/lexicon_numbers.txt data/train_dev/text "<unk>" | gzip -c - > $dir/labels.cv.gz

# Train the network with CTC. Refer to the script for details about the arguments
steps/train_ctc_parallel.sh --add-deltas true --num-sequence 10 --frame-num-limit 25000 \
    --learn-rate 0.00004 --report-step 1000 --halving-after-epoch 12 \
    data/train_100k_nodup data/train_dev $dir || exit 1;

echo =====================================================================
echo "                            Decoding                               "
echo =====================================================================
# decoding
for lm_suffix in sw1_tg sw1_fsh_tgpr; do
  steps/decode_ctc_lat.sh --cmd "$decode_cmd" --nj 20 --beam 17.0 --lattice_beam 8.0 --max-active 5000 --acwt 0.6 \
    data/lang_phn_${lm_suffix} data/eval2000 $dir/decode_eval2000_${lm_suffix} || exit 1;
done

echo =====================================================================
echo "                  Network Training with the Full Set               "
echo =====================================================================
input_feat_dim=120   # dimension of the input features; we will use 40-dimensional fbanks with deltas and double deltas
lstm_layer_num=5     # number of LSTM layers
lstm_cell_dim=320    # number of memory cells in every LSTM layer

dir=exp/train_phn_l${lstm_layer_num}_c${lstm_cell_dim}
mkdir -p $dir

target_num=`cat data/lang_phn/units.txt | wc -l`; target_num=$[$target_num+1]; # #targets = #labels + 1 (the blank)

# Output the network topology
utils/model_topo.py --input-feat-dim $input_feat_dim --lstm-layer-num $lstm_layer_num \
  --lstm-cell-dim $lstm_cell_dim --target-num $target_num \
  --fgate-bias-init 1.0 > $dir/nnet.proto || exit 1;

# Label sequences; simply convert words into their label indices
utils/prep_ctc_trans.py data/lang_phn/lexicon_numbers.txt data/train_nodup/text "<unk>" | gzip -c - > $dir/labels.tr.gz
utils/prep_ctc_trans.py data/lang_phn/lexicon_numbers.txt data/train_dev/text "<unk>" | gzip -c - > $dir/labels.cv.gz

# Train the network with CTC. Refer to the script for details about the arguments
steps/train_ctc_parallel.sh --add-deltas true --num-sequence 10 --frame-num-limit 25000 \
    --learn-rate 0.00004 --report-step 1000 --halving-after-epoch 8 \
    data/train_nodup data/train_dev $dir || exit 1;

echo =====================================================================
echo "                            Decoding                               "
echo =====================================================================
# decoding
for lm_suffix in sw1_tg sw1_fsh_tgpr; do
  steps/decode_ctc_lat.sh --cmd "$decode_cmd" --nj 20 --beam 17.0 --lattice_beam 8.0 --max-active 5000 --acwt 0.6 \
    data/lang_phn_${lm_suffix} data/eval2000 $dir/decode_eval2000_${lm_suffix} || exit 1;
done


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary" />
    <stroke
        android:width="0dip"
        android:color="@color/colorPrimary" />
    <corners android:radius="20dip" />
    <padding
        android:bottom="0dip"
        android:left="0dip"
        android:right="0dip"
        android:top="0dip" />
</shape>


text:
'use strict';

function jsHelper(){
  /* jshint validthis: true */
  var result = '';
  var path = '';

  for (var i = 0, len = arguments.length; i < len; i++){
    path = arguments[i];

    if (i) result += '\n';

    if (Array.isArray(path)){
      result += jsHelper.apply(this, path);
    } else {
      if (path.substring(path.length - 3, path.length) !== '.js') path += '.js';
      result += '<script src="' + this.url_for(path) + '" type="text/javascript"></script>';
    }
  }

  return result;
}

module.exports = jsHelper;


text:
package ${package};

public class PropertyChecker {

    private String prompt;

    public PropertyChecker(String prompt) {
        System.out.println("PropertyChecker: constructor: " + prompt);
        this.prompt = prompt;
    }

    public String check() {
        System.out.println(prompt);
        return prompt;
    }

}


text:
layout: feature
title: 'Evidentiality'
shortdef: 'Evidentiality'
---

This document is a placeholder for the language-specific documentation
for `Evidentiality`.


text:
class NotifiableAdmin::Admin::JobsController <NotifiableAdmin::Admin::BaseController

  load_and_authorize_resource :app, :class => "Notifiable::App"
  load_and_authorize_resource :job, :class => "Delayed::Job"

  before_filter :find_jobs, :only => :index

  def index
    authorize! :read, Delayed::Job
    authorize! :read, @app

    @jobs = @jobs.order(:run_at).page(params[:page])
  end

  def destroy
    if @job.destroy && Notifiable::Notification.find(@job.notification_id).destroy
      redirect_to admin_account_app_jobs_path(@account, @app), notice: "Notification was deleted."
    else
      redirect_to admin_account_app_jobs_path(@account, @app), alert: @job.errors.full_messages.to_sentence
    end
  end

  private
  def find_jobs
    @jobs = Delayed::Job.where(:app_id => params[:app_id])
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />

    <title>Saving a Search Query</title>
    <link rel="StyleSheet" href="css/caMOD%20searches.css" type="text/css" media="all" />
    <link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" />

      Searching the caMOD Database > caMOD Search Results > Saving a Search Query

Saving a Search Query

 You must be logged in before you can save a search query.

Once you have submitted a search query, at the top of the Search Results page, a Save Query button displays. To save a search query, in the text box enter a name for the query and click the Save Query button.

To see search queries you have saved, click the View Saved Queries hypertext link in the lower left sidebar. (This link displays in the left sidebar in any caMOD viewer window.)

The Saved Queries dialog box displays search queries identified by the names you assigned to each, the time point of the search and the number of hits in the search.

To see the search criteria for each search query listed, click the Query Name.

Click the associated RUN QUERY or EDIT QUERY buttons to resubmit the query or to edit the query.

•

RUN QUERY--When you re-run the query, the new search result hits display in a Search Results page. If launched as a Keyword Search, the query term is highlighted in yellow wherever it occurs in the search results text.

•

EDIT QUERY--The Advanced Search page displays, allowing you to edit or add fields to your original query. To launch a search with the edited criteria and to save the changes in your query, click the Search button at the bottom of the Saved Queries page. The new Search Results page opens; at the top of the page, select the option to save the query with new criteria under the existing search query name or to save the new criteria under a new search query name, which you enter into the text box. Click the Save Query button to execute your selection.


text:
require 'spec_helper'
require_relative './factories/factories'
require_relative 'shared'

describe Lbaas2::Loadbalancers::Pools::MembersController, type: :controller do
  routes { Lbaas2::Engine.routes }

  default_params = {  domain_id: AuthenticationStub.domain_id,
                      project_id: AuthenticationStub.project_id,
                      loadbalancer_id: 'lb_123456789',
                      pool_id: 'pool_123456789' }

  before(:all) do
    FriendlyIdEntry.find_or_create_entry(
      'Domain', nil, default_params[:domain_id], 'default'
    )
    FriendlyIdEntry.find_or_create_entry(
      'Project', default_params[:domain_id], default_params[:project_id],
      default_params[:project_id]
    )
  end

  describe "GET 'index'" do
    before :each do
      members = double('elektron', service: double('octavia', get: double('get', map_to: [])))
      allow_any_instance_of(ServiceLayer::Lbaas2Service).to receive(:elektron).and_return(members)
    end

    it_behaves_like 'index action' do
      subject do
        @default_params = default_params
      end
    end
  end

  describe "GET 'show'" do
    before :each do
      member = double('elektron', service: double('octavia', get: double('get', map_to: double('member', to_json: {}))))
      allow_any_instance_of(ServiceLayer::Lbaas2Service).to receive(:elektron).and_return(member)
    end

    it_behaves_like 'show action' do
      subject do
        @default_params = default_params
      end
    end
  end

  describe "PUT 'update'" do
    before :each do
      member = double('elektron',
                      service: double('octavia',
                                      get: double('get', map_to: double('member', to_json: {}, identifier: '', attributes: {}, update_attributes: {}, update: {})), put: double('put', body: {})))
      allow_any_instance_of(ServiceLayer::Lbaas2Service).to receive(:elektron).and_return(member)
      allow_any_instance_of(Lbaas2::Loadbalancers::Pools::MembersController).to receive(:parseMemberParams).and_return(::Lbaas2::FakeFactory.new.member_params)
    end

    context 'network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_admin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json  #added content type to keep int attr (like weight) as integer
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_admin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'cloud_network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'cloud_network_admin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'member' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'member' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_poolmemberadmin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_poolmemberadmin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'network_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_viewer' }
          token
        end
      end
      it 'return 403 error' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'loadbalancer_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_viewer' }
          token
        end
      end
      it 'return 403 error' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'empty network roles' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token
        end
      end
      it 'return 403 error' do
        member = ::Lbaas2::FakeFactory.new.update_member
        put :update, params: default_params.merge({ id: member[:id], member: member }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
  end

  describe "PUT 'batch_update'" do
    before :each do
      elektronObj = double('elektron',
        service: double('octavia', get: double('get', map_to: double('lb', vip_subnet_id: 'some_id', to_json: {})),
                                   put: double('put', body: "")))
      allow_any_instance_of(ServiceLayer::Lbaas2Service).to receive(:elektron).and_return(elektronObj)
    end

    context 'network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_admin' }
          token
        end
      end
      it 'return http success' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_admin' }
          token
        end
      end
      it 'return http success' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response).to be_successful
      end
    end
    context 'cloud_network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'cloud_network_admin' }
          token
        end
      end
      it 'return http success' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response).to be_successful
      end
    end
    context 'member' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'member' }
          token
        end
      end
      it 'return http success' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_poolmemberadmin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_poolmemberadmin' }
          token
        end
      end
      it 'return http success' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response).to be_successful
      end
    end
    context 'network_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_viewer' }
          token
        end
      end
      it 'return 403 error' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'loadbalancer_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_viewer' }
          token
        end
      end
      it 'return 403 error' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'empty network roles' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token
        end
      end
      it 'return 403 error' do
        put :batch_update, params: default_params.merge({ members: [::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.240",  "protocol_port"=>8888), ::Lbaas2::FakeFactory.new.member("address"=>"10.180.0.241",  "protocol_port"=>8889)] }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
  end

  describe "POST 'create'" do
    before :each do
      member = double('elektron',
                      service: double('octavia', get: double('get', map_to: double('lb', vip_subnet_id: 'some_id', to_json: {})),
                                                 post: double('post', body: {})))
      allow_any_instance_of(ServiceLayer::Lbaas2Service).to receive(:elektron).and_return(member)
      allow_any_instance_of(Lbaas2::Loadbalancers::Pools::MembersController).to receive(:member_params).and_return(::Lbaas2::FakeFactory.new.member)
    end

    context 'network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_admin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_admin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'cloud_network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'cloud_network_admin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'member' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'member' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_poolmemberadmin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_poolmemberadmin' }
          token
        end
      end
      it 'return http success' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response).to be_successful
      end
    end
    context 'network_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_viewer' }
          token
        end
      end
      it 'return 403 error' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'loadbalancer_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_viewer' }
          token
        end
      end
      it 'return 403 error' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'empty network roles' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token
        end
      end
      it 'return 403 error' do
        member = ::Lbaas2::FakeFactory.new.member
        post :create, params: default_params.merge({ member: member }), as: :json
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
  end

  describe "DELETE 'destroy'" do
    before :each do
      member = double('elektron', service: double('octavia', delete: double('delete')))
      allow_any_instance_of(ServiceLayer::Lbaas2Service).to receive(:elektron).and_return(member)
    end

    context 'network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_admin' }
          token
        end
      end
      it 'return http success' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_admin' }
          token
        end
      end
      it 'return http success' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response).to be_successful
      end
    end
    context 'cloud_network_admin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'cloud_network_admin' }
          token
        end
      end
      it 'return http success' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response).to be_successful
      end
    end
    context 'member' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'member' }
          token
        end
      end
      it 'return http success' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response).to be_successful
      end
    end
    context 'loadbalancer_poolmemberadmin' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_poolmemberadmin' }
          token
        end
      end
      it 'return http success' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response).to be_successful
      end
    end
    context 'network_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'network_viewer' }
          token
        end
      end
      it 'return 403 error' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'loadbalancer_viewer' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token['roles'] << { 'id' => 'lbaas2_role', 'name' => 'loadbalancer_viewer' }
          token
        end
      end
      it 'return 403 error' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
    context 'no network roles' do
      before :each do
        stub_authentication do |token|
          token['roles'] = []
          token
        end
      end

      it 'return 403 error' do
        delete :destroy, params: default_params.merge(id: 'member_id')
        expect(response.code).to be == ('403')
        expect(response).to_not be_successful
      end
    end
  end

  describe "GET 'serversForSelect'" do
    before :each do
      lbs = double('elektron',
                   service: double('octavia',
                                   get: double('get', map_to: double('lb', vip_network_id: '123', to_json: {}))))
      allow_any_instance_of(ServiceLayer::Lbaas2Service).to receive(:elektron).and_return(lbs)

      allow_any_instance_of(ServiceLayer::KeyManagerService).to receive(:containers).and_return([])
      allow_any_instance_of(ServiceLayer::NetworkingService).to receive(:ports).and_return([])
      allow_any_instance_of(ServiceLayer::ComputeService).to receive(:servers).and_return([])
    end

    it_behaves_like 'GET action with editor context including loadbalancer_poolmemberadmin' do
      subject do
        loadbalancer = ::Lbaas2::FakeFactory.new.update_loadbalancer
        @default_params = default_params
        @extra_params = { id: loadbalancer[:id] }
        @path = 'serversForSelect'
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ReceiptActivity</title>
<meta name="date" content="2015-04-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

ca.ualberta.cs.scandaloutraveltracker.views

Class ReceiptActivity

java.lang.Object

Activity

ca.ualberta.cs.scandaloutraveltracker.views.MenuActivity

ca.ualberta.cs.scandaloutraveltracker.views.ReceiptActivity

public class ReceiptActivity
extends MenuActivity

Shows the image that had it's file path passed as an intent to the activity

Author:

Team3ScandalouStopwatch

Constructor Summary

Constructors

Constructor and Description

ReceiptActivity()

Method Summary

Methods inherited from class ca.ualberta.cs.scandaloutraveltracker.views.MenuActivity

onCreateOptionsMenu, onOptionsItemSelected

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ReceiptActivity

public ReceiptActivity()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD


text:
package org.apache.calcite.sql.test;

import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorWithHints;

/**
* Creates the objects needed to run a SQL parsing or validation test.
 *
 * @see org.apache.calcite.sql.test.SqlTester
*/
public interface SqlTestFactory {
  SqlOperatorTable createOperatorTable(SqlTestFactory factory);
  SqlParser createParser(SqlTestFactory factory, String sql);
  SqlValidator getValidator(SqlTestFactory factory);
  SqlAdvisor createAdvisor(SqlValidatorWithHints validator);
  Object get(String name);
}

// End SqlTestFactory.java


text:
<h0>Using the REST API</h0>

# API endpoints

To use the GoCardless API to query data, you will need to send a request to the correct endpoint. Request endpoints should depend on whether you wish to query the live or sandbox environment:

* __Sandbox__: `https://sandbox.gocardless.com`
* __Live__: `https://gocardless.com`

To see all the available GoCardless endpoints, please see the [resources section](#bill).

_Please note:_ the GoCardless API does not allow you to set up a GoCardless payment, instead you will need to send your customers a [link to a GoCardless payment page](#generating-payment-links).


text:
require('./setup');

var utils = require('./../lib/utils'),
    expect = require('chai').expect;

describe('getDateDisplayString', function(){

  it('basic', function(){
    expect(utils.getDateDisplayString('1931-02-01')).to.equal('February 1, 1931');
    expect(utils.getDateDisplayString('1918-01-01')).to.equal('January 1, 1918');
  });

});


text:
{% extends "base.html" %}
{% load humanize %}

{% block title %}page not found{% endblock %}

{% block content %}

Supervsiord not configured

Sorry, Supervisord is not configured, or is not in a running state to report the details.

{% endblock %}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('game', '0007_auto_20161026_0608'),
    ]

    operations = [
        migrations.AddField(
            model_name='cheatcode',
            name='menu_text',
            field=models.CharField(default=' ', max_length=32),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='cheatcode',
            name='trigger_code',
            field=models.CharField(default=' ', max_length=128),
            preserve_default=False,
        ),
    ]