text:
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash](https://lodash.com/) exported as [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) modules.

Generated using [lodash-cli](https://www.npmjs.com/package/lodash-cli):
```bash
$ lodash modularize modern exports=node -o ./
$ lodash modern -d -o ./index.js
```

## Installation

Using npm:

```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash
```

In Node.js/io.js:

```js
// load the modern build
var _ = require('lodash');

// or a method category
var array = require('lodash/array');

// or a method
var chunk = require('lodash/array/chunk');
```

See the [package source](https://github.com/lodash/lodash/tree/3.0.0-npm) for more details.

**Note:**

Don't assign values to the [special variable](http://nodejs.org/api/repl.html#repl_repl_features) `_` when in the REPL.

Install [n_](https://www.npmjs.com/package/n_) for a REPL that includes lodash by default.

## Module formats

lodash is also available in a variety of other builds & module formats.

 * npm packages for [modern](https://www.npmjs.com/package/lodash), [compatibility](https://www.npmjs.com/package/lodash-compat), & [per method](https://www.npmjs.com/browse/keyword/lodash-modularized) builds
 * AMD modules for [modern](https://github.com/lodash/lodash/tree/3.0.0-amd) & [compatibility](https://github.com/lodash/lodash-compat/tree/3.0.0-amd) builds
 * ES modules for the [modern](https://github.com/lodash/lodash/tree/3.0.0-es) build

## Features *not* in Underscore

 * ~100% [code coverage](https://coveralls.io/r/lodash)
 * Follows [semantic versioning](http://semver.org/) for releases
 * Deferred chaining & [lazy evaluation](http://filimanjaro.com/blog/2014/introducing-lazy-evaluation/)
 * [_(…)](https://lodash.com/docs#_) supports intuitive chaining
 * [_.ary](https://lodash.com/docs#ary) & [_.rearg](https://lodash.com/docs#rearg) to change function argument limits & order
 * [_.at](https://lodash.com/docs#at) for cherry-picking collection values
 * [_.attempt](https://lodash.com/docs#attempt) to execute functions which may error without a try-catch
 * [_.before](https://lodash.com/docs#before) to complement [_.after](https://lodash.com/docs#after)
 * [_.bindKey](https://lodash.com/docs#bindKey) for binding [*"lazy"*](http://michaux.ca/articles/lazy-function-definition-pattern) defined methods
 * [_.chunk](https://lodash.com/docs#chunk) for splitting an array into chunks of a given size
 * [_.clone](https://lodash.com/docs#clone) supports shallow cloning of `Date` & `RegExp` objects
 * [_.cloneDeep](https://lodash.com/docs#cloneDeep) for deep cloning arrays & objects
 * [_.create](https://lodash.com/docs#create) for easier object inheritance
 * [_.curry](https://lodash.com/docs#curry) & [_.curryRight](https://lodash.com/docs#curryRight) for creating [curried](http://hughfdjackson.com/javascript/why-curry-helps/) functions
 * [_.debounce](https://lodash.com/docs#debounce) & [_.throttle](https://lodash.com/docs#throttle) are cancelable & accept options for more control
 * [_.findIndex](https://lodash.com/docs#findIndex) & [_.findKey](https://lodash.com/docs#findKey) for finding indexes & keys
 * [_.flow](https://lodash.com/docs#flow) to complement [_.flowRight](https://lodash.com/docs#vlowRight) (a.k.a `_.compose`)
 * [_.forEach](https://lodash.com/docs#forEach) supports exiting early
 * [_.forIn](https://lodash.com/docs#forIn) for iterating all enumerable properties
 * [_.forOwn](https://lodash.com/docs#forOwn) for iterating own properties
 * [_.includes](https://lodash.com/docs#includes) accepts a `fromIndex`
 * [_.isError](https://lodash.com/docs#isError) to check for error objects
 * [_.isNative](https://lodash.com/docs#isNative) to check for native functions
 * [_.isPlainObject](https://lodash.com/docs#isPlainObject) & [_.toPlainObject](https://lodash.com/docs#toPlainObject) to check for & convert to `Object` objects
 * [_.isTypedArray](https://lodash.com/docs#isTypedArray) to check for typed arrays
 * [_.keysIn](https://lodash.com/docs#keysIn) & [_.valuesIn](https://lodash.com/docs#valuesIn) for getting keys & values of all enumerable properties
 * [_.mapValues](https://lodash.com/docs#mapValues) for [mapping](https://lodash.com/docs#map) values to an object
 * [_.merge](https://lodash.com/docs#merge) for a deep [_.extend](https://lodash.com/docs#extend)
 * [_.parseInt](https://lodash.com/docs#parseInt) for consistent cross-environment behavior
 * [_.pull](https://lodash.com/docs#pull), [_.pullAt](https://lodash.com/docs#pullAt), & [_.remove](https://lodash.com/docs#remove) for mutating arrays
 * [_.random](https://lodash.com/docs#random) supports returning floating-point numbers
 * [_.runInContext](https://lodash.com/docs#runInContext) for collisionless mixins & easier mocking
 * [_.slice](https://lodash.com/docs#slice) for creating subsets of array-like values
 * [_.sortByAll](https://lodash.com/docs#sortBy) for sorting by multiple properties
 * [_.support](https://lodash.com/docs#support) for flagging environment features
 * [_.template](https://lodash.com/docs#template) supports [*"imports"*](https://lodash.com/docs#templateSettings_imports) options & [ES template delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components)
 * [_.transform](https://lodash.com/docs#transform) as a powerful alternative to [_.reduce](https://lodash.com/docs#reduce) for transforming objects
 * [_.thru](https://lodash.com/docs#thru) to pass values thru method chains
 * [_.where](https://lodash.com/docs#where) supports deep object comparisons
 * [_.xor](https://lodash.com/docs#xor) to complement [_.difference](https://lodash.com/docs#difference), [_.intersection](https://lodash.com/docs#intersection), & [_.union](https://lodash.com/docs#union)
 * [_.bind](https://lodash.com/docs#bind), [_.curry](https://lodash.com/docs#curry), [_.partial](https://lodash.com/docs#partial), &
   [more](https://lodash.com/docs "_.bindKey, _.curryRight, _.partialRight") support customizable argument placeholders
 * [_.capitalize](https://lodash.com/docs#capitalize), [_.trim](https://lodash.com/docs#trim), &
   [more](https://lodash.com/docs "_.camelCase, _.deburr, _.endsWith, _.escapeRegExp, _.kebabCase, _.pad, _.padLeft, _.padRight, _.repeat, _.snakeCase, _.startsWith, _.trimLeft, _.trimRight, _.trunc, _.words") string methods
 * [_.clone](https://lodash.com/docs#clone), [_.isEqual](https://lodash.com/docs#isEqual), &
   [more](https://lodash.com/docs "_.assign, _.cloneDeep, _.merge") accept callbacks
 * [_.dropWhile](https://lodash.com/docs#dropWhile), [_.takeWhile](https://lodash.com/docs#takeWhile), &
   [more](https://lodash.com/docs "_.drop, _.dropRightWhile, _.take, _.takeRightWhile") to complement [_.first](https://lodash.com/docs#first), [_.initial](https://lodash.com/docs#initial), [_.last](https://lodash.com/docs#last), & [_.rest](https://lodash.com/docs#rest)
 * [_.findLast](https://lodash.com/docs#findLast), [_.findLastIndex](https://lodash.com/docs#findLastIndex), &
   [more](https://lodash.com/docs "_.findLastKey, _.flowRight, _.forEachRight, _.forInRight, _.forOwnRight, _.partialRight") right-associative methods
 * [_.includes](https://lodash.com/docs#includes), [_.toArray](https://lodash.com/docs#toArray), &
   [more](https://lodash.com/docs "_.at, _.countBy, _.every, _.filter, _.find, _.findLast, _.forEach, _.forEachRight, _.groupBy, _.indexBy, _.invoke, _.map, _.max, _.min, _.partition, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.size, _.some, _.sortBy") accept strings

## Support

Tested in Chrome 39-40, Firefox 34-35, IE 6-11, Opera 25-26, Safari 5-8, io.js 1.0.4, Node.js 0.8.28 & 0.10.35, PhantomJS 1.9.8, RingoJS 0.11, & Rhino 1.7RC5.

Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. Special thanks to [Sauce Labs](https://saucelabs.com/) for providing automated browser testing.


text:
package sinalgo.models;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

import sinalgo.configuration.Configuration;
import sinalgo.configuration.WrongConfigurationException;
import sinalgo.tools.Tuple;

/**
 * This model class provides some static functionalities to create models.
 */
public abstract class Model {

	private String paramString = ""; // The parameter string passed either on the console or by the gui

	/**
	 * Sets the parameter string that was passed to the constructor of this model on the console or through the GUI.
	 * @param params The String to set the parameter string to.
	 */
	public void setParamString(String params) {
		paramString = params;
	}

	/**
	 * Returns the parameter string pased to the constructor of this model on the console or through the GUI.
	 * @return The parameter string pased to the constructor of this model on the console or through the GUI.
	 */
	public String getParamString() {
		return paramString;
	}

	/**
	 * Returns the type of this model.
	 * @return The type of this model.
	 */
	public abstract ModelType getType();

	/**
	 * Returns the class-object of a given model.
	 *
	 * @param type The type of the model
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 *
	 * @return A class object of the required model.
	 * @throws WrongConfigurationException If the specified class cannot be found or created.
	 */
	public static Class<?> getModelClass(ModelType type, String className) throws WrongConfigurationException {
		String modelName = type.name();
	  // replace first letter with lower-case version and append an 's'
		modelName = modelName.substring(0,1).toLowerCase() + modelName.substring(1) + "s";

		Class<?> result = null;
		try {
			String name = "";
			if(className.contains(".")) {
				name = className; // kind of a hack: the name is already absolute.
			} else if(className.contains(":")){ // the name is composed as 'project-name':'class-name'
				String[] parts = className.split(":",2);
				name =  Configuration.userProjectsPath + "." + parts[0] + ".models." + modelName + "." + parts[1];

			}	else{
				name = Configuration.defaultProjectPath + ".models." + modelName + "." + className;
			}
			result = Class.forName(name);
		} catch (ClassNotFoundException e) {
			throw new WrongConfigurationException(e, "Cannot generate class for the " +
			                                      modelName + ". The class " +  className +
			                                      " cannot be found. ("+ e.getMessage() + ")");
		}

		return result;
	}

	/**
	 * Creates an instance of a model given the name and type of the model.
	 *
	 * @param type The type of the model
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 *
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	public static Model getModelInstance(ModelType type, String className, Object ...parameters) throws WrongConfigurationException {
		Class<?> c = getModelClass(type, className);
		return getModelInstance(c, className, parameters);
	}

	/**
	 * Creates an instance of a connectivity model given the name of the model.
	 *
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	public static ConnectivityModel getConnectivityModelInstance(String className, Object ...parameters) throws WrongConfigurationException {
		return (ConnectivityModel) getModelInstance(ModelType.ConnectivityModel, className, parameters);
	}

	/**
	 * Creates an instance of a distribution model given the name of the model.
	 *
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	public static DistributionModel getDistributionModelInstance(String className, Object ...parameters) throws WrongConfigurationException {
		return (DistributionModel) getModelInstance(ModelType.DistributionModel, className, parameters);
	}

	/**
	 * Creates an instance of a interference model given the name of the model.
	 *
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	public static InterferenceModel getInterferenceModelInstance(String className, Object ...parameters) throws WrongConfigurationException {
		return (InterferenceModel) getModelInstance(ModelType.InterferenceModel, className, parameters);
	}

	/**
	 * Creates an instance of a message transmission model given the name of the model.
	 *
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	public static MessageTransmissionModel getMessageTransmissionModelInstance(String className, Object ...parameters) throws WrongConfigurationException {
		return (MessageTransmissionModel) getModelInstance(ModelType.MessageTransmissionModel, className, parameters);
	}

	/**
	 * Creates an instance of a mobility model given the name of the model.
	 *
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	public static MobilityModel getMobilityModelInstance(String className, Object ...parameters) throws WrongConfigurationException {
		return (MobilityModel) getModelInstance(ModelType.MobilityModel, className, parameters);
	}

	/**
	 * Creates an instance of a reliabitliy model given the name of the model.
	 *
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	public static ReliabilityModel getReliabilityModelInstance(String className, Object ...parameters) throws WrongConfigurationException {
		return (ReliabilityModel) getModelInstance(ModelType.ReliabilityModel, className, parameters);
	}

	/**
	 * Creates an instance of a model given the class.
	 *
	 * @param c The class of the model.
	 * @param className The name of the model - only used to produce meaningful error-texts.
	 * @param parameters The parameters for the constructor, no further parameters if no parameters should be passed on to the constructor.
	 * @return An instance of the specified model.
	 * @throws WrongConfigurationException If the constructor cannot be created or the instanciation fails. Note:
	 * call getCause() to obtain the original exception.
	 */
	private static Model getModelInstance(Class<?> c, String className, Object ...parameters) throws WrongConfigurationException {
		Class<?>[] types = new Class[parameters.length];
		for(int i=0; i < parameters.length; i++) {
			types[1] = parameters[i].getClass();
		}
		Model result = null;
		try {
			Constructor<?> constructor = c.getConstructor(types);
			result = (Model) constructor.newInstance(parameters);
		} catch (SecurityException e) {
			throw new WrongConfigurationException("Cannot generate constructor of the model '" + className + "' due to a SecurityException: " + e.getMessage());
		} catch (NoSuchMethodException e) {
			String paramTypes = "";
			for(Class<?> cl : types) {
				paramTypes += cl.getSimpleName() + ", ";
			}
			throw new WrongConfigurationException(e, "Cannot generate constructor of the model '" + className + "'. There is no constructor that takes the parameters: (" + paramTypes + ").");
		} catch (IllegalArgumentException e) {
			throw new WrongConfigurationException(e, "Cannot generate instance of the model '" + className + "' due to wrong arguments.");
		} catch (InstantiationException e) {
			String cause = e.getCause() == null ? "" : e.getCause().getMessage();
			throw new WrongConfigurationException(e, "Cannot generate instance of the model '" + className + "' : " + cause);
		} catch (IllegalAccessException e) {
			throw new WrongConfigurationException(e, "Cannot generate instance of the model '" + className + "'");
		} catch (InvocationTargetException e) {
			String cause = e.getCause() == null ? "" : e.getCause().getMessage();
			throw new WrongConfigurationException(e, "Cannot generate instance of the model '" + className + "' :  " + cause);
		}

		return result;
	}

	/**
	 * The model can be prefix with the type of the model in an abreviated manner in the form X=model_name
	 * where X is the prefix of one character and model_name the name of the model. X is one of the
	 * characters in {C|D|I|T|M|R} and maps to a model as defined below in the initializer.
	 *

	 * The prefix X is used to disambiguate different models if different several models have the same name.
	 */
	private static HashMap<String, ModelType> modelEnumPrefix = new HashMap<String, ModelType>();
	static {
		// initialize the mapping from prefix to ModelEnum
		modelEnumPrefix.put("C", ModelType.ConnectivityModel);
		modelEnumPrefix.put("D", ModelType.DistributionModel);
		modelEnumPrefix.put("I", ModelType.InterferenceModel);
		modelEnumPrefix.put("T", ModelType.MessageTransmissionModel);
		modelEnumPrefix.put("M", ModelType.MobilityModel);
		modelEnumPrefix.put("R", ModelType.ReliabilityModel);
	}

	/**
	 * Creates the class of a model given the model-name, if the model-name uniquely defines the model.
	 *

	 * This method does not require the model-type. I.e. this method tests all possible model-folders
	 * and returns the model that matches this name. If there is an ambiguity, this method throws an exception.
	 *

	 * To disambiguate a model-name, it can be prefixed to indicate the model-kind.
	 * The prefix looks like X=model-name where X is {C|D|I|T|M|R}. The mapping is as following:
	 *

	 *
C-ConnectivityModel

	 *
D-DistributionModel

	 *
I-InterferenceModel

	 *
T-MessageTransmissionModel

	 *
M-MobilityModel

	 *
R-ReliabilityModel

	 *

	 *
	 * @param modelName The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @return A class object of the required model.
	 * @throws WrongConfigurationException If the specified class cannot be found or created, or if the modelName does
	 * not uniquely define a model.
	 */
	public static Tuple<ModelType, Class<?>> getModelClass(String modelName) throws WrongConfigurationException {
		if(modelName.length() > 2 && modelName.charAt(1) == '=') {
			// the modelName is prefixed with a disambiguation prefix that indicates the model type
			if(!modelEnumPrefix.containsKey(modelName.substring(0,1))) {
				throw new WrongConfigurationException("Cannot create an instance of the model " + modelName +
				                                      ". The prefix '" + modelName.substring(0,1) +
				                                      "' does not specify a model. Valid prefixes are {C|D|I|T|M|R}."
				);
			}
			ModelType model = modelEnumPrefix.get(modelName.substring(0,1));
			return new Tuple<ModelType, Class<?>>(model , getModelClass(model, modelName.substring(2)));
		} else {
			Class<?> modelClass = null;
			ModelType type = null;
			int succeeded = 0;
			String modelNames = ""; // the list of possible models (for exception text)
			// test each model, exactly one should succeed
			for(ModelType mt : ModelType.values()) {
				try {
					modelClass = getModelClass(mt, modelName);
					type = mt;
					succeeded ++;
					modelNames += mt.name() + " ";
				} catch(WrongConfigurationException e) {} // ok to fail
			}
			if(succeeded == 0) {
				throw new WrongConfigurationException("Cannot create an instance of the model " + modelName + ". The class is not found.");
			} else if(succeeded > 1){
				throw new WrongConfigurationException("Cannot create an instance of the model '" + modelName +
				                                      "'. The model is not uniquely defined - there exists a model with the name '" +
				                                      modelName + "' for [" + modelNames + "]. To disambiguate the situaion, you may " +
				                                      "prefix the model to indicate the model-kind. The prefix looks like X=model-name, " +
				                                      "where X is {C|D|I|T|M|R}. The mapping is as following: \n" +
				                                      "C-ConnectivityModel\n" +
				                                      "D-DistributionModel\n" +
				                                      "I-InterferenceModel\n" +
				                                      "T-MessageTransmissionModel\n" +
				                                      "M-MobilityModel\n" +
				                                      "R-ReliabilityModel"
				);
			} else {
				return new Tuple<ModelType, Class<?>>(type, modelClass);
			}
		}
	}

	/**
	 * Creates an instance of a model given the model-name, if the model-name uniquely defines the model.
	 *

	 * This method does not require the model-type. I.e. this method tests all possible model-folders
	 * and returns the model that matches this name. If there is an ambiguity, this method throws an exception.
	 *

	 * To disambiguate a model-name, it can be prefixed to indicate the model-kind.
	 * The prefix looks like X=model-name where X is {C|D|I|T|M|R}. The mapping is as following:
	 *

	 *
C-ConnectivityModel

	 *
D-DistributionModel

	 *
I-InterferenceModel

	 *
T-MessageTransmissionModel

	 *
M-MobilityModel

	 *
R-ReliabilityModel

	 *

	 *
	 * @param className The name of the model. If the model is stored
	 * in a project, it must be prefixed with the proejct-name and a
	 * colon. E.g. looks like 'project-name':'class-name'.
	 * Otherwise, to take the default model, only give the class-name.
	 * If className contains '.' characters, it is assumed that the fully qualified
	 * class-name is provided.
	 * @param parameters The parameters passed to the constructor.
	 * @return A class object of the required model.
	 * @throws WrongConfigurationException If the specified class cannot be found or created, or if the modelName does
	 * not uniquely define a model.
	 */
	public static Model getModelInstance(String className, Object ...parameters) throws WrongConfigurationException {
		Tuple<ModelType, Class<?>> tmp = getModelClass(className);
		return getModelInstance(tmp.second, className, parameters);
	}
}

redpajama_set_name: RedPajamaGithub


text:
'''
forms module

.. moduleauthor::  Gerson Galang <gerson.galang@versi.edu.au>

'''

from os.path import basename
from UserDict import UserDict

from django import forms
from django.forms import ValidationError
from django.forms.util import ErrorList
from django.forms.models import ModelChoiceField
from django.forms.models import inlineformset_factory
from django.forms.models import BaseInlineFormSet
from django.forms.widgets import HiddenInput
from django.forms import ModelForm
from django.contrib.auth.forms import AuthenticationForm
from django.conf import settings
from django.db import transaction
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

from haystack.forms import SearchForm

from form_utils import forms as formutils
from registration.models import RegistrationProfile

from tardis.tardis_portal import models
from tardis.tardis_portal.fields import MultiValueCommaSeparatedField
from tardis.tardis_portal.widgets import CommaSeparatedInput, Span, TextInput
from tardis.tardis_portal.models import UserProfile, UserAuthentication, \
    Experiment, License
from tardis.tardis_portal.auth.localdb_auth \
    import auth_key as locabdb_auth_key

from tardis.tardis_portal.ParameterSetManager import ParameterSetManager

import logging
logger = logging.getLogger(__name__)

def getAuthMethodChoices():
    authMethodChoices = ()
    for authMethods in settings.AUTH_PROVIDERS:
        authMethodChoices += ((authMethods[0], authMethods[1]),)
    return authMethodChoices

class LoginForm(AuthenticationForm):
    authMethod = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.fields['username'] = \
             forms.CharField(required=True,
                             label="Username",
                             max_length=75)

        self.fields['authMethod'] = \
            forms.CharField(required=True,
                            widget=forms.Select(choices=getAuthMethodChoices()),
                            label='Authentication Method')

attrs_dict = {'class': 'required'}

class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.

    Validates that the requested username is not already in use, and
    requires the password to be entered twice to catch typos.

    Subclasses should feel free to add any additional validation they
    need, but should avoid defining a ``save()`` method -- the actual
    saving of collected user data is delegated to the active
    registration backend.

    """

    username = forms.RegexField(
        regex=r'^[\w\.]+$',
        max_length=30,
        widget=forms.TextInput(attrs=attrs_dict),
        label=_("Username"),
        error_messages={'invalid':
            _("This value must contain only letters, \
            numbers and underscores.")})
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
                                                               maxlength=75)),
                             label=_("Email address"))

    password1 = forms.CharField(
        widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
        label=_("Password"))

    password2 = forms.CharField(
        widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
        label=_("Password (again)"))

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.

        """
        username = '%s' % self.cleaned_data['username']

        try:
            User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            _("A user with that username already exists."))

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.

        """
        if 'password1' in self.cleaned_data and \
                'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != \
                    self.cleaned_data['password2']:
                raise forms.ValidationError(
                    _("The two password fields didn't match."))

        return self.cleaned_data

    @transaction.commit_on_success()
    def save(self, profile_callback=None):
        user = RegistrationProfile.objects.create_inactive_user(
            username=self.cleaned_data['username'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'])

        userProfile = UserProfile(user=user, isDjangoAccount=True)
        userProfile.save()

        authentication = UserAuthentication(
            userProfile=userProfile,
            username=self.cleaned_data['username'],
            authenticationMethod=locabdb_auth_key)
        authentication.save()

        return user

class ChangeUserPermissionsForm(ModelForm):

    class Meta:
        from django.forms.extras.widgets import SelectDateWidget
        from tardis.tardis_portal.models import ExperimentACL
        model = ExperimentACL
        exclude = ('entityId', 'pluginId', 'experiment', 'aclOwnershipType',)
        widgets = {
            'expiryDate': SelectDateWidget(),
            'effectiveDate': SelectDateWidget()}

class ChangeGroupPermissionsForm(forms.Form):

    from django.forms.extras.widgets import SelectDateWidget

    canRead = forms.BooleanField(label='canRead', required=False)
    canWrite = forms.BooleanField(label='canWrite', required=False)
    canDelete = forms.BooleanField(label='', required=False,
                                   widget=forms.HiddenInput)

    effectiveDate = forms.DateTimeField(label='Effective Date',
            widget=SelectDateWidget(), required=False)
    expiryDate = forms.DateTimeField(label='Expiry Date',
            widget=SelectDateWidget(), required=False)

class AddUserPermissionsForm(forms.Form):

    entered_user = forms.CharField(label='User', required=False, max_length=100)
    autocomp_user = forms.CharField(label='', required=False, max_length=100,
                                   widget=forms.HiddenInput)
    authMethod = forms.CharField(required=True,
        widget=forms.Select(choices=getAuthMethodChoices()),
        label='Authentication Method')
    read = forms.BooleanField(label='Read access', required=False, initial=True)
    read.widget.attrs['class'] = 'canRead'
    write = forms.BooleanField(label='Edit access', required=False)
    write.widget.attrs['class'] = 'canWrite'
    delete = forms.BooleanField(label='', required=False,
                                   widget=forms.HiddenInput)
    delete.widget.attrs['class'] = 'canDelete'

class AddGroupPermissionsForm(forms.Form):

    addgroup = forms.CharField(label='Group', required=False, max_length=100)
    addgroup.widget.attrs['class'] = 'groupsuggest'
    authMethod = forms.CharField(required=True,
        widget=forms.Select(choices=getAuthMethodChoices()),
        label='Authentication Method')

class CreateGroupPermissionsForm(forms.Form):
    addgroup = forms.CharField(label='Group', required=False, max_length=100)
    addgroup.widget.attrs['class'] = 'groupsuggest'
    authMethod = forms.CharField(required=True,
        widget=forms.Select(choices=getAuthMethodChoices()),
        label='Authentication Method')
    adduser = forms.CharField(label='User', required=False, max_length=100)
    adduser.widget.attrs['class'] = 'usersuggest'

class ManageGroupPermissionsForm(forms.Form):

    authMethod = forms.CharField(required=True,
        widget=forms.Select(choices=getAuthMethodChoices()),
        label='Authentication Method')
    adduser = forms.CharField(label='User', required=False, max_length=100)
    adduser.widget.attrs['class'] = 'usersuggest'
    admin = forms.BooleanField(label='Group Admin', required=False, initial=False)
    admin.widget.attrs['class'] = 'isAdmin'

class CreateUserPermissionsForm(RegistrationForm):
    authMethod = forms.CharField(required=True,
        widget=forms.Select(choices=getAuthMethodChoices()),
        label='Authentication Method')

class DatafileSearchForm(forms.Form):

    filename = forms.CharField(required=False, max_length=100)

# microscopy
class MXDatafileSearchForm(DatafileSearchForm):

    __DIFFRACTOMETER_CHOICES = (
        ('-', '-'),
        ('Synchrotron', 'Synchrotron'),
        ('Rotating Anode', 'Rotating Anode'),
        ('Tube', 'Tube'))
    diffractometerType = \
        forms.CharField(widget=forms.Select(choices=__DIFFRACTOMETER_CHOICES),
        label='Diffractometer Type')
    xraySource = forms.CharField(
        required=False, label='X-ray Source', max_length=20)
    crystalName = forms.CharField(
        required=False, label='Crystal Name', max_length=20)
    resolutionLimit = forms.IntegerField(
        required=False, label='Max Resolution Limit')
    xrayWavelengthFrom = forms.IntegerField(
        required=False, label='X-ray Wavelength From',
        widget=forms.TextInput(attrs={'size': '4'})
        )
    xrayWavelengthTo = forms.IntegerField(
        required=False, label='X-ray Wavelength To',
        widget=forms.TextInput(attrs={'size': '4'})
        )

def createLinkedUserAuthenticationForm(authMethods):
    """Create a LinkedUserAuthenticationForm and use the contents of
    authMethods to the list of options in the dropdown menu for
    authenticationMethod.

    """
    _authenticationMethodChoices = ()
    for authMethodKey in authMethods.keys():
        _authenticationMethodChoices += (
            (authMethodKey, authMethods[authMethodKey]), )

    fields = {}
    fields['authenticationMethod'] = \
        forms.CharField(label='Authentication Method',
        widget=forms.Select(choices=_authenticationMethodChoices),
        required=True)
    fields['username'] = forms.CharField(label='Username',
        max_length=75, required=True)
    fields['password'] = forms.CharField(required=True,
        widget=forms.PasswordInput(), label='Password', max_length=12)

    return type('LinkedUserAuthenticationForm', (forms.BaseForm, ),
                    {'base_fields': fields})

# infrared
class IRDatafileSearchForm(DatafileSearchForm):
    pass

class ImportParamsForm(forms.Form):

    username = forms.CharField(max_length=400, required=True)
    password = forms.CharField(max_length=400, required=True)
    params = forms.FileField()

class RegisterExperimentForm(forms.Form):

    username = forms.CharField(max_length=400, required=True)
    password = forms.CharField(max_length=400, required=True)
    xmldata = forms.FileField()
    experiment_owner = forms.CharField(max_length=400, required=False)
    originid = forms.CharField(max_length=400, required=False)
    from_url = forms.CharField(max_length=400, required=False)

class DatasetForm(forms.ModelForm):

    class Meta:
        model = models.Dataset
        exclude = ('experiments', 'immutable')

class Author_Experiment(forms.ModelForm):

    class Meta:
        model = models.Author_Experiment
        exclude = ('experiment', )

class ExperimentForm(forms.ModelForm):
    """
    This handles the complex experiment forms.

    All internal datasets forms are prefixed with `dataset_`, and all
    internal dataset file fields are prefixed with `file_`. These
    are parsed out of the post data and added to the form as internal
    lists.
    """
    url = forms.CharField(required=False)

    class Meta:
        model = models.Experiment
        fields = ('title', 'institution_name', 'description')

    class FullExperiment(UserDict):
        """
        This is a dict wrapper that store the values returned from
        the :func:`tardis.tardis_portal.forms.ExperimentForm.save` function.
        It provides a convience method for saving the model objects.
        """

        def save_m2m(self):
            """
            {'experiment': experiment,
            'author_experiments': author_experiments,
            'authors': authors,
            'datasets': datasets,
            'dataset_files': dataset_files}
            """
            self.data['experiment'].save()
            for ae in self.data['author_experiments']:
                ae.experiment = self.data['experiment']
                print ae
                ae.save()

    def __init__(self, data=None, files=None, auto_id='%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None, extra=0):

        super(ExperimentForm, self).__init__(data=data,
                                             files=files,
                                             auto_id=auto_id,
                                             prefix=prefix,
                                             initial=initial,
                                             instance=instance,
                                             error_class=error_class,
                                             label_suffix=label_suffix,
                                             empty_permitted=False)

        # fix up experiment form
        if instance and not data:
                authors = instance.author_experiment_set.all()
                self.initial['authors'] = ', '.join([self._format_author(a)
                                                     for a in authors])

        self.author_experiments = []

        if data:
            self._update_authors(data)

        self.fields['authors'] = \
            MultiValueCommaSeparatedField([author.fields['author'] for
                                        author in self.author_experiments],
                widget=CommaSeparatedInput(attrs={
                    'placeholder': "eg. Howard W. Florey, Brian Schmidt "+
                                   "(http://nla.gov.au/nla.party-1480342)"}),
                help_text="Comma-separated authors and optional URLs")

        for _, field in self.fields.items():
            field.widget.attrs['class'] = "span8"

    def _format_author(self, author):
        if author.url:
            return "%s (%s)" % (author.author, author.url)
        return author.author

    def _parse_authors(self, data):
        """
        create a dictionary containing each of the sub form types.
        """
        if 'authors' not in data:
            return []

        def build_dict(order, author_str):
            import re
            author_str = author_str.strip()
            url_match = re.match('([^\(]+)\(([^\)]+)\)', author_str)
            if url_match:
                try:
                    author_str, url = url_match.group(1, 2)
                    # Check that it really is a URL
                    url = Author_Experiment().fields['url'].clean(url)
                    return {'order': order,
                            'author': author_str.strip(),
                            'url': url}
                except ValidationError:
                    pass
            return {'order': order,
                    'author': author_str}

        return [build_dict(i, a)
                for i, a in enumerate(data.get('authors').split(','))]

    def _update_authors(self, data):
        # For each author in the POST in a position
        for data in self._parse_authors(data):
            try:
                # Get the current author for that position
                o_ae = self.author_experiments[data['order']]
                # Update the author form for that position with the new data
                self.author_experiments[data['order']] = \
                    Author_Experiment(data=data,
                                      instance=o_ae.instance)
            except IndexError:
                # Or create an author for that position
                o_ae = Author_Experiment(data=data,
                                         instance=models.Author_Experiment())
                self.author_experiments.append(o_ae)

    def save(self, commit=True):
        # remove m2m field before saving
        del self.cleaned_data['authors']

        # fix up experiment form
        if self.instance:
            authors = self.instance.author_experiment_set.all()
            for author in authors:
                author.delete()

        experiment = super(ExperimentForm, self).save(commit)

        authors = []
        author_experiments = []

        for ae in self.author_experiments:
            o_ae = ae.save(commit=commit)
            author_experiments.append(o_ae)

        return self.FullExperiment({'experiment': experiment,
                                    'author_experiments': author_experiments,
                                    'authors': authors})

    def is_valid(self):
        """
        Test the validity of the form, the form may be invalid even if the
        error attribute has no contents. This is because the returnd value
        is dependent on the validity of the nested forms.

        This validity also takes into account forign keys that might be
        dependent on an unsaved model.

        :rtype: bool
        """
        if self.is_bound and bool(self.errors):
            return not bool(self.errors)

        # TODO since this is a compound field, this should merge the errors
        for ae in self.author_experiments:
            for name, error in ae.errors.items():
                if isinstance(ae.fields[name], ModelChoiceField):
                    continue
                if ae.is_bound and bool(ae.errors[name]):
                    return False
        return True

def createSearchDatafileForm(searchQueryType):

    from errors import UnsupportedSearchQueryTypeError
    from tardis.tardis_portal.models import ParameterName

    parameterNames = None

    if searchQueryType in models.Schema.getSubTypes():
        parameterNames = \
            ParameterName.objects.filter(
            schema__namespace__in=models.Schema.getNamespaces(
            models.Schema.DATAFILE, searchQueryType) +
            models.Schema.getNamespaces(models.Schema.DATASET,
            searchQueryType), is_searchable='True')

        fields = {}

        fields['filename'] = forms.CharField(label='Filename',
                max_length=100, required=False)
        fields['type'] = forms.CharField(widget=forms.HiddenInput,
                initial=searchQueryType)

        for parameterName in parameterNames:
            fieldName = parameterName.getUniqueShortName()
            if parameterName.data_type == ParameterName.NUMERIC:
                if parameterName.comparison_type \
                    == ParameterName.RANGE_COMPARISON:
                    fields[fieldName + 'From'] = \
                        forms.DecimalField(label=parameterName.full_name
                            + ' From', required=False)
                    fields[fieldName + 'To'] = \
                        forms.DecimalField(label=parameterName.full_name
                            + ' To', required=False)
                else:
                    # note that we'll also ignore the choices text box entry
                    # even if it's filled if the parameter is of numeric type
                    # TODO: decide if we are to raise an exception if
                    #       parameterName.choices is not empty
                    fields[fieldName] = \
                        forms.DecimalField(label=parameterName.full_name,
                            required=False)
            else:  # parameter is a string
                if parameterName.choices != '':
                    fields[fieldName] = \
                        forms.CharField(label=parameterName.full_name,
                        widget=forms.Select(choices=__getParameterChoices(
                        parameterName.choices)), required=False)
                else:
                    fields[fieldName] = \
                        forms.CharField(label=parameterName.full_name,
                        max_length=255, required=False)

        return type('SearchDatafileForm', (forms.BaseForm, ),
                    {'base_fields': fields})
    else:
        raise UnsupportedSearchQueryTypeError(
            "'%s' search query type is currently unsupported" %
            (searchQueryType, ))

def createSearchExperimentForm():

    from django.forms.extras.widgets import SelectDateWidget
    from tardis.tardis_portal.models import ParameterName

    fields = {}

    fields['title'] = forms.CharField(label='Title',
            max_length=20, required=False)
    fields['description'] = forms.CharField(label='Experiment Description',
            max_length=20, required=False)
    fields['institutionName'] = forms.CharField(label='Institution Name',
            max_length=20, required=False)
    fields['creator'] = forms.CharField(label='Author\'s Name',
            max_length=20, required=False)
    fields['date'] = forms.DateTimeField(label='Experiment Date',
            widget=SelectDateWidget(), required=False)

    fieldsets = [('main fields', {'fields': ['title', 'description', 'institutionName', 'creator', 'date']})]

    schemaAndFieldLists = []

    experimentSchemata = models.Schema.objects.filter(type=models.Schema.EXPERIMENT)
    for schema in experimentSchemata:
        searchableParameterNames = \
            schema.parametername_set.filter(is_searchable=True)
        fieldNames = []
        schemaAndFieldLists.append((schema, fieldNames))
        for parameterName in searchableParameterNames:
            fieldName = parameterName.getUniqueShortName()
            if parameterName.data_type == ParameterName.NUMERIC:
                if parameterName.comparison_type \
                    == ParameterName.RANGE_COMPARISON:
                    fields[fieldName + 'From'] = \
                        forms.DecimalField(label=parameterName.full_name
                            + ' From', required=False)
                    fields[fieldName + 'To'] = \
                        forms.DecimalField(label=parameterName.full_name
                            + ' To', required=False)
                    fieldNames.append(fieldName + 'From')
                    fieldNames.append(fieldName + 'To')
                else:
                    # note that we'll also ignore the choices text box entry
                    # even if it's filled if the parameter is of numeric type
                    # TODO: decide if we are to raise an exception if
                    #       parameterName.choices is not empty
                    fields[fieldName] = \
                        forms.DecimalField(label=parameterName.full_name,
                            required=False)
                    fieldNames.append(fieldName)
            else:  # parameter is a string
                if parameterName.choices != '':
                    fields[fieldName] = \
                        forms.CharField(label=parameterName.full_name,
                        widget=forms.Select(choices=__getParameterChoices(
                        parameterName.choices)), required=False)
                else:
                    fields[fieldName] = \
                        forms.CharField(label=parameterName.full_name,
                        max_length=255, required=False)
                fieldNames.append(fieldName)

    for schema, fieldlist in schemaAndFieldLists:
        name = schema.name if schema.name != None else 'No schema name'
        if fieldlist:
            fieldsets.append((name, {'fields': fieldlist}))

    return type('SearchExperimentForm', (formutils.BetterBaseForm, forms.BaseForm, ),
                    {'base_fields': fields, 'base_fieldsets': fieldsets,
                     'base_row_attrs': {}})

def __getParameterChoices(choicesString):
    """Handle the choices string in this format:
    '(hello:hi how are you), (yes:i am here), (no:joe)'

    Note that this parser is very strict and is not smart enough to handle
    any extra unknown characters that the user might put in the choices
    textbox.

    """

    import string
    import re
    paramChoices = ()

    # we'll always add '-' as the default value for a dropdown menu just
    # incase the user doesn't specify a value they'd like to search for
    paramChoices += (('-', '-'),)
    dropDownEntryPattern = re.compile(r'\((.*):(.*)\)')

    dropDownEntryStrings = string.split(choicesString, ',')
    for dropDownEntry in dropDownEntryStrings:
        dropDownEntry = string.strip(dropDownEntry)
        (key, value) = dropDownEntryPattern.search(dropDownEntry).groups()
        paramChoices += ((str(key), str(value)),)

    return paramChoices

def createSearchDatafileSelectionForm(initial=None):

    supportedDatafileSearches = (('-', 'Datafile'),)
    for key in models.Schema.getSubTypes():
        supportedDatafileSearches += ((key, key.upper()),)

    fields = {}
    fields['type'] = \
        forms.CharField(label='type',
        widget=forms.Select(choices=supportedDatafileSearches),
        required=False, initial=initial)
    fields['type'].widget.attrs['class'] = 'searchdropdown'
    return type('DatafileSelectionForm', (forms.BaseForm, ),
                    {'base_fields': fields})

class NoInput(forms.Widget):

    def render(self, name, value, attrs=None):
        from django.utils.safestring import mark_safe
        return mark_safe(value)

class StaticField(forms.Field):

    widget = NoInput

    def clean(self, value):
        return

def create_parameterset_edit_form(
    parameterset,
    request=None):

    from tardis.tardis_portal.models import ParameterName

    # if POST data to save
    if request:
        from django.utils.datastructures import SortedDict
        fields = SortedDict()

        for key, value in sorted(request.POST.iteritems()):

            x = 1

            stripped_key = key.replace('_s47_', '/')
            stripped_key = stripped_key.rpartition('__')[0]

            parameter_name = ParameterName.objects.get(
                schema=parameterset.schema,
                name=stripped_key)

            units = ""
            if parameter_name.units:
                units = " (" + parameter_name.units + ")"
                # if not valid, spit back as exact
                if parameter_name.isNumeric():
                    fields[key] = \
                        forms.DecimalField(label=parameter_name.full_name + units,
                                           required=False,
                                           initial=value)
                elif parameter_name.isLongString():
                    fields[key] = \
                        forms.CharField(widget=forms.Textarea, label=parameter_name.full_name + units,
                                        max_length=255, required=False,
                                        initial=value)
                else:
                    fields[key] = \
                        forms.CharField(label=parameter_name.full_name + units,
                                        max_length=255, required=False,
                                        initial=value)

        return type('DynamicForm', (forms.BaseForm, ), {'base_fields': fields})

    else:
        from django.utils.datastructures import SortedDict
        fields = SortedDict()
        psm = ParameterSetManager(parameterset=parameterset)

        for dfp in psm.parameters:

            x = 1

            form_id = dfp.name.name + "__" + str(x)

            while form_id in fields:
                x = x + 1
                form_id = dfp.name.name + "__" + str(x)

            units = ""
            if dfp.name.units:
                units = " (" + dfp.name.units + ")"

            form_id = form_id.replace('/', '_s47_')

            if dfp.name.isNumeric():
                fields[form_id] = \
                    forms.DecimalField(label=dfp.name.full_name + units,
                                       required=False,
                                       initial=dfp.numerical_value)
            elif dfp.name.isLongString():
                fields[form_id] = \
                    forms.CharField(widget=forms.Textarea, label=dfp.name.full_name + units,
                                    max_length=255,
                                    required=False,
                                    initial=dfp.string_value)

            else:
                fields[form_id] = \
                    forms.CharField(label=dfp.name.full_name + units,
                                    max_length=255,
                                    required=False,
                                    initial=dfp.string_value)

            if dfp.name.immutable or dfp.name.schema.immutable:
                fields[form_id].widget.attrs['readonly'] = True
                fields[form_id].label = \
                    fields[form_id].label + " (read only)"

        return type('DynamicForm', (forms.BaseForm, ),
                    {'base_fields': fields})

def save_datafile_edit_form(parameterset, request):

    psm = ParameterSetManager(parameterset=parameterset)

    psm.delete_all_params()

    for key, value in sorted(request.POST.iteritems()):
        if value:
            stripped_key = key.replace('_s47_', '/')
            stripped_key = stripped_key.rpartition('__')[0]

            psm.new_param(stripped_key, value)

def create_datafile_add_form(
    schema, parentObject,
    request=None):

    from tardis.tardis_portal.models import ParameterName

    # if POST data to save
    if request:
        from django.utils.datastructures import SortedDict
        fields = SortedDict()

        for key, value in sorted(request.POST.iteritems()):

            x = 1

            stripped_key = key.replace('_s47_', '/')
            stripped_key = stripped_key.rpartition('__')[0]

            parameter_name = ParameterName.objects.get(
                schema__namespace=schema,
                name=stripped_key)

            if parameter_name.immutable == False:
                units = ""
                if parameter_name.units:
                    units = " (" + parameter_name.units + ")"

                # if not valid, spit back as exact
                if parameter_name.isNumeric():
                    fields[key] = \
                        forms.DecimalField(label=parameter_name.full_name + units,
                                           required=False,
                                           initial=value,
                                           )
                elif parameter_name.isLongString():
                    fields[key] = forms.CharField(widget=forms.Textarea, label=parameter_name.full_name + units, max_length=255, required=False, initial=value)
                else:
                    fields[key] = \
                        forms.CharField(label=parameter_name.full_name + units,
                                        max_length=255, required=False,
                                        initial=value,
                                        )

        return type('DynamicForm', (forms.BaseForm, ), {'base_fields': fields})

    else:
        from django.utils.datastructures import SortedDict
        fields = SortedDict()

        parameternames = ParameterName.objects.filter(
            schema__namespace=schema,
            immutable=False).order_by('name')

        for dfp in parameternames:

            x = 1

            form_id = dfp.name + "__" + str(x)

            while form_id in fields:
                x = x + 1
                form_id = dfp.name + "__" + str(x)

            units = ""
            if dfp.units:
                units = " (" + dfp.units + ")"

            form_id = form_id.replace('/', '_s47_')

            if dfp.isNumeric():
                fields[form_id] = \
                forms.DecimalField(label=dfp.full_name + units,
                required=False)
            elif dfp.isLongString():
                fields[form_id] = forms.CharField(label=dfp.full_name + units, widget=forms.Textarea, required=False, max_length=255)
            else:
                fields[form_id] = \
                forms.CharField(label=dfp.full_name + units,
                max_length=255, required=False)

        return type('DynamicForm', (forms.BaseForm, ),
            {'base_fields': fields})

def save_datafile_add_form(schema, parentObject, request):

    psm = ParameterSetManager(schema=schema,
        parentObject=parentObject)

    for key, value in sorted(request.POST.iteritems()):
        if value:
            stripped_key = key.replace('_s47_', '/')
            stripped_key = stripped_key.rpartition('__')[0]

            psm.new_param(stripped_key, value)

class RawSearchForm(SearchForm):

    def search(self):
        query = self.cleaned_data['q']
        # NOTE: end_offset = 1 is just a quick hack way to stop haystack getting lots of search
        # results even though we dont need them. Fix this to properly set rows=0
        sqs = self.searchqueryset.facet('experiment_id_stored').raw_search(query, end_offset=1)
        if self.load_all:
            sqs = sqs.load_all()

        return sqs

class RightsForm(ModelForm):
    """
    Form for changing public access and licence.

    """
    class Meta:
        model = Experiment
        fields = ('public_access', 'license')
        widgets = {
            'license': HiddenInput()
        }

    def clean(self):
        cleaned_data = super(RightsForm, self).clean()
        public_access = cleaned_data.get("public_access")
        license_ = cleaned_data.get("license")

        if license_ is None:
            # Only data which is not distributed can have no explicit licence
            suitable = not \
                Experiment.public_access_implies_distribution(public_access)
        else:
            suitable = license_ in License.get_suitable_licenses(public_access)

        if not suitable:
            raise forms.ValidationError("Selected license it not suitable "+
                                        "for public access level.");

        return cleaned_data

class ManageAccountForm(ModelForm):
    """
    Form for changing account details.

    """
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')


text:
from distutils.core import setup
import py2exe

setup(console=['getLinkTargets.py'],
      windows=['launcher.py'],
      zipfile=None)


text:
// Taken from https://github.com/ryanflorence/async-props. (MIT License)
// Modified to pass location in addition to params and loadContext.

/*global __ASYNC_PROPS__*/
import React from 'react'
import RouterContext from 'react-router/lib/RouterContext'
import computeChangedRoutes from 'react-router/lib/computeChangedRoutes'

// todo: replace with ES6 classes in this file
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
const { array, func, object } = PropTypes;

function eachComponents(components, iterator) {
  for (var i = 0, l = components.length; i < l; i++) {
    if (typeof components[i] === 'object') {
      for (var key in components[i]) {
        iterator(components[i][key], i, key)
      }
    } else {
      iterator(components[i], i)
    }
  }
}

function filterAndFlattenComponents(components) {
  var flattened = []
  eachComponents(components, (Component) => {
    if (Component && Component.loadProps)
      flattened.push(Component)
  })
  return flattened
}

function loadAsyncProps({ components, params, location, loadContext }, cb) {
  // flatten the multi-component routes
  let componentsArray = []
  let propsArray = []
  let needToLoadCounter = components.length
  let hasCalledBack = []

  const maybeFinish = (err) => {
    if ( err ) {
      // error occured, stop executing
      cb(err)
      return
    }

    if (needToLoadCounter === 0)
      cb(null, { propsArray, componentsArray })
  }

  // If there are no components we should resolve directly
  if (needToLoadCounter === 0) {
    return maybeFinish()
  }

  components.forEach((Component, index) => {
    Component.loadProps({ params, location, loadContext }, (error, props) => {
      if (hasCalledBack[index] && needToLoadCounter === 0) {
        // deferred data
        cb(error, {
          propsArray: [ props ],
          componentsArray: [ Component ]
        })
      } else {
        if (!hasCalledBack[index])
          needToLoadCounter--
        propsArray[index] = props
        componentsArray[index] = Component
        hasCalledBack[index] = true
        maybeFinish(error)
      }
    })
  })
}

function lookupPropsForComponent(Component, propsAndComponents) {
  const { componentsArray, propsArray } = propsAndComponents
  var index = componentsArray.indexOf(Component)
  return propsArray[index]
}

function mergePropsAndComponents(current, changes) {
  for (var i = 0, l = changes.propsArray.length; i < l; i++) {
    let Component = changes.componentsArray[i]
    let position = current.componentsArray.indexOf(Component)
    let isNew = position === -1

    if (isNew) {
      current.propsArray.push(changes.propsArray[i])
      current.componentsArray.push(changes.componentsArray[i])
    } else {
      current.propsArray[position] = changes.propsArray[i]
    }
  }
  return current
}

function createElement(Component, props) {
  if (Component.loadProps)
    return <AsyncPropsContainer Component={Component} routerProps={props}/>
  else
    return <Component {...props}/>
}

export function loadPropsOnServer({ components, params }, loadContext, cb) {
  loadAsyncProps({
    components: filterAndFlattenComponents(components),
    params,
    loadContext
  }, (err, propsAndComponents) => {
    if (err) {
      cb(err)
    }
    else {
      const json = JSON.stringify(propsAndComponents.propsArray, null, 2)
      const scriptString = `<script>__ASYNC_PROPS__ = ${json}</script>`
      cb(null, propsAndComponents, scriptString)
    }
  })
}

function hydrate(props) {
  if (typeof __ASYNC_PROPS__ !== 'undefined')
    return {
      propsArray: __ASYNC_PROPS__,
      componentsArray: filterAndFlattenComponents(props.components)
    }
  else
    return null
}

const AsyncPropsContainer = createReactClass({

  propTypes: {
    Component: func.isRequired,
    routerProps: object.isRequired
  },

  contextTypes: {
    asyncProps: object.isRequired
  },

  render() {
    const { Component, routerProps, ...props } = this.props
    const { propsAndComponents, loading, reloadComponent } = this.context.asyncProps
    const asyncProps = lookupPropsForComponent(Component, propsAndComponents)
    const reload = () => reloadComponent(Component)
    return (
      <Component
        {...props}
        {...routerProps}
        {...asyncProps}
        reloadAsyncProps={reload}
        loading={loading}
      />
    )
  }

})

const AsyncProps = createReactClass({

  childContextTypes: {
    asyncProps: object
  },

  propTypes: {
    loadContext: object,
    components: array.isRequired,
    params: object.isRequired,
    location: object.isRequired,
    onError: func.isRequired,
    renderLoading: func.isRequired,

    // server rendering
    propsArray: array,
    componentsArray: array
  },

  getDefaultProps() {
    return {
      onError(err) {
        throw err
      },

      renderLoading() {
        return null
      },

      render(props) {
        return <RouterContext {...props} createElement={createElement}/>
      }
    }
  },

  getInitialState() {
    const { propsArray, componentsArray } = this.props
    const isServerRender = propsArray && componentsArray
    return {
      loading: false,
      prevProps: null,
      propsAndComponents: isServerRender ?
        { propsArray, componentsArray } :
        hydrate(this.props)
    }
  },

  getChildContext() {
    const { loading, propsAndComponents } = this.state
    return {
      asyncProps: {
        loading,
        propsAndComponents,
        reloadComponent: (Component) => {
          this.reloadComponent(Component)
        }
      }
    }
  },

  componentDidMount() {
    const wasHydrated = this.state.propsAndComponents !== null
    if (!wasHydrated) {
      const { components, params, location } = this.props
      this.loadAsyncProps(components, params, location)
    }
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.location === this.props.location)
      return

    const { enterRoutes } = computeChangedRoutes(
      { routes: this.props.routes, params: this.props.params },
      { routes: nextProps.routes, params: nextProps.params }
    )

    const indexDiff = nextProps.components.length - enterRoutes.length
    const components = []
    for (let i = 0, l = enterRoutes.length; i < l; i++)
      components.push(nextProps.components[indexDiff + i])

    this.loadAsyncProps(
      filterAndFlattenComponents(components),
      nextProps.params,
      nextProps.location
    )
  },

  handleError(cb) {
    return (err, ...args) => {
      if (err && this.props.onError)
        this.props.onError(err)
      else
        cb(null, ...args)
    }
  },

  componentWillUnmount() {
    this._unmounted = true
  },

  loadAsyncProps(components, params, location, options) {
    const { loadContext } = this.props
    this.setState({
      loading: true,
      prevProps: this.props
    }, () => {
      loadAsyncProps({
        components: filterAndFlattenComponents(components),
        params,
        location,
        loadContext
      }, this.handleError((err, propsAndComponents) => {
        const reloading = options && options.reload
        const didNotChangeRoutes = this.props.location === location
        // FIXME: next line has potential (rare) race conditions I think. If
        // somebody calls reloadAsyncProps, changes location, then changes
        // location again before its done and state gets out of whack (Rx folks
        // are like "LOL FLAT MAP LATEST NEWB"). Will revisit later.
        if ((reloading || didNotChangeRoutes) && !this._unmounted) {
          if (this.state.propsAndComponents) {
            propsAndComponents = mergePropsAndComponents(
              this.state.propsAndComponents,
              propsAndComponents
            )
          }
          this.setState({
            loading: false,
            propsAndComponents,
            prevProps: null
          })
        }
      }))
    })
  },

  reloadComponent(Component) {
    const { params } = this.props
    this.loadAsyncProps([ Component ], params, null, { reload: true })
  },

  render() {
    const { propsAndComponents } = this.state
    if (!propsAndComponents) {
      return this.props.renderLoading()
    }
    else {
      const props = this.state.loading ? this.state.prevProps : this.props
      return this.props.render(props)
    }
  }

})

export default AsyncProps


text:
package org.jimmutable.core.exceptions;

/**
 * A RuntimeException with the semantic meaning "hey! you just tried to modify
 * and object that is immutable (i.e. after it has been completed/frozen)"
 *
 * @author jim.kane
 *
 */
@SuppressWarnings("serial")
public class ImmutableException extends RuntimeException
{
	public ImmutableException()
	{
		super();
	}

	public ImmutableException(String message)
	{
		super(message);
	}
}


text:
/* $Id: list.h,v 1.6 2006/10/31 06:25:28 gmm Exp $ */
/*-
 * Copyright (C) 2005-2011 HighPoint Technologies, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD$
 */
#include <dev/hptnr/hptnr_config.h>
#ifndef _HPT_LIST_H_
#define _HPT_LIST_H_

#ifndef _LINUX_LIST_H

#ifndef HPT_INLINE
#define HPT_INLINE __inline
#endif

struct list_head {
	struct list_head *next, *prev;
};

#define INIT_LIST_HEAD(ptr) do { (ptr)->next = (ptr); (ptr)->prev = (ptr); } while (0)

static HPT_INLINE void __list_add(struct list_head * _new, struct list_head * prev, struct list_head * next)
{
	next->prev = _new;
	_new->next = next;
	_new->prev = prev;
	prev->next = _new;
}

static HPT_INLINE void list_add(struct list_head *_new, struct list_head *head)
{
	__list_add(_new, head, head->next);
}

static HPT_INLINE void list_add_tail(struct list_head *_new, struct list_head *head)
{
	__list_add(_new, head->prev, head);
}

static HPT_INLINE void __list_del(struct list_head * prev, struct list_head * next)
{
	next->prev = prev;
	prev->next = next;
}

static HPT_INLINE void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
}

static HPT_INLINE void list_del_init(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	INIT_LIST_HEAD(entry);
}

static HPT_INLINE int list_empty(struct list_head *head)
{
	HPT_ASSERT(!(head->next==head && head->prev!=head));
	return head->next == head;
}

static HPT_INLINE void __list_splice(struct list_head *list,
				 struct list_head *head)
{
	struct list_head *first = list->next;
	struct list_head *last = list->prev;
	struct list_head *at = head->next;

	first->prev = head;
	head->next = first;

	last->next = at;
	at->prev = last;
}

static HPT_INLINE void list_splice(struct list_head *list, struct list_head *head)
{
	if (!list_empty(list))
		__list_splice(list, head);
}

static HPT_INLINE void list_splice_init(struct list_head *list, struct list_head *head)
{
	if (!list_empty(list)) {
		__list_splice(list, head);
		INIT_LIST_HEAD(list);
	}
}

#define list_entry(ptr, type, member) \
	((type *)((char *)(ptr)-(HPT_UPTR)(&((type *)0)->member)))

#define list_for_each(pos, head) \
	for (pos = (head)->next; pos != (head); pos = pos->next)

#define list_for_each_safe(pos, n, head) \
	for (pos = (head)->next, n = pos->next; pos != (head); \
		pos = n, n = pos->next)

#define get_first_item(attached, type, member) \
	((type *)((char *)((attached)->next)-(HPT_UPTR)(&((type *)0)->member)))

#endif

#endif


text:
package org.shaolin.bmdp.runtime;

import org.junit.BeforeClass;
import org.shaolin.bmdp.i18n.LocaleContext;
import org.shaolin.bmdp.runtime.spi.IServerServiceManager;
import org.shaolin.bmdp.runtime.spi.IAppServiceManager.Env;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Profile;

/**
 * The test root of spring boot context.
 *
 * @author wushaol
 *
 */
@SpringBootTest(classes=SpringBootTestRoot.class)
@EnableAutoConfiguration
@ComponentScan(basePackages = {"org.shaolin.*"})
@Profile("default")
public class SpringBootTestRoot {

	//extends SpringBootServletInitializer
	//@Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootTestRoot.class);
    }

	@Bean
    public CommandLineRunner commandLineRunner(final ApplicationContext ctx) {
        return args->{
	        	LocaleContext.createLocaleContext("default");
	        	Registry.getInstance().initRegistry();
	    		IServerServiceManager.setSpringContext(ctx);
	    		IServerServiceManager.INSTANCE.setAppClassLoader(this.getClass().getClassLoader());
	    		IServerServiceManager.INSTANCE.setRunningEnv(Env.Testing);
//	    		if (isSkipScanEntities()) {
//	        		return;
//	        	}
//
//	    		IEntityManager entityManager = IServerServiceManager.INSTANCE.getEntityManager();
//	    		((EntityManager)entityManager).initRuntime();
//	    		IServerServiceManager.INSTANCE.configureLifeCycleProviders();
        };
    }

	public boolean isSkipScanEntities() {
		return false;
	}

	@BeforeClass
	public static void setup() {
		if (IServerServiceManager.INSTANCE != null && IServerServiceManager.INSTANCE.getSpringContext() != null) {
			return;
		}

		SpringApplication app = new SpringApplication(SpringBootTestRoot.class);
	    	app.setWebEnvironment(false);
	    	app.setBannerMode(Banner.Mode.OFF);
        app.run(new String[0]);
	}

	@BeforeClass
	public static void teardown() {

	}
}


text:
package internal.msm.spikes.dw.server;

import com.google.common.base.Optional;

import static java.lang.String.format;

/**
 *
 * @author Paul Gilligan <Paul.Gilligan@moneysupermarket.com>
 */
public class HelloWorldTemplate {

    private final String content;
    private final String defaultName;

    public HelloWorldTemplate(String content, String defaultName) {
        this.content = content;
        this.defaultName = defaultName;
    }

    public String render(Optional<String> name) {
        return format(content, name.or(defaultName));
    }

}


text:
require "json"
require "socket"
require "time"

module Sano
  OK = 'OK'
  WARNING = 'WARNING'
  CRITICAL = 'CRITICAL'

  LEVELS = [ OK, WARNING, CRITICAL]

  class Page
    attr_accessor :application, :status, :system

    def initialize
      @details = []
      @datasources = []
      @application = Application.new
      @system = SystemInfo.new
      @properties = {}
    end

    def add_property(key, value)
      @properties[key] = value
    end

    def add_datasource(ds)
      @datasources << ds
    end

    def add_detail(detail)
      @details << detail

      calculate_status
      true
    end

    def to_json
      json_hash = {
        'application' => @application.to_h.merge({'statusDetails' => {}}),
        'system' => @system.to_h,
        'datasources' => [],
        'properties' => @properties
      }

      @details.each do |d|
        json_hash['application']['statusDetails'][d.name] = d.to_h
      end

      @datasources.each do |d|
        json_hash['datasources'] << d.to_h
      end

      JSON.dump(json_hash)
    end

    protected

    def calculate_status
      tmp_status = OK

      @details.each do |d|
        if LEVELS.index(d.status) > LEVELS.index(tmp_status)
          tmp_status = d.status
        end
      end

      @application.status = tmp_status
      @status = tmp_status
    end
  end

  class Application < Struct.new(:name, :status, :version)
    def to_h
      {
        'name' => name,
        'status' => status,
        'version' => (version || "UNSET")
      }
    end
  end

  class SystemInfo
    attr_accessor :hostname, :system_time

    def initialize
      @hostname = Socket.gethostbyname(Socket.gethostname).first
      @system_time = Time.now
    end

    def to_h
      {
        'hostname' => @hostname,
        'systemTime' => @system_time.iso8601
      }
    end
  end

  class Detail < Struct.new(:name, :status, :message, :link)
    attr_accessor :properties

    def initialize
      status = OK
      @properties = {}
    end

    def self.create(&block)
      d = Detail.new
      yield(d) if block_given?

      d
    end

    def to_h
      {
        'name' => name,
        'status' => status,
        'properties' => properties,
        'message' => message,
        'uri' => link
      }
    end
  end

  class Datasource
    attr_accessor :name, :type, :properties, :hosts

    def initialize(name, type, hosts = [], properties = {})
      @name = name
      @type = type
      @hosts = hosts
      @properties = properties
    end

    def self.create(&block)
      datasource = Datasource.new("unnamed", "unknown")

      yield(datasource) if block_given?

      datasource
    end

    def to_h
      {
        'name' => @name,
        'type' =>  @type,
        'hosts' => @hosts,
        'properties' => @properties
      }
    end
  end
end


text:
from typing import Dict, Iterable

from systemds.operator import OperationNode, Matrix, Frame, List, MultiReturn, Scalar
from systemds.script_building.dag import OutputType
from systemds.utils.consts import VALID_INPUT_TYPES

def xdummy1(X: Matrix):

    params_dict = {'X': X}
    return Matrix(X.sds_context,
        'xdummy1',
        named_input_nodes=params_dict)


text:
title: "Icyigisho"
date: 12/12/2022
---

### Turacyari gukora aya migisho
Muze kugaruka nyuma, Murakoze kwihangana.


text:
using System;
using InAudioSystem.ExtensionMethods;
using InAudioSystem.Internal;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

namespace InAudioSystem.InAudioEditor
{

    public static class NodeWorker
    {
        public static bool IsChildOf<T>(T node, T potentialChild) where T : Object, InITreeNode<T>
        {
            if (node == potentialChild)
                return true;

            for (int i = 0; i < node._getChildren.Count; ++i)
            {
                bool isChild = IsChildOf(node._getChildren[i], potentialChild);
                if (isChild)
                    return true;
            }
            return false;
        }

        public static bool IsParentOf<T>(T baseNode, T potentialParent) where T : Object, InITreeNode<T>
        {
            if (baseNode == potentialParent)
                return true;

            if (baseNode._getParent != null)
                return IsParentOf(baseNode._getParent, potentialParent);

            return false;
        }

        public static void RemoveFromParent<T>(T node) where T : Object, InITreeNode<T>
        {
            node._getParent._getChildren.Remove(node);
        }

        public static void RemoveNullChildren<T>(T node) where T : Object, InITreeNode<T>
        {
            var children = node._getChildren;
            for (int i = 0; i < children.Count; ++i)
            {
                if (children[i] == null)
                {
                    children.RemoveAt(i);
                }
            }
        }

        //public static void AssignParent<T>(T node, T newParent) where T : Object, ITreeNode<T>
        //{
        //    if (node != null && newParent != null)
        //    {
        //        newParent.GetChildren.Add(node);
        //        node.GetParent = newParent;
        //    }
        //}

        public static void ReasignNodeParent<T>(T current, T newParent) where T : Object, InITreeNode<T>
        {
            RemoveFromParent(current);
            current.AssignParent(newParent);
        }

        public static void ReasignNodeParent(InAudioNode current, InAudioNode newParent)
        {
            if (current._parent._type == AudioNodeType.Random)
            {
                //Remove self from parent random

                int currentIndexInParent = current._parent._children.IndexOf(current);
                (current._parent._nodeData as RandomData).weights.RemoveAt(currentIndexInParent);
            }
            RemoveFromParent(current);
            current.AssignParent(newParent);
            if (newParent._type == AudioNodeType.Random)
            {
                (newParent._nodeData as RandomData).weights.Add(50);
            }

        }

        public static void MoveNodeOneUp<T>(T node) where T : Object, InITreeNode<T>
        {

            if (node is InAudioNode)//As parent could be a random one, it needs to record this first
            {
                InUndoHelper.RecordObject(new Object[] { node._getParent, (node._getParent as InAudioNode)._nodeData },
                    "Undo Reorder Of " + node.GetName);
            }
            else
            {
                InUndoHelper.RecordObject(new Object[] { node._getParent }, "Undo Reorder Of " + node.GetName);
            }

            var children = node._getParent._getChildren;
            var index = children.IndexOf(node);
            if (index != 0 && children.Count > 0)
            {
                //TODO Remove hack
                if (node.GetType() == typeof(InAudioNode))
                {
                    var audioNode = node as InAudioNode;
                    if (audioNode._parent._type == AudioNodeType.Random)
                    {
                        (audioNode._parent._nodeData as RandomData).weights.SwapAtIndexes(index, index - 1);
                    }
                }
                children.SwapAtIndexes(index, index - 1);
            }
        }

        public static void MoveNodeOneDown<T>(T node) where T : Object, InITreeNode<T>
        {

            if (node is InAudioNode)
            {
                InUndoHelper.RecordObject(new Object[] { node._getParent, (node._getParent as InAudioNode)._nodeData },
                    "Undo Reorder Of " + node.GetName);
            }
            else
            {
                InUndoHelper.RecordObject(new Object[] { node._getParent }, "Undo Reorder Of " + node.GetName);
            }

            var children = node._getParent._getChildren;
            var index = children.IndexOf(node);
            if (children.Count > 0 && index != children.Count - 1)
            {
                //TODO Remove hack
                if (node.GetType() == typeof(InAudioNode))
                {
                    var audioNode = node as InAudioNode;
                    if (audioNode._parent._type == AudioNodeType.Random)
                    {
                        (audioNode._parent._nodeData as RandomData).weights.SwapAtIndexes(index, index + 1);
                    }
                }
                children.SwapAtIndexes(index, index + 1);
            }
        }

        public static void AssignToNodes<T>(T node, Action<T> assignFunc) where T : Component, InITreeNode<T>
        {
            assignFunc(node);
            for (int i = 0; i < node._getChildren.Count; ++i)
            {
                AssignToNodes(node._getChildren[i], assignFunc);
            }
        }

        public static T DuplicateHierarchy<T>(T toCopy, Action<T, T> elementAction = null) where T : Component, InITreeNode<T>
        {
            return CopyHierarchy(toCopy, toCopy._getParent, toCopy.gameObject, elementAction);
        }

        public static T DuplicateHierarchy<T>(T toCopy, T newParent, GameObject targetGO, Action<T, T> elementAction = null) where T : Component, InITreeNode<T>
        {
            return CopyHierarchy(toCopy, newParent, targetGO, elementAction);
        }

        private static T CopyHierarchy<T>(T toCopy, T parent, GameObject targetGO, Action<T, T> elementAction) where T : Component, InITreeNode<T>
        {
            T newNode = CopyComponent(toCopy, targetGO);
            newNode.AssignParent(parent);
            newNode._ID = GUIDCreator.Create();

            if (elementAction != null)
                elementAction(toCopy, newNode);

            int childrenCount = newNode._getChildren.Count;
            for (int i = 0; i < childrenCount; i++)
            {
                CopyHierarchy(newNode._getChildren[i], newNode, targetGO, elementAction);
            }
            newNode._getChildren.RemoveRange(0, childrenCount);
            return newNode;
        }

        public static T CopyComponent<T>(T toCopy) where T : Component
        {
            return CopyComponent(toCopy, toCopy.gameObject);
        }

        public static T CopyComponent<T>(T toCopy, GameObject targetGO) where T : Component
        {
            T newComp = targetGO.AddComponentUndo(toCopy.GetType()) as T;
            EditorUtility.CopySerialized(toCopy, newComp);

            return newComp;
        }
    }
}


text:
package cl.ml.ceppi.core.model.estado;

public enum Estado {

	ACTIVO, INACTIVO

}