text:
---
layout: post97
title:  Executor Based Remoting
categories: XAP97
parent: space-based-remoting-overview.html
weight: 200
---

{% summary%}{%endsummary%}

{%comment%}
{% summary%}Executor Remoting allows you to use remote invocations of POJO services, with the space as the transport layer using OpenSpaces Executors.{% endsummary %}

# Overview
{%endcomment%}

*Executor Based Remoting* uses [Executors](./task-execution-over-the-space.html) to provided remoting capabilities on top of the Space. Executor Based Remoting allows for direct invocation of services in an asynchronous manner in a broadcast or routed manner. Executor Remoting works with services that are deployed in a Processing Unit and execute within a collocated space.

![Executor.jpg](/attachment_files/Executor.jpg)

# The executor-proxy

The `executor-proxy` should be created on the client side to interact with the remote service. It can be created via Spring namespace, Spring Bean or via API.

The `executor-proxy` include the following properties:

{: .table .table-bordered}
| property| Class Type | Required | NameSpace Bean | Description | Default |
|:--------|:-----------|:---------|:---------------|:------------|:--------|
|gigaSpace | GigaSpace | giga-space | Yes |Sets the GigaSpace interface that will be used to work with the space as the transport layer for executions of Space tasks.| |
|timeout | long |  Yes | timeout | Sets the timeout that will be used to wait for the remote invocation response. The timeout value is in milliseconds.  | 60000 (60 seconds).|
|remoteRoutingHandler | RemoteRoutingHandler | No | routing-handler |In case of remote invocation over a partitioned space,  the default partitioned routing index will be random (the hashCode of the newly created remote invocation). This RemoteRoutingHandler allows for custom routing computation (for example, based on one of the service method parameters).| |
|metaArgumentsHandler | MetaArgumentsHandler | No | meta-arguments-handler | Allows the meta arguments handler to be set, which will process the meta-arguments passed on each remote invocation.| |
|asyncMethodPrefix | String |
|broadcast | boolean | No | broadcast| If set the true (defaults to false), the remote invocation will be called on all active (primary) cluster members.| |
|returnFirstResult | boolean |No | return-first-result | When set to true (defaults to true), the first result will be returned (when using broadcast). If set to false, an array of results will be returned. Note, this only applies when no reducer is provided.| |
|remoteResultReducer | RemoteResultReducer |No| result-reducer | When using broadcast is set to true, a custom reducer can be provided to reduce the array of result objects into a calculated response object.| |
| remoteInvocationAspect | RemoteInvocationAspect |No| An Aspect that will be executed around each service invocation.| |
|serviceProxy | Object |
| methodHashLookup | Map<Method, MethodHash> |
|interface | Class | Yes | | The interface (fully qualified class name) that this remoting proxy implements. Also controls which service will be invoked in the "server" (Processing Unit).| |

Example:
{% highlight xml %}
<bean id="dataProcessor" class="org.openspaces.remoting.ExecutorSpaceRemotingProxyFactoryBean">
    <property name="gigaSpace" ref="gigaSpace" />
    <property name="timeout" value="60000" />

    <property name="serviceInterface" value="org.openspaces.example.data.common.IDataProcessor" />
    <property name="broadcast" value="true" />

    <property name="remoteInvocationAspect">
    	<bean class="eg.MyRemoteInvocationAspect" />
    </property>

	<property name="metaArgumentsHandler">
    	<bean class="eg.MyMetaArgumentsHandler" />
    </property>

	<property name="remoteResultReducer">
    	<bean class="eg.MyRemoteResultReducer" />
    </property>

	<property name="remoteRoutingHandler">
        <bean class="org.openspaces.example.data.feeder.support.DataRemoteRoutingHandler"/>
    </property>
</bean>
{% endhighlight %}

# Defining the Contract

In order to support remoting, the first step is to define the contract between the client and the server. In our case, the contract is a simple Java interface. Here is an example:

{% highlight java %}
public interface IDataProcessor {

    /**
     * Process a given Data object, returning the processed Data object.
     */
    Data processData(Data data);
}
{% endhighlight %}

{% exclamation %} The `Data` object should be `Serializable`, or better yet, `Externalizable` (for better performance).

# Implementing the Contract

Next, an implementation of this contract needs to be provided. This implementation will "live" on the server side. Here is a sample implementation:

{% inittab os_simple_space|top %}
{% tabcontent Annotation %}

{% highlight java %}
@RemotingService
public class DataProcessor implements IDataProcessor {

    public Data processData(Data data) {
    	data.setProcessor(true);
    	return data;
    }
}
{% endhighlight %}

{% endtabcontent %}
{% tabcontent XML %}

{% highlight java %}
public class DataProcessor implements IDataProcessor {

    public Data processData(Data data) {
    	data.setProcessor(true);
    	return data;
    }
}
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

The XML tab corresponds to exporting the service using an xml configuration (explained in the next section). The Annotation tab corresponds to exporting the service using annotations.

# Exporting the Service Over the Space

The next step is exporting the service over the space. Exporting the service is done on the server side. As with other Spring remoting support, exporting the service and the mechanism of exporting the service is a configuration-time decision. Here is an example of a Spring XML configuration:

{% inittab os_simple_space|top %}
{% tabcontent Annotation %}

{% highlight xml %}

<context:component-scan base-package="com.mycompany"/>

<os-remoting:annotation-support />

<os-core:space id="space" url="/./space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<os-remoting:service-exporter id="serviceExporter" />
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Namespace %}

{% highlight xml %}
<os-core:space id="space" url="/./space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<bean id="dataProcessor" class="DataProcessor" />

<os-remoting:service-exporter id="serviceExporter">
     <os-remoting:service ref="dataProcessor"/>
</os-remoting:service-exporter>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="/./space" />
</bean>

<bean id="gigaSpace" class="org.openspaces.core.GigaSpaceFactoryBean">
	<property name="space" ref="space" />
</bean>

<bean id="dataProcessor" class="DataProcessor" />

<bean id="serviceExporter" class="org.openspaces.remoting.SpaceRemotingServiceExporter">
    <property name="services">
        <list>
            <ref bean="dataProcessor" />
        </list>
    </property>
</bean>
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

The name/id of the `SpaceRemotingServiceExporter` bean is important when using Executor Based Remoting. By default, the `Task` representing the remote invocation searches for a service exporter named `serviceExporter`, otherwise, it uses the first bean that is of the type `SpaceRemotingServiceExporter`.

{% note %}
Exporting services is done on a Processing Unit (or a Spring application context) that starts an embedded space.
{%endnote%}

# Using the Service on the Client Side

In order to use the exported `IDataProcessor` on the client side, beans should use the `IDataProcessor` interface directly:

{% highlight java %}
public class DataRemoting {

    private IDataProcessor dataProcessor;

    public void setDataProcessor(IDataProcessor dataProcessor) {
        this.dataProcessor = dataProcessor;

    }
}
{% endhighlight %}

Configuring the `IDataProcessor` proxy can done in the following manner:

{% inittab os_simple_space|top %}
{% tabcontent Namespace %}

{% highlight xml %}
<os-core:space id="space" url="jini://*/*/space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<os-remoting:executor-proxy id="dataProcessor" giga-space="gigaSpace"
                   interface="org.openspaces.example.data.common.IDataProcessor">
</os-remoting:executor-proxy>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="jini://*/*/space" />
</bean>

<bean id="gigaSpace" class="org.openspaces.core.GigaSpaceFactoryBean">
	<property name="space" ref="space" />
</bean>

<bean id="dataProcessor" class="org.openspaces.remoting.ExecutorSpaceRemotingProxyFactoryBean">
    <property name="gigaSpace" ref="gigaSpace" />
    <property name="serviceInterface" value="org.openspaces.example.data.common.IDataProcessor" />
</bean>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Code %}

{% highlight java %}
IJSpace space = new UrlSpaceConfigurer("jini://*/*/space").space();

GigaSpace gigaSpace = new GigaSpaceConfigurer(space).gigaSpace();

IDataProcessor dataProcessor = new ExecutorRemotingProxyConfigurer<IDataProcessor>(gigaSpace, IDataProcessor.class)
                               .proxy();

DataRemoting dataRemoting = new DataRemoting();

dataRemoting.setDataProcessor(dataProcessor);
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

The example above uses the `executor-proxy` bean in order to create the remoting proxy which can later be injected into the `DataRemoting` object. OpenSpaces remoting also allows injection of the remoting proxy into the remoting service property using annotations. Here is an example of annotating the `DataRemoting` class:

{% highlight java %}
public class DataRemoting {

    @ExecutorProxy
    private IDataProcessor dataProcessor;

    // ...
}
{% endhighlight %}

If there are more than one `GigaSpace` beans defined within the application context, the ID of the `giga-space` bean needs to be defined on the annotations.

In order to enable this feature, the following element needs to be added to the application context XML:

{% inittab os_simple_space|top %}
{% tabcontent Namespace %}

{% highlight xml %}
<os-remoting:annotation-support />
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}
<bean id="space" class="org.openspaces.remoting.RemotingAnnotationBeanPostProcessor" />
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

## Remote Routing Handler

Many times, space remoting is done by exporting services in a space with a partitioned cluster topology. The service is exported when working directly with a cluster member (and not against the whole space cluster). When working with such a topology, the client side remoting automatically generates a random routing index value. In order to control the routing index, the following interface can be implemented:

{% highlight java %}
public interface RemoteRoutingHandler<T> {

    /**
     * Returns the routing field value based on the remoting invocation. If null
     * is returned, will use internal calcualtion of the routing index.
     */
    T computeRouting(SpaceRemotingInvocation remotingEntry);
}
{% endhighlight %}

Here is a sample implementation which uses the first parameter `Data` object type as the routing index.

{% highlight java %}
public class DataRemoteRoutingHandler implements RemoteRoutingHandler<Long> {

    public Long computeRouting(SpaceRemotingInvocation remotingEntry) {
        if (remotingEntry.getMethodName().equals("processData")) {
            Data data = (Data) remotingEntry.getArguments()[0];
            return data.getType();
        }
        return null;
    }
}
{% endhighlight %}

Finally, the wiring is done in the following manner:

{% inittab os_simple_space|top %}
{% tabcontent Namespace %}

{% highlight xml %}
<os-core:space id="space" url="jini://*/*/space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<os-remoting:executor-proxy id="dataProcessor" giga-space="gigaSpace"
                   interface="org.openspaces.example.data.common.IDataProcessor">
    <os-remoting:routing-handler>
        <bean class="org.openspaces.example.data.feeder.support.DataRemoteRoutingHandler"/>
    </os-remoting:routing-handler>
</os-remoting:executor-proxy>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="jini://*/*/space" />
</bean>

<bean id="gigaSpace" class="org.openspaces.core.GigaSpaceFactoryBean">
	<property name="space" ref="space" />
</bean>

<bean id="dataProcessor" class="org.openspaces.remoting.ExecutorSpaceRemotingProxyFactoryBean">
    <property name="gigaSpace" ref="gigaSpace" />
    <property name="serviceInterface" value="org.openspaces.example.data.common.IDataProcessor" />
    <property name="remoteRoutingHandler">
        <bean class="org.openspaces.example.data.feeder.support.DataRemoteRoutingHandler"/>
    </property>
</bean>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Code %}

{% highlight java %}
IJSpace space = new UrlSpaceConfigurer("jini://*/*/space").space();

GigaSpace gigaSpace = new GigaSpaceConfigurer(space).gigaSpace();

IDataProcessor dataProcessor = new ExecutorRemotingProxyConfigurer<IDataProcessor>(gigaSpace, IDataProcessor.class)
                               .remoteRoutingHandler(new DataRemoteRoutingHandler())
                               .proxy();

DataRemoting dataRemoting = new DataRemoting();

dataRemoting.setDataProcessor(dataProcessor);
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

## Routing Annotation

The option, above, using the remote routing handler is very handy when not using annotations (broadcasting). OpenSpaces remoting also supports the `@Routing` annotation in order to define which parameter controls the routing. Here is an example:

{% highlight java %}
public interface MyService {

    void doSomething(@Routing int param1, int param2);
}
{% endhighlight %}

In the example above, the routing is done using the param1 value. In complex objects, a method name can be specified to be invoked on the parameter, in order to get the actual routing index. Here is an example:

{% highlight java %}
public interface MyService {

    void doSomething(@Routing("getProperty") Value param1, int param2);
}
{% endhighlight %}

In the example, the `getProperty` method is called on the `Value` object, and its return value is subsequently used to extract the routing index.

{% note %}
**Note:** Using a [SpaceDocument](./document-api.html) as the annotated routing argument will cause an Exception since the `SpaceDocument` class does not define a getter method for each property, but rather a generic getter method to get a property value by its name. To avoid the Exception, simply extend the `SpaceDocument` class as described in [Extending Space Documents](./document-extending.html) and then define the relevant `getProperty` method in the extension class. Alternatively, an Exception can be avoided by implementing a `RemoteRoutingHandler`, as described above.
{%endnote%}

# Asynchronous Execution

OpenSpaces executor remoting supports asynchronous execution of remote services using the `AsyncFuture` interface (which extends the `java.util.concurrent.Future` interface). Since the remoting implementation is asynchronous by nature, a `Future` can be used to execute remote services asynchronously.

Since the definition of the interface acts as the contract between the client and the server, asynchronous invocation requires the interface to also support the same business method, returning a `Future` or `AsyncFuture` instead of its actual return value. The asynchronous nature is only relevant on the client side, provided by the asynchronous nature of OpenSpaces remoting. There are two options to implement such behavior:

## Different Service Interfaces

The client and the server can have a different service interface definition under the same package and under the same name. The server includes the actual implementation:

{% highlight java %}
public interface SimpleService {

    String say(String message);

    int calc(int value1, int value2);
}
{% endhighlight %}

The client has the same method except it returns a future:

{% highlight java %}
public interface SimpleService {

    AsyncFuture<String> say(String message);

    int calc(int value1, int value2);
}
{% endhighlight %}

In the above example, the `say()` method uses a `Future` in order to receive the result, while the `calc` method remains synchronous.

{% info %}
When using different services, it is important to include the interface definition in the processing unit `lib` directory (or the compiled classes root directory), so that both client and server use their own definitions and don't share a single one.
{%endinfo%}

## Single Service Interface

Both the client and server share the same interface, with the interface holding both synchronous and asynchronous services. Here is an example:

{% highlight java %}
public interface SimpleService {

    String say(String message);

    AsyncFuture<String> asyncSay(String message);
}
{% endhighlight %}

In the above case, the server implementation does not need to implement the `asyncSay` method (simply return `null` for the `asyncSay` method). The client side can choose which service to invoke.
You should note the naming convention and the signature of the asynchronous method in this case.
If the regular method looks as follows:
`T doSomething(String arg)`, T being the return value type, then the asynchronous method should have the following signature:
`Future<T> asyncDoSomething(String arg)`.
In other words, the regular method should be prefixed with `async` and the return value should be a `Future` of the original return value (unless it's `void`, in which case it stays `void`).

# Server Side Services Injection

Each parameter of a remote service can be dynamically injected as if it were a bean defined within the server side (where the service is actually executed) context. This allows you to utilize server side resources and state, within the actual invocation. In order to enable such injection the service interface should either be annotated with `AutowireArguments` annotation, or implement the marker interface `AutowireArgumentsMarker`. Let's see an example:

{% highlight java %}
@AutowireArguments
public interface MyService {

    void doSomething(Value param1);
}
{% endhighlight %}

The above service exposes a service which accepts a `Value` as a parameter. The `Value` parameter, if needed, can be injected dynamically with server side resources and state. For example, if the server side execution needs to be aware of the `ClusterInfo`, the `Value` parameter can implement the `ClusterInfoAware` interface. Here is what it looks like:

{% highlight java %}
public class Value implements ClusterInfoAware {

    private transient ClusterInfo clusterInfo;

    public void setClusterInfo(ClusterInfo clusterInfo) {
        this.clusterInfo = clusterInfo;
    }
}
{% endhighlight %}

{% info %}
Note the fact that `clusterInfo` is transient, so it won't be marshaled after injection back to the client.
{%endinfo%}

Another example is injecting another service that is defined in the server side directly into the parameter, for example, using Spring `@Autowired` annotation.

{% highlight java %}
public class Value implements ClusterInfoAware {

    @Autowired
    private transient AnotherService anotherService;
}
{% endhighlight %}

# Transactional Execution

Executor remoting supports transactional execution of services. On the client side, if there is an ongoing declarative transaction during the service invocation (a Space based transaction), the service will be executed under the same transaction. The transaction itself is passed to the server and any Space related operations (performed using `GigaSpace`) will be executed under the same transaction. The transaction lifecycle itself is controlled on the client side (declaratively) and is committed / rolled back only on the client side. (Note, exceptions on the server side will simply propagate to the client side, and will cause a rollback only if the client "decides" so.)

When using broadcast with executor remoting, a declarative distributed transaction must be used and not a local (or JTA one). Also note, the `GigaSpace` instance that is used internally by the executor remoting invocation must be configured with a transaction manager (as is the case for enabling transaction execution with any other `GigaSpace` based operation).

Here is a simple example how the Client and the Service should be configured:

Client pu.xml

{% highlight xml %}
<context:component-scan base-package="com.demo"/>
<os-core:space id="space" url="jini://*/*/space" />

<os-core:distributed-tx-manager id="myTransactionManager" />
<os-core:giga-space id="gigaspace" space="space"  tx-manager="myTransactionManager"/>
<tx:annotation-driven transaction-manager="myTransactionManager" />

<os-remoting:executor-proxy id="myService" giga-space="gigaspace" interface="com.demo.IMyService" broadcast="true">
<os-remoting:result-reducer>
	<bean class="com.demo.MyRemoteResultReducer" />
	</os-remoting:result-reducer>
	</os-remoting:executor-proxy>

<bean id="callingBean" class="com.demo.ClientWarrper">
           <property name="client" ref="client"/>
</bean>

<bean id="client" class="com.demo.Client">
	   <property name="myService" ref="myService" />
	   <property name="gigaspace" ref="gigaspace" />
</bean>
{% endhighlight %}

Client Implementation

{% highlight java %}
@Transactional(readOnly = true , value="myTransactionManager")
public class Client{
	GigaSpace gigaspace ;
	IMyService myService ;

	public static void main(String[] args) {
	}

	@Transactional(propagation=Propagation.REQUIRES_NEW , value="myTransactionManager")
	public void doTX() throws Exception
	{
		MyData myObj = new MyData(1);
		gigaspace.write(myObj);

		System.out.println("Client - TX:" + gigaspace.getCurrentTransaction());
		boolean ret = myService.doTX();
		System.out.println("Service Call Done! - Result:"+ret);
	}
}
{% endhighlight %}

Service pu.xml

{% highlight java %}
<context:component-scan base-package="com.demo"/>
<os-remoting:annotation-support />
<os-core:space id="space" url="/./space" />
<os-core:giga-space id="gigaSpace" space="space"/>
<os-remoting:service-exporter id="serviceExporter" />
{% endhighlight %}

Service Implementation

{% highlight java %}
@RemotingService
@Transactional(readOnly = true)
public class MyService implements IMyService {
	public MyService()	{}
	@Autowired
	GigaSpace gigaSpace;

	@Transactional(propagation=Propagation.SUPPORTS)
	public boolean doTX()
	{
		MyData myObj = new MyData(2);
		gigaSpace.write(myObj);
		System.out.println("Service - TX:" + gigaSpace.getCurrentTransaction());
	}
}
{% endhighlight %}

# Execution Aspects

Space based remoting allows you to inject "aspects" that can wrap the invocation of a remote method on the client side, as well as wrapping the execution of an invocation on the server side.

## The Client Invocation Aspect

The client invocation aspect interface is shown below. You should implement this interface and wire and instance of the implementing class to the client side remote proxy, as explained below:

{% highlight java %}
public interface RemoteInvocationAspect<T> {

    /**
     * The aspect is called instead of the actual remote invocation. The methodInvocation can
     * be used to access any method related information. The remoting invoker passed can be used
     * to actually invoke the remote invocation.
     */
    T invoke(MethodInvocation methodInvocation, RemotingInvoker remotingInvoker) throws Throwable;
}
{% endhighlight %}

An implementation of such an aspect can be configured as follows:

{% inittab os_simple_space|top %}
{% tabcontent Namespace %}

{% highlight xml %}
<os-core:space id="space" url="jini://*/*/space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<os-remoting:executor-proxy id="dataProcessor" giga-space="gigaSpace"
                   interface="org.openspaces.example.data.common.IDataProcessor">
    <os-remoting:aspect>
    	<bean class="eg.MyRemoteInvocationAspect" />
    </os-remoting:aspect>
</os-remoting:executor-proxy>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="jini://*/*/space" />
</bean>

<bean id="gigaSpace" class="org.openspaces.core.GigaSpaceFactoryBean">
	<property name="space" ref="space" />
</bean>

<bean id="dataProcessor" class="org.openspaces.remoting.ExecutorSpaceRemotingProxyFactoryBean">
    <property name="gigaSpace" ref="gigaSpace" />
    <property name="serviceInterface" value="org.openspaces.example.data.common.IDataProcessor" />
    <property name="remoteInvocationAspect">
    	<bean class="eg.MyRemoteInvocationAspect" />
    </property>
</bean>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Code %}

{% highlight java %}
IJSpace space = new UrlSpaceConfigurer("jini://*/*/space").space();

GigaSpace gigaSpace = new GigaSpaceConfigurer(space).gigaSpace();

IDataProcessor dataProcessor = new ExecutorRemotingProxyConfigurer<IDataProcessor>(gigaSpace, IDataProcessor.class)
                               .remoteInvocationAspect(new MyRemoteInvocationAspect())
                               .proxy();

DataRemoting dataRemoting = new DataRemoting();

dataRemoting.setDataProcessor(dataProcessor);
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

The instance of the class that implements the `RemoteInvocationAspect` interface will be called by the framework prior to the invocation on the client side. Note that it is up to the aspect implementation to decide whether or not the call should proceed.
If the aspect implementation decides to proceed with the call it should call `method.invoke()` on the provided `method` argument. Otherwise the call to the server will not be performed.

{% anchor serverExecutionApect %}

## The Server Invocation Aspect

The server side invocation aspect interface is shown below. You should implement this interface and wire and instance of the implementing class to the server side service exporter (this is the component that is responsible for exposing your service bean to remote clients):

{% highlight java %}
public interface ServiceExecutionAspect {

    /**
     * A service execution callback allows you to wrap the execution of "server side" service. If
     * actual execution of the service is needed, the invoke method will need to
     * be called on the passed Method using the service as the actual service to
     * invoke it on, and {@link SpaceRemotingInvocation#getArguments()} as the method arguments.
     *
     *
As an example: method.invoke(service, invocation.getArguments()).
     */
    Object invoke(SpaceRemotingInvocation invocation, Method method, Object service)
                                  throws InvocationTargetException, IllegalAccessException;
}
{% endhighlight %}

An implementation of such an aspect can be configured as follows:

{% inittab os_simple_space|top %}
{% tabcontent Namespace %}

{% highlight xml %}
<os-core:space id="space" url="/./space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<bean id="dataProcessor" class="DataProcessor" />

<os-remoting:service-exporter id="serviceExporter">
     <os-remoting:aspect>
         <bean class="eg.MyServiceExecutionAspect" />
     </os-remoting:aspect>
     <os-remoting:service ref="dataProcessor"/>
</os-remoting:service-exporter>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="/./space" />
</bean>

<bean id="gigaSpace" class="org.openspaces.core.GigaSpaceFactoryBean">
	<property name="space" ref="space" />
</bean>

<bean id="dataProcessor" class="DataProcessor" />

<bean id="serviceExporter" class="org.openspaces.remoting.SpaceRemotingServiceExporter">
    <property name="serviceExecutionAspect">
         <bean class="eg.MyServiceExecutionAspect" />
    </property>
    <property name="services">
        <list>
            <ref bean="dataProcessor" />
        </list>
    </property>
</bean>
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

The instance of the class that implements the `ServiceExecutionAspect` interface will be called by the framework prior to the invocation of the service bean on the server side. Note that it is up to the aspect implementation to decide whether or not the call should proceed.
If the aspect implementation decides to proceed with the call it should call `method.invoke()` on the provided `method` argument. Otherwise the call to the service bean will not be performed.

# The Metadata Handler

When executing a service using Space based remoting, a set of one or more metadata arguments (in the form of a `java.lang.Object` array) can be passed to the server with the remote invocation. This feature is very handy when you want to pass certain metadata with every remote call that is not part of the arguments of the method you call. A prime example for using meta arguments is security -- i.e. passing security credentials as meta arguments, and using a server side aspect to authorize the execution or to log who actually called the method.

To create the meta arguments on the client side you should implement the following interface and inject an instance of the implementing class to the client side proxy:

{% highlight java %}
public interface MetaArgumentsHandler {

    /**
     * Meta argument handler can control the meta data objects that will be used
     * for the remote invocation.
     */
    Object[] obtainMetaArguments(SpaceRemotingInvocation remotingEntry);
}
{% endhighlight %}

The following snippets show how to plug a custom meta arguments handler to the client side remote proxy. The `Object` array returned by the implementation of the `MetaArgumentsHandler` interface will be sent along with the invocation to server side.

{% inittab os_simple_space|top %}
{% tabcontent Namespace %}

{% highlight xml %}

<os-core:space id="space" url="jini://*/*/space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<os-remoting:executor-proxy id="dataProcessor" giga-space="gigaSpace"
                   interface="org.openspaces.example.data.common.IDataProcessor">
    <os-remoting:meta-arguments-handler>
    	<bean class="eg.MyMetaArgumentsHandler" />
    </os-remoting:meta-arguments-handler>
</os-remoting:executor-proxy>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}

<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="jini://*/*/space" />
</bean>

<bean id="gigaSpace" class="org.openspaces.core.GigaSpaceFactoryBean">
	<property name="space" ref="space" />
</bean>

<bean id="dataProcessor" class="org.openspaces.remoting.ExecutorSpaceRemotingProxyFactoryBean">
    <property name="gigaSpace" ref="gigaSpace" />
    <property name="serviceInterface" value="org.openspaces.example.data.common.IDataProcessor" />
    <property name="metaArgumentsHandler">
    	<bean class="eg.MyMetaArgumentsHandler" />
    </property>
</bean>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Code %}

{% highlight java %}
IJSpace space = new UrlSpaceConfigurer("jini://*/*/space").space();

GigaSpace gigaSpace = new GigaSpaceConfigurer(space).gigaSpace();

IDataProcessor dataProcessor = new ExecutorRemotingProxyConfigurer<IDataProcessor>(gigaSpace, IDataProcessor.class)
                               .metaArgumentsHandler(new MyMetaArgumentsHandler())
                               .proxy();

DataRemoting dataRemoting = new DataRemoting();

dataRemoting.setDataProcessor(dataProcessor);
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

The way to access the meta arguments on the server side is to configure a [server side execution aspect](#serverExecutionApect) by implementing the `ServiceExecutionAspect` and wiring it on the server side as shown [above](#serverExecutionApect). To access the meta arguments, you should call `SpaceRemotingInvocation.getMetaArguments()` on the `invocation` argument provided to the server side aspect.

# Broadcast Remoting

When using executor remoting, a remote invocation can be broadcasted to all active (primary) cluster members. Each Service instance is invoked and return a result to its called which in turn reduce these and pass the final result to the application.

The First phase involves the Service invocation:
![Executor1.jpg](/attachment_files/Executor1.jpg)

The Second phase involves reducing the results retrieved from the Services:
![Executor2.jpg](/attachment_files/Executor2.jpg)

The configuration of enabling broadcasting is done on the client level, by setting the broadcast flag to `true`:

{% inittab os_simple_space|top %}
{% tabcontent Namespace %}

{% highlight xml %}
<os-core:space id="space" url="jini://*/*/space" />

<os-core:giga-space id="gigaSpace" space="space"/>

<os-remoting:executor-proxy id="dataProcessor" giga-space="gigaSpace"
                   interface="org.openspaces.example.data.common.IDataProcessor" broadcast="true">
</os-remoting:executor-proxy>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Plain XML %}

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="jini://*/*/space" />
</bean>

<bean id="gigaSpace" class="org.openspaces.core.GigaSpaceFactoryBean">
	<property name="space" ref="space" />
</bean>

<bean id="dataProcessor" class="org.openspaces.remoting.ExecutorSpaceRemotingProxyFactoryBean">
    <property name="gigaSpace" ref="gigaSpace" />
    <property name="serviceInterface" value="org.openspaces.example.data.common.IDataProcessor" />
    <property name="broadcast" value="true" />
</bean>

<bean id="dataRemoting" class="DataRemoting">
    <property name="dataProcessor" ref="dataProcessor" />
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Code %}

{% highlight java %}
IJSpace space = new UrlSpaceConfigurer("jini://*/*/space").space();

GigaSpace gigaSpace = new GigaSpaceConfigurer(space).gigaSpace();

IDataProcessor dataProcessor = new ExecutorRemotingProxyConfigurer<IDataProcessor>(gigaSpace, IDataProcessor.class)
                               .broadcast(true)
                               .proxy();

DataRemoting dataRemoting = new DataRemoting();

dataRemoting.setDataProcessor(dataProcessor);
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

## The Remote Result Reducer

When broadcasting remote invocations to all active cluster members, and the remote method returns a result, on the client side an array of all remote results needs to be processed. By default, the first result is returned, and it can be overridden using the `return-first-result` flag (which will then return the array of responses). The executor remoting proxy allows for a pluggable remote result reducer that can reduce a collection of remoting results into a single one. Here is the defined interface:

{% highlight java %}
public interface RemoteResultReducer<T, Y> {

    /**
     * Reduces a list of Space remoting invocation results to an Object value. Can use
     * the provided remote invocation to perform different reduce operations, for example
     * based on the {@link SpaceRemotingInvocation#getMethodName()}.
     *
     *
An exception thrown from the reduce operation will be propagated to the client.
     *
     * @param results            A list of results from (usually) broadcast sync remote invocation.
     * @param remotingInvocation The remote invocation
     * @return A reduced return value (to the calling client)
     * @throws Exception An exception that will be propagated to the client
     */
    T reduce(SpaceRemotingResult<Y>[] results, SpaceRemotingInvocation remotingInvocation) throws Exception;
}
{% endhighlight %}

# Failover

In case of a Primary Backup clusters and Partitioned Sync2Backup clusters, when there is failure of primary space partition, remoting request is transparently forwarded to the backup.

Executor proxy is aware of each partition in the cluster and connection with the failed primary partition will get interrupted/disconnected in case of a failure. Proxy recognizes failure and redirects the request to the backup partition. When the backup becomes ready (any warmup code that needs to run and is ready to accept operations), it will accept this request and process the request. All of this failover behavior is done within the GigaSpaces proxy code and client does not need any extra logic. For more information refer to [Proxy Connectivity]({%currentadmurl%}/tuning-proxy-connectivity.html).

If the backup space does not become ready to accept requests within the configured number of retries, execute request will fail with an Exception. In case of a broadcast request, `SpaceRemotingResult` for failed partition will have an exception. Following example shows how to inspect for exceptions in Reducer,

{% highlight java %}
public class DataProcessorServiceReducer implements RemoteResultReducer<Integer, Integer>{

	public Integer reduce(SpaceRemotingResult<Integer>[] results,
                               SpaceRemotingInvocation sri) throws Exception {
		int total_result =0;
		for (SpaceRemotingResult<Integer> result : results)
		{
			if (result.getException() == null) {
				int temp_result = result.getResult().intValue();
				total_result +=  temp_result ;
			} else {
				System.out.println("Exception on the Server: "
                                                   + result.getException().getMessage());
				result.getException().printStackTrace();
			}

		}
		return total_result/results.length  ;
	}
}
{% endhighlight %}

# Working Examples

1. [This repository](https://github.com/jasonnerothin/gs-executor-remoting/) provides both a [service exporter](https://github.com/jasonnerothin/gs-executor-remoting/blob/master/src/main/resources/META-INF/Spring/pu.xml#L23) and a [service consumer](https://github.com/jasonnerothin/gs-executor-remoting/blob/master/src/test/resources/com/gigaspaces/sbp/WatchRepairClient.xml#L24). Test code dispatches a remoted request right [here](https://github.com/jasonnerothin/gs-executor-remoting/blob/master/src/test/scala/com/gigaspaces/sbp/WatchRepairSuite.scala#L95).


text:
namespace llvm {

namespace codeview {

struct CrossModuleImportItem {
  const CrossModuleImport *Header = nullptr;
  FixedStreamArray<support::ulittle32_t> Imports;
};

} // end namespace codeview

template <> struct VarStreamArrayExtractor<codeview::CrossModuleImportItem> {
public:
  using ContextType = void;

  Error operator()(BinaryStreamRef Stream, uint32_t &Len,
                   codeview::CrossModuleImportItem &Item);
};

namespace codeview {

class DebugStringTableSubsection;

class DebugCrossModuleImportsSubsectionRef final : public DebugSubsectionRef {
  using ReferenceArray = VarStreamArray<CrossModuleImportItem>;
  using Iterator = ReferenceArray::Iterator;

public:
  DebugCrossModuleImportsSubsectionRef()
      : DebugSubsectionRef(DebugSubsectionKind::CrossScopeImports) {}

  static bool classof(const DebugSubsectionRef *S) {
    return S->kind() == DebugSubsectionKind::CrossScopeImports;
  }

  Error initialize(BinaryStreamReader Reader);
  Error initialize(BinaryStreamRef Stream);

  Iterator begin() const { return References.begin(); }
  Iterator end() const { return References.end(); }

private:
  ReferenceArray References;
};

class DebugCrossModuleImportsSubsection final : public DebugSubsection {
public:
  explicit DebugCrossModuleImportsSubsection(
      DebugStringTableSubsection &Strings)
      : DebugSubsection(DebugSubsectionKind::CrossScopeImports),
        Strings(Strings) {}

  static bool classof(const DebugSubsection *S) {
    return S->kind() == DebugSubsectionKind::CrossScopeImports;
  }

  void addImport(StringRef Module, uint32_t ImportId);

  uint32_t calculateSerializedSize() const override;
  Error commit(BinaryStreamWriter &Writer) const override;

private:
  DebugStringTableSubsection &Strings;
  StringMap<std::vector<support::ulittle32_t>> Mappings;
};

} // end namespace codeview

} // end namespace llvm

#endif // LLVM_DEBUGINFO_CODEVIEW_DEBUGCROSSIMPSUBSECTION_H

redpajama_set_name: RedPajamaGithub


text:
package com.b2international.snowowl.datastore.internal.branch;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;

import org.eclipse.emf.cdo.common.branch.CDOBranch;

import com.b2international.commons.collections.Collections3;
import com.b2international.snowowl.core.Metadata;
import com.google.common.collect.ImmutableSet;

/**
 * @since 4.1
 */
public class CDOMainBranchImpl extends MainBranchImpl implements InternalCDOBasedBranch {

	static final String TYPE = "CDOMainBranchImpl";

	private final int cdoBranchId = CDOBranch.MAIN_BRANCH_ID;
	private final int segmentId;
	private final Collection<Integer> segments;

	CDOMainBranchImpl(long baseTimestamp, long headTimestamp, Metadata metadata, int segmentId, Collection<Integer> segments) {
		super(baseTimestamp, headTimestamp, metadata);
		this.segmentId = segmentId;
		this.segments = Collections3.toImmutableSet(segments);
	}

	@Override
	protected BranchImpl doCreateBranch(String name, String parentPath, long baseTimestamp, long headTimestamp, boolean deleted, Metadata metadata) {
		return new CDOMainBranchImpl(baseTimestamp, headTimestamp, metadata, segmentId, segments);
	}

	@Override
	public int segmentId() {
		return segmentId;
	}

	@Override
	public Collection<Integer> segments() {
		return segments;
	}

	@Override
	public Collection<Integer> parentSegments() {
		return Collections.emptySet();
	}

	@Override
	public int cdoBranchId() {
		return cdoBranchId;
	}

	@Override
	public InternalCDOBasedBranch withSegmentId(int newSegmentId) {
		final Set<Integer> newSegments = ImmutableSet.<Integer>builder()
				.add(newSegmentId)
				// MAIN branch uses all his previous segments because he never gets reopened
				.addAll(segments())
				.build();

		final CDOMainBranchImpl main = new CDOMainBranchImpl(baseTimestamp(), headTimestamp(), metadata(), newSegmentId, newSegments);
		main.setBranchManager(getBranchManager());
		return main;
	}

	@Override
	public BranchDocument.Builder toDocument() {
		return super.toDocument()
				.type(TYPE)
				.cdoBranchId(cdoBranchId)
				.segmentId(segmentId)
				.segments(segments);
	}

	static InternalBranch from(BranchDocument doc) {
		return new CDOMainBranchImpl(
				doc.getBaseTimestamp(),
				doc.getHeadTimestamp(),
				doc.getMetadata(),
				doc.getSegmentId(),
				doc.getSegments());
	}

}


text:
![banner](Resources/README/Assets/Banner.png)

[![Release](https://img.shields.io/github/release/graycampbell/GCCalendar.svg)](https://github.com/graycampbell/GCCalendar/releases/latest)
[![CocoaPods](https://img.shields.io/cocoapods/v/GCCalendar.svg)](https://cocoapods.org/pods/GCCalendar)
[![Documentation](https://img.shields.io/badge/docs-100%25-brightgreen.svg)](https://graycampbell.github.io/GCCalendar)
[![Codacy Code Quality](https://img.shields.io/codacy/grade/7ef16773008b4ed9b7798dd3d0da54af.svg)](https://www.codacy.com/app/graycampbell/GCCalendar?utm_source=github.com&utm_medium=referral&utm_content=graycampbell/GCCalendar&utm_campaign=Badge_Grade)
[![Swift 4 Compatible](https://img.shields.io/badge/Swift_4-compatible-4BC51D.svg?style=flat)](https://developer.apple.com/swift)
![Platform](https://img.shields.io/cocoapods/p/GCCalendar.svg?style=flat)
[![License](https://img.shields.io/cocoapods/l/GCCalendar.svg)](https://github.com/graycampbell/GCCalendar/blob/master/LICENSE)

### CocoaPods

```
pod 'GCCalendar'
```

### Implementation

1. Add GCCalendar to your file's import statements.

    ```
    import GCCalendar
    ```

2. Create an instance of GCCalendarView.

    ```
    let calendarView = GCCalendarView()
    ```

3. Set the delegate and the display mode. If you don't set the delegate and the display mode, the calendar will not appear.

    ```
    calendarView.delegate = self
    calendarView.displayMode = .month
    ```

4. Implement GCCalendarViewDelegate.

    ```
    func calendarView(_ calendarView: GCCalendarView, didSelectDate date: Date, inCalendar calendar: Calendar)
    ```

### Documentation

- [Classes](https://graycampbell.github.io/GCCalendar/Classes.html)
  - [GCCalendarView](https://graycampbell.github.io/GCCalendar/Classes/GCCalendarView.html)

- [Enums](https://graycampbell.github.io/GCCalendar/Enums.html)
  - [GCCalendarDisplayMode](https://graycampbell.github.io/GCCalendar/Enums/GCCalendarDisplayMode.html)

- [Protocols](https://graycampbell.github.io/GCCalendar/Protocols.html)
  - [GCCalendarViewDelegate](https://graycampbell.github.io/GCCalendar/Protocols/GCCalendarViewDelegate.html)

### License

GCCalendar is available under the MIT license. See the [LICENSE](https://github.com/graycampbell/GCCalendar/blob/master/LICENSE) file for more info.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    >

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/topline"
        android:textStyle="normal|bold"
        android:textSize="18sp" />

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bottomline" />
</LinearLayout>


text:
package org.literacyapp.authentication.animaloverlay;

import java.io.File;

/**
 * Created by sladomic on 27.12.16.
 */

public class AnimalOverlay {
    private String name;
    private int frameStartX;
    private int frameStartY;
    private int frameEndX;
    private int frameEndY;
    private String soundFile;

    public AnimalOverlay(String name, int frameStartX, int frameStartY, int frameEndX, int frameEndY, String soundFile) {
        this.name = name;
        this.frameStartX = frameStartX;
        this.frameStartY = frameStartY;
        this.frameEndX = frameEndX;
        this.frameEndY = frameEndY;
        this.soundFile = soundFile;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getFrameStartX() {
        return frameStartX;
    }

    public void setFrameStartX(int frameStartX) {
        this.frameStartX = frameStartX;
    }

    public int getFrameStartY() {
        return frameStartY;
    }

    public void setFrameStartY(int frameStartY) {
        this.frameStartY = frameStartY;
    }

    public int getFrameEndX() {
        return frameEndX;
    }

    public void setFrameEndX(int frameEndX) {
        this.frameEndX = frameEndX;
    }

    public int getFrameEndY() {
        return frameEndY;
    }

    public void setFrameEndY(int frameEndY) {
        this.frameEndY = frameEndY;
    }

    public String getSoundFile() {
        return soundFile;
    }

    public void setSoundFile(String soundFile) {
        this.soundFile = soundFile;
    }
}


text:
package quizleague.util.encrypt

object QLSessionInfo {
  val headerName = "ql-session-id"
}


text:
package io.hummer.prefetch.sim.swisscom;

import io.hummer.osm.OpenStreetMap;
import io.hummer.prefetch.context.Path.PathPoint;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Waldemar Hummer
 */
public class NetworkOutagePath {

	public final List<PathPoint> path = new LinkedList<>();

	public double getLengthKM() {
		double length = 0;
		for(int i = 0; i < path.size() - 1; i ++) {
			length += OpenStreetMap.getDistance(
					path.get(i).coordinates.toPoint(),
					path.get(i+1).coordinates.toPoint());
		}
		return length;
	}

}


text:
shouldSearch=true
poolingTime=$1

while [ "$shouldSearch" = true ]
do
	rm content.txt
	echo "Searching... 🔎 "
	curl -sS http://guicheweb.com.br/selecao >> content.txt

	if !(grep -q "
VENDAS ON-LINE ENCERRADA.
" content.txt)
	then
		echo "Tickets are available! 🇧🇷"
		shouldSearch=false
		# TODO: Notify!
	else
		echo "Tickets are not available yet."
	fi

sleep "$poolingTime"
done


text:
Summary:
--------
How can you incorporate IoT into a mobile application? We show you how to build
a mobile application and integrate it with IoT using Octoblu.

## Outline
1. What is IOT?
  - Examples with videos (Mindwave, Reaper, Simple Flow - Blink 1  Twitter?)
1. What is Octoblu?
  1.1 - Intro
  1.2 - Meshblu
  1.3 - Octoblu
  1.4 - Flow engine
  1.5 -Gateblu
  1.6 - Blu
2. Why IoT?
  2.1 Allow automation and interactions based on physical context
  2.2 Provide richer opportunities for user interactions
3. Current State of Mobile and IoT
  3.1 - For Every Device an App
  Vendor lock in - you need the app to use the Device
  3.2 Wearables - tethered to your Phone
  3.3 Beacons - check in time
  3.4 BLE - For you and for me
4. Our Example in Retail - The self checkout application.
  4.1. How it works - Script
5. App components - Tech review
  5.1 MeshbluBeaconKit, MeshbluHttp, Octoblu
  5.2 Show flows
6. Conclusion - You can easily bake IoT into your existing mobile apps


text:
<?xml version="1.0" encoding="utf-8"?>

<openerp>
  <data>
	<record model="account.tax.code.template" id="vat_code_tax">
		<field name="name">Argentina Impuestos</field>
	</record>
		<record model="account.tax.code.template" id="vat_code_base">
			<field name="name">Base Imponible</field>
			<field name="parent_id" ref="vat_code_tax"/>
		</record>
			<record model="account.tax.code.template" id="vat_code_base_sale_parent">
				<field name="name">Base Imponible - Ventas</field>
				<field name="parent_id" ref="vat_code_base"/>
			</record>
				<record model="account.tax.code.template" id="vat_code_base_sale">
					<field name="name">Ventas Gravadas con IVA</field>
					<field name="parent_id" ref="vat_code_base_sale_parent"/>
				</record>
				<record model="account.tax.code.template" id="vat_code_base_sale_exonerada">
					<field name="name">Ventas NO Gravadas (Exoneradas)</field>
					<field name="parent_id" ref="vat_code_base_sale_parent"/>
				</record>
				<record model="account.tax.code.template" id="vat_code_base_sale_fuera">
					<field name="name">Ventas Gravadas Fuera de Ámbito</field>
					<field name="parent_id" ref="vat_code_base_sale_parent"/>
				</record>
			<record model="account.tax.code.template" id="vat_code_base_purchase_parent">
				<field name="name">Base Imponible - Compras</field>
				<field name="parent_id" ref="vat_code_base"/>
			</record>
				<record model="account.tax.code.template" id="vat_code_base_purchase">
					<field name="name">Compras Gravadas con IVA</field>
					<field name="parent_id" ref="vat_code_base_purchase_parent"/>
				</record>
				<record model="account.tax.code.template" id="vat_code_base_purchase_exonerada">
					<field name="name">Compras NO Gravadas (Exoneradas)</field>
					<field name="parent_id" ref="vat_code_base_purchase_parent"/>
				</record>
				<record model="account.tax.code.template" id="vat_code_base_purchase_fuera">
					<field name="name">Compras Gravadas Fuera de Ámbito</field>
					<field name="parent_id" ref="vat_code_base_purchase_parent"/>
				</record>

		<record model="account.tax.code.template" id="vat_code_IVA">
			<field name="name">Impuesto General a las Ventas (IVA) Total a Pagar</field>
			<field name="parent_id" ref="vat_code_tax"/>
		</record>
			<record model="account.tax.code.template" id="vat_code_IVA_pay_parent">
				<field name="name">Impuesto Pagado</field>
				<field name="parent_id" ref="vat_code_IVA"/>
			</record>
				<record model="account.tax.code.template" id="vat_code_IVA_pay">
					<field name="name">Impuesto Pagado IVA</field>
					<field name="parent_id" ref="vat_code_IVA_pay_parent"/>
                    <field name="sign">-1</field>
				</record>
				<record model="account.tax.code.template" id="vat_code_IVA_pay_exonerado">
					<field name="name">Impuesto Pagado de Exonerados al IVA</field>
					<field name="parent_id" ref="vat_code_IVA_pay_parent"/>
                    <field name="sign">-1</field>
				</record>
				<record model="account.tax.code.template" id="vat_code_IVA_pay_fuera">
					<field name="name">Impuesto Pagado Fuera de Ámbito</field>
					<field name="parent_id" ref="vat_code_IVA_pay_parent"/>
                    <field name="sign">-1</field>
				</record>
			<record model="account.tax.code.template" id="vat_code_IVA_receive_parent">
				<field name="name">Impuesto Cobrado</field>
				<field name="parent_id" ref="vat_code_IVA"/>
			</record>
				<record model="account.tax.code.template" id="vat_code_IVA_receive">
					<field name="name">Impuesto Cobrado IVA</field>
					<field name="parent_id" ref="vat_code_IVA_receive_parent"/>
				</record>
				<record model="account.tax.code.template" id="vat_code_IVA_receive_exonerado">
					<field name="name">Impuesto Cobrado de Exonerados al IVA</field>
					<field name="parent_id" ref="vat_code_IVA_receive_parent"/>
				</record>
				<record model="account.tax.code.template" id="vat_code_IVA_receive_fuera">
					<field name="name">Impuesto Cobrado Fuera de Ámbito</field>
					<field name="parent_id" ref="vat_code_IVA_receive_parent"/>
				</record>

		<record model="account.tax.code.template" id="vat_code_renta">
			<field name="name">Impuesto Nacionales a Pagar</field>
			<field name="parent_id" ref="vat_code_tax"/>
		</record>
			<record model="account.tax.code.template" id="vat_code_ganancias">
				<field name="name">Impuesto a las Ganancias a Pagar</field>
				<field name="parent_id" ref="vat_code_renta"/>
			</record>
			<record model="account.tax.code.template" id="vat_code_bienes">
				<field name="name">Impuesto a los Bienes Personales a Pagar</field>
				<field name="parent_id" ref="vat_code_renta"/>
			</record>
			<record model="account.tax.code.template" id="vat_code_presunta">
				<field name="name">Impuesto a la Ganancia Mínima Presunta a Pagar</field>
				<field name="parent_id" ref="vat_code_renta"/>
			</record>
            <record model="account.tax.code.template" id="vat_code_monotributo">
				<field name="name">Monotributo a Pagar</field>
				<field name="parent_id" ref="vat_code_renta"/>
			</record>
  </data>
</openerp>


text:
var ModelRelationsToolBar = function() {
  this.Extends = RelationsToolBar;

	this.initialize = function() {
		this.parent(ModelRelationsToolBar.ID);
	};
};
ModelRelationsToolBar = new Class(new ModelRelationsToolBar());
ModelRelationsToolBar.ID = "modelRelationsToolBar";


text:
Namespace Db.ORM
    Public Class QueryBuilder

        Private _table As Table

        Private _fields As String = ""

        Private _condition As String = ""

        Private _conDic As New Dictionary(Of String, String)

        Private _limit As String = ""

        Private _groupBy As String = ""

        Private _orderBy As String = ""

        Private _joinDic As New Dictionary(Of String, String)

        Private _conString As String = ""

        Public Sub New(ByRef table As Table)
            _table = table
        End Sub

        ''' <summary>
        ''' Ajout des element a selectioner
        ''' </summary>
        ''' <param name="fieldList"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function Fields(ByVal ParamArray fieldList As String()) As QueryBuilder
            '_fields = String.Join(", ", fieldList)
            For Each k As String In fieldList
                AddField(k)
            Next
            Return Me
        End Function

        Dim whereAlreadyCalled As Boolean = False

        ''' <summary>
        ''' Ajoute une clause where a la requete
        ''' </summary>
        ''' <param name="field"></param>
        ''' <param name="fieldValue"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function Where(ByVal field As String, ByVal fieldValue As String) As QueryBuilder
            If whereAlreadyCalled Then
                AndWhere(field, fieldValue)
            Else
                ParseCondition(field, fieldValue)
                whereAlreadyCalled = True
            End If
            Return Me
        End Function

        ''' <summary>
        ''' Ajoute une clause where a la requete
        ''' </summary>
        '''
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function Where(ByVal condition As String) As QueryBuilder
            If _conString.Length > 0 Then
                _conString &= " AND (" & condition & ") "
            Else
                _conString = "(" & condition & ")"
            End If
            Return Me
        End Function

        ''' <summary>
        ''' Parse une condition
        ''' </summary>
        ''' <param name="field"></param>
        ''' <param name="fieldValue"></param>
        ''' <remarks></remarks>
        Private Sub ParseCondition(field As String, fieldValue As String)

            field = field.Trim

            If field.EndsWith(">") Then
                AddCondition(field.Replace(">", ""), ">", fieldValue)
            ElseIf field.EndsWith("<") Then
                AddCondition(field.Replace("<", ""), "<", fieldValue)
            ElseIf field.EndsWith("<>") Then
                AddCondition(field.Replace("<>", ""), "<>", fieldValue)
            ElseIf field.EndsWith("=") Then
                AddCondition(field, "=", fieldValue)
            ElseIf field.EndsWith("!=") Then
                AddCondition(field, "!=", fieldValue)
            ElseIf field.EndsWith("LIKE") Then
                AddCondition(field, "LIKE", fieldValue & "%")
            Else
                AddCondition(field, "=", fieldValue)
            End If
        End Sub

        ''' <summary>
        ''' Ajoute une condition where
        ''' </summary>
        ''' <param name="field"></param>
        ''' <param name="fieldValue"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function AndWhere(ByVal field As String, ByVal fieldValue As String) As QueryBuilder
            _condition &= " AND "
            ParseCondition(field, fieldValue)
            Return Me
        End Function

        ''' <summary>
        ''' Ajoute une condition avec le or
        ''' </summary>
        ''' <param name="field"></param>
        ''' <param name="fieldValue"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function OrWhere(ByVal field As String, ByVal fieldValue As String) As QueryBuilder
            _condition &= " OR "
            ParseCondition(field, fieldValue)
            Return Me
        End Function

        ''' <summary>
        ''' Ajoute une condition a la requete
        ''' </summary>
        ''' <param name="col"></param>
        ''' <param name="oper"></param>
        ''' <param name="value"></param>
        ''' <remarks></remarks>
        Private Sub AddCondition(col As String, oper As String, value As String)
            Dim count = _conDic.Count
            col = col.Trim.Replace(oper, "").Trim
            _conDic.Add(col & count, value)
            _condition &= "(" & col & " " & oper & " @" & col & count & ")"
        End Sub

        Public Overridable Function HaveJoin(tableName As String, condition As String) As QueryBuilder
            _joinDic.Add(tableName, condition)
            Return Me
        End Function

        Public Overridable Function HaveJoin(tableName As String) As QueryBuilder
            If Not tableName.EndsWith("s") Then
                Throw New Exception("La table " & tableName & " doit se terminer par un s")
            End If
            Dim foreignKey As String = tableName.Remove(tableName.Length - 1, 1)
            foreignKey &= "_id"
            Dim condition As String = _table.TableName & "." & foreignKey
            condition &= " = " & tableName & ".id"
            _joinDic.Add(tableName, condition)
            Return Me
        End Function

        Public Overridable Function JoinChild(tableName As String) As QueryBuilder

            If Not _table.TableName.EndsWith("s") Then
                Throw New Exception("La table " & _table.TableName & " doit se terminer par un s")
            End If
            Dim foreignKey As String = _table.TableName.Remove(_table.TableName.Length - 1, 1)
            foreignKey &= "_id"
            Dim condition As String = _table.TableName & ".id"
            condition &= " = " & tableName & "." & foreignKey
            _joinDic.Add(tableName, condition)

            Return Me
        End Function

        Public Function GroupBy(value As String) As QueryBuilder
            _groupBy = value
            Return Me
        End Function

        Public Function OrderBY(value As String) As QueryBuilder
            _orderBy = value
            Return Me
        End Function

        Public Function Limit(limitValue As String) As QueryBuilder
            _limit = limitValue
            Return Me
        End Function

        Private Sub AddField(ByVal field As String)
            If Not field.Contains("AS ") Then
                field = field & " AS '" & field & "'"
            End If
            _fields &= field & ", "
        End Sub

        Public Function GetSqlQuery() As String
            If _fields.Length = 0 Then
                If _table.Fields.Count = 0 Then
                    Throw New Exception("Specifier les champs a selectionner")
                End If
                Dim i As Integer = 0
                For Each k As String In _table.Fields
                    _fields &= k & " AS '" & k & "', "
                Next

            End If

            _fields = _fields.Trim.Trim(",")

            Dim req As String = "SELECT " & _fields & " FROM " & _table.TableName

            If _joinDic.Count > 0 Then
                Dim item As New KeyValuePair(Of String, String)
                For Each item In _joinDic
                    req &= " INNER JOIN " & item.Key & " ON " & item.Value
                Next
            End If

            If _condition.Length > 0 Then
                req &= " WHERE " & _condition
            End If

            If _conString.Length > 0 Then
                If req.Contains("WHERE") Then
                    req &= " AND " & _conString
                Else
                    req &= " WHERE " & _conString & " "
                End If
            End If

            If _groupBy.Length > 0 Then
                req &= " GROUP BY " & _groupBy
            End If

            If _orderBy.Length > 0 Then
                req &= " ORDER BY " & _orderBy
            End If

            If _limit.Length > 0 Then
                req &= " LIMIT " & _limit
            End If

            Return req
        End Function

        ''' <summary>
        ''' Execution de la requete
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function ExecuteStatement() As MySql.Data.MySqlClient.MySqlDataReader

            Try
                Dim req = GetSqlQuery()
                Dim cmd = Database.GetCommand
                cmd.CommandText = req
                cmd.Prepare()

                If _conDic.Count > 0 Then
                    Dim pair As KeyValuePair(Of String, String)
                    For Each pair In _conDic
                        cmd.Parameters.AddWithValue("@" & pair.Key, pair.Value)
                    Next
                End If

                Dim result = cmd.ExecuteReader
                cmd.Dispose()
                Return result
            Catch ex As Exception
                If My.Settings.app_debug_mode Then
                    Util.ShowMessage(ex.ToString)
                Else
                    Util.ShowMessage("Echec de connexion a la base de donnes", 2)
                End If
            End Try
            Return Nothing
        End Function

        Public Function GetParams() As Dictionary(Of String, String)
            Return _conDic
        End Function

        ''' <summary>
        ''' Execute la requete et recuperer un resultat
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function One() As Entity

            Dim entity As New Entity

            Try
                Dim res = ExecuteStatement()

                While res.Read
                    For Each k As String In _fields.Split(",")
                        Dim prop = k.Split("AS")(1)
                        prop = prop.Substring(2).Trim("'")

                        Dim value = res.Item(prop.Trim)
                        If Not TypeOf value Is DBNull Then
                            entity.SetProperty(prop.Trim, value)
                        Else
                            entity.SetProperty(prop.Trim, "")
                        End If

                    Next
                End While
                res.Close()
                res.Dispose()
                Database.CloseConnection()
                Return entity
            Catch ex As Exception
                If My.Settings.app_debug_mode Then
                    Util.ShowMessage(ex.ToString, 2)
                Else
                    Util.ShowMessage("Erreur de lecture des donnees", 2)
                End If
            End Try
        End Function

        ''' <summary>
        ''' Execute la requete et renvoie tous les enregistrements
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function All() As List(Of Entity)

            Dim res = ExecuteStatement()

            Dim backList As New List(Of Entity)

            Try
                While res.Read
                    Dim entity As New Entity
                    For Each k As String In _fields.Split(",")
                        Dim prop = k.Split("AS")(1)
                        prop = prop.Substring(2).Trim("'")

                        Dim value = res.Item(prop.Trim)
                        If Not TypeOf value Is DBNull Then
                            entity.SetProperty(prop.Trim, value)
                        Else
                            entity.SetProperty(prop.Trim, "")
                        End If
                    Next
                    backList.Add(entity)
                End While

                res.Close()
                res.Dispose()
                Database.CloseConnection()
            Catch ex As Exception
                If My.Settings.app_debug_mode Then
                    Util.ShowMessage(ex.ToString)
                Else
                    Util.ShowMessage("Impossible de parcourir les resultats", 2)
                End If
            End Try
            Return backList
        End Function

    End Class
End Namespace


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.NewLines.MultipleBlankLines;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.NewLines.MultipleBlankLines;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.MultipleBlankLines
{
    using Verify = CSharpCodeFixVerifier<
        CSharpMultipleBlankLinesDiagnosticAnalyzer,
        MultipleBlankLinesCodeFixProvider>;

    public class MultipleBlankLinesTests
    {
        [Fact]
        public async Task TestOneBlankLineAtTopOfFile()
        {
            var code =
@"
// comment";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineAtTopOfFile()
        {
            var code =
@"[||]

// comment";
            var fixedCode =
@"
// comment";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineAtTopOfFile_NotWithOptionOff()
        {
            var code =
@"

// comment";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.TrueWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLineAtTopOfFile()
        {
            var code =
@"[||]

// comment";
            var fixedCode =
@"
// comment";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLineAtTopOfFile()
        {
            var code =
@"[||]

// comment";
            var fixedCode =
@"
// comment";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestOneBlankLineAtTopOfEmptyFile()
        {
            var code =
@"
";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLinesAtTopOfEmptyFile()
        {
            var code =
@"[||]

";
            var fixedCode =
@"
";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLinesAtTopOfEmptyFile()
        {
            var code =
@"[||]

";
            var fixedCode =
@"
";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLinesAtTopOfEmptyFile()
        {
            var code =
@"[||]

";
            var fixedCode =
@"
";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestNoBlankLineAtEndOfFile_1()
        {
            var code =
@"class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestNoBlankLineAtEndOfFile_2()
        {
            var code =
@"class C
{
}
";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestOneBlankLineAtEndOfFile()
        {
            var code =
@"class C
{
}

";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineAtEndOfFile()
        {
            var code =
@"class C
{
}
[||]

";
            var fixedCode =
@"class C
{
}

";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLineAtEndOfFile()
        {
            var code =
@"class C
{
}
[||]

";
            var fixedCode =
@"class C
{
}

";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLineAtEndOfFile()
        {
            var code =
@"class C
{
}
[||]

";
            var fixedCode =
@"class C
{
}

";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestNoBlankLineBetweenTokens()
        {
            var code =
@"class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestOneBlankLineBetweenTokens()
        {
            var code =
@"class C
{

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineBetweenTokens()
        {
            var code =
@"class C
{
[||]

}";
            var fixedCode =
@"class C
{

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLineBetweenTokens()
        {
            var code =
@"class C
{
[||]

}";
            var fixedCode =
@"class C
{

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLineBetweenTokens()
        {
            var code =
@"class C
{
[||]

}";
            var fixedCode =
@"class C
{

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestNoBlankLineAfterComment()
        {
            var code =
@"class C
{
    // comment
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestOneBlankLineAfterComment()
        {
            var code =
@"class C
{
    // comment

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineAfterComment()
        {
            var code =
@"class C
{
    // comment
[||]

}";
            var fixedCode =
@"class C
{
    // comment

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLineAfterComment()
        {
            var code =
@"class C
{
    // comment
[||]

}";
            var fixedCode =
@"class C
{
    // comment

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLineAfterComment()
        {
            var code =
@"class C
{
    // comment
[||]

}";
            var fixedCode =
@"class C
{
    // comment

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestNoBlankLineAfterDirective()
        {
            var code =
@"class C
{
    #nullable enable
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestOneBlankLineAfterDirective()
        {
            var code =
@"class C
{
    #nullable enable

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineAfterDirective()
        {
            var code =
@"class C
{
    #nullable enable
[||]

}";
            var fixedCode =
@"class C
{
    #nullable enable

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLineAfterDirective()
        {
            var code =
@"class C
{
    #nullable enable
[||]

}";
            var fixedCode =
@"class C
{
    #nullable enable

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLineAfterDirective()
        {
            var code =
@"class C
{
    #nullable enable
[||]

}";
            var fixedCode =
@"class C
{
    #nullable enable

}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestNoBlankLineAfterDocComment()
        {
            var code =
@"
/// <summary/>
class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestOneBlankLineAfterDocComment()
        {
            var code =
@"
/// <summary/>

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineAfterDocComment()
        {
            var code =
@"
/// <summary/>
[||]

class C
{
}";
            var fixedCode =
@"
/// <summary/>

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLineAfterDocComment()
        {
            var code =
@"
/// <summary/>
[||]

class C
{
}";
            var fixedCode =
@"
/// <summary/>

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLineAfterDocComment()
        {
            var code =
@"
/// <summary/>
[||]

class C
{
}";
            var fixedCode =
@"
/// <summary/>

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestNoBlankLineAllConstructs()
        {
            var code =
@"/// <summary/>
//
#nullable enable
class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestOneBlankLineAllConstructs()
        {
            var code =
@"
/// <summary/>

//

#nullable enable

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = code,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestTwoBlankLineAllConstructs()
        {
            var code =
@"[||]

/// <summary/>

//

#nullable enable

class C
{
}";
            var fixedCode =
@"
/// <summary/>

//

#nullable enable

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestThreeBlankLineAllConstructs()
        {
            var code =
@"[||]

/// <summary/>

//

#nullable enable

class C
{
}";
            var fixedCode =
@"
/// <summary/>

//

#nullable enable

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }

        [Fact]
        public async Task TestFourBlankLineAllConstructs()
        {
            var code =
@"[||]

/// <summary/>

//

#nullable enable

class C
{
}";
            var fixedCode =
@"
/// <summary/>

//

#nullable enable

class C
{
}";

            await new Verify.Test()
            {
                TestCode = code,
                FixedCode = fixedCode,
                LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
                Options = { { CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSuggestionEnforcement } }
            }.RunAsync();
        }
    }
}


text:
package userservice.application.exceptionhandler;

public class ResponseError {
    private final ErrorMessage error;

    public ResponseError(ErrorMessage error) {
        this.error = error;
    }

    public ErrorMessage getError() {
        return error;
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace DebuggerTesting
{
    [Flags]
    public enum SupportedCompiler
    {
        ClangPlusPlus = 0x1,
        GPlusPlus = 0x2,
        VisualCPlusPlus = 0x4,
        XCodeBuild = 0x8
    }
}


text:
package http_metrics_test

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/go-chi/chi"
	"github.com/improbable-eng/go-httpwares"
	"github.com/improbable-eng/go-httpwares/metrics"
	"github.com/improbable-eng/go-httpwares/metrics/prometheus"
	"github.com/improbable-eng/go-httpwares/tags"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

type testReporter struct {
	tracked int

	reqstarted  int
	reqread     int
	respstarted int
	respdone    int

	reqsize  int
	status   int
	respsize int
}

func (r *testReporter) Track(req *http.Request) http_metrics.Tracker {
	r.tracked += 1
	return r
}

func (r *testReporter) RequestStarted() {
	r.reqstarted += 1
}

func (r *testReporter) RequestRead(duration time.Duration, size int) {
	r.reqread += 1
	r.reqsize = size
}

func (r *testReporter) ResponseStarted(duration time.Duration, status int, header http.Header) {
	r.respstarted += 1
	r.status = status
}

func (r *testReporter) ResponseDone(duration time.Duration, status int, size int) {
	r.respdone += 1
	r.respsize = size
}

func handler(t *testing.T, status int, req string, resp string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b, err := ioutil.ReadAll(r.Body)
		assert.NoError(t, err)
		assert.Equal(t, req, string(b))
		r.Body.Close()
		w.WriteHeader(status)
		w.Write([]byte(resp))
	})
}

func TestMiddleware_ReportsAllStats(t *testing.T) {
	r := &testReporter{}
	s := httptest.NewServer(chi.Chain(http_metrics.Middleware(r)).Handler(handler(t, 200, "req-body", "resp-body")))
	defer s.Close()
	resp, err := http.Post(s.URL, "text/plain", bytes.NewBufferString("req-body"))
	require.NoError(t, err)
	require.NoError(t, resp.Body.Close())
	assert.Equal(t, &testReporter{
		tracked:     1,
		reqstarted:  1,
		reqread:     1,
		respstarted: 1,
		respdone:    1,
		reqsize:     8,
		respsize:    9,
		status:      200,
	}, r)
}

func TestTripperware_ReportsAllStats(t *testing.T) {
	r := &testReporter{}
	s := httptest.NewServer(handler(t, 200, "req-body", "resp-body"))
	defer s.Close()
	c := httpwares.WrapClient(http.DefaultClient, http_metrics.Tripperware(r))
	resp, err := c.Post(s.URL, "test/plain", bytes.NewBufferString("req-body"))
	require.NoError(t, err)
	_, err = ioutil.ReadAll(resp.Body)
	require.NoError(t, err)
	require.NoError(t, resp.Body.Close())
	assert.Equal(t, &testReporter{
		tracked:     1,
		reqstarted:  1,
		reqread:     1,
		respstarted: 1,
		respdone:    1,
		reqsize:     8,
		respsize:    9,
		status:      200,
	}, r)
}

func ExampleMiddleware() {
	r := chi.NewRouter()
	r.Use(http_ctxtags.Middleware("default"))
	r.Use(http_metrics.Middleware(http_prometheus.ServerMetrics(http_prometheus.WithLatency())))
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
	})
	http.ListenAndServe(":8888", r)
}

func ExampleTripperware() {
	c := httpwares.WrapClient(
		http.DefaultClient,
		http_ctxtags.Tripperware(),
		http_metrics.Tripperware(http_prometheus.ClientMetrics(http_prometheus.WithName("testclient"))),
	)
	c.Get("example.org/foo")
}


text:
module System.Taffybar.CPUMonitor where

import Data.IORef
import Graphics.UI.Gtk
import System.Information.CPU2 (getCPUInfo)
import System.Information.StreamInfo (getAccLoad)
import System.Taffybar.Widgets.PollingGraph

-- | Creates a new CPU monitor. This is a PollingGraph fed by regular calls to
-- getCPUInfo, associated to an IORef used to remember the values yielded by the
-- last call to this function.
cpuMonitorNew :: GraphConfig -- ^ Configuration data for the Graph.
              -> Double      -- ^ Polling period (in seconds).
              -> String      -- ^ Name of the core to watch (e.g. \"cpu\", \"cpu0\").
              -> IO Widget
cpuMonitorNew cfg interval cpu = do
    info <- getCPUInfo cpu
    sample <- newIORef info
    pollingGraphNew cfg interval $ probe sample cpu

probe :: IORef [Int] -> String -> IO [Double]
probe sample cpuName = do
    load <- getAccLoad sample $ getCPUInfo cpuName
    case load of
      l0:l1:l2:_ -> return [ l0 + l1, l2 ] -- user, system
      _ -> return []


text:
'use strict';

const path      = require('path');
const _         = require('lodash');
const webpack   = require('webpack');

// BASE VERSION OF THE CONFIG. DOES NOT UGLIFY
const base = {

  context: path.resolve(__dirname, './assets'),

  entry: {
    background:       './js/background.js',
    options:          './js/options.js',
    info:             './js/info.js',
    welcome:          './js/welcome.js'
  },

  output: {
    path: path.resolve(__dirname, './chrome/public/js'),
    filename: '[name].js',
  },

  resolve: {
    extensions: ['.js']
  },

  plugins: [],

  module: {
    rules: [
      {
        test: /\.js?$/,
        include: [path.resolve(__dirname, './assets')],
        exclude: [
          path.resolve(__dirname, './node_modules'),
          path.resolve(__dirname, './chrome/public')
        ],
        loader: 'babel-loader',
        options: {
          presets: ['env']
        }
      }
    ]
  }
};

// CLONE THE BASE
const uglified = _.cloneDeep(base);

// ...AND ADD UGLIFY PLUGIN
uglified.plugins.push(
  new webpack.optimize.UglifyJsPlugin({
    compress: true
  })
);

module.exports = {
  uglified: uglified,
  debug:    base
};


text:
package com.intellij.openapi.roots;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;

import java.util.List;
import java.util.Set;

/**
 * Interface providing root information model for a given module.
 * It's implemented by {@link ModuleRootManager}.
 *
 * @author dsl
 */
@ApiStatus.NonExtendable
public interface ModuleRootModel {
  /**
   * Returns the module to which the model belongs.
   *
   * @return the module instance.
   */
  @NotNull
  Module getModule();

  /**
   * Use this method to obtain all content entries of a module. Entries are given in
   * lexicographical order of their paths.
   *
   * @return list of content entries for this module
   * @see ContentEntry
   */
  ContentEntry @NotNull [] getContentEntries();

  /**
   * Use this method to obtain order of roots of a module. Order of entries is important.
   *
   * @return list of order entries for this module
   */
  OrderEntry @NotNull [] getOrderEntries();

  /**
   * Returns the SDK used by the module.
   *
   * @return either module-specific or inherited SDK
   * @see #isSdkInherited()
   */
  @Nullable
  Sdk getSdk();

  /**
   * Returns {@code true} if SDK for this module is inherited from a project.
   *
   * @return true if the SDK is inherited, false otherwise
   * @see ProjectRootManager#getProjectSdk()
   * @see ProjectRootManager#setProjectSdk(Sdk)
   */
  boolean isSdkInherited();

  /**
   * Returns an array of content roots from all content entries.
   *
   * @return the array of content roots.
   * @see #getContentEntries()
   */
  VirtualFile @NotNull [] getContentRoots();

  /**
   * Returns an array of content root urls from all content entries.
   *
   * @return the array of content root URLs.
   * @see #getContentEntries()
   */
  String @NotNull [] getContentRootUrls();

  /**
   * Returns an array of exclude roots from all content entries.
   *
   * @return the array of excluded roots.
   * @see #getContentEntries()
   */
  VirtualFile @NotNull [] getExcludeRoots();

  /**
   * Returns an array of exclude root urls from all content entries.
   *
   * @return the array of excluded root URLs.
   * @see #getContentEntries()
   */
  String @NotNull [] getExcludeRootUrls();

  /**
   * Returns an array of source roots from all content entries.
   *
   * @return the array of source roots.
   * @see #getContentEntries()
   * @see #getSourceRoots(boolean)
   */
  @NotNull VirtualFile @NotNull [] getSourceRoots();

  /**
   * Returns an array of source roots from all content entries.
   *
   * @param includingTests determines whether test source roots should be included in the result
   * @return the array of source roots.
   * @see #getContentEntries()
   */
  VirtualFile @NotNull [] getSourceRoots(boolean includingTests);

  /**
   * Return a list of source roots of the specified type.
   *
   * @param rootType type of source roots
   * @return list of source roots
   */
  @NotNull
  List<VirtualFile> getSourceRoots(@NotNull JpsModuleSourceRootType<?> rootType);

  /**
   * Return a list of source roots which types belong to the specified set.
   *
   * @param rootTypes types of source roots
   * @return list of source roots
   */
  @NotNull
  List<VirtualFile> getSourceRoots(@NotNull Set<? extends JpsModuleSourceRootType<?>> rootTypes);

  /**
   * Returns an array of source root urls from all content entries.
   *
   * @return the array of source root URLs.
   * @see #getContentEntries()
   * @see #getSourceRootUrls(boolean)
   */
  String @NotNull [] getSourceRootUrls();

  /**
   * Returns an array of source root urls from all content entries.
   *
   * @param includingTests determines whether test source root urls should be included in the result
   * @return the array of source root URLs.
   * @see #getContentEntries()
   */
  String @NotNull [] getSourceRootUrls(boolean includingTests);

  /**
   * Passes all order entries in the module to the specified visitor.
   *
   * @param policy       the visitor to accept.
   * @param initialValue the default value to be returned by the visit process.
   * @return the value returned by the visitor.
   * @see OrderEntry#accept(RootPolicy, Object)
   */
  <R> R processOrder(@NotNull RootPolicy<R> policy, R initialValue);

  /**
   * Returns {@link OrderEnumerator} instance which can be used to process order entries of the module (with or without dependencies) and
   * collect classes or source roots.
   *
   * @return {@link OrderEnumerator} instance
   */
  @NotNull
  OrderEnumerator orderEntries();

  /**
   * Returns list of module names <i>this module</i> depends on.
   *
   * @return the list of module names this module depends on.
   */
  String @NotNull [] getDependencyModuleNames();

  <T> T getModuleExtension(@NotNull Class<T> klass);

  Module @NotNull [] getModuleDependencies();

  Module @NotNull [] getModuleDependencies(boolean includeTests);
}