text:
package org.cytoscape.rest.internal.resource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.cytoscape.io.write.CyWriter;
import org.cytoscape.io.write.VizmapWriterFactory;
import org.cytoscape.rest.internal.CyActivator.WriterListener;
import org.cytoscape.rest.internal.MappingFactoryManager;
import org.cytoscape.rest.internal.datamapper.VisualStyleMapper;
import org.cytoscape.rest.internal.serializer.VisualStyleModule;
import org.cytoscape.rest.internal.serializer.VisualStyleSerializer;
import org.cytoscape.rest.internal.task.HeadlessTaskMonitor;
import org.cytoscape.view.model.DiscreteRange;
import org.cytoscape.view.model.Range;
import org.cytoscape.view.model.VisualLexicon;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.vizmap.VisualMappingFunction;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.work.TaskMonitor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Singleton
@Path("/v1/styles")
public class StyleResource extends AbstractResource {

	private final VisualStyleSerializer styleSerializer = new VisualStyleSerializer();

	@Context
	private WriterListener writerListener;

	@Context
	private TaskMonitor tm;

	@Context
	private VisualStyleFactory vsFactory;

	@Context
	private MappingFactoryManager factoryManager;

	private final ObjectMapper styleMapper;
	private final VisualStyleMapper visualStyleMapper;
	private final VisualStyleSerializer visualStyleSerializer;

	public StyleResource() {
		super();
		this.styleMapper = new ObjectMapper();
		this.styleMapper.registerModule(new VisualStyleModule());

		this.visualStyleMapper = new VisualStyleMapper();
		this.visualStyleSerializer = new VisualStyleSerializer();
	}

	/**
	 *
	 * @summary Get list of Visual Style titles
	 *
	 * @return List of Visual Style titles.
	 */
	@GET
	@Path("/")
	@Produces(MediaType.APPLICATION_JSON)
	public String getStyleNames() {
		final Collection<VisualStyle> styles = vmm.getAllVisualStyles();
		final List<String> styleNames = new ArrayList<String>();
		for (final VisualStyle style : styles) {
			styleNames.add(style.getTitle());
		}
		try {
			return getNames(styleNames);
		} catch (IOException e) {
			throw getError("Could not get style names.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}

	}

	/**
	 * @summary Get number of Visual Styles
	 *
	 * @return Number of Visual Styles available in current session.
	 *
	 */
	@GET
	@Path("/count")
	@Produces(MediaType.APPLICATION_JSON)
	public String getStylCount() {
		return getNumberObjectString(JsonTags.COUNT, vmm.getAllVisualStyles().size());
	}

	/**
	 *
	 * @summary Delete a Visual Style
	 *
	 * @param name
	 */
	@DELETE
	@Path("/{name}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteStyle(@PathParam("name") String name) {
		vmm.removeVisualStyle(getStyleByName(name));
		return Response.ok().build();
	}

	/**
	 * @summary Delete all Visual Styles except default style
	 *
	 */
	@DELETE
	@Path("/")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteAllStyles() {
		Set<VisualStyle> styles = vmm.getAllVisualStyles();
		Set<VisualStyle> toBeDeleted = new HashSet<VisualStyle>();
		for(final VisualStyle style: styles) {
			if(style.getTitle().equals("default") == false) {
				toBeDeleted.add(style);
			}
		}
		toBeDeleted.stream()
			.forEach(style->vmm.removeVisualStyle(style));
		return Response.ok().build();
	}

	/**
	 *
	 * @summary Delete a Visual Mapping from a Visual Style
	 *
	 * @param name Name of the Visual Style
	 * @param vpName Visual Property name associated with the mapping
	 *
	 */
	@DELETE
	@Path("/{name}/mappings/{vpName}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteMapping(@PathParam("name") String name, @PathParam("vpName") String vpName) {
		final VisualStyle style = getStyleByName(name);
		final VisualProperty<?> vp = getVisualProperty(vpName);
		if(vp == null) {
			throw new NotFoundException("Could not find Visual Property: " + vpName);
		}
		final VisualMappingFunction<?,?> mapping = style.getVisualMappingFunction(vp);
		if(mapping == null) {
			throw new NotFoundException("Could not find mapping for: " + vpName);
		}
		style.removeVisualMappingFunction(vp);

		return Response.ok().build();
	}

	/**
	 *
	 * @summary Get all default values for the Visual Style
	 *
	 * @param name Name of the Visual Style
	 *
	 * @return List of all default values
	 *
	 */
	@GET
	@Path("/{name}/defaults")
	@Produces(MediaType.APPLICATION_JSON)
	public String getDefaults(@PathParam("name") String name) {
		return serializeDefaultValues(name);
	}

	/**
	 *
	 * @summary Get a default value for the Visual Property
	 *
	 * @param name Name of Visual Style
	 * @param vp Unique ID of the Visual Property.  This should be the unique ID of the VP.
	 *
	 * @return Default value for the Visual Property
	 *
	 */
	@GET
	@Path("/{name}/defaults/{vp}")
	@Produces(MediaType.APPLICATION_JSON)
	public String getDefaultValue(@PathParam("name") String name, @PathParam("vp") String vp) {
		return serializeDefaultValue(name, vp);
	}

	/**
	 * This method is only for Visual Properties with DiscreteRange, such as
	 * NODE_SHAPE or EDGE_LINE_TYPE.
	 *
	 * @summary Get all available range values for the Visual Property
	 *
	 * @param vp Visual Property ID
	 *
	 * @return List of all available values for the visual property.
	 */
	@GET
	@Path("/visualproperties/{vp}/values")
	@Produces(MediaType.APPLICATION_JSON)
	public String getRangeValues(@PathParam("vp") String vp) {
		return serializeRangeValue(vp);
	}

	/**
	 * @summary Get all available Visual Properties
	 *
	 * @return Array of Visual Properties
	 *
	 */
	@GET
	@Path("/visualproperties")
	@Produces(MediaType.APPLICATION_JSON)
	public String getVisualProperties() {
		final Set<VisualProperty<?>> vps = getAllVisualProperties();
		try {
			return styleSerializer.serializeVisualProperties(vps);
		} catch (IOException e) {
			e.printStackTrace();
			throw getError("Could not serialize Visual Properties.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * @summary Get a Visual Property
	 *
	 * @param visualProperty Target Visual Property ID
	 *
	 * @return Visual Property as object
	 */
	@GET
	@Path("/visualproperties/{visualProperty}")
	@Produces(MediaType.APPLICATION_JSON)
	public String getSingleVisualProperty(@PathParam("visualProperty") String visualProperty) {
		final VisualProperty<?> vp = getVisualProperty(visualProperty);
		try {
			return styleSerializer.serializeVisualProperty(vp);
		} catch (IOException e) {
			throw getError("Could not serialize Visual Properties.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 *
	 * @summary Get all Visual Mappings for the Visual Style
	 *
	 * @param name Name of the Visual Style
	 *
	 * @return List of all Visual Mappings.
	 *
	 */
	@GET
	@Path("/{name}/mappings")
	@Produces(MediaType.APPLICATION_JSON)
	public String getMappings(@PathParam("name") String name) {
		final VisualStyle style = getStyleByName(name);
		final Collection<VisualMappingFunction<?, ?>> mappings = style.getAllVisualMappingFunctions();
		if(mappings.isEmpty()) {
			return "[]";
		}

		try {
			return styleMapper.writeValueAsString(mappings);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			throw getError("Could not serialize Mappings.", e, Response.Status.INTERNAL_SERVER_ERROR);
		} catch(Exception ex) {
			ex.printStackTrace();
			throw getError("Could not serialize Mappings.", ex, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 *
	 * @summary Get a Visual Mapping associated with the Visual Property
	 *
	 * @param name Name of the Visual Style
	 * @param vp Unique ID of the Visual Property.  This should be the unique ID of the VP.
	 *
	 * @return Visual Mapping assigned to the Visual Property
	 *
	 */
	@GET
	@Path("/{name}/mappings/{vp}")
	@Produces(MediaType.APPLICATION_JSON)
	public String getMapping(@PathParam("name") String name, @PathParam("vp") String vp) {
		final VisualStyle style = getStyleByName(name);
		final VisualMappingFunction<?, ?> mapping = getMappingFunction(vp, style);

		try {
			return styleMapper.writeValueAsString(mapping);
		} catch (JsonProcessingException e) {
			throw getError("Could not serialize Mapping.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	private final VisualMappingFunction<?, ?> getMappingFunction(final String vp, final VisualStyle style) {
		final VisualLexicon lexicon = getLexicon();
		final Set<VisualProperty<?>> allVp = lexicon.getAllVisualProperties();
		VisualProperty<?> visualProp = null;
		for (VisualProperty<?> curVp : allVp) {
			if (curVp.getIdString().equals(vp)) {
				visualProp = curVp;
				break;
			}
		}
		if (visualProp == null) {
			throw new NotFoundException("Could not find VisualProperty: " + vp);
		}
		final VisualMappingFunction<?, ?> mapping = style.getVisualMappingFunction(visualProp);

		if(mapping == null) {
			throw new NotFoundException("Could not find visual mapping function for " + vp);
		}

		return mapping;
	}

	private final String serializeDefaultValues(String name) {
		final VisualStyle style = getStyleByName(name);
		final VisualLexicon lexicon = getLexicon();
		final Collection<VisualProperty<?>> vps = lexicon.getAllVisualProperties();
		try {
			return styleSerializer.serializeDefaults(vps, style);
		} catch (IOException e) {
			throw getError("Could not serialize default values.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	private final String serializeDefaultValue(final String styleName, final String vpName) {
		final VisualStyle style = getStyleByName(styleName);
		VisualProperty<Object> vp = (VisualProperty<Object>) getVisualProperty(vpName);
		try {
			return styleSerializer.serializeDefault(vp, style);
		} catch (IOException e) {
			throw getError("Could not serialize default value for " + vpName, e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	private final String serializeRangeValue(final String vpName) {
		VisualProperty<Object> vp = (VisualProperty<Object>) getVisualProperty(vpName);
		Range<Object> range = vp.getRange();
		if (range.isDiscrete()) {
			final DiscreteRange<Object> discRange = (DiscreteRange<Object>)range;
			try {
				return styleSerializer.serializeDiscreteRange(vp, discRange);
			} catch (IOException e) {
				throw getError("Could not serialize default value for "
						+ vpName, e, Response.Status.INTERNAL_SERVER_ERROR);
			}
		} else {
			throw new NotFoundException("Range object is not available for " + vpName);
		}
	}

	private final Set<VisualProperty<?>> getAllVisualProperties() {
		final VisualLexicon lexicon = getLexicon();
		return lexicon.getAllVisualProperties();
	}

	private final VisualProperty<?> getVisualProperty(String vpName) {
		final VisualLexicon lexicon = getLexicon();
		final Collection<VisualProperty<?>> vps = lexicon.getAllVisualProperties();
		for (VisualProperty<?> vp : vps) {
			if (vp.getIdString().equals(vpName)) {
				return vp;
			}
		}

		return null;
	}

	// /////////// Update Default Values ///////////////

	/**
	 *
	 * @summary Update a default value for the Visual Property
	 *
	 * The body of the request should be a list of key-value pair:
	 *

	 * 		[
	 * 			{
	 * 				"visualProperty": VISUAL_PROPERTY_ID,
	 * 				"value": value
	 * 			}, ...
	 * 		]
	 *

	 *
	 * @param name Name of the Visual Style
	 *
	 */
	@PUT
	@Path("/{name}/defaults")
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateDefaults(@PathParam("name") String name, InputStream is) {
		final VisualStyle style = getStyleByName(name);
		final ObjectMapper objMapper = new ObjectMapper();
		try {
			final JsonNode rootNode = objMapper.readValue(is, JsonNode.class);
			updateVisualProperties(rootNode, style);
		} catch (Exception e) {
			throw getError("Could not update default values.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}

		return Response.ok().build();
	}

	@SuppressWarnings("unchecked")
	private final void updateVisualProperties(final JsonNode rootNode, VisualStyle style) {
		for(JsonNode defaultNode: rootNode) {
			final String vpName = defaultNode.get(VisualStyleMapper.MAPPING_VP).textValue();

			@SuppressWarnings("rawtypes")
			final VisualProperty vp = getVisualProperty(vpName);
			if (vp == null) {
				continue;
			}
			final Object value = vp.parseSerializableString(defaultNode.get("value").asText());
			if(value != null) {
				style.setDefaultValue(vp, value);
			}
		}
	}

	/**
	 *
	 * @summary Get a Visual Style in Cytoscape.js CSS format.
	 *
	 * @param name Name of the Visual Style
	 *
	 * @return Visual Style in Cytoscape.js CSS format.  This is always in an array.
	 *
	 */
	@GET
	@Path("/{name}.json")
	@Produces(MediaType.APPLICATION_JSON)
	public String getStyle(@PathParam("name") String name) {
		if(networkViewManager.getNetworkViewSet().isEmpty()) {
			throw getError("You need at least one view object to use this feature."
					, new IllegalStateException(), Response.Status.INTERNAL_SERVER_ERROR);
		}
		final VisualStyle style = getStyleByName(name);
		final VizmapWriterFactory jsonVsFact = this.writerListener.getFactory();
		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		final Set<VisualStyle> styleCollection = new HashSet<VisualStyle>();
		styleCollection.add(style);
		try {
			final CyWriter styleWriter = jsonVsFact.createWriter(os, styleCollection);
			styleWriter.run(new HeadlessTaskMonitor());
			String jsonString = os.toString("UTF-8");
			os.close();
			return jsonString;
		} catch (Exception e) {
			throw getError("Could not get Visual Style in Cytoscape.js format.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 *
	 * This returns JSON version of Visual Style object with full details.  Format is simple:
	 *
	 *

	 * {
	 * 	"title": (name of this Visual Style),
	 * 	"defaults": [ default values ],
	 * 	"mappings": [ Mappings ]
	 * }
	 *

	 *
	 * Essentially, this is a JSON version of the Visual Style XML file.
	 *
	 *
	 * @summary Get a Visual Style with full details
	 *
	 * @param name Name of the Visual Style
	 *
	 * @return Visual Style in Cytoscape JSON format
	 */
	@GET
	@Path("/{name}")
	@Produces(MediaType.APPLICATION_JSON)
	public String getStyleFull(@PathParam("name") String name) {
		final VisualStyle style = getStyleByName(name);
		try {
			return styleSerializer.serializeStyle(getLexicon().getAllVisualProperties(), style);
		} catch (IOException e) {
			throw getError("Could not get Visual Style JSON.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * @summary Create a new Visual Style from JSON.
	 *
	 * @return Title of the new Visual Style.
	 */
	@POST
	@Path("/")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response createStyle(InputStream is) {
		final ObjectMapper objMapper = new ObjectMapper();
		JsonNode rootNode;
		try {
			rootNode = objMapper.readValue(is, JsonNode.class);
			VisualStyle style = this.visualStyleMapper.buildVisualStyle(factoryManager, vsFactory, getLexicon(),
					rootNode);
			vmm.addVisualStyle(style);

			// This may be different from the original one if same name exists.
			final String result = "{\"title\": \""+ style.getTitle() + "\"}";

			return Response.status(Response.Status.CREATED).entity(result).build();
		} catch (Exception e) {
			throw getError("Could not create new Visual Style.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 *
	 * Create a new Visual Mapping function from JSON and add it to the Style.
	 *
	 *
Discrete Mapping

	 *
Continuous Mapping

	 *
Passthrough Mapping

	 *
	 * @summary Add a new Visual Mapping
	 *
	 * @param name Name of the Visual Style
	 */
	@POST
	@Path("/{name}/mappings")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response createMappings(@PathParam("name") String name,InputStream is) {
		final VisualStyle style = getStyleByName(name);
		final ObjectMapper objMapper = new ObjectMapper();
		JsonNode rootNode;
		try {
			rootNode = objMapper.readValue(is, JsonNode.class);
			this.visualStyleMapper.buildMappings(style, factoryManager, getLexicon(),rootNode);
		} catch (Exception e) {
			e.printStackTrace();
			throw getError("Could not create new Mapping.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}

		return Response.status(Response.Status.CREATED).build();
	}

	/**
	 *
	 * @summary Update name of a Visual Style
	 *
	 * @param name Original name of the Visual Style
	 *
	 */
	@PUT
	@Path("/{name}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public void updateStyleName(@PathParam("name") String name, InputStream is) {
		final VisualStyle style = getStyleByName(name);
		final ObjectMapper objMapper = new ObjectMapper();
		JsonNode rootNode;
		try {
			rootNode = objMapper.readValue(is, JsonNode.class);
			this.visualStyleMapper.updateStyleName(style, getLexicon(), rootNode);
		} catch (Exception e) {
			throw getError("Could not update Visual Style title.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * Currently, this is same as POST; it simply replaces existing mapping.
	 * You need to send complete information for the new mappings.
	 *
	 * @summary Update an existing Visual Mapping
	 *
	 * @param name Name of visual Style
	 * @param vp Target Visual Property
	 *
	 */
	@PUT
	@Path("/{name}/mappings/{vp}")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response updateMapping(@PathParam("name") String name,  @PathParam("vp") String vp, InputStream is) {
		final VisualStyle style = getStyleByName(name);
		final VisualMappingFunction<?, ?> currentMapping = getMappingFunction(vp, style);

		final ObjectMapper objMapper = new ObjectMapper();
		JsonNode rootNode;
		try {
			rootNode = objMapper.readValue(is, JsonNode.class);
			this.visualStyleMapper.buildMappings(style, factoryManager, getLexicon(),rootNode);
		} catch (Exception e) {
			e.printStackTrace();
			throw getError("Could not update Mapping.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}

		return Response.ok().build();
	}

	private final VisualStyle getStyleByName(final String name) {
		final Collection<VisualStyle> styles = vmm.getAllVisualStyles();
		for (final VisualStyle style : styles) {
			if (style.getTitle().equals(name)) {
				return style;
			}
		}

		throw new NotFoundException("Could not find Visual Style: " + name);
	}

	/**
	 *
	 * Check status of Visual Property Dependencies.  If a dependency is enables, it has true for "enabled."
	 *
	 * @summary Get all Visual Property Dependency status
	 *
	 * @param name Name of the Visual Style
	 *
	 * @return List of the status of all Visual Property dependencies.
	 *
	 */
	@GET
	@Path("/{name}/dependencies")
	@Produces(MediaType.APPLICATION_JSON)
	public String getAllDependencies(@PathParam("name") String name) {
		final VisualStyle style = getStyleByName(name);

		final Set<VisualPropertyDependency<?>> dependencies = style.getAllVisualPropertyDependencies();
		try {
			return visualStyleSerializer.serializeDependecies(dependencies);
		} catch (IOException e) {
			throw getError("Could not get Visual Property denendencies.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 *
	 * The body should be the following format:
	 *

	 * [
	 * 	{
	 * 		"visualPropertyDependnecy" : "DEPENDENCY_ID",
	 * 		"enabled" : true or false
	 * 	}, ... {}
	 * ]
	 *

	 *
	 * @summary Set Visual Property Dependency flags
	 *
	 * @param name Name of Visual Style
	 *
	 */
	@PUT
	@Path("/{name}/dependencies")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public void updateDependencies(@PathParam("name") String name, InputStream is) {
		final VisualStyle style = getStyleByName(name);

		final ObjectMapper objMapper = new ObjectMapper();
		JsonNode rootNode;
		try {
			rootNode = objMapper.readValue(is, JsonNode.class);
			this.visualStyleMapper.updateDependencies(style, rootNode);
		} catch (Exception e) {
			throw getError("Could not update Visual Style title.", e, Response.Status.INTERNAL_SERVER_ERROR);
		}
	}
}


text:
Drivers

                    Username Filter:

                    <input type="text" class="form-control" placeholder ="Filter" ng-model="search" ng-change="loadPage()" />

                    Page:

                    <input type="text" class="form-control" ng-model="page" ng-change="loadPage()"/>

    <form class="form">

                Name
                Upcoming Trips
                Total Trips

                {{driver.name}}
                {{driver.numberOfUpcomingTrips}}
                {{driver.numberOfTotalTrips}}

    </form>

redpajama_set_name: RedPajamaGithub


text:
#ifndef SCIDB_H
#define SCIDB_H

#include <string>

#include "../format/format.h"
#include "scidbAttribute.h"

class SciDB: public Format {

public:
	virtual ~SciDB();

	/**
	 * Initialize the SciDB format.
	 *
	 * @mode read or write (mode how to open the file)
	 * @fileName the name of the file
	 * @fileMode "r" read, "w" write
	 */
	SciDB(const std::string & fileName, const char* fileMode);

	SciDB();

	virtual void setTypeAttributeMap();

	virtual bool isTheEnd();
};

#endif // SCIDB_H


text:
using System;
using LibWorkbooks.Common;

namespace LibWorkbooks.StandardFunctions
{
    public class Power
    {
        public void Function(IFunctionArgs args, IFunctionCaller caller)
        {
            // Syntax: POWER(number, power)
            // https://support.office.com/en-gb/article/POWER-function-d3f2908b-56f4-4c3f-895a-07fb519c362a

            if (args.Parameters.Length != 2)
            {
                throw new ArgumentException(
                    $"POWER function takes 2 arguments, got {args.Parameters.Length}",
                    nameof(args));
            }

            var arg1 = args.Parameters[0].Evaluate();
            if (arg1 is ErrorValue)
            {
                args.Result = arg1;
                return;
            }

            var arg2 = args.Parameters[1].Evaluate();
            if (arg2 is ErrorValue)
            {
                args.Result = arg2;
                return;
            }

            var val1 = Conversion.ToDoubleOrErrorValue(arg1);
            if (val1 is ErrorValue)
            {
                args.Result = val1;
                return;
            }

            var val2 = Conversion.ToDoubleOrErrorValue(arg2);
            if (val2 is ErrorValue)
            {
                args.Result = val2;
                return;
            }

            args.Result = Math.Pow((double)val1, (double)val2);
        }
    }
}


text:
/*
 * $Id$
 */
package lia.util.net.copy.monitoring;

import lia.util.net.common.Config;
import lia.util.net.common.Utils;
import lia.util.net.copy.Accountable;
import lia.util.net.copy.disk.DiskReaderManager;
import lia.util.net.copy.monitoring.base.AbstractAccountableMonitoringTask;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Monitors disk activity
 *
 * @author ramiro
 */
public class DiskReaderManagerMonitoringTask extends AbstractAccountableMonitoringTask {

    private static AtomicBoolean inited = new AtomicBoolean(false);
    Config config = Config.getInstance();

    public DiskReaderManagerMonitoringTask(DiskReaderManager drm) {
        super(new Accountable[]{drm});
    }

    public void rateComputed() {

        if (inited.compareAndSet(false, true) && config.getHostName() != null && config.isLisaRestartEnabled() && !config.isLisaDisabled()) {
            //is Client lisa is enabled and restart also... start monitoring transfer
            Utils.getMonitoringExecService().scheduleWithFixedDelay(new ClientTransportMonitorTask(this), 6, 6, TimeUnit.SECONDS);
        }

        if (DiskReaderManager.getInstance().sessionsSize() == 0) {
            resetAllCounters();
        }
    }

    public double getTotalRate() {
        return getTotalRate(DiskReaderManager.getInstance());
    }

}


text:
package ibis.constellation.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ibis.constellation.AbstractContext;
import ibis.constellation.Activity;
import ibis.constellation.Constellation;
import ibis.constellation.Event;

/**
 * A MultiEventCollector is an {@link Activity} that just waits for a specific number of events, and collects them.
 * It provides a method {@link #waitForEvents()}, to be used by other activities, to collect the events and block until the
 * specified number of events is reached, after which the MultiEventCollector will finish.
 */
public class MultiEventCollector extends Activity {

    public static final Logger logger = LoggerFactory.getLogger(MultiEventCollector.class);

    private static final long serialVersionUID = -538414301465754654L;

    private final Event[] events;
    private int count;

    /**
     * Constructs a MultiEventCollector with the specified activity context and event count. Note: this is an
     * activity that will receive events (see {@link Activity#Activity(ActivityContext, boolean)}).
     *
     * @param c
     *            the activity context of this event collector
     * @param events
     *            the number of events to be collected
     */
    public MultiEventCollector(AbstractContext c, int events) {
        super(c, false, true);
        this.events = new Event[events];
    }

    @Override
    public int initialize(Constellation c) {
        return SUSPEND;
    }

    @Override
    public synchronized int process(Constellation c, Event e) {

        if (logger.isDebugEnabled()) {
            logger.debug("MultiEventCollector: received event " + count + " of " + events.length);
        }

        events[count++] = e;

        if (count == events.length) {
            notifyAll();
            return FINISH;
        } else {
            return SUSPEND;
        }
    }

    @Override
    public void cleanup(Constellation c) {
        // empty
    }

    @Override
    public String toString() {
        return "MultiEventCollector(" + identifier() + ", " + events.length + ")";
    }

    /**
     * This method blocks waiting for the specified number of events. As soon as they are available, it creates an array
     * containing these events, and returns the array.
     *
     * @return an array containing the received events.
     */
    public synchronized Event[] waitForEvents() {
        while (count != events.length) {
            try {
                wait();
            } catch (Exception e) {
                // ignore
            }
        }

        return events;
    }

    /**
     * This method returns whether the event collector is finished, without blocking.
     *
     * @return whether the event collector is finished.
     */
    public synchronized boolean isFinished() {
        return count == events.length;
    }
}


text:
// Helper class managing dynamic linkage to DLL functions.

#ifndef __RFB_WIN32_DYNAMICFN_H__
#define __RFB_WIN32_DYNAMICFN_H__

#include "stdhdrs.h"

class DynamicFnBase {
public:
	DynamicFnBase(const TCHAR* dllName, const char* fnName);
	~DynamicFnBase();
	bool isValid() const {return fnPtr != 0;}
protected:
	void* fnPtr;
	HMODULE dllHandle;
private:
	DynamicFnBase(const DynamicFnBase&);
	DynamicFnBase operator=(const DynamicFnBase&);
};

template<class T> class DynamicFn : public DynamicFnBase {
public:
	DynamicFn(const TCHAR* dllName, const char* fnName) : DynamicFnBase(dllName, fnName) {}
	T operator *() const {return (T)fnPtr;};
};

#endif


text:
<resources>
    <string name="app_name">Service Notes</string>
    <string name="firstpopup">Questo contenuto non è ancora disponibile</string>
    <!-- Other strings -->
    <string name="other_settings">Altro</string>
    <string name="other_info">Sito Web</string>
    <string name="other_library">Librierie</string>
    <string name="check_updates">Controlla Aggiornamenti</string>
    <string name="check_updates_summary">Controlla se ci sono aggiornamenti disponibili per l\'app</string>
    <string name="beta_title">Partecipa al Beta</string>
    <string name="beta_desc">Partecipa al Beta testing dell\'app</string>
    <!-- Themes strings -->
    <string name="themes_summary">Scegli il tema</string>
    <string name="themes_title">Tema</string>
    <!-- Libraries strings -->
    <string name="libraries">Librerie</string>
    <string name="used_libraries_title">Librerie utilizzate</string>
    <!-- Backup strings -->
    <string name="ok">HO CAPITO</string>
    <string name="backuppopup">Il riavvio è necessario affinchè le modifiche vengano applicate</string>
    <string name="createbackup">Crea Backup</string>
    <string name="deletebackup">Resetta App</string>
    <string name="importbackup">Importa Backup</string>
    <string name="importbnote">Nota: Se importi un Backup perderai tutte le note attuali</string>
    <string name="deletebnote">Cliccando Resetta perderai tutte le tue attuali note</string>
    <string name="backup1">Il Backup esportera tutte le tue note in questa cartella: Cartella di Backup: /storage/sdcard/ServiceNotes</string>
    <string name="backup">Backup</string>
    <string name="info">Info</string>
    <!-- Animations strings -->
    <string name="animations_summary">Attiva o disattiva le animazioni</string>
    <string name="animations_title">Animazioni</string>
    <!-- Donate strings -->
    <string name="donatewithgoogle">Dona con Google Play</string>
    <string name="donatewithpaypal">Dona con PayPal</string>
    <!-- Languages strings -->
    <string name="language_settings">Lingua</string>
    <string name="language_title">Imposta lingua</string>
    <string name="language_summary">Imposta la lingua dell\'app. Nota:Alcune lingue potrebbero non essere accurate.</string>
    <string name="help_translating_title">Aiuta a tradurre</string>
    <string name="help_translating_summary">Collabora a questo progetto ed aiutaci a tradurre l\'app</string>
    <!-- Other strings -->
    <string name="navigation_drawer_open">Apri il navigation drawer</string>
    <string name="navigation_drawer_close">Chiudi il navigation drawer</string>
    <string name="donate2">Con PayPal potete effettuare una donazione completamente volontaria dove siete voi a decidere la quota, Google Play attualmente non supporta questa funzione ma potete donare delle cifre già impostate. Grazie per il supporto</string>
    <string name="donate">Molte persone hanno espresso il desiderio di fare una donazione per sostenere lo sviluppo di questa app.</string>
    <string name="Comunica">Comunica</string>
    <string name="feed">Feedback</string>
    <string name="action_bug">Riporta un problema</string>
    <string name="action_donate2">Dona</string>
    <string name="action_settings">Impostazioni</string>
    <string name="appbar_scrolling_view_behavior">android.support.design.widget.AppBarLayout$ScrollingViewBehavior</string>
    <string name="customization_settings">Personalizza</string>
    <string name="rate">Valuta</string>
    <string name="done_button">Fatto</string>
    <string name="gcm_defaultSenderId">482450084677</string>
    <string name="gittyreporter_action_settings">Impostazioni</string>
    <string name="gittyreporter_app_name">Gitty Reporter</string>
    <string name="gittyreporter_description">Descrivi il tuo problema</string>
    <string name="gittyreporter_device_info">Informazioni sul tuo dispositivo:</string>
    <string name="gittyreporter_headline1">Riporta un nuovo problema</string>
    <string name="gittyreporter_headline2">Accedi a GitHub</string>
    <string name="gittyreporter_hello_world">Hello world!</string>
    <string name="gittyreporter_login_password">Password:</string>
    <string name="gittyreporter_login_skip">"Non ho un account"</string>
    <string name="gittyreporter_login_username">Nome utente:</string>
    <string name="gittyreporter_title">Titolo</string>
    <string name="title_activity_oauth">OAuthActivity</string>
    <string name="skip">Prosegui</string>
    <string name="skip_button">Prosegui</string>
    <string name="status_bar_notification_info_overflow">999+</string>
    <string name="title_activity_my_intro">MyIntro</string>
    <string name="action_backup">Backup e Ripristino</string>
    <!-- MainActivity strings -->
    <string name="yes">Invia</string>
    <string name="cancel">Annulla</string>
    <string name="feedbacknotsent">Feedback non inviato, ci dispiace</string>
    <string name="feedbacksent">Feedback inviato con successo</string>
    <string name="feedbackempty">Il campo feedback non può essere vuoto.</string>
    <string name="feedbackmsg">Inserisci il tuo feedback</string>
    <string name="no_notes">Nessuna Nota</string>
    <string name="action_delete">Elimina</string>
    <string name="delete_notes_alert">Eliminare %s nota(e)?</string>
    <string name="introview">Puoi aggiungere una nota cliccando qua</string>
    <string name="gotit">HO CAPITO</string>
    <!-- Licenses dialog -->

    <!-- About dialog -->
    <string name="version_format">Versione:</string>
    <string name="copyright_info">Jonathan Imperato, Italia</string>
    <string name="drawerversion">Service Notes</string>
    <string name="source">Codice Sorgente</string>
    <string name="contributors">Collaboratori</string>
    <!-- EditNoteActivity strings -->
    <string name="title_activity_edit_note">Modifica nota</string>
    <string name="action_save">Salva</string>
    <!-- Intro -->
    <string name="intro1_title">Service Notes</string>
    <string name="intro1_content">Salva le tue note in maniera sicura ed ordinata</string>
    <string name="intro2_title">Note</string>
    <string name="intro2_content">Trova le tue note ovunque, in qualsiasi momento</string>
    <string name="intro3_title">Modificabili</string>
    <string name="intro3_content">Modifica le tue note facilmente e salvale</string>
    <string name="intro4_title">Molte altre funzioni</string>
    <string name="intro4_content">Alcune funzioni sono nel menu di fianco e molte altre saranno presto disponibili</string>

    <string name="title_activity_display_file">DisplayFileActivity</string>
    <string name="title_activity_upload_file">UploadFileActivity</string>
    <string name="title_activity_retrieve_contents_file">RetrieveContentsActivity</string>

    <string name="hint_note_title">Titolo</string>
    <string name="hint_note_content">Descrizione</string>
    <string name="hint_note_adress">Indirizzo</string>
    <string name="title_required">La nota deve avere un titolo</string>
    <string name="content_required">La nota deve avere una descrizione</string>

    <!-- ViewNoteActivity strings -->
    <string name="title_activity_view_note">Nota</string>
    <string name="label_created_at">Creata alle:</string>
    <string name="label_updated_at">Aggiornata alle:</string>
    <!-- App Updater strings -->
    <string name="appupdater_update_available">Nuovo aggiornamento disponibile!</string>
    <string name="appupdater_update_available_description_dialog">L\'aggiornamento %1$s è disponibile al download. Scarica l\'ultima versione contenente miglioramenti, risoluzione di errori e nuove funzioni per %2$s.</string>
    <string name="appupdater_update_available_description_snackbar">Aggiornamento %1$s disponibile!</string>
    <string name="appupdater_update_available_description_notification">Aggiornamento %1$s di %2$s è disponibile al download</string>
    <string name="appupdater_update_not_available">Nessun aggiornamento disponibile</string>
    <string name="appupdater_update_not_available_description">Hai l\'ultima versione di %s!</string>
    <string name="appupdater_btn_update">Aggiorna</string>
    <string name="appupdater_btn_disable">Non mostrare più</string>
    <string name="appupdater_btn_dismiss">Annulla</string>

</resources>


text:
using System;
using Newtonsoft.Json.Linq;
using System.Globalization;
using System.Text;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Web.Models;

namespace Umbraco.Web
{
    /// <summary>
    /// Provides extension methods for getting ImageProcessor URL from the core Image Cropper property editor
    /// </summary>
    public static class ImageCropperTemplateExtensions
    {
        /// <summary>
        /// Gets the ImageProcessor URL by the crop alias (from the "umbracoFile" property alias) on the IPublishedContent item
        /// </summary>
        /// <param name="mediaItem">
        /// The IPublishedContent item.
        /// </param>
        /// <param name="cropAlias">
        /// The crop alias e.g. thumbnail
        /// </param>
        /// <returns>
        /// The ImageProcessor.Web URL.
        /// </returns>
        public static string GetCropUrl(this IPublishedContent mediaItem, string cropAlias) => ImageCropperTemplateCoreExtensions.GetCropUrl(mediaItem, cropAlias, Current.ImageUrlGenerator);

        /// <summary>
        /// Gets the ImageProcessor URL by the crop alias using the specified property containing the image cropper Json data on the IPublishedContent item.
        /// </summary>
        /// <param name="mediaItem">
        /// The IPublishedContent item.
        /// </param>
        /// <param name="propertyAlias">
        /// The property alias of the property containing the Json data e.g. umbracoFile
        /// </param>
        /// <param name="cropAlias">
        /// The crop alias e.g. thumbnail
        /// </param>
        /// <returns>
        /// The ImageProcessor.Web URL.
        /// </returns>
        public static string GetCropUrl(this IPublishedContent mediaItem, string propertyAlias, string cropAlias) => ImageCropperTemplateCoreExtensions.GetCropUrl(mediaItem, propertyAlias, cropAlias, Current.ImageUrlGenerator);

        /// <summary>
        /// Gets the ImageProcessor URL from the IPublishedContent item.
        /// </summary>
        /// <param name="mediaItem">
        /// The IPublishedContent item.
        /// </param>
        /// <param name="width">
        /// The width of the output image.
        /// </param>
        /// <param name="height">
        /// The height of the output image.
        /// </param>
        /// <param name="propertyAlias">
        /// Property alias of the property containing the Json data.
        /// </param>
        /// <param name="cropAlias">
        /// The crop alias.
        /// </param>
        /// <param name="quality">
        /// Quality percentage of the output image.
        /// </param>
        /// <param name="imageCropMode">
        /// The image crop mode.
        /// </param>
        /// <param name="imageCropAnchor">
        /// The image crop anchor.
        /// </param>
        /// <param name="preferFocalPoint">
        /// Use focal point, to generate an output image using the focal point instead of the predefined crop
        /// </param>
        /// <param name="useCropDimensions">
        /// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters.
        /// </param>
        /// <param name="cacheBuster">
        /// Add a serialized date of the last edit of the item to ensure client cache refresh when updated
        /// </param>
        /// <param name="furtherOptions">
        /// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example:
        /// <example>
        /// <![CDATA[
        /// furtherOptions: "&bgcolor=fff"
        /// ]]>
        /// </example>
        /// </param>
        /// <param name="ratioMode">
        /// Use a dimension as a ratio
        /// </param>
        /// <param name="upScale">
        /// If the image should be upscaled to requested dimensions
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetCropUrl(
             this IPublishedContent mediaItem,
             int? width = null,
             int? height = null,
             string propertyAlias = Constants.Conventions.Media.File,
             string cropAlias = null,
             int? quality = null,
             ImageCropMode? imageCropMode = null,
             ImageCropAnchor? imageCropAnchor = null,
             bool preferFocalPoint = false,
             bool useCropDimensions = false,
             bool cacheBuster = true,
             string furtherOptions = null,
             ImageCropRatioMode? ratioMode = null,
             bool upScale = true) => ImageCropperTemplateCoreExtensions.GetCropUrl(mediaItem, Current.ImageUrlGenerator, width, height, propertyAlias, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, ratioMode, upScale);

        /// <summary>
        /// Gets the ImageProcessor URL from the image path.
        /// </summary>
        /// <param name="imageUrl">
        /// The image URL.
        /// </param>
        /// <param name="width">
        /// The width of the output image.
        /// </param>
        /// <param name="height">
        /// The height of the output image.
        /// </param>
        /// <param name="imageCropperValue">
        /// The Json data from the Umbraco Core Image Cropper property editor
        /// </param>
        /// <param name="cropAlias">
        /// The crop alias.
        /// </param>
        /// <param name="quality">
        /// Quality percentage of the output image.
        /// </param>
        /// <param name="imageCropMode">
        /// The image crop mode.
        /// </param>
        /// <param name="imageCropAnchor">
        /// The image crop anchor.
        /// </param>
        /// <param name="preferFocalPoint">
        /// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one
        /// </param>
        /// <param name="useCropDimensions">
        /// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters
        /// </param>
        /// <param name="cacheBusterValue">
        /// Add a serialized date of the last edit of the item to ensure client cache refresh when updated
        /// </param>
        /// <param name="furtherOptions">
        /// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example:
        /// <example>
        /// <![CDATA[
        /// furtherOptions: "&bgcolor=fff"
        /// ]]>
        /// </example>
        /// </param>
        /// <param name="ratioMode">
        /// Use a dimension as a ratio
        /// </param>
        /// <param name="upScale">
        /// If the image should be upscaled to requested dimensions
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetCropUrl(
            this string imageUrl,
            int? width = null,
            int? height = null,
            string imageCropperValue = null,
            string cropAlias = null,
            int? quality = null,
            ImageCropMode? imageCropMode = null,
            ImageCropAnchor? imageCropAnchor = null,
            bool preferFocalPoint = false,
            bool useCropDimensions = false,
            string cacheBusterValue = null,
            string furtherOptions = null,
            ImageCropRatioMode? ratioMode = null,
            bool upScale = true) => ImageCropperTemplateCoreExtensions.GetCropUrl(imageUrl, Current.ImageUrlGenerator, width, height, imageCropperValue, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode, upScale);

        /// <summary>
        /// Gets the ImageProcessor URL from the image path.
        /// </summary>
        /// <param name="imageUrl">
        /// The image URL.
        /// </param>
        /// <param name="cropDataSet"></param>
        /// <param name="width">
        /// The width of the output image.
        /// </param>
        /// <param name="height">
        /// The height of the output image.
        /// </param>
        /// <param name="cropAlias">
        /// The crop alias.
        /// </param>
        /// <param name="quality">
        /// Quality percentage of the output image.
        /// </param>
        /// <param name="imageCropMode">
        /// The image crop mode.
        /// </param>
        /// <param name="imageCropAnchor">
        /// The image crop anchor.
        /// </param>
        /// <param name="preferFocalPoint">
        /// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one
        /// </param>
        /// <param name="useCropDimensions">
        /// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters
        /// </param>
        /// <param name="cacheBusterValue">
        /// Add a serialized date of the last edit of the item to ensure client cache refresh when updated
        /// </param>
        /// <param name="furtherOptions">
        /// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example:
        /// <example>
        /// <![CDATA[
        /// furtherOptions: "&bgcolor=fff"
        /// ]]>
        /// </example>
        /// </param>
        /// <param name="ratioMode">
        /// Use a dimension as a ratio
        /// </param>
        /// <param name="upScale">
        /// If the image should be upscaled to requested dimensions
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetCropUrl(
            this string imageUrl,
            ImageCropperValue cropDataSet,
            int? width = null,
            int? height = null,
            string cropAlias = null,
            int? quality = null,
            ImageCropMode? imageCropMode = null,
            ImageCropAnchor? imageCropAnchor = null,
            bool preferFocalPoint = false,
            bool useCropDimensions = false,
            string cacheBusterValue = null,
            string furtherOptions = null,
            ImageCropRatioMode? ratioMode = null,
            bool upScale = true) => ImageCropperTemplateCoreExtensions.GetCropUrl(imageUrl, Current.ImageUrlGenerator, cropDataSet, width, height, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode, upScale);

        internal static ImageCropperValue DeserializeImageCropperValue(this string json)
        {
            var imageCrops = new ImageCropperValue();
            if (json.DetectIsJson())
            {
                try
                {
                    imageCrops = JsonConvert.DeserializeObject<ImageCropperValue>(json, new JsonSerializerSettings
                    {
                        Culture = CultureInfo.InvariantCulture,
                        FloatParseHandling = FloatParseHandling.Decimal
                    });
                }
                catch (Exception ex)
                {
                    Current.Logger.Error(typeof(ImageCropperTemplateExtensions), ex, "Could not parse the json string: {Json}", json);
                }
            }

            return imageCrops;
        }
    }
}


text:
var Promise = require('promise')

module.exports = {

    parse: Promise.resolve,

}


text:
> A set of higher-order components to turn any list into an animated, touch-friendly, sortable list.

[![npm version](https://img.shields.io/npm/v/react-sortable-hoc.svg)](https://www.npmjs.com/package/react-sortable-hoc)
![npm downloads](https://img.shields.io/npm/dm/react-sortable-hoc.svg)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg?maxAge=2592000)](https://github.com/clauderic/react-sortable-hoc/blob/master/LICENSE)
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
[![Gitter](https://badges.gitter.im/clauderic/react-sortable-hoc.svg)](https://gitter.im/clauderic/react-sortable-hoc)

### Examples available here: http://clauderic.github.io/react-sortable-hoc/

Features
---------------
* **Higher Order Components** – Integrates with your existing components
* **Drag handle, auto-scrolling, locked axis, events, and more!**
* **Suuuper smooth animations** – Chasing the 60FPS dream 🌈
* **Works with React Virtualized, React-Infinite, etc.**
* **Horizontal or vertical lists** ↔ ↕
* **Touch support** 👌

Installation
------------

Using [npm](https://www.npmjs.com/package/react-sortable-hoc):

	$ npm install react-sortable-hoc --save

Then, using a module bundler that supports either CommonJS or ES2015 modules, such as [webpack](https://github.com/webpack/webpack):

```js
// Using an ES6 transpiler like Babel
import {SortableContainer, SortableElement} from 'react-sortable-hoc';

// Not using an ES6 transpiler
var Sortable = require('react-sortable-hoc');
var SortableContainer = Sortable.SortableContainer;
var SortableElement = Sortable.SortableElement;
```

Alternatively, an UMD build is also available:
```html
<script src="react-sortable-hoc/dist/umd/react-sortable-hoc.js"></script>
```

Usage
------------
### Basic Example

```js
import React, {Component} from 'react';
import {render} from 'react-dom';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-hoc';

const SortableItem = SortableElement(({value}) => <li>{value}</li>);

const SortableList = SortableContainer(({items}) => {
	return (
		<ul>
			{items.map((value, index) =>
                <SortableItem key={`item-${index}`} index={index} value={value} />
            )}
		</ul>
	);
});

class SortableComponent extends Component {
    state = {
        items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6']
    }
    onSortEnd = ({oldIndex, newIndex}) => {
        this.setState({
            items: arrayMove(this.state.items, oldIndex, newIndex)
        });
    };
    render() {
        return (
            <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />
        )
    }
}

render(<SortableComponent/>, document.getElementById('root'));
```
That's it! React Sortable does not come with any styles by default, since it's meant to enhance your existing components.

More code examples are available [here](https://github.com/clauderic/react-sortable-hoc/blob/master/examples/).

### Prop Types

#### SortableContainer HOC
| Property                   | Type     | Default | Description                                                                                |
|:---------------------------|:---------|:--------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| axis                       | String   | `y`     | The axis you want to sort on, either 'x' or 'y'                                                                                |
| lockAxis                   | String   |         | If you'd like, you can lock movement to an axis while sorting. This is not something that is possible with HTML5 Drag & Drop                                                                                |
| helperClass                | String   |         | You can provide a class you'd like to add to the sortable helper to add some styles to it                                                                                |
| transitionDuration         | Number   | `300`   | The duration of the transition when elements shift positions. Set this to `0` if you'd like to disable transitions                                                                                |
| pressDelay                 | Number   | `0`     | If you'd like elements to only become sortable after being pressed for a certain time, change this property. A good sensible default value for mobile is `200`                                                               |
| onSortStart                | Function |         | Callback that get's invoked when sorting begins. `function({node, index, collection}, event)`                                                                                |
| onSortMove                 | Function |         | Callback that get's invoked during sorting as the cursor moves. `function(event)`                                                                                |
| onSortEnd                  | Function |         | Callback that get's invoked when sortin ends. `function({oldIndex, newIndex, collection}, e)`                                                                                |
| useDragHandle              | Boolean  | `false` | If you're using the `SortableHandle` HOC, set this to `true`                                                                                |
| useWindowAsScrollContainer | Boolean  | `false` | If you want, you can set the `window` as the scrolling container                                                                                |
| hideSortableGhost          | Boolean  | `true`  | Whether to auto-hide the ghost element. By default, as a convenience, React Sortable List will automatically hide the element that is currently being sorted. Set this to false if you would like to apply your own styling. |
| lockToContainerEdges       | Boolean  | `false` | You can lock movement of the sortable element to it's parent `SortableContainer`                                                                                |
| lockOffset                 | `OffsetValue`\* \| [`OffsetValue`\*, `OffsetValue`\*] | `"50%"` | When `lockToContainerEdges` is set to `true`, this controls the offset distance between the sortable helper and the top/bottom edges of it's parent `SortableContainer`. Percentage values are relative to the height of the item currently being sorted. If you wish to specify different behaviours for locking to the *top* of the container vs the *bottom*, you may also pass in an `array` (For example: `["0%", "100%"]`). |
| getContainer | Function |  | Optional function to return the scrollable container element. This property defaults to the `SortableContainer` element itself or (if `useWindowAsScrollContainer` is true) the window. Use this function to specify a custom container object (eg this is useful for integrating with certain 3rd party components such as `FlexTable`). This function is passed a single parameter (the `wrappedInstance` React element) and it is expected to return a DOM element. |

\* `OffsetValue` is either a finite `Number` or a `String` made-up of a number and a unit (`px` or `%`).
Examples: `10` (is the same as `"10px"`), `"50%"`

#### SortableElement HOC
| Property   | Type             | Default | Required? | Description                                                                                |
|:-----------|:-----------------|:--------|:---------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| index      | Number           |         |     ✓     | This is the element's sortableIndex within it's collection. This prop is required.                                                                                |
| collection | Number or String | `0`     |           | The collection the element is part of. This is useful if you have multiple groups of sortable elements within the same `SortableContainer`. [Example](http://clauderic.github.io/react-sortable-hoc/#/basic-configuration/multiple-lists) |
| disabled   | Boolean          | `false` |           | Whether the element should be sortable or not                                                                                |
Why shoud I use this?
--------------------
There are already a number of great Drag & Drop libraries out there (for instance, [react-dnd](https://github.com/gaearon/react-dnd/) is fantastic). If those libraries fit your needs, you should definitely give them a try first. However, most of those libraries rely on the HTML5 Drag & Drop API, which has some severe limitations. For instance, things rapidly become tricky if you need to support touch devices, if you need to lock dragging to an axis, or want to animate the nodes as they're being sorted. React Sortable HOC aims to provide a simple set of higher-order components to fill those gaps. If you're looking for a dead-simple, mobile-friendly way to add sortable functionality to your lists, then you're in the right place.

Dependencies
------------
React Sortable List has very few dependencies. It depends on `invariant` and a couple `lodash` functions. It has the following peerDependencies: `react`, `react-dom`

Reporting Issues
----------------
If believe you've found an issue, please [report it](https://github.com/clauderic/react-sortable-hoc/issues) along with any relevant details to reproduce it. The easiest way to do so is to fork this [jsfiddle](https://jsfiddle.net/clauderic/6r7r2cva/).

Contributions
------------
Yes please! Feature requests / pull requests are welcome.

Made with ❤ in the heart of Montreal.


text:
package net.lemonfactory.sudokusolver.gui;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

import net.lemonfactory.sudokusolver.type.SudokuType;
import net.lemonfactory.sudokusolver.type.SudokuTypeStructure;

/**
 *
 * @author Choongmin Lee
 */
@SuppressWarnings("serial")
final class SudokuBoardPanel extends JComponent {

    private JLabel[] cells;
    private Color[] colors;
    private Color[] bgColors;
    private char[] chars;
    private Font font;

    private SudokuType type;
    private Map<Character, Integer> symbolToIndex;
    private int boardSize;
    private int boxWidth;
    private int boxHeight;

    private int[] hor;
    private int[] ver;

    private boolean cleared;
    private boolean editable;
    private int selected;

    public SudokuBoardPanel(SudokuType t) {
        setLayout(null);
        setFocusable(true);
        addMouseListener(new MyMouseListener());
        addKeyListener(new MyKeyboardListener());
        addFocusListener(new MyFocusListener());
        sudokuTypeChanged(t);
    }

    private void sudokuTypeChanged(SudokuType t) {
        type = t;
        boxWidth = type.getStructure().boxWidth();
        boxHeight = type.getStructure().boxHeight();
        boardSize = type.getStructure().size();
        symbolToIndex = makeSymbolToIndex(type);

        removeAll();
        cells = new JLabel[boardSize * boardSize];
        colors = new Color[boardSize * boardSize];
        bgColors = new Color[boardSize * boardSize];
        chars = new char[boardSize * boardSize];

        hor = new int[boardSize + 1];
        ver = new int[boardSize + 1];

        editable = true;
        cleared = true;
        selected = -1;

        for (int i = 0; i < boardSize * boardSize; ++i) {
            add(cells[i] = new JLabel());
            cells[i].setHorizontalAlignment(SwingConstants.CENTER);
            cells[i].setVerticalAlignment(SwingConstants.CENTER);
            cells[i].setOpaque(true);
            setCellBackground(i);
        }
        repaint();
    }

    private void symbolsChanged(SudokuType t) {
        for (int i = 0; i < chars.length; ++i)
            if (chars[i] != '\0')
                chars[i] = t.getSymbols().get(symbolToIndex.get(chars[i]));
        symbolToIndex = makeSymbolToIndex(t);
        repaint();
    }

    private Map<Character, Integer> makeSymbolToIndex(SudokuType type) {
        Map<Character, Integer> symbolToIndex;
        symbolToIndex = new HashMap<Character, Integer>();
        int index = 0;
        for (Character c : type.getSymbols().toString().toCharArray())
            symbolToIndex.put(c, index++);
        return symbolToIndex;
    }

    public boolean setSudokuType(SudokuType t) {
        if (type.equals(t))
            return false;
        if (type.getStructure().equals(t.getStructure()))
            symbolsChanged(t);
        else
            sudokuTypeChanged(t);
        type = t;
        return true;
    }

    public void clear() {
        if (!cleared) {
            Arrays.fill(chars, '\0');
            Arrays.fill(colors, null);
            Arrays.fill(bgColors, null);
            cleared = true;
        }
    }

    public char getChar(int i) {
        char c = chars[i];
        return c == '\0' ? type.getBlank() : c;
    }

    public Color getColor(int i) {
        return colors[i];
    }

    public String getPuzzle() {
        StringBuilder buf = new StringBuilder(chars.length);
        for (int i = 0; i < chars.length; ++i)
            buf.append(getChar(i));
        return buf.toString();
    }

    public void setChar(int i, char c) {
        setChar(i, c, Color.BLACK);
    }

    public void setChar(int i, char c, Color color) {
        if (c == type.getBlank())
            c = '\0';
        chars[i] = c;
        colors[i] = color;
        cleared = false;
    }

    public void setEditable(boolean aFlag) {
        editable = aFlag;
        if (aFlag)
            select(selected);
        else
            unselect();
    }

    public boolean isEditable() {
        return editable;
    }

    public void paint(Graphics g) {
        Dimension d = getSize();
        int x;
        int y;
        int width;
        int height;
        if (d.height < d.width) {
            x = (d.width - d.height) / 2;
            y = 0;
            width = height = d.height - 1;
        } else {
            x = 0;
            y = (d.height - d.width) / 2;
            width = height = d.width - 1;
        }

        // draw outer
        g.setColor(Color.WHITE);
        g.fillRect(x, y, width, height);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, width, height);
        g.drawRect(x + 1, y + 1, width - 2, height - 2);

        // draw inner lines
        ver[0] = x;
        hor[0] = y;
        ver[boardSize] = x + width - 1;
        hor[boardSize] = y + height - 1;
        for (int i = 1, j, k = 0; i < boardSize; ++i) {
            j = x + (i * (width - 1 - boxHeight) / boardSize) + 2;
            g.drawLine(j + k, y, j + k, y + height);
            ver[i] = j + k;
            if (boxWidth != 0 && i % boxWidth == 0) {
                g.drawLine(j + k + 1, y, j + k + 1, y + height);
                ++k;
            }
        }
        for (int i = 1, j, k = 0; i < boardSize; ++i) {
            j = y + (i * (height - 1 - boxWidth) / boardSize) + 2;
            g.drawLine(x, j + k, x + width, j + k);
            hor[i] = j + k;
            if (boxHeight != 0 && i % boxHeight == 0) {
                g.drawLine(x, j + k + 1, x + width, j + k + 1);
                ++k;
            }
        }

        // fix cells
        for (int i = 0, bx, by, w, h, mx, my, ind; i < boardSize; ++i) {
            for (int j = 0; j < boardSize; ++j) {
                mx = (boxWidth != 0 && j % boxWidth == 0 || j == 0 ? 2 : 1);
                my = (boxHeight != 0 && i % boxHeight == 0 || i == 0 ? 2 : 1);
                bx = ver[j] + mx;
                by = hor[i] + my;
                w = ver[j + 1] - ver[j] - mx;
                h = hor[i + 1] - hor[i] - my;
                ind = i * boardSize + j;
                cells[ind].setBounds(bx, by, w, h);
                cells[ind].setText(String.valueOf(chars[ind]));
            }
        }
        makeFont();
        super.paint(g);
    }

    public void repaint() {
        makeFont();
        for (int i = 0; i < cells.length; ++i) {
            cells[i].setFont(font);
            cells[i].setForeground(colors[i]);
        }
        super.repaint();
    }

    private void repaint(int index) {
        cells[index].setFont(font);
        cells[index].setForeground(colors[index]);
        super.repaint();
    }

    private void setCellBackground(int cell) {
        if (bgColors[cell] == null) {
            SudokuTypeStructure structure = type.getStructure();
            int[] cellGroupIndexes = structure.getCellGroupIndexes(cell);
            Color[] toBeMixed = new Color[cellGroupIndexes.length];
            int i = 0;
            for (int j = 0; j < cellGroupIndexes.length; ++j) {
                Color bgColor = structure.getCellGroupColor(cellGroupIndexes[j]);
                if (bgColor != null)
                    toBeMixed[i++] = bgColor;
            }
            bgColors[cell] = mix(toBeMixed, 0, i);
        }
        cells[cell].setBackground(bgColors[cell]);
    }

    // RGB mean
    private Color mix(Color[] colors, int start, int end) {
        if (start == end)
            return Color.WHITE;
        int r = 0;
        int g = 0;
        int b = 0;
        for (int i = start; i < end; ++i) {
            r += colors[i].getRed();
            g += colors[i].getGreen();
            b += colors[i].getBlue();
        }
        int n = end - start;
        return new Color(r / n, g / n, b / n);
    }

    private void makeFont() {
        Dimension d = getSize();
        int height = (d.height < d.width ? d.height : d.width) - 1;
        font = new Font(
                "sans-serif",
                0,
                (int) (0.6 * (height - 1 - boxWidth) / boardSize));
    }

    private void select(int index) {
        unselect();
        selected = index;
        if (selected > -1 && editable)
            cells[selected].setBackground(cells[selected].getBackground().darker());
    }

    private void unselect() {
        if (selected > -1)
            setCellBackground(selected);
    }

    private class MyMouseListener extends MouseAdapter {

        private int calculateIndex(int x, int y) {
            int cx = -Arrays.binarySearch(ver, x) - 2;
            int cy = -Arrays.binarySearch(hor, y) - 2;
            if (cx >= 0 && cx < boardSize && cy >= 0 && cy < boardSize)
                return cy * boardSize + cx;
            return -1;
        }

        public void mousePressed(MouseEvent e) {
            requestFocusInWindow();
            if (!editable)
                return;
            int index = calculateIndex(e.getX(), e.getY());
            switch (e.getClickCount()) {
            case 1:
                if (index != -1)
                    select(index);
                break;
            case 2:
                setChar(selected, '\0');
                repaint(selected);
                break;
            }
        }
    }

    private class MyKeyboardListener extends KeyAdapter {

        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            switch (keyCode) {
            case KeyEvent.VK_ESCAPE:
            case KeyEvent.VK_ENTER:
                transferFocus();
                break;
            }
            if (!editable)
                return;
            switch (keyCode) {
            case KeyEvent.VK_LEFT:
                if (selected % boardSize != 0)
                    select(selected - 1);
                else
                    select(selected - 1 + boardSize);
                break;
            case KeyEvent.VK_RIGHT:
                if ((selected + 1) % boardSize != 0)
                    select(selected + 1);
                else
                    select(selected + 1 - boardSize);
                break;
            case KeyEvent.VK_UP:
                if (selected / boardSize != 0)
                    select(selected - boardSize);
                else
                    select(selected - boardSize + boardSize * boardSize);
                break;
            case KeyEvent.VK_DOWN:
                if (selected / boardSize != boardSize - 1)
                    select(selected + boardSize);
                else
                    select(selected + boardSize - boardSize * boardSize);
                break;
            case KeyEvent.VK_SPACE:
            case KeyEvent.VK_BACK_SPACE:
            case KeyEvent.VK_DELETE:
                setChar(selected, '\0');
                repaint(selected);
                break;
            }
        }

        public void keyTyped(KeyEvent e) {
            if (!editable)
                return;
            switch (e.getModifiersEx()) {
            case 0:
            case InputEvent.SHIFT_DOWN_MASK:
                char c = e.getKeyChar();
                if (symbolToIndex.containsKey(c)) {
                    setChar(selected, c);
                    repaint(selected);
                }
                else if (c == type.getBlank()) {
                    setChar(selected, '\0');
                    repaint(selected);
                }
                break;
            }
        }
    }

    private class MyFocusListener extends FocusAdapter {

        public void focusGained(FocusEvent e) {
            select(selected > -1 ? selected : 0);
        }

        public void focusLost(FocusEvent e) {
            unselect();
        }
    }
}