text:
package org.springframework.cloud.contract.maven.verifier;

import java.io.File;

import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystemSession;
import org.springframework.cloud.contract.maven.verifier.stubrunner.AetherStubDownloaderFactory;
import org.springframework.cloud.contract.stubrunner.AetherStubDownloader;
import org.springframework.cloud.contract.stubrunner.ContractDownloader;
import org.springframework.cloud.contract.stubrunner.StubConfiguration;
import org.springframework.cloud.contract.stubrunner.StubDownloader;
import org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder;
import org.springframework.cloud.contract.stubrunner.StubDownloaderBuilderProvider;
import org.springframework.cloud.contract.stubrunner.StubRunnerOptions;
import org.springframework.cloud.contract.stubrunner.StubRunnerOptionsBuilder;
import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
import org.springframework.util.StringUtils;

/**
 * Downloads JAR with contracts
 *
 * @author Marcin Grzejszczak
 * @since 1.0.0
 */
class MavenContractsDownloader {

	private static final String LATEST_VERSION = "+";
	private static final String CONTRACTS_DIRECTORY_PROP = "CONTRACTS_DIRECTORY";

	private final MavenProject project;
	private final Dependency contractDependency;
	private final String contractsPath;
	private final String contractsRepositoryUrl;
	private final boolean contractsWorkOffline;
	private final Log log;
	private final AetherStubDownloaderFactory aetherStubDownloaderFactory;
	private final RepositorySystemSession repoSession;
	private final StubDownloaderBuilderProvider stubDownloaderBuilderProvider;

	MavenContractsDownloader(MavenProject project, Dependency contractDependency,
			String contractsPath, String contractsRepositoryUrl,
			boolean contractsWorkOffline, Log log,
			AetherStubDownloaderFactory aetherStubDownloaderFactory,
			RepositorySystemSession repoSession) {
		this.project = project;
		this.contractDependency = contractDependency;
		this.contractsPath = contractsPath;
		this.contractsRepositoryUrl = contractsRepositoryUrl;
		this.contractsWorkOffline = contractsWorkOffline;
		this.log = log;
		this.aetherStubDownloaderFactory = aetherStubDownloaderFactory;
		this.repoSession = repoSession;
		this.stubDownloaderBuilderProvider = new StubDownloaderBuilderProvider();
	}

	File downloadAndUnpackContractsIfRequired(ContractVerifierConfigProperties config, File defaultContractsDir) {
		String contractsDirFromProp = this.project.getProperties().getProperty(CONTRACTS_DIRECTORY_PROP);
		File downloadedContractsDir = StringUtils.hasText(contractsDirFromProp) ?
				new File(contractsDirFromProp) : null;
		// reuse downloaded contracts from another mojo
		if (downloadedContractsDir != null && downloadedContractsDir.exists()) {
			this.log.info("Another mojo has downloaded the contracts - will reuse them from [" + downloadedContractsDir + "]");
			contractDownloader().updatePropertiesWithInclusion(downloadedContractsDir, config);
			return downloadedContractsDir;
		} else if (shouldDownloadContracts()) {
			this.log.info("Download dependency is provided - will download contract jars");
			File downloadedContracts = contractDownloader().unpackedDownloadedContracts(config);
			this.project.getProperties().setProperty(CONTRACTS_DIRECTORY_PROP, downloadedContracts.getAbsolutePath());
			return downloadedContracts;
		}
		this.log.info("Will use contracts provided in the folder [" + defaultContractsDir + "]");
		return defaultContractsDir;
	}

	private boolean shouldDownloadContracts() {
		return this.contractDependency != null && StringUtils.hasText(this.contractDependency.getArtifactId());
	}

	private ContractDownloader contractDownloader() {
		return new ContractDownloader(stubDownloader(), stubConfiguration(),
				this.contractsPath, this.project.getGroupId(), this.project.getArtifactId());
	}

	private StubDownloader stubDownloader() {
		StubDownloaderBuilder builder = this.stubDownloaderBuilderProvider.get();
		if (StringUtils.hasText(this.contractsRepositoryUrl) || this.contractsWorkOffline) {
			this.log.info("Will download contracts from [" + this.contractsRepositoryUrl + "]. "
					+ "Work offline switch equals to [" + this.contractsWorkOffline + "]");
			if (builder != null) {
				logStubDownloader(builder);
				return builder.build(buildOptions());
			}
			return new AetherStubDownloader(buildOptions());
		}
		this.log.info("Will download contracts using current build's Maven repository setup");
		if (builder != null) {
			logStubDownloader(builder);
			return builder.build(buildOptions());
		}
		return this.aetherStubDownloaderFactory.build(this.repoSession);
	}

	private void logStubDownloader(StubDownloaderBuilder builder) {
		this.log.info("A custom stub downloader [" + builder + "] was provided");
	}

	StubRunnerOptions buildOptions() {
		return new StubRunnerOptionsBuilder()
				.withStubRepositoryRoot(this.contractsRepositoryUrl)
				.withWorkOffline(this.contractsWorkOffline)
				.build();
	}

	private StubConfiguration stubConfiguration() {
		String groupId = this.contractDependency.getGroupId();
		String artifactId = this.contractDependency.getArtifactId();
		String version = StringUtils.hasText(this.contractDependency.getVersion()) ?
				this.contractDependency.getVersion() : LATEST_VERSION;
		String classifier = this.contractDependency.getClassifier();
		return new StubConfiguration(groupId, artifactId, version, classifier);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/app_icon"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="10dp"
        android:background="#163240"
        android:scaleType="centerInside"
        android:contentDescription="@null"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/chronometer_description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/app_icon"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:textSize="14sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/app_icon"
        android:layout_below="@id/chronometer_description"
        android:orientation="horizontal"
        android:weightSum="1">

        <Chronometer
            android:id="@+id/trackChronometer"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:textSize="12sp"
            android:layout_weight="0.99"/>

        <ImageButton
            android:id="@+id/chronometer_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="@dimen/notification_padding_bottom_top"
            android:paddingLeft="@dimen/notification_padding_left_right"
            android:paddingRight="@dimen/notification_padding_left_right"
            android:paddingTop="@dimen/notification_padding_bottom_top"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_notification_pause"
            android:contentDescription="@string/notification_action"
            android:text="@string/notification_pause" />

        <ImageButton
            android:id="@+id/chronometer_stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="@dimen/notification_padding_bottom_top"
            android:paddingLeft="@dimen/notification_padding_left_right"
            android:paddingRight="@dimen/notification_padding_left_right"
            android:paddingTop="@dimen/notification_padding_bottom_top"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_notification_save"
            android:contentDescription="@string/notification_close"
            android:text="@string/notification_close"/>

        <ImageButton
            android:id="@+id/chronometer_close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="@dimen/notification_padding_bottom_top"
            android:paddingLeft="@dimen/notification_padding_left_right"
            android:paddingRight="@dimen/notification_padding_left_right"
            android:paddingTop="@dimen/notification_padding_bottom_top"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_window_close"
            android:contentDescription="@string/notification_submit"
            android:text="@string/notification_submit" />

    </LinearLayout>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
package cz.metacentrum.perun.webgui.tabs.perunadmintabs;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.ui.*;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.client.UiElements;
import cz.metacentrum.perun.webgui.client.localization.ButtonTranslation;
import cz.metacentrum.perun.webgui.client.mainmenu.MainMenu;
import cz.metacentrum.perun.webgui.client.resources.ButtonType;
import cz.metacentrum.perun.webgui.client.resources.PerunSearchEvent;
import cz.metacentrum.perun.webgui.client.resources.SmallIcons;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.JsonUtils;
import cz.metacentrum.perun.webgui.json.ownersManager.DeleteOwner;
import cz.metacentrum.perun.webgui.json.ownersManager.GetOwners;
import cz.metacentrum.perun.webgui.model.Owner;
import cz.metacentrum.perun.webgui.tabs.PerunAdminTabs;
import cz.metacentrum.perun.webgui.tabs.TabItem;
import cz.metacentrum.perun.webgui.tabs.TabItemWithUrl;
import cz.metacentrum.perun.webgui.tabs.UrlMapper;
import cz.metacentrum.perun.webgui.widgets.CustomButton;
import cz.metacentrum.perun.webgui.widgets.ExtendedSuggestBox;
import cz.metacentrum.perun.webgui.widgets.TabMenu;

import java.util.ArrayList;
import java.util.Map;

/**
 * Owners Management for Perun Admin
 *
 * @author Pavel Zlamal <256627@mail.muni.cz>
 * @author Vaclav Mach <374430@mail.muni.cz>
 */
public class OwnersTabItem implements TabItem, TabItemWithUrl {

	/**
	 * Perun web session
	 */
	private PerunWebSession session = PerunWebSession.getInstance();

	/**
	 * Content widget - should be simple panel
	 */
	private SimplePanel contentWidget = new SimplePanel();

	/**
	 * Title widget
	 */
	private Label titleWidget = new Label("Owners");

	/**
	 * Creates a tab instance
	 */
	public OwnersTabItem(){ }

	public boolean isPrepared(){
		return true;
	}

	public Widget draw() {

		// tab content
		final VerticalPanel mainTab = new VerticalPanel();
		mainTab.setSize("100%", "100%");

		// horizontal menu
		TabMenu tabMenu = new TabMenu();
		tabMenu.addWidget(UiElements.getRefreshButton(this));

		final GetOwners owners = new GetOwners();

		final JsonCallbackEvents events = JsonCallbackEvents.refreshTableEvents(owners);

		// create button
		tabMenu.addWidget(TabMenu.getPredefinedButton(ButtonType.CREATE, true, ButtonTranslation.INSTANCE.createOwner(), new ClickHandler() {
			public void onClick(ClickEvent event) {
				session.getTabManager().addTabToCurrentTab(new CreateOwnerTabItem());
			}
		}));

		// remove button
		final CustomButton removeButton = TabMenu.getPredefinedButton(ButtonType.DELETE, ButtonTranslation.INSTANCE.deleteOwner());
		removeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				final ArrayList<Owner> itemsToRemove = owners.getTableSelectedList();
				String text = "Following owners will be removed.";
				UiElements.showDeleteConfirm(itemsToRemove, text, new ClickHandler() {
					@Override
					public void onClick(ClickEvent clickEvent) {
						// TODO - SHOULD HAVE ONLY ONE CALLBACK TO CORE !!
						for (int i=0; i<itemsToRemove.size(); i++ ) {
							DeleteOwner request;
							if(i == itemsToRemove.size() - 1){
								request = new DeleteOwner(JsonCallbackEvents.disableButtonEvents(removeButton, events));
							} else {
								request = new DeleteOwner(JsonCallbackEvents.disableButtonEvents(removeButton));
							}
							request.deleteOwner(itemsToRemove.get(i).getId());
						}
					}
				});
			}}
			);
		tabMenu.addWidget(removeButton);

		tabMenu.addFilterWidget(new ExtendedSuggestBox(owners.getOracle()), new PerunSearchEvent() {
			@Override
			public void searchFor(String text) {
				owners.filterTable(text);
			}
		}, ButtonTranslation.INSTANCE.filterOwners());

		// adding menu to the page
		mainTab.add(tabMenu);
		mainTab.setCellHeight(tabMenu, "30px");

		CellTable<Owner> table = owners.getTable();
		table.addStyleName("perun-table");
		ScrollPanel sp = new ScrollPanel();
		sp.add(table);
		sp.addStyleName("perun-tableScrollPanel");

		mainTab.add(sp);

		removeButton.setEnabled(false);
		JsonUtils.addTableManagedButton(owners, table, removeButton);

		// resize perun table to correct size on screen
		session.getUiElements().resizePerunTable(sp, 350, this);

		this.contentWidget.setWidget(mainTab);

		return getWidget();
	}

	public Widget getWidget() {
		return this.contentWidget;
	}

	public Widget getTitle() {
		return this.titleWidget;
	}

	public ImageResource getIcon() {
		return SmallIcons.INSTANCE.userSilhouetteIcon();
	}

	@Override
	public int hashCode() {
		final int prime = 941;
		int result = 1;
		result = prime * result + 122341;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;

		return true;
	}

	public boolean multipleInstancesEnabled() {
		return false;
	}

	public void open()
	{
		session.getUiElements().getMenu().openMenu(MainMenu.PERUN_ADMIN, true);
		session.getUiElements().getBreadcrumbs().setLocation(MainMenu.PERUN_ADMIN, "Owners", getUrlWithParameters());
	}

	public boolean isAuthorized() {

		if (session.isPerunAdmin()) {
			return true;
		} else {
			return false;
		}

	}

	public final static String URL = "owners";

	public String getUrl()
	{
		return URL;
	}

	public String getUrlWithParameters()
	{
		return PerunAdminTabs.URL + UrlMapper.TAB_NAME_SEPARATOR + getUrl();
	}

	static public OwnersTabItem load(Map<String, String> parameters)
	{
		return new OwnersTabItem();
	}

}


text:
HG_NAMESPACE_START

class GLStateManager
{
    HG_SINGLETON_INSTANCE(GLStateManager);

public:
    void    setClearColor(const KMColor clearColor);

    void    enableBlending();
    void    disableBlending();

    void    bindTexture(GLuint textureID);
    bool    deleteTexture(GLuint textureID);
    void    readOpenglTextureState();

    void    useProgram(GLuint shaderProgramID);

    // vertex buffer handling
    void    bindBuffer(GLuint bufferID);
    void    bindIndexBuffer(GLuint bufferID);
    void    clearBufferBindings();
    bool    deleteBuffer(GLuint bufferID);
    bool    deleteIndexBuffer(GLuint bufferID);

    // frame buffer handling
    void    bindFrameBuffer(GLuint bufferID);
    void    bindRenderBuffer(GLuint bufferID);

private:
    GLuint  mCurrentTexture;
    GLuint  mCurrentShaderProgram;
    GLuint  mCurrentBuffer;
    GLuint  mCurrentIndexBuffer;
    GLuint  mCurrentFrameBuffer;
    GLuint  mCurrentRenderBuffer;

    bool    mBlendingEnabled;

    KMColor mCurrentClearColor;

    HG_SINGLETON_PROPERTY(GLStateManager);
};

HG_NAMESPACE_END


text:
from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index')
)


text:
Contributions to mtools are very welcome. Please check if the particular bug / issue has already been
reported on the [mtools issues](https://github.com/rueckstiess/mtools/issues?state=open) page and create
a new issue if it doesn't exist yet.

### Development Installation

You can install mtools in "development" mode, which will not move it into the Python `site-packages`
directory but keeps it in your local development directory instead. It will still install the necessary
hooks so you will be able to use it like normal, both from Python and the command line. In addition,
you can modify the files directly in your local directory and test the changes right away.

Clone the repository

	cd /your/code/path
    git clone https://github.com/rueckstiess/mtools

Then change into the directory and install in "development" mode

	cd mtools
	sudo python setup.py develop

No changes to your `$PATH` and `$PYTHONPATH` environment variables are needed.

### Branching Model

mtools uses a simplified version of [this git branching model](http://nvie.com/posts/a-successful-git-branching-model/)
by [@nvie](https://twitter.com/nvie).

The [master branch](https://github.com/rueckstiess/mtools) should only ever contain versioned releases. **Do not send
pull requests against the master branch.**

Development happens on the [develop branch](https://github.com/rueckstiess/mtools/tree/develop).

First, fork the [main repository](https://github.com/rueckstiess/mtools) into your own github account (<username>).
Then clone a copy to your local machine:

    git clone https://github.com/<username>/mtools

Now you need to add the upstream repository to pull in the latest changes.

    cd mtools
    git remote add upstream https://github.com/rueckstiess/mtools
    git fetch upstream

To get a local `develop` branch you need to check out and track your remote `develop` branch:

    git checkout -b develop origin/develop

If you want to work on a bug or feature implementation, first pull in the latest changes from upstream:

    git checkout develop
    git pull upstream develop

Then create a feature/bugfix branch that forks off the local `develop` branch:

    git checkout -b feature-37-fast develop

The naming is not that relevant, but it's good practice to start with `feature-` or `bugfix-` and include the issue number
in the branch name (if available).

Now make your changes to the code. Commit as often as you like. Please use meaningful, descriptive git commit messages and
avoid `asdf` or `changed stuff` descriptions.

When you're happy with your changes, push your feature branch to github:

    git push origin feature-37-fast

and raise a pull request against the upstream `develop` branch. Once the code is merged into the `develop` branch,
you can pull the change from upstream develop and then delete your local and github feature/bugfix branch.

    git checkout develop
    git pull upstream develop
    git push origin --delete feature-37-fast
    git branch -d feature-37-fast

### Version Numbers

The versioning standard in mtools is pretty straight-forward. It follows a major.minor.micro version system. We decided to start
mtools at version 1.0.0  (it was already pretty stable and useable at that stage). Bugfixes and minor feature additions are released
as part of micro releases in roughly a two-week cycle:  1.0.0 --> 1.0.1 --> 1.0.2 --> ...

Minor releases will include more significant changes, including interface changes.

I'm not sure yet what a major release constitutes :-)

The development version has the suffix `dev` attached. For example `1.0.1dev` is the development version leading up to `1.0.1` release.

Minor and major releases might have release candidates leading up to the final release. Those are marked with the suffix `rcX` where `X`
is a number starting at 0. For example, version `1.2rc2` is the 3rd release candidate for upcoming release version `1.2`.

Github milestones and git tags are named with a prefix `v`, for example `v1.0.1`.

### Testing

mtools uses the [nose testing framework](https://github.com/nose-devs/nose). You can install it with `sudo pip install nose` or
you can just run the test suite, which will take care of all the testing dependencies:

    python setup.py test

If you want to run the tests manually, go into the `mtools/test/` directory and run `nosetests`. The full test suite may take a while, as
some of the tests have to set up and tear down replica sets and sharded clusters, especially for mlaunch testing. You can skip the slow tests
with this command:

    nosetests -a '!slow'

If you implement a new feature anywhere in mlaunch, please write a test function or test class for the feature. If you fix a bug,
please re-run the test suite after the code change and make sure the tests still pass. Please think carefully before changing
a code and its related test concurrently, so it still tests the expected behavior and not what you consider as "fixed behavior".


text:
---
layout: post97
title:  Data
categories: XAP97
parent: securing-xap-components.html
weight: 100
---

{% summary %}{% endsummary %}

# Secured Space

A secured embedded Space protects access (to data) which is granted only to users with sufficient privileges. When a remote Space proxy connects to a secured Space, it must provide security credentials (usually username and password - see [Custom Security](./custom-security.html) for extensions).

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

{% highlight xml %}
<os-core:space id="space" url="jini://*/*/space">
    <os-core:security username="sa" password="adaw@##$" />
</os-core:space>
{% endhighlight %}

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

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="jini://*/*/space" />
    <property name="securityConfig">
        <bean class="org.openspaces.core.space.SecurityConfig">
            <property name="username" value="sa" />
            <property name="password" value="adaw@##$" />
        </bean>
    </property>
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Code %}

{% highlight java %}
UrlSpaceConfigurer urlSpaceConfigurer = new UrlSpaceConfigurer("jini://*/*/space").userDetails("sa", "adaw@##$");
GigaSpace gigaSpace = new GigaSpaceConfigurer(urlSpaceConfigurer).gigaSpace();
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

An embedded Space may be configured with internal services (Space filters, Notify/Polling Containers, etc.) which must have privileges to operate on the embedded Space. These privileges are propagated by the security credentials provided when creating a Space.

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

{% highlight xml %}
<os-core:space id="space" url="/./space">
    <os-core:security username="sa" password="adaw@##$" />
</os-core:space>
{% endhighlight %}

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

{% highlight xml %}
<bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="/./space" />
    <property name="securityConfig">
        <bean class="org.openspaces.core.space.SecurityConfig">
            <property name="username" value="sa" />
            <property name="password" value="adaw@##$" />
        </bean>
    </property>
</bean>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent Code %}
The security credentials can be either be supplied as an `UserDetails` object or in its simpler form of two Strings (username and password).
These will be used to _implicitly_ create a **`secured`** Space, with security privileges being propagated to internal services.

{% highlight java %}
UrlSpaceConfigurer urlSpaceConfigurer = new UrlSpaceConfigurer("/./space").userDetails("user", "password");
GigaSpace gigaSpace = new GigaSpaceConfigurer(urlSpaceConfigurer).gigaSpace();
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

An embedded Space with no internal services, can be simply configured as secured.

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

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

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

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

{% endtabcontent %}
{% tabcontent Code %}
The **`secured`** Space URL property indicates that the Space being created should be secured.

{% highlight java %}
UrlSpaceConfigurer urlSpaceConfigurer = new UrlSpaceConfigurer("/./space?secured");
GigaSpace gigaSpace = new GigaSpaceConfigurer(urlSpaceConfigurer).gigaSpace();
{% endhighlight %}

The **`secured`** URL property is also exposed as a convenient `.secured(true)` method call.

{% highlight java %}
UrlSpaceConfigurer urlSpaceConfigurer = new UrlSpaceConfigurer("/./space").secured(true);
GigaSpace gigaSpace = new GigaSpaceConfigurer(urlSpaceConfigurer).gigaSpace();
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

For security reasons, you may not want to expose the security credentials in your processing unit XML (pu.xml). These properties can be supplied as deploy time properties (bean level properties).

# Processing Unit

{% refer %}[Configuring Processing Unit Elements](./configuring-processing-unit-elements.html), [Configuring the Space](./the-space-configuration.html){% endrefer %}

A processing unit by itself is not secured. It inherits its security from the managing GSM and GSC. These protect the processing unit from being restarted, relocated, destroyed, and undeployed.

A processing unit (for example a feeder application) may access a secured Space using a remote Space proxy.

{% highlight xml %}
<os-core:space id="mySpace" url="jini://*/*/mySpace">
    <os-core:security username="sa" password="adaw@##$" />
</os-core:space>
{% endhighlight %}

The `username` and `password` can also be supplied using a `pu.properties` file supplied during deployment. If these are supplied, they will be used to _implicitly_ connect to a **`secured`** Space, returning an authenticated proxy for this user.

{% highlight java %}
#pu.properties
security.username=user
security.password=password
{% endhighlight %}

The `security.username` and `security.password` are constant property keys. If you would like to set your own property placeholders, e.g. $\{mySpace.username\} and $\{mySpace.password\}, you will need to use plain XML configuration. These properties would then need to be injected at deploy time, by some property resolver.

{% highlight xml %}
<bean id="mySpace" class="org.openspaces.core.space.UrlSpaceFactoryBean">
    <property name="url" value="jini://*/*/mySpace" />
    <property name="securityConfig">
        <bean class="org.openspaces.core.space.SecurityConfig">
            <property name="username" value="${myusername}" />
            <property name="password" value="${mypassword}" />
        </bean>
    </property>
</bean>

Using the CLI deploy command embed the username and password matching the placeholders given in the pu.xml:
> gs deploy -properties embed://myusername=testing;mypassword=1234 myPU.jar
{% endhighlight %}

## Protecting User/Password {% exclamation %}

Of course, having the username and password exposed (in pu.xml/pu.properties) isn't that "secure". A preferred usage would be to supply the credentials **during deployment**. The _UI_, _CLI_ and _Admin API_ provide a comprehensive support for deploying a secured processing unit (see [Security Administration](./security-administration.html)).

Here is how the CLI deploy command would look like:

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

Using the CLI deploy command supply username and password using the -user and -password.
> gs deploy -secured -user testing -password 1234 myPU.jar
{% endhighlight %}

# Local Cache

{% refer %}[Local Cache](./client-side-caching.html){% endrefer %}

The local cache is a read-only service on top of a remote Space. Thus, the local cache "creator" needs to have **Read** privileges.
Security is enforced by the remote Space, and the proxy should be acquired by supplying the username and password.

{% inittab localcacheview|tablocation=top %}
{% tabcontent  Local Cache Configurer %}

{% highlight java %}
UrlSpaceConfigurer urlSpaceConfigurer = new UrlSpaceConfigurer("jini://*/*/space").userDetails("user", "password");
GigaSpace remoteSpace = new GigaSpaceConfigurer(urlSpaceConfigurer).gigaSpace();

LocalCacheSpaceConfigurer configurer = new LocalCacheSpaceConfigurer(remoteSpace.getSpace()).updateMode(UpdateMode.PULL);
GigaSpace localCache = new GigaSpaceConfigurer(configurer.localCache()).gigaSpace();
{% endhighlight %}

{% endtabcontent %}
{% tabcontent  Local Cache Namespace %}

{% highlight java %}
<os-core:space id="remoteSpace" url="jini://*/*/space" >
    <os-core:security username="user" password="password"/>
</os-core:space>

<os-core:local-cache id="localCacheSpace" space="remoteSpace" update-mode="PULL"/>

<!--
 OpenSpaces simplified Space API built on top of IJSpace/JavaSpace.
-->
<os-core:giga-space id="localCache" space="localCacheSpace"/>
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

# Local View

{% refer %}[Local View](./client-side-caching.html){% endrefer %}

Similar to a Local Cache, the Local View is a read-only service on top of a remote Space. Here, the cache is limited to Views. Thus, the local view "creator" needs to have **Read** privileges for the specific views. For example, needs to have **Read** privileges for both `Trade` and `Stock` classes, otherwise access will be denied.

{% inittab localcacheview|tablocation=top %}
{% tabcontent  Local View Configurer %}

{% highlight java %}
UrlSpaceConfigurer urlSpaceConfigurer = new UrlSpaceConfigurer("jini://*/*/space").userDetails("user", "password");
GigaSpace remoteSpace = new GigaSpaceConfigurer(urlSpaceConfigurer).gigaSpace();

LocalViewSpaceConfigurer configurer = new LocalViewSpaceConfigurer(remoteSpace.getSpace())
 .addView(new View(Trade.class, "quantity = 20"))
 .addView(new View(Stock.class, "stockId => 10"));

GigaSpace localView = new GigaSpaceConfigurer(configurer.localView()).gigaSpace();
{% endhighlight %}

{% endtabcontent %}
{% tabcontent  Local View Namespace %}

{% highlight java %}
<os-core:space id="remoteSpace" url="jini://*/*/space" >
   <os-core:security username="user" password="password"/>
</os-core:space>

<os-core:local-view id="localViewSpace" space="space">
   <os-core:view-query where="quantity = 20" class="...Trade"/>
   <os-core:view-query where="stockId => 10" class="...Stock"/>
</os-core:local-view>

<!--
 OpenSpaces simplified Space API built on top of IJSpace/JavaSpace.
-->
<os-core:giga-space id="localView" space="localViewSpace"/>
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

# Space Filters

{% refer %}[OpenSpaces Space Filter support]./the-space-component.html#SpaceFilters), [Space Filters](./the-space-filters.html){% endrefer %}

Filters are interceptors inside the GigaSpaces Space which allow implementation of user-defined logic based on Space events. Some filters need to perform operations on the embedded Space. If secured, the filter needs to have sufficient privileges for its operations.

The username and password supplied when creating a Space, will be used to _implicitly_ create a **`secured`** Space. The security privileges of the specified user will be propagated to the Filter. If the user has **Read** privileges, then the filter will be able to perform a `space.read(..)` on its embedded Space.

#### Before Authentication operation

A filter can be registered for `before-authentication` events. Before a client tries to authenticate, any filter with the `before-authentication` operation-code will be invoked. The `SpaceContext` supplied as part of the call holds a `SecurityContext` that has the `UserDetails` object.

{% inittab filters|tablocation=top %}
{% tabcontent  Namespace %}
The following Spring configuration registers this filter for `before-authentication` (6) operation:

{% highlight java %}
<bean id="simpleISpaceFilter" class="eg.SimpleISpaceFilter" />

<os-core:space id="space" url="/./space">
    <os-core:security secured="true"/>
    <os-core:space-filter>
        <os-core:filter ref="simpleISpaceFilter" />
        <os-core:operation code="6" />
        ...
    </os-core:space-filter>
</os-core:space>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent  Annotations %}
An example of a simple POJO filter using annotations:

{% highlight java %}
<bean id="simpleFilter" class="eg.SimpleFilter" />

<os-core:space id="space" url="/./space">
	<os-core:security secured="true"/>
	<os-core:annotation-adapter-filter priority="1">
		<os-core:filter ref="simpleFilter" />
	</os-core:annotation-adapter-filter>
</os-core:space>
{% endhighlight %}

**Note** that the annotated method must have the `SpaceContext` as a parameter.

{% highlight java %}
//Delegate Filter
public class SimpleFilter {

    @BeforeAuthentication
    public void beforeAuthenticationMethod(SpaceContext context) {
        SecurityContext securityContext = context.getSecurityContext();
        UserDetails user = securityContext.getUserDetails();
        AuditDetails audit = securityContext.getAuditDetails();
        System.out.println("user: " + user.getUsername() + " connecting from host: " + audit.getHost());
    }

    ...
}
{% endhighlight %}

{% endtabcontent %}
{% tabcontent  Method listings %}
The following Spring configuration XML shows how the filter can be configured, using explicit method listings. (In this case, annotations are not required.)
Note the `before-authentication` method adapter.

{% highlight java %}
<bean id="simpleFilter" class="eg.SimpleFilter" />

<os-core:space id="space" url="/./space">
    <os-core:security secured="true"/>
    <os-core:method-adapter-filter before-authentication="beforeAuthenticationMethod">
        <os-core:filter ref="simpleFilter"/>
    </os-core:method-adapter-filter>
</os-core:space>
{% endhighlight %}

{% endtabcontent %}
{% tabcontent  Embedded-space operations %}

_Implicitly_ create a **`secured`** Space, with security privileges being propagated to the filter.
These privileges need to be sufficient for operations being perform by the filter on the embedded Space.

{% highlight java %}
<!-- pu.xml -->
<bean id="simpleFilter" class="eg.SimpleFilter" />

<os-core:space id="space" url="/./space">
   <os-core:security username="user" password="password"/>
   <os-core:method-adapter-filter filter-init="init"
                                  before-write="beforeWrite">
        <os-core:filter ref="simpleFilter"/>
   </os-core:method-adapter-filter>
</os-core:space>
{% endhighlight %}

The filter acquires a GigaSpaces reference on filter initialization. Now the filter can perform operations on the embedded secured Space.

{% highlight java %}
public class SimpleFilter {

    GigaSpace gigaSpace;

    @OnFilterInit
    void init(IJSpace space) {
        gigaSpace= new GigaSpaceConfigurer(space).gigaSpace();
    }

    @BeforeWrite
    public void beforeWrite(Data data) {
        int seq = gigaSpace.count(new Data()); //Needs 'Read' privileges for 'count' operation
        data.setSeq( seq++);
        data.setTimestamp( new Date());
    }
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

# Custom Access Control

Custom Access control using Space Filters allows for access decisions based on user/role/data relationships. The `SpaceContext` filter invocation parameter holds the `SecurityContext` of the current operation. This context provides you with `UserDetails`, the `Authentication` and `AuditDetails`. Based on these, you can enforce custom access decisions (e.g. allow or disallow the operation).

{% info %}
Note that the `SpaceContext` may be `null` in cases related to replication/recovery and filter operations such as "`notify-trigger`". In these cases, there is no user context.
{%endinfo%}

The filter can be declared just like any other filter, but note that the `priority` plays a role in the order of filter execution. Default priority is zero.

{% highlight java %}
<bean id="customAccessControlFilter" class="example.CustomAccessControlFilter" />

<os-core:space id="space" url="/./space">
	<os-core:security secured="true"/>
	<os-core:annotation-adapter-filter priority="0">
		<os-core:filter ref="customAccessControlFilter" />
	</os-core:annotation-adapter-filter>
</os-core:space>
{% endhighlight %}

Usage examples:

{% inittab customaccess|tablocation=top %}
{% tabcontent  Access based on user name %}

{% highlight java %}
public class CustomAccessControlFilter {
    ...
    @BeforeRead
    public void beforeRead(Account account, int operationCode, SpaceContext context) {
        SecurityContext securityContext = context.getSecurityContext();
        UserDetails user = securityContext.getUserDetails();

        /*
         * only owner of an account can have access to his/her record data
         */
        if (!user.getUsername().equals(account.getOwner())) {
            throw new AccessDeniedException("you are not the account owner!");
        }
    }
...
}
{% endhighlight %}

{% endtabcontent %}
{% tabcontent  Access based on role & field data %}

{% highlight java %}
public class CustomAccessControlFilter {
    ...
    @BeforeWrite
    public void beforeWrite(Account account, int operationCode, SpaceContext context) {
        SecurityContext securityContext = context.getSecurityContext();
        GrantedAuthorities authorities = securityContext.getAuthentication().getGrantedAuthorities();

        /*
         * "accountants" can only create an account with an initial balance of $500
         */
        if (authorities.isUserInRole("accountants") && account.getBalance() > 500) {
            throw new AccessDeniedException("don't be greedy!");
        }
    }
...
}
{% endhighlight %}

{% endtabcontent %}
{% endinittab %}

# Task Execution over the Space

{% refer %}[Executors](./task-execution-over-the-space.html){% endrefer %}

Tasks can be executed in a collocated asynchronous manner within the Space (processing unit with an embedded Space). To execute a task, you must have **Execute** privileges. Execution can be restricted to certain tasks by applying the 'Class-Filter'. There is no need to define specific privileges for operations being performed by the task on the Space.

Here is a simple implementation of a task that performs a 'count' operation on the space.

{% highlight java %}
private static final class MyTask implements Task<Integer> {
   @TaskGigaSpace
   transient GigaSpace gigaSpace;

   public Integer execute() throws Exception {
      return gigaSpace.count(null,null);
   };
}
{% endhighlight %}

While executed tasks are effective when collocated, you may require operations on the Cluster.

{% highlight java %}
GigaSpace clustered = gigaSpace.getClustered();
{% endhighlight %}

{% info %}
Space operations performed from +within+ the task are guarded by a _temporary_ trust available throughout the life-cycle of the task. If you are trying to enforce custom access control, the `SecurityContext` will need to be extracted in a `before-execute` filter call.
{% endinfo %}

# Executors Based Remoting

{% refer %}[Executors Based Remoting](./executor-based-remoting.html){% endrefer %}

Executor Remoting allows you to use remote invocations of POJO services, with the Space as the transport layer using OpenSpaces Executors. To invoke a service method, you must have **Execute** privileges for class `org.openspaces.remoting.ExecutorRemotingTask`.

# Event Driven Remoting

{% refer %}[Event Driven Remoting](./event-driven-remoting.html){% endrefer %}

Event Driven Remoting allows you to use remote invocations of POJO services, with the space as the transport layer using a polling container on the space side to process the invocations. Under the wires, event driven remoting uses the Space write and take capabilities. Thus, you must have **Write* and *Take** privileges (at both ends) for class `org.openspaces.remoting.EventDrivenSpaceRemotingEntry`.

# JDBC Driver

{% refer %}[JDBC Driver](./jdbc-driver.html){% endrefer %}

GigaSpaces allows applications to connect using a JDBC driver. A GigaSpaces JDBC driver accepts SQL statements, translates them to Space operations, and returns standard result sets. To acquire a connection to a remote secured space, provide the credentials (username and password) as parameters to the connection.

{% highlight java %}
Class.forName("com.j_spaces.jdbc.driver.GDriver").newInstance();
String url = "jdbc:gigaspaces:url:jini://*/*/space";
Connection conn = DriverManager.getConnection(url, "user", "password");
Statement st = conn.createStatement();
...
{% endhighlight %}

{% note %}
An alternative way of querying the Space using SQL syntax is the [SQLQuery](./query-sql.html) class, with a privileged GigaSpace proxy.
{%endnote%}


text:
require 'test_helper'

class ArticlesControllerTest < ActionDispatch::IntegrationTest
  test "should get index" do
    get articles_url
    assert_response :success
  end
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace EpheMeral.EventDrivenDesign
{
	/// <summary>
	/// EventAggregator class.
	/// This class represents a multi threaded IEventAggregator implementation
	/// that uses a minimum of reflection and the EventHandler generic delegate type.
	/// This class will fork a triggered event into multiple tasks, each of them being
	/// defined by one of the registered handlers.
	/// For more information see IEventAggregator.
	/// </summary>
	public class ConcurrentEventAggregator : IEventAggregator
	{

		IDictionary<Type, IList<EventHandler<IEvent>>> handlers;

		public ConcurrentEventAggregator()
		{
			handlers = new ConcurrentDictionary<Type, IList<EventHandler<IEvent>>>();
		}

		public void Register(IRegisterable registerable)
		{
			registerable.RegisterMeWith(this);
		}

		public void Register<T>(EventHandler<T> handler) where T : IEvent
		{
			if (!handlers.ContainsKey(typeof(T)))
			{
				handlers[typeof(T)] = new List<EventHandler<IEvent>>();
			}

			var handlerList = handlers[typeof(T)];

			handlerList.Add(evt => handler((T)evt));
		}

		public void Trigger(IEvent evt)
		{
			IList<EventHandler<IEvent>> handlerList;

			if (handlers.TryGetValue(evt.GetType(), out handlerList))
			{
				Parallel.ForEach (handlerList, handler =>
				{
					handler.Invoke(evt);
				});
			}
		}
	}
}


text:
<?php

class LocuTest extends PHPUnit_Framework_TestCase
{

    public static $config = array(
        'api_key' => 'APIKEY'
    );

    public function setUp()
    {
        $stub = $this->getMock(
            'Request',
            array('call'),
            array(self::$config)
        );

        $response = new stdClass;

        $stub->expects($this->any())
            ->method('call')
            ->will($this->returnValue($response));
        $this->Locu = new Locu(self::$config, $stub);
    }

    /**
     * @expectedException Exception
     */
    public function testMissingConfigThrowsException()
    {
        $Locu = new Locu();
    }

    /**
     * @expectedException Exception
     */
    public function testMissingApiKeyThrowsException()
    {
        $config = array();
        $Locu = new Locu($config);
    }

    private function _testCallResponse($method, $params = array())
    {
        return $this->assertTrue( is_object( $this->Locu->$method($params) ) );
    }

    public function testVenueSearch()
    {
        $this->_testCallResponse('venue_search');
    }

    public function testVenueDetails()
    {
        $this->_testCallResponse('venue_details');
    }

    public function testVenueInsights()
    {
        $this->_testCallResponse('venue_insights');
    }

    public function testMenuItemSearch()
    {
        $this->_testCallResponse('menu_item_search');
    }

    public function testMenuItemDetails()
    {
        $this->_testCallResponse('menu_item_detail');
    }

    public function testMenuItemInsight()
    {
        $this->_testCallResponse('menu_item_insight');
    }

}


text:
cordova.define("com.pylonproducts.wifiwizard.WifiWizard", function(require, exports, module) { /*
 * This is the interface for the WifiWizard Phonegap plugin.
 */

var WifiWizard = {

	/**
	 * 	This method formats wifi information into an object for use with the
	 * 	addNetwork function. Currently only supports
	 *		@param SSID			the SSID of the network enclosed in double quotes
	 *		@param password		the password for the network enclosed in double quotes
	 * 	@param algorithm	the authentication algorithm
	 * 	@return	wifiConfig	a JSON object properly formatted for the plugin.
	 */
	formatWifiConfig: function(SSID, password, algorithm) {
		if (algorithm === 'WPA') {
			var wifiConfig = {
				'SSID': WifiWizard.formatWifiString(SSID),
				'auth' : {
					'algorithm' : algorithm,
					'password' : WifiWizard.formatWifiString(password)
					// Other parameters can be added depending on algorithm.
				}
			};
		}
		else if (algorithm === 'New network type') {
			var wifiConfig = {
				'SSID' : WifiWizard.formatWifiString(SSID),
				'auth' : {
					'algorithm' : algorithm,
					// Etc...
				}
			}
		}
		else {
			console.log("Algorithm incorrect")
			return false;
		}
		return wifiConfig;
	},

	/**
	 *	This method is a helper method that returns a wifi object with WPA.
	 */
	formatWPAConfig: function(SSID, password) {
		return formatWifiConfig(SSID, password, 'WPA');
	},

	/**
	 *	This method formats a given SSID and ensures that it is appropriate.
	 *	If the SSID is not wrapped in double quotes, it wraps it in double quotes.
	 * Despite the name, this also needs to be done to WPA PSK.
	 *	@param	ssid	the SSID to format
	 */
	formatWifiString: function(ssid) {
		if (ssid === undefined || ssid === null) {
			ssid = "";
		}
		ssid = ssid.trim()

		if (ssid.charAt(0) != '"' ) {
			ssid = '"' + ssid;
		}

		if (ssid.charAt(ssid.length-1) != '"' ) {
			ssid = ssid + '"';
		}

		return ssid;
	},

	/**
	 * This methods adds a network to the list of available networks.
	 * Currently, only WPA authentication method is supported.
	 *
	 * @param 	wifi is JSON formatted information necessary for adding the Wifi
	 * 			network, as is done in formatWifiConfig.
	 * @param 	win is a callback function that gets called if the plugin is
	 * 			successful.
	 * @param 	fail is a callback function that gets called if the plugin gets
	 * 			an error
	 */
	addNetwork: function(wifi, win, fail) {
		//console.log("WifiWizard add method entered.");
		if (wifi !== null && typeof wifi === 'object') {
			// Ok to proceed!
		}
		else {
			console.log('WifiWizard: Invalid parameter. wifi not an object.');
		}

		var networkInformation = [];

		if (wifi.SSID !== undefined && wifi.SSID !== '') {
			networkInformation.push(wifi.SSID);
		}
		else {
			// i dunno, like, reject the call or something? what are you even doing?
			console.log('WifiWizard: No SSID given.');
			return false;
		}

		if (typeof wifi.auth == 'object') {

			if (wifi.auth.algorithm === 'WPA') {
				networkInformation.push(wifi.auth.algorithm);
				networkInformation.push(wifi.auth.password);
			}
			else if (wifi.auth.algorithm === 'Newly supported type') {
				// Push values in specific order, and implement new type in the Java code.
			}
			else {
				console.log("WifiWizard: authentication invalid.");
			}
		}
		else {
			console.log('WifiWizard: No authentication algorithm given.');
			return false;
		}

		cordova.exec(win, fail, 'WifiWizard', 'addNetwork', networkInformation);
	},

	/**
	 *	This method removes a given network from the list of configured networks.
	 *	@param	SSID	of the network to remove
	 *	@param	win		function to handle successful callback
	 *	@param	fail		function to handle error callback
	 */
	removeNetwork: function(SSID, win, fail) {
		cordova.exec(win, fail, 'WifiWizard', 'removeNetwork', [WifiWizard.formatWifiString(SSID)]);

	},

	/**
	 *	This method connects a network if it is configured.
	 *	@param	SSID	the network to connect
	 *	@param	win		function that is called if successful
	 * @param	fail		function that is called to handle errors
	 */
	connectNetwork: function(SSID, win, fail) {
		cordova.exec(win, fail, 'WifiWizard', 'connectNetwork', [WifiWizard.formatWifiString(SSID)]);
	},

	/**
	 *	This method disconnects a network if it is configured.
	 *	@param	SSID	the network to disconnect
	 *	@param	win		function that is called if successful
	 * @param	fail		function that is called to handle errors
	 */
	disconnectNetwork: function(SSID, win, fail) {
		cordova.exec(win, fail, 'WifiWizard', 'disconnectNetwork', [WifiWizard.formatWifiString(SSID)]);

	},

	/**
	 *	Hands the list of available networks to the `win` success callback function.
	 * @param 	win	callback function that receives list of networks
	 * @param 	fail	callback function if error
	 * @return		a list of networks
	 */
	listNetworks: function(win, fail) {
		if (typeof win != "function") {
			console.log("listNetworks first parameter must be a function to handle list.");
			return;
		}
		cordova.exec(win, fail, 'WifiWizard', 'listNetworks', []);
	}
};

// module.exports = WifiWizard;

});


text:
<?php

namespace Noback\Bundle\DoctrineOrmValueObjectBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;

class NobackDoctrineOrmValueObjectExtension extends Extension
{
    public function load(array $config, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.xml');

        $processedConfig = $this->processConfiguration(new Configuration(), $config);

        $cacheDirectory = $container->getParameterBag()->resolveValue($processedConfig['metadata_cache_dir']);
        $container->setParameter(
            'noback_doctrine_orm_value_object.cache_dir',
            $cacheDirectory
        );

        if (!is_dir($cacheDirectory)) {
            mkdir($cacheDirectory, 0777, true);
        }
    }
}


text:
namespace Structures.ArithmeticTree {
  public class Division : BinaryExpr {

    public Division() { }

    public Division(Expr expr1, Expr expr2) {
      Expr1 = expr1;
      Expr2 = expr2;
    }

    public override string ToString() {
      return $"{Expr1?.ToNestedString()} / {Expr2?.ToNestedString()}";
    }
  }
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['abandoned'] = 'Abandonado';
$string['abstract'] = 'Resumen';
$string['accepted'] = 'Aceptado';
$string['access'] = 'Acceso';
$string['allownotifications_help'] = '
Cuando se habilita, a los participantes se les notifica por correo electrónico cuando cambian datos relevantes para ellos.
';
$string['analysing'] = 'Análisis';
$string['assessment'] = 'Valoración';
$string['assessments'] = 'Valoraciones';
$string['assessmentstart'] = 'Inicio de valoraciones';
$string['assessmentstartevent'] = 'Evento deinicio de valoración';
$string['assessmentstart_help'] = 'Fecha a partir de la que empieza la evaluación del proyecto';
$string['assigneddeliverables'] = 'Entregables asignados';
$string['assignedspecs'] = 'Especificaciones asignadas:';
$string['assignedto'] = 'Asignado a';
$string['assignedwork'] = 'Trabajo asignado:';
$string['august'] = 'Agosto';
$string['autograde'] = 'Auto-calificar';
$string['autogradingenabled'] = 'Habilitar auto-calificación';
$string['autogradingweight'] = 'Peso para la calificación automatizada';
$string['autogradingweight_help'] = '
La auto-calificación se mezclará con las otras calificaciones empleando el factor de peso. Usted puede escribir aquí valores numéricos no-enteros.
';
$string['beta'] = 'Beta';
$string['calculate'] = 'Calcular';
$string['cancel'] = 'Cancelar';
$string['canwait'] = 'Puede esperar';
$string['canwaitdesc'] = 'Esto puede esperar un rato';
$string['choosewhat'] = 'Elegir acción...';
$string['clearall'] = 'Limpiar todo';
$string['close'] = 'Cerrar sesión';
$string['code'] = 'Código';
$string['complete'] = 'Completado';
$string['complexity'] = 'Complejidad';
$string['continue'] = 'Continuar';
$string['copying'] = 'Copiando';
$string['covered'] = 'Cubierto';
$string['covering'] = 'Cubriendo';
$string['created'] = 'Creado';
$string['criteria'] = 'Criterios';
$string['criterion'] = 'Criterio';
$string['criterion_help'] = '
A criterio es una palabra clave para identificar el elemento de calificación. Debería de escribirse como una ficha (token) textual única, sin espacios.
';
$string['december'] = 'Diciembre';
$string['deliverable'] = 'Entregable';
$string['deliverables'] = 'Entregables';
$string['delivered'] = 'entregado';
$string['delivlinks'] = 'Entregables asociados';
$string['deliv_status'] = 'Estatus de entregable';
$string['delivtitle'] = 'Título del entregable';
$string['deliv_to_miles_help'] = '
A un entregable se le puede asignar un logro igual que a una tarea.
Los entregables asignados implican envíos (paso 2) que tendrán que realizarse antes que termine el logro.
';
$string['demomodeclosedproject'] = 'Modo demostración (Proyecto cerrado. Sin edición)';
$string['department'] = 'Departamento';
$string['description'] = 'Descripción';
$string['detail'] = 'Detalle';
$string['difficult'] = 'Dificil';
$string['difficultdesc'] = 'Será unaparte dificil de hacer o de obtener';
$string['done'] = 'Hecho';
$string['enableedit'] = 'Habilitar edición';
$string['endofproject'] = 'Elproyecto ha terminado';
$string['environment'] = 'Entorno';
$string['essential'] = 'Esencial';
$string['evident'] = 'Evidente';
$string['february'] = 'Febrero';
$string['from'] = 'De:';
$string['gantt'] = 'Gant';
$string['ganttchart'] = 'Diagrama Gant';
$string['grade'] = 'Calificación';
$string['grades'] = 'Calificaciones';
$string['grading'] = 'Calificando';
$string['groupoperations'] = 'Operaciones de grupo';
$string['guestsallowed'] = 'Permitirles ver a invitados';
$string['guestscanuse'] = 'Permitirles usar a invitados (demo)';
$string['guestspermissions'] = 'Permisos para invitados';
$string['halfdays'] = 'Medios días';
$string['heavy'] = 'Complejo';
$string['heavyness_help'] = '
El peso es la estimación de la dificultad para proporcionarle los requerimientos al cliente.

Esta medida es diferente de la complejidad, que proporcionará información factual sobre la característica una vez que se haya realizado el análisis. El peso puede no saber exactamente qué solución está disponible que pueda llenar los requisitos, pero expresará la habilidad de estimación basada en experiencia.
';
$string['hours'] = 'Horas';
$string['import'] = 'Importar';
$string['impossible'] = 'Imposible';
$string['introformat'] = 'Formato';
$string['introtechproject'] = 'Descripción';
$string['investigating'] = 'Investigación';
$string['investigation'] = 'Investigación';
$string['itemcriteriaset_help'] = '
Este conjunto de criterios se aplica a elementos evaluables individuales (por ejemplo: una calificación por cada elemento evaluable). Todos los elementos evaluables compartirán la misma definición de conjunto de criterios.

En el paso 1, solamente los logros fechados son evaluables. El paso 2 permitirá definir evaluabilidad para cualquier unidad de entidad.
';
$string['january'] = 'Enero';
$string['july'] = 'Julio';
$string['june'] = 'Junio';
$string['label'] = 'Etiqueta';
$string['label_help'] = '
La etiqueta define el texto visible en la interfaz gráfica del usuario (GUI) cuando se muestra el criterio para usuarios.
';
$string['march'] = 'Marzo';
$string['may'] = 'May';
$string['mean'] = 'Mayo';
$string['medium'] = 'Medio';
$string['missing'] = 'Faltante';
$string['needswork'] = 'A desarrollar';
$string['next'] = 'Siguiente';
$string['norequirements'] = 'Sin requisito';
$string['nospecifications'] = 'Sin especificaciones';
$string['notevaluated'] = 'No evaluado';
$string['notimplementedyet'] = 'No disponible en este lanzamiento';
$string['notprioritary'] = 'No prioritario';
$string['november'] = 'Noviembre';
$string['october'] = 'Octubre';
$string['optional'] = 'Opcional';
$string['other'] = 'Otro';
$string['owner'] = 'Propietario';
$string['parent'] = 'Padre';
$string['phase'] = 'Fase';
$string['prioritary'] = 'Prioritario';
$string['priority'] = 'Prioridad';
$string['project'] = 'Proyecto';
$string['quoted'] = 'Costo estimado';
$string['rationale'] = 'Razonamiento';
$string['realwork'] = 'Trabajo efectivo:';
$string['regression'] = 'Regresión';
$string['requirement'] = 'Requisito';
$string['requirements'] = 'Requisitos';
$string['risk'] = 'Factor de riesgo';
$string['save'] = 'Guardar';
$string['savechanges'] = 'Guardar cambios';
$string['scale'] = 'Escala';
$string['scheduled'] = 'Agendado';
$string['seedetail'] = 'Ver detalle';
$string['selectall'] = 'Seleccionar todo';
$string['september'] = 'Septiembre';
$string['severity'] = 'Severidad';
$string['simple'] = 'Simple';
$string['specifying'] = 'Especificaciones';
$string['starteddesc'] = 'Estamos trabajando en la bestia';
$string['status'] = 'Estatus';
$string['strength_help'] = '
Fuerza es la medida de la importancia del requisito para el cliente.
';
$string['taskdependency'] = 'Depende de';
$string['teacherusescriteria_help'] = '
Cuando se habilita esta opción, la evaluación del proyecto usará un conjunto de criterios definido por el profesor.

Los profesores pondrán el criterio con un panel relevante en la sección de "herramientas del profesor".

Los criterios pueden modificarse aún cuando ya haya empezado la evaluación. Eliminar un criterio eliminará las calificaciones previas para este criterio para todos los espacios de trabajo evaluados.
';
$string['techproject:changedelivs'] = 'Editar entregables';
$string['techproject_help'] = 'Proyecto técnico';
$string['techproject:validate'] = 'Validar';
$string['thedelivs'] = 'Los entregables';
$string['timetocomplete'] = 'Tiempo para completar';
$string['timeunit'] = 'Unidad de tiempo';
$string['title'] = 'Nombre del proyecto';
$string['uncovered'] = 'Descubierto';
$string['update'] = 'actualizar';
$string['uploadfile'] = 'Subir un archivo';
$string['urgent'] = 'Urgente';
$string['urgentdesc'] = 'Urgente';
$string['url'] = 'URL';
$string['useful'] = 'Útil';
$string['verycomplex'] = 'Muy complejo';
$string['wehave'] = 'Disponible';
$string['what'] = '¿Qué?';
$string['writing'] = 'Escribiendo';
$string['writingdesc'] = 'Escribiendo contenidos';


text:
package com.selfservit.util;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.os.SystemClock;

import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import java.io.BufferedReader;
import java.io.File;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class CheckSumService extends Service {
    public Timer setChecksumTimerInterval;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        TimerTask setChecksumTimerIntervalObj;

        // *** CheckSum value Indicator Timer *** //
        setChecksumTimerInterval = new Timer();
        setChecksumTimerIntervalObj = new TimerTask() {
            public void run() {
                try {
                    if (isConnected()) {
                        new CheckSumIndicatorResult().execute();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        setChecksumTimerInterval.schedule(setChecksumTimerIntervalObj, 180000, 180000);

		        return START_STICKY;
    }
    private class CheckSumIndicatorResult extends AsyncTask < String,
            Void,
            String > {
        @ Override
        protected String doInBackground(String...strings) {
            File baseDirectory,
                    checksumFile,
                    userProfileFile;

            BufferedReader checksumFileReader,
                    userProfileFileReader,
                    responseReader;

            String currentLine,
                    checksumFileData,
                    checksumValue,
                    refreshIndValue,
                    userProfileFileData,
                    serverResponseData;

            JSONObject checksumObj,
                    userProfileObj,
                    serverResponseObj;

            JSONArray serverResponseArray;

            URL requestPath;

            HttpURLConnection urlConObj;

            OutputStreamWriter oStreamObj;

            FileWriter writerObj;

            try {

                baseDirectory = Environment.getExternalStorageDirectory();
                checksumFileData = "";
                checksumValue = "";
                refreshIndValue = "";
                userProfileFileData = "";
                serverResponseData = "";

				/* READ THE CHECKSUM VALUE AND GET CHECKSUM AND REFRESH INDICATOR VALUE*/
                checksumFile = new File(baseDirectory, "/mservice/database/checksum_value.txt");
                if (checksumFile.exists()) {
                    checksumFileReader = new BufferedReader(new FileReader(checksumFile));
                    while ((currentLine = checksumFileReader.readLine()) != null) {
                        checksumFileData += currentLine;
                    }
                    checksumFileReader.close();
                    checksumObj = new JSONObject(checksumFileData);
                    checksumValue = checksumObj.optString("checksum_value").toString();
                    refreshIndValue = checksumObj.optString("refresh_ind").toString();
                }

                if (refreshIndValue.matches("") || refreshIndValue.matches("false")) {

					/* READ THE USER PROFILE VALUE */
                    userProfileFile = new File(baseDirectory, "/mservice/user_profile.txt");
                    if (userProfileFile.exists()) {
                        userProfileFileReader = new BufferedReader(new FileReader(userProfileFile));
                        while ((currentLine = userProfileFileReader.readLine()) != null) {
                            userProfileFileData += currentLine;
                        }
                        userProfileFileReader.close();
                        userProfileObj = new JSONObject(userProfileFileData);
                        userProfileObj = userProfileObj.optJSONObject("login_profile");

						/* SEND VALIDATE CHECKSUM REQUEST TO SERVER */
                        requestPath = new URL(userProfileObj.optString("protocol").toString() + "//" + userProfileObj.optString("domain_name").toString() + ":" + userProfileObj.optString("portno").toString() + "/JSONServiceEndpoint.aspx?appName=common_modules&serviceName=retrieve_listof_values_for_searchcondition&path=context/outputparam");
                        urlConObj = (HttpURLConnection)requestPath.openConnection();
                        urlConObj.setDoOutput(true);
                        urlConObj.setRequestMethod("POST");
                        urlConObj.setRequestProperty("CONTENT-TYPE", "application/json");
                        urlConObj.connect();

                        oStreamObj = new OutputStreamWriter(urlConObj.getOutputStream());
                        oStreamObj.write("{\"context\":{\"sessionId\":" + "\"" + userProfileObj.optString("guid_val").toString() + "\"" + ",\"userId\":" + "\"" + userProfileObj.optString("user_id").toString() + "\"" + ",\"client_id\":" + "\"" + userProfileObj.optString("client_id").toString() + "\"" + ",\"locale_id\":" + "\"" + userProfileObj.optString("locale_id").toString() + "\"" + ",\"country_code\":" + "\"" + userProfileObj.optString("country_code").toString() + "\"" + ",\"inputparam\":{\"p_inputparam_xml\":\"<inputparam><lov_code_type>VALIDATE_CHECKSUM</lov_code_type><search_field_1>" + checksumValue + "</search_field_1><search_field_2>" + userProfileObj.optString("emp_id").toString() + "</search_field_2><search_field_3>MOBILE</search_field_3></inputparam>\"}}}");
                        oStreamObj.flush();
                        oStreamObj.close();

						/* READ THE SERVER RESPONSE AND WRITE TO THE FILE */
                        responseReader = new BufferedReader(new InputStreamReader(urlConObj.getInputStream()));
                        while ((currentLine = responseReader.readLine()) != null) {
                            serverResponseData += currentLine;
                        }
                        responseReader.close();
                        urlConObj.disconnect();

                        serverResponseArray = new JSONArray(serverResponseData);
                        serverResponseObj = serverResponseArray.optJSONObject(0);
                        writerObj = new FileWriter(checksumFile);
                        writerObj.write(serverResponseObj.toString());
                        writerObj.flush();
                        writerObj.close();
                        String date,
                                hour,
                                minute;
                        date = serverResponseObj.optString("serverDate").toString();
                        hour = serverResponseObj.optString("serverHour").toString();
                        minute = serverResponseObj.optString("serverMinute").toString();
                        new mInterfaceUtil().refreshTimeProfile(date, hour, minute);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    /* USER CLEARED APP FROM CACHE */
    @ Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        if (setChecksumTimerInterval != null) {
            setChecksumTimerInterval.cancel();
        }
        Intent restartService = new Intent(getApplicationContext(),
                this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI);
    }
    /* WHEN THE RAM IS LOW */
    @ Override
    public void onLowMemory() {
        super.onLowMemory();
        if (setChecksumTimerInterval != null) {
            setChecksumTimerInterval.cancel();
        }
        startService(new Intent(getApplicationContext(), CheckSumService.class));
    }
    /* USER CLICK FORCE STOP IN SETTINGS */
    @ Override
    public void onDestroy() {
        super.onDestroy();
        if (setChecksumTimerInterval != null) {
            setChecksumTimerInterval.cancel();
        }
        startService(new Intent(getApplicationContext(), CheckSumService.class));
    }
    public boolean isConnected() {
        ConnectivityManager online = (ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = online.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}


text:
namespace PrimusFlex.Web.Common.DAL
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    using PrimusFlex.Data.Common;
    using PrimusFlex.Data.Models;

    public class ItemData
    {
        private IDbRepository<Item> items;

        public ItemData(IDbRepository<Item> items)
        {
            this.items = items;
        }

        public IEnumerable<SelectListItem> GetAllItemsAsSelectListItems()
        {
            return this.items.All()
                        .OrderBy(i => i.Name)
                        .Select(i => new SelectListItem()
                        {
                            Text = i.Name,
                            Value = i.Id.ToString()
                        })
                        .ToList();
        }
    }
}