text:
package create

import (
	"testing"

	rbac "k8s.io/api/rbac/v1"
	"k8s.io/apimachinery/pkg/api/equality"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/client-go/rest/fake"
	cmdtesting "k8s.io/kubectl/pkg/cmd/testing"
	"k8s.io/kubectl/pkg/scheme"
)

func TestCreateClusterRole(t *testing.T) {
	clusterRoleName := "my-cluster-role"

	tf := cmdtesting.NewTestFactory().WithNamespace("test")
	defer tf.Cleanup()

	tf.Client = &fake.RESTClient{}
	tf.ClientConfigVal = cmdtesting.DefaultClientConfig()

	tests := map[string]struct {
		verbs               string
		resources           string
		nonResourceURL      string
		resourceNames       string
		aggregationRule     string
		expectedClusterRole *rbac.ClusterRole
	}{
		"test-duplicate-resources": {
			verbs:     "get,watch,list",
			resources: "pods,pods",
			expectedClusterRole: &rbac.ClusterRole{
				TypeMeta: metav1.TypeMeta{APIVersion: "rbac.authorization.k8s.io/v1", Kind: "ClusterRole"},
				ObjectMeta: metav1.ObjectMeta{
					Name: clusterRoleName,
				},
				Rules: []rbac.PolicyRule{
					{
						Verbs:         []string{"get", "watch", "list"},
						Resources:     []string{"pods"},
						APIGroups:     []string{""},
						ResourceNames: []string{},
					},
				},
			},
		},
		"test-valid-case-with-multiple-apigroups": {
			verbs:     "get,watch,list",
			resources: "pods,deployments.extensions",
			expectedClusterRole: &rbac.ClusterRole{
				TypeMeta: metav1.TypeMeta{APIVersion: "rbac.authorization.k8s.io/v1", Kind: "ClusterRole"},
				ObjectMeta: metav1.ObjectMeta{
					Name: clusterRoleName,
				},
				Rules: []rbac.PolicyRule{
					{
						Verbs:         []string{"get", "watch", "list"},
						Resources:     []string{"pods"},
						APIGroups:     []string{""},
						ResourceNames: []string{},
					},
					{
						Verbs:         []string{"get", "watch", "list"},
						Resources:     []string{"deployments"},
						APIGroups:     []string{"extensions"},
						ResourceNames: []string{},
					},
				},
			},
		},
		"test-non-resource-url": {
			verbs:          "get",
			nonResourceURL: "/logs/,/healthz",
			expectedClusterRole: &rbac.ClusterRole{
				TypeMeta: metav1.TypeMeta{APIVersion: "rbac.authorization.k8s.io/v1", Kind: "ClusterRole"},
				ObjectMeta: metav1.ObjectMeta{
					Name: clusterRoleName,
				},
				Rules: []rbac.PolicyRule{
					{
						Verbs:           []string{"get"},
						NonResourceURLs: []string{"/logs/", "/healthz"},
					},
				},
			},
		},
		"test-resource-and-non-resource-url": {
			verbs:          "get",
			nonResourceURL: "/logs/,/healthz",
			resources:      "pods",
			expectedClusterRole: &rbac.ClusterRole{
				TypeMeta: metav1.TypeMeta{APIVersion: "rbac.authorization.k8s.io/v1", Kind: "ClusterRole"},
				ObjectMeta: metav1.ObjectMeta{
					Name: clusterRoleName,
				},
				Rules: []rbac.PolicyRule{
					{
						Verbs:         []string{"get"},
						Resources:     []string{"pods"},
						APIGroups:     []string{""},
						ResourceNames: []string{},
					},
					{
						Verbs:           []string{"get"},
						NonResourceURLs: []string{"/logs/", "/healthz"},
					},
				},
			},
		},
		"test-aggregation-rules": {
			aggregationRule: "foo1=foo2,foo3=foo4",
			expectedClusterRole: &rbac.ClusterRole{
				TypeMeta: metav1.TypeMeta{APIVersion: "rbac.authorization.k8s.io/v1", Kind: "ClusterRole"},
				ObjectMeta: metav1.ObjectMeta{
					Name: clusterRoleName,
				},
				AggregationRule: &rbac.AggregationRule{
					ClusterRoleSelectors: []metav1.LabelSelector{
						{
							MatchLabels: map[string]string{
								"foo1": "foo2",
								"foo3": "foo4",
							},
						},
					},
				},
			},
		},
	}

	for name, test := range tests {
		ioStreams, _, buf, _ := genericclioptions.NewTestIOStreams()
		cmd := NewCmdCreateClusterRole(tf, ioStreams)
		cmd.Flags().Set("dry-run", "client")
		cmd.Flags().Set("output", "yaml")
		cmd.Flags().Set("verb", test.verbs)
		cmd.Flags().Set("resource", test.resources)
		cmd.Flags().Set("non-resource-url", test.nonResourceURL)
		cmd.Flags().Set("aggregation-rule", test.aggregationRule)
		if test.resourceNames != "" {
			cmd.Flags().Set("resource-name", test.resourceNames)
		}
		cmd.Run(cmd, []string{clusterRoleName})
		actual := &rbac.ClusterRole{}
		if err := runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), buf.Bytes(), actual); err != nil {
			t.Log(string(buf.Bytes()))
			t.Fatal(err)
		}
		if !equality.Semantic.DeepEqual(test.expectedClusterRole, actual) {
			t.Errorf("%s:\nexpected:\n%#v\nsaw:\n%#v", name, test.expectedClusterRole, actual)
		}
	}
}

func TestClusterRoleValidate(t *testing.T) {
	tf := cmdtesting.NewTestFactory().WithNamespace("test")
	defer tf.Cleanup()

	tests := map[string]struct {
		clusterRoleOptions *CreateClusterRoleOptions
		expectErr          bool
	}{
		"test-missing-name": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{},
			},
			expectErr: true,
		},
		"test-missing-verb": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name: "my-clusterrole",
				},
			},
			expectErr: true,
		},
		"test-missing-resource": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get"},
				},
			},
			expectErr: true,
		},
		"test-missing-resource-existing-apigroup": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get"},
					Resources: []ResourceOptions{
						{
							Group: "extensions",
						},
					},
				},
			},
			expectErr: true,
		},
		"test-missing-resource-existing-subresource": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get"},
					Resources: []ResourceOptions{
						{
							SubResource: "scale",
						},
					},
				},
			},
			expectErr: true,
		},
		"test-invalid-verb": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"invalid-verb"},
					Resources: []ResourceOptions{
						{
							Resource: "pods",
						},
					},
				},
			},
			expectErr: false,
		},
		"test-nonresource-verb": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"post"},
					Resources: []ResourceOptions{
						{
							Resource: "pods",
						},
					},
				},
			},
			expectErr: false,
		},
		"test-special-verb": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"use"},
					Resources: []ResourceOptions{
						{
							Resource: "pods",
						},
					},
				},
			},
			expectErr: true,
		},
		"test-mix-verbs": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"impersonate", "use"},
					Resources: []ResourceOptions{
						{
							Resource:    "userextras",
							SubResource: "scopes",
						},
					},
				},
			},
			expectErr: true,
		},
		"test-special-verb-with-wrong-apigroup": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"impersonate"},
					Resources: []ResourceOptions{
						{
							Resource:    "userextras",
							SubResource: "scopes",
							Group:       "extensions",
						},
					},
				},
			},
			expectErr: true,
		},
		"test-invalid-resource": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get"},
					Resources: []ResourceOptions{
						{
							Resource: "invalid-resource",
						},
					},
				},
			},
			expectErr: true,
		},
		"test-resource-name-with-multiple-resources": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get"},
					Resources: []ResourceOptions{
						{
							Resource: "pods",
						},
						{
							Resource: "deployments",
							Group:    "extensions",
						},
					},
				},
			},
			expectErr: false,
		},
		"test-valid-case": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "role-binder",
					Verbs: []string{"get", "list", "bind"},
					Resources: []ResourceOptions{
						{
							Resource: "roles",
							Group:    "rbac.authorization.k8s.io",
						},
					},
				},
			},
			expectErr: false,
		},
		"test-valid-case-with-subresource": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get", "list"},
					Resources: []ResourceOptions{
						{
							Resource:    "replicasets",
							SubResource: "scale",
						},
					},
				},
			},
			expectErr: false,
		},
		"test-valid-case-with-additional-resource": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"impersonate"},
					Resources: []ResourceOptions{
						{
							Resource:    "userextras",
							SubResource: "scopes",
							Group:       "authentication.k8s.io",
						},
					},
				},
			},
			expectErr: false,
		},
		"test-invalid-empty-non-resource-url": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"create"},
				},
				NonResourceURLs: []string{""},
			},
			expectErr: true,
		},
		"test-invalid-non-resource-url": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"create"},
				},
				NonResourceURLs: []string{"logs"},
			},
			expectErr: true,
		},
		"test-invalid-non-resource-url-with-*": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"create"},
				},
				NonResourceURLs: []string{"/logs/*/"},
			},
			expectErr: true,
		},
		"test-invalid-non-resource-url-with-multiple-*": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"create"},
				},
				NonResourceURLs: []string{"/logs*/*"},
			},
			expectErr: true,
		},
		"test-invalid-verb-for-non-resource-url": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"create"},
				},
				NonResourceURLs: []string{"/logs/"},
			},
			expectErr: true,
		},
		"test-resource-and-non-resource-url-specified-together": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get"},
					Resources: []ResourceOptions{
						{
							Resource:    "replicasets",
							SubResource: "scale",
						},
					},
				},
				NonResourceURLs: []string{"/logs/", "/logs/*"},
			},
			expectErr: false,
		},
		"test-aggregation-rule-with-verb": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name:  "my-clusterrole",
					Verbs: []string{"get"},
				},
				AggregationRule: map[string]string{"foo-key": "foo-vlue"},
			},
			expectErr: true,
		},
		"test-aggregation-rule-with-resource": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name: "my-clusterrole",
					Resources: []ResourceOptions{
						{
							Resource:    "replicasets",
							SubResource: "scale",
						},
					},
				},
				AggregationRule: map[string]string{"foo-key": "foo-vlue"},
			},
			expectErr: true,
		},
		"test-aggregation-rule-with-no-resource-url": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name: "my-clusterrole",
				},
				NonResourceURLs: []string{"/logs/"},
				AggregationRule: map[string]string{"foo-key": "foo-vlue"},
			},
			expectErr: true,
		},
		"test-aggregation-rule": {
			clusterRoleOptions: &CreateClusterRoleOptions{
				CreateRoleOptions: &CreateRoleOptions{
					Name: "my-clusterrole",
				},
				AggregationRule: map[string]string{"foo-key": "foo-vlue"},
			},
			expectErr: false,
		},
	}

	for name, test := range tests {
		t.Run(name, func(t *testing.T) {
			test.clusterRoleOptions.IOStreams = genericclioptions.NewTestIOStreamsDiscard()
			var err error
			test.clusterRoleOptions.Mapper, err = tf.ToRESTMapper()
			if err != nil {
				t.Fatal(err)
			}
			err = test.clusterRoleOptions.Validate()
			if test.expectErr && err == nil {
				t.Errorf("%s: expect error happens, but validate passes.", name)
			}
			if !test.expectErr && err != nil {
				t.Errorf("%s: unexpected error: %v", name, err)
			}
		})
	}
}


text:
Tracker Hacker
==============

Extension that enhances the Pivotal Tracker experience.

## Features

* Instant filtering of cards when typing in search box
 * Can also filter by owner if you type: mywork:name\_or\_abbreviation

redpajama_set_name: RedPajamaGithub


text:
azure mobile table create ogfiostestapp iosAdmin
azure mobile table create ogfiostestapp iosApplication
azure mobile table create ogfiostestapp iosAuthenticated
azure mobile table create ogfiostestapp iosTodoItem
azure mobile table create ogfiostestapp iosMovies
azure mobile table create ogfiostestapp iosPushTest

azure mobile table update -p insert=admin,read=admin,update=admin,delete=admin ogfiostestapp iosAdmin
azure mobile table update -p insert=application,read=application,update=application,delete=application ogfiostestapp iosApplication
azure mobile table update -p insert=user,read=user,update=user,delete=user ogfiostestapp iosAuthenticated

azure mobile script upload ogfiostestapp table/iosMovies.insert -f iosMovies.insert.js
azure mobile script upload ogfiostestapp table/iosTodoItem.insert -f iosTodoItem.insert.js
azure mobile script upload ogfiostestapp table/iosPushTest.insert -f iosPushTest.insert.js


text:
package org.apache.hadoop.yarn.server.sharedcachemanager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException;
import org.apache.hadoop.yarn.exceptions.YarnException;

/**
 * An implementation of AppChecker that queries the resource manager remotely to
 * determine whether the app is running.
 */
@Private
@Unstable
public class RemoteAppChecker extends AppChecker {

  private static final EnumSet<YarnApplicationState> ACTIVE_STATES = EnumSet
      .of(YarnApplicationState.NEW, YarnApplicationState.ACCEPTED,
          YarnApplicationState.NEW_SAVING, YarnApplicationState.SUBMITTED,
          YarnApplicationState.RUNNING);

  private final YarnClient client;

  public RemoteAppChecker() {
    this(YarnClient.createYarnClient());
  }

  RemoteAppChecker(YarnClient client) {
    super("RemoteAppChecker");
    this.client = client;
  }

  @Override
  protected void serviceInit(Configuration conf) throws Exception {
    addService(client);
    super.serviceInit(conf);
  }

  @Override
  @Private
  public boolean isApplicationActive(ApplicationId id) throws YarnException {
    ApplicationReport report = null;
    try {
      report = client.getApplicationReport(id);
    } catch (ApplicationNotFoundException e) {
      // the app does not exist
      return false;
    } catch (IOException e) {
      throw new YarnException(e);
    }

    if (report == null) {
      // the app does not exist
      return false;
    }

    return ACTIVE_STATES.contains(report.getYarnApplicationState());
  }

  @Override
  @Private
  public Collection<ApplicationId> getActiveApplications() throws YarnException {
    try {
      List<ApplicationId> activeApps = new ArrayList<ApplicationId>();
      List<ApplicationReport> apps = client.getApplications(ACTIVE_STATES);
      for (ApplicationReport app: apps) {
        activeApps.add(app.getApplicationId());
      }
      return activeApps;
    } catch (IOException e) {
      throw new YarnException(e);
    }
  }
}


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

{% block content %}

All Parler elements

    {% for document in object_list %}

            {{ document.title }}

          {{ document.text }}

    {% endfor %}

{% endblock %}


text:
package org.fcrepo.http.api;

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Strings.nullToEmpty;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
import static javax.ws.rs.core.HttpHeaders.LINK;
import static javax.ws.rs.core.HttpHeaders.LOCATION;
import static javax.ws.rs.core.MediaType.WILDCARD;
import static javax.ws.rs.core.Response.noContent;
import static javax.ws.rs.core.Response.notAcceptable;
import static javax.ws.rs.core.Response.ok;
import static javax.ws.rs.core.Response.status;
import static javax.ws.rs.core.Response.temporaryRedirect;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.CONFLICT;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.FOUND;
import static javax.ws.rs.core.Response.Status.METHOD_NOT_ALLOWED;
import static javax.ws.rs.core.Response.Status.UNSUPPORTED_MEDIA_TYPE;
import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.jena.atlas.web.ContentType.create;
import static org.apache.jena.rdf.model.ResourceFactory.createResource;
import static org.apache.jena.riot.WebContent.contentTypeSPARQLUpdate;
import static org.apache.jena.riot.WebContent.ctSPARQLUpdate;
import static org.apache.jena.riot.WebContent.ctTextCSV;
import static org.apache.jena.riot.WebContent.ctTextPlain;
import static org.apache.jena.riot.WebContent.matchContentType;
import static org.fcrepo.http.commons.domain.RDFMediaType.JSON_LD;
import static org.fcrepo.http.commons.domain.RDFMediaType.N3_ALT2_WITH_CHARSET;
import static org.fcrepo.http.commons.domain.RDFMediaType.N3_WITH_CHARSET;
import static org.fcrepo.http.commons.domain.RDFMediaType.NTRIPLES;
import static org.fcrepo.http.commons.domain.RDFMediaType.RDF_XML;
import static org.fcrepo.http.commons.domain.RDFMediaType.TEXT_HTML_WITH_CHARSET;
import static org.fcrepo.http.commons.domain.RDFMediaType.TEXT_PLAIN_WITH_CHARSET;
import static org.fcrepo.http.commons.domain.RDFMediaType.TURTLE_WITH_CHARSET;
import static org.fcrepo.http.commons.domain.RDFMediaType.TURTLE_X;
import static org.fcrepo.kernel.api.FedoraTypes.FEDORA_PAIRTREE;
import static org.fcrepo.kernel.api.RdfLexicon.BASIC_CONTAINER;
import static org.fcrepo.kernel.api.RdfLexicon.DIRECT_CONTAINER;
import static org.fcrepo.kernel.api.RdfLexicon.INDIRECT_CONTAINER;
import static org.fcrepo.kernel.api.RdfLexicon.INTERACTION_MODELS;
import static org.fcrepo.kernel.api.RdfLexicon.NON_RDF_SOURCE;
import static org.fcrepo.kernel.api.RdfLexicon.VERSIONED_RESOURCE;
import static org.fcrepo.kernel.api.FedoraExternalContent.COPY;
import static org.fcrepo.kernel.api.services.VersionService.MEMENTO_RFC_1123_FORMATTER;
import static org.slf4j.LoggerFactory.getLogger;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotSupportedException;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Link;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilderException;
import javax.ws.rs.core.Variant.VariantListBuilder;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.jena.atlas.web.ContentType;
import org.apache.jena.rdf.model.Resource;
import org.fcrepo.http.api.PathLockManager.AcquiredLock;
import org.fcrepo.http.commons.domain.PATCH;
import org.fcrepo.kernel.api.FedoraTypes;
import org.fcrepo.kernel.api.RdfStream;
import org.fcrepo.kernel.api.exception.AccessDeniedException;
import org.fcrepo.kernel.api.exception.CannotCreateResourceException;
import org.fcrepo.kernel.api.exception.InsufficientStorageException;
import org.fcrepo.kernel.api.exception.InteractionModelViolationException;
import org.fcrepo.kernel.api.exception.InvalidChecksumException;
import org.fcrepo.kernel.api.exception.InvalidMementoPathException;
import org.fcrepo.kernel.api.exception.MalformedRdfException;
import org.fcrepo.kernel.api.exception.MementoDatetimeFormatException;
import org.fcrepo.kernel.api.exception.PathNotFoundRuntimeException;
import org.fcrepo.kernel.api.exception.RepositoryRuntimeException;
import org.fcrepo.kernel.api.exception.RequestWithAclLinkHeaderException;
import org.fcrepo.kernel.api.exception.UnsupportedAccessTypeException;
import org.fcrepo.kernel.api.exception.UnsupportedAlgorithmException;
import org.fcrepo.kernel.api.models.Container;
import org.fcrepo.kernel.api.models.FedoraBinary;
import org.fcrepo.kernel.api.models.FedoraResource;
import org.fcrepo.kernel.api.rdf.DefaultRdfStream;
import org.fcrepo.kernel.api.utils.ContentDigest;
import org.glassfish.jersey.media.multipart.ContentDisposition;
import org.slf4j.Logger;
import org.springframework.context.annotation.Scope;

/**
 * @author cabeer
 * @author ajs6f
 * @since 9/25/14
 */

@Scope("request")
@Path("/{path: .*}")
public class FedoraLdp extends ContentExposingResource {

    private static final Logger LOGGER = getLogger(FedoraLdp.class);

    static final String WANT_DIGEST = "Want-Digest";

    static final String DIGEST = "Digest";

    @PathParam("path") protected String externalPath;

    @Inject private FedoraHttpConfiguration httpConfiguration;

    /**
     * Default JAX-RS entry point
     */
    public FedoraLdp() {
        super();
    }

    /**
     * Create a new FedoraNodes instance for a given path
     * @param externalPath the external path
     */
    @VisibleForTesting
    public FedoraLdp(final String externalPath) {
        this.externalPath = externalPath;
    }

    /**
     * Retrieve the node headers
     *
     * @return response
     * @throws UnsupportedAlgorithmException if unsupported digest algorithm occurred
     * @throws UnsupportedAccessTypeException if unsupported access-type occurred
     */
    @HEAD
    @Produces({ TURTLE_WITH_CHARSET + ";qs=1.0", JSON_LD + ";qs=0.8",
        N3_WITH_CHARSET, N3_ALT2_WITH_CHARSET, RDF_XML, NTRIPLES, TEXT_PLAIN_WITH_CHARSET,
        TURTLE_X, TEXT_HTML_WITH_CHARSET })
    public Response head() throws UnsupportedAlgorithmException, UnsupportedAccessTypeException {
        LOGGER.info("HEAD for: {}", externalPath);

        checkMementoPath();

        final String datetimeHeader = headers.getHeaderString(ACCEPT_DATETIME);
        if (!isBlank(datetimeHeader) && resource().isVersioned()) {
            return getMemento(datetimeHeader, resource());
        }

        checkCacheControlHeaders(request, servletResponse, resource(), session);

        addResourceHttpHeaders(resource());

        Response.ResponseBuilder builder = ok();

        if (resource() instanceof FedoraBinary) {
            final FedoraBinary binary = (FedoraBinary) resource();
            final MediaType mediaType = getBinaryResourceMediaType(binary);

            if (binary.isRedirect()) {
                    builder = temporaryRedirect(binary.getRedirectURI());
            }

            // we set the content-type explicitly to avoid content-negotiation from getting in the way
            builder.type(mediaType.toString());

            // Respect the Want-Digest header with fixity check
            final String wantDigest = headers.getHeaderString(WANT_DIGEST);
            if (!isNullOrEmpty(wantDigest)) {
                builder.header(DIGEST, handleWantDigestHeader(binary, wantDigest));
            }
        } else {
            final String accept = headers.getHeaderString(HttpHeaders.ACCEPT);
            if (accept == null || "*/*".equals(accept)) {
                builder.type(TURTLE_WITH_CHARSET);
            }
            setVaryAndPreferenceAppliedHeaders(servletResponse, prefer, resource());
        }

        return builder.build();
    }

    /**
     * Outputs information about the supported HTTP methods, etc.
     * @return the outputs information about the supported HTTP methods, etc.
     */
    @OPTIONS
    public Response options() {
        LOGGER.info("OPTIONS for '{}'", externalPath);

        checkMementoPath();

        addLinkAndOptionsHttpHeaders(resource());
        return ok().build();
    }

    /**
     * Retrieve the node profile
     *
     * @param rangeValue the range value
     * @return a binary or the triples for the specified node
     * @throws IOException if IO exception occurred
     * @throws UnsupportedAlgorithmException if unsupported digest algorithm occurred
     * @throws UnsupportedAccessTypeException if unsupported access-type occurred
     */
    @GET
    @Produces({TURTLE_WITH_CHARSET + ";qs=1.0", JSON_LD + ";qs=0.8",
            N3_WITH_CHARSET, N3_ALT2_WITH_CHARSET, RDF_XML, NTRIPLES, TEXT_PLAIN_WITH_CHARSET,
            TURTLE_X, TEXT_HTML_WITH_CHARSET})
    public Response getResource(@HeaderParam("Range") final String rangeValue)
            throws IOException, UnsupportedAlgorithmException, UnsupportedAccessTypeException {

        checkMementoPath();

        final String datetimeHeader = headers.getHeaderString(ACCEPT_DATETIME);
        if (!isBlank(datetimeHeader) && resource().isVersioned()) {
            return getMemento(datetimeHeader, resource());
        }

        checkCacheControlHeaders(request, servletResponse, resource(), session);

        LOGGER.info("GET resource '{}'", externalPath);
        final AcquiredLock readLock = lockManager.lockForRead(resource().getPath());
        try (final RdfStream rdfStream = new DefaultRdfStream(asNode(resource()))) {

            // If requesting a binary, check the mime-type if "Accept:" header is present.
            // (This needs to be done before setting up response headers, as getContent
            // returns a response - so changing headers after that won't work so nicely.)
            final ImmutableList<MediaType> acceptableMediaTypes = ImmutableList.copyOf(headers
                    .getAcceptableMediaTypes());

            if (resource() instanceof FedoraBinary && acceptableMediaTypes.size() > 0) {

                final MediaType mediaType = getBinaryResourceMediaType(resource());

                // Respect the Want-Digest header for fixity check
                final String wantDigest = headers.getHeaderString(WANT_DIGEST);
                if (!isNullOrEmpty(wantDigest)) {
                    servletResponse.addHeader(DIGEST, handleWantDigestHeader((FedoraBinary)resource(), wantDigest));
                }

                if (!acceptableMediaTypes.stream().anyMatch(t -> t.isCompatible(mediaType))) {
                    return notAcceptable(VariantListBuilder.newInstance().mediaTypes(mediaType).build()).build();
                }
            }

            addResourceHttpHeaders(resource());

            if (resource() instanceof FedoraBinary && ((FedoraBinary)resource()).isRedirect()) {
                return temporaryRedirect(((FedoraBinary) resource()).getRedirectURI()).build();
            } else {
                return getContent(rangeValue, getChildrenLimit(), rdfStream, resource());
            }
        } finally {
            readLock.release();
        }
    }

    /**
     * Return the location of a requested Memento.
     *
     * @param datetimeHeader The RFC datetime for the Memento.
     * @param resource The fedora resource
     * @return A 302 Found response or 406 if no mementos.
     */
    private Response getMemento(final String datetimeHeader, final FedoraResource resource) {
        try {
            final Instant mementoDatetime = Instant.from(MEMENTO_RFC_1123_FORMATTER.parse(datetimeHeader));
            final FedoraResource memento = resource.findMementoByDatetime(mementoDatetime);
            final Response builder;
            if (memento != null) {
                builder =
                    status(FOUND).header(LOCATION, translator().reverse().convert(memento).toString()).build();
            } else {
                builder = status(NOT_ACCEPTABLE).build();
            }
            addResourceHttpHeaders(resource);
            setVaryAndPreferenceAppliedHeaders(servletResponse, prefer, resource);
            return builder;
        } catch (final DateTimeParseException e) {
            throw new MementoDatetimeFormatException("Invalid Accept-Datetime value: " + e.getMessage()
                + ". Please use RFC-1123 date-time format, such as 'Tue, 3 Jun 2008 11:05:30 GMT'", e);
        }
    }

    /**
     * Deletes an object.
     *
     * @return response
     */
    @DELETE
    public Response deleteObject() {
        hasRestrictedPath(externalPath);
        if (resource() instanceof Container) {
            final String depth = headers.getHeaderString("Depth");
            LOGGER.debug("Depth header value is: {}", depth);
            if (depth != null && !depth.equalsIgnoreCase("infinity")) {
                throw new ClientErrorException("Depth header, if present, must be set to 'infinity' for containers",
                        SC_BAD_REQUEST);
            }
        }

        evaluateRequestPreconditions(request, servletResponse, resource(), session);

        LOGGER.info("Delete resource '{}'", externalPath);

        final AcquiredLock lock = lockManager.lockForDelete(resource().getPath());

        try {
            resource().delete();
            session.commit();
            return noContent().build();
        } finally {
            lock.release();
        }
    }

    /**
     * Create a resource at a specified path, or replace triples with provided RDF.
     *
     * @param requestContentType the request content type
     * @param requestBodyStream the request body stream
     * @param contentDisposition the content disposition value
     * @param ifMatch the if-match value
     * @param rawLinks the raw link values
     * @param digest the digest header
     * @return 204
     * @throws InvalidChecksumException if invalid checksum exception occurred
     * @throws MalformedRdfException if malformed rdf exception occurred
     * @throws UnsupportedAlgorithmException if an unsupported algorithm exception occurs
     * @throws UnsupportedAccessTypeException if the access type of the resource is not supported
     */
    @PUT
    @Consumes
    public Response createOrReplaceObjectRdf(
            @HeaderParam(CONTENT_TYPE) final MediaType requestContentType,
            final InputStream requestBodyStream,
            @HeaderParam(CONTENT_DISPOSITION) final ContentDisposition contentDisposition,
            @HeaderParam("If-Match") final String ifMatch,
            @HeaderParam(LINK) final List<String> rawLinks,
            @HeaderParam("Digest") final String digest)
            throws InvalidChecksumException, MalformedRdfException, UnsupportedAlgorithmException,
            UnsupportedAccessTypeException {

        hasRestrictedPath(externalPath);

        final List<String> links = unpackLinks(rawLinks);

        if (externalPath.contains("/" + FedoraTypes.FCR_VERSIONS)) {
            handleRequestDisallowedOnMemento();

            return status(METHOD_NOT_ALLOWED).build();
        }

        final String interactionModel = checkInteractionModel(links);

        checkAclLinkHeader(links);

        final FedoraResource resource;

        final String path = toPath(translator(), externalPath);

        final AcquiredLock lock = lockManager.lockForWrite(path, session.getFedoraSession(), nodeService);

        try {

            final Collection<String> checksums = parseDigestHeader(digest);
            final ExternalContentHandler extContent = extContentHandlerFactory.createFromLinks(links);

            final MediaType contentType =  getSimpleContentType(
                    extContent != null ? extContent.getContentType() : requestContentType);

            if (nodeService.exists(session.getFedoraSession(), path)) {
                resource = resource();

                final String resInteractionModel = getInteractionModel(resource);
                if (StringUtils.isNoneBlank(interactionModel) && StringUtils.isNoneBlank(resInteractionModel)
                        && !resInteractionModel.equals(interactionModel)) {
                    throw new InteractionModelViolationException("Changing the interaction model " + resInteractionModel
                                + " to " + interactionModel + " is not allowed!");
                }

            } else {

                checkExistingAncestor(path);

                final MediaType effectiveContentType
                        = requestBodyStream == null || requestContentType == null ? null : contentType;
                resource = createFedoraResource(path, interactionModel, effectiveContentType,
                        !(requestBodyStream == null || requestContentType == null), extContent != null ? true : false);
            }

            if (httpConfiguration.putRequiresIfMatch() && StringUtils.isBlank(ifMatch) && !resource.isNew()) {
                throw new ClientErrorException("An If-Match header is required", 428);
            }

            evaluateRequestPreconditions(request, servletResponse, resource, session);
            final boolean created = resource.isNew();

            try (final RdfStream resourceTriples =
                    created ? new DefaultRdfStream(asNode(resource())) : getResourceTriples(resource())) {
                if (resource instanceof FedoraBinary) {
                    InputStream stream = requestBodyStream;
                    MediaType type = requestContentType;
                    // override a few things, if it's external content
                    if (extContent != null) {
                        if (extContent.isCopy()) {
                            LOGGER.debug("External content COPY '{}', '{}'", externalPath, extContent.getURL());
                            stream = extContent.fetchExternalContent();
                        }

                        type = contentType;  // if external, then this already holds the correct value
                    }
                    final String handling = extContent != null ? extContent.getHandling() : null;
                    replaceResourceBinaryWithStream((FedoraBinary) resource,
                            stream, contentDisposition, type, checksums,
                            (handling != null && !handling.equals(COPY)) ? handling : null,
                            (extContent != null && !handling.equals(COPY)) ? extContent.getURL() : null);

                } else if (isRdfContentType(contentType.toString())) {
                    replaceResourceWithStream(resource, requestBodyStream, contentType, resourceTriples);
                } else if (!created) {
                    boolean emptyRequest = true;
                    try {
                        emptyRequest = requestBodyStream.read() == -1;
                    } catch (final IOException ex) {
                        LOGGER.debug("Error checking for request body content", ex);
                    }

                    if (requestContentType == null && emptyRequest) {
                        throw new ClientErrorException("Resource Already Exists", CONFLICT);
                    }
                    throw new NotSupportedException("Invalid Content Type " + requestContentType);
                }
            } catch (final Exception e) {
                checkForInsufficientStorageException(e, e);
            }

            if (hasVersionedResourceLink(links)) {
                resource.enableVersioning();
            }

            ensureInteractionType(resource, interactionModel,
                    (requestBodyStream == null || requestContentType == null));

            session.commit();
            return createUpdateResponse(resource, created);

        } finally {
            lock.release();
        }
    }

    /**
     * Make sure the resource has the specified interaction model
     */
    private static void ensureInteractionType(final FedoraResource resource, final String interactionModel,
            final boolean defaultContent) {
        if (interactionModel != null) {
            if (!interactionModel.equals("ldp:NonRDFSource") && !resource.hasType(interactionModel)) {
                resource.addType(interactionModel);
            }
        } else if (defaultContent) {
            resource.addType("ldp:BasicContainer");
        }
    }

    /**
     * Update an object using SPARQL-UPDATE
     *
     * @param requestBodyStream the request body stream
     * @return 201
     * @throws IOException if IO exception occurred
     */
    @PATCH
    @Consumes({contentTypeSPARQLUpdate})
    public Response updateSparql(final InputStream requestBodyStream)
            throws IOException {
        hasRestrictedPath(externalPath);

        if (externalPath.contains("/" + FedoraTypes.FCR_VERSIONS)) {
            handleRequestDisallowedOnMemento();

            return status(METHOD_NOT_ALLOWED).build();
        }

        if (null == requestBodyStream) {
            throw new BadRequestException("SPARQL-UPDATE requests must have content!");
        }

        if (resource() instanceof FedoraBinary) {
            throw new BadRequestException(resource().getPath() + " is not a valid object to receive a PATCH");
        }

        final AcquiredLock lock = lockManager.lockForWrite(resource().getPath(), session.getFedoraSession(),
                nodeService);

        try {
            final String requestBody = IOUtils.toString(requestBodyStream, UTF_8);
            if (isBlank(requestBody)) {
                throw new BadRequestException("SPARQL-UPDATE requests must have content!");
            }

            evaluateRequestPreconditions(request, servletResponse, resource(), session);

            try (final RdfStream resourceTriples =
                    resource().isNew() ? new DefaultRdfStream(asNode(resource())) : getResourceTriples(resource())) {
                LOGGER.info("PATCH for '{}'", externalPath);
                patchResourcewithSparql(resource(), requestBody, resourceTriples);
            }
            session.commit();

            addCacheControlHeaders(servletResponse, resource(), session);

            return noContent().build();
        } catch (final IllegalArgumentException iae) {
            throw new BadRequestException(iae.getMessage());
        } catch (final AccessDeniedException e) {
            throw e;
        } catch ( final RuntimeException ex ) {
            final Throwable cause = ex.getCause();
            if (cause instanceof PathNotFoundRuntimeException) {
                // the sparql update referred to a repository resource that doesn't exist
                throw new BadRequestException(cause.getMessage());
            }
            throw ex;
        } finally {
            lock.release();
        }
    }

    /**
     * Creates a new object.
     *
     * This originally used application/octet-stream;qs=1001 as a workaround
     * for JERSEY-2636, to ensure requests without a Content-Type get routed here.
     * This qs value does not parse with newer versions of Jersey, as qs values
     * must be between 0 and 1. We use qs=1.000 to mark where this historical
     * anomaly had been.
     *
     * @param contentDisposition the content Disposition value
     * @param requestContentType the request content type
     * @param slug the slug value
     * @param requestBodyStream the request body stream
     * @param rawLinks the link values
     * @param digest the digest header
     * @return 201
     * @throws InvalidChecksumException if invalid checksum exception occurred
     * @throws IOException if IO exception occurred
     * @throws MalformedRdfException if malformed rdf exception occurred
     * @throws UnsupportedAlgorithmException if an unsupported algorithm exception occurs
     * @throws UnsupportedAccessTypeException if the access type of the resource is not supported
     */
    @POST
    @Consumes({MediaType.APPLICATION_OCTET_STREAM + ";qs=1.000", WILDCARD})
    @Produces({TURTLE_WITH_CHARSET + ";qs=1.0", JSON_LD + ";qs=0.8",
            N3_WITH_CHARSET, N3_ALT2_WITH_CHARSET, RDF_XML, NTRIPLES, TEXT_PLAIN_WITH_CHARSET,
            TURTLE_X, TEXT_HTML_WITH_CHARSET, "*/*"})
    public Response createObject(@HeaderParam(CONTENT_DISPOSITION) final ContentDisposition contentDisposition,
                                 @HeaderParam(CONTENT_TYPE) final MediaType requestContentType,
                                 @HeaderParam("Slug") final String slug,
            final InputStream requestBodyStream,
                                 @HeaderParam(LINK) final List<String> rawLinks,
                                 @HeaderParam("Digest") final String digest)
            throws InvalidChecksumException, IOException, MalformedRdfException, UnsupportedAlgorithmException,
            UnsupportedAccessTypeException {

        final List<String> links = unpackLinks(rawLinks);

        if (externalPath.contains("/" + FedoraTypes.FCR_VERSIONS)) {
            handleRequestDisallowedOnMemento();

            return status(METHOD_NOT_ALLOWED).build();
        }

        final String interactionModel = checkInteractionModel(links);

        checkAclLinkHeader(links);

        // If request is an external binary, verify link header before proceeding
        final ExternalContentHandler extContent = extContentHandlerFactory.createFromLinks(links);

        if (!(resource() instanceof Container)) {
            throw new ClientErrorException("Object cannot have child nodes", CONFLICT);
        } else if (resource().hasType(FEDORA_PAIRTREE)) {
            throw new ClientErrorException("Objects cannot be created under pairtree nodes", FORBIDDEN);
        }

        final MediaType contentType = getSimpleContentType(
                extContent != null ? extContent.getContentType() : requestContentType);

        final String contentTypeString = contentType.toString();

        final String newObjectPath = mintNewPid(slug);
        hasRestrictedPath(newObjectPath);

        final AcquiredLock lock = lockManager.lockForWrite(newObjectPath, session.getFedoraSession(), nodeService);

        try {

            final Collection<String> checksum = parseDigestHeader(digest);

            LOGGER.info("Ingest with path: {}", newObjectPath);

            final FedoraResource resource = createFedoraResource(newObjectPath, interactionModel, contentType,
                    !(requestBodyStream == null || requestContentType == null), extContent != null ? true : false);

            try (final RdfStream resourceTriples =
                     resource.isNew() ? new DefaultRdfStream(asNode(resource())) : getResourceTriples(resource())) {

                if (requestBodyStream == null && extContent == null) {
                    LOGGER.trace("No request body detected");
                } else {
                    LOGGER.trace("Received createObject with a request body and content type \"{}\"",
                            contentTypeString);

                    if ((resource instanceof Container) && isRdfContentType(contentTypeString)) {
                        replaceResourceWithStream(resource, requestBodyStream, contentType, resourceTriples);
                    } else if (resource instanceof FedoraBinary) {
                        LOGGER.trace("Created a datastream and have a binary payload.");

                        InputStream stream = requestBodyStream;
                        MediaType type = requestContentType;

                        if (extContent != null) {
                            if (extContent.isCopy()) {
                                LOGGER.debug("POST copying data {} ", externalPath);
                                stream = extContent.fetchExternalContent();
                            }

                            type = contentType; // if external, then this already holds the correct value
                        }

                        final String handling = extContent != null ? extContent.getHandling() : null;
                        replaceResourceBinaryWithStream((FedoraBinary) resource,
                                stream, contentDisposition, type, checksum,
                            handling != null && !handling.equals(COPY) ? handling : null,
                            extContent != null ? extContent.getURL() : null);

                    } else if (contentTypeString.equals(contentTypeSPARQLUpdate)) {
                        LOGGER.trace("Found SPARQL-Update content, applying..");
                        patchResourcewithSparql(resource, IOUtils.toString(requestBodyStream, UTF_8), resourceTriples);
                    } else {
                        if (requestBodyStream.read() != -1) {
                            throw new ClientErrorException("Invalid Content Type " + contentTypeString,
                                    UNSUPPORTED_MEDIA_TYPE);
                        }
                    }
                }

                if (hasVersionedResourceLink(links)) {
                    resource.enableVersioning();
                    if (resource instanceof FedoraBinary) {
                        resource.enableVersioning();
                    }
                }

                ensureInteractionType(resource, interactionModel,
                        (requestBodyStream == null || requestContentType == null));

                session.commit();
            } catch (final Exception e) {
                checkForInsufficientStorageException(e, e);
            }

            LOGGER.debug("Finished creating resource with path: {}", newObjectPath);
            return createUpdateResponse(resource, true);
        } finally {
            lock.release();
        }
    }

    /**
     * @param rootThrowable The original throwable
     * @param throwable The throwable under direct scrutiny.
     */
    @Override
    protected void checkForInsufficientStorageException(final Throwable rootThrowable, final Throwable throwable)
            throws InvalidChecksumException {
        final String message = throwable.getMessage();
        if (throwable instanceof IOException && message != null && message.contains(
                INSUFFICIENT_SPACE_IDENTIFYING_MESSAGE)) {
            throw new InsufficientStorageException(throwable.getMessage(), rootThrowable);
        }

        if (throwable.getCause() != null) {
            checkForInsufficientStorageException(rootThrowable, throwable.getCause());
        }

        if (rootThrowable instanceof InvalidChecksumException) {
            throw (InvalidChecksumException) rootThrowable;
        } else if (rootThrowable instanceof RuntimeException) {
            throw (RuntimeException) rootThrowable;
        } else {
            throw new RepositoryRuntimeException(rootThrowable);
        }
    }

    /**
     * Returns true if there is a link with a VERSIONED_RESOURCE type.
     * @param links a list of link header values.
     * @return True if there is a matching link header.
     */
    private boolean hasVersionedResourceLink(final List<String> links) {
        if (!CollectionUtils.isEmpty(links)) {
            try {
                for (final String link : links) {
                    final Link linq = Link.valueOf(link);
                    if ("type".equals(linq.getRel())) {
                        final Resource type = createResource(linq.getUri().toString());
                        if (type.equals(VERSIONED_RESOURCE)) {
                            return true;
                        }
                    }
                }
            } catch (final RuntimeException e) {
                if (e instanceof IllegalArgumentException | e instanceof UriBuilderException) {
                    throw new ClientErrorException("Invalid link specified: " + String.join(", ", links),
                            BAD_REQUEST);
                }
                throw e;
            }
        }

        return false;
    }

    @Override
    protected void addResourceHttpHeaders(final FedoraResource resource) {
        super.addResourceHttpHeaders(resource);

        if (session.isBatchSession()) {
            final String canonical = translator().reverse()
                    .convert(resource)
                    .toString()
                    .replaceFirst("/tx:[^/]+", "");

            servletResponse.addHeader(LINK, "<" + canonical + ">;rel=\"canonical\"");

        }
        addExternalContentHeaders(resource);
    }

    @Override
    protected String externalPath() {
        return externalPath;
    }

    private static boolean isRDF(final MediaType requestContentType) {
        if (requestContentType == null) {
            return false;
        }

        final ContentType ctRequest = create(requestContentType.toString());

        // Text files and CSV files are not considered RDF to Fedora, though CSV is a valid
        // RDF type to Jena (although deprecated).
        if (matchContentType(ctRequest, ctTextPlain) || matchContentType(ctRequest, ctTextCSV)) {
            return false;
        }

        // SPARQL updates are done on containers.
        return isRdfContentType(requestContentType.toString()) || matchContentType(ctRequest, ctSPARQLUpdate);
    }

    private void checkExistingAncestor(final String path) {
        // check the closest existing ancestor for containment violations.
        String parentPath = path.substring(0, path.lastIndexOf("/"));
        while (!(parentPath.isEmpty() || parentPath.equals("/"))) {
            if (nodeService.exists(session.getFedoraSession(), parentPath)) {
                if (!(getResourceFromPath(parentPath) instanceof Container)) {
                    throw new ClientErrorException("Unable to add child " + path.replace(parentPath, "")
                            + " to resource " + parentPath + ".", CONFLICT);
                }
                break;
            }
            parentPath = parentPath.substring(0, parentPath.lastIndexOf("/"));
        }
    }

    private FedoraResource createFedoraResource(final String path, final String interactionModel,
            final MediaType contentType, final boolean contentPresent, final boolean contentExternal) {

        final MediaType simpleContentType = contentPresent ? getSimpleContentType(contentType) : null;

        final FedoraResource result;
        if ("ldp:NonRDFSource".equals(interactionModel) || contentExternal ||
                (contentPresent && interactionModel == null && !isRDF(simpleContentType))) {
            result = binaryService.findOrCreate(session.getFedoraSession(), path);
        } else {
            result = containerService.findOrCreate(session.getFedoraSession(), path);
        }

        final String resInteractionModel = getInteractionModel(result);
        if (StringUtils.isNoneBlank(interactionModel) && StringUtils.isNoneBlank(resInteractionModel)
                && !resInteractionModel.equals(interactionModel)) {
            throw new InteractionModelViolationException("Changing the interaction model " + resInteractionModel
                        + " to " + interactionModel + " is not allowed!");
        }

        return result;
    }

    /*
     * Get the interaction model from the Fedora Resource
     * @param resource Fedora Resource
     * @return String the Interaction Model
     */
    private String getInteractionModel(final FedoraResource resource) {
        final Optional<String> result = INTERACTION_MODELS.stream().filter(x -> resource.hasType(x)).findFirst();
        return result.isPresent() ? result.get() : null;
    }

    private String mintNewPid(final String slug) {
        String pid;

        if (slug != null && !slug.isEmpty()) {
            pid = slug;
        } else if (pidMinter != null) {
            pid = pidMinter.get();
        } else {
            pid = defaultPidMinter.get();
        }
        // reverse translate the proffered or created identifier
        LOGGER.trace("Using external identifier {} to create new resource.", pid);
        LOGGER.trace("Using prefixed external identifier {} to create new resource.", uriInfo.getBaseUri() + "/"
                + pid);

        final URI newResourceUri = uriInfo.getAbsolutePathBuilder().clone().path(FedoraLdp.class)
                .resolveTemplate("path", pid, false).build();

        pid = translator().asString(createResource(newResourceUri.toString()));
        try {
            pid = URLDecoder.decode(pid, "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            // noop
        }
        // remove leading slash left over from translation
        LOGGER.trace("Using internal identifier {} to create new resource.", pid);

        if (nodeService.exists(session.getFedoraSession(), pid)) {
            LOGGER.trace("Resource with path {} already exists; minting new path instead", pid);
            return mintNewPid(null);
        }

        return pid;
    }

    private String handleWantDigestHeader(final FedoraBinary binary, final String wantDigest)
            throws UnsupportedAlgorithmException, UnsupportedAccessTypeException {
        // handle the Want-Digest header with fixity check
        final Collection<String> preferredDigests = parseWantDigestHeader(wantDigest);
        if (preferredDigests.isEmpty()) {
            throw new UnsupportedAlgorithmException(
                    "Unsupported digest algorithm provided in 'Want-Digest' header: " + wantDigest);
        }

        final Collection<URI> checksumResults = binary.checkFixity(idTranslator, preferredDigests);
        final String digestValue = checksumResults.stream().map(uri -> uri.toString().replaceFirst("urn:", "")
                .replaceFirst(":", "=").replaceFirst("sha1=", "sha=")).collect(Collectors.joining(","));
        return digestValue;
    }

    private static String checkInteractionModel(final List<String> links) {
        if (links == null) {
            return null;
        }

        try {
            for (final String link : links) {
                final Link linq = Link.valueOf(link);
                if ("type".equals(linq.getRel())) {
                    final Resource type = createResource(linq.getUri().toString());
                    if (type.equals(NON_RDF_SOURCE) || type.equals(BASIC_CONTAINER) ||
                            type.equals(DIRECT_CONTAINER) || type.equals(INDIRECT_CONTAINER)) {
                        return "ldp:" + type.getLocalName();
                    } else if (type.equals(VERSIONED_RESOURCE)) {
                        // skip if versioned resource link header
                        // NB: the versioned resource header is used for enabling
                        // versioning on a resource and is thus orthogonal to
                        // issue of interaction models. Nevertheless, it is
                        // a possible link header and, therefore, must be ignored.
                    } else {
                        LOGGER.info("Invalid interaction model: {}", type);
                        throw new CannotCreateResourceException("Invalid interaction model: " + type);
                    }
                }
            }
        } catch (final RuntimeException e) {
            if (e instanceof IllegalArgumentException | e instanceof UriBuilderException) {
                throw new ClientErrorException("Invalid link specified: " + String.join(", ", links), BAD_REQUEST);
            }
            throw e;
        }

        return null;
    }

    /**
     * Parse the RFC-3230 Digest response header value.  Look for a
     * sha1 checksum and return it as a urn, if missing or malformed
     * an empty string is returned.
     * @param digest The Digest header value
     * @return the sha1 checksum value
     * @throws UnsupportedAlgorithmException if an unsupported digest is used
     */
    protected static Collection<String> parseDigestHeader(final String digest) throws UnsupportedAlgorithmException {
        try {
            final Map<String,String> digestPairs = RFC3230_SPLITTER.split(nullToEmpty(digest));
            final boolean allSupportedAlgorithms = digestPairs.keySet().stream().allMatch(
                    ContentDigest.DIGEST_ALGORITHM::isSupportedAlgorithm);

            // If you have one or more digests that are all valid or no digests.
            if (digestPairs.isEmpty() || allSupportedAlgorithms) {
                return digestPairs.entrySet().stream()
                    .filter(entry -> ContentDigest.DIGEST_ALGORITHM.isSupportedAlgorithm(entry.getKey()))
                    .map(entry -> ContentDigest.asURI(entry.getKey(), entry.getValue()).toString())
                    .collect(Collectors.toSet());
            } else {
                throw new UnsupportedAlgorithmException(String.format("Unsupported Digest Algorithm: %1$s", digest));
            }
        } catch (final RuntimeException e) {
            if (e instanceof IllegalArgumentException) {
                throw new ClientErrorException("Invalid Digest header: " + digest + "\n", BAD_REQUEST);
            }
            throw e;
        }
    }

    /**
     * Parse the RFC-3230 Want-Digest header value.
     * @param wantDigest The Want-Digest header value with optional q value in format:
     *    'md5', 'md5, sha', 'MD5;q=0.3, sha;q=1' etc.
     * @return Digest algorithms that are supported
     */
    private static Collection<String> parseWantDigestHeader(final String wantDigest) {
        final Map<String, Double> digestPairs = new HashMap<String, Double>();
        try {
            final List<String> algs = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(wantDigest);
            // Parse the optional q value with default 1.0, and 0 ignore. Format could be: SHA-1;qvalue=0.1
            for (final String alg : algs) {
                final String[] tokens = alg.split(";", 2);
                final double qValue = tokens.length == 1 || tokens[1].indexOf("=") < 0 ?
                        1.0 : Double.parseDouble(tokens[1].split("=", 2)[1]);
                digestPairs.put(tokens[0], qValue);
            }

            return digestPairs.entrySet().stream().filter(entry -> entry.getValue() > 0)
                .filter(entry -> ContentDigest.DIGEST_ALGORITHM.isSupportedAlgorithm(entry.getKey()))
                .map(entry -> entry.getKey()).collect(Collectors.toSet());
        } catch (final NumberFormatException e) {
            throw new ClientErrorException("Invalid 'Want-Digest' header value: " + wantDigest, SC_BAD_REQUEST, e);
        } catch (final RuntimeException e) {
            if (e instanceof IllegalArgumentException) {
                throw new ClientErrorException("Invalid 'Want-Digest' header value: " + wantDigest + "\n", BAD_REQUEST);
            }
            throw e;
        }
    }

    private void checkAclLinkHeader(final List<String> links) throws RequestWithAclLinkHeaderException {
        if (links != null && links.stream().anyMatch(l -> Link.valueOf(l).getRel().equals("acl"))) {
            throw new RequestWithAclLinkHeaderException(
                    "Unable to handle request with the specified LDP-RS as the ACL.");
        }
    }

    private void handleRequestDisallowedOnMemento() {
        try {
            addLinkAndOptionsHttpHeaders(resource());
        } catch (final Exception ex) {
            // Catch the exception to ensure status 405 for any requests on memento.
            LOGGER.debug("Unable to add link and options headers for PATCH request to memento path {}: {}.",
                externalPath, ex.getMessage());
        }

        LOGGER.info("Unable to handle {} request on a path containing {}. Path was: {}", request.getMethod(),
            FedoraTypes.FCR_VERSIONS, externalPath);
    }

    /*
     * Ensure that an incoming versioning/memento path can be converted.
     */
    private void checkMementoPath() {
        if (externalPath.contains("/" + FedoraTypes.FCR_VERSIONS)) {
            final String path = toPath(translator(), externalPath);
            if (path.contains(FedoraTypes.FCR_VERSIONS)) {
                throw new InvalidMementoPathException("Invalid versioning request with path: " + path);
            }
        }
    }
}


text:
'use strict';

exports.BarChart = require('./barchart').BarChart;
exports.LineChart = require('./linechart').LineChart;
exports.PieChart = require('./piechart').PieChart;
exports.AreaChart = require('./areachart').AreaChart;
exports.Treemap = require('./treemap').Treemap;
exports.ScatterChart = require('./scatterchart').ScatterChart;
exports.CandlestickChart = require('./candlestick').CandlestickChart;


text:
package com.endusersoft.svnconverter;

import com.endusersoft.svnconverter.model.drawing.AbstractKhanObject;
import com.endusersoft.svnconverter.model.handlers.KhanPathHandler;
import com.endusersoft.svnconverter.model.parsers.SvgFileParser;
import org.apache.batik.parser.PathHandler;
import org.apache.batik.parser.PathParser;
import org.apache.batik.svggen.SVGConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Class responsible for parsing a file into a nodelist, then processing those nodes with a path parser.
 */
public class SvgConverter {
    private static final Logger LOGGER = LoggerFactory.getLogger(SvgConverter.class);

    public static void main(String[] args) {

        System.out.print("Hello, World.");
    }

    void ConsumeFile(File file)
            throws IOException, XPathExpressionException, ParserConfigurationException, SAXException {

        SVGConverterFileSource fileSource = new SvgConverter();
        StringBuilder builder = new StringBuilder();

        // this will do the actual parsing
        // this will contain the results
        List<AbstractKhanObject> khanObjects = new ArrayList<AbstractKhanObject>();
        // this performs the conversion
        PathHandler pathHandler = new KhanPathHandler(khanObjects);
        SvgFileParser svgFileParser = new SvgFileParser(parseSVGFile(file));

        /*LOGGER.debug("found {} nodes", nodeList.getLength());

        for (int i = 0; i < nodeList.getLength(); i++) {
            LOGGER.debug("\tlooking at '{}'", nodeList.item(i).getNodeName());
            switch (nodeList.item(i).getNodeName()) {
                case "path":
                    PathParser pathParser = new PathParser();

                    pathParser.setPathHandler(pathHandler);
                    pathParser.parse(nodeList.item(i)
                            .getAttributes().getNamedItem("d")
                            .getNodeValue());
                    break;
                case "line":
                    // pathParser = new lineParser();
            }*/

        SVGConverter
                XMLInputHandler inputHandler

        }

//        processResults(builder, khanObjects);
//        System.out.printf(builder.toString());

    private void processResults(StringBuilder sb, List<AbstractKhanObject> objects) {
        for (AbstractKhanObject khanObject : objects) {
            sb.append(khanObject.toString() + "\n");
        }
    }

    private NodeList  parseSVGFile(File file)
            throws XPathExpressionException, ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(file);

        String xpathExpression = "//path[@d]";

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath.compile(xpathExpression);

        return (NodeList) expression.evaluate(document, XPathConstants.NODESET);
    }

}


text:
import java.util.LinkedHashMap;
import java.util.Map;

public class MethodSymbol extends Symbol implements Scope {
	Map<String, Symbol> orderedArgs = new LinkedHashMap<String, Symbol>();
    Scope enclosingScope;

    public MethodSymbol(String name, Type retType, Scope enclosingScope) {
        super(name, retType);
        this.enclosingScope = enclosingScope;
    }

    public Symbol resolve(String name) {
		Symbol s = orderedArgs.get(name);
        if ( s!=null ) return s;
		// if not here, check any enclosing scope
		if ( getEnclosingScope() != null ) {
			return getEnclosingScope().resolve(name);
		}
		return null; // not found
	}

	public void define(Symbol sym) {
		orderedArgs.put(sym.name, sym);
		sym.scope = this; // track the scope in each symbol
	}

	public Scope getEnclosingScope() { return enclosingScope; }
	public String getScopeName() { return name; }

    public String toString() { return "method"+super.toString()+":"+orderedArgs.values(); }
}


text:
package com.cronutils.model.time;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class NearestValueTest {
    private int value;
    private int shifts;

    private NearestValue nearestValue;

    @Before
    public void setUp(){
        value = 1;
        shifts = 1;
        nearestValue = new NearestValue(value, shifts);
    }

    @Test
    public void testGetValue() throws Exception {
        assertEquals(value, nearestValue.getValue());
    }

    @Test
    public void testGetShifts() throws Exception {
        assertEquals(shifts, nearestValue.getShifts());
    }
}


text:
package org.duracloud.syncui;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class SyncUI extends AbstractHandler {

    public void handle(String target,
                       Request baseRequest,
                       HttpServletRequest request,
                       HttpServletResponse response)
        throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("
Sync
");
    }

}


text:
@extends(Config::get('syntara::views.master'))

@section('content')

 @include('syntara::layouts.dashboard.confirmation-modal',  array('title' => trans('syntara::all.confirm-delete-title'), 'content' => trans('syntara::all.confirm-delete-message'), 'type' => 'delete-group'))

                    {{ trans('syntara::groups.all') }}

                     @include('syntara::group.list-groups')

                    {{ trans('syntara::all.search') }}

                    <form id="search-form" onsubmit="return false;">

                            {{ trans('syntara::groups.id') }}
                            <input type="text" class="form-control" id="groupIdSearch" name="groupIdSearch">

                            {{ trans('syntara::groups.name') }}
                            <input type="text" class="form-control" id="groupnameSearch" name="groupnameSearch">

                        <button type="submit" class="btn btn-primary">{{ trans('syntara::all.search') }}</button>
                    </form>

@stop


text:
package io.netty.handler.codec.mqtt;

import org.apache.commons.lang3.StringUtils;

import static com.github.j1stiot.mqtt.util.UUIDs.shortUuid;

/**
 * MQTT Utils
 */
public class Mqtts {

    /**
     * Sanitize MQTT message
     *
     * @param msg MQTT message
     */
    public static void sanitize(MqttMessage msg) {
        switch (msg.fixedHeader().messageType()) {
            case CONNECT:
                if (StringUtils.isBlank(((MqttConnectMessage) msg).payload().clientId())
                        && ((MqttConnectMessage) msg).variableHeader().cleanSession())
                    ((MqttConnectMessage) msg).payload().clientId = shortUuid();
            case CONNACK:
            case PUBACK:
            case PUBREC:
            case PUBCOMP:
            case SUBACK:
            case UNSUBACK:
            case PINGREQ:
            case PINGRESP:
            case DISCONNECT:
                msg.fixedHeader().dup = false;
                msg.fixedHeader().qos = MqttQoS.AT_MOST_ONCE;
                msg.fixedHeader().retain = false;
                break;
            case PUBREL:
            case SUBSCRIBE:
            case UNSUBSCRIBE:
                msg.fixedHeader().dup = false;
                msg.fixedHeader().qos = MqttQoS.AT_LEAST_ONCE;
                msg.fixedHeader().retain = false;
                break;
            case PUBLISH:
                if (msg.fixedHeader().qos == MqttQoS.AT_MOST_ONCE)
                    ((MqttPublishVariableHeader) msg.variableHeader()).packetId = 0;
                break;
        }
    }
}


text:
<meta charset="utf-8">
<?php if (isset($info)) { ?>
<script>alert("<?php echo addslashes($info);?>")</script>
<?php } ?>
<?php if (isset($fartherurl)) { ?>
<script>window.parent.location.href="<?php echo $fartherurl;?>"</script>
<?php } elseif (isset($url)) { ?>
<script>window.location.href="<?php echo $url;?>"</script>
<?php } else { ?>
<script>history.go(-1);</script>
<?php } ?>


text:
document.onreadystatechange = function(e)
{
  if(document.readyState=="interactive")
  {
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++)
    {
      set_ele(all[i]);
    }
  }
}

function check_element(ele)
{
  var all = document.getElementsByTagName("*");
  var total=all.length;
  var per_inc=100/total;

  if($(ele).on()){
    var prog_width=per_inc+Number($("#progress_width").val());
    $("#progress_width").val(prog_width);
    $("#bar1").animate({width:prog_width+"%"},100,function(){
      if($("#progress_width").css("width")>="100%"){
        $(".progress").fadeOut("slow");
      }
    });
  }

  else
  {
    set_ele(ele);
  }
}

function set_ele(set_element)
{
  check_element(set_element);
}


text:
var controllerInfraDashboardLoader = new ControllerInfraDashboardLoader();

function ControllerInfraDashboardLoader() {
    this.load = function (paramObject) {
        var self = this,
            hashParams = paramObject['hashParams'],
            renderFn = paramObject['function'];

        if(monInfraDashboardLoader.loadedControllerInfoboxes != true) {
            monInfraDashboardLoader.loadedControllerInfoboxes = true;
            require(['mon-infra-dashboard-view'],function() {
                require(['mon-infra-controller-dashboard'], function (ControllerDashboardView) {
                    self.monInfraDashboardView = new ControllerDashboardView({
                        el: $(contentContainer)
                    });
                    self.monInfraDashboardView.render();
                });
            });
        }
    };

    this.destroy = function()  {
    }
}


text:
var ProgressReporter = require('./progress');
var BaseColorReporter = require('./base_color');

var ProgressColorReporter = function(formatError, reportSlow) {
  ProgressReporter.call(this, formatError, reportSlow);
  BaseColorReporter.call(this);
};

// PUBLISH
module.exports = ProgressColorReporter;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.wise</groupId>
		<artifactId>wise</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>generator-sqlmap</artifactId>

	<dependencies>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<!-- jdk1.7 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
All Notable changes to `laravel-permission` will be documented in this file

## 1.12.0

- made foreign key name to users table configurable

## 1.11.1

- `hasPermissionTo` uses the cache to avoid extra queries when it is called multiple times

## 1.11.0

- add `getDirectPermissions`, `getPermissionsViaRoles`, `getAllPermissions`

## 1.10.0 - 2017-02-22

- add `hasAnyPermission`

## 1.9.0 - 2017-02-20
- add `log_registration_exception` in settings file
- fix for ambiguous column name `id` when using the role scope

## 1.8.0 - 2017-02-09
- `hasDirectPermission` method is now public

## 1.7.0 - 2016-01-23
- added support for Laravel 5.4

## 1.6.1 - 2016-01-19
- make exception logging more verbose

## 1.6.0 - 2016-12-27
- added `Role` scope

## 1.5.3 - 2016-12-15
- moved some things to `boot` method in SP to solve some compatibilty problems with other packages

## 1.5.2 - 2016-08-26
- make compatible with L5.3

## 1.5.1 - 2016-07-23
- fixes `givePermissionTo` and `assignRole` in Laravel 5.1

## 1.5.0 - 2016-07-23
** this version does not work in Laravel 5.1, please upgrade to version 1.5.1 of this package

- allowed `givePermissonTo` to accept multiple permissions
- allowed `assignRole` to accept multiple roles
- added `syncPermissions`-method
- added `syncRoles`-method
- dropped support for PHP 5.5 and HHVM

## 1.4.0 - 2016-05-08
-  added `hasPermissionTo` function to the `Role` model

## 1.3.4 - 2016-02-27
-  `hasAnyRole` can now properly process an array

## 1.3.3 - 2016-02-24

- `hasDirectPermission` can now accept a string

## 1.3.2 - 2016-02-23

- fixed user table configuration

## 1.3.1 - 2016-01-10

- fixed bug when testing for non existing permissions

## 1.3.0 - 2015-12-25

- added compatiblity for Laravel 5.2

## 1.2.1 - 2015-12-22

- use database_path to publish migrations

## 1.2.0 - 2015-10-28

###Added
- support for custom models

## 1.1.0 - 2015-10-12

### Added
- Blade directives
- `hasAllRoles()`- and `hasAnyRole()`-functions

## 1.0.2 - 2015-10-11

### Fixed
- Fix for running phpunit locally

## 1.0.1 - 2015-09-30

### Fixed
- Fixed the inconsistent naming of the `hasPermission`-method.

## 1.0.0 - 2015-09-16

### Added
- Everything, initial release


text:
<?php

// ensure we get report on all possible php errors
error_reporting(-1);

define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);
define('YII_ENV', 'test');

$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
$_SERVER['REQUEST_URI'] = '/';
$_SERVER['SERVER_NAME'] = 'yii2-frontend.test';

require_once(__DIR__ . '/../vendor/autoload.php');
require_once(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

Yii::setAlias('@DevGroup/Frontend/tests', __DIR__);
Yii::setAlias('@DevGroup/Frontend', dirname(__DIR__).'/src/');


text:
package de.djuelg.neuronizer.domain.model.preview;

/**
 * Created by Domi on 22.08.2017.
 */

public enum Sortation {
    IMPORTANCE(0),
    LAST_CHANGE(1),
    CREATION_DATE(2),
    ALPHABETICAL(3);

    private final int position;

    Sortation(int position) {
        this.position = position;
    }

    public static Sortation parse(int position) {
        switch (position) {
            case 0:
                return IMPORTANCE;
            case 1:
                return LAST_CHANGE;
            case 2:
                return CREATION_DATE;
            case 3:
                return ALPHABETICAL;
            default:
                break;
        }
        throw new IllegalArgumentException(position + " is out of bounds.");
    }

    public int toInt() {
        return position;
    }
}


text:
namespace Serilog.Core;

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Interface)]
sealed class CustomDefaultMethodImplementationAttribute : Attribute
{
}

#endif


text:
namespace Clase17Binding
{
    partial class ClientesForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.NuevoButton = new System.Windows.Forms.Button();
            this.ElimnarButton = new System.Windows.Forms.Button();
            this.ModificarButton = new System.Windows.Forms.Button();
            this.CerrarButton = new System.Windows.Forms.Button();
            this.personaBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.personaDataGridView = new System.Windows.Forms.DataGridView();
            this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.dataGridViewCheckBoxColumn1 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
            ((System.ComponentModel.ISupportInitialize)(this.personaBindingSource)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.personaDataGridView)).BeginInit();
            this.SuspendLayout();
            //
            // NuevoButton
            //
            this.NuevoButton.Location = new System.Drawing.Point(12, 12);
            this.NuevoButton.Name = "NuevoButton";
            this.NuevoButton.Size = new System.Drawing.Size(75, 23);
            this.NuevoButton.TabIndex = 0;
            this.NuevoButton.Text = "Nuevo";
            this.NuevoButton.UseVisualStyleBackColor = true;
            this.NuevoButton.Click += new System.EventHandler(this.NuevoButton_Click);
            //
            // ElimnarButton
            //
            this.ElimnarButton.Location = new System.Drawing.Point(93, 12);
            this.ElimnarButton.Name = "ElimnarButton";
            this.ElimnarButton.Size = new System.Drawing.Size(75, 23);
            this.ElimnarButton.TabIndex = 1;
            this.ElimnarButton.Text = "Eliminar";
            this.ElimnarButton.UseVisualStyleBackColor = true;
            //
            // ModificarButton
            //
            this.ModificarButton.Location = new System.Drawing.Point(174, 12);
            this.ModificarButton.Name = "ModificarButton";
            this.ModificarButton.Size = new System.Drawing.Size(75, 23);
            this.ModificarButton.TabIndex = 2;
            this.ModificarButton.Text = "Modificar";
            this.ModificarButton.UseVisualStyleBackColor = true;
            //
            // CerrarButton
            //
            this.CerrarButton.Location = new System.Drawing.Point(519, 12);
            this.CerrarButton.Name = "CerrarButton";
            this.CerrarButton.Size = new System.Drawing.Size(75, 23);
            this.CerrarButton.TabIndex = 4;
            this.CerrarButton.Text = "Cerrar";
            this.CerrarButton.UseVisualStyleBackColor = true;
            this.CerrarButton.Click += new System.EventHandler(this.CerrarButton_Click);
            //
            // personaBindingSource
            //
            this.personaBindingSource.DataSource = typeof(Entidades.Cliente);
            //
            // personaDataGridView
            //
            this.personaDataGridView.AutoGenerateColumns = false;
            this.personaDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.personaDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.dataGridViewTextBoxColumn1,
            this.dataGridViewTextBoxColumn2,
            this.dataGridViewTextBoxColumn3,
            this.dataGridViewTextBoxColumn4,
            this.dataGridViewCheckBoxColumn1});
            this.personaDataGridView.DataSource = this.personaBindingSource;
            this.personaDataGridView.Location = new System.Drawing.Point(12, 52);
            this.personaDataGridView.Name = "personaDataGridView";
            this.personaDataGridView.Size = new System.Drawing.Size(582, 286);
            this.personaDataGridView.TabIndex = 5;
            //
            // dataGridViewTextBoxColumn1
            //
            this.dataGridViewTextBoxColumn1.DataPropertyName = "Nombre";
            this.dataGridViewTextBoxColumn1.HeaderText = "Nombre";
            this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
            this.dataGridViewTextBoxColumn1.Width = 160;
            //
            // dataGridViewTextBoxColumn2
            //
            this.dataGridViewTextBoxColumn2.DataPropertyName = "Apellido";
            this.dataGridViewTextBoxColumn2.HeaderText = "Apellido";
            this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
            this.dataGridViewTextBoxColumn2.Width = 160;
            //
            // dataGridViewTextBoxColumn3
            //
            this.dataGridViewTextBoxColumn3.DataPropertyName = "FechaNacimiento";
            this.dataGridViewTextBoxColumn3.HeaderText = "Nacimiento";
            this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
            this.dataGridViewTextBoxColumn3.Width = 80;
            //
            // dataGridViewTextBoxColumn4
            //
            this.dataGridViewTextBoxColumn4.DataPropertyName = "DocumentoIdentidad";
            this.dataGridViewTextBoxColumn4.HeaderText = "Documento";
            this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
            this.dataGridViewTextBoxColumn4.Width = 70;
            //
            // dataGridViewCheckBoxColumn1
            //
            this.dataGridViewCheckBoxColumn1.DataPropertyName = "EsCasado";
            this.dataGridViewCheckBoxColumn1.HeaderText = "Casado";
            this.dataGridViewCheckBoxColumn1.Name = "dataGridViewCheckBoxColumn1";
            this.dataGridViewCheckBoxColumn1.Width = 60;
            //
            // ClientesForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(606, 350);
            this.Controls.Add(this.personaDataGridView);
            this.Controls.Add(this.CerrarButton);
            this.Controls.Add(this.ModificarButton);
            this.Controls.Add(this.ElimnarButton);
            this.Controls.Add(this.NuevoButton);
            this.Name = "ClientesForm";
            this.Text = "ClientesForm";
            ((System.ComponentModel.ISupportInitialize)(this.personaBindingSource)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.personaDataGridView)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button NuevoButton;
        private System.Windows.Forms.Button ElimnarButton;
        private System.Windows.Forms.Button ModificarButton;
        private System.Windows.Forms.Button CerrarButton;
        private System.Windows.Forms.BindingSource personaBindingSource;
        private System.Windows.Forms.DataGridView personaDataGridView;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
        private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
        private System.Windows.Forms.DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn1;
    }
}


text:
__author__ = 'c8d8z8@gmail.com'
'''
http 请求 支持cookie
'''
import urllib
import urllib2
import cookielib

#获取Cookiejar对象(存在本机的cookie信息)
cookie = cookielib.CookieJar()
#自定义opener,并将opener跟Cookiejar对象绑定
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
#添加header emulate iphone 5s
opener.addheaders = [('User-agent', 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4')]

#安装opener,此后调用urlopen()时都会使用安装过的opener对象
urllib2.install_opener(opener)

import re
import hashlib
import json
import datetime
import os

def GET(url,data = None):
    if data:
        url = url + '?' + urllib.urlencode(data)
        print 'get param : %s' % urllib.urlencode(data)
    print 'get url : %s' % url
    req = urllib2.Request(url)
    resp = urllib2.urlopen(req).read()
    print resp
    return resp

def request(url,data = None,cookie=None):
    print url
    print data
    if data:
        #将postdata转化成服务器编码的格式
        post_data = urllib.urlencode(data);
        req = urllib2.Request(url,post_data)
    else:
        req = urllib2.Request(url)

    #添加cookie
    if cookie:
        print cookie
        req.add_header('Cookie',cookie)

    resp = urllib2.urlopen(req).read()
    #print decode
    #resp = resp.decode(decode)
    print resp
    #print resp.status
    #print resp.encode(decode)

    #insert_req_to_musql(resp,url,post_data)
    return resp

def download(url,fpath,fname):
    print fpath+fname
    try:
        if not os.path.exists(fpath):
            os.makedirs(fpath)
    except Exception as e:
        print e
        print u'path not found!'
        exit()

    data = urllib.urlopen(url).read()

    f = file(fpath+fname,'wb')
    f.write(data)
    f.close()
    print 'download file complete - save as ' + fpath+fname

def paramparse(param):
    # 将url上的参数 转换为dic
    print param
    str_arr = param.split('&')
    print str_arr
    body_data = {};
    for str in str_arr:
        temp_arr = str.split('=')
        body_data[temp_arr[0]]=temp_arr[1].encode('utf-8')
    print body_data
    return body_data
def cookies():
    return cookie

def test_request():
    url = 'https://www.itoumi.com/sxb/products/loans.json'
    data = {}
    data['url'] = 'products/loans.json'
    data['prodNo'] = '20150811163740805506'
    data['startId'] =  1
    data['maxRecords'] = 5

    rt = request(url,data)
    jrt = json.loads(rt)

    pass

if __name__ == '__main__':
    test_request()
    print urllib.urlencode({"username":"root","password":"ROOTXXOO"})
    print cookie


text:
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Calc where
import           StackVM
import           Data.Functor ((<$>))
import qualified ExprT as E
import qualified Data.Map as M
import           Parser

-- Exercise #1:
eval :: E.ExprT -> Integer
eval (E.Lit a) = a
eval (E.Add a b) = eval a + eval b
eval (E.Mul a b) = eval a * eval b

-- Exercise #2:
evalStr :: String -> Maybe Integer
evalStr str = eval <$> parseExp E.Lit E.Add E.Mul str

-- Exercise #3:
class Expr a where
    lit :: Integer -> a
    add :: a -> a -> a
    mul :: a -> a -> a

instance Expr E.ExprT where
    lit a   = E.Lit a
    add a b = E.Add a b
    mul a b = E.Mul a b

-- Exercise #4:
instance Expr Integer where
    lit a   = a
    add a b = a + b
    mul a b = a * b

instance Expr Bool where
    lit a | a <= 0 = False
          | a >  0 = True
    add a b = a || b
    mul a b = a && b

data MinMax = MinMax Integer
    deriving (Show, Eq, Ord)

instance Expr MinMax where
    lit a = MinMax a
    add a b = max a b
    mul a b = min a b

data Mod7 = Mod7 Integer
    deriving (Show, Eq, Ord)

instance Num Mod7 where
    fromInteger a   = Mod7 (a `mod` 7)
    Mod7 a + Mod7 b = fromInteger (a + b)
    Mod7 a * Mod7 b = fromInteger (a * b)
    Mod7 a - Mod7 b = fromInteger (a - b)
    signum (Mod7 a) = Mod7 (signum a)
    abs (Mod7 a)    = Mod7 (abs a)

instance Expr Mod7 where
    lit a   = fromInteger a :: Mod7
    add a b = a + b
    mul a b = a * b

-- Exercise #5:

instance Expr Program where
   lit a   = [PushI a]
   add a b = a ++ b ++ [Add]
   mul a b = a ++ b ++ [Mul]

compile :: String -> Maybe Program
compile str = parseExp lit add mul str

-- Exercise #6:

class HasVars a where
    var :: String -> a

data VarExprT = LitV Integer
              | Var String
              | AddV VarExprT VarExprT
              | MulV VarExprT VarExprT
              deriving (Eq, Ord, Show)

instance HasVars VarExprT where
    var x = Var x

instance Expr VarExprT where
    lit a   = LitV a
    add a b = AddV a b
    mul a b = MulV a b


text:
angular.module('ngBoilerplate')

.factory('Message', ['$resource', function($resource) {
    return $resource('/api/messages/:id');
}]);


text:
package org.apereo.cas.adaptors.gauth;

import org.apereo.cas.authentication.OneTimeTokenCredential;

import lombok.NoArgsConstructor;

/**
 * This is {@link GoogleAuthenticatorTokenCredential}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@NoArgsConstructor
public class GoogleAuthenticatorTokenCredential extends OneTimeTokenCredential {

    private static final long serialVersionUID = -7570600701132111037L;

    public GoogleAuthenticatorTokenCredential(final String token) {
        super(token);
    }
}