text:
This repository has been deprecated as of 2019-01-27. That code was written a long time ago and has been unmaintained for several years.
Thus, repository will now be [archived](https://github.blog/2017-11-08-archiving-repositories/).
If you are interested in taking over ownership, feel free to [contact me](https://www.pascallandau.com/about/).

---

# comparison-utility
[![Build Status](https://travis-ci.org/paslandau/comparison-utility.svg?branch=master)](https://travis-ci.org/paslandau/comparison-utility)

Collection of different common comparison classes/functions

## Description
[todo]

## Requirements

- PHP >= 5.5

## Installation

The recommended way to install comparison-utility is through [Composer](http://getcomposer.org/).

    curl -sS https://getcomposer.org/installer | php

Next, update your project's composer.json file to include comparison-utility:

    {
        "repositories": [ { "type": "composer", "url": "http://packages.myseosolution.de/"} ],
        "minimum-stability": "dev",
        "require": {
             "paslandau/comparison-utility": "dev-master"
        }
        "config": {
            "secure-http": false
        }
    }

_**Caution:** You need to explicitly set `"secure-http": false` in order to access http://packages.myseosolution.de/ as repository.
This change is required because composer changed the default setting for `secure-http` to true at [the end of february 2016](https://github.com/composer/composer/commit/cb59cf0c85e5b4a4a4d5c6e00f827ac830b54c70#diff-c26d84d5bc3eed1fec6a015a8fc0e0a7L55)._

After installing, you need to require Composer's autoloader:
```php

require 'vendor/autoload.php';
```


text:
package com.vuzix.sensorAnalysis.activities;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.vuzix.sensorAnalysis.R;
import com.vuzix.sensorAnalysis.functions.AbsoluteCS;
import com.vuzix.sensorAnalysis.functions.CoordinateSystem;
import com.vuzix.sensorAnalysis.functions.HighPassFilterCS;
import com.vuzix.sensorAnalysis.functions.LowPassFilterCS;
import com.vuzix.sensorAnalysis.functions.RawCS;
import com.vuzix.sensorAnalysis.functions.SphericalCS;

/**
 * The main functionality of the application is contained in SensorActivity
 *
 * Defines several views based on the com.vuzix.sensorAnalysis.functions.
 * Dynamically loads each view and executes unique code for each coordinate system.
 *
 * The main functionality is to display X (or Magnitude), Y (or Inclination), and
 *  Z (or Azimuth) values.  Provides additional functionality to display CPU usage
 *  of the app and the ability to modify the sensor's rate of collection.
 *
 * @author Connor Hack <connor_hack@vuzix.com>
 *
 */
public class SensorActivity extends Activity implements SensorEventListener {

	// Global variables declared here
	private static String PACKAGE_NAME ;
	private static Activity ORIGINAL_ACTIVITY ;

	private SensorManager mSensorManager;
	private Sensor sensorAccelerometer, sensorGravity,
					sensorMagnetic, sensorAcceleration ;
	private CoordinateSystem coordinateSystem ;
	private static int RATE = MainActivity.DELAY_FASTEST ;

	// Globals for the CPU thread
	private Thread threadCPU ;
	private boolean cpuRunning, paused ;

	// Globals for onSensorChanged
	private float mGravity[] = new float[3] ;
	private float mMagnetic[] = new float[3] ;
	private float mInclination[] = new float[9] ;
	private float mRotation[] = new float[9] ;
	private float values[] = new float[3] ;

	/////////////////////////////////////////////////////
	// Below methods are for the extension of Activity //
	/////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sensors);

		// Enable the home as up from this activity
		getActionBar().setDisplayHomeAsUpEnabled(true);

		initGlobals();
	}

	@Override
	protected void onResume() {
		super.onResume();

		//TODO Keep if needed/wanted in the future
		/*// Identify if the android device is charging/plugged in
		Intent intent = this.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        // If the device is plugged in, increase the rate at which the sensors collect data
		if (plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
			RATE = SensorManager.SENSOR_DELAY_FASTEST;
			Log.i("M100Dev", "Device charging; changing sensor delay to fastest speed.");
		}*/

		setSensorRates(RATE);

		// Indicate the CPU usage thread is no longer paused
		paused = false ;

		// Interrupt the waiting thread to indicate it can resume execution
		if (threadCPU.getState() == Thread.State.TIMED_WAITING) {
			threadCPU.interrupt();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		// Unregister the sensors and pause the CPU usage thread
		mSensorManager.unregisterListener(this);
		paused = true ;
	}

	@Override
	protected void onDestroy() {
		super.onStop();

		// Terminate the thread processing the CPU usage; unpause the thread
		//  to allow it to finish.
		paused = false ;
		cpuRunning = false ;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

	    // Inflate the menu items for use in the action bar
	    getMenuInflater().inflate(R.menu.menu_main, menu);

	    // Find the menu id and create a corresponding adapter
	    MenuItem item = menu.findItem(R.id.menuRate);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
	    		R.array.rates, R.layout.spinner_rates_header);

	    // Specifies the layout to use when the list of choices appears
	    adapter.setDropDownViewResource(R.layout.spinner_rates_items);

	    // Find the spinner and attach the adapter to it
	    Spinner spinner = (Spinner) item.getActionView().findViewById(R.id.spinner_rates);
	    spinner.setAdapter(adapter);

	    // Set the next left focus to be the home (back) button
	    spinner.setNextFocusLeftId(android.R.id.home);

	    // Store the context for the spinner's listener to create toast messages
	    final Context mContext = this.getApplicationContext();

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {

				// Grab the item that was selected
                Object item = parent.getItemAtPosition(pos);

                if (item != null) {
                	// Create a default toast message if something unexpected occurs
                    Toast toast = Toast.makeText(mContext, "There was an unexpected error.", Toast.LENGTH_SHORT);

                	if(item.toString().equals(mContext.getResources().getString(R.string.rate_normal))) {
                		// Set the sensor rate to the Normal mode
                		RATE = MainActivity.DELAY_NORMAL ;
                		toast.setText("Sensor rate set to Slowest Rate.");

                	} else if(item.toString().equals(mContext.getResources().getString(R.string.rate_ui))) {
                		// Set the sensor rate to the UI mode
                		RATE = MainActivity.DELAY_UI ;
                		toast.setText("Sensor rate set to Slow Rate.");

                	} else if(item.toString().equals(mContext.getResources().getString(R.string.rate_game))) {
                		// Set the sensor rate to the Game mode
                		RATE = MainActivity.DELAY_GAME ;
                		toast.setText("Sensor rate set to Normal Rate.");

                	} else if(item.toString().equals(mContext.getResources().getString(R.string.rate_fastest))) {
                		// Set the sensor rate to the Fastest mode
                		RATE = MainActivity.DELAY_FASTEST ;
                		toast.setText("Sensor rate set to Fast Rate.");
                	}

                	// Reset the sensors that are dependent on the sensor rate
                	setSensorRates(RATE);
                	toast.show();
                }
			}
			@Override
			public void onNothingSelected(AdapterView<?> parent) {}
		});

		// Set the initial selection at the middle value
		spinner.setSelection((int) (Math.floor( (MainActivity.RATES.size()-1)/2) ));

	    return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// If the home button was pressed, finish this activity
			this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	////////////////////////////////////////////////
	// Below are methods specific to MainActivity //
	////////////////////////////////////////////////

	/**
	 * Helper function to organize code
	 *
	 * Used to initialize global variables used throughout this module
	 */
	private void initGlobals() {

		// Store the package name and context for the CPU thread
		PACKAGE_NAME = getApplicationContext().getPackageName();
		ORIGINAL_ACTIVITY = this ;

		mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);

		// Attempt to instantiate the sensors
		sensorAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		sensorGravity = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
		sensorMagnetic = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
		sensorAcceleration = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

		// Identify if there does not exist an accelerometer on the device
		if (sensorAccelerometer == null)
			Log.w("M100Dev", "Device does not possess an accelerometer.");
		if (sensorGravity == null)
			Log.w("M100Dev", "Device does not possess a gravity sensor.");
		if (sensorMagnetic == null)
			Log.w("M100Dev", "Device does not possess a magnetic field sensor.");
		if (sensorAcceleration == null)
			Log.w("M100Dev", "Device does not possess a magnetic field sensor.");

		// From the intent, retrieve the parcelable coordinate system extra
		Bundle data = getIntent().getExtras();
		coordinateSystem = data.getParcelable("coordinate_system");

		identifyCSType() ;

		cpuRunning = true ;

		// Create the thread that will find the CPU usage on the device
		threadCPU = new Thread() {
			public void run() {

				// Keep looping while the activity has not been stopped
				while (cpuRunning) {
					if (paused) {
						// If the activity is paused
						try {
							// Tell the thread to sleep for 30 seconds and
							//  if it is still running in that time, finish
							//  the activity.
							Thread.sleep(30000);
							ORIGINAL_ACTIVITY.finish();
						} catch (InterruptedException ie) {
							Log.w("M100_Exceptions", "Caught a thrown interruption: " + ie.toString());
						}
					} else {

						try {
							// Run from the adb shell a command to grab the top
							//  ten processes taking up CPU
							Process p = Runtime.getRuntime().exec("top -n 1 -m 10");

							// Wait for the thread to finish executing
							p.waitFor();

							// Initialize the input stream and reader to parse
							//  the message from executing <p> command
							BufferedInputStream buffer = new BufferedInputStream( p.getInputStream() );
							BufferedReader commandOutput= new BufferedReader( new InputStreamReader( buffer ) );

							// Attempt to parse each string produced from the command
							parseCPU(commandOutput);
							commandOutput.close();

						} catch (InterruptedException ie) {
							ie.printStackTrace();
						} catch (IOException ioe) {
							ioe.printStackTrace();
						}
					}
				}
			}
		};
		threadCPU.start();
	}

	private void parseCPU(BufferedReader commandOutput) throws IOException {

		String line = null ;

		// Read each line from the reader that is used to parse commands
		while ( ( line = commandOutput.readLine() ) != null ) {
			// Split the string by spaces
			final String[] result = line.split(" ");

			// If the last string from the split is the same as the package name
			if (result[result.length-1].equalsIgnoreCase(PACKAGE_NAME)) {
				// Run a thread on the UI thread to update views
				runOnUiThread(new Runnable() {
				     @Override
				     public void run() {

				    	 int i ;
				    	 // Establish the position in the string array where
				    	 //  our CPU usage percentage is
				    	 for(i=0; i<result.length; i++) {
				    		 if ( (result[i].length() != 0) &&
				    				 (result[i].charAt(result[i].length()-1) == '%') ) {
				    			 break ;
				    		 }
				    	 }

				    	 // Change the CPU value TextView to the digits
				    	 //  from the parsed string (excludes the % sign)
				    	 if (i != result.length) {
				    		 ((TextView) findViewById(R.id.tv_cpu_value))
					    	 	.setText(result[i].subSequence(0, result[i].length()-1));
				    	 } else {
				    		 // If the process is not in the top ten processes,
				    		 //  set the value to zero
				    		 ((TextView) findViewById(R.id.tv_cpu_value))
					    	 	.setText(0);
				    	 }

				    }
				});
				// Discontinue parsing
				break ;
			}
		}
	}

	/**
	 * Helper function used to identify the type of coordinate system currently in use
	 */
	private void identifyCSType() {

		String types[] = {"RawCS", "AbsoluteCS", "SphericalCS", "LowPassFilterCS", "HighPassFilterCS"};

		// Confirm the coordinate system has been instantiated
		if(coordinateSystem == null) {
			Log.e("M100Dev", "No coordinate system was passed in the intent.");
			return ;
		}

		// Compare the strings to those that represent the types of CS classes.
		if(coordinateSystem.toString().equals(types[0])) {
			coordinateSystem = (RawCS) coordinateSystem ;
			this.setTitle(R.string.activity_raw);
		} else if(coordinateSystem.toString().equals(types[1])) {
			coordinateSystem = (AbsoluteCS) coordinateSystem ;
			this.setTitle(R.string.activity_absolute);
		} else if(coordinateSystem.toString().equals(types[2])) {
			coordinateSystem = (SphericalCS) coordinateSystem ;
			this.setTitle(R.string.activity_spherical);
		} else if(coordinateSystem.toString().equals(types[3])) {
			coordinateSystem = (LowPassFilterCS) coordinateSystem ;
			this.setTitle(R.string.activity_lpf);
		} else if(coordinateSystem.toString().equals(types[4])) {
			coordinateSystem = (HighPassFilterCS) coordinateSystem ;
			this.setTitle(R.string.activity_hpf);
		}

		updateUI(coordinateSystem, 0, 0, 0);
	}

	/**
	 * Helper function to set the rate at which the sensors collect data
	 * @param rate - provided from SensorManager.SENSOR_DELAY_*
	 */
	private void setSensorRates(int rate) {
		mSensorManager.registerListener(this, sensorAccelerometer, rate);
		mSensorManager.registerListener(this, sensorGravity, rate);
		mSensorManager.registerListener(this, sensorMagnetic, rate);
		mSensorManager.registerListener(this, sensorAcceleration, rate);
	}

	/**
	 * Massive helper function to set the user interface
	 *
	 * Sets each text for each TextView that depends on a Coordinate System
	 * Also modifies the margins of the View if the CS is an instance of SphericalCS
	 *
	 * @param cs - A coordinate system
	 * @param x - The x value to set in a TextView
	 * @param y - The y value to set in a TextView
	 * @param z - The z value to set in a TextView
	 */
	private void updateUI(CoordinateSystem cs, float x, float y, float z) {

		// Set the format for printing out values
		DecimalFormat df = new DecimalFormat("####.##");

		// Create TextViews for each dynamic TextView
		TextView 	acc_x, acc_x_val, acc_x_unit,
					acc_y, acc_y_val, acc_y_unit,
					acc_z, acc_z_val, acc_z_unit ;

		// Find each view by their specified ID
		acc_x 		=	((TextView) findViewById(R.id.tv_acceleration_x)) ;
		acc_y 		= 	((TextView) findViewById(R.id.tv_acceleration_y)) ;
		acc_z 		= 	((TextView) findViewById(R.id.tv_acceleration_z)) ;
		acc_x_val 	=	((TextView) findViewById(R.id.tv_acceleration_x_value)) ;
		acc_y_val 	= 	((TextView) findViewById(R.id.tv_acceleration_y_value)) ;
		acc_z_val 	= 	((TextView) findViewById(R.id.tv_acceleration_z_value)) ;
		acc_x_unit 	=	((TextView) findViewById(R.id.tv_acceleration_x_units)) ;
		acc_y_unit 	= 	((TextView) findViewById(R.id.tv_acceleration_y_units)) ;
		acc_z_unit 	=  	((TextView) findViewById(R.id.tv_acceleration_z_units)) ;

		// Set the description text for each TextView
		acc_x.setText(cs.getDesc("x"));
		acc_y.setText(cs.getDesc("y"));
		acc_z.setText(cs.getDesc("z"));

		// Set the value for each TextView
		acc_x_val.setText(df.format(x));
		acc_y_val.setText(df.format(y));
		acc_z_val.setText(df.format(z));

		// Set the units for each TextView
		acc_x_unit.setText(cs.getAccUnits("x"));
		acc_y_unit.setText(cs.getAccUnits("y"));
		acc_z_unit.setText(cs.getAccUnits("z"));

		// If the coordinate system is an instance of SphericalCS, modify the margins
		// We want this section to only be called once, so within identifyCSTYpe we
		//  call this method with x/y/z all zero.  Since the probability of X, Y, and
		//  Z all being zero is incredibly low, this is a relatively safe procedure.
		if ( (cs instanceof SphericalCS) && ( (x == 0) && (y == 0) && (z == 0) )){

			// Find each LayoutParameter for each related TextView
			LayoutParams acc_x_rlp 		= (LayoutParams) acc_x_val.getLayoutParams() ;
			LayoutParams acc_y_rlp 		= (LayoutParams) acc_y_val.getLayoutParams() ;
			LayoutParams acc_z_rlp 		= (LayoutParams) acc_z_val.getLayoutParams() ;
			LayoutParams acc_x_unit_rlp = (LayoutParams) acc_x_unit.getLayoutParams() ;
			LayoutParams acc_y_unit_rlp = (LayoutParams) acc_y_unit.getLayoutParams() ;
			LayoutParams acc_z_unit_rlp = (LayoutParams) acc_z_unit.getLayoutParams() ;

			// setMargins(left, top, right, bottom)
			// Set the margins for each TextView
			acc_x_rlp.setMargins(15, 0, 0, 0);
			acc_y_rlp.setMargins(15, 0, 0, 0);
			acc_z_rlp.setMargins(33, 0, 0, 0);
			acc_x_unit_rlp.setMargins(210, 0, 0, 0);
			acc_y_unit_rlp.setMargins(210, 0, 0, 0);
			acc_z_unit_rlp.setMargins(210, 0, 0, 0);

			// Apply each new LayoutParam
			acc_x_val.setLayoutParams(acc_x_rlp);
			acc_y_val.setLayoutParams(acc_y_rlp);
			acc_z_val.setLayoutParams(acc_z_rlp);
			acc_x_unit.setLayoutParams(acc_x_unit_rlp);
			acc_y_unit.setLayoutParams(acc_y_unit_rlp);
			acc_z_unit.setLayoutParams(acc_z_unit_rlp);
		}
	}

	/////////////////////////////////////////////////////////////
	// Below methods are for the interface SensorEventListener //
	/////////////////////////////////////////////////////////////

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// Report any changes to sensors' accuracy
		Log.w("M100Dev","ACCURACY CHANGED: " + sensor.getName() + ": " + String.valueOf(accuracy));
	}

	// Override the method to capture the sensors' changes
	@Override
	public void onSensorChanged(SensorEvent event) {

		// if the CS is of type Spherical, find the orientation
		if (coordinateSystem instanceof SphericalCS) {
			if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
				// If the CS is of a type to apply a HPF or a LPF, filter the
				//  found values by the appropriate filter
				if (coordinateSystem instanceof LowPassFilterCS) {
					mGravity = ((LowPassFilterCS) coordinateSystem).filter(event.values, mGravity);
				} else if (coordinateSystem instanceof HighPassFilterCS) {
					mGravity = ((HighPassFilterCS) coordinateSystem).filter(event.values, mGravity);
				} else {
					// Else just store the values
					mGravity = event.values ;
				}
			} else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
				// If the CS is of a type to apply a HPF or a LPF, filter the
				//  found values by the appropriate filter
				if (coordinateSystem instanceof LowPassFilterCS) {
					mMagnetic = ((LowPassFilterCS) coordinateSystem).filter(event.values, mMagnetic);
				} else if (coordinateSystem instanceof HighPassFilterCS) {
					mMagnetic = ((HighPassFilterCS) coordinateSystem).filter(event.values, mMagnetic);
				} else {
					// Else just store the values
					mMagnetic = event.values ;
				}
			} else if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
				// Store the values within the CS to calculate the magnitude component
				((SphericalCS) coordinateSystem).setValueX(event.values);
			}

			// If values have been found for both the gravity and magnetic sensor
			if (mGravity != null && mMagnetic != null) {

				// Get the rotation matrix for the azimuth (requires modification
				//  of the ordering of the values due to axes differences)
				SensorManager.getRotationMatrix(mRotation, mInclination,
						new float[]{mGravity[0], -mGravity[2], mGravity[1]},
						new float[]{mMagnetic[0], -mMagnetic[2], mMagnetic[1]});
				SensorManager.getOrientation(mRotation, values);
				// Store the value found by the two methods above as the azimuth
				((SphericalCS) coordinateSystem).setValueZ(values[0]);

				// Get the rotation matrix for the inclination
				SensorManager.getRotationMatrix(mRotation, mInclination, mGravity, mMagnetic) ;
				SensorManager.getOrientation(mRotation, values) ;
				// Store the value found by the two methods above as the inclination
				((SphericalCS) coordinateSystem).setValueY((float) (((values[1]*180) / Math.PI) + 90) );
			}
		}

		// Filter out all other sensors besides the accelerometer and linear acc.
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			if (! (coordinateSystem instanceof AbsoluteCS) ){
				// Give accelerometer values to all instances not of AbsoluteCS
				coordinateSystem.setValues(event.values);
			}
		} else if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
			if (coordinateSystem instanceof AbsoluteCS) {
				// Give linear acceleration values to the AbsoluteCS
				coordinateSystem.setValues(event.values);
			}
		} else {
			// Don't allow other sensors to update the UI
			return ;
		}

		// Pass in parameters to modify the UI
		updateUI(coordinateSystem, coordinateSystem.getValueX() ,
								coordinateSystem.getValueY() ,
								coordinateSystem.getValueZ() );

	}
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaerostilbe sanguinea Fuckel

### Remarks
null


text:
util::ProgramOption optionPerformWatershed(
		util::_long_name        = "performWatershed",
		util::_module           = "sopnet.skeletons",
		util::_description_text = "Perform a watershed to obtain superpixels from seeds and a boundary map. If not set, seeded region growing is used instead.",
		util::_default_value    = true);

FindSuperPixels::FindSuperPixels() {

	registerInput(_boundaryMap, "boundary map");
	registerInput(_seeds, "seeds");
	registerOutput(_labels, "labels");
}

void
FindSuperPixels::updateOutputs() {

	if (!_labels)
		_labels = new ImageStack();
	else
		_labels->clear();

	float minX = _boundaryMap->getBoundingBox().getMinX();
	float minY = _boundaryMap->getBoundingBox().getMinY();
	float minZ = _boundaryMap->getBoundingBox().getMinZ();

	float resX = _boundaryMap->getResolutionX();
	float resY = _boundaryMap->getResolutionY();
	float resZ = _boundaryMap->getResolutionZ();

	if (resX != resY)
		UTIL_THROW_EXCEPTION(
				NotYetImplemented,
				"anisotropic x and y is not yet implemented");

	vigra::Shape3 size(
			_boundaryMap->width(),
			_boundaryMap->height(),
			_boundaryMap->size());

	// create boundary map
	vigra::MultiArray<3, float> anisotropic(size);
	for (int z = 0; z < size[2]; z++)
		vigra::copyMultiArray(
				*(*_boundaryMap)[z],
				anisotropic.bind<2>(z));

	// correct for anisotropy
	float correctZ = resZ/resX;
	resZ /= correctZ;
	size[2] *= correctZ;

	vigra::MultiArray<3, float> boundaries(size);
	vigra::resizeMultiArraySplineInterpolation(
			anisotropic,
			boundaries);

	// create seed point image
	vigra::MultiArray<3, float> seeds(size);
	unsigned int label = 1;
	foreach (Sphere& sphere, *_seeds) {

		unsigned int x = (sphere.getX() - minX)/resX;
		unsigned int y = (sphere.getY() - minY)/resY;
		unsigned int z = (sphere.getZ() - minZ)/resZ;

		seeds(x, y, z) = label++;
	}

	if (optionPerformWatershed) {

		// perform watershed
		vigra::watershedsMultiArray(
				boundaries,
				seeds,
				vigra::DirectNeighborhood,
				vigra::WatershedOptions().stopAtThreshold(0.99));

	} else {

		vigra::ArrayOfRegionStatistics<vigra::SeedRgDirectValueFunctor<float> >  stats(_seeds->size());

		vigra::transformMultiArray(
				boundaries,
				boundaries,
				vigra::functor::Arg1() >= vigra::functor::Param(0.99));

		vigra::seededRegionGrowing3D(
				boundaries,
				seeds,
				seeds,
				stats,
				vigra::StopAtThreshold,
				vigra::NeighborCode3DSix(),
				0.99);
	}

	// provide labels as output
	_labels->setBoundingBox(
			BoundingBox(
					minX, minY, minZ,
					minX + size[0]*resX, minY + size[1]*resY, minZ + size[2]*resZ));
	_labels->setResolution(resX, resY, resZ);
	for (unsigned int z = 0; z < size[2]; z++) {

		boost::shared_ptr<Image> image = boost::make_shared<Image>(size[0], size[1]);
		vigra::copyMultiArray(
				seeds.bind<2>(z),
				*image);
		_labels->add(image);
	}
}


text:
% Set the default options andrRead the user input options
%

function [optGAMP, optPE] = check_opts(optGAMP_user, optPE_user)

%Set default GAMP options
optGAMP = GampOpt('nit',1000,...
                    'removeMean',false,...
                    'adaptStep',true,...
                    'adaptStepBethe',true,...
                    'stepWindow',0,...
                    'bbStep',0,...
                    'uniformVariance',0,...
                    'verbose',0,...
                    'tol',1e-6,...
                    'step',0.1,...
                    'stepMin',0,...
                    'stepMax',0.9,...
                    'stepIncr',1.1,...
                    'stepDecr',0.9,...
                    'pvarMin',1e-12,...
                    'xvarMin',1e-12,...
                    'maxBadSteps',inf,...
                    'maxStepDecr',0.9,...
                    'stepTol',1e-12,...
                    'pvarStep',true,...
                    'varNorm',false, ...
                    'valIn0',-Inf);

%Override GAMP defaults if specified by user
if ~isempty(optGAMP_user)
    names = fieldnames(optGAMP_user);
    for i = 1:length(names)
        if any(strcmp(fieldnames(optGAMP), names{i}));
            optGAMP.(names{i}) = optGAMP_user.(names{i});
	else
	    warning(['''',names{i},''' is an unrecognized GAMP option'])
        end
    end
end
%Force these GAMP options regardless of what user or default says!
optGAMP.legacyOut = false;
optGAMP.warnOut = false;

%Set default PE options
optPE = PEOpt();

%Change any PE options specified by user
if ~isempty(optPE_user)

    %Check to see if user set any other optional PE parameters

    if isfield(optPE_user,'noise_var'),
      optPE.noise_var = optPE_user.noise_var;
    end;
    if isfield(optPE_user,'lambda'),
      optPE.lambda = optPE_user.lambda;
    end;
    if isfield(optPE_user,'cmplx_in')
        optPE.cmplx_in = optPE_user.cmplx_in;
    end
    if isfield(optPE_user,'cmplx_out')
        optPE.cmplx_out = optPE_user.cmplx_out;
    end
    if isfield(optPE_user, 'maxPEiter')
        optPE.maxPEiter = optPE_user.maxPEiter;
    end

    %Change the main PE options if specified by user
    names = fieldnames(optPE_user);
    for i = 1:length(names)
        if any(strcmp(fieldnames(optPE), names{i}));
            optPE.(names{i}) = optPE_user.(names{i});
		else
	    	warning(['''',names{i},''' is an unrecognized PE option'])
        end
    end
end

return


text:
require 'azure_mgmt_machine_learning_services'

module Azure::Profiles::Latest
  module MachineLearningServices
    module Mgmt
      Operations = Azure::MachineLearningServices::Mgmt::V2019_05_01::Operations
      Workspaces = Azure::MachineLearningServices::Mgmt::V2019_05_01::Workspaces
      Usages = Azure::MachineLearningServices::Mgmt::V2019_05_01::Usages
      VirtualMachineSizes = Azure::MachineLearningServices::Mgmt::V2019_05_01::VirtualMachineSizes
      MachineLearningCompute = Azure::MachineLearningServices::Mgmt::V2019_05_01::MachineLearningCompute

      module Models
        AKSProperties = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AKSProperties
        OperationDisplay = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::OperationDisplay
        DataLakeAnalyticsProperties = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DataLakeAnalyticsProperties
        OperationListResult = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::OperationListResult
        PaginatedComputeResourcesList = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::PaginatedComputeResourcesList
        WorkspaceUpdateParameters = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::WorkspaceUpdateParameters
        SystemService = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::SystemService
        Usage = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Usage
        SslConfiguration = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::SslConfiguration
        VirtualMachineSize = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSize
        AksNetworkingConfiguration = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AksNetworkingConfiguration
        WorkspaceListResult = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::WorkspaceListResult
        Operation = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Operation
        Resource = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Resource
        Password = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Password
        ScaleSettings = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ScaleSettings
        ListWorkspaceKeysResult = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ListWorkspaceKeysResult
        UserAccountCredentials = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UserAccountCredentials
        ErrorResponse = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ErrorResponse
        NodeStateCounts = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::NodeStateCounts
        Compute = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Compute
        AmlComputeProperties = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlComputeProperties
        UsageName = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UsageName
        ComputeSecrets = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeSecrets
        VirtualMachineSizeListResult = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSizeListResult
        VirtualMachineSshCredentials = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSshCredentials
        ResourceId = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ResourceId
        VirtualMachineProperties = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineProperties
        ErrorDetail = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ErrorDetail
        AmlComputeNodeInformation = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlComputeNodeInformation
        ServicePrincipalCredentials = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ServicePrincipalCredentials
        ListUsagesResult = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ListUsagesResult
        HDInsightProperties = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::HDInsightProperties
        RegistryListCredentialsResult = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::RegistryListCredentialsResult
        ComputeNodesInformation = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeNodesInformation
        Identity = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Identity
        ClusterUpdateParameters = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ClusterUpdateParameters
        MachineLearningServiceError = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::MachineLearningServiceError
        DatabricksProperties = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DatabricksProperties
        Workspace = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Workspace
        ComputeResource = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeResource
        AKS = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AKS
        AmlCompute = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlCompute
        VirtualMachine = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachine
        HDInsight = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::HDInsight
        DataFactory = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DataFactory
        Databricks = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Databricks
        DataLakeAnalytics = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DataLakeAnalytics
        AmlComputeNodesInformation = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlComputeNodesInformation
        AksComputeSecrets = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AksComputeSecrets
        VirtualMachineSecrets = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSecrets
        DatabricksComputeSecrets = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DatabricksComputeSecrets
        ProvisioningState = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ProvisioningState
        UsageUnit = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UsageUnit
        ResourceIdentityType = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ResourceIdentityType
        VmPriority = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VmPriority
        AllocationState = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AllocationState
        ComputeType = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeType
        UnderlyingResourceAction = Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UnderlyingResourceAction
      end

      class MachineLearningServicesManagementClass
        attr_reader :operations, :workspaces, :usages, :virtual_machine_sizes, :machine_learning_compute, :configurable, :base_url, :options, :model_classes

        def initialize(configurable, base_url=nil, options=nil)
          @configurable, @base_url, @options = configurable, base_url, options

          @client_0 = Azure::MachineLearningServices::Mgmt::V2019_05_01::MachineLearningServicesClient.new(configurable.credentials, base_url, options)
          if(@client_0.respond_to?(:subscription_id))
            @client_0.subscription_id = configurable.subscription_id
          end
          add_telemetry(@client_0)
          @operations = @client_0.operations
          @workspaces = @client_0.workspaces
          @usages = @client_0.usages
          @virtual_machine_sizes = @client_0.virtual_machine_sizes
          @machine_learning_compute = @client_0.machine_learning_compute

          @model_classes = ModelClasses.new
        end

        def add_telemetry(client)
          profile_information = "Profiles/azure_sdk/#{Azure::VERSION}/Latest/MachineLearningServices/Mgmt"
          client.add_user_agent_information(profile_information)
        end

        def method_missing(method, *args)
          if @client_0.respond_to?method
            @client_0.send(method, *args)
          else
            super
          end
        end

        class ModelClasses
          def aksproperties
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AKSProperties
          end
          def operation_display
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::OperationDisplay
          end
          def data_lake_analytics_properties
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DataLakeAnalyticsProperties
          end
          def operation_list_result
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::OperationListResult
          end
          def paginated_compute_resources_list
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::PaginatedComputeResourcesList
          end
          def workspace_update_parameters
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::WorkspaceUpdateParameters
          end
          def system_service
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::SystemService
          end
          def usage
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Usage
          end
          def ssl_configuration
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::SslConfiguration
          end
          def virtual_machine_size
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSize
          end
          def aks_networking_configuration
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AksNetworkingConfiguration
          end
          def workspace_list_result
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::WorkspaceListResult
          end
          def operation
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Operation
          end
          def resource
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Resource
          end
          def password
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Password
          end
          def scale_settings
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ScaleSettings
          end
          def list_workspace_keys_result
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ListWorkspaceKeysResult
          end
          def user_account_credentials
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UserAccountCredentials
          end
          def error_response
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ErrorResponse
          end
          def node_state_counts
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::NodeStateCounts
          end
          def compute
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Compute
          end
          def aml_compute_properties
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlComputeProperties
          end
          def usage_name
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UsageName
          end
          def compute_secrets
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeSecrets
          end
          def virtual_machine_size_list_result
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSizeListResult
          end
          def virtual_machine_ssh_credentials
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSshCredentials
          end
          def resource_id
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ResourceId
          end
          def virtual_machine_properties
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineProperties
          end
          def error_detail
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ErrorDetail
          end
          def aml_compute_node_information
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlComputeNodeInformation
          end
          def service_principal_credentials
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ServicePrincipalCredentials
          end
          def list_usages_result
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ListUsagesResult
          end
          def hdinsight_properties
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::HDInsightProperties
          end
          def registry_list_credentials_result
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::RegistryListCredentialsResult
          end
          def compute_nodes_information
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeNodesInformation
          end
          def identity
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Identity
          end
          def cluster_update_parameters
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ClusterUpdateParameters
          end
          def machine_learning_service_error
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::MachineLearningServiceError
          end
          def databricks_properties
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DatabricksProperties
          end
          def workspace
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Workspace
          end
          def compute_resource
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeResource
          end
          def aks
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AKS
          end
          def aml_compute
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlCompute
          end
          def virtual_machine
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachine
          end
          def hdinsight
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::HDInsight
          end
          def data_factory
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DataFactory
          end
          def databricks
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::Databricks
          end
          def data_lake_analytics
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DataLakeAnalytics
          end
          def aml_compute_nodes_information
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AmlComputeNodesInformation
          end
          def aks_compute_secrets
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AksComputeSecrets
          end
          def virtual_machine_secrets
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VirtualMachineSecrets
          end
          def databricks_compute_secrets
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::DatabricksComputeSecrets
          end
          def provisioning_state
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ProvisioningState
          end
          def usage_unit
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UsageUnit
          end
          def resource_identity_type
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ResourceIdentityType
          end
          def vm_priority
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::VmPriority
          end
          def allocation_state
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::AllocationState
          end
          def compute_type
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::ComputeType
          end
          def underlying_resource_action
            Azure::MachineLearningServices::Mgmt::V2019_05_01::Models::UnderlyingResourceAction
          end
        end
      end
    end
  end
end


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

import org.flowable.bpmn.model.TimerEventDefinition;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.persistence.entity.AbstractRuntimeJobEntity;
import org.flowable.engine.impl.persistence.entity.DeadLetterJobEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.JobEntity;
import org.flowable.engine.impl.persistence.entity.SuspendedJobEntity;
import org.flowable.engine.impl.persistence.entity.TimerJobEntity;
import org.flowable.engine.runtime.JobInfo;

/**
 * Contains methods that are not tied to any specific job type (async, timer, suspended or deadletter), but which are generally applicable or are about going from one type to another.
 *
 * @author Tijs Rademakers
 * @author Joram Barrez
 */
public interface JobManager {

    /**
     * Execute a job, which means that the logic (async logic, timer that fires, etc) is executed, typically by a background thread of an executor.
     */
    void execute(JobInfo job);

    /**
     * Unacquires a job, meaning that this job was previously locked, and it is now freed to be acquired by other executor nodes.
     */
    void unacquire(JobInfo job);

    /**
     * Unacquires a job, meaning that this job was previously locked, and it is now freed to be acquired by other executor nodes.
     */
    void unacquireWithDecrementRetries(JobInfo job);

    /**
     * Creates an async job for the provided {@link ExecutionEntity}, so that it can be continued later in a background thread.
     */
    JobEntity createAsyncJob(ExecutionEntity execution, boolean exclusive);

    /**
     * Schedules and async job. If the {@link AsyncExecutor} is running, it can be executed immediately after the transaction. Otherwise it can be picked up by other executors.
     */
    void scheduleAsyncJob(JobEntity job);

    /**
     * Creates a {@link TimerJobEntity} based on the current {@link ExecutionEntity} and the configuration in the {@link TimerEventDefinition}.
     */
    TimerJobEntity createTimerJob(TimerEventDefinition timerEventDefinition, boolean interrupting, ExecutionEntity execution, String timerEventType, String jobHandlerConfiguration);

    /**
     * Schedules a timer, meaning it will be inserted in the datastore.
     */
    void scheduleTimerJob(TimerJobEntity timerJob);

    /**
     * Reschedules a timer by deleting the timer job and creating a new one with the specified definition.
     */
    TimerJobEntity rescheduleTimerJob(String timerJobId, TimerEventDefinition timerEventDefinition);

    /**
     * Moves a {@link TimerJobEntity} to become an async {@link JobEntity}.
     *
     * This happens for example when the due date of a timer is reached, the timer entity then becomes a 'regular' async job that can be picked up by the {@link AsyncExecutor}.
     */
    JobEntity moveTimerJobToExecutableJob(TimerJobEntity timerJob);

    /**
     * Moves an {@link AbstractRuntimeJobEntity} to become a {@link TimerJobEntity}.
     *
     * This happens for example when an async job is executed and fails. It then becomes a timer, as it needs to be retried later.
     */
    TimerJobEntity moveJobToTimerJob(AbstractRuntimeJobEntity job);

    /**
     * Moves an {@link AbstractRuntimeJobEntity} to become a {@link SuspendedJobEntity}, such that the {@link AsyncExecutor} won't pick it up anymore for execution.
     */
    SuspendedJobEntity moveJobToSuspendedJob(AbstractRuntimeJobEntity job);

    /**
     * Transforms a {@link SuspendedJobEntity} back to an {@link AbstractRuntimeJobEntity} (i.e. to what it was originally). The job will now again be able to picked up by the {@link AsyncExecutor}.
     */
    AbstractRuntimeJobEntity activateSuspendedJob(SuspendedJobEntity job);

    /**
     * Transforms an {@link AbstractRuntimeJobEntity} to a {@link DeadLetterJobEntity}. This means that the job has been tried a configurable amount of times, but kept failing.
     */
    DeadLetterJobEntity moveJobToDeadLetterJob(AbstractRuntimeJobEntity job);

    /**
     * Transforms a {@link DeadLetterJobEntity} to a {@link JobEntity}, thus making it executable again. Note that a 'retries' parameter needs to be passed, as the job got into the deadletter table
     * because of it failed and retries became 0.
     */
    JobEntity moveDeadLetterJobToExecutableJob(DeadLetterJobEntity deadLetterJobEntity, int retries);

    /**
     * The ProcessEngineConfiguration instance will be passed when the {@link ProcessEngine} is built.
     */
    void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration);

}


text: /opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py housekeeping


text:
import Governor from 'autocrat-governor'
import constant from 'lodash.constant'
import omit from 'lodash.omit'
import initializePeople from '../../../lib/initialize-people'
import { updateSeenCount, updateScore } from '../../../lib/update-people'
import find from 'lodash.find'

export default class PeopleGovernor extends Governor {

  state () { return {

    view: (prop) => { return {
      fetching: prop('fetching', {}),
      currentSet: prop('currentSet', []),
      showLoading: prop('showLoading'),
      currentlyFocused: prop('currentlyFocused'),
      currentSubject: prop('currentSubject')
    }},

    db: (prop) => { return {
      collection: prop('people', [])
    }}

    // ui: (prop) => { return {
    //   showLoading: prop('uiShowLoading', false)
    // }}

  }}

  laws (when, the) {

    when(the.app.mounts)
      .advise(the.people).to('fetch')

    when(the.people.areFetching)
      .updateProp('fetching')

    when(the.people.haveFetched)
      .updateProp('people')

    when(the.page.changesTo('Play'))
      .advise(the.people).to('selectNewSet')

    when(the.page.changesFrom('Play'))
      .advise(the.people).to('clearSet')

    when(the.people.getsNewSet)
      .advise(the.people).to('startLoading')
      .updateProps('currentSet', 'people', 'currentSubject', 'currentlyFocused')

    when(the.people.startsLoading)
      .updateProp('showLoading')

    when(the.people.stopsLoading)
      .updateProp('showLoading')
      .advise(the.timer).to('start')

    // Deep-linking to /play
    when.all(the.people.haveFetched, the.page.changesTo('Play'))
      .updateProp('people')
      .advise(the.people).to('selectNewSet')

    when(the.people.clearsItsSet)
      .updateProps('currentSet', 'currentlyFocused')
      .advise(the.timer).to('reset')

    when(the.app.focusesPerson)
      .updateProps('currentlyFocused')

    when(the.app.calculatesScore)
      .updateProps('people')

    when(the.app.finishesGivingPostAnswerFeedback)
      .advise(the.timer).to('reset')
      .advise(the.people).to('selectNewSet')

  }

  updateFetching (currVal, e) {
    if(e.type === 'people:areFetching' && e.data === true) {
      return { ...currVal, collection: true }
    } else {
      return omit(currVal, 'collection')
    }
  }

  // Oh... my... god... This should not be this hard.
  // TODO: Fix the bug where an updater can potentially be called
  // with a currVal that isn't the return value of the previous call
  updatePeople (currVal, e) {
    if(e.type === 'people:fetched') {
      const people = initializePeople(e.data.collection)
      return people
    } else if(e.type === 'people:selectNewSet') {
      const currentSet = e.data
      if(currVal && currentSet && currentSet.length) {
        let people
        const currPageName = this.autocrat.get('view.route.current.name').value()
        const isDeepLink = this.autocrat.get('view.route.isDeepLink').value()
        if(currPageName === 'Start' && isDeepLink) {
          if(!this.updatedSeenCount) {
            people = updateSeenCount(currVal, currentSet)
            this.seenCount = people
            this.updatedSeenCount = true
            return people
          } else {
            people = this.seenCount
            this.updatedSeenCount = false
            this.seenCount = null
            return people
          }
        } else {
          let upToDatePeople = this.autocrat.get('db.people.collection').value()
          if(!upToDatePeople.length) upToDatePeople = currVal
          people = updateSeenCount(upToDatePeople, currentSet)
          return people
        }
      } else {
        return currVal
      }
    } else if(e.type === 'app:calculateScore') {
      const [ subject ] = e.data
      const updated = updateScore(currVal, subject)
      return updated
    } else {
      return currVal
    }
  }

  updateCurrentSet (currVal, e) {
    if(e.type === 'people:clearSet') return []
    return (e.data || currVal)
  }

  updateShowLoading (currVal, e) {
    return e.type === 'people:startLoading' ? true : false
    // let nextVal
    // if(e && e.type === 'people:selectNewSet') {
    //   nextVal = true
    // } else {
    //   nextVal = false
    // }
    // this.props.uiShowLoading = nextVal
    // if(!e) this.props.showLoading = nextVal
    // return nextVal
  }

  updateCurrentlyFocused (currVal, e) {
    if(e.type === 'app:focusPerson') return e.data
    return null
  }

  updateCurrentSubject (currVal, e) {
    if(e.type === 'people:clearSet') return null
    return find(e.data, { isSubject: true })
  }

}


text:
package uk.ac.ebi.pride.utilities.data.controller.impl.ControllerImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.pride.utilities.data.controller.DataAccessController;
import uk.ac.ebi.pride.utilities.data.controller.DataAccessException;
import uk.ac.ebi.pride.utilities.data.controller.DataAccessMode;
import uk.ac.ebi.pride.utilities.data.controller.cache.CacheEntry;
import uk.ac.ebi.pride.utilities.data.controller.cache.strategy.MzDataCachingStrategy;
import uk.ac.ebi.pride.utilities.data.controller.impl.Transformer.MzDataTransformer;
import uk.ac.ebi.pride.utilities.data.core.*;
import uk.ac.ebi.pride.utilities.data.io.file.MzDataUnmarshallerAdaptor;
import uk.ac.ebi.pride.utilities.data.utils.MD5Utils;
import uk.ac.ebi.pride.tools.jmzreader.JMzReaderException;
import uk.ac.ebi.pride.tools.mzdata_parser.MzDataFile;
import uk.ac.ebi.pride.tools.mzdata_parser.mzdata.model.Admin;
import uk.ac.ebi.pride.tools.mzdata_parser.mzdata.model.CvLookup;
import uk.ac.ebi.pride.tools.mzdata_parser.mzdata.model.InstrumentDescription;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This controller is used to retrieve the information from mzData files. It uses the jmzReader
 * to retrieve the information from mzData files. The mzData files support Spectrum and Chromatogram
 * Information and also other important Metadata.
 *
 * @author Yasset Perez-Riverol
 * Date: 3/15/12
 * Time: 8:17 AM
 *
 */
public class MzDataControllerImpl extends CachedDataAccessController {

    private static final Logger logger = LoggerFactory.getLogger(MzDataControllerImpl.class);
    /**
     * Pattern for validating mzData format
     */
    private static final Pattern mzDataHeaderPattern = Pattern.compile("^[^<]*(<\\?xml [^>]*>\\s*(<!--[^>]*-->\\s*)*)?<(mzData) version=.*", Pattern.MULTILINE);

    /**
     * Reader for getting information from mzData file
     */
    private MzDataUnmarshallerAdaptor unmarshaller;

    public MzDataControllerImpl(File file) {
        super(file, DataAccessMode.CACHE_AND_SOURCE);
        initialize();
    }

    private void initialize() {
        File file = (File) this.getSource();
        // create unmarshaller
        MzDataFile um;
        try {
            um = new MzDataFile(file);
            unmarshaller = new MzDataUnmarshallerAdaptor(um);

            // set data source name
            this.setName(file.getName());
            // set the type
            this.setType(DataAccessController.Type.XML_FILE);
            // set the content categories
            this.setContentCategories(DataAccessController.ContentCategory.SPECTRUM,
                DataAccessController.ContentCategory.SAMPLE,
                DataAccessController.ContentCategory.INSTRUMENT,
                DataAccessController.ContentCategory.SOFTWARE,
                DataAccessController.ContentCategory.DATA_PROCESSING);
            // create cache builder
            setCachingStrategy(new MzDataCachingStrategy());
            // populate cache
            populateCache();
        } catch (JMzReaderException e) {
            String msg = "Exception while create the MzData File";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);

        }

    }

    /**
     * Get the backend data reader
     *
     * @return MzMLUnmarshallerAdaptor mzML reader
     */
    public MzDataUnmarshallerAdaptor getUnmarshaller() {
        return unmarshaller;
    }

    /**
     * Get the unique id for this data access controller
     * It generates a MD5 hash using the absolute path of the file
     * This will guarantee the same id if the file path is the same
     *
     * @return String  unique id
     */
    @Override
    public String getUid() {
        String uid = super.getUid();
        if (uid == null) {
            // create a new UUID
            File file = (File) this.getSource();
            try {
                uid = MD5Utils.generateHash(file.getAbsolutePath());
            } catch (NoSuchAlgorithmException e) {
                String msg = "Failed to generate unique id for mzML file";
                logger.error(msg, e);
            }
        }
        return uid;
    }

    /**
     * Get a list of cvlookups, these are not cached
     *
     * @return List<CvLookup>  a list of cvlookups
     * @ data access exception
     */
    public List<CVLookup> getCvLookups() {
        try {
            List<CvLookup> rawCvList = unmarshaller.getCvLookups();
            return MzDataTransformer.transformCVList(rawCvList);
        } catch (JMzReaderException e) {
            String msg = "Exception while trying to read a list of cv lookups";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * Get a list of samples by checking the cache first
     *
     * @return List<Sample>    a list of samples
     * @ data access exception
     */
    @Override
    public List<Sample> getSamples() {
        ExperimentMetaData metaData = super.getExperimentMetaData();

        if (metaData == null) {
            try {
                Admin rawSample = unmarshaller.getAdmin();
                return MzDataTransformer.transformSampleList(rawSample);
            } catch (JMzReaderException e) {
                String msg = "Exception while trying to read samples";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getSamples();
        }
    }

    /**
     * Get a list of person contacts
     *
     * @return List<Person>    list of persons
     * @ data access exception
     */
    public List<Person> getPersonContacts() {
        try {
            List<uk.ac.ebi.pride.tools.mzdata_parser.mzdata.model.Person> rawFileDesc = unmarshaller.getPersonContacts();
            // List of Persons
            return MzDataTransformer.transformToPerson(rawFileDesc);
        } catch (JMzReaderException e) {
            String msg = "Error while getting a list of person contacts";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * Get the information of SourceFiles.
     *
     * @return List of Source Files
     * @
     */
    public List<SourceFile> getSourceFiles() {
        try {
            uk.ac.ebi.pride.tools.mzdata_parser.mzdata.model.SourceFile rawFileDesc = unmarshaller.getSourceFiles();
            // List of Persons
            return MzDataTransformer.transformToFileSource(rawFileDesc);
        } catch (JMzReaderException e) {
            String msg = "Error while getting a list of source files";
            logger.error(msg, e);
            throw new DataAccessException(msg, e);
        }
    }

    /**
     * File Content is extra parameters related with Source Files in case of mzData.
     *
     * @return ParamGroup
     * @
     */
    public ParamGroup getFileContent() {
        ParamGroup paramGroup = null;
        List<SourceFile> sourceFiles = getSourceFiles();
        Set<CvParam> cvParamSet = null;

        if(sourceFiles != null){
            cvParamSet = new HashSet<CvParam>();
            for(SourceFile sourceFile: sourceFiles){
                if(sourceFile.getFileFormat() != null){
                    cvParamSet.add(sourceFile.getFileFormat());
                }
            }
        }
        if (cvParamSet != null){
            List<CvParam> cvParams = new ArrayList<CvParam>();
            cvParams.addAll(cvParamSet);
            paramGroup = new ParamGroup(cvParams,null);
        }
        return paramGroup;
    }

    /**
     * Get a List of Software
     * @return List<Software> List of Software
     * @
     */
    public List<Software> getSoftwares() {
        ExperimentMetaData metaData = super.getExperimentMetaData();

        if (metaData == null) {
            try {
                uk.ac.ebi.pride.tools.mzdata_parser.mzdata.model.Software rawSoftware = unmarshaller.getSoftware();
                return MzDataTransformer.transformSoftware(rawSoftware);
            } catch (JMzReaderException e) {
                String msg = "Error while getting a list of software";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getSoftwares();
        }
    }

    /**
     * Get a list of instrument configurations by checking the cache first
     *
     * @return List<Instrumentconfiguration>   a list of instrument configurations
     * @ data access exception
     */
    public List<InstrumentConfiguration> getInstrumentConfigurations() {
        MzGraphMetaData metaData = super.getMzGraphMetaData();

        if (metaData == null) {
            try {
                InstrumentDescription rawInstrumentList = unmarshaller.getInstrument();
                return MzDataTransformer.transformInstrumentConfiguration(rawInstrumentList);
            } catch (JMzReaderException e) {
                String msg = "Error while getting a list of instrument configurations";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getInstrumentConfigurations();
        }
    }

    /**
     * Get a list of data processings by checking the cache first
     *
     * @return List<DataProcessing>    a list of data processings
     * @ data access exception
     */
    public List<DataProcessing> getDataProcessings() {
        MzGraphMetaData metaData = super.getMzGraphMetaData();

        if (metaData == null) {
            try {
                uk.ac.ebi.pride.tools.mzdata_parser.mzdata.model.DataProcessing rawDataProcList = unmarshaller.getDataProcessing();
                return MzDataTransformer.transformDataProcessing(rawDataProcList);
            } catch (JMzReaderException e) {
                String msg = "Error while getting a list of data processings";
                logger.error(msg, e);
                throw new DataAccessException(msg, e);
            }
        } else {
            return metaData.getDataProcessings();
        }

    }

    /**
     * Get spectrum using a spectrum id, gives the option to choose whether to use cache.
     * This implementation provides a way of by passing the cache.
     *
     * @param id       spectrum id
     * @param useCache true means to use cache
     * @return Spectrum spectrum object
     * @ data access exception
     */
    @Override
    Spectrum getSpectrumById(Comparable id, boolean useCache) {
        Spectrum spectrum = super.getSpectrumById(id, useCache);
        if (spectrum == null) {
            try {
                uk.ac.ebi.pride.tools.jmzreader.model.Spectrum rawSpec = unmarshaller.getSpectrumById(id.toString());
                spectrum = MzDataTransformer.transformSpectrum(rawSpec);
                if (useCache) {
                    getCache().store(CacheEntry.SPECTRUM, id, spectrum);
                }
            } catch (JMzReaderException ex) {
                logger.error("Get spectrum by id", ex);
                throw new DataAccessException("Exception while trying to read Spectrum using Spectrum ID", ex);
            }
        }
        return spectrum;
    }

    /**
     * Get chromatogram using a chromatogram id, gives the option to choose whether to use cache.
     * This implementation provides a way of by passing the cache.
     *
     * @param id       chromatogram id
     * @param useCache true means to use cache
     * @return Chromatogram chromatogram object
     * @ data access exception
     */
    @Override
    public Chromatogram getChromatogramById(Comparable id, boolean useCache) {
        throw new UnsupportedOperationException("This method is not supported");
    }

    /**
     * Close data access controller by resetting the data reader first
     */
    @Override
    public void close() {
        unmarshaller = null;
        super.close();
    }

    @Override
    public ExperimentMetaData getExperimentMetaData(){

        ExperimentMetaData metaData = super.getExperimentMetaData();

        if (metaData == null) {
            // id , accession and version
            String id = unmarshaller.getIdMzData();

            String accession = null;
            // File Version
            String version = unmarshaller.getVersionMzData();

            // SourceFile List
            List<SourceFile> sourceFileList = getSourceFiles();

            // List of Persons
            List<Person> personList = getPersonContacts();

            // List of Organizations
            List<Organization> organizationList = null;

            // Sample list
            List<Sample> samples = getSamples();

            // Software list
            List<Software> softwares = getSoftwares();

            ParamGroup fileContent = getFileContent();

            metaData = new ExperimentMetaData(fileContent, id, accession, version, null, samples, softwares, personList, sourceFileList, null, organizationList, null, null, null, null);
        }
        return metaData;
    }

    @Override
    public MzGraphMetaData getMzGraphMetaData() {
        MzGraphMetaData metaData = super.getMzGraphMetaData();
        if (metaData == null) {
            List<ScanSetting> scanSettings = null;
            List<DataProcessing> dataProcessings = getDataProcessings();
            List<InstrumentConfiguration> instrumentConfigurations = getInstrumentConfigurations();
            metaData = new MzGraphMetaData(null, null, scanSettings, instrumentConfigurations, dataProcessings);
        }
        return metaData;
    }

    @Override
    public IdentificationMetaData getIdentificationMetaData() {
        return null;
    }

    /**
     * Check a file is mzML file
     *
     * @param file input file
     * @return boolean true means mzML
     */
    public static boolean isValidFormat(File file) {
        boolean valid = false;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            // read the first ten lines
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < 10; i++) {
                content.append(reader.readLine());
            }

            Matcher matcher = mzDataHeaderPattern.matcher(content);

            valid = matcher.find();
        } catch (Exception e) {
            logger.error("Failed to read file", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // do nothing here
                }
            }
        }

        return valid;
    }

}


text:
This is very simple editor of tesseract box files for Windows, in which you can create those files from scratch and not just refine tesseract's output.

[Download binary releases here](https://github.com/EvilVir/tesseract-box-creator/releases)

[Grab source code here](https://github.com/EvilVir/tesseract-box-creator.git)

##For now you can:

1. Load any one-page image
2. Create new box file from scratch or load existing one
3. Draw directly on the image
4. Fine edit box coordinates on the grid view
5. Zoom in/out

##For now you can't:

1. Load multipage tiff (most of code is there but needs some pieces to do).
2. Train your tesseract from this editor - this is just boxes editor, nothing more for now but also much more than anything I could find on the Web.

And yes, I know that some parts of this code could/should be done better. For now I just need simple editor to kickstart my other project, refinements will maybe come later (or you can pull and do some ;).

##Used technologies:
.NET 4.6.1, C#, WPF


text:
package org.apache.pig.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.pig.ExecType;
import org.apache.pig.backend.hadoop.executionengine.spark.SparkExecType;

public class SparkMiniCluster extends MiniGenericCluster {
    private static final File CONF_DIR = new File("build/classes");
    private static final File CONF_FILE = new File(CONF_DIR, "hadoop-site.xml");
    private ExecType spark = new SparkExecType();
    SparkMiniCluster() {

    }

    @Override
    public ExecType getExecType() {
        return spark;
    }

    @Override
    protected void setupMiniDfsAndMrClusters() {
        try {
            CONF_DIR.mkdirs();
            if (CONF_FILE.exists()) {
                CONF_FILE.delete();
            }
            m_conf = new Configuration();
            m_conf.set("io.sort.mb", "1");
            m_conf.writeXml(new FileOutputStream(CONF_FILE));
            int dataNodes = 4;
            m_dfs = new MiniDFSCluster(m_conf, dataNodes, true, null);
            m_fileSys = m_dfs.getFileSystem();
        } catch (IOException e) {
            throw new RuntimeException(e);

        }

    }

    @Override
    protected void shutdownMiniMrClusters() {
        if (CONF_FILE.exists()) {
            CONF_FILE.delete();
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2002-2004 Carl D. Worth, Jamey Sharp, Bart Massey, Josh Triplett
All Rights Reserved.  See the file COPYING in this directory
for licensing information.
-->
<xcb header="render" extension-xname="RENDER" extension-name="Render"
    major-version="0" minor-version="11">
  <!-- supports version 0.11 -->

  <import>xproto</import>

  <enum name="PictType">
    <item name="Indexed"> <value>0</value> </item>
    <item name="Direct">  <value>1</value> </item>
  </enum>

  <enum name="Picture">
    <item name="None"> <value>0</value> </item>
  </enum>

  <!-- Disjoint* and Conjoint* are new in version 0.2 -->
  <!-- PDF blend modes are new in version 0.11 -->
  <enum name="PictOp">
    <item name="Clear">               <value>0</value> </item>
    <item name="Src">                 <value>1</value> </item>
    <item name="Dst">                 <value>2</value> </item>
    <item name="Over">                <value>3</value> </item>
    <item name="OverReverse">         <value>4</value> </item>
    <item name="In">                  <value>5</value> </item>
    <item name="InReverse">           <value>6</value> </item>
    <item name="Out">                 <value>7</value> </item>
    <item name="OutReverse">          <value>8</value> </item>
    <item name="Atop">                <value>9</value> </item>
    <item name="AtopReverse">         <value>10</value> </item>
    <item name="Xor">                 <value>11</value> </item>
    <item name="Add">                 <value>12</value> </item>
    <item name="Saturate">            <value>13</value> </item>

    <item name="DisjointClear">       <value>16</value></item>
    <item name="DisjointSrc">         <value>17</value> </item>
    <item name="DisjointDst">         <value>18</value> </item>
    <item name="DisjointOver">        <value>19</value> </item>
    <item name="DisjointOverReverse"> <value>20</value> </item>
    <item name="DisjointIn">          <value>21</value> </item>
    <item name="DisjointInReverse">   <value>22</value> </item>
    <item name="DisjointOut">         <value>23</value> </item>
    <item name="DisjointOutReverse">  <value>24</value> </item>
    <item name="DisjointAtop">        <value>25</value> </item>
    <item name="DisjointAtopReverse"> <value>26</value> </item>
    <item name="DisjointXor">         <value>27</value> </item>

    <item name="ConjointClear">       <value>32</value></item>
    <item name="ConjointSrc">         <value>33</value> </item>
    <item name="ConjointDst">         <value>34</value> </item>
    <item name="ConjointOver">        <value>35</value> </item>
    <item name="ConjointOverReverse"> <value>36</value> </item>
    <item name="ConjointIn">          <value>37</value> </item>
    <item name="ConjointInReverse">   <value>38</value> </item>
    <item name="ConjointOut">         <value>39</value> </item>
    <item name="ConjointOutReverse">  <value>40</value> </item>
    <item name="ConjointAtop">        <value>41</value> </item>
    <item name="ConjointAtopReverse"> <value>42</value> </item>
    <item name="ConjointXor">         <value>43</value> </item>

    <!-- PDF blend modes are new in version 0.11 -->
    <item name="Multiply">            <value>48</value></item>
    <item name="Screen">              <value>49</value> </item>
    <item name="Overlay">             <value>50</value> </item>
    <item name="Darken">              <value>51</value> </item>
    <item name="Lighten">             <value>52</value> </item>
    <item name="ColorDodge">          <value>53</value> </item>
    <item name="ColorBurn">           <value>54</value> </item>
    <item name="HardLight">           <value>55</value> </item>
    <item name="SoftLight">           <value>56</value> </item>
    <item name="Difference">          <value>57</value> </item>
    <item name="Exclusion">           <value>58</value> </item>
    <item name="HSLHue">              <value>59</value> </item>
    <item name="HSLSaturation">       <value>60</value> </item>
    <item name="HSLColor">            <value>61</value> </item>
    <item name="HSLLuminosity">       <value>62</value> </item>
  </enum>

  <enum name="PolyEdge">
    <item name="Sharp">  <value>0</value> </item>
    <item name="Smooth"> <value>1</value> </item>
  </enum>

  <enum name="PolyMode">
    <item name="Precise">   <value>0</value> </item>
    <item name="Imprecise"> <value>1</value> </item>
  </enum>

  <enum name="CP">
    <item name="Repeat">          <bit>0</bit></item>
    <item name="AlphaMap">        <bit>1</bit></item>
    <item name="AlphaXOrigin">    <bit>2</bit></item>
    <item name="AlphaYOrigin">    <bit>3</bit></item>
    <item name="ClipXOrigin">     <bit>4</bit></item>
    <item name="ClipYOrigin">     <bit>5</bit></item>
    <item name="ClipMask">        <bit>6</bit></item>
    <item name="GraphicsExposure"><bit>7</bit></item>
    <item name="SubwindowMode">   <bit>8</bit></item>
    <item name="PolyEdge">        <bit>9</bit></item>
    <item name="PolyMode">        <bit>10</bit></item>
    <item name="Dither">          <bit>11</bit></item>
    <item name="ComponentAlpha">  <bit>12</bit></item>
  </enum>

  <enum name="SubPixel">
    <item name="Unknown">       <value>0</value> </item>
    <item name="HorizontalRGB"> <value>1</value> </item>
    <item name="HorizontalBGR"> <value>2</value> </item>
    <item name="VerticalRGB">   <value>3</value> </item>
    <item name="VerticalBGR">   <value>4</value> </item>
    <item name="None">          <value>5</value> </item>
  </enum>

  <!-- Extended repeat attributes introduced in 0.10 -->
  <enum name="Repeat">
    <item name="None">    <value>0</value> </item>
    <item name="Normal">  <value>1</value> </item>
    <item name="Pad">     <value>2</value> </item>
    <item name="Reflect"> <value>3</value> </item>
  </enum>

  <typedef oldname="CARD32" newname="GLYPH" />
  <xidtype name="GLYPHSET" />

  <xidtype name="PICTURE" />
  <xidtype name="PICTFORMAT" />

  <typedef oldname="INT32" newname="FIXED" />

  <error name="PictFormat" number="0" />
  <error name="Picture" number="1" />
  <error name="PictOp" number="2" />
  <error name="GlyphSet" number="3" />
  <error name="Glyph" number="4" />

  <struct name="DIRECTFORMAT">
    <field type="CARD16" name="red_shift" />
    <field type="CARD16" name="red_mask" />
    <field type="CARD16" name="green_shift" />
    <field type="CARD16" name="green_mask" />
    <field type="CARD16" name="blue_shift" />
    <field type="CARD16" name="blue_mask" />
    <field type="CARD16" name="alpha_shift" />
    <field type="CARD16" name="alpha_mask" />
  </struct>

  <struct name="PICTFORMINFO">
    <field type="PICTFORMAT" name="id" />
    <field type="CARD8" name="type" enum="PictType" />
    <field type="CARD8" name="depth" />
    <pad bytes="2" />
    <field type="DIRECTFORMAT" name="direct" />
    <field type="COLORMAP" name="colormap" />
  </struct>

  <struct name="PICTVISUAL">
    <field type="VISUALID" name="visual" />
    <field type="PICTFORMAT" name="format" />
  </struct>

  <struct name="PICTDEPTH">
    <field type="CARD8" name="depth" />
    <pad bytes="1" />
    <field type="CARD16" name="num_visuals" />
    <pad bytes="4" />
    <list type="PICTVISUAL" name="visuals">
      <fieldref>num_visuals</fieldref>
    </list>
  </struct>

  <struct name="PICTSCREEN">
    <field type="CARD32" name="num_depths" />
    <field type="PICTFORMAT" name="fallback" />
    <list type="PICTDEPTH" name="depths">
      <fieldref>num_depths</fieldref>
    </list>
  </struct>

  <struct name="INDEXVALUE">
    <field type="CARD32" name="pixel" />
    <field type="CARD16" name="red" />
    <field type="CARD16" name="green" />
    <field type="CARD16" name="blue" />
    <field type="CARD16" name="alpha" />
  </struct>

  <struct name="COLOR">
    <field type="CARD16" name="red" />
    <field type="CARD16" name="green" />
    <field type="CARD16" name="blue" />
    <field type="CARD16" name="alpha" />
  </struct>

  <struct name="POINTFIX">
    <field type="FIXED" name="x" />
    <field type="FIXED" name="y" />
  </struct>

  <struct name="LINEFIX">
    <field type="POINTFIX" name="p1" />
    <field type="POINTFIX" name="p2" />
  </struct>

  <struct name="TRIANGLE">
    <field type="POINTFIX" name="p1" />
    <field type="POINTFIX" name="p2" />
    <field type="POINTFIX" name="p3" />
  </struct>

  <struct name="TRAPEZOID">
    <field type="FIXED" name="top" />
    <field type="FIXED" name="bottom" />
    <field type="LINEFIX" name="left" />
    <field type="LINEFIX" name="right" />
  </struct>

  <struct name="GLYPHINFO">
    <field type="CARD16" name="width" />
    <field type="CARD16" name="height" />
    <field type="INT16" name="x" />
    <field type="INT16" name="y" />
    <field type="INT16" name="x_off" />
    <field type="INT16" name="y_off" />
  </struct>

  <request name="QueryVersion" opcode="0">
    <field type="CARD32" name="client_major_version" />
    <field type="CARD32" name="client_minor_version" />
    <reply>
      <pad bytes="1" />
      <field type="CARD32" name="major_version" />
      <field type="CARD32" name="minor_version" />
      <pad bytes="16" />
    </reply>
  </request>

  <request name="QueryPictFormats" opcode="1">
    <reply>
      <pad bytes="1" />
      <field type="CARD32" name="num_formats" />
      <field type="CARD32" name="num_screens" />
      <field type="CARD32" name="num_depths" />
      <field type="CARD32" name="num_visuals" />
      <field type="CARD32" name="num_subpixel" /> <!-- new in version 0.6 -->
      <pad bytes="4" />
      <list type="PICTFORMINFO" name="formats">
        <fieldref>num_formats</fieldref>
      </list>
      <list type="PICTSCREEN" name="screens">
        <fieldref>num_screens</fieldref>
      </list>
      <list type="CARD32" name="subpixels" enum="SubPixel" >
        <fieldref>num_subpixel</fieldref>
      </list>
    </reply>
  </request>

  <!-- from version 0.7 -->
  <request name="QueryPictIndexValues" opcode="2">
    <field type="PICTFORMAT" name="format" />
    <reply>
      <pad bytes="1" />
      <field type="CARD32" name="num_values" />
      <pad bytes="20" />
      <list type="INDEXVALUE" name="values">
        <fieldref>num_values</fieldref>
      </list>
    </reply>
  </request>

  <!-- opcode 3 reserved for QueryDithers -->

  <request name="CreatePicture" opcode="4">
    <field type="PICTURE" name="pid" />
    <field type="DRAWABLE" name="drawable" />
    <field type="PICTFORMAT" name="format" />
    <valueparam value-mask-type="CARD32"
                value-mask-name="value_mask"
                value-list-name="value_list" />
  </request>

  <request name="ChangePicture" opcode="5">
    <field type="PICTURE" name="picture" />
    <valueparam value-mask-type="CARD32"
                value-mask-name="value_mask"
                value-list-name="value_list" />
  </request>

  <request name="SetPictureClipRectangles" opcode="6">
    <field type="PICTURE" name="picture" />
    <field type="INT16" name="clip_x_origin" />
    <field type="INT16" name="clip_y_origin" />
    <list type="RECTANGLE" name="rectangles" />
  </request>

  <request name="FreePicture" opcode="7">
    <field type="PICTURE" name="picture" />
  </request>

  <request name="Composite" opcode="8">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="mask" altenum="Picture" />
    <field type="PICTURE" name="dst" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <field type="INT16" name="mask_x" />
    <field type="INT16" name="mask_y" />
    <field type="INT16" name="dst_x" />
    <field type="INT16" name="dst_y" />
    <field type="CARD16" name="width" />
    <field type="CARD16" name="height" />
  </request>

  <!-- opcode 9 reserved for Scale -->

  <request name="Trapezoids" opcode="10">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="dst" />
    <field type="PICTFORMAT" name="mask_format" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <list type="TRAPEZOID" name="traps" />
  </request>

  <request name="Triangles" opcode="11">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="dst" />
    <field type="PICTFORMAT" name="mask_format" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <list type="TRIANGLE" name="triangles" />
  </request>

  <request name="TriStrip" opcode="12">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="dst" />
    <field type="PICTFORMAT" name="mask_format" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <list type="POINTFIX" name="points" />
  </request>

  <request name="TriFan" opcode="13">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="dst" />
    <field type="PICTFORMAT" name="mask_format" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <list type="POINTFIX" name="points" />
  </request>

  <!-- opcode 14 reserved for ColorTrapezoids -->

  <!-- opcode 15 reserved for ColorTriangles -->

  <!-- opcode 16 reserved for Transform -->

  <request name="CreateGlyphSet" opcode="17">
    <field type="GLYPHSET" name="gsid" />
    <field type="PICTFORMAT" name="format" />
  </request>

  <request name="ReferenceGlyphSet" opcode="18">
    <field type="GLYPHSET" name="gsid" />
    <field type="GLYPHSET" name="existing" />
  </request>

  <request name="FreeGlyphSet" opcode="19">
    <field type="GLYPHSET" name="glyphset" />
  </request>

  <request name="AddGlyphs" opcode="20">
    <field type="GLYPHSET" name="glyphset" />
    <field type="CARD32" name="glyphs_len" />
    <list type="CARD32" name="glyphids">
      <fieldref>glyphs_len</fieldref>
    </list>
    <list type="GLYPHINFO" name="glyphs">
      <fieldref>glyphs_len</fieldref>
    </list>
    <list type="BYTE" name="data" />
  </request>

  <!-- opcode 21 reserved for AddGlyphsFromPicture -->

  <request name="FreeGlyphs" opcode="22">
    <field type="GLYPHSET" name="glyphset" />
    <list type="GLYPH" name="glyphs" />
  </request>

  <request name="CompositeGlyphs8" opcode="23">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="dst" />
    <field type="PICTFORMAT" name="mask_format" />
    <field type="GLYPHSET" name="glyphset" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <list type="BYTE" name="glyphcmds" />
  </request>

  <request name="CompositeGlyphs16" opcode="24">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="dst" />
    <field type="PICTFORMAT" name="mask_format" />
    <field type="GLYPHSET" name="glyphset" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <list type="BYTE" name="glyphcmds" />
  </request>

  <request name="CompositeGlyphs32" opcode="25">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="src" />
    <field type="PICTURE" name="dst" />
    <field type="PICTFORMAT" name="mask_format" />
    <field type="GLYPHSET" name="glyphset" />
    <field type="INT16" name="src_x" />
    <field type="INT16" name="src_y" />
    <list type="BYTE" name="glyphcmds" />
  </request>

  <!-- new in version 0.1 -->

  <request name="FillRectangles" opcode="26">
    <field type="CARD8" name="op" enum="PictOp" />
    <pad bytes="3" />
    <field type="PICTURE" name="dst" />
    <field type="COLOR" name="color" />
    <list type="RECTANGLE" name="rects" />
  </request>

  <!-- new in version 0.5 -->

  <request name="CreateCursor" opcode="27">
    <field type="CURSOR" name="cid" />
    <field type="PICTURE" name="source" />
    <field type="CARD16" name="x" />
    <field type="CARD16" name="y" />
  </request>

  <!-- new in version 0.6 -->

  <struct name="TRANSFORM">
    <field type="FIXED" name="matrix11" />
    <field type="FIXED" name="matrix12" />
    <field type="FIXED" name="matrix13" />
    <field type="FIXED" name="matrix21" />
    <field type="FIXED" name="matrix22" />
    <field type="FIXED" name="matrix23" />
    <field type="FIXED" name="matrix31" />
    <field type="FIXED" name="matrix32" />
    <field type="FIXED" name="matrix33" />
  </struct>

  <request name="SetPictureTransform" opcode="28">
    <field type="PICTURE" name="picture" />
    <field type="TRANSFORM" name="transform" />
  </request>

  <request name="QueryFilters" opcode="29">
    <field type="DRAWABLE" name="drawable" />
    <reply>
      <pad bytes="1" />
      <field type="CARD32" name="num_aliases" />
      <field type="CARD32" name="num_filters" />
      <pad bytes="16" />
      <list type="CARD16" name="aliases">
        <fieldref>num_aliases</fieldref>
      </list>
      <list type="STR" name="filters">
        <fieldref>num_filters</fieldref>
      </list>
    </reply>
  </request>

  <request name="SetPictureFilter" opcode="30">
    <field type="PICTURE" name="picture" />
    <field type="CARD16" name="filter_len" />
    <pad bytes="2" />
    <list type="char" name="filter">
      <fieldref>filter_len</fieldref>
    </list>
    <list type="FIXED" name="values" />
  </request>

  <!-- new in version 0.8 -->

  <struct name="ANIMCURSORELT">
    <field type="CURSOR" name="cursor" />
    <field type="CARD32" name="delay" />
  </struct>

  <request name="CreateAnimCursor" opcode="31">
    <field type="CURSOR" name="cid" />
    <list type="ANIMCURSORELT" name="cursors" />
  </request>

  <!-- new in version 0.9 -->

  <struct name="SPANFIX">
    <field type="FIXED" name="l" />
    <field type="FIXED" name="r" />
    <field type="FIXED" name="y" />
  </struct>

  <struct name="TRAP">
    <field type="SPANFIX" name="top" />
    <field type="SPANFIX" name="bot" />
  </struct>

  <request name="AddTraps" opcode="32">
    <field type="PICTURE" name="picture" />
    <field type="INT16" name="x_off" />
    <field type="INT16" name="y_off" />
    <list type="TRAP" name="traps" />
  </request>

  <!-- new in version 0.10 -->

  <request name="CreateSolidFill" opcode="33">
    <field type="PICTURE" name="picture" />
    <field type="COLOR" name="color" />
  </request>

  <request name="CreateLinearGradient" opcode="34">
    <field type="PICTURE" name="picture" />
    <field type="POINTFIX" name="p1" />
    <field type="POINTFIX" name="p2" />
    <field type="CARD32" name="num_stops" />
    <list type="FIXED" name="stops">
      <fieldref>num_stops</fieldref>
    </list>
    <list type="COLOR" name="colors">
      <fieldref>num_stops</fieldref>
    </list>
  </request>

  <request name="CreateRadialGradient" opcode="35">
    <field type="PICTURE" name="picture" />
    <field type="POINTFIX" name="inner" />
    <field type="POINTFIX" name="outer" />
    <field type="FIXED" name="inner_radius" />
    <field type="FIXED" name="outer_radius" />
    <field type="CARD32" name="num_stops" />
    <list type="FIXED" name="stops">
      <fieldref>num_stops</fieldref>
    </list>
    <list type="COLOR" name="colors">
      <fieldref>num_stops</fieldref>
    </list>
  </request>

  <request name="CreateConicalGradient" opcode="36">
    <field type="PICTURE" name="picture" />
    <field type="POINTFIX" name="center" />
    <field type="FIXED" name="angle" />        <!-- degrees -->
    <field type="CARD32" name="num_stops" />
    <list type="FIXED" name="stops">
      <fieldref>num_stops</fieldref>
    </list>
    <list type="COLOR" name="colors">
      <fieldref>num_stops</fieldref>
    </list>
  </request>
</xcb>