text:
using System;
using TravelGuide.Models.Abstractions;

namespace TravelGuide.Models.Stories
{
    public class StoryComment : Comment
    {
        public StoryComment()
            : base()
        {
        }

        public StoryComment(string userId, User user, string content, Guid storyId)
            : base()
        {
            this.UserId = userId;
            this.User = user;
            this.Content = content;
            this.StoryId = storyId;
        }

        public Guid StoryId { get; set; }

        public virtual Story Story { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  def logger
    Rails.logger
  end

  private

    # Returns true inside an integration test.
    def integration_test?
      defined?(post_via_redirect)
    end
end


text:
Installation
============

From PyPI::

  $ pip install doubles

From source::

  $ git clone https://github.com/uber/doubles
  $ cd doubles
  $ python setup.py install


text:
import * as api from '@/api'
import * as ls from '@/store/localStorage'

let timer

const state = () => {
  return {
    now: '',
    isOpenQuery: false,
    isAdminMode: false,
    loading: false,
    response: [],
    error: null
  }
}

const getters = {}

const actions = {
  async getQlist ({commit, rootState, rootGetters}, {isAutoQlist}) {
    const {datasource} = rootState.hash
    const {isPresto, isHive, isSpark, isElasticsearch, authInfo} = rootGetters

    isAutoQlist = isAutoQlist || false

    commit('refreshNow')

    if (!isAutoQlist) {
      commit('setLoading', {data: true})
    }

    try {
      let data
      if (isPresto) {
        data = await api.getQlistPresto(datasource, authInfo)
      } else if (isHive) {
        data = await api.getQlistHive(datasource)
      } else if (isSpark) {
        data = await api.getQlistSpark(datasource)
      } else if (isElasticsearch) {
        commit('setLoading', {data: false})
        return
      } else {
        throw new Error('not supported')
      }
      if (data.error) {
        commit('setError', {data: data.error})
      } else {
        commit('setResponse', {data})
      }
    } catch (e) {
    }

    commit('setLoading', {data: false})
  },
  async autoQlist ({dispatch, rootState, rootGetters}, {enable}) {
    const {isPresto} = rootGetters
    const refreshPeriod = 1
    const period = isPresto ? 1000 : 1000 * 10

    enable = enable || false

    clearInterval(timer)
    dispatch('getQlist', {isAutoQlist: false})

    let time = refreshPeriod
    if (enable) {
      timer = setInterval(() => {
        const {isModal} = rootState
        const {tab} = rootState.hash

        time--
        if (time === 0) {
          if (tab === 'qlist' && !isModal) {
            dispatch('getQlist', {isAutoQlist: true})
          }
          time = refreshPeriod
        }
      }, period)
    }
  }
}

const mutations = {
  init (state) {
    state.response = []
    state.error = null
  },
  refreshNow (state) {
    state.now = Date.create().format('{yyyy}/{M}/{d} {24hr}:{mm}:{ss}')
  },
  setLoading (state, {data}) {
    state.loading = data
  },
  setResponse (state, {data}) {
    state.response = data
  },
  setError (state, {data}) {
    state.error = data
  },
  setIsOpenQuery (state, {data}) {
    state.isOpenQuery = data
    ls.setItemBoolean('openQuery', state.isOpenQuery)
  },
  setIsAdminMode (state, {data}) {
    state.isAdminMode = data
    ls.setItemBoolean('adminMode', state.isAdminMode)
  },
  loadLocalStorage (state) {
    state.isOpenQuery = ls.getItemBoolean('openQuery', false)
    state.isAdminMode = ls.getItemBoolean('adminMode', false)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}


text:
/**
 * Provider classes of XEP-0202: Entity Time.
 */
package org.jivesoftware.smackx.time.provider;


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FsCheck;
using FsCheck.MsTest.Examples.ClassesToTest;

namespace FsCheck.MsTest.Examples
{
    [TestClass]
    public class CounterTest
    {
        [TestMethod, ExpectedException(typeof(Exception))]
        public void QuickCounter()
        {
            new CounterSpec().ToProperty().QuickCheckThrowOnFailure();
        }

        [TestMethod, ExpectedException(typeof(Exception))]
        public void VerboseCounter()
        {
            new CounterSpec().ToProperty().VerboseCheckThrowOnFailure();
        }

        [TestMethod, ExpectedException(typeof(Exception))]
        public void CheckCounterWithQuick()
        {
            new CounterSpec().ToProperty().Check(Configuration.QuickThrowOnFailure);
        }

        [TestMethod, ExpectedException(typeof(Exception))]
        public void CheckCounterWithVerbose()
        {
            new CounterSpec().ToProperty().Check(Configuration.VerboseThrowOnFailure);
        }
    }
}


text:
import datetime
from dateutil import rrule
import arcpy, os, sys
from arcpy import env
import numpy as np
##import matplotlib.pyplot as plt

#  Set workspace to GIS gauge data location, loop through individual watersheds

arcpy.env.workspace = "C:\\Recharge_GIS\\Watersheds"
fc = "nm_wtrs_11DEC15.shp"
field = "USGS_Code"
cursor = arcpy.SearchCursor(fc)

#  List csv gauge data, create list of gauge codes

folder = 'C:\\Users\David\\Documents\\Recharge\\Gauges\\Gauge_Data_HF_csv'
os.chdir(folder)
csvList = os.listdir(folder)
# make sure that this is getting the right string from the file name
files = [str(name[1:8]) for name in csvList]
print files
print len(files)
print csvList

#  Create layer from polygon fc so it is selectable by attribute

arcpy.env.workspace = "C:\\Recharge_GIS\Watersheds\\Watersheds"
arcpy.MakeFeatureLayer_management("C:\\Recharge_GIS\\Watersheds\\nm_wtrs_11DEC15.shp", "wtrshds_lyr")

#  Loop through polygon features in watersheds layer, select polygon geometry by attribute

for row in cursor:
    gPoly = row.getValue(field)
    polyStr = str(gPoly)
    print gPoly
    gstr = arcpy.AddFieldDelimiters("C:\\Recharge_GIS\\Watersheds\\nm_wtrs_11DEC15.shp", field)
    sqlExp = gstr + " = " + polyStr
    print sqlExp
    geo = arcpy.SelectLayerByAttribute_management("wtrshds_lyr", "NEW_SELECTION", sqlExp)
    print "USGS code: " + str(gPoly)

#  Get csv data from gauges and identify time interval of needed precip data

    if polyStr in files:
        print "true"
        folder = 'C:\\Users\David\\Documents\\Recharge\\Gauges\\Gauge_Data_HF_csv'
        os.chdir(folder)
        pos = files.index(gPoly)
        recs = []
        fid = open(csvList[pos])
        lines = fid.readlines()[0:]
        fid.close()
        rows = [line.split(',') for line in lines]
        for line in rows:
            try:
                recs.append([datetime.datetime.strptime(line[2], '%m/%d/%Y'),  # date
                float(line[3])])  # discharge
            except ValueError:
                recs.append([datetime.datetime.strptime(line[2], '%m/%d/%Y'),  # date
                float(0.0)])  # discharge
        print "Data points: " + str(len(recs))
        qRecs = np.array(recs)

#  Make start and end dates correspond with available PRISM data (i.e., 1984-01-01 to 2013-12-31)

        start = qRecs[0, 0]
        beginPrecip = datetime.datetime(1984, 1, 1)
        if start < beginPrecip:
            start = beginPrecip
        print "Data start: " + str(start)
        end = qRecs[len(qRecs)-1, 0]
        endPrecip = datetime.datetime(2013, 12, 31)
        if end > endPrecip:
            end = endPrecip
        print "Data end: " + str(end)

#  Loop through raster data, clipping and creating arrays of data:  Date Q Ppt
        rasSq = 1013.02**2/1000  # ppt [mm -> m] and cellsize (x*y) [m*m]
        precip = []
        date = []
        q = []

        for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end):
            folder = "C:\\Recharge_GIS\\Precip\\800m\\Daily\\"
            yr = day.year
            if yr <= 1991:
                arcpy.env.overwriteOutput = True      # Ensure overwrite capability
                arcpy.env.workspace = folder + str(day.year) + "a"
                ras = folder + str(day.year) + "a\\" + "PRISM_NM_" + str(day.year) + day.strftime('%m') + day.strftime('%d') + ".tif"
                if arcpy.Exists(ras):
                    try:
                        arcpy.CheckOutExtension("Spatial")
                        mask = "C:\\Recharge_GIS\\nm_gauges.gdb\\nm_wtrshds"
                        rasPart = arcpy.sa.ExtractByMask(ras, geo)
                        if day == beginPrecip:
                            rasPart.save(folder + str(day.year) + "a\\" + str(gPoly) + "_rasterClipTest.tif")
                        arr = arcpy.RasterToNumPyArray(rasPart, nodata_to_value=0)
                        arrVal = np.multiply(arr, rasSq)
                        arrSum = arrVal.sum()
                        print "Sum of precip on " + str(day) + ":  " + str(arrSum)
                        precip.append(arrSum)
                        date.append(day)
                        for rec in qRecs:
                            if rec[0] == day:
                                q.append(rec[1])
                    except:
                        pass
            if yr > 1991:
                arcpy.env.workspace = folder + str(day.year)
                ras = folder + str(day.year) + "\\" + "PRISM_NMHW2Buff_" + str(day.year) + day.strftime('%m') + day.strftime('%d') + ".tif"
                if arcpy.Exists(ras):
                    try:
                        arcpy.CheckOutExtension("Spatial")
                        mask = "C:\\Recharge_GIS\\nm_gauges.gdb\\nm_wtrshds"
                        rasPart = arcpy.sa.ExtractByMask(ras, geo)
                        if day == beginPrecip:
                            rasPart.save(folder + str(day.year) + str(gPoly) + "_rasterClipTest.tif")
                        arr = arcpy.RasterToNumPyArray(rasPart, nodata_to_value=0)
                        arrVal = np.multiply(arr,rasSq)
                        arrSum = arrVal.sum()
                        print "Sum of precip on " + str(day) + ":  " + str(arrSum)
                        precip.append(arrSum)
                        date.append(day)
                        for rec in qRecs:
                            if rec[0] == day:
                                q.append(rec[1])
                    except:
                        pass

#  Create numpy arrays, convert time objects to strings, stack columns, save as CSV

        q = np.array(q,dtype=float)
        ppt = np.array(precip,dtype=float)
        date = [rec.strftime('%Y/%m/%d') for rec in date]
        date = np.array(date,object)
        data = np.column_stack((date,q,ppt))
        print data
        np.savetxt(('C:\\Users\David\\Documents\\Recharge\\Gauges\\Gauge_ppt_csv\\' + str(gPoly) + ".csv"),
                   data, fmt=['%s', '%1.1f', '%1.3f'], delimiter=',')
        print "You have been saved!"


text:
package com.sgtcodfish.mobiusListing;

import java.util.ArrayList;
import java.util.HashMap;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.maps.MapLayers;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Pool.Poolable;
import com.sgtcodfish.mobiusListing.WorldConstants.InteractableLayerTypes;
import com.sgtcodfish.mobiusListing.levels.LevelEntityFactory;

/**
 * @author Ashley Davis (SgtCoDFish)
 */
public class TerrainCollisionMap implements Poolable {
	private TiledMapTileLayer										layer			= null;
	private HashMap<TiledMapTileLayer, PlatformManipulationHandler>	platformLayers	= null;
	private ArrayList<Integer>										collisionMap	= null;

	protected TerrainCollisionMap(TiledMapTileLayer layer,
			HashMap<TiledMapTileLayer, PlatformManipulationHandler> platformLayers, ArrayList<Integer> collisionMap) {
		this.layer = layer;
		this.platformLayers = platformLayers;
		this.collisionMap = collisionMap;
	}

	/**
	 * @param p
	 *        The position vector to use for checking (in world coordinates).
	 * @param v
	 *        The velocity vector to use for checking (in world
	 *        coordinates/frame).
	 * @return true if the object travelling in the given tile (converted from
	 *         world coordinates in variable p) with velocity v will collide in
	 *         either y direction.
	 */
	public boolean willCollideY(Vector2 p, Vector2 v) {
		int tx = worldToTileCoordinatesX(p.x + v.x);

		int ty = worldToTileCoordinatesY(p.y + v.y);

		if (tx == -1 || ty == -1) {
			return false;
		} else {
			return isSolidTile(tx, ty);
		}
	}

	/**
	 * @param p
	 *        The position vector (in world coordinates) to use for checking.
	 * @param v
	 *        The velocity vector (in world coordinates/frame) to use for
	 *        checking. Note that the y velocity may be ignored.
	 * @return true if the object travelling in the given tile(converted from
	 *         world coordinates in argument p) with velocity v will collide in
	 *         either x direction.
	 */
	public boolean willCollideX(Vector2 p, Vector2 v) {
		int ty = worldToTileCoordinatesY(p.y);

		int tx = worldToTileCoordinatesX(p.x + v.x);

		if (tx == -1 || ty == -1) {
			return false;
		} else {
			return isSolidTile(tx, ty);
		}
	}

	public void layerInteracted(TiledMapTileLayer interacted, int degree) {
		PlatformManipulationHandler handler = platformLayers.get(interacted);

		if (handler == null) {
			Gdx.app.debug("LAYER_INTERACTED", "Call to layerInteracted with improperly initialised platform layer.");
		} else {
			handler.update(degree);
		}
	}

	/**
	 *

	 * Checks to see if the tile specified by (tileX, tileY) is solid.
	 *

	 *

	 * Note: this function doesn't perform checking on its arguments
	 * and invalid coordinates lead to undefined behaviour. Ensure coordinates
	 * are correct before passing them.
	 *

	 *
	 * @param tileX
	 *        The x coordinate of the tile, assumed to be inside the map.
	 * @param tileY
	 *        The y coordinate of the tile, assumed to be inside the map.
	 * @return true if the tile is solid, false if it is not.
	 */
	public boolean isSolidTile(int tileX, int tileY) {
		return mapRetrieve(tileX, tileY) >= 1;
	}

	/**
	 *

	 * Retrieves the cell specified by (tileX, tileY) from the map.
	 * Values of 1 or greater indiciate a solid tile.
	 *

	 *
	 * @param tileX
	 *        The x coordinate, in tile coordinates of the cell to retrieve.
	 * @param tileY
	 *        The y coordinate, in tile coordinates of the cell to retrieve.
	 * @return An integer where 0 or less indicates non-collidable terrain and 1
	 *         or greater indicates solid terrain.
	 */
	public int mapRetrieve(int tileX, int tileY) {
		return collisionMap.get((int) (tileY * (actualWidthInTiles()) + tileX)).intValue();
	}

	/**
	 *

	 * Converts x coordinates in world space to tile coordinates; this probably
	 * involves dividing by the tile width.
	 *

	 *
	 * @param x
	 *        The coordinate, in world coordinates to convert.
	 * @return An x coordinate in tile coordinates.
	 */
	public int worldToTileCoordinatesX(float x) {
		int tx = (int) (x / layer.getTileWidth());

		if (tx < 0 || tx >= actualWidthInTiles()) {
			tx = tx % actualWidthInTiles();
		}

		return tx;
	}

	/**
	 *

	 * Converts y coordinates in world space to tile coordinates; this probably
	 * involves dividing by the tile height.
	 *

	 *
	 * @param y
	 *        The y coordinate, in world coordinates to convert.
	 * @return An y coordinate in tile coordinates.
	 */
	public int worldToTileCoordinatesY(float y) {
		int ty = (int) (y / layer.getTileHeight());

		if (ty < 0) {
			ty = ty % actualHeightInTiles();
		} else if (ty >= actualHeightInTiles()) {
			ty = actualHeightInTiles() - 1;
		}

		return ty;
	}

	public float tileToWorldCoordinatesX(int x) {
		return x * layer.getTileWidth();
	}

	public float tileToWorldCoordinatesY(int y) {
		return y * layer.getTileHeight();
	}

	public float worldToGridWorldCoordinatesX(float x) {
		return x - (x % layer.getTileWidth());
	}

	public float worldToGridWorldCoordinatesY(float y) {
		return y - (y % layer.getTileHeight());
	}

	public int actualWidthInTiles() {
		return layer.getWidth() * 2;
	}

	public float actualWidthInWorld() {
		return layer.getWidth() * layer.getTileWidth() * 2;
	}

	public int actualHeightInTiles() {
		return layer.getHeight();
	}

	/**
	 *

	 * Debug only, returns the collision map
	 *

	 *
	 * @return the integer-array collision map as stored in this
	 *         {@link TerrainCollisionMap}
	 */
	public ArrayList<Integer> getMap() {
		return collisionMap;
	}

	@Override
	public void reset() {
		layer = null;
		platformLayers.clear();
		collisionMap.clear();
	}

	/**
	 *

	 * Scans every cell in the layer and indiscriminately marks it as solid in a
	 * collision map, and returns the map.
	 *

	 *
	 * @param layer
	 *        The layer to use to generate the map.
	 * @param mirrorLayer
	 *        The mirror layer corresponding to the layer.
	 * @return A boolean array where map[layer.getWidth() * y + x] is a cell,
	 *         and true means "solid".
	 */
	public static ArrayList<Integer> generateCollisionArray(TiledMapTileLayer layer, TiledMapTileLayer mirrorLayer) {
		ArrayList<Integer> collisionMap = new ArrayList<Integer>();

		collisionMap.ensureCapacity((layer.getWidth() + mirrorLayer.getWidth()) * layer.getHeight());

		for (int y = 0; y < layer.getHeight(); y++) {
			for (int x = 0; x < (layer.getWidth() + mirrorLayer.getWidth()); x++) {
				if (x < layer.getWidth()) {
					collisionMap.add((layer.getCell(x, y) != null ? 1 : 0));
				} else {
					collisionMap.add((mirrorLayer.getCell(x - layer.getWidth(), y) != null ? 1 : 0));
				}
			}
		}

		return collisionMap;
	}

	/**
	 *

	 * Takes an already partially populated collision array for the map
	 * containing the layer and mirror layer given, adds to it the contents of
	 * the layers supplied and returns the modified array.
	 *

	 *

	 * Behaviour is undefined if collisionMap does not have similar
	 * dimensions to the layers given.
	 *

	 *
	 * @param collisionMap
	 *        A pre-populated list of integers to be modified.
	 * @param layer
	 *        A layer to add to the map.
	 * @param mirrorLayer
	 *        The mirror of layer
	 * @return collisionMap with the contents of the layers added.
	 */
	public static ArrayList<Integer> accumulateCollisionArray(ArrayList<Integer> collisionMap, TiledMapTileLayer layer,
			TiledMapTileLayer mirrorLayer) {
		// first check the array is sensibly dimensioned for the input layers
		int expectedSize = layer.getWidth() * 2 * layer.getHeight();
		int totalWidth = layer.getWidth() + mirrorLayer.getWidth();
		// widths should be the same but let's be careful

		if (collisionMap.size() != expectedSize) {
			Gdx.app.debug("ACCUMULATE_COLLISION_ARRAY", "Expected array of size " + expectedSize
					+ " for accumulation but only got size of " + collisionMap.size() + ".");
		}

		for (int y = 0; y < layer.getHeight(); y++) {
			// split into two loops to avoid an if statement and possible branch
			// prediction fails
			for (int x = 0; x < layer.getWidth(); x++) {
				int offset = y * totalWidth + x; // location of cell in array

				if (layer.getCell(x, y) != null) {
					collisionMap.set(offset, collisionMap.get(offset).intValue() + 1);
				}
			}

			for (int x = 0; x < mirrorLayer.getWidth(); x++) {
				int offset = y * totalWidth + x + layer.getWidth();

				if (mirrorLayer.getCell(x, y) != null) {
					collisionMap.set(offset, collisionMap.get(offset).intValue() + 1);
				}
			}
		}

		return collisionMap;
	}

	/**
	 *

	 * Creates and returns a new {@link TerrainCollisionMap} from the given map.
	 * If the map is not a valid Möbius map, the behaviour is undefined.
	 *

	 *
	 * @param map
	 *        The map from which to create a TerrainCollisionMap.
	 * @return
	 */
	public static TerrainCollisionMap generateCollisionMap(TiledMap map, TiledMap mirrorMap) {
		TerrainCollisionMap retVal = null;

		MapLayers layers = map.getLayers();
		MapLayers mirrorLayers = mirrorMap.getLayers();

		TiledMapTileLayer egLayer = (TiledMapTileLayer) layers.get(0);
		HashMap<TiledMapTileLayer, PlatformManipulationHandler> platformLayers = new HashMap<TiledMapTileLayer, PlatformManipulationHandler>();

		ArrayList<Integer> collisionArray = null;

		for (int i = 0; i < layers.getCount(); i++) {
			TiledMapTileLayer origLayer = (TiledMapTileLayer) layers.get(i);
			TiledMapTileLayer mirrorLayer = (TiledMapTileLayer) mirrorLayers.get(i);

			if ((LevelEntityFactory.isSolidLayer(origLayer) && LevelEntityFactory.isSolidLayer(mirrorLayer))
					|| (LevelEntityFactory.isInteractableLayer(origLayer) && LevelEntityFactory
							.isInteractableLayer(mirrorLayer))) {
				if (collisionArray == null) {
					collisionArray = generateCollisionArray(origLayer, mirrorLayer);
				} else {
					if (origLayer.getOpacity() >= WorldConstants.GLOBAL_SOLID_OPACITY_THRESHOLD) {
						collisionArray = accumulateCollisionArray(collisionArray, origLayer, mirrorLayer);
					}
				}

				if (LevelEntityFactory.isInteractableLayer(origLayer)) {
					PlatformManipulationHandler handler = null;
					ArrayList<TerrainMapTileCoordinate> tileCoords = generatePlatformTileCoordinateArray(origLayer,
							mirrorLayer);

					InteractableLayerTypes layerType = LevelEntityFactory.getInteractableLayerType(origLayer);

					if (layerType.equals(InteractableLayerTypes.DX) || layerType.equals(InteractableLayerTypes.DY)) {
						handler = new MovingPlatformManipulationHandler(collisionArray, tileCoords,
								layerType.equals(InteractableLayerTypes.DX),
								layerType.equals(InteractableLayerTypes.DY));
					} else if (layerType.equals(InteractableLayerTypes.FADABLE)) {
						float opacity = origLayer.getOpacity();
						handler = new FadableLayerManipulationHandler(collisionArray, tileCoords,
								(opacity >= WorldConstants.GLOBAL_SOLID_OPACITY_THRESHOLD));
					}

					if (handler == null) {
						throw new GdxRuntimeException("Trying to create handler for invalid platform type.");
					} else {
						platformLayers.put(origLayer, handler);
						platformLayers.put(mirrorLayer, handler);
					}
				}
			}
		}

		retVal = new TerrainCollisionMap(egLayer, platformLayers, collisionArray);

		return retVal;
	}

	/**
	 *

	 * Creates and populates an array with the tile coordinates of every
	 * non-null cell in the given layer and mirrorLayer.
	 *

	 *

	 * Useful for platform layers which need to be manipulated.
	 *

	 *
	 * @param layer
	 *        The layer from which to find cells.
	 * @param mirrorLayer
	 *        The layer, a mirror of layer from which to find cells.
	 * @return A populated array of every non-null cell in the layers.
	 */
	public static ArrayList<TerrainMapTileCoordinate> generatePlatformTileCoordinateArray(TiledMapTileLayer layer,
			TiledMapTileLayer mirrorLayer) {
		ArrayList<TerrainMapTileCoordinate> retVal = new ArrayList<TerrainCollisionMap.TerrainMapTileCoordinate>();
		int width = layer.getWidth() + mirrorLayer.getWidth();

		for (int y = 0; y < layer.getHeight(); y++) {
			for (int x = 0; x < layer.getWidth(); x++) {
				if (layer.getCell(x, y) != null) {
					retVal.add(new TerrainMapTileCoordinate(width, x, y));
				}
			}

			for (int x = 0; x < mirrorLayer.getWidth(); x++) {
				if (mirrorLayer.getCell(x, y) != null) {
					retVal.add(new TerrainMapTileCoordinate(width, x + layer.getWidth(), y, true));
				}
			}
		}

		// Gdx.app.debug("GEN_PLATFORM_TILE_ARRAY",
		// "Generated " + retVal.size() + " tile coordinates for layer " +
		// layer.getName() + " and mirror "
		// + mirrorLayer.getName());

		return retVal;
	}

	/**
	 *

	 * A super simple integer 2D vector to hold tile coords internally.
	 *

	 *
	 * @author Ashley Davis (SgtCoDFish)
	 */
	public static class TerrainMapTileCoordinate {
		public int		width		= -1;
		public int		x			= -1;
		public int		y			= -1;
		public boolean	isMirror	= false;

		public TerrainMapTileCoordinate(int width) {
			this(width, -1, -1, false);
		}

		public TerrainMapTileCoordinate(int width, int x, int y) {
			this(width, x, y, false);
		}

		public TerrainMapTileCoordinate(int width, int x, int y, boolean isMirror) {
			set(x, y);
			this.width = width;
			this.isMirror = isMirror;
		}

		public void set(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public int to1DOffset() {
			return width * y + x;
		}
	}

	public static abstract class PlatformManipulationHandler {
		protected ArrayList<Integer>				map			= null;
		public ArrayList<TerrainMapTileCoordinate>	tileCoords	= null;

		public PlatformManipulationHandler(ArrayList<Integer> map, ArrayList<TerrainMapTileCoordinate> tileCoords) {
			this.map = map;
			this.tileCoords = tileCoords;
		}

		public void update(int degree) {
			begin();

			for (TerrainMapTileCoordinate tc : tileCoords) {
				manipulate(tc, degree);
			}

			end();
		}

		public void begin() {

		}

		public void end() {

		}

		protected abstract void manipulate(TerrainMapTileCoordinate tileCoord, int degree);
	}

	public static class MovingPlatformManipulationHandler extends PlatformManipulationHandler {
		protected boolean	moveInX	= false;
		protected boolean	moveInY	= false;

		public MovingPlatformManipulationHandler(ArrayList<Integer> map,
				ArrayList<TerrainMapTileCoordinate> tileCoords, boolean moveInX, boolean moveInY) {
			super(map, tileCoords);
			this.moveInX = moveInX;
			this.moveInY = moveInY;

			if (!moveInX && !moveInY) {
				// if we're not moving in either direction, what's the point?
				throw new GdxRuntimeException("MovingPlatformManipulationHandler created with no movement direction.");
			}
		}

		@Override
		protected void manipulate(TerrainMapTileCoordinate tileCoord, int degree) {
			/*
			 * Note this is not very optimised as a move by 1 simplifies to
			 * changing the beginning and end of a platform (but only if we can
			 * guarantee it's a joined platform).
			 *
			 * Still, the game isn't exactly intensive and this optimisation is
			 * probably premature until problems present themselves.
			 */

			map.set(tileCoord.to1DOffset(), map.get(tileCoord.to1DOffset()) - 1);

			tileCoord.x += (moveInX ? degree : 0);
			tileCoord.y -= (moveInY ? degree * (tileCoord.isMirror ? -1 : 1) : 0);

			map.set(tileCoord.to1DOffset(), map.get(tileCoord.to1DOffset()) + 1);
		}
	}

	public static class FadableLayerManipulationHandler extends PlatformManipulationHandler {
		public boolean	isOpaque	= false;

		public FadableLayerManipulationHandler(ArrayList<Integer> map, ArrayList<TerrainMapTileCoordinate> tileCoords,
				boolean startsOpaque) {
			super(map, tileCoords);
			this.isOpaque = startsOpaque;
		}

		@Override
		protected void manipulate(TerrainMapTileCoordinate tileCoord, int degree) {
			int newVal = map.get(tileCoord.to1DOffset()) + degree * (isOpaque ? -1 : 1);
			map.set(tileCoord.to1DOffset(), newVal);
		}

		@Override
		public void end() {
			isOpaque = !isOpaque;
		}

	}
}


text:
/** Bar chart **/

var docEl = document.documentElement;
var divEl = document.getElementById('svg');
//divEl.hide();

var width = divEl.clientWidth,
    height =  300;

var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
.rangeRound([height, 0]);

var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888"]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));

/* Main */

function updateWindow(){
    "use strict";
    width = divEl.clientWidth;
    height = 500;

    svg.attr("width", width).attr("height", height);
}

window.onresize = updateWindow;

/* Support envoi données */
d3.select("#upload-input").on("click", function(){
    document.getElementById("hidden-file-upload").click();
});
d3.select("#hidden-file-upload").on("change", function(){
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        //Vars fichiers
        var uploadFile = this.files[0];
        var filereader = new window.FileReader();

        filereader.onload = function(){
            //Fichier brut
            var txtRes = filereader.result;
            try{
                //TODO Lire les fichiers en CSV
                var data = d3.csv.parse(txtRes);
                callSvg(data);

            }catch(err){
                window.alert("Erreur de parsing \nerror message: " + err.message);
                return;
            }
        };
        filereader.readAsText(uploadFile);

    } else {
        alert("Navigateur incompatible, essayez avec Google chrome ou Firefox (dernières versions).");
    }
});

function callSvg(data){
    var nbGroupe = 0;
    var nbGenes = 0;

    color.domain(data.map(function(d) { // liste des groupes (1/2/3/..)

        console.log("dgroupe : ", d.Groupe);

        return d.Groupe;
    })); //met les couleurs pour les groupes
    nbGroupe = color.domain().length;
    //    console.log("colorfinal : ", color.domain());
    x.domain(d3.keys(data[0]).filter(function(key) {         //récupère le nom des gènes pour l'axe x
        if(key !== "Groupe" && key !== "genespatients"){
            //console.log("key: ", key);
            nbGenes++;
            return key;} }));

    var groupeTmp = "";
    var dataRanger = new Array();

    data.forEach(function(d) {
        x.domain().map(function(name) {
            var test = +d.Groupe;
            if(typeof  dataRanger[name] === 'undefined'){
                dataRanger[name] = new Array();
                for(var i = 0; i < nbGroupe; i++){
                    dataRanger[name][i] = 0;
                }
            }

            dataRanger[name][test-1] += +d[name];
        });
    });
    var dataFinal = new Array();

    for(var key in dataRanger){
        var dataObject = new Object();
        dataObject["ages"] = new Array();

        var cpt = 0;
        for(var j = 1; j < nbGroupe+1; j++){
            var ageObject = new Object();
            dataObject[j] = dataRanger[key][j-1];
            ageObject["name"] = j;
            ageObject["y0"] = cpt;
            cpt = cpt + dataRanger[key][j-1];
            ageObject["y1"] = cpt;
            dataObject["ages"][j-1] = ageObject;
        }
        dataObject["total"] = cpt;
        dataObject["groupeGenes"] = key;
        dataFinal.push(dataObject);
    }

    y.domain([0, d3.max(dataFinal, function(d) { return d.total; })]);

    /** SVG **/
    var svg = d3.select(divEl).append("svg")
    .attr("width", width)
    .attr("height", height);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Population");

    var state = svg.selectAll(".groupeGenes")
    .data(dataFinal)
    .enter().append("g")
    .attr("class", "g")
    .attr("transform", function(d) { return "translate(" + x(d.groupeGenes) + ",0)"; });

    state.selectAll("rect")
        .data(function(d) { return d.ages; })
        .enter().append("rect")
        .attr("width", x.rangeBand())
        .attr("y", function(d) { return y(d.y1); })
        .attr("height", function(d) { return y(d.y0) - y(d.y1); })
        .style("fill", function(d) { return color(d.name); });

    var legend = svg.selectAll(".legend")
    .data(color.domain().slice().reverse())
    .enter().append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color);

    legend.append("text")
        .attr("x", width - 24)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function(d) { return d; });
}

//BarCreator.prototype.setIdCt = function(idct){
//    this.idct = idct;
//};
//
//var BarCreator(svg){
//    var thisGraph = this;
//    thisGraph.idct = 0;
//
//    thisGraph.state = {
//        selectedBar: null,
//        mouseDownBar: null,
//        justDragged: false,
//        justScaleTransGraph: false,
//        selectedText: null
//    };
//
//    var xDisplay = svg.append('svg:xDisplay');
//    xDisplay.attr("class", "x axis")
//        .attr("transform", "translate(0," + height + ")")
//        .call(xAxis);
//
//    var yDisplay = svg.append('svg:yDisplay');
//    yDisplay.attr("class", 'y axis')
//        .call(yAxis);
//
//    thisGraph.svg = svg;
//
//    thisGraph.svgG = svg.append("g")
//        .classed(thisGraph.consts.graphClass, true);
//    var svgG = thisGraph.svgG;
//
//
//}
//
//
//BarCreator.prototype.consts =  {
//    selectedClass: "selected",
//    barClass: "barClass",
//    graphClass: "graph",
//};
//
//// call to propagate changes to graph
//BarCreator.prototype.updateGraph = function(){
//
//    var thisGraph = this,
//        consts = thisGraph.consts,
//        state = thisGraph.state;
//
//};

/* TODO :
Hover sur groupe
Zoom
D3.Behavior.zoom (mousewheel)
*/


text:
// Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii
// Author : Dean Shi
// Date   : 2018-01-20

/***************************************************************************************
 *
 * Say you have an array for which the ith element is the price of a given stock on day
 * i.
 *
 * Design an algorithm to find the maximum profit. You may complete as many
 * transactions as you like (ie, buy one and sell one share of the stock multiple times)
 * . However, you may not engage in multiple transactions at the same time (ie, you
 * must sell the stock before you buy again).
 *
 ***************************************************************************************/

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let sum = 0

    for (let i = 1; i < prices.length; i++) {
        if (prices[i] > prices[i - 1]) sum += prices[i] - prices[i - 1]
    }

    return sum
};


text:
package com.spectralogic.ds3client.helpers.strategy.transferstrategy;

import com.google.common.base.Preconditions;
import com.spectralogic.ds3client.helpers.ExceptionClassifier;
import com.spectralogic.ds3client.helpers.JobPart;

import java.io.IOException;

/**
 * A {@link TransferRetryDecorator} that will continue to retry a blob transfer at most {@code maxNumObjectTransferAttempts}
 * times, until the transfer either succeeds or experiences an unrecoverable exception.
 */
public class MaxNumObjectTransferAttemptsDecorator implements TransferRetryDecorator {
    private final int maxNumObjectTransferAttempts;
    private TransferMethod transferMethodDelegate;

    public MaxNumObjectTransferAttemptsDecorator(final int maxNumObjectTransferAttempts) {
        this.maxNumObjectTransferAttempts = maxNumObjectTransferAttempts;
    }

    /**
     * @param transferMethod An instance of {@link TransferMethod} used as a delegate when attempting a transfer.
     * @return An instance of this class, with the intent to be able to chain a call to
     *         {@code transferJobPart}.
     */
    @Override
    public TransferMethod wrap(final TransferMethod transferMethod) {
        Preconditions.checkNotNull(transferMethod, "transferMethod may not be null.");
        transferMethodDelegate = transferMethod;
        return this;
    }

    /**
     * @param jobPart An instance of {@link JobPart}, which tells us which Black Pearl is the source
     *                or destination for a blob transfer.
     * @throws IOException
     */
    @Override
    public void transferJobPart(final JobPart jobPart) throws IOException {
        int objectTransfersAttempted = 0;

        while(true) {
            try {
                transferMethodDelegate.transferJobPart(jobPart);
                break;
            } catch (final Throwable t) {
                if (ExceptionClassifier.isUnrecoverableException(t) || ++objectTransfersAttempted >= maxNumObjectTransferAttempts) {
                    throw t;
                }
            }
        }
    }
}


text:
#include <stddef.h>
#include "unity_fixture.h"
#include "os/task.h"
#include "tests/task_mock.h"

typedef struct _task_delay_call_t task_delay_call_t;

struct _task_delay_call_t
{
	int32_t				expect_ms;
	task_delay_ms_delegate_f	then_cbk;
	task_delay_call_t		*next;
};

void *unity_malloc(size_t size);
void unity_free(void *ptr);

static void mock_task_delay_ms(int32_t ms);

static task_delay_call_t *gs_first = NULL;
static task_delay_call_t *gs_last = NULL;

static void mock_task_delay_ms(int32_t ms)
{
	int32_t expected = 0;
	TEST_ASSERT_NOT_NULL_MESSAGE(gs_first, "Unexpected call to task_delay_ms");
	expected = gs_first->expect_ms;
	if ((expected == ms) && (gs_first->then_cbk != NULL)) {
		gs_first->then_cbk();
	}

	task_delay_call_t *next = gs_first->next;
	unity_free(gs_first);
	gs_first = next;
	if (gs_first == NULL) {
		gs_last = NULL;
	}

	TEST_ASSERT_EQUAL_INT32(expected, ms);
}

static void task_delay_ms_ExpectthenCbk(uint32_t ms, task_delay_ms_delegate_f cbk)
{
	task_delay_call_t *new = unity_malloc(sizeof(task_delay_call_t));
	new->expect_ms = ms;
	new->then_cbk = cbk;
	new->next = NULL;

	if (gs_first == NULL) {
		gs_first = new;
	}
	if (gs_last != NULL) {
		gs_last->next = new;
	}
	gs_last = new;
}

void task_mock_delay_ms_setup(void)
{
	UT_PTR_SET(task_delay_ms, mock_task_delay_ms);
}

void task_delay_ms_ExpectNthenCbk(uint32_t ms, uint32_t times, task_delay_ms_delegate_f cbk)
{
	if (times == 0) {
		return;
	}

	for (int i = 0; i < (times-1); i++) {
		task_delay_ms_ExpectthenCbk(ms, NULL);
	}
	task_delay_ms_ExpectthenCbk(ms, cbk);
}

void task_mock_delay_ms_verify(void)
{
	bool success = (gs_last == NULL);
	while (gs_last != NULL) {
		task_delay_call_t *c = gs_last->next;
		unity_free(gs_last);
		gs_last = c;
	}
	gs_first = NULL;
	TEST_ASSERT_MESSAGE(success, "missing call to task_delay_ms");
}


text:
## Objective: The objective of this workflow is to identify concepts (genes) that are related with Butanol tolerance within the EKP (Euretos Knowledge Platform) platform.

This repo contains notebook ranging from basic usages of this script that is mapped with [EKP](http://www.euretos.com/EKPlatform.php) (Euretos Knowledge Platform) API.

## How to use

The python notebooks are written in [Jupyter](http://jupyter.org/).

- **View** We can view the notebooks on either
  [github](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/DSM_workflow.ipynb)

- **Run** We can run and modify these notebooks if both [R](https://www.r-project.org/) and [jupyter](http://jupyter.org/) are installed together with its required. These scripts are tested on Ubuntu but should work as well on Windows (not tested).

  If you have a EKP, here is an easier way to run the notebooks:

  1. Create a config.yaml file with received username and passwords from EKP.

  2. Create a file with SGD identifiers and replace this with and its name [20170119_GeneList_DSM.txt](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/20170119_GeneList_DSM.txt)

  1.  Launch a [DSM_Workflow.R](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/DSM_workflow.R) instance by either with R or using the iPython notebook in an interactive way.

  2.  Once launch is succeed a complete list of concepts related with Butanol Tolerance will be created for example [ConceptsRelatedwithButanolTriples.csv](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/ConceptsRelatedwithButanolTriples.csv)

## General Workflow
### Steps carried out within this workflow
1. File [EuretosInfrastructure.R](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/EuretosInfrastructure.R) is the actual file which fetches information from EKP.
2. [DSM_Workflow.R](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/DSM_workflow.R) is the file where actual analysis happens.
3. Concepts for gene identifiers (Provided by DSM) are searched within the EKP for their relationship with "Butanol".
4. Next concepts are for these gene identifiers (Provided by DSM) are searched again within EKP for their relationship with "Resistance to Chemicals".
5. The resulting relationships are combined together to generate the output [ConceptsRelatedwithButanolTriples.csv](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/ConceptsRelatedwithButanolTriples.csv)
6. Results are summarized using post processing script that is at the bottom of [DSM_Workflow.R](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/DSM_workflow.R)
7. Final results consists of information on Genes, Intermetiate Concepts, Score (PWS from EKP) and Provenance (PubMed IDs) for further analysis.
8. A graphical format of the workflow can be found [DSM_workflow.png](https://github.com/DTL-FAIRData/ODEX4all-UseCases/blob/master/DSM/src/DSM_workflow.png)


text:
package com.hello2morrow.sonargraph.integration.access.model.internal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;

import com.hello2morrow.sonargraph.integration.access.model.IElement;
import com.hello2morrow.sonargraph.integration.access.model.ILogicalNamespace;
import com.hello2morrow.sonargraph.integration.access.model.ILogicalProgrammingElement;
import com.hello2morrow.sonargraph.integration.access.model.IMetricId;
import com.hello2morrow.sonargraph.integration.access.model.IMetricLevel;
import com.hello2morrow.sonargraph.integration.access.model.IMetricValue;
import com.hello2morrow.sonargraph.integration.access.model.INamedElement;
import com.hello2morrow.sonargraph.integration.access.model.INamedElementContainer;

public abstract class NamedElementContainerImpl extends NamedElementImpl implements INamedElementContainer
{
    private static final long serialVersionUID = 995206422502257231L;
    private final Map<IMetricLevel, HashMap<IMetricId, HashMap<INamedElement, IMetricValue>>> metricValues = new HashMap<>();
    private final Map<String, Set<INamedElement>> kindToNamedElements = new HashMap<>();
    private final Set<LogicalNamespaceImpl> logicalNamespaces = new TreeSet<>(new NamedElementComparator());
    private final Set<LogicalProgrammingElementImpl> logicalProgrammingElements = new TreeSet<>(new NamedElementComparator());
    private final MetaDataAccessImpl metaDataAccessImpl;
    private final NamedElementRegistry elementRegistryImpl;

    public NamedElementContainerImpl(final String kind, final String presentationKind, final String name, final String presentationName,
            final String fqName, final String description, final MetaDataAccessImpl metaDataAccessImpl,
            final NamedElementRegistry elementRegistryImpl, final String imageResourceName)
    {
        super(kind, presentationKind, name, presentationName, fqName, description, imageResourceName);
        assert metaDataAccessImpl != null : "Parameter 'metaDataAccessImpl' of method 'NamedElementContainerImpl' must not be null";
        assert elementRegistryImpl != null : "Parameter 'elementRegistryImpl' of method 'NamedElementContainerImpl' must not be null";
        this.metaDataAccessImpl = metaDataAccessImpl;
        this.elementRegistryImpl = elementRegistryImpl;
    }

    public final MetaDataAccessImpl getMetaDataAccess()
    {
        return metaDataAccessImpl;
    }

    public final NamedElementRegistry getElementRegistry()
    {
        return elementRegistryImpl;
    }

    public final void addElement(final INamedElement element)
    {
        assert element != null : "Parameter 'element' of method 'addElement' must not be null";

        Set<INamedElement> namedElements = kindToNamedElements.get(element.getKind());
        if (namedElements == null)
        {
            namedElements = new LinkedHashSet<>();
            kindToNamedElements.put(element.getKind(), namedElements);
        }
        namedElements.add(element);
        if (!element.isLocationOnly())
        {
            //'location-only' elements are never added to the registry - they are reachable through their refactored  counterparts and never have issues nor metrics
            getElementRegistry().addElement(element);
        }
    }

    public boolean hasElement(final INamedElement element)
    {
        assert element != null : "Parameter 'element' of method 'hasElement' must not be null";
        final Set<INamedElement> namedElements = kindToNamedElements.get(element.getKind());
        return namedElements != null ? namedElements.contains(element) : false;
    }

    @Override
    public final Set<INamedElement> getElements(final String elementKind)
    {
        assert elementKind != null && elementKind.length() > 0 : "Parameter 'elementKind' of method 'getElements' must not be empty";
        final Set<INamedElement> namedElements = kindToNamedElements.get(elementKind);
        return namedElements != null ? Collections.unmodifiableSet(namedElements) : Collections.emptySet();
    }

    @Override
    public final Set<INamedElement> getElements(final Predicate<INamedElement> predicate)
    {
        assert predicate != null;

        final Set<INamedElement> result = new HashSet<>();

        for (final Set<INamedElement> elements : kindToNamedElements.values())
        {
            elements.stream().filter(n -> predicate.test(n)).forEach(n -> result.add(n));
        }
        return result;
    }

    @Override
    public final Set<String> getElementKinds()
    {
        return Collections.unmodifiableSet(kindToNamedElements.keySet());
    }

    public final void addLogicalNamespace(final LogicalNamespaceImpl logicalNamespaceImpl)
    {
        assert logicalNamespaceImpl != null : "Parameter 'logicalNamespaceImpl' of method 'addLogicalNamespace' must not be null";
        final boolean success = logicalNamespaces.add(logicalNamespaceImpl);
        assert success : "Logical namespace already added: " + logicalNamespaceImpl;
    }

    public final void addLogicalProgrammingElement(final LogicalProgrammingElementImpl logicalProgrammingElementImpl)
    {
        assert logicalProgrammingElementImpl != null : "Parameter 'logicalProgrammingElementImpl' of method 'addLogicalProgrammingElement' must not be null";
        final boolean success = logicalProgrammingElements.add(logicalProgrammingElementImpl);
        assert success : "Logical programming element already added: " + logicalProgrammingElementImpl;
    }

    @Override
    public final Set<ILogicalNamespace> getLogicalNamespaces()
    {
        return Collections.unmodifiableSet(logicalNamespaces);
    }

    @Override
    public final Set<ILogicalProgrammingElement> getLogicalProgrammingElements()
    {
        return Collections.unmodifiableSet(logicalProgrammingElements);
    }

    public final void addMetricValueForElement(final IMetricValue value, final INamedElement element)
    {
        assert value != null : "Parameter 'value' of method 'addMetricValue' must not be null";
        final IMetricId metricId = value.getId();
        assert metaDataAccessImpl.getMetricIds().containsKey(metricId.getName()) : "MetricId '" + metricId.getName() + "'has not been added";
        assert element != null : "Parameter 'element' of method 'addMetricValueForElement' must not be null";

        final IMetricLevel level = value.getLevel();
        assert metaDataAccessImpl.getMetricLevels().containsKey(level.getName()) : "Level '" + level.getName() + "' has not been added";

        final HashMap<IMetricId, HashMap<INamedElement, IMetricValue>> valuesOfLevel;
        if (!metricValues.containsKey(level))
        {
            valuesOfLevel = new HashMap<>();
            metricValues.put(level, valuesOfLevel);
        }
        else
        {
            valuesOfLevel = metricValues.get(level);
        }

        final HashMap<INamedElement, IMetricValue> valuesForMetric;
        if (!valuesOfLevel.containsKey(metricId))
        {
            valuesForMetric = new HashMap<>();
            valuesOfLevel.put(metricId, valuesForMetric);
        }
        else
        {
            valuesForMetric = valuesOfLevel.get(metricId);
        }

        valuesForMetric.put(element, value);
    }

    public final Optional<IMetricValue> getMetricValueForElement(final IMetricId metricId, final IMetricLevel metricLevel, final String elementName)
    {
        assert metricId != null : "Parameter 'metricId' of method 'getMetricValueForElement' must not be null";
        assert elementName != null && elementName.length() > 0 : "Parameter 'elementName' of method 'getMetricValueForElement' must not be empty";

        if (!metricValues.containsKey(metricLevel))
        {
            return Optional.empty();
        }

        final HashMap<IMetricId, HashMap<INamedElement, IMetricValue>> metricIdsOfLevel = metricValues.get(metricLevel);
        if (!metricIdsOfLevel.containsKey(metricId))
        {
            return Optional.empty();
        }

        final Optional<INamedElement> element = getElementRegistry().getElement(elementName);
        if (!element.isPresent())
        {
            return Optional.empty();
        }

        final IElement namedElement = element.get();
        final Map<INamedElement, IMetricValue> valuesForMetricId = metricIdsOfLevel.get(metricId);
        if (!valuesForMetricId.containsKey(namedElement))
        {
            return Optional.empty();
        }

        return Optional.of(valuesForMetricId.get(namedElement));
    }

    public final void addMetricLevel(final IMetricLevel level)
    {
        assert level != null : "Parameter 'level' of method 'addMetricLevel' must not be null";
        metaDataAccessImpl.addMetricLevel(level);
    }

    public final Map<String, IMetricLevel> getAllMetricLevels()
    {
        return metaDataAccessImpl.getMetricLevels();
    }

    public List<IMetricId> getMetricIdsForLevel(final IMetricLevel metricLevel)
    {
        assert metricLevel != null : "Parameter 'metricLevel' of method 'getMetricIdsForLevel' must not be null";
        if (!metricValues.containsKey(metricLevel))
        {
            return Collections.emptyList();
        }
        return Collections.unmodifiableList(new ArrayList<>(metricValues.get(metricLevel).keySet()));
    }

    public Map<INamedElement, IMetricValue> getMetricValues(final String metricLevel, final String metricId)
    {
        assert metricLevel != null && metricLevel.length() > 0 : "Parameter 'metricLevel' of method 'getMetricValues' must not be empty";
        assert metricId != null && metricId.length() > 0 : "Parameter 'metricId' of method 'getMetricValues' must not be empty";

        final Map<String, IMetricLevel> metricLevels = getAllMetricLevels();
        if (!metricLevels.containsKey(metricLevel))
        {
            return Collections.emptyMap();
        }

        final IMetricLevel level = metricLevels.get(metricLevel);
        final HashMap<IMetricId, HashMap<INamedElement, IMetricValue>> metricIdValueMap = metricValues.get(level);

        final Optional<IMetricId> optionalId = metricIdValueMap.keySet().stream().filter((final IMetricId id) -> id.getName().equals(metricId))
                .findAny();

        if (!optionalId.isPresent())
        {
            return Collections.emptyMap();
        }

        return Collections.unmodifiableMap(metricIdValueMap.get(optionalId.get()));
    }

    public Map<INamedElement, IMetricValue> getMetricValues(final IMetricLevel metricLevel, final IMetricId metricId)
    {
        assert metricLevel != null : "Parameter 'metricLevel' of method 'getMetricValues' must not be null";
        assert metricId != null : "Parameter 'metricId' of method 'getMetricValues' must not be null";

        if (!metricValues.containsKey(metricLevel))
        {
            return Collections.emptyMap();
        }

        final HashMap<IMetricId, HashMap<INamedElement, IMetricValue>> metricIdValueMap = metricValues.get(metricLevel);
        if (!metricIdValueMap.containsKey(metricId))
        {
            return Collections.emptyMap();
        }

        return Collections.unmodifiableMap(metricIdValueMap.get(metricId));
    }
}


text:
#import <iWorkImport/KNRecordingEvent.h>

// Not exported
@interface KNRecordingLaserEvent : KNRecordingEvent
{
    struct CGPoint mUnscaledLocation;
}

@property(readonly, nonatomic) struct CGPoint unscaledLocation; // @synthesize unscaledLocation=mUnscaledLocation;
- (unsigned long long)hash;
- (_Bool)isEqual:(id)arg1;
- (id)description;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithStartTime:(double)arg1;
- (id)initWithStartTime:(double)arg1 unscaledLocation:(struct CGPoint)arg2;

@end


text:
package org.mrgeo.data.raster;

import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconstConstants;
import org.mrgeo.aggregators.Aggregator;
import org.mrgeo.data.raster.Interpolator.Bilinear;
import org.mrgeo.data.raster.Interpolator.Nearest;
import org.mrgeo.data.raster.RasterWritable.RasterWritableException;
import org.mrgeo.utils.ByteArrayUtils;
import org.mrgeo.utils.FloatUtils;
import org.mrgeo.utils.GDALUtils;
import org.mrgeo.utils.tms.Bounds;
import org.mrgeo.utils.tms.Pixel;
import org.mrgeo.utils.tms.TMSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.io.Serializable;
import java.nio.*;

public abstract class MrGeoRaster implements Serializable
{
private static Logger log = LoggerFactory.getLogger(MrGeoRaster.class);
final static int HEADER_LEN = 12;
// data offset: byte (VERSION) + int (width) + int (height) + short (bands) + byte (datatype)
private final static int VERSION_OFFSET = 0;    // start
private final static int WIDTH_OFFSET = 1;      // byte (VERSION)
private final static int HEIGHT_OFFSET = 5;     // byte (VERSION) + int (width)
private final static int BANDS_OFFSET = 9;      // byte (VERSION) + int (width) + int (height)
private final static int DATATYPE_OFFSET = 11;  // byte (VERSION) + int (width) + int (height) + short (bands)
private final static byte VERSION = 0x03;  // MUST NOT BE 0!
final byte[] data;
private final int width;
private final int height;
private final int bands;
private final int datatype;
private final int dataoffset;
private final int bandoffset;

MrGeoRaster(int width, int height, int bands, int datatype, byte[] data, int dataoffset)
{
  this.width = width;
  this.height = height;
  this.bands = bands;
  this.datatype = datatype;
  this.data = data;
  this.dataoffset = dataoffset;

  bandoffset = width * height;
}

public static MrGeoRaster createEmptyRaster(int width, int height, int bands, int datatype) throws MrGeoRasterException
{
  switch (datatype)
  {
  case DataBuffer.TYPE_BYTE:
    return MrGeoByteRaster.createEmptyRaster(width, height, bands);
  case DataBuffer.TYPE_FLOAT:
    return MrGeoFloatRaster.createEmptyRaster(width, height, bands);
  case DataBuffer.TYPE_DOUBLE:
    return MrGeoDoubleRaster.createEmptyRaster(width, height, bands);
  case DataBuffer.TYPE_INT:
    return MrGeoIntRaster.createEmptyRaster(width, height, bands);
  case DataBuffer.TYPE_SHORT:
    return MrGeoShortRaster.createEmptyRaster(width, height, bands);
  case DataBuffer.TYPE_USHORT:
    return MrGeoUShortRaster.createEmptyRaster(width, height, bands);
  default:
    throw new RasterWritableException("Error trying to read raster.  Bad raster data type");
  }
}

public static MrGeoRaster createEmptyRaster(int width, int height, int bands, int datatype, double nodata)
    throws MrGeoRasterException
{
  MrGeoRaster raster = createEmptyRaster(width, height, bands, datatype);
  raster.fill(nodata);
  return raster;
}

public static MrGeoRaster createEmptyRaster(int width, int height, int bands, int datatype, double[] nodatas)
    throws MrGeoRasterException
{
  MrGeoRaster raster = createEmptyRaster(width, height, bands, datatype);
  raster.fill(nodatas);
  return raster;
}

public static MrGeoRaster createRaster(int width, int height, int bands, int datatype, byte[] data, int dataOffset)
{
  switch (datatype)
  {
  case DataBuffer.TYPE_BYTE:
    return new MrGeoByteRaster(width, height, bands, data, dataOffset);
  case DataBuffer.TYPE_FLOAT:
    return new MrGeoFloatRaster(width, height, bands, data, dataOffset);
  case DataBuffer.TYPE_DOUBLE:
    return new MrGeoDoubleRaster(width, height, bands, data, dataOffset);
  case DataBuffer.TYPE_INT:
    return new MrGeoIntRaster(width, height, bands, data, dataOffset);
  case DataBuffer.TYPE_SHORT:
  case DataBuffer.TYPE_USHORT:
    return new MrGeoShortRaster(width, height, bands, data, dataOffset);
  default:
    throw new RasterWritableException("Error trying to read raster.  Bad raster data type");
  }
}

public static MrGeoRaster fromRaster(Raster raster) throws IOException
{
  MrGeoRaster mrgeo =
      createEmptyRaster(raster.getWidth(), raster.getHeight(), raster.getNumBands(), raster.getTransferType());

  for (int b = 0; b < raster.getNumBands(); b++)
  {
    for (int y = 0; y < raster.getHeight(); y++)
    {
      for (int x = 0; x < raster.getWidth(); x++)
      {
        switch (mrgeo.datatype())
        {
        case DataBuffer.TYPE_BYTE:
          mrgeo.setPixel(x, y, b, (byte) raster.getSample(x, y, b));
          break;
        case DataBuffer.TYPE_INT:
          mrgeo.setPixel(x, y, b, raster.getSample(x, y, b));
          break;
        case DataBuffer.TYPE_SHORT:
        case DataBuffer.TYPE_USHORT:
          mrgeo.setPixel(x, y, b, (short) raster.getSample(x, y, b));
          break;
        case DataBuffer.TYPE_FLOAT:
          mrgeo.setPixel(x, y, b, raster.getSampleFloat(x, y, b));
          break;
        case DataBuffer.TYPE_DOUBLE:
          mrgeo.setPixel(x, y, b, raster.getSampleDouble(x, y, b));
          break;
        default:
          throw new RasterWritableException("Error trying to read raster.  Bad raster data type");
        }
      }
    }
  }

  return mrgeo;
}

public static MrGeoRaster fromDataset(Dataset dataset) throws MrGeoRasterException
{
  return fromDataset(dataset, 0, 0, dataset.GetRasterXSize(), dataset.GetRasterYSize());
}

public static MrGeoRaster fromDataset(Dataset dataset, int x, int y, int width,
    int height)
    throws MrGeoRasterException
{
  int gdaltype = dataset.GetRasterBand(1).getDataType();
  int bands = dataset.GetRasterCount();
  int datasize = gdal.GetDataTypeSize(gdaltype) / 8;

  MrGeoRaster raster = createEmptyRaster(width, height, bands, GDALUtils.toRasterDataBufferType(gdaltype));

  for (int b = 0; b < bands; b++)
  {
    Band band = dataset.GetRasterBand(b + 1); // gdal bands are 1's based
    byte[] data = new byte[datasize * width * height];

    int success = band.ReadRaster(x, y, width, height, width, height, gdaltype, data);

    if (success != gdalconstConstants.CE_None)
    {
      String lastErr = gdal.GetLastErrorMsg();
      log.warn("Failed reading raster. gdal error: " + success + ": " + lastErr + " (This may be a result of the threading problem in GDAL)");
    }
    //GDALUtils.swapBytes(data, gdaltype);

    System.arraycopy(data, 0, raster.data, raster.calculateByteOffset(0, 0, b), data.length);
  }

  return raster;
}

static int writeHeader(int width, int height, int bands, int datatype, byte[] data)
{
  ByteArrayUtils.setByte(VERSION, data, VERSION_OFFSET);
  ByteArrayUtils.setInt(width, data, WIDTH_OFFSET);
  ByteArrayUtils.setInt(height, data, HEIGHT_OFFSET);
  ByteArrayUtils.setShort((short) bands, data, BANDS_OFFSET);
  ByteArrayUtils.setByte((byte) datatype, data, DATATYPE_OFFSET);
  return HEADER_LEN;
}

static int[] readHeader(byte[] data)
{
  return new int[]{
      ByteArrayUtils.getByte(data, VERSION_OFFSET),
      ByteArrayUtils.getInt(data, WIDTH_OFFSET),
      ByteArrayUtils.getInt(data, HEIGHT_OFFSET),
      ByteArrayUtils.getShort(data, BANDS_OFFSET),
      ByteArrayUtils.getByte(data, DATATYPE_OFFSET),
      HEADER_LEN
  };
}

static MrGeoRaster createRaster(byte[] data)
{
  int[] header = readHeader(data);
  return createRaster(header[1], header[2], header[3], header[4], data, header[5]);
}

final public MrGeoRaster createCompatibleRaster(int width, int height) throws MrGeoRasterException
{
  return createEmptyRaster(width, height, bands, datatype);
}

final public MrGeoRaster createCompatibleEmptyRaster(int width, int height, double nodata) throws MrGeoRasterException
{
  MrGeoRaster raster = createEmptyRaster(width, height, bands, datatype);

  MrGeoRaster row = createEmptyRaster(width, 1, 1, datatype);
  for (int x = 0; x < width; x++)
  {
    row.setPixel(x, 0, 0, nodata);
  }

  int headerlen = raster.dataoffset;
  int len = row.data.length - headerlen;

  for (int b = 0; b < bands; b++)
  {
    for (int y = 0; y < height; y++)
    {
      int offset = raster.calculateByteOffset(0, y, b);

      System.arraycopy(row.data, headerlen, raster.data, offset, len);
    }
  }

  return raster;
}

final public MrGeoRaster createCompatibleEmptyRaster(int width, int height, double[] nodata) throws MrGeoRasterException
{
  MrGeoRaster raster = createEmptyRaster(width, height, bands, datatype);

  MrGeoRaster row;

  for (int b = 0; b < bands; b++)
  {
    row = createEmptyRaster(width, 1, 1, datatype);

    for (int x = 0; x < width; x++)
    {
      row.setPixel(x, 0, 0, nodata[b]);
    }

    int headerlen = raster.dataoffset();
    int len = row.data.length - headerlen;

    for (int y = 0; y < height; y++)
    {
      int offset = raster.calculateByteOffset(0, y, b);

      System.arraycopy(row.data, headerlen, raster.data, offset, len);
    }
  }

  return raster;
}

final public int width()
{
  return width;
}

final public int height()
{
  return height;
}

final public int bands()
{
  return bands;
}

final public int datatype()
{
  return datatype;
}

final public int dataoffset()
{
  return dataoffset;
}

final public int datasize()
{
  return data.length - dataoffset;
}

final public int datalength()
{
  return data.length;
}

final public MrGeoRaster clip(int x, int y, int width, int height) throws MrGeoRasterException
{
  MrGeoRaster clipraster = createEmptyRaster(width, height, bands, datatype);

  for (int b = 0; b < bands; b++)
  {
    for (int yy = 0; yy < height; yy++)
    {
      int[] offsets = calculateByteRangeOffset(x, yy + y, x + width, yy + y, b);
      int dstOffset = clipraster.calculateByteOffset(0, yy, b);

      System.arraycopy(data, offsets[0], clipraster.data, dstOffset, offsets[1] - offsets[0]);
    }
  }

  return clipraster;
}

final public MrGeoRaster clip(int x, int y, int width, int height, int band) throws MrGeoRasterException
{
  MrGeoRaster clipraster = createEmptyRaster(width, height, 1, datatype);

  for (int yy = 0; yy < height; yy++)
  {
    int[] offsets = calculateByteRangeOffset(x, yy + y, x + width, yy + y, band);
    int dstOffset = clipraster.calculateByteOffset(0, yy, 0);

    System.arraycopy(data, offsets[0], clipraster.data, dstOffset, offsets[1] - offsets[0]);
  }

  return clipraster;
}

final public void copyFrom(int srcx, int srcy, int width, int height, MrGeoRaster src, int dstx, int dsty)
{
  for (int b = 0; b < bands; b++)
  {
    for (int yy = 0; yy < height; yy++)
    {
      int[] srcoffcets = src.calculateByteRangeOffset(srcx, yy + srcy, srcx + width, yy + srcy, b);
      int dstOffset = calculateByteOffset(dstx, yy + dsty, b);

      System.arraycopy(src.data, srcoffcets[0], data, dstOffset, srcoffcets[1] - srcoffcets[0]);
    }
  }
}

final public void copyFrom(int srcx, int srcy, int srcBand, int width, int height, MrGeoRaster src,
    int dstx, int dsty, int dstBand)
{
  for (int yy = 0; yy < height; yy++)
  {
    int[] srcoffcets = src.calculateByteRangeOffset(srcx, yy + srcy, srcx + width, yy + srcy, srcBand);
    int dstOffset = calculateByteOffset(dstx, yy + dsty, dstBand);

    System.arraycopy(src.data, srcoffcets[0], data, dstOffset, srcoffcets[1] - srcoffcets[0]);
  }
}

final public void fill(double value) throws MrGeoRasterException
{
  MrGeoRaster row = createEmptyRaster(width, 1, 1, datatype);
  for (int x = 0; x < width; x++)
  {
    row.setPixel(x, 0, 0, value);
  }

  int len = row.data.length - dataoffset;

  for (int b = 0; b < bands; b++)
  {
    for (int y = 0; y < height; y++)
    {
      int offset = calculateByteOffset(0, y, b);

      System.arraycopy(row.data, dataoffset, data, offset, len);
    }
  }

}

final public void fill(double[] values) throws MrGeoRasterException
{
  MrGeoRaster row[] = new MrGeoRaster[bands];

  for (int b = 0; b < bands; b++)
  {
    row[b] = createEmptyRaster(width, 1, 1, datatype);

    for (int x = 0; x < width; x++)
    {
      row[b].setPixel(x, 0, 0, values[b]);
    }
  }

  int headerlen = dataoffset;
  int len = row[0].data.length - headerlen;

  for (int b = 0; b < bands; b++)
  {
    int offset = headerlen + (b * bandoffset * bytesPerPixel());
    for (int y = 0; y < height; y++)
    {
      System.arraycopy(row[b].data, headerlen, data, offset, len);

      offset += len;
    }
  }
}

final public void fill(int band, double value) throws MrGeoRasterException
{
  MrGeoRaster row = createEmptyRaster(width, 1, 1, datatype);
  for (int x = 0; x < width; x++)
  {
    row.setPixel(x, 0, 0, value);
  }

  int headerlen = dataoffset;
  int len = row.data.length - headerlen;

  int offset = headerlen + (band * bandoffset * bytesPerPixel());
  for (int y = 0; y < height; y++)
  {

    System.arraycopy(row.data, headerlen, data, offset, len);
    offset += len;
  }
}

// Scaling algorithm taken from: http://willperone.net/Code/codescaling.php and modified to use
// Rasters. It is an optimized Bresenham's algorithm.
// Interpolated algorithm was http://tech-algorithm.com/articles/bilinear-image-scaling/
// Also used was http://www.compuphase.com/graphic/scale.htm, explaining interpolated
// scaling
public MrGeoRaster scale(int dstWidth,
    int dstHeight, boolean interpolate, double[] nodatas) throws MrGeoRasterException
{

  MrGeoRaster src = this;

  double scaleW = (double) dstWidth / src.width;
  double scaleH = (double) dstHeight / src.height;

  while (true)
  {
    int dw;
    int dh;

    double scale = Math.max(scaleW, scaleH);

    // bresenham's scalar really doesn't like being scaled more than 2x or 1/2x without the
    // possibility of artifacts. But it turns out you can scale, then scale, etc. and get
    // an answer without artifacts. Hence the loop here...
    if (interpolate)
    {
      if (scale > 2.0)
      {
        dw = (int) (src.width * 2.0);
        dh = (int) (src.height * 2.0);

      }
      else if (scale < 0.50)
      {
        dw = (int) (src.width * 0.50);
        dh = (int) (src.height * 0.50);
      }
      else
      {
        dw = dstWidth;
        dh = dstHeight;
      }
    }
    else
    {
      dw = dstWidth;
      dh = dstHeight;
    }

    MrGeoRaster dst = createCompatibleRaster(dw, dh);

    switch (datatype)
    {
    case DataBuffer.TYPE_BYTE:
    case DataBuffer.TYPE_INT:
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT:
      if (interpolate)
      {
        Bilinear.scaleInt(src, dst, nodatas);
      }
      else
      {
        Nearest.scaleInt(src, dst);
      }
      break;
    case DataBuffer.TYPE_FLOAT:
      if (interpolate)
      {
        Bilinear.scaleFloat(src, dst, nodatas);
      }
      else
      {
        Nearest.scaleFloat(src, dst);
      }
      break;
    case DataBuffer.TYPE_DOUBLE:
      if (interpolate)
      {
        Bilinear.scaleDouble(src, dst, nodatas);
      }
      else
      {
        Nearest.scaleDouble(src, dst);
      }
      break;
    default:
      throw new RasterWritableException("Error trying to scale raster. Bad raster data type");
    }

    if (dst.width == dstWidth && dst.height == dstHeight)
    {
      return dst;
    }

    src = dst;

    scaleW = (double) dstWidth / src.width;
    scaleH = (double) dstHeight / src.height;
  }
}

final public MrGeoRaster reduce(int xfactor, int yfactor, Aggregator aggregator, double[] nodatas)
    throws MrGeoRasterException
{
  MrGeoRaster child = createCompatibleRaster(width / xfactor, height / yfactor);

  int subsize = xfactor * yfactor;
  byte[] bytesamples = new byte[subsize];
  short[] shortsamples = new short[subsize];
  int[] intsamples = new int[subsize];
  float[] floatsamples = new float[subsize];
  double[] doublesamples = new double[subsize];

  int ndx;

  for (int b = 0; b < bands; b++)
  {
    for (int y = 0; y < height; y += yfactor)
    {
      for (int x = 0; x < width; x += xfactor)
      {
        ndx = 0;
        switch (datatype)
        {
        case DataBuffer.TYPE_BYTE:
          for (int yy = y; yy < y + yfactor; yy++)
          {
            for (int xx = x; xx < x + xfactor; xx++)
            {
              bytesamples[ndx++] = getPixelByte(xx, yy, b);
            }
          }

          byte bytesample = aggregator.aggregate(bytesamples, (byte) nodatas[b]);
          child.setPixel(x / xfactor, y / yfactor, b, bytesample);
          break;

        case DataBuffer.TYPE_SHORT:
          for (int yy = y; yy < y + yfactor; yy++)
          {
            for (int xx = x; xx < x + xfactor; xx++)
            {
              shortsamples[ndx++] = getPixelShort(xx, yy, b);
            }
          }

          short shortsample = aggregator.aggregate(shortsamples, (short) nodatas[b]);
          child.setPixel(x / xfactor, y / yfactor, b, shortsample);
          break;
        case DataBuffer.TYPE_USHORT:
          for (int yy = y; yy < y + yfactor; yy++)
          {
            for (int xx = x; xx < x + xfactor; xx++)
            {
              shortsamples[ndx++] = getPixelShort(xx, yy, b);
            }
          }

          int ushortsample = aggregator.aggregate(shortsamples, (short) nodatas[b]);
          child.setPixel(x / xfactor, y / yfactor, b, ushortsample);
          break;
        case DataBuffer.TYPE_INT:
          for (int yy = y; yy < y + yfactor; yy++)
          {
            for (int xx = x; xx < x + xfactor; xx++)
            {
              intsamples[ndx++] = getPixelInt(xx, yy, b);
            }
          }

          int intSample = aggregator.aggregate(intsamples, (int) nodatas[b]);
          child.setPixel(x / xfactor, y / yfactor, b, intSample);
          break;
        case DataBuffer.TYPE_FLOAT:
          for (int yy = y; yy < y + yfactor; yy++)
          {
            for (int xx = x; xx < x + xfactor; xx++)
            {
              floatsamples[ndx++] = getPixelFloat(xx, yy, b);
            }
          }

          float floatsample = aggregator.aggregate(floatsamples, (float) nodatas[b]);
          child.setPixel(x / xfactor, y / yfactor, b, floatsample);
          break;
        case DataBuffer.TYPE_DOUBLE:
          for (int yy = y; yy < y + yfactor; yy++)
          {
            for (int xx = x; xx < x + xfactor; xx++)
            {
              doublesamples[ndx++] = getPixelDouble(xx, yy, b);
            }
          }

          double doublesample = aggregator.aggregate(doublesamples, nodatas[b]);
          child.setPixel(x / xfactor, y / yfactor, b, doublesample);
          break;
        default:
          throw new RasterWritableException(
              "Error trying to get decimate pixels in the raster. Bad raster data type");
        }
      }
    }
  }

  return child;
}

final public void mosaic(MrGeoRaster other, double[] nodata)
{
  for (int b = 0; b < bands; b++)
  {
    for (int y = 0; y < height; y++)
    {
      for (int x = 0; x < width; x++)
      {
        switch (datatype)
        {
        case DataBuffer.TYPE_BYTE:
        {
          byte p = other.getPixelByte(x, y, b);
          if (getPixelByte(x, y, b) == (byte) nodata[b])
          {
            setPixel(x, y, b, p);
          }
          break;
        }
        case DataBuffer.TYPE_FLOAT:
        {
          float p = other.getPixelFloat(x, y, b);
          if (FloatUtils.isNotNodata(p, (float) nodata[b]))
          {
            setPixel(x, y, b, p);
          }

          break;
        }
        case DataBuffer.TYPE_DOUBLE:
        {
          double p = other.getPixelDouble(x, y, b);
          if (FloatUtils.isNotNodata(p, nodata[b]))
          {
            setPixel(x, y, b, p);
          }

          break;
        }
        case DataBuffer.TYPE_INT:
        {
          int p = other.getPixelInt(x, y, b);
          if (getPixelInt(x, y, b) == (int) nodata[b])
          {
            setPixel(x, y, b, p);
          }

          break;
        }
        case DataBuffer.TYPE_SHORT:
        {
          short p = other.getPixelShort(x, y, b);
          if (getPixelShort(x, y, b) == (short) nodata[b])
          {
            setPixel(x, y, b, p);
          }

          break;
        }
        case DataBuffer.TYPE_USHORT:
          int p = other.getPixeUShort(x, y, b);
          if (getPixeUShort(x, y, b) == (short) nodata[b])
          {
            setPixel(x, y, b, p);
          }

          break;
        default:
          throw new RasterWritableException(
              "Error trying to get mosaic raster. Bad raster data type");
        }

      }
    }
  }
}

final public Dataset toDataset()
{
  return toDataset(null, null);
}

final public Dataset toDiskBasedDataset(Bounds bounds, double[] nodatas,
    int xoffset, int yoffset, int outWidth, int outHeight)
{
  int gdaltype = GDALUtils.toGDALDataType(datatype);
  Dataset ds = GDALUtils.createEmptyDiskBasedRaster(outWidth, outHeight, bands, gdaltype, nodatas);
  return toDataset(ds, gdaltype, bounds, xoffset, yoffset, outWidth, outHeight, nodatas);
}

final public Dataset toDataset(Bounds bounds, double[] nodatas)
{
  int gdaltype = GDALUtils.toGDALDataType(datatype);
  Dataset ds = GDALUtils.createEmptyMemoryRaster(width, height, bands, gdaltype, nodatas);
  return toDataset(ds, gdaltype, bounds, 0, 0, width, height, nodatas);
}

private Dataset toDataset(Dataset ds, int gdaltype, Bounds bounds,
    int xoffset, int yoffset,
    int outWidth, int outHeight,
    double[] nodatas)
{
  double[] xform = new double[6];
  if (bounds != null)
  {

    xform[0] = bounds.w;
    xform[1] = bounds.width() / outWidth;
    xform[2] = 0;
    xform[3] = bounds.n;
    xform[4] = 0;
    xform[5] = -bounds.height() / outHeight;

    ds.SetProjection(GDALUtils.EPSG4326());
  }
  else
  {
    xform[0] = 0;
    xform[1] = outWidth;
    xform[2] = 0;
    xform[3] = 0;
    xform[4] = 0;
    xform[5] = -outHeight;
  }
  ds.SetGeoTransform(xform);

  byte[] rowdata = new byte[bytesPerPixel() * outWidth];

  for (int b = 0; b < bands; b++)
  {
    Band band = ds.GetRasterBand(b + 1); // gdal bands are 1's based
    if (nodatas != null)
    {
      if (b < nodatas.length)
      {
        band.SetNoDataValue(nodatas[b]);
      }
      else
      {
        band.SetNoDataValue(nodatas[nodatas.length - 1]);
      }
    }
    for (int y=0; y < outHeight; y++) {
      System.arraycopy(data, calculateByteOffset(xoffset, y + yoffset, b), rowdata, 0, rowdata.length);
      int success = band.WriteRaster(0, y, outWidth, 1, outWidth, 1, gdaltype, rowdata);
      if (success != gdalconstConstants.CE_None)
      {
        System.out.println("Failed writing raster. gdal error: " + success);
        break;
      }
    }
  }

  return ds;
}

public void copyToDataset(Dataset ds, int dsWidth, int dsHeight, Bounds fullBounds, Bounds bounds,
    int tilesize, int zoomlevel, int gdaltype) throws IOException
{
  Pixel ulPixelTile = TMSUtils
      .latLonToPixelsUL(bounds.n, bounds.w, zoomlevel, tilesize);
  Pixel ulPixelDS = TMSUtils
      .latLonToPixelsUL(fullBounds.n, fullBounds.w, zoomlevel, tilesize);
  Pixel lrPixelTile = TMSUtils
      .latLonToPixelsUL(bounds.s, bounds.e, zoomlevel, tilesize);
  Pixel lrPixelDS = TMSUtils
      .latLonToPixelsUL(fullBounds.s, fullBounds.e, zoomlevel, tilesize);

  long leftPixel = Math.max(ulPixelDS.px, ulPixelTile.px);
  long rightPixel = Math.min(lrPixelDS.px, lrPixelTile.px);
  long topPixel = Math.max(ulPixelDS.py, ulPixelTile.py);
  long bottomPixel = Math.min(lrPixelDS.py, lrPixelTile.py);
  int xoffset = (ulPixelTile.px < leftPixel) ? (int) (leftPixel - ulPixelTile.px) : 0;
  int yoffset = (ulPixelTile.py < topPixel) ? (int) (topPixel - ulPixelTile.py) : 0;
  int xoffsetWrite = (int)(leftPixel - ulPixelDS.px);
  int yoffsetWrite = (int)(topPixel - ulPixelDS.py);
  int outWidth = (int) (rightPixel - leftPixel);
  int outHeight = (int) (bottomPixel - topPixel);

  byte[] rowdata = new byte[bytesPerPixel() * outWidth];
  for (int b = 0; b < ds.GetRasterCount(); b++) {
    for (int y = 0; y < outHeight; y++) {
      Band band = ds.GetRasterBand(b + 1); // gdal bands are 1's based
      System.arraycopy(data, calculateByteOffset(xoffset, y + yoffset, b), rowdata, 0, rowdata.length);
      int success = band.WriteRaster(xoffsetWrite, y + yoffsetWrite, outWidth, 1, outWidth, 1, gdaltype, rowdata);
      if (success != gdalconstConstants.CE_None) {
        throw new IOException("Failed writing raster. gdal error: " + success);
      }
    }
  }
}

final public Raster toRaster()
{
  WritableRaster raster = RasterUtils.createEmptyRaster(width, height, bands, datatype);

  ByteBuffer rasterBuffer = ByteBuffer.wrap(data);
  rasterBuffer.order(ByteOrder.LITTLE_ENDIAN);

  // skip over the header in the data buffer
  for (int i = 0; i < HEADER_LEN; i++)
  {
    rasterBuffer.get();
  }

  int databytes = data.length - HEADER_LEN;

  switch (datatype)
  {
  case DataBuffer.TYPE_BYTE:
    // we can't use the byte buffer explicitly because the header info is
    // still in it...
    byte[] bytedata = new byte[databytes];
    rasterBuffer.get(bytedata);

    raster.setDataElements(0, 0, width, height, bytedata);
    break;
  case DataBuffer.TYPE_FLOAT:
    FloatBuffer floatbuff = rasterBuffer.asFloatBuffer();
    float[] floatdata = new float[databytes / bytesPerPixel()];

    floatbuff.get(floatdata);

    raster.setDataElements(0, 0, width, height, floatdata);
    break;
  case DataBuffer.TYPE_DOUBLE:
    DoubleBuffer doublebuff = rasterBuffer.asDoubleBuffer();
    double[] doubledata = new double[databytes / bytesPerPixel()];

    doublebuff.get(doubledata);

    raster.setDataElements(0, 0, width, height, doubledata);

    break;
  case DataBuffer.TYPE_INT:
    IntBuffer intbuff = rasterBuffer.asIntBuffer();
    int[] intdata = new int[databytes / bytesPerPixel()];

    intbuff.get(intdata);

    raster.setDataElements(0, 0, width, height, intdata);

    break;
  case DataBuffer.TYPE_SHORT:
  case DataBuffer.TYPE_USHORT:
    ShortBuffer shortbuff = rasterBuffer.asShortBuffer();
    short[] shortdata = new short[databytes / bytesPerPixel()];
    shortbuff.get(shortdata);
    raster.setDataElements(0, 0, width, height, shortdata);
    break;
  default:
    throw new RasterWritableException("Error trying to read raster.  Bad raster data type");
  }

  return raster;
}

public abstract byte getPixelByte(int x, int y, int band);

public abstract short getPixelShort(int x, int y, int band);

public abstract short getPixeUShort(int x, int y, int band);

public abstract int getPixelInt(int x, int y, int band);

public abstract float getPixelFloat(int x, int y, int band);

public abstract double getPixelDouble(int x, int y, int band);

public abstract void setPixel(int x, int y, int band, byte pixel);

public abstract void setPixel(int x, int y, int band, short pixel);

public abstract void setPixel(int x, int y, int band, int pixel);

public abstract void setPixel(int x, int y, int band, float pixel);

public abstract void setPixel(int x, int y, int band, double pixel);

final byte[] data()
{
  return data;
}

final int calculateByteOffset(int x, int y, int band)
{
  return ((y * width + x) + band * bandoffset) * bytesPerPixel() + dataoffset;
}

final int[] calculateByteRangeOffset(int startx, int starty, int endx, int endy, int band)
{
  int bpp = bytesPerPixel();
  int bandoffset = band * this.bandoffset;

  return new int[]{
      ((starty * width + startx) + bandoffset) * bpp + dataoffset,
      ((endy * width + endx) + bandoffset) * bpp + dataoffset};
}

final int[] calculateByteRangeOffset(int startx, int starty, int startband,
    int endx, int endy, int endband)
{
  int bpp = bytesPerPixel();

  return new int[]{
      ((starty * width + startx) + (startband * bandoffset)) * bpp + dataoffset,
      ((endy * width + endx) + (endband * bandoffset)) * bpp + dataoffset};
}

public abstract int bytesPerPixel();

public static class MrGeoRasterException extends IOException
{
  private static final long serialVersionUID = 1L;

  private final Exception origException;

  MrGeoRasterException(String msg)
  {
    origException = new Exception(msg);
  }

  @Override
  public void printStackTrace()
  {
    origException.printStackTrace();
  }
}

}