text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.operator.scalar;

import io.trino.spi.TrinoException;
import io.trino.spi.block.Block;
import io.trino.spi.function.Description;
import io.trino.spi.function.ScalarFunction;
import io.trino.spi.function.SqlNullable;
import io.trino.spi.function.SqlType;
import io.trino.spi.function.TypeParameter;
import io.trino.spi.type.Type;

import static io.trino.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static java.lang.Math.toIntExact;

@ScalarFunction("element_at")
@Description("Get element of array at given index")
public final class ArrayElementAtFunction
{
    private ArrayElementAtFunction() {}

    @TypeParameter("E")
    @SqlNullable
    @SqlType("E")
    public static Long longElementAt(@TypeParameter("E") Type elementType, @SqlType("array(E)") Block array, @SqlType("bigint") long index)
    {
        int position = checkedIndexToBlockPosition(array, index);
        if (position == -1) {
            return null;
        }
        if (array.isNull(position)) {
            return null;
        }

        return elementType.getLong(array, position);
    }

    @TypeParameter("E")
    @SqlNullable
    @SqlType("E")
    public static Boolean booleanElementAt(@TypeParameter("E") Type elementType, @SqlType("array(E)") Block array, @SqlType("bigint") long index)
    {
        int position = checkedIndexToBlockPosition(array, index);
        if (position == -1) {
            return null;
        }
        if (array.isNull(position)) {
            return null;
        }

        return elementType.getBoolean(array, position);
    }

    @TypeParameter("E")
    @SqlNullable
    @SqlType("E")
    public static Double doubleElementAt(@TypeParameter("E") Type elementType, @SqlType("array(E)") Block array, @SqlType("bigint") long index)
    {
        int position = checkedIndexToBlockPosition(array, index);
        if (position == -1) {
            return null;
        }
        if (array.isNull(position)) {
            return null;
        }

        return elementType.getDouble(array, position);
    }

    @TypeParameter("E")
    @SqlNullable
    @SqlType("E")
    public static Object sliceElementAt(@TypeParameter("E") Type elementType, @SqlType("array(E)") Block array, @SqlType("bigint") long index)
    {
        int position = checkedIndexToBlockPosition(array, index);
        if (position == -1) {
            return null;
        }
        if (array.isNull(position)) {
            return null;
        }

        return elementType.getObject(array, position);
    }

    /**
     * @return TrinoException if the index is 0, -1 if the index is out of range (to tell the calling function to return null), and the element position otherwise.
     */
    private static int checkedIndexToBlockPosition(Block block, long index)
    {
        int arrayLength = block.getPositionCount();
        if (index == 0) {
            throw new TrinoException(INVALID_FUNCTION_ARGUMENT, "SQL array indices start at 1");
        }
        if (Math.abs(index) > arrayLength) {
            return -1; // -1 indicates that the element is out of range and "ELEMENT_AT" should return null
        }
        if (index > 0) {
            return toIntExact(index - 1);
        }
        return toIntExact(arrayLength + index);
    }
}


text:
#include "rdx_pragmas.hpp"

template<bool T>
struct rdxStaticAssertCheck
{
};

template<>
struct rdxStaticAssertCheck<true>
{
	RDX_FORCEINLINE static void STATIC_ASSERT_FAILED() { }
};

#define rdxStaticAssert(cond) do { rdxStaticAssertCheck<cond>::STATIC_ASSERT_FAILED(); } while(false)

#endif

redpajama_set_name: RedPajamaGithub


text:
"""
Example that trains an LSTM or GRU based recurrent networks.
The dataset uses Penn Treebank dataset parsing on word-level.

Reference:
    Recurrent Neural Network Regularization `[Zaremba2015]`_
    Generating sequences with recurrent neural networks `[Graves2014]`_
.. _[Zaremba2015]: http://arxiv.org/pdf/1409.2329v5.pdf
.. _[Graves2014]: http://arxiv.org/pdf/1308.0850.pdf

Usage:
    python examples/word_lstm.py -e 13 -eval 1 --rlayer_type lstm

"""

from neon.backends import gen_backend
from neon.data import Text, load_text
from neon.initializers import Uniform
from neon.layers import GeneralizedCost, LSTM, Affine, GRU, LookupTable
from neon.models import Model
from neon.optimizers import GradientDescentMomentum, Schedule
from neon.transforms import Logistic, Tanh, Softmax, CrossEntropyMulti
from neon.callbacks.callbacks import Callbacks
from neon.util.argparser import NeonArgparser, extract_valid_args

# parse the command line arguments
parser = NeonArgparser(__doc__)
parser.add_argument('--rlayer_type', default='lstm', choices=['gru', 'lstm'],
                    help='type of recurrent layer to use (gru or lstm)')
args = parser.parse_args(gen_be=False)

# hyperparameters from the reference
args.batch_size = 20
time_steps = 20
hidden_size = 200
gradient_clip_norm = 5

# setup backend
be = gen_backend(**extract_valid_args(args, gen_backend))

# download penn treebank
train_path = load_text('ptb-train', path=args.data_dir)
valid_path = load_text('ptb-valid', path=args.data_dir)

# define a custom function to parse the input into individual tokens, which for
# this data, splits into individual words.  This can be passed into the Text
# object during dataset creation as seen below.
def tokenizer(s):
    return s.replace('\n', '<eos>').split()

# load data and parse on word-level
train_set = Text(time_steps, train_path, tokenizer=tokenizer, onehot_input=False)
valid_set = Text(time_steps, valid_path, vocab=train_set.vocab, tokenizer=tokenizer,
                 onehot_input=False)

# weight initialization
init = Uniform(low=-0.1, high=0.1)

# model initialization
rlayer_params = {"output_size": hidden_size, "init": init,
                 "activation": Tanh(), "gate_activation": Logistic()}
if args.rlayer_type == 'lstm':
    rlayer1, rlayer2 = LSTM(**rlayer_params), LSTM(**rlayer_params)
else:
    rlayer1, rlayer2 = GRU(**rlayer_params), GRU(**rlayer_params)

layers = [
    LookupTable(vocab_size=len(train_set.vocab), embedding_dim=hidden_size, init=init),
    rlayer1,
    rlayer2,
    Affine(len(train_set.vocab), init, bias=init, activation=Softmax())
]

cost = GeneralizedCost(costfunc=CrossEntropyMulti(usebits=True))

model = Model(layers=layers)

# vanilla gradient descent with decay schedule on learning rate and gradient scaling
learning_rate_sched = Schedule(range(5, args.epochs), .5)
optimizer = GradientDescentMomentum(1, 0, gradient_clip_norm=gradient_clip_norm,
                                    schedule=learning_rate_sched)

# configure callbacks
callbacks = Callbacks(model, train_set, eval_set=valid_set, **args.callback_args)

# train model
model.fit(train_set, optimizer=optimizer, num_epochs=args.epochs, cost=cost, callbacks=callbacks)


text:
package handler

import (
	"fmt"
	"log"
	"net/http"
	"strconv"

	restful "github.com/emicklei/go-restful"
	// TODO(maciaszczykm): Avoid using dot-imports.
	. "github.com/kubernetes/dashboard/client"
	. "github.com/kubernetes/dashboard/resource/container"
	"github.com/kubernetes/dashboard/resource/deployment"
	. "github.com/kubernetes/dashboard/resource/event"
	. "github.com/kubernetes/dashboard/resource/namespace"
	"github.com/kubernetes/dashboard/resource/pod"
	"github.com/kubernetes/dashboard/resource/replicaset"
	. "github.com/kubernetes/dashboard/resource/replicationcontroller"
	. "github.com/kubernetes/dashboard/resource/secret"
	resourceService "github.com/kubernetes/dashboard/resource/service"
	"github.com/kubernetes/dashboard/resource/workload"
	. "github.com/kubernetes/dashboard/validation"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
)

const (
	// RequestLogString is a template for request log message.
	RequestLogString = "Incoming %s %s %s request from %s"

	// ResponseLogString is a template for response log message.
	ResponseLogString = "Outcoming response to %s with %d status code"
)

// ApiHandler is a representation of API handler. Structure contains client, Heapster client and
// client configuration.
type ApiHandler struct {
	client         *client.Client
	heapsterClient HeapsterClient
	clientConfig   clientcmd.ClientConfig
}

// Web-service filter function used for request and response logging.
func wsLogger(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	log.Printf(FormatRequestLog(req))
	chain.ProcessFilter(req, resp)
	log.Printf(FormatResponseLog(resp, req))
}

// FormatRequestLog formats request log string.
// TODO(maciaszczykm): Display request body.
func FormatRequestLog(req *restful.Request) string {
	reqURI := ""
	if req.Request.URL != nil {
		reqURI = req.Request.URL.RequestURI()
	}

	return fmt.Sprintf(RequestLogString, req.Request.Proto, req.Request.Method,
		reqURI, req.Request.RemoteAddr)
}

// FormatResponseLog formats response log string.
// TODO(maciaszczykm): Display response content.
func FormatResponseLog(resp *restful.Response, req *restful.Request) string {
	return fmt.Sprintf(ResponseLogString, req.Request.RemoteAddr, resp.StatusCode())
}

// CreateHttpApiHandler creates a new HTTP handler that handles all requests to the API of the backend.
func CreateHttpApiHandler(client *client.Client, heapsterClient HeapsterClient,
	clientConfig clientcmd.ClientConfig) http.Handler {

	apiHandler := ApiHandler{client, heapsterClient, clientConfig}
	wsContainer := restful.NewContainer()

	deployWs := new(restful.WebService)
	deployWs.Filter(wsLogger)
	deployWs.Path("/api/v1/appdeployments").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	deployWs.Route(
		deployWs.POST("").
			To(apiHandler.handleDeploy).
			Reads(AppDeploymentSpec{}).
			Writes(AppDeploymentSpec{}))
	deployWs.Route(
		deployWs.POST("/validate/name").
			To(apiHandler.handleNameValidity).
			Reads(AppNameValiditySpec{}).
			Writes(AppNameValidity{}))
	deployWs.Route(
		deployWs.POST("/validate/imagereference").
			To(apiHandler.handleImageReferenceValidity).
			Reads(ImageReferenceValiditySpec{}).
			Writes(ImageReferenceValidity{}))
	deployWs.Route(
		deployWs.POST("/validate/protocol").
			To(apiHandler.handleProtocolValidity).
			Reads(ProtocolValiditySpec{}).
			Writes(ProtocolValidity{}))
	deployWs.Route(
		deployWs.GET("/protocols").
			To(apiHandler.handleGetAvailableProcotols).
			Writes(Protocols{}))
	wsContainer.Add(deployWs)

	deployFromFileWs := new(restful.WebService)
	deployFromFileWs.Path("/api/v1/appdeploymentfromfile").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	deployFromFileWs.Route(
		deployFromFileWs.POST("").
			To(apiHandler.handleDeployFromFile).
			Reads(AppDeploymentFromFileSpec{}).
			Writes(AppDeploymentFromFileResponse{}))
	wsContainer.Add(deployFromFileWs)

	replicationControllerWs := new(restful.WebService)
	replicationControllerWs.Filter(wsLogger)
	replicationControllerWs.Path("/api/v1/replicationcontrollers").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	replicationControllerWs.Route(
		replicationControllerWs.GET("").
			To(apiHandler.handleGetReplicationControllerList).
			Writes(ReplicationControllerList{}))
	replicationControllerWs.Route(
		replicationControllerWs.GET("/{namespace}/{replicationController}").
			To(apiHandler.handleGetReplicationControllerDetail).
			Writes(ReplicationControllerDetail{}))
	replicationControllerWs.Route(
		replicationControllerWs.POST("/{namespace}/{replicationController}/update/pods").
			To(apiHandler.handleUpdateReplicasCount).
			Reads(ReplicationControllerSpec{}))
	replicationControllerWs.Route(
		replicationControllerWs.DELETE("/{namespace}/{replicationController}").
			To(apiHandler.handleDeleteReplicationController))
	replicationControllerWs.Route(
		replicationControllerWs.GET("/pods/{namespace}/{replicationController}").
			To(apiHandler.handleGetReplicationControllerPods).
			Writes(ReplicationControllerPods{}))
	wsContainer.Add(replicationControllerWs)

	workloadsWs := new(restful.WebService)
	workloadsWs.Filter(wsLogger)
	workloadsWs.Path("/api/v1/workloads").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	workloadsWs.Route(
		workloadsWs.GET("").
			To(apiHandler.handleGetWorkloads).
			Writes(workload.Workloads{}))
	wsContainer.Add(workloadsWs)

	replicaSetsWs := new(restful.WebService)
	replicaSetsWs.Filter(wsLogger)
	replicaSetsWs.Path("/api/v1/replicasets").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	replicaSetsWs.Route(
		replicaSetsWs.GET("").
			To(apiHandler.handleGetReplicaSets).
			Writes(replicaset.ReplicaSetList{}))
	wsContainer.Add(replicaSetsWs)

	podsWs := new(restful.WebService)
	podsWs.Filter(wsLogger)
	podsWs.Path("/api/v1/pods").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	podsWs.Route(
		podsWs.GET("").
			To(apiHandler.handleGetPods).
			Writes(pod.PodList{}))
	wsContainer.Add(podsWs)

	deploymentsWs := new(restful.WebService)
	deploymentsWs.Filter(wsLogger)
	deploymentsWs.Path("/api/v1/deployments").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	deploymentsWs.Route(
		deploymentsWs.GET("").
			To(apiHandler.handleGetDeployments).
			Writes(deployment.DeploymentList{}))
	wsContainer.Add(deploymentsWs)

	namespacesWs := new(restful.WebService)
	namespacesWs.Filter(wsLogger)
	namespacesWs.Path("/api/v1/namespaces").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	namespacesWs.Route(
		namespacesWs.POST("").
			To(apiHandler.handleCreateNamespace).
			Reads(NamespaceSpec{}).
			Writes(NamespaceSpec{}))
	namespacesWs.Route(
		namespacesWs.GET("").
			To(apiHandler.handleGetNamespaces).
			Writes(NamespaceList{}))
	wsContainer.Add(namespacesWs)

	logsWs := new(restful.WebService)
	logsWs.Filter(wsLogger)
	logsWs.Path("/api/v1/logs").
		Produces(restful.MIME_JSON)
	logsWs.Route(
		logsWs.GET("/{namespace}/{podId}").
			To(apiHandler.handleLogs).
			Writes(Logs{}))
	logsWs.Route(
		logsWs.GET("/{namespace}/{podId}/{container}").
			To(apiHandler.handleLogs).
			Writes(Logs{}))
	wsContainer.Add(logsWs)

	eventsWs := new(restful.WebService)
	eventsWs.Filter(wsLogger)
	eventsWs.Path("/api/v1/events").
		Produces(restful.MIME_JSON)
	eventsWs.Route(
		eventsWs.GET("/{namespace}/{replicationController}").
			To(apiHandler.handleEvents).
			Writes(Events{}))
	wsContainer.Add(eventsWs)

	secretsWs := new(restful.WebService)
	secretsWs.Path("/api/v1/secrets").Produces(restful.MIME_JSON)
	secretsWs.Route(
		secretsWs.GET("/{namespace}").
			To(apiHandler.handleGetSecrets).
			Writes(SecretsList{}))
	secretsWs.Route(
		secretsWs.POST("").
			To(apiHandler.handleCreateImagePullSecret).
			Reads(ImagePullSecretSpec{}).
			Writes(Secret{}))
	wsContainer.Add(secretsWs)

	servicesWs := new(restful.WebService)
	servicesWs.Filter(wsLogger)
	servicesWs.Path("/api/v1/services").
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)
	servicesWs.Route(
		servicesWs.GET("").
			To(apiHandler.handleGetServiceList).
			Writes(resourceService.ServiceList{}))
	servicesWs.Route(
		servicesWs.GET("/{namespace}/{service}").
			To(apiHandler.handleGetServiceDetail).
			Writes(resourceService.ServiceDetail{}))
	wsContainer.Add(servicesWs)

	return wsContainer
}

// Handles get service list API call.
func (apiHandler *ApiHandler) handleGetServiceList(request *restful.Request, response *restful.Response) {
	result, err := resourceService.GetServiceList(apiHandler.client)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles get service detail API call.
func (apiHandler *ApiHandler) handleGetServiceDetail(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	service := request.PathParameter("service")
	result, err := resourceService.GetServiceDetail(apiHandler.client, namespace, service)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles deploy API call.
func (apiHandler *ApiHandler) handleDeploy(request *restful.Request, response *restful.Response) {
	appDeploymentSpec := new(AppDeploymentSpec)
	if err := request.ReadEntity(appDeploymentSpec); err != nil {
		handleInternalError(response, err)
		return
	}
	if err := DeployApp(appDeploymentSpec, apiHandler.client); err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, appDeploymentSpec)
}

// Handles deploy from file API call.
func (apiHandler *ApiHandler) handleDeployFromFile(request *restful.Request, response *restful.Response) {
	deploymentSpec := new(AppDeploymentFromFileSpec)
	if err := request.ReadEntity(deploymentSpec); err != nil {
		handleInternalError(response, err)
		return
	}

	isDeployed, err := DeployAppFromFile(
		deploymentSpec, CreateObjectFromInfoFn, apiHandler.clientConfig)
	if !isDeployed {
		handleInternalError(response, err)
		return
	}

	errorMessage := ""
	if err != nil {
		errorMessage = err.Error()
	}

	response.WriteHeaderAndEntity(http.StatusCreated, AppDeploymentFromFileResponse{
		Name:    deploymentSpec.Name,
		Content: deploymentSpec.Content,
		Error:   errorMessage,
	})
}

// Handles app name validation API call.
func (apiHandler *ApiHandler) handleNameValidity(request *restful.Request, response *restful.Response) {
	spec := new(AppNameValiditySpec)
	if err := request.ReadEntity(spec); err != nil {
		handleInternalError(response, err)
		return
	}

	validity, err := ValidateAppName(spec, apiHandler.client)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, validity)
}

// Handles image reference validation API call.
func (ApiHandler *ApiHandler) handleImageReferenceValidity(request *restful.Request, response *restful.Response) {
	spec := new(ImageReferenceValiditySpec)
	if err := request.ReadEntity(spec); err != nil {
		handleInternalError(response, err)
		return
	}

	validity, err := ValidateImageReference(spec)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusCreated, validity)
}

// Handles protocol validation API call.
func (apiHandler *ApiHandler) handleProtocolValidity(request *restful.Request, response *restful.Response) {
	spec := new(ProtocolValiditySpec)
	if err := request.ReadEntity(spec); err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, ValidateProtocol(spec))
}

// Handles get available protocols API call.
func (apiHandler *ApiHandler) handleGetAvailableProcotols(request *restful.Request, response *restful.Response) {
	response.WriteHeaderAndEntity(http.StatusCreated, GetAvailableProtocols())
}

// Handles get Replication Controller list API call.
func (apiHandler *ApiHandler) handleGetReplicationControllerList(
	request *restful.Request, response *restful.Response) {

	result, err := GetReplicationControllerList(apiHandler.client)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles get Workloads list API call.
func (apiHandler *ApiHandler) handleGetWorkloads(
	request *restful.Request, response *restful.Response) {

	result, err := workload.GetWorkloads(apiHandler.client, apiHandler.heapsterClient)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles get Replica Sets list API call.
func (apiHandler *ApiHandler) handleGetReplicaSets(
	request *restful.Request, response *restful.Response) {

	result, err := replicaset.GetReplicaSetList(apiHandler.client)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles get Deployment list API call.
func (apiHandler *ApiHandler) handleGetDeployments(
	request *restful.Request, response *restful.Response) {

	result, err := deployment.GetDeploymentList(apiHandler.client)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles get Pod list API call.
func (apiHandler *ApiHandler) handleGetPods(
	request *restful.Request, response *restful.Response) {

	result, err := pod.GetPodList(apiHandler.client, apiHandler.heapsterClient)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles get Replication Controller detail API call.
func (apiHandler *ApiHandler) handleGetReplicationControllerDetail(
	request *restful.Request, response *restful.Response) {

	namespace := request.PathParameter("namespace")
	replicationController := request.PathParameter("replicationController")
	result, err := GetReplicationControllerDetail(apiHandler.client, apiHandler.heapsterClient, namespace, replicationController)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles update of Replication Controller pods update API call.
func (apiHandler *ApiHandler) handleUpdateReplicasCount(
	request *restful.Request, response *restful.Response) {

	namespace := request.PathParameter("namespace")
	replicationControllerName := request.PathParameter("replicationController")
	replicationControllerSpec := new(ReplicationControllerSpec)

	if err := request.ReadEntity(replicationControllerSpec); err != nil {
		handleInternalError(response, err)
		return
	}

	if err := UpdateReplicasCount(apiHandler.client, namespace, replicationControllerName,
		replicationControllerSpec); err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeader(http.StatusAccepted)
}

// Handles delete Replication Controller API call.
// TODO(floreks): there has to be some kind of transaction here
func (apiHandler *ApiHandler) handleDeleteReplicationController(
	request *restful.Request, response *restful.Response) {

	namespace := request.PathParameter("namespace")
	replicationController := request.PathParameter("replicationController")
	deleteServices, err := strconv.ParseBool(request.QueryParameter("deleteServices"))
	if err != nil {
		handleInternalError(response, err)
		return
	}

	if err := DeleteReplicationController(apiHandler.client, namespace,
		replicationController, deleteServices); err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeader(http.StatusOK)
}

// Handles get Replication Controller Pods API call.
func (apiHandler *ApiHandler) handleGetReplicationControllerPods(
	request *restful.Request, response *restful.Response) {

	namespace := request.PathParameter("namespace")
	replicationController := request.PathParameter("replicationController")
	limit, err := strconv.Atoi(request.QueryParameter("limit"))
	if err != nil {
		limit = 0
	}
	result, err := GetReplicationControllerPods(apiHandler.client, namespace, replicationController, limit)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles namespace creation API call.
func (apiHandler *ApiHandler) handleCreateNamespace(request *restful.Request,
	response *restful.Response) {
	namespaceSpec := new(NamespaceSpec)
	if err := request.ReadEntity(namespaceSpec); err != nil {
		handleInternalError(response, err)
		return
	}
	if err := CreateNamespace(namespaceSpec, apiHandler.client); err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, namespaceSpec)
}

// Handles get namespace list API call.
func (apiHandler *ApiHandler) handleGetNamespaces(
	request *restful.Request, response *restful.Response) {

	result, err := GetNamespaceList(apiHandler.client)
	if err != nil {
		handleInternalError(response, err)
		return
	}

	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles image pull secret creation API call.
func (apiHandler *ApiHandler) handleCreateImagePullSecret(request *restful.Request, response *restful.Response) {
	secretSpec := new(ImagePullSecretSpec)
	if err := request.ReadEntity(secretSpec); err != nil {
		handleInternalError(response, err)
		return
	}
	secret, err := CreateSecret(apiHandler.client, secretSpec)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusCreated, secret)
}

// Handles get secrets list API call.
func (apiHandler *ApiHandler) handleGetSecrets(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	result, err := GetSecrets(apiHandler.client, namespace)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusOK, result)
}

// Handles log API call.
func (apiHandler *ApiHandler) handleLogs(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	podId := request.PathParameter("podId")
	container := request.PathParameter("container")

	result, err := GetPodLogs(apiHandler.client, namespace, podId, container)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handles event API call.
func (apiHandler *ApiHandler) handleEvents(request *restful.Request, response *restful.Response) {
	namespace := request.PathParameter("namespace")
	replicationController := request.PathParameter("replicationController")
	result, err := GetEvents(apiHandler.client, namespace, replicationController)
	if err != nil {
		handleInternalError(response, err)
		return
	}
	response.WriteHeaderAndEntity(http.StatusCreated, result)
}

// Handler that writes the given error to the response and sets appropriate HTTP status headers.
func handleInternalError(response *restful.Response, err error) {
	log.Print(err)
	response.AddHeader("Content-Type", "text/plain")
	response.WriteErrorString(http.StatusInternalServerError, err.Error()+"\n")
}


text:
namespace gfx {
class RectF;
}

namespace blink {

class AffineTransform;
class LayoutRect;
class LayoutUnit;
class PropertyTreeState;
class TransformPaintPropertyNode;

class PLATFORM_EXPORT CullRect {
  DISALLOW_NEW();

 public:
  CullRect() = default;
  explicit CullRect(const gfx::Rect& rect) : rect_(rect) {}

  static CullRect Infinite() { return CullRect(LayoutRect::InfiniteIntRect()); }

  bool IsInfinite() const { return rect_ == LayoutRect::InfiniteIntRect(); }

  bool Intersects(const gfx::Rect&) const;
  bool IntersectsTransformed(const AffineTransform&, const gfx::RectF&) const;
  bool IntersectsHorizontalRange(LayoutUnit lo, LayoutUnit hi) const;
  bool IntersectsVerticalRange(LayoutUnit lo, LayoutUnit hi) const;

  void Move(const gfx::Vector2d& offset);

  // Applies one transform to the cull rect. Before this function is called,
  // the cull rect is in the space of the parent the transform node.
  void ApplyTransform(const TransformPaintPropertyNode&);

  // For CullRectUpdate only. Similar to the above but also applies clips and
  // expands for all directly composited transforms (including scrolling and
  // non-scrolling ones). |root| is used to calculate the expansion distance in
  // the local space, to make the expansion distance approximately the same in
  // the root space.
  // Returns whether the cull rect has been expanded.
  bool ApplyPaintProperties(const PropertyTreeState& root,
                            const PropertyTreeState& source,
                            const PropertyTreeState& destination,
                            const absl::optional<CullRect>& old_cull_rect);

  const gfx::Rect& Rect() const { return rect_; }

  String ToString() const { return String(rect_.ToString()); }

 private:
  friend class CullRectTest;

  enum ApplyTransformResult {
    // The cull rect is transformed into the target transform space (by mapping
    // the cull rect with the inverse of the transform) without expansion.
    // In SlimmingPaintV1, the functions always return this value.
    kNotExpanded,
    // The cull rect is converted by a scroll translation (in the steps
    // described in ApplyTransform(), and the result covers the whole scrolling
    // contents.
    kExpandedForWholeScrollingContents,
    // The cull rect is converted by a scroll translation, and the result
    // doesn't cover the whole scrolling contents.
    kExpandedForPartialScrollingContents,
  };
  ApplyTransformResult ApplyScrollTranslation(
      const TransformPaintPropertyNode& root_transform,
      const TransformPaintPropertyNode& scroll_translation);

  // Returns false if the rect is clipped to be invisible. Otherwise returns
  // true, even if the cull rect is empty due to a special 3d transform in case
  // later 3d transforms make the cull rect visible again.
  bool ApplyPaintPropertiesWithoutExpansion(
      const PropertyTreeState& source,
      const PropertyTreeState& destination);

  bool ChangedEnough(const CullRect& old_cull_rect,
                     const absl::optional<gfx::Rect>& expansion_bounds) const;

  gfx::Rect rect_;
};

inline bool operator==(const CullRect& a, const CullRect& b) {
  return a.Rect() == b.Rect();
}
inline bool operator!=(const CullRect& a, const CullRect& b) {
  return !(a == b);
}

inline std::ostream& operator<<(std::ostream& os, const CullRect& cull_rect) {
  return os << cull_rect.ToString();
}

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_CULL_RECT_H_


text:
.. EN-Revision: none
.. _zend.view.helpers.initial.partial:

Partielle Helfer
================

Der ``Partial`` (Partielle) View Helfer wird verwendet um ein spezielles Template innerhalb seines eigenen
variablen Bereichs zu rendern. Primär wird er für wiederverwendbare Templatefragmente verwendet bei denen man
keine Vorsorge wegen variablen Namenskonflikten aufpassen muß. Zusätzlich erlauben Sie es Teile von View Skripten
von speziellen Modulen zu spezifizieren.

Ein Geschwisterteil zum ``Partial`` ist der ``PartialLoop`` View Helfer der es erlaubt Daten zu übergeben die
durchlaufen werden können, und einen Abschnitt für jedes Teil auszugeben.

.. note::

   **PartialLoop Zähler**

   Der ``PartialLoop`` View Helfer fügt der View eine Variable hinzu die **partialCounter** heißt und welche die
   aktuelle Position des Arrays zum View Skript übergibt. Das bietet einen einfachen Weg um alternative
   Farbgebungen zum Bespiel bei Tabellenzeilen zu haben.

.. _zend.view.helpers.initial.partial.usage:

.. rubric:: Grundsätzliche Verwendung von Partials

Die grundsätzliche Verwendung von Partials ist die Ausgabe von Templatefragmenten im eigenen Viewbereich. Es wird
das folgende teilweise Skript angenommen:

.. code-block:: php
   :linenos:

   <?php // partial.phtml ?>

Von: <?php echo $this->escape($this->from) ?>

Subjekt: <?php echo $this->escape($this->subject) ?>

Dieses würde dann vom View Skript aufgerufen indem das folgende verwendet wird:

.. code-block:: php
   :linenos:

   <?php echo $this->partial('partial.phtml', array(
       'from' => 'Team Framework',
       'subject' => 'Teil der View')); ?>

Was dann das folgende ausgibt:

.. code-block:: html
   :linenos:

From: Team Framework

Subject: Teil der View

.. note::

   **Was ist ein Modell?**

   Ein Modell das mit dem ``Partial`` View Helfer verwendet wird kann eines der folgenden sein:

   - **Array**. Wenn ein Array übergeben wird, sollte es assoziativ sein, und seine Schlüssel/Werte Paare werden
     der View mit dem Schlüssel als View Variable zugeordnet.

   - **Objekt das die toArray() Methode implementiert**. Wenn ein Objekt übergeben wird das eine ``toArray()``
     Methode besitzt, wird das Ergebnis von ``toArray()`` dem View Objekt als View Variablen zugeordnet.

   - **Standard Objekt**. Jedes andere Objekt wird die Ergebnisse von ``object_get_vars()`` (essentiell alle
     öffentlichen Eigenschaften des Objektes) dem View Objekt zuordnen.

   Wenn das eigene Modell ein Objekt ist, kann es gewünscht sein, es **als Objekt** an das Partielle Skript zu
   übergeben, statt es in ein Array von Variablen zu serialisieren. Das kann durch das Setzen der 'objectKey'
   Eigenschaft des betreffenden Helfers getan werden:

   .. code-block:: php
      :linenos:

      // Dem Partiellen mitteilen das ein Objekt als 'model' Variable übergeben wird
      $view->partial()->setObjectKey('model');

      // Dem Partiellen mitteilen das ein Objekt von partialLoop als 'model'
      // Variable im letzten Partiellen View Skript übergeben wird
      $view->partialLoop()->setObjectKey('model');

   Diese Technik ist speziell dann sinnvoll wenn ``Zend\Db\Table\Rowset``\ s an ``partialLoop()`` übergeben
   werden, da man dann kompletten Zugriff auf die Zeilenobjekte im View Skript hat, was es einem erlaubt Ihre
   Methoden auszurufen (wie das empfangen von Werten bei Eltern- oder abhängigen Zeilen).

.. _zend.view.helpers.initial.partial.partialloop:

.. rubric:: Verwendung von PartialLoop um iterierbare Modelle darzustellen

Typischerweise, wird man Partials in einer Schleife verwenden um das selbe Inhaltsfragment, viele Male,
darzustellen; auf diesem Weg können große Blöcke von wiederholenden Inhalten oder komplexe Anzeigelogik auf
einen einzelnen Platz gegeben werden. Trotzdem hat das einen Geschwindigkeitsnachteil, da der partielle Helfer
einmal für jede Iteration aufgerufen werden muß.

Der ``PartialLoop`` View Helfer hilft bei der Lösung dieses Problems. Er erlaubt es einen wiederholenden Teil
(Array oder Objekt das einen **Iterator** implementiert) als Modell zu übergeben. Er iteriert dann darüber, und
übergibt dessen Teile dem Partial Skript als Modell. Teil in diesem Iterator kann jedes Modell sein das der
``Partial`` View Helfer erlaubt.

Es wird das folgende teilweise View Skript angenommen:

.. code-block:: php
   :linenos:

   <?php // partialLoop.phtml ?>

<?php echo $this->key ?>

<?php echo $this->value ?>

Und das folgende "Modell":

.. code-block:: php
   :linenos:

   $model = array(
       array('key' => 'Säugetier', 'value' => 'Kamel'),
       array('key' => 'Vogel', 'value' => 'Pinguin'),
       array('key' => 'Reptil', 'value' => 'Viper'),
       array('key' => 'Fisch', 'value' => 'Flunder'),
   );

Im View Skript wird dann der ``PartialLoop`` Helfer aufgerufen:

.. code-block:: php
   :linenos:

   <?php echo $this->partialLoop('partialLoop.phtml', $model) ?>

.. code-block:: html
   :linenos:

Säugetier

Kamel

Vogel

Pinguin

Reptil

Viper

Fisch

Flunder

.. _zend.view.helpers.initial.partial.modules:

.. rubric:: Partials in anderen Modulen darstellen

Zeitweise existiert ein Parial in einem anderen Modul. Wenn der Name des Moduls bekannt ist, kann dieses als
zweites Argument entweder ``partial()`` oder ``partialLoop()`` übergeben werden, indem das ``$model`` Argument an
dritte Stelle verschoben wird.

Wenn zum Beispiel, eine Teilseite existiert im 'list' Modul existiert die verwendet werden soll, kann diese wie
folgt genommen werden:

.. code-block:: php
   :linenos:

   <?php echo $this->partial('pager.phtml', 'list', $pagerData) ?>

Auf diesem Weg, können Teile wiederverwendet werden die speziell für andere Module erstellt wurden. Deshalb ist
es besser, wiederverwendbare Teile in einen Pfad für geteilt View Skripte zu geben.


text:
require 'spec_helper'

describe StaticController do

  render_views
  subject{ response }

  describe 'GET guidelines' do
    before{ get :guidelines, {locale: :pt} }
    it{ should be_success }
    its(:body){ should =~ /#{I18n.t('static.guidelines.title')}/ }
    its(:body){ should =~ /#{I18n.t('static.guidelines.subtitle')}/ }
  end

  describe "GET sitemap" do
    before{ get :sitemap, {locale: :pt} }
    it{ should be_success }
  end

  describe 'GET thank_you' do
    let(:backer) { FactoryGirl.create(:backer) }

    context 'with a session with backer' do
      before do
        request.session[:thank_you_backer_id] = backer.id
        get :thank_you, { locale: :pt }
      end

      it{ should redirect_to(project_backer_path(backer.project, backer)) }
    end

    context 'without session' do
      it{ lambda { get :thank_you, { locale: :pt } }.should raise_exception(ActiveRecord::RecordNotFound)}
    end
  end
end


text:
(function(Utils, API) {
  'use strict';

  /**
   * @namespace API
   * @memberof OSjs
   */

  /*@
   * Please note that there are some more methods defined in `process.js`
   */

  var DefaultLocale = 'en_EN';
  var CurrentLocale = 'en_EN';

  var _MENU;              // Current open 'OSjs.GUI.Menu'
  var _CLIPBOARD;         // Current 'clipboard' data

  var _hooks = {
    'onInitialize':          [],
    'onInited':              [],
    'onWMInited':            [],
    'onSessionLoaded':       [],
    'onShutdown':            [],
    'onApplicationPreload':  [],
    'onApplicationLaunch':   [],
    'onApplicationLaunched': [],
    'onBlurMenu':            []
  };

  /////////////////////////////////////////////////////////////////////////////
  // SERVICERING
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Service Notification Icon Class
   *
   * This is a private class and can only be retrieved through
   * OSjs.API.getServiceNotificationIcon()
   */
  function ServiceNotificationIcon() {
    this.entries = {};
    this.size = 0;
    this.notif = null;

    this.init();
  }

  ServiceNotificationIcon.prototype.init = function() {
    var wm = OSjs.Core.getWindowManager();
    var self = this;

    function show(ev) {
      self.displayMenu(ev);
      return false;
    }

    if ( wm ) {
      this.notif = wm.createNotificationIcon('ServiceNotificationIcon', {
        image: OSjs.API.getIcon('status/gtk-dialog-authentication.png'),
        onContextMenu: show,
        onClick: show,
        onInited: function(el, img) {
          self._updateIcon();
        }
      });

      this._updateIcon();
    }
  };

  /**
   * Destroys the notification icon
   */
  ServiceNotificationIcon.prototype.destroy = function() {
    var wm = OSjs.Core.getWindowManager();
    if ( wm ) {
      wm.removeNotificationIcon('ServiceNotificationIcon');
    }

    this.size = 0;
    this.entries = {};
    this.notif = null;
  };

  ServiceNotificationIcon.prototype._updateIcon = function() {
    if ( this.notif ) {
      if ( this.notif.$container ) {
        this.notif.$container.style.display = this.size ? 'inline-block' : 'none';
      }
      this.notif.setTitle(OSjs.API._('SERVICENOTIFICATION_TOOLTIP', this.size.toString()));
    }
  };

  /**
   * Show the menu
   *
   * @param   DOMEvent      ev      Event
   */
  ServiceNotificationIcon.prototype.displayMenu = function(ev) {
    var menu = [];
    var entries = this.entries;

    Object.keys(entries).forEach(function(name) {
      menu.push({
        title: name,
        menu: entries[name]
      });
    });

    OSjs.API.createMenu(menu, ev);
  };

  /**
   * Adds an entry
   */
  ServiceNotificationIcon.prototype.add = function(name, menu) {
    if ( !this.entries[name] ) {
      this.entries[name] = menu;

      this.size++;
      this._updateIcon();
    }
  };

  /**
   * Removes an entry
   */
  ServiceNotificationIcon.prototype.remove = function(name) {
    if ( this.entries[name] ) {
      delete this.entries[name];
      this.size--;
      this._updateIcon();
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // LOCALE API METHODS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Translate given string
   *
   * @function _
   * @memberof OSjs.API
   *
   * @param  {String}       s       Translation key/string
   * @param  {...String}    sargs   Format values
   *
   * @return {String}
   */
  API._ = function _apiTranslate() {
    var s = arguments[0];
    var a = arguments;

    if ( OSjs.Locales[CurrentLocale][s] ) {
      a[0] = OSjs.Locales[CurrentLocale][s];
    } else {
      a[0] = OSjs.Locales[DefaultLocale][s] || s;
    }

    return a.length > 1 ? Utils.format.apply(null, a) : a[0];
  };

  /**
   * Same as _ only you can supply the list as first argument
   *
   * @function __
   * @memberof OSjs.API
   * @see OSjs.API._
   */
  API.__ = function _apiTranslateList() {
    var l = arguments[0];
    var s = arguments[1];
    var a = Array.prototype.slice.call(arguments, 1);

    if ( l[CurrentLocale] && l[CurrentLocale][s] ) {
      a[0] = l[CurrentLocale][s];
    } else {
      a[0] = l[DefaultLocale] ? (l[DefaultLocale][s] || s) : s;
      if ( a[0] && a[0] === s ) {
        a[0] = API._.apply(null, a);
      }
    }

    return a.length > 1 ? Utils.format.apply(null, a) : a[0];
  };

  /**
   * Get current locale
   *
   * @function getLocale
   * @memberof OSjs.API
   *
   * @return {String}
   */
  API.getLocale = function _apiGetLocale() {
    return CurrentLocale;
  };

  /**
   * Set locale
   *
   * @function setLocale
   * @memberof OSjs.API
   *
   * @param  {String}   s     Locale name
   */
  API.setLocale = function _apiSetLocale(l) {
    var RTL = API.getConfig('LocaleOptions.RTL', []);

    if ( OSjs.Locales[l] ) {
      CurrentLocale = l;
    } else {
      console.warn('API::setLocale()', 'Invalid locale', l, '(Using default)');
      CurrentLocale = DefaultLocale;
    }

    var major = CurrentLocale.split('_')[0];
    var html = document.querySelector('html');
    if ( html ) {
      html.setAttribute('lang', l);
      html.setAttribute('dir', RTL.indexOf(major) !== -1 ? 'rtl' : 'ltr');
    }

    console.info('API::setLocale()', CurrentLocale);
  };

  /////////////////////////////////////////////////////////////////////////////
  // REQUEST API METHODS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Perform cURL call
   *
   * The response is in form of: {httpCode, body}
   *
   * @function curl
   * @memberof OSjs.API
   *
   * @param   {Object}    args      cURL Arguments (see docs)
   * @param   {Function}  callback  Callback function => fn(error, response)
   *
   * @link https://os.js.org/doc/tutorials/using-curl.html
   * @link https://os.js.org/doc/server/srcservernodenode_modulesosjsapijs.html#api-curl
   */
  API.curl = function _apiCurl(args, callback) {
    args = args || {};
    callback = callback || {};

    var opts = args.body;
    if ( typeof opts === 'object' ) {
      console.warn('DEPRECATION WARNING', 'The \'body\' wrapper is no longer needed');
    } else {
      opts = args;
    }

    API.call('curl', opts, callback, args.options);
  };

  /**
   * Global function for calling API (backend)
   *
   * You can call VFS functions by prefixing your method name with "FS:"
   *
   * @function call
   * @memberof OSjs.API
   * @see OSjs.Core.Handler#callAPI
   * @see OSjs.Utils.ajax
   * @throws {Error} On invalid arguments
   *
   * @param   {String}    m         Method name
   * @param   {Object}    a         Method arguments
   * @param   {Function}  cb        Callback on success => fn(err, res)
   * @param   {Object}    [options] Options to send to the XHR request
   */
  var _CALL_INDEX = 1;
  API.call = function _apiCall(m, a, cb, options) {
    a = a || {};

    var lname = 'APICall_' + _CALL_INDEX;

    if ( typeof a.__loading === 'undefined' || a.__loading === true ) {
      API.createLoading(lname, {className: 'BusyNotification', tooltip: 'API Call'});
    }

    if ( typeof cb !== 'function' ) {
      throw new TypeError('call() expects a function as callback');
    }

    if ( options && typeof options !== 'object' ) {
      throw new TypeError('call() expects an object as options');
    }

    _CALL_INDEX++;

    var handler = OSjs.Core.getHandler();
    return handler.callAPI(m, a, function(response) {
      API.destroyLoading(lname);
      response = response || {};
      cb(response.error || false, response.result);
    }, function(err) {
      cb(err);
    }, options);
  };

  /////////////////////////////////////////////////////////////////////////////
  // PROCESS API METHODS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Open a file
   *
   * @function open
   * @memberof OSjs.API
   * @see OSjs.API.launch
   * @throws {Error} On invalid arguments
   *
   * @param   {OSjs.VFS.File}   file          The File reference (can also be a tuple with 'path' and 'mime')
   * @param   {Object}          launchArgs    Arguments to send to process launch function
   */
  API.open = function _apiOpen(file, launchArgs) {
    launchArgs = launchArgs || {};

    if ( !file.path ) {
      throw new Error('Cannot API::open() without a path');
    }

    var settingsManager = OSjs.Core.getSettingsManager();
    var wm = OSjs.Core.getWindowManager();
    var handler = OSjs.Core.getHandler();
    var args = {file: file};

    function getApplicationNameByFile(file, forceList, callback) {
      if ( !(file instanceof OSjs.VFS.File) ) {
        throw new Error('This function excepts a OSjs.VFS.File object');
      }

      var pacman = OSjs.Core.getPackageManager();
      var val = settingsManager.get('DefaultApplication', file.mime);

      console.debug('getApplicationNameByFile()', 'default application', val);
      if ( !forceList && val ) {
        if ( pacman.getPackage(val) ) {
          callback([val]);
          return;
        }
      }
      callback(pacman.getPackagesByMime(file.mime));
    }

    function setDefaultApplication(mime, app, callback) {
      callback = callback || function() {};
      console.debug('setDefaultApplication()', mime, app);
      settingsManager.set('DefaultApplication', mime, app);
      settingsManager.save('DefaultApplication', callback);
    }

    function _launch(name) {
      if ( name ) {
        OSjs.API.launch(name, args, launchArgs.onFinished, launchArgs.onError, launchArgs.onConstructed);
      }
    }

    function _launchApp(name, ar) {
      console.groupEnd();
      API.launch(name, ar);
    }

    function _onDone(app) {
      console.debug('Found', app.length, 'applications supporting this mime');
      console.groupEnd();
      if ( app.length ) {

        if ( app.length === 1 ) {
          _launch(app[0]);
        } else {
          if ( wm ) {
            OSjs.API.createDialog('ApplicationChooser', {
              file: file,
              list: app
            }, function(ev, btn, result) {
              if ( btn !== 'ok' ) {
                return;
              }

              _launch(result.name);

              setDefaultApplication(file.mime, result.useDefault ? result.name : null);
            });
          } else {
            OSjs.API.error(OSjs.API._('ERR_FILE_OPEN'),
                           OSjs.API._('ERR_FILE_OPEN_FMT', file.path),
                           OSjs.API._('ERR_NO_WM_RUNNING') );
          }
        }
      } else {
        OSjs.API.error(OSjs.API._('ERR_FILE_OPEN'),
                       OSjs.API._('ERR_FILE_OPEN_FMT', file.path),
                       OSjs.API._('ERR_APP_MIME_NOT_FOUND_FMT', file.mime) );
      }
    }

    console.group('API::open()', file);

    if ( file.mime === 'osjs/application' ) {
      _launchApp(Utils.filename(file.path), launchArgs);
    } else if ( file.type === 'dir' ) {
      var fm = settingsManager.instance('DefaultApplication').get('dir', 'ApplicationFileManager');
      _launchApp(fm, {path: file.path});
    } else {
      if ( launchArgs.args ) {
        Object.keys(launchArgs.args).forEach(function(i) {
          args[i] = launchArgs.args[i];
        });
      }

      getApplicationNameByFile(file, launchArgs.forceList, _onDone);
    }
  };

  /**
   * Restarts all processes with the given name
   *
   * This also reloads any metadata preload items defined in the application.
   *
   * @function relaunch
   * @memberof OSjs.API
   *
   * @param   {String}      n               Application Name
   */
  API.relaunch = function _apiRelaunch(n) {
    function relaunch(p) {
      var data = null;
      var args = {};
      if ( p instanceof OSjs.Core.Application ) {
        data = p._getSessionData();
      }

      try {
        p.destroy(); // kill
      } catch ( e ) {
        console.warn('OSjs.API.relaunch()', e.stack, e);
      }

      if ( data !== null ) {
        args = data.args;
        args.__resume__ = true;
        args.__windows__ = data.windows || [];
      }

      args.__preload__ = {force: true};

      //setTimeout with 500 ms is used to allow applications that might need
      //  some time to destroy resources before it can be relaunched.
      setTimeout(function() {
        OSjs.API.launch(n, args);
      }, 500);
    }

    OSjs.API.getProcess(n).forEach(relaunch);
  };

  /**
   * Launch a Process
   *
   * @function launch
   * @memberof OSjs.API
   *
   * @param   {String}      name          Application Name
   * @param   {Object}      [args]          Launch arguments
   * @param   {Function}    [ondone]        Callback on success
   * @param   {Function}    [onerror]       Callback on error
   * @param   {Function}    [onconstruct]   Callback on application init
   *
   * @return  {Boolean}
   */
  API.launch = function _apiLaunch(name, args, ondone, onerror, onconstruct) {
    args = args || {};

    var err;

    var splash = null;
    var instance = null;
    var pargs = {};

    var handler = OSjs.Core.getHandler();
    var packman = OSjs.Core.getPackageManager();
    var compability = Utils.getCompability();
    var metadata = packman.getPackage(name);
    var running = OSjs.API.getProcess(name, true);

    var preloads = (function() {
      var list = (metadata.preload || []).slice(0);
      var additions = [];

      function _add(chk) {
        if ( chk && chk.preload ) {
          chk.preload.forEach(function(p) {
            additions.push(p);
          });
        }
      }

      // If this package depends on another package, make sure
      // to load the resources for the related one as well
      if ( metadata.depends instanceof Array ) {
        metadata.depends.forEach(function(k) {
          if ( !OSjs.Applications[k] ) {
            console.info('Using dependency', k);
            _add(packman.getPackage(k));
          }
        });
      }

      // ... same goes for packages that uses this package
      // as a dependency.
      var pkgs = packman.getPackages(false);
      Object.keys(pkgs).forEach(function(pn) {
        var p = pkgs[pn];
        if ( p.type === 'extension' && p.uses === name ) {
          console.info('Using extension', pn);
          _add(p);
        }
      });

      list = additions.concat(list);
      additions = [];

      // For user packages, make sure to load the correct URL
      if ( metadata.scope === 'user' ) {
        list = list.map(function(p) {
          if ( p.src.substr(0, 1) !== '/' && !p.src.match(/^(https?|ftp)/) ) {
            OSjs.VFS.url(p.src, function(error, url) {
              if ( !error ) {
                p.src = url;
              }
            });
          }

          return p;
        });
      }

      return list;
    })();

    function _createSplash() {
      API.createLoading(name, {className: 'StartupNotification', tooltip: 'Starting ' + name});
      if ( !OSjs.Applications[name] ) {
        if ( metadata.splash !== false ) {
          splash = OSjs.API.createSplash(metadata.name, metadata.icon);
        }
      }
    }

    function _destroySplash() {
      API.destroyLoading(name);
      if ( splash ) {
        splash.destroy();
        splash = null;
      }
    }

    function _onError(err, exception) {
      _destroySplash();

      OSjs.API.error(OSjs.API._('ERR_APP_LAUNCH_FAILED'),
                  OSjs.API._('ERR_APP_LAUNCH_FAILED_FMT', name),
                  err, exception, true);

      console.groupEnd();

      (onerror || function() {})(err, name, args, exception);
    }

    function _onFinished(skip) {
      _destroySplash();

      console.groupEnd();

      (ondone || function() {})(instance, metadata);
    }

    function _preLaunch(cb) {
      var isCompatible = (function() {
        var list = (metadata.compability || []).filter(function(c) {
          if ( typeof compability[c] !== 'undefined' ) {
            return !compability[c];
          }
          return false;
        });

        if ( list.length ) {
          return OSjs.API._('ERR_APP_LAUNCH_COMPABILITY_FAILED_FMT', name, list.join(', '));
        }
        return true;
      })();

      if ( isCompatible !== true ) {
        throw new Error(isCompatible);
      }

      if ( metadata.singular === true && running ) {
        if ( running instanceof OSjs.Core.Application ) {
          // In this case we do not trigger an error. Applications simply get a signal for attention
          console.warn('API::launch()', 'detected that this application is a singular and already running...');
          running._onMessage('attention', args);
          _onFinished(true);
          return; // muy importante!
        } else {
          throw new Error(OSjs.API._('ERR_APP_LAUNCH_ALREADY_RUNNING_FMT', name));
        }
      }

      Utils.asyncs(_hooks.onApplicationPreload, function(qi, i, n) {
        qi(name, args, preloads, function(p) {
          if ( p && (p instanceof Array) ) {
            preloads = p;
          }
          n();
        });
      }, function() {
        _createSplash();
        cb();
      });

      API.triggerHook('onApplicationLaunch', [name, args]);
    }

    function _preload(cb) {
      Utils.preload(preloads, function(total, failed) {
        if ( failed.length ) {
          cb(OSjs.API._('ERR_APP_PRELOAD_FAILED_FMT', name, failed.join(',')));
        } else {
          setTimeout(function() {
            cb(false);
          }, 0);
        }
      }, function(progress, count) {
        if ( splash ) {
          splash.update(progress, count);
        }
      }, pargs);
    }

    function _createProcess(cb) {
      function __onprocessinitfailed() {
        if ( instance ) {
          try {
            instance.destroy();
            instance = null;
          } catch ( ee ) {
            console.warn('Something awful happened when trying to clean up failed launch Oo', ee);
            console.warn(ee.stack);
          }
        }
      }

      if ( typeof OSjs.Applications[name] === 'undefined' ) {
        throw new Error(OSjs.API._('ERR_APP_RESOURCES_MISSING_FMT', name));
      }

      if ( typeof OSjs.Applications[name] === 'function' ) {
        OSjs.Applications[name]();
        cb(false, true);
        return;
      }

      try {
        instance = new OSjs.Applications[name].Class(args, metadata);

        (onconstruct || function() {})(instance, metadata);
      } catch ( e ) {
        console.warn('Error on constructing application', e, e.stack);
        __onprocessinitfailed();
        cb(OSjs.API._('ERR_APP_CONSTRUCT_FAILED_FMT', name, e), e);
        return;
      }

      try {
        var settings = OSjs.Core.getSettingsManager().get(instance.__pname) || {};
        instance.init(settings, metadata, function() {}); // NOTE: Empty function is for backward-compability

        API.triggerHook('onApplicationLaunched', [{
          application: instance,
          name: name,
          args: args,
          settings: settings,
          metadata: metadata
        }]);
      } catch ( ex ) {
        console.warn('Error on init() application', ex, ex.stack);
        __onprocessinitfailed();
        cb(OSjs.API._('ERR_APP_INIT_FAILED_FMT', name, ex.toString()), ex);
        return;
      }

      cb(false, true);
    }

    if ( !name ) {
      err = 'Cannot API::launch() witout a application name';
      _onError(err);
      throw new Error(err);
    }

    if ( !metadata ) {
      err = OSjs.API._('ERR_APP_LAUNCH_MANIFEST_FAILED_FMT', name);
      _onError(err);
      throw new Error(err);
    }

    console.group('API::launch()', {
      name: name,
      args: args,
      metadata: metadata,
      preloads: preloads
    });

    if ( args.__preload__ ) { // This is for relaunch()
      pargs = args.__preload__;
      delete args.__preload__;
    }

    // Main blob
    try {
      _preLaunch(function() {
        _preload(function(err, res) {
          if ( err ) {
            _onError(err, res);
          } else {
            try {
              _createProcess(function(err, res) {
                if ( err ) {
                  _onError(err, res);
                } else {
                  try {
                    _onFinished(res);
                  } catch ( e ) {
                    _onError(e.toString(), e);
                  }
                }
              });
            } catch ( e ) {
              _onError(e.toString(), e);
            }
          }
        });
      });
    } catch ( e ) {
      _onError(e.toString());
    }
  };

  /**
   * Launch Processes from a List
   *
   * @function launchList
   * @memberof OSjs.API
   * @see OSjs.API.launch
   *
   * @param   {Array}         list        List of launch application arguments
   * @param   {Function}      onSuccess   Callback on success => fn(app, metadata, appName, appArgs)
   * @param   {Function}      onError     Callback on error => fn(error, appName, appArgs)
   * @param   {Function}      onFinished  Callback on finished running => fn()
   */
  API.launchList = function _apiLaunchList(list, onSuccess, onError, onFinished) {
    list        = list        || []; /* idx => {name: 'string', args: 'object', data: 'mixed, optional'} */
    onSuccess   = onSuccess   || function() {};
    onError     = onError     || function() {};
    onFinished  = onFinished  || function() {};

    Utils.asyncs(list, function(s, current, next) {
      if ( typeof s === 'string' ) {
        var args = {};
        var spl = s.split('@');
        var name = spl[0];
        if ( typeof spl[1] !== 'undefined' ) {
          try {
            args = JSON.parse(spl[1]);
          } catch ( e ) {}
        }

        s = {
          name: name,
          args: args
        };
      }

      var aname = s.name;
      var aargs = (typeof s.args === 'undefined') ? {} : (s.args || {});

      if ( !aname ) {
        console.warn('API::launchList() next()', 'No application name defined');
        next();
        return;
      }

      OSjs.API.launch(aname, aargs, function(app, metadata) {
        onSuccess(app, metadata, aname, aargs);
        next();
      }, function(err, name, args) {
        console.warn('API::launchList() _onError()', err);
        onError(err, name, args);
        next();
      });
    }, onFinished);
  };

  /////////////////////////////////////////////////////////////////////////////
  // RESOURCE API METHODS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Get a resource from application
   *
   * @function getApplicationResource
   * @memberof OSjs.API
   *
   * @param   {OSjs.Core.Process}   app     Application instance reference. You can also specify a name by String
   * @param   {String}              name    Resource Name
   * @param   {Boolean}             vfspath Return a valid VFS path
   *
   * @return  {String}            The absolute URL of resource
   */
  API.getApplicationResource = function _apiGetAppResource(app, name, vfspath) {
    if ( name.match(/^\//) ) {
      return name;
    }
    name = name.replace(/^\.\//, '');

    function getName() {
      var appname = null;
      if ( app instanceof OSjs.Core.Process ) {
        if ( app.__path ) {
          appname = app.__path;
        }
      } else if ( typeof app === 'string' ) {
        appname = app;

        var pacman = OSjs.Core.getPackageManager();
        var packs = pacman ? pacman.getPackages() : {};
        if ( packs[appname] ) {
          appname = packs[appname].path;
        }
      }
      return appname;
    }

    function getResultPath(path, userpkg) {
      path = Utils.checkdir(path);

      if ( vfspath ) {
        if ( userpkg ) {
          path = path.substr(OSjs.API.getConfig('Connection.FSURI').length);
        } else {
          path = 'osjs:///' + path;
        }
      }

      return path;
    }

    function getResourcePath() {
      var appname = getName();
      var path = '';

      var root, sub;
      if ( appname ) {
        if ( appname.match(/^(.*)\/(.*)$/) ) {
          root = OSjs.API.getConfig('Connection.PackageURI');
          path = root + '/' + appname + '/' + name;
        } else {
          root = OSjs.API.getConfig('Connection.FSURI');
          sub = OSjs.API.getConfig('PackageManager.UserPackages');
          path = root + '/get/' + Utils.pathJoin(sub, appname, name);
        }
      }

      return getResultPath(path, !!sub);
    }

    return getResourcePath();
  };

  /**
   * Get path to css theme
   *
   * @function getThemeCSS
   * @memberof OSjs.API
   *
   * @param   {String}    name    CSS Stylesheet name (without extension)
   *
   * @return  {String}            The absolute URL of css file
   */
  API.getThemeCSS = function _apiGetThemeCSS(name) {
    var root = OSjs.API.getConfig('Connection.RootURI', '/');
    if ( name === null ) {
      return root + 'blank.css';
    }

    root = OSjs.API.getConfig('Connection.ThemeURI');
    return Utils.checkdir(root + '/' + name + '.css');
  };

  /**
   * Get a icon based in file and mime
   *
   * @function getFileIcon
   * @memberof OSjs.API
   *
   * @param   {File}      file            File Data (see supported types)
   * @param   {String}    [size=16x16]    Icon size
   * @param   {String}    [icon]          Default icon
   *
   * @return  {String}            The absolute URL to the icon
   */
  API.getFileIcon = function _apiGetFileIcon(file, size, icon) {
    icon = icon || 'mimetypes/gnome-fs-regular.png';

    if ( typeof file === 'object' && !(file instanceof OSjs.VFS.File) ) {
      file = new OSjs.VFS.File(file);
    }

    if ( !file.filename ) {
      throw new Error('Filename is required for getFileIcon()');
    }

    var map = [
      {match: 'application/pdf', icon: 'mimetypes/gnome-mime-application-pdf.png'},
      {match: 'application/zip', icon: 'mimetypes/folder_tar.png'},
      {match: 'application/x-python', icon: 'mimetypes/stock_script.png'},
      {match: 'application/x-lua', icon: 'mimetypes/stock_script.png'},
      {match: 'application/javascript', icon: 'mimetypes/stock_script.png'},
      {match: 'text/html', icon: 'mimetypes/stock_script.png'},
      {match: 'text/xml', icon: 'mimetypes/stock_script.png'},
      {match: 'text/css', icon: 'mimetypes/stock_script.png'},

      {match: 'osjs/document', icon: 'mimetypes/gnome-mime-application-msword.png'},
      {match: 'osjs/draw', icon: 'mimetypes/image.png'},

      {match: /^text\//, icon: 'mimetypes/txt.png'},
      {match: /^audio\//, icon: 'mimetypes/sound.png'},
      {match: /^video\//, icon: 'mimetypes/video.png'},
      {match: /^image\//, icon: 'mimetypes/image.png'},
      {match: /^application\//, icon: 'mimetypes/binary.png'}
    ];

    if ( file.type === 'dir' ) {
      icon = 'places/folder.png';
    } else if ( file.type === 'trash' ) {
      icon = 'places/user-trash.png';
    } else {
      var mime = file.mime || 'application/octet-stream';

      map.every(function(iter) {
        var match = false;
        if ( typeof iter.match === 'string' ) {
          match = (mime === iter.match);
        } else {
          match = mime.match(iter.match);
        }

        if ( match ) {
          icon = iter.icon;
          return false;
        }

        return true;
      });
    }

    return OSjs.API.getIcon(icon, size);
  };

  /**
   * Default method for getting a resource from current theme
   *
   * @function getThemeResource
   * @memberof OSjs.API
   *
   * @param   {String}    name    Resource filename
   * @param   {String}    type    Type ('base' or a sub-folder)
   *
   * @return  {String}            The absolute URL to the resource
   */
  API.getThemeResource = function _apiGetThemeResource(name, type) {
    name = name || null;
    type = type || null;

    var root = OSjs.API.getConfig('Connection.ThemeURI');
    if ( !root.match(/^\//) ) {
      root = window.location.pathname + root;
    }

    function getName(str, theme) {
      if ( !str.match(/^\//) ) {
        if ( type === 'base' || type === null ) {
          str = root + '/' + theme + '/' + str;
        } else {
          str = root + '/' + theme + '/' + type + '/' + str;
        }
      }
      return str;
    }

    if ( name ) {
      var wm = OSjs.Core.getWindowManager();
      var theme = (wm ? wm.getSetting('theme') : 'default') || 'default';
      name = getName(name, theme);
    }

    return Utils.checkdir(name);
  };

  /**
   * Default method for getting a sound from theme
   *
   * @function getSound
   * @memberof OSjs.API
   *
   * @param   {String}    name    Resource filename
   *
   * @return  {String}            The absolute URL to the resource
   */
  API.getSound = function _apiGetSound(name) {
    name = name || null;
    if ( name ) {
      var wm = OSjs.Core.getWindowManager();
      var theme = wm ? wm.getSoundTheme() : 'default';
      var root = OSjs.API.getConfig('Connection.SoundURI');
      var compability = Utils.getCompability();
      if ( !name.match(/^\//) ) {
        var ext = 'oga';
        if ( !compability.audioTypes.ogg ) {
          ext = 'mp3';
        }
        name = root + '/' + theme + '/' + name + '.' + ext;
      }
    }
    return Utils.checkdir(name);
  };

  /**
   * Default method for getting a icon from theme
   *
   * @function getIcon
   * @memberof OSjs.API
   *
   * @param   {String}              name          Resource filename
   * @param   {String}              [size=16x16]  Icon size
   * @param   {OSjs.Core.Process}   [app]         Application instance reference. Can also be String. For `name` starting with './'
   *
   * @return  {String}            The absolute URL to the resource
   */
  API.getIcon = function _apiGetIcon(name, size, app) {
    name = name || null;
    size = size || '16x16';
    app  = app  || null;

    var root = OSjs.API.getConfig('Connection.IconURI');
    var wm = OSjs.Core.getWindowManager();
    var theme = wm ? wm.getIconTheme() : 'default';

    function checkIcon() {
      if ( name.match(/^\.\//) ) {
        name = name.replace(/^\.\//, '');
        if ( (app instanceof OSjs.Core.Application) || (typeof app === 'string') ) {
          return OSjs.API.getApplicationResource(app, name);
        } else {
          if ( app !== null && typeof app === 'object' ) {
            return OSjs.API.getApplicationResource(app.path, name);
          }
        }
      } else {
        if ( !name.match(/^\//) ) {
          name = root + '/' + theme + '/' + size + '/' + name;
        }
      }
      return null;
    }

    if ( name && !name.match(/^(http|\/\/)/) ) {
      var chk = checkIcon();
      if ( chk !== null ) {
        return chk;
      }
    }

    return Utils.checkdir(name);
  };

  /**
   * Method for getting a config parameter by path (Ex: "VFS.Mountpoints.shared.enabled")
   *
   * @function getConfig
   * @memberof OSjs.API
   * @see OSjs.Core.getConfig
   *
   * @param   {String}    [path]                        Path
   * @param   {Mixed}     [defaultValue=undefined]      Use default value
   *
   * @return  {Mixed}             Parameter value or entire tree on no path
   */
  API.getConfig = function _apiGetConfig(path, defaultValue) {
    var config = Utils.cloneObject(OSjs.Core.getConfig());
    if ( typeof path === 'string' ) {
      var result = window.undefined;
      var queue = path.split(/\./);
      var ns = config;

      queue.forEach(function(k, i) {
        if ( i >= queue.length - 1 ) {
          if ( ns ) {
            result = ns[k];
          }
        } else {
          ns = ns[k];
        }
      });

      if ( typeof result === 'undefined' && typeof defaultValue !== 'undefined' ) {
        return defaultValue;
      }

      return result;
    }
    return config;
  };

  /**
   * Get default configured path
   *
   * @function getDefaultPath
   * @memberof OSjs.API
   *
   * @param   {String}    fallback      Fallback path on error (default= "osjs:///")
   * @return  {String}
   */
  API.getDefaultPath = function _apiGetDefaultPath(fallback) {
    if ( fallback && fallback.match(/^\//) ) {
      fallback = null;
    }
    return OSjs.API.getConfig('VFS.Home') || fallback || 'osjs:///';
  };

  /////////////////////////////////////////////////////////////////////////////
  // GUI API METHODS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Create a new Desktop Notification
   *
   * @function createNotification
   * @memberof OSjs.API
   * @see OSjs.Core.WindowManager#notification
   */
  API.createNotification = function _apiCreateNotification(opts) {
    var wm = OSjs.Core.getWindowManager();
    return wm.notification(opts);
  };

  /**
   * Create a new dialog
   *
   * You can also pass a function as `className` to return an instance of your own class
   *
   * @function createDialog
   * @memberof OSjs.API
   *
   * @param   {String}        className       Dialog Namespace Class Name
   * @param   {Object}        args            Arguments you want to send to dialog
   * @param   {Function}      callback        Callback on dialog action (close/ok etc) => fn(ev, button, result)
   * @param   {Mixed}         [parentObj]     A window or app (to make it a child window)
   *
   * @return  {OSjs.Core.Window}
   */
  API.createDialog = function _apiCreateDialog(className, args, callback, parentObj) {
    callback = callback || function() {};

    function cb() {
      if ( parentObj ) {
        if ( (parentObj instanceof OSjs.Core.Window) && parentObj._destroyed ) {
          console.warn('API::createDialog()', 'INGORED EVENT: Window was destroyed');
          return;
        }
        if ( (parentObj instanceof OSjs.Core.Process) && parentObj.__destroyed ) {
          console.warn('API::createDialog()', 'INGORED EVENT: Process was destroyed');
          return;
        }
      }

      callback.apply(null, arguments);
    }

    var win = typeof className === 'string' ? new OSjs.Dialogs[className](args, cb) : className(args, cb);

    if ( !parentObj ) {
      var wm = OSjs.Core.getWindowManager();
      wm.addWindow(win, true);
    } else if ( parentObj instanceof OSjs.Core.Window ) {
      win._on('destroy', function() {
        if ( parentObj ) {
          parentObj._focus();
        }
      });
      parentObj._addChild(win, true);
    } else if ( parentObj instanceof OSjs.Core.Application ) {
      parentObj._addWindow(win);
    }

    setTimeout(function() {
      win._focus();
    }, 10);

    return win;
  };

  /**
   * Create (or show) loading indicator
   *
   * @function createLoading
   * @memberof OSjs.API
   *
   * @param   {String}    name          Name of notification (unique)
   * @param   {Object}    opts          Options
   * @param   {Number}    [panelId]     Panel ID
   *
   * @return  {String}                Or false on error
   */
  API.createLoading = function _apiCreateLoading(name, opts, panelId) {
    var wm = OSjs.Core.getWindowManager();
    if ( wm ) {
      if ( wm.createNotificationIcon(name, opts, panelId) ) {
        return name;
      }
    }
    return false;
  };

  /**
   * Destroy (or hide) loading indicator
   *
   * @function destroyLoading
   * @memberof OSjs.API
   *
   * @param   {String}    name          Name of notification (unique)
   * @param   {Number}    [panelId]     Panel ID
   *
   * @return  {Boolean}
   */
  API.destroyLoading = function _apiDestroyLoading(name, panelId) {
    var wm = OSjs.Core.getWindowManager();
    if ( name ) {
      if ( wm ) {
        if ( wm.removeNotificationIcon(name, panelId) ) {
          return true;
        }
      }
    }
    return false;
  };

  /**
   * Checks the given permission (groups) against logged in user
   *
   * @function checkPermission
   * @memberof OSjs.API
   *
   * @param   {Mixed}     group         Either a string or array of groups
   */
  API.checkPermission = function _apiCheckPermission(group) {
    var user = OSjs.Core.getHandler().getUserData();
    var userGroups = user.groups || [];

    if ( !(group instanceof Array) ) {
      group = [group];
    }

    var result = true;
    if ( userGroups.indexOf('admin') < 0 ) {
      group.every(function(g) {
        if ( userGroups.indexOf(g) < 0 ) {
          result = false;
        }
        return result;
      });
    }
    return result;
  };

  /**
   * Checks the given permission (groups) against logged in user
   *
   * Returns an object with the methods `update(precentage)` and `destroy()`
   *
   * @function createSplash
   * @memberof OSjs.API
   *
   * @param   {String}      name              The name to display
   * @param   {String}      icon              The icon to display
   * @param   {String}      [label=Starting]  The label
   * @param   {Node}        [parentEl]        The parent element
   *
   * @return  {Object}
   */
  API.createSplash = function _apiCreateSplash(name, icon, label, parentEl) {
    label = label || 'Starting';
    parentEl = parentEl || document.body;

    var splash = document.createElement('application-splash');
    splash.setAttribute('role', 'dialog');

    var img;
    if ( icon ) {
      img = document.createElement('img');
      img.alt = name;
      img.src = OSjs.API.getIcon(icon);
    }

    var titleText = document.createElement('b');
    titleText.appendChild(document.createTextNode(name));

    var title = document.createElement('span');
    title.appendChild(document.createTextNode(label + ' '));
    title.appendChild(titleText);
    title.appendChild(document.createTextNode('...'));

    var splashBar = document.createElement('gui-progress-bar');
    OSjs.GUI.Elements['gui-progress-bar'].build(splashBar);

    if ( img ) {
      splash.appendChild(img);
    }
    splash.appendChild(title);
    splash.appendChild(splashBar);

    parentEl.appendChild(splash);

    return {
      destroy: function() {
        splash = Utils.$remove(splash);

        img = null;
        title = null;
        titleText = null;
        splashBar = null;
      },

      update: function(p, c) {
        if ( !splash || !splashBar ) {
          return;
        }

        var per = c ? 0 : 100;
        if ( c ) {
          per = (p / c) * 100;
        }
        (new OSjs.GUI.Element(splashBar)).set('value', per);
      }
    };
  };

  /////////////////////////////////////////////////////////////////////////////
  // MISC API METHODS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Global function for showing an error dialog
   *
   * @function error
   * @memberof OSjs.API
   *
   * @param   {String}    title               Dialog title
   * @param   {String}    message             Dialog message
   * @param   {String}    error               Error message
   * @param   {Object}    [exception]         Exception reference
   * @param   {Boolean}   [bugreport=false]   Enable bugreporting for this error
   */
  API.error = function _apiError(title, message, error, exception, bugreport) {
    bugreport = (function() {
      if ( OSjs.API.getConfig('BugReporting') ) {
        return typeof bugreport === 'undefined' ? false : (bugreport ? true : false);
      }
      return false;
    })();

    function _dialog() {
      var wm = OSjs.Core.getWindowManager();
      if ( wm && wm._fullyLoaded ) {
        try {
          OSjs.API.createDialog('Error', {
            title: title,
            message: message,
            error: error,
            exception: exception,
            bugreport: bugreport
          });

          return true;
        } catch ( e ) {
          console.warn('An error occured while creating Dialogs.Error', e);
          console.warn('stack', e.stack);
        }
      }

      return false;
    }

    OSjs.API.blurMenu();

    if ( exception && (exception.message.match(/^Script Error/i) && String(exception.lineNumber).match(/^0/)) ) {
      console.error('VENDOR ERROR', {
        title: title,
        message: message,
        error: error,
        exception: exception
      });
      return;
    }

    if ( OSjs.API.getConfig('MOCHAMODE') ) {
      console.error(title, message, error, exception);
    } else {
      if ( _dialog() ) {
        return;
      }

      window.alert(title + '\n\n' + message + '\n\n' + error);
    }
  };

  /**
   * Global function for playing a sound
   *
   * @function playSound
   * @memberof OSjs.API
   *
   * @param   {String}      name      Sound name
   * @param   {Number}      volume    Sound volume (0.0 - 1.0)
   *
   * @return {Audio}
   */
  API.playSound = function _apiPlaySound(name, volume) {
    var compability = Utils.getCompability();
    if ( !compability.audio ) {
      console.debug('API::playSound()', 'Browser has no support for sounds!');
      return false;
    }

    var wm = OSjs.Core.getWindowManager();
    if ( wm && !wm.getSetting('enableSounds') ) {
      console.debug('API::playSound()', 'Window Manager has disabled sounds!');
      return false;
    }

    if ( typeof volume === 'undefined' ) {
      volume = 1.0;
    }

    var f = OSjs.API.getSound(name);
    console.debug('API::playSound()', name, f);
    var a = new Audio(f);
    a.volume = volume;
    a.play();
    return a;
  };

  /**
   * Set the "clipboard" data
   *
   * NOTE: This does not set the operating system clipboard (yet...)
   *
   * @function setClipboard
   * @memberof OSjs.API
   *
   * @param   {Mixed}       data      What data to set
   */
  API.setClipboard = function _apiSetClipboard(data) {
    console.debug('OSjs.API.setClipboard()', data);
    _CLIPBOARD = data;
  };

  /**
   * Get the "clipboard" data
   *
   * NOTE: This does not the operating system clipboard (yet...)
   *
   * @function getClipboard
   * @memberof OSjs.API
   *
   * @return  {Mixed}
   */
  API.getClipboard = function _apiGetClipboard() {
    return _CLIPBOARD;
  };

  /**
   * Returns an instance of ServiceNotificationIcon
   *
   * This is the icon in the panel where external connections
   * etc gets a menu entry.
   *
   * @function getServiceNotificationIcon
   * @memberof OSjs.API
   *
   * @return  {ServiceNotificationIcon}
   */
  API.getServiceNotificationIcon = (function() {
    var _instance;

    return function _apiGetServiceNotificationIcon() {
      if ( !_instance ) {
        _instance = new ServiceNotificationIcon();
      }
      return _instance;
    };
  })();

  /**
   * Toggles fullscreen of an element
   *
   * @function toggleFullscreen
   * @memberof OSjs.API
   *
   * @param {Node}      el    The DOM Node
   * @param {Boolean}   [t]   Toggle value (auto-detected)
   */
  API.toggleFullscreen = (function() {

    var _prev;

    function trigger(el, state) {
      function _request() {
        if ( el.requestFullscreen ) {
          el.requestFullscreen();
        } else if ( el.mozRequestFullScreen ) {
          el.mozRequestFullScreen();
        } else if ( el.webkitRequestFullScreen ) {
          el.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        }
      }

      function _restore() {
        if ( el.webkitCancelFullScreen ) {
          el.webkitCancelFullScreen();
        } else if ( el.mozCancelFullScreen ) {
          el.mozCancelFullScreen();
        } else if ( el.exitFullscreen ) {
          el.exitFullscreen();
        }
      }

      if ( el ) {
        if ( state ) {
          _request();
        } else {
          _restore();
        }
      }
    }

    return function _apiToggleFullscreen(el, t) {
      if ( typeof t === 'boolean' ) {
        trigger(el, t);
      } else {
        if ( _prev && _prev !== el ) {
          trigger(_prev, false);
        }

        trigger(el, _prev !== el);
      }

      _prev = el;
    };

  })();

  /////////////////////////////////////////////////////////////////////////////
  // MISC
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Signs the user out and shuts down OS.js
   *
   * @function signOut
   * @memberof OSjs.API
   */
  API.signOut = function _apiSignOut() {
    var handler = OSjs.Core.getHandler();
    var wm = OSjs.Core.getWindowManager();

    function signOut(save) {
      OSjs.API.playSound('service-logout');

      handler.logout(save, function() {
        OSjs.API.shutdown();
      });
    }

    if ( wm ) {
      var user = handler.getUserData() || {name: OSjs.API._('LBL_UNKNOWN')};
      OSjs.API.createDialog('Confirm', {
        title: OSjs.API._('DIALOG_LOGOUT_TITLE'),
        message: OSjs.API._('DIALOG_LOGOUT_MSG_FMT', user.name)
      }, function(ev, btn) {
        if ( btn === 'yes' ) {
          signOut(true);
        } else if ( btn === 'no' ) {
          signOut(false);
        }
      });
    } else {
      signOut(true);
    }
  };

  /**
   * Method for triggering a hook
   *
   * @function triggerHook
   * @memberof OSjs.API
   *
   * @param   {String}    name      Hook name
   * @param   {Array}     args      List of arguments
   * @param   {Object}    thisarg   'this' ref
   */
  API.triggerHook = function _apiTriggerHook(name, args, thisarg) {
    thisarg = thisarg || OSjs;
    args = args || [];

    if ( _hooks[name] ) {
      _hooks[name].forEach(function(hook) {
        if ( typeof hook === 'function' ) {
          try {
            hook.apply(thisarg, args);
          } catch ( e ) {
            console.warn('Error on Hook', e, e.stack);
          }
        } else {
          console.warn('No such Hook', name);
        }
      });
    }
  };

  /**
   * Method for adding a hook
   *
   * @function addHook
   * @memberof OSjs.API
   *
   * @param   {String}    name    Hook name
   * @param   {Function}  fn      Callback => fn()
   *
   * @return  {Number}       The index of hook
   */
  API.addHook = function _apiAddHook(name, fn) {
    if ( typeof _hooks[name] !== 'undefined' ) {
      return _hooks[name].push(fn) - 1;
    }
    return -1;
  };

  /**
   * Method for removing a hook
   *
   * @function removeHook
   * @memberof OSjs.API
   *
   * @param   {String}    name    Hook name
   * @param   {Number}    index     Hook index
   *
   * @return  {Boolean}
   */
  API.removeHook = function _apiRemoveHook(name, index) {
    if ( typeof _hooks[name] !== 'undefined' ) {
      if ( _hooks[name][index] ) {
        _hooks[name][index] = null;
        return true;
      }
    }
    return false;
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXTERNALS
  /////////////////////////////////////////////////////////////////////////////

  API.shutdown = API.shutdown || function() {}; // init.js

  /**
   * @function createMenu
   * @memberof OSjs.API
   * @see OSjs.GUI.Helpers.createMenu
   */
  API.createMenu = function() {
    return OSjs.GUI.Helpers.createMenu.apply(null, arguments);
  };

  /**
   * @function blurMenu
   * @memberof OSjs.API
   * @see OSjs.GUI.Helpers.blurMenu
   */
  API.blurMenu = function() {
    return OSjs.GUI.Helpers.blurMenu.apply(null, arguments);
  };

})(OSjs.Utils, OSjs.API);


text:
package ananas.waymq.ht5.litegroup;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * Servlet implementation class LiteGroup2
 */
@WebServlet("/LiteGroup2/*")
public class LiteGroup2Servlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LiteGroup2Servlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String path1 = request.getContextPath();
		String pathf = request.getRequestURI();
		String path2 = pathf.substring(path1.length());
		String[] array = path2.split("/");
		array = this.normalStringArray(array);

		RequestContext rc = new RequestContext(request, response);
		rc._do = request.getParameter("do");
		rc._target_path = path2;
		rc._repo = LG2Repo.Factory.getInstance();

		switch (array.length) {
		case 1: {
			this.procAsSystem(rc);
			break;
		}
		case 2: {
			this.procAsGroup(rc);
			break;
		}
		case 3: {
			this.procAsEvent(rc);
			break;
		}
		default:
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			break;
		}
	}

	private void procAsEvent(RequestContext rc) throws ServletException,
			IOException {
		if (rc._do == null) {
			// html
			String path = "/lg2/event.html";
			rc._request.getRequestDispatcher(path).forward(rc._request,
					rc._response);
		} else {
			// json
			JSONResponder resp = JSONResponderForEvent.getInstance();
			this.processJSON(rc, resp);
		}
	}

	private void processJSON(RequestContext rc, JSONResponder resp)
			throws IOException {

		JSONObject json = rc._json;
		try {
			resp.process(rc);
		} catch (Exception e) {
			e.printStackTrace();
			String str = e + "";
			json.put("exception", str);
		}
		String err = json.getString("error");
		String exp = json.getString("exception");
		json.put("success", (err == null && exp == null));
		String str = JSON.toJSONString(json, true);
		rc._response.setContentType("application/json");
		rc._response.setCharacterEncoding("UTF-8");
		OutputStream out = rc._response.getOutputStream();
		Writer wtr = new OutputStreamWriter(out, "UTF-8");
		wtr.write(str);
		wtr.flush();
		System.out.println(str);
	}

	private void procAsSystem(RequestContext rc) throws ServletException,
			IOException {
		if (rc._do == null) {
			// html
			String path = "/lg2/system.html";
			rc._request.getRequestDispatcher(path).forward(rc._request,
					rc._response);
		} else {
			// json
			JSONResponder resp = JSONResponderForSystem.getInstance();
			this.processJSON(rc, resp);
		}
	}

	private void procAsGroup(RequestContext rc) throws ServletException,
			IOException {
		if (rc._do == null) {
			// html
			String path = "/lg2/group.html";
			rc._request.getRequestDispatcher(path).forward(rc._request,
					rc._response);
		} else {
			// json
			JSONResponder resp = JSONResponderForGroup.getInstance();
			this.processJSON(rc, resp);
		}
	}

	private String[] normalStringArray(String[] array) {
		List<String> list = new ArrayList<String>();
		for (String s : array) {
			if (s.length() > 0) {
				list.add(s);
			}
		}
		return list.toArray(new String[list.size()]);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		this.doGet(request, response);

	}

}


text:
// The MIT License (MIT)
//
// Copyright (c) 2014-2016, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

namespace Tests.Serialization.Objects
{
	using System.Collections.Generic;
	using SafetySharp.Modeling;
	using SafetySharp.Runtime.Serialization;
	using Shouldly;

	internal class Dictionaries : SerializationObject
	{
		protected override void Check()
		{
			var o1 = new object();
			var o2 = new object();
			var c = new C
			{
				D = new Dictionary<int, int> { [1] = 3, [5] = 8, [-1] = -1 },
				E = new Dictionary<object, object> { [o1] = o2, [o2] = o1 },
				F = new Dictionary<int, X> { [0] = new X { A = 2, O = o1 } }
			};

			GenerateCode(SerializationMode.Optimized, c, o1, o2);
			Serialize();

			c.D.Clear();
			c.E.Clear();

			c.D[344] = 32;
			c.E[new object()] = new object();
			c.F[1] = new X();
			c.G[4] = 6;

			Deserialize();

			c.D.Count.ShouldBe(3);
			c.D[1].ShouldBe(3);
			c.D[5].ShouldBe(8);
			c.D[-1].ShouldBe(-1);

			c.E.Count.ShouldBe(2);
			c.E[o1].ShouldBe(o2);
			c.E[o2].ShouldBe(o1);

			c.F.Count.ShouldBe(1);
			c.F[0].A.ShouldBe(2);
			c.F[0].O.ShouldBe(o1);

			c.G.Count.ShouldBe(0);

			c.D.Keys.ShouldBe(new[] { 1, 5, -1 }, ignoreOrder: true);
			c.E.Keys.ShouldBe(new[] { o1, o2 }, ignoreOrder: true);
			c.F.Keys.ShouldBe(new[] { 0 });

			c.D.Values.ShouldBe(new[] { 3, 8, -1 }, ignoreOrder: true);
			c.E.Values.ShouldBe(new[] { o1, o2 }, ignoreOrder: true);
			c.F.Values.ShouldBe(new[] { new X { A = 2, O = o1 } });

			c.D[1] = 77;
			c.F.Clear();
			c.F[3] = new X { A = 7, O = o2 };
			Serialize();

			c.D.Clear();
			c.E.Clear();

			c.D[344] = 32;
			c.E[new object()] = new object();
			c.F[1] = new X();

			Deserialize();

			c.D.Count.ShouldBe(3);
			c.D[1].ShouldBe(77);
			c.F.Count.ShouldBe(1);
			c.F[3].A.ShouldBe(7);
			c.F[3].O.ShouldBe(o2);
		}

		private class C : Component
		{
			public Dictionary<int, int> D = new Dictionary<int, int>();
			public Dictionary<object, object> E = new Dictionary<object, object>();
			public Dictionary<int, X> F = new Dictionary<int, X>();
			public Dictionary<int, int> G = new Dictionary<int, int>();
		}

		private struct X
		{
			public int A;
			public object O;
		}
	}
}


text:
<?php

use Kapi\Http\Response;

describe('Response', function () {
    describe('withStatus', function () {
        it('set only code', function () {
            $response = new Response();
            $response = $response->withStatus(200);

            expect($response->getStatusCode())->toBe(200);
            expect($response->getReasonPhrase())->toBe('OK');
        });

        it('set custom reason', function () {
            $response = new Response();
            $response = $response->withStatus(404, 'This page doesn\'t exist');

            expect($response->getStatusCode())->toBe(404);
            expect($response->getReasonPhrase())->toBe('This page doesn\'t exist');
        });
    });
});


text:
package com.aspectran.web.support.multipart.inmemory;

import org.apache.commons.io.output.ThresholdingOutputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * An output stream which will retain data in memory (always).
 */
public class InMemoryOutputStream extends ThresholdingOutputStream {

    /**
     * The output stream to which data will be written prior to the threshold being reached.
     */
    private final ByteArrayOutputStream outputStream;

    /**
     * True when close() has been called successfully.
     */
    private boolean closed;

    /**
     * Constructs an instance of this class which will trigger throw
     * UnsupportedOperationException if the specified threshold is reached.
     * @param threshold the number of bytes at which to trigger an event
     */
    public InMemoryOutputStream(long threshold) {
        super((int)threshold);
        outputStream = new ByteArrayOutputStream();
    }

    /**
     * Returns the current output stream. This may be memory based or disk based, depending on the
     * current state with respect to the threshold.
     * @return the underlying output stream
     * @exception IOException if an error occurs
     */
    @Override
    protected OutputStream getStream() throws IOException {
        return outputStream;
    }

    /**
     * Not possible in GAE. Will never reach!!
     * If it happens, try changing max upload size setting.
     */
    @Override
    protected void thresholdReached() {
        throw new UnsupportedOperationException("Not possible in GAE. Will never reach!! " +
                "Try changing max upload size setting.");
    }

    /**
     * Determines whether or not the data for this output stream has been retained in memory.
     * @return always {@code true}
     */
    public boolean isInMemory() {
        return true;
    }

    /**
     * Returns the data for this output stream as an array of bytes.
     * @return the data for this output stream, or {@code null} if no such data is available
     */
    public byte[] getData() {
        return outputStream.toByteArray();
    }

    /**
     * Closes underlying output stream, and mark this as closed
     * @exception IOException if an error occurs
     */
    @Override
    public void close() throws IOException {
        super.close();
        closed = true;
    }

    /**
     * Writes the data from this output stream to the specified output stream, after it has been
     * closed.
     * @param out output stream to write to
     * @exception IOException if this stream is not yet closed or an error occurs
     */
    public void writeTo(OutputStream out) throws IOException {
        // we may only need to check if this is closed if we are working with a file
        // but we should force the habit of closing whether we are working with a file or memory.
        if (!closed) {
            throw new IOException("Stream not closed");
        }
        outputStream.writeTo(out);
    }

}


text:
package org.apache.eagle.query.parser;

import org.apache.eagle.query.antlr.generated.EagleFilterLexer;
import org.apache.eagle.query.antlr.generated.EagleFilterParser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EagleQueryParser {
    private static final Logger LOG = LoggerFactory.getLogger(EagleQueryParser.class);
    private String query;

    public EagleQueryParser(String query) {
        this.query = query;
    }

    public ORExpression parse() throws EagleQueryParseException {
        try {
            EagleFilterLexer lexer = new EagleFilterLexer(new ANTLRInputStream(query));
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            tokens.fill();
            EagleFilterParser p = new EagleFilterParser(tokens);
            p.setErrorHandler(new EagleANTLRErrorStrategy());
            p.setBuildParseTree(true);
            EagleQueryFilterListenerImpl listener = new EagleQueryFilterListenerImpl();
            p.addParseListener(listener);
            EagleFilterParser.FilterContext fc = p.filter();
            if (fc.exception != null) {
                LOG.error("Can not successfully parse the query:" + query, fc.exception);
                throw fc.exception;
            }
            return listener.result();
        } catch (Exception ex) {
            LOG.error("Can not successfully parse the query:", ex);
            throw new EagleQueryParseException("can not successfully parse the query:" + query);
        }
    }
}


text:
/**
 * Created by Andrey Khalzov
 * 18.12.2008 20:14:53
 */
package org.wannatrak.client.layout;

import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.PushButton;
import org.wannatrak.client.MainWidget;
import org.wannatrak.client.layout.command.MainWidgetLayoutCommand;

public interface MainWidgetLayout {

    void executeCommand(MainWidgetLayoutCommand mainWidgetLayoutCommand);

    void setLeftWidgetLabel(MainWidget mainWidget, Label leftWidgetLabel);

    void setLeftWidgetLabel(MainWidget mainWidget, Label leftWidgetLabel, String cellStyleName);

    void setRightWidgetLabel(MainWidget mainWidget, Label rightWidgetLabel);

    void setRightWidgetLabel(MainWidget mainWidget, Label rightWidgetLabel, String cellStyleName);

    void setCenterWidgetHeader(MainWidget mainWidget, Widget centerWidgetHeader);

    void setCenterWidgetHeader(MainWidget mainWidget, Widget centerWidgetHeader, String cellStyleName);

    void setLeftWidget(MainWidget mainWidget, Widget leftWidget);

    void setLeftWidget(MainWidget mainWidget, Widget leftWidget, String cellStyleName);

    void setCenterWidget(MainWidget mainWidget, Widget centerWidget);

    void setCenterWidget(MainWidget mainWidget, Widget centerWidget, String cellStyleName);

    void setRightWidget(MainWidget mainWidget, Widget rightWidget);

    void setRightWidget(MainWidget mainWidget, Widget rightWidget, String cellStyleName);

    void setBottomWidget(MainWidget mainWidget, Widget bottomWidget);

    void setBottomWidget(MainWidget mainWidget, Widget bottomWidget, String cellStyleName);

    void setLeftHideButton(MainWidget mainWidget, PushButton leftHideButton);

    void setLeftHideButton(MainWidget mainWidget, PushButton leftHideButton, String cellStyleName);

    void setRightHideButton(MainWidget mainWidget, PushButton rightHideButton);

    void setRightHideButton(MainWidget mainWidget, PushButton rightHideButton, String cellStyleName);

    void setLeftShowButton(MainWidget mainWidget, PushButton leftShowButton);

    void setLeftShowButton(MainWidget mainWidget, PushButton leftShowButton, String cellStyleName);

    void setRightShowButton(MainWidget mainWidget, PushButton rightShowButton);

    void setRightShowButton(MainWidget mainWidget, PushButton rightShowButton, String cellStyleName);
}