text:
var chain= require('frontle-chain');
var fs= require('fs');
var path= require('path');
var expect= require('chai').expect;
var clearRequire = require('clear-require');

var responseClass= function () {
	this.res={};
}

responseClass.prototype.status = function(status) {
	this.res.status=status;
	return this;
};

responseClass.prototype.json = function(json) {
	this.res.json=json;
	return this;
};

responseClass.prototype.value = function() {
	return this.res;
};

describe('Testing core.acltoken',function () {

	after(function (done) {
		fs.unlinkSync(path.resolve('./config/acl.js'));
		fs.unlinkSync(path.resolve('./config/token.js'));
		done();
	});

	it('Should not pass through as non authenticated if acl says not ok',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		chain({
			headers:{},
			options:{action:'update',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
			expect(res.value()).to.have.property('status',401);
			expect(res.value()).to.have.property('json').to.have.property('code',4302);
			expect(res.value()).to.have.property('json').to.have.property('msg','Unauthorized Access');
			done();
		},function (ctx,next) {

		}]);
	});

	it('Should not pass through as non authenticated if acl does not have the property for the action under the same controller',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={not_authenticated:{User:{create:true}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		chain({
			headers:{},
			options:{action:'update',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
			expect(res.value()).to.have.property('status',401);
			expect(res.value()).to.have.property('json').to.have.property('code',4302);
			expect(res.value()).to.have.property('json').to.have.property('msg','Unauthorized Access');
			done();
		},function (ctx,next) {

		}]);
	});

	it('Should pass through as non authenticated if acl has a property for the action under the controller',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{not_authenticated:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		chain({
			headers:{},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
			// console.log(res);
		},function (ctx,next) {
			done();
		}]);
	});

	it('Should not pass through if token provided is malformed',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{authenticated:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		chain({
			headers:{authorization:'Bearer not_a_token'},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
			expect(res.value()).to.have.property('status',401);
			expect(res.value()).to.have.property('json').to.have.property('code',4300);
			expect(res.value()).to.have.property('json').to.have.property('msg','Malformed token supplied');
			done();
		},function (ctx,next) {
		}]);
	});

	it('Should not pass through if token provided is okay but acl does not exist',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{manager:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		var tokenLib=require('../../app/token');

		chain({
			headers:{authorization:'Bearer '+tokenLib.create('2',{auth:'admin'})},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
			expect(res.value()).to.have.property('status',401);
			expect(res.value()).to.have.property('json').to.have.property('code',4301);
			expect(res.value()).to.have.property('json').to.have.property('msg','Unauthorized Access');
			done();
		},function (ctx,next) {
		}]);
	});

	it('Should pass through if token provided is okay and acl exist',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{admin:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		var tokenLib=require('../../app/token');

		chain({
			headers:{authorization:'Bearer '+tokenLib.create('2',{auth:'admin'})},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
		},function (ctx,next) {
			expect(ctx).to.have.property('user').to.have.property('id','2');
			expect(ctx).to.have.property('user').to.have.property('auth','admin');
			done();
		}]);
	});

	it('Should have req.user and req.user.getUser in all req chain',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{not_authenticated:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');

		chain({
			headers:{},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
		},function (ctx,next) {
			expect(ctx).to.have.property('user').to.have.property('getUser');
			done();
		}]);
	});

	it('Should have req.user.getUser should return the not_authenticated user',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{not_authenticated:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');

		chain({
			headers:{},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
		},function (ctx,next) {
			expect(ctx).to.have.property('user').to.have.property('getUser');
			expect(ctx.user.getUser()).to.be.equal('not_authenticated');
			done();
		}]);
	});

	it('Should have req.user.getUser should return the authenticated user',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{authenticated:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		var tokenLib=require('../../app/token');

		chain({
			headers:{authorization:'Bearer '+tokenLib.create('2')},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
		},function (ctx,next) {
			expect(ctx).to.have.property('user').to.have.property('getUser');
			expect(ctx.user.getUser()).to.be.equal('authenticated');
			done();
		}]);
	});

	it('Should have req.user.getUser should return the named admin user',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={routes:{admin:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		var tokenLib=require('../../app/token');

		chain({
			headers:{authorization:'Bearer '+tokenLib.create('2',{auth:'admin'})},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
		},function (ctx,next) {
			expect(ctx).to.have.property('user').to.have.property('getUser');
			expect(ctx.user.getUser()).to.be.equal('admin');
			done();
		}]);
	});

	it('Should have req.user.getUser should return the default not_authenticated user',function (done) {

		clearRequire.all();
		fs.writeFileSync(path.resolve('./config/acl.js'),'module.exports={not_authenticated_default:"public",routes:{public:{User:{create:true}}}}','utf8');
		fs.writeFileSync(path.resolve('./config/token.js'),'module.exports={secret:\'my secret\'}','utf8');
		var token= require('../../app/core/middlewares/token');
		var tokenLib=require('../../app/token');

		chain({
			headers:{},
			options:{action:'create',controller:'User'}
		},[function (ctx,next) {
			var responseInst= new responseClass();

			var res=token()(ctx,responseInst,next);
		},function (ctx,next) {
			expect(ctx).to.have.property('user').to.have.property('getUser');
			expect(ctx.user.getUser()).to.be.equal('public');
			done();
		}]);
	});
})


text:
/**
 * Module dependencies
 */

var _ = require('lodash'),
    utils = require('./utils'),
    hasOwnProperty = utils.object.hasOwnProperty;

/**
 * Expose JoinTables
 */

module.exports = JoinTables;

/**
 * Insert Join/Junction Tables where needed whenever two collections
 * point to each other. Also replaces the references to point to the new join table.
 *
 * @param {Object} collections
 * @return {Object}
 * @api private
 */

function JoinTables(collections) {
  var self = this;

  collections = collections || {};
  this.collections = _.cloneDeep(collections);
  this.tables = {};

  // Build Up Join Tables
  for(var collection in collections) {
    var joinTables = this.buildJoins(collection);
    this.uniqueTables(joinTables);

    // Mark hasManyThrough tables as junction tables with select all set to true
    this.markCustomJoinTables(collection);
  }

  // Update Collection Attributes to point to the join table
  this.linkAttributes();

  // Remove properties added just for unqueness
  Object.keys(this.tables).forEach(function(table) {
    delete self.tables[table].joinedAttributes;
  });

  return _.extend(this.collections, this.tables);
}

/**
 * Build A Set of Join Tables
 *
 * @param {String} collection
 * @api private
 * @return {Array}
 */

JoinTables.prototype.buildJoins = function(collection) {
  var attributes = this.collections[collection].attributes,
      collectionAttributes = this.mapCollections(attributes),
      tables = [];

  // If there are no collection attributes return an empty array
  if(Object.keys(collectionAttributes).length === 0) return [];

  // For each collection attribute, inspect it to build up a join table if needed.
  for(var attribute in collectionAttributes) {

    // Check the collection it references to see if this is a one-to-many or many-to-many
    // relationship. If it's a one-to-many we don't need to build up a join table.
    var attr = collectionAttributes[attribute];

    // Ensure the attribute has a `via` property
    if(!hasOwnProperty(attr, 'via')) {
      throw new Error('Collection ' + collection + ' has an association attribute that is missing a '+
        '`via` property. Any associations with a `collection` attribute must specify a `via` option ' +
        'that points to another attribute. Update the attribute: ' + attribute + ' and add a `via` property');
    }

    // Check if this is a hasManyThrough attribute, if so a join table doesn't need to be created
    if(hasOwnProperty(attr, 'through')) continue;

    // Normalize `collection` property name to lowercased version
    attr.collection = attr.collection.toLowerCase();

    var child = this.collections[attr.collection];

    // Ensure the `via` exists on the child.
    if(!hasOwnProperty(child.attributes, attr.via)) {
      throw new Error('Collection ' + collection + ' has a `via` attribute which is missing from the ' +
        'collection ' + attr.collection);
    }

    // If the associated attribute is a foreign key, ignore it
    if(hasOwnProperty(child.attributes[attr.via], 'foreignKey')) continue;

    // Build up an object that can be used to build a join table
    var tableAttributes = {
      column_one: {
        collection: collection.toLowerCase(),
        attribute: attribute,
        via: attr.via
      },

      column_two: {
        collection: attr.collection,
        attribute: attr.via,
        via: attribute
      }
    };

    // Build join tables
    tables = tables.concat(this.buildTable(tableAttributes));
  }

  return tables;
};

/**
 * Find Has Many attributes for a given set of attributes.
 *
 * @param {Object} attributes
 * @return {Object}
 * @api private
 */

JoinTables.prototype.mapCollections = function(attributes) {
  var collectionAttributes = {};

  for(var attribute in attributes) {
    if(!hasOwnProperty(attributes[attribute], 'collection')) continue;
    collectionAttributes[attribute] = attributes[attribute];
  }

  return collectionAttributes;
};

/**
 * Build Collection for a single join
 *
 * @apram {Object} columns
 * @return {Object}
 * @api private
 */

JoinTables.prototype.buildTable = function(columns) {
  var table = {};

  var c1 = columns.column_one;
  var c2 = columns.column_two;

  table.identity = this.buildCollectionName(columns).toLowerCase();
  table.tableName = table.identity;
  table.tables = [c1.collection, c2.collection];
  table.joinedAttributes = [];
  table.junctionTable = true;

  // Look for a dominant collection property so the join table can be created on the correct connection.
  table.connection = this.findDominantConnection(columns);
  if(!table.connection) {
    var err = "A 'dominant' property was not supplied for the two collections in a many-to-many relationship. " +
        "One side of the relationship between '" + c1.collection + "' and '" + c2.collection + "' needs a " +
        "'domiant: true' flag set so a join table can be created on the correct connection.";

    throw new Error(err);
  }

  // Add each foreign key as an attribute
  table.attributes = {
    id: {
      primaryKey: true,
      autoIncrement: true,
      type: 'integer'
    }
  };

  table.attributes[c1.collection + '_' + c1.attribute] = this.buildForeignKey(c1, c2);
  table.attributes[c2.collection + '_' + c2.attribute] = this.buildForeignKey(c2, c1);

  table.joinedAttributes.push(c1.collection + '_' + c1.attribute);
  table.joinedAttributes.push(c2.collection + '_' + c2.attribute);

  return table;
};

/**
 * Build a collection name by combining two collection and attribute names.
 *
 * @param {Object} columns
 * @return {String}
 * @api private
 */

JoinTables.prototype.buildCollectionName = function(columns) {

  var c1 = columns.column_one;
  var c2 = columns.column_two;

  if(c1.collection < c2.collection) {
    return c1.collection + '_' + c1.attribute + '__' + c2.collection + '_' + c2.attribute;
  }

  return c2.collection + '_' + c2.attribute + '__' + c1.collection + '_' + c1.attribute;
};

/**
 * Find the dominant collection.
 *
 * @param {Object} columns
 * @return {String}
 * @api private
 */

JoinTables.prototype.findDominantConnection = function(columns) {

  var c1 = this.collections[columns.column_one.collection];
  var c2 = this.collections[columns.column_two.collection];

  // Don't require a dominant collection on self-referencing associations
  if(columns.column_one.collection === columns.column_two.collection) {
    return c1.connection;
  }

  var dominantCollection = this.searchForAttribute(columns.column_one.collection, 'dominant');
  if(dominantCollection) return c1.connection;

  dominantCollection = this.searchForAttribute(columns.column_two.collection, 'dominant');
  if(dominantCollection) return c2.connection;

  return false;
};

/**
 * Search Attributes for an attribute property.
 *
 * @param {String} collectionName
 * @param {String} attributeName
 * @return {String}
 * @api private
 */

JoinTables.prototype.searchForAttribute = function(collectionName, attributeName) {
  var collection = this.collections[collectionName],
      matching;

  Object.keys(collection.attributes).forEach(function(key) {
    var properties = collection.attributes[key];
    if(hasOwnProperty(properties, attributeName)) matching = key;
  });

  return matching;
};

/**
 * Build a Foreign Key value for an attribute in the join collection
 *
 * @param {Object} column_one
 * @param {Object} column_two
 * @return {Object}
 * @api private
 */

JoinTables.prototype.buildForeignKey = function(column_one, column_two) {
  var primaryKey = this.findPrimaryKey(column_one.collection);
  var columnName = (column_one.collection + '_' + column_one.attribute);
  var viaName = column_two.collection + '_' + column_one.via;

  return {
    columnName: columnName,
    type: primaryKey.attributes.type,
    foreignKey: true,
    references: column_one.collection,
    on: primaryKey.name,
    via: viaName,
    groupKey: column_one.collection
  };
};

/**
 * Filter Out Duplicate Join Tables
 *
 * @param {Array} tables
 * @api private
 */

JoinTables.prototype.uniqueTables = function(tables) {
  var self = this;

  tables.forEach(function(table) {
    var add = true;

    // Check if any tables are already joining these attributes together
    Object.keys(self.tables).forEach(function(tableName) {
      var currentTable = self.tables[tableName];
      if(currentTable.joinedAttributes.indexOf(table.joinedAttributes[0]) === -1) return;
      if(currentTable.joinedAttributes.indexOf(table.joinedAttributes[1]) === -1) return;

      add = false;
    });

    if(hasOwnProperty(self.tables, table.identity)) return;
    if(add) self.tables[table.identity] = table;
  });
};

/**
 * Find a collection's primary key attribute
 *
 * @param {String} collection
 * @return {Object}
 * @api private
 */

JoinTables.prototype.findPrimaryKey = function(collection) {
  if(!this.collections[collection]) {
    throw new Error('Trying to access a collection ' + collection + ' that is not defined.');
  }
  if(!this.collections[collection].attributes) {
    throw new Error('Collection, ' + collection + ', has no attributes defined.');
  }

  var primaryKey = null;

  for(var key in this.collections[collection].attributes) {
    var attribute = this.collections[collection].attributes[key];

    if(!hasOwnProperty(attribute, 'primaryKey')) continue;

    primaryKey = {
      name: key,
      attributes: attribute
    };
  }

  if(!primaryKey) {
    var error = 'Trying to create an association on a model that doesn\'t have a Primary Key.';
    throw new Error(error);
  }

  return primaryKey;
};

/**
 * Update Collection Attributes to point to the join table instead of the other collection
 *
 * @api private
 */

JoinTables.prototype.linkAttributes = function() {
  for(var collection in this.collections) {
    var attributes = this.collections[collection].attributes;
    this.updateAttribute(collection, attributes);
  }
};

/**
 * Update An Attribute
 *
 * @param {String} collection
 * @param {Object} attributes
 * @api private
 */

JoinTables.prototype.updateAttribute = function(collection, attributes) {

  for(var attribute in attributes) {
    if(!hasOwnProperty(attributes[attribute], 'collection')) continue;

    var attr = attributes[attribute];
    var parent = collection;
    var child = attr.collection;
    var via = attr.via;

    var joined = this.findJoinTable(parent, child, via);

    if(!joined.join) continue;

    this.collections[collection].attributes[attribute] = {
      collection: joined.table.identity,
      references: joined.table.identity,
      on: joined.table.attributes[collection + '_' + attribute].columnName
    };
  }
};

/**
 * Mark Custom Join Tables as a Junction Table
 *
 * If a collection has an attribute with a `through` property, lookup
 * the collection it points to and mark it as a `junctionTable`.
 *
 * @param {String} collection
 * @api private
 */

JoinTables.prototype.markCustomJoinTables = function(collection) {
  var attributes = this.collections[collection].attributes;

  for(var attribute in attributes) {
    if(!hasOwnProperty(attributes[attribute], 'through')) continue;

    var linkedCollection = attributes[attribute].through;
    this.collections[linkedCollection].junctionTable = true;

    // Build up proper reference on the attribute
    attributes[attribute].collection = linkedCollection;
    attributes[attribute].references = linkedCollection;

    // Find Reference Key
    var reference = this.findReference(collection, linkedCollection);
    attributes[attribute].on = reference;

    delete attributes[attribute].through;
  }
};

/**
 * Find Reference attribute name in a set of attributes
 *
 * @param {String} parent
 * @param {String} collection
 * @return {String}
 * @api private
 */

JoinTables.prototype.findReference = function(parent, collection) {
  var attributes = this.collections[collection].attributes,
      reference;

  for(var attribute in attributes) {
    if(!hasOwnProperty(attributes[attribute], 'foreignKey')) continue;
    if(!hasOwnProperty(attributes[attribute], 'references')) continue;
    if(attributes[attribute].references !== parent) continue;

    reference = attributes[attribute].columnName || attribute;
    break;
  }

  return reference;
};

/**
 * Search for a matching join table
 *
 * @param {String} parent
 * @param {String} child
 * @param {String} via
 * @return {Object}
 * @api private
 */

JoinTables.prototype.findJoinTable = function(parent, child, via) {
  var join = false,
      tableCollection;

  for(var table in this.tables) {
    var tables = this.tables[table].tables;

    if(tables.indexOf(parent) < 0) continue;
    if(tables.indexOf(child) < 0) continue;

    var column = child + '_' + via;

    if(!hasOwnProperty(this.tables[table].attributes, column)) continue;

    join = true;
    tableCollection = this.tables[table];
    break;
  }

  return { join: join, table: tableCollection };
};

redpajama_set_name: RedPajamaGithub


text:
package hydrograph.ui.propertywindow.widgets.customwidgets.operational;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import hydrograph.ui.common.util.Constants;
import hydrograph.ui.common.util.CustomColorRegistry;
import hydrograph.ui.common.util.ImagePathConstant;
import hydrograph.ui.common.util.OSValidator;
import hydrograph.ui.datastructure.expression.ExpressionEditorData;
import hydrograph.ui.datastructure.property.ComponentsOutputSchema;
import hydrograph.ui.datastructure.property.FixedWidthGridRow;
import hydrograph.ui.datastructure.property.mapping.MappingSheetRow;
import hydrograph.ui.expression.editor.enums.DataTypes;
import hydrograph.ui.expression.editor.launcher.LaunchExpressionEditor;
import hydrograph.ui.graph.model.Component;
import hydrograph.ui.graph.model.Link;
import hydrograph.ui.graph.schema.propagation.SchemaPropagation;
import hydrograph.ui.propertywindow.messages.Messages;
import hydrograph.ui.propertywindow.widgets.customwidgets.config.OperationClassConfig;
import hydrograph.ui.propertywindow.widgets.customwidgets.config.WidgetConfig;
import hydrograph.ui.propertywindow.widgets.listeners.ELTVerifyTextListener;
import hydrograph.ui.propertywindow.widgets.listeners.ListenerHelper;
import hydrograph.ui.propertywindow.widgets.listeners.ListenerHelper.HelperType;
import hydrograph.ui.propertywindow.widgets.utility.WidgetUtility;

/**
 * @author Bitwise
 *
 * This is Expression composite for aggregate and cumulate component
 *
 */
public class AggregateCumulateExpressionComposite extends AbstractExpressionComposite {

	private Label lblNewLabel_2;

	public AggregateCumulateExpressionComposite(Composite parent, int style, final MappingSheetRow mappingSheetRow,
			final Component component, WidgetConfig widgetConfig) {
		super(parent, style);
		setLayout(new GridLayout(1, true));
		configurationForTransformWidget = (OperationClassConfig) widgetConfig;

		this.mappingSheetRow = mappingSheetRow;
		this.component = component;
		Composite mainComposite=new Composite(this, SWT.NONE);
		mainComposite.setLayout(new GridLayout(3, false));
		mainComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		Composite selectColumnComposite = new Composite(mainComposite, SWT.NONE);
		selectColumnComposite.setLayout(new GridLayout(1, false));
		GridData gd_selectColumnComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_selectColumnComposite.heightHint = 275;
		gd_selectColumnComposite.widthHint = 159;
		selectColumnComposite.setLayoutData(gd_selectColumnComposite);

		Composite buttonComposite = new Composite(selectColumnComposite, SWT.NONE);
		buttonComposite.setLayout(new GridLayout(2, false));
		GridData gd_buttonComposite = new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 1);
		gd_buttonComposite.heightHint = 36;
		gd_buttonComposite.widthHint = 139;
		buttonComposite.setLayoutData(gd_buttonComposite);

		addButton = new Button(buttonComposite, SWT.NONE);
		addButton.setImage(ImagePathConstant.ADD_BUTTON.getImageFromRegistry());
		deletButton = new Button(buttonComposite, SWT.NONE);
		deletButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		deletButton.setImage(ImagePathConstant.DELETE_BUTTON.getImageFromRegistry());

		tableViewer = new TableViewer(selectColumnComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
		table = tableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		table.setVisible(true);

		Composite composite = new Composite(mainComposite, SWT.NONE);
		composite.setLayout(new GridLayout(4, false));
		GridData gd_composite = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_composite.heightHint = 275;
		gd_composite.widthHint = 184;
		composite.setLayoutData(gd_composite);
		new Label(composite, SWT.NONE);

		lblNewLabel_1 = new Label(composite, SWT.NONE);
		lblNewLabel_1.setText(Messages.SWITCH_TO);

		Composite radioButtonComposite = new Composite(composite, SWT.NONE);
		GridLayout radioButtonCompositeLayout = new GridLayout(2, false);
		radioButtonCompositeLayout.marginWidth = 0;
		radioButtonComposite.setLayout(radioButtonCompositeLayout);
		radioButtonComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		switchToExpressionButton = new Button(radioButtonComposite, SWT.RADIO);
		switchToExpressionButton.setText(Messages.EXPRESSION);

		switchToClassButton = new Button(radioButtonComposite, SWT.RADIO);
		switchToClassButton.setText(Messages.CLASS);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		switchToExpressionButton.setSelection(true);
		radioButtonComposite.setVisible(true);
		lblNewLabel_1.setVisible(true);
		Label lblExpression = new Label(composite, SWT.NONE);
		GridData gd_lblExpression = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
		gd_lblExpression.minimumWidth = 70;
		gd_lblExpression.heightHint = 15;
		lblExpression.setLayoutData(gd_lblExpression);
		lblExpression.setText(Messages.EXPRESSION_ID);

		GridData gd_composite_1, gd_composite_2, gd_browseButton;
		expressionIdTextBox = new Text(composite, SWT.BORDER);
		gd_composite_1 = new GridData(SWT.LEFT, SWT.BOTTOM, false, false, 1, 6);
		gd_composite_2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_browseButton = new GridData(SWT.LEFT, SWT.TOP, false, false, 0, 1);
		expressionIdTextBox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);

		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);

		lblNewLabel_2 = new Label(composite, SWT.NONE);
		lblNewLabel_2.setText(Messages.DATATYPE);
		comboDataTypes = new Combo(composite, SWT.NONE);
		GridData comboLayout = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		comboLayout.widthHint = 25;
		comboDataTypes.setLayoutData(comboLayout);
		if (OSValidator.isMac()) {
			gd_browseButton.widthHint = 40;
		} else {
			gd_browseButton.widthHint = 28;
		}
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);

		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);

		labelAccumulator = new Label(composite, SWT.NONE);
		labelAccumulator.setText(Messages.ACCUMULATOR);

		textAccumulator = new Text(composite, SWT.BORDER);
		textAccumulator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		if (!StringUtils.isBlank(mappingSheetRow.getAccumulator())) {
			textAccumulator.setText(mappingSheetRow.getAccumulator());
		}
		if (StringUtils.isBlank(textAccumulator.getText())) {
			textAccumulator.setBackground(CustomColorRegistry.INSTANCE.getColorFromRegistry( 255, 255, 000));
		} else {
			textAccumulator.setBackground(CustomColorRegistry.INSTANCE.getColorFromRegistry( 255, 255, 255));
		}
		addDataTypes();
		if (!StringUtils.isBlank(mappingSheetRow.getComboDataType())) {
			comboDataTypes.setText(mappingSheetRow.getComboDataType());
		}

		isParamAccumulator = new Button(composite, SWT.CHECK);
		GridData gd_btnCheckButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_btnCheckButton.horizontalIndent = 12;
		isParamAccumulator.setLayoutData(gd_btnCheckButton);
		isParamAccumulator.setText(Messages.IS_PARAM);
		new Label(composite, SWT.NONE);

		if (mappingSheetRow.isAccumulatorParameter()) {
			isParamAccumulator.setSelection(true);
			comboDataTypes.setEnabled(false);
		}

		textAccumulator.addFocusListener(new FocusListener() {
			@Override
			public void focusLost(FocusEvent e) {
				Text textBox = (Text) e.widget;
				String parameterText = textBox.getText();

				if (!StringUtils.isBlank(parameterText) && isParamAccumulator.getSelection()) {
					parameterText = StringUtils.replace(
							StringUtils.replace(parameterText, Constants.PARAMETER_PREFIX, ""),
							Constants.PARAMETER_SUFFIX, "");
					textBox.setText(Constants.PARAMETER_PREFIX + parameterText + Constants.PARAMETER_SUFFIX);
				}
			}

			@Override
			public void focusGained(FocusEvent e) {
				Text textBox = (Text) e.widget;
				String parameterText = textBox.getText();
				parameterText = StringUtils.replace(StringUtils.replace(parameterText, Constants.PARAMETER_PREFIX, ""),
						Constants.PARAMETER_SUFFIX, "");
				textBox.setText(parameterText);
			}
		});

		isParamAccumulator.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (isParamAccumulator.getSelection()) {
					comboDataTypes.setEnabled(false);
					if (!StringUtils.isBlank(textAccumulator.getText())) {
						String text = StringUtils.replace(
								StringUtils.replace(textAccumulator.getText(), Constants.PARAMETER_PREFIX, ""),
								Constants.PARAMETER_SUFFIX, "");
						textAccumulator.setText(Constants.PARAMETER_PREFIX + text + Constants.PARAMETER_SUFFIX);
					}

				} else {
					comboDataTypes.setEnabled(true);
					String text = StringUtils.replace(
							StringUtils.replace(textAccumulator.getText(), Constants.PARAMETER_PREFIX, ""),
							Constants.PARAMETER_SUFFIX, "");
					textAccumulator.setText(text);
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});

		label = new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);

		gd_composite_1 = new GridData(SWT.LEFT, SWT.BOTTOM, false, false, 1, 4);

		composite_1 = new Composite(composite, SWT.NONE);
		composite_1.setLayout(new GridLayout(1, false));
		if (OSValidator.isMac()) {
			gd_browseButton.widthHint = 40;
			gd_browseButton.horizontalIndent = -5;
		} else {
			gd_browseButton.widthHint = 28;
		}
		gd_composite_1.heightHint = 80;
		gd_composite_1.widthHint = 90;
		composite_1.setLayoutData(gd_composite_1);

		composite_2 = new Composite(composite_1, SWT.NONE);
		gd_composite_2.heightHint = 75;
		gd_composite_2.widthHint = 80;
		composite_2.setLayoutData(gd_composite_2);
		composite_2.setLayout(new GridLayout(1, false));
		browseButton = new Button(composite_2, SWT.NONE);
		gd_browseButton.heightHint = 25;
		browseButton.setLayoutData(gd_browseButton);
		browseButton.setText("...");
		browseButton.setToolTipText(Messages.EXPRESSION_COMPOSITE_BROWSE_BUTTON_TOOL_TIP);
		browseButton.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				createExpressionEditorData();

				LaunchExpressionEditor launchExpressionEditor = new LaunchExpressionEditor();
				launchExpressionEditor.launchExpressionEditor(mappingSheetRow.getExpressionEditorData(),
						getInputSchema(component), mappingSheetRow.getOperationID());
				expressionTextBox.setText(mappingSheetRow.getExpressionEditorData().getExpression());
			}

		});
		new Label(composite_2, SWT.NONE);
		btnIsParam = new Button(composite_2, SWT.CHECK);
		btnIsParam.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
			}
		});
		GridData gd_btnIsParam = new GridData(SWT.LEFT, SWT.BOTTOM, false, false, 1, 1);
		gd_btnIsParam.widthHint = 75;
		gd_btnIsParam.heightHint = 19;
		btnIsParam.setLayoutData(gd_btnIsParam);
		btnIsParam.setText(Messages.IS_PARAM);
		btnIsParam.setSelection(mappingSheetRow.isWholeOperationParameter());

		new Label(composite, SWT.NONE);
		Label lblNewLabel = new Label(composite, SWT.NONE);
		GridData gd_lblNewLabel = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
		gd_lblNewLabel.minimumWidth = 50;
		lblNewLabel.setLayoutData(gd_lblNewLabel);
		lblNewLabel.setText(Messages.EXPRESSION);

		expressionTextBox = new Text(composite, SWT.BORDER);
		expressionTextBox.setEditable(false);
		expressionTextBox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);

		Label lblParameter = new Label(composite, SWT.NONE);
		GridData gd_lblParameter = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
		gd_lblParameter.minimumWidth = 50;
		lblParameter.setLayoutData(gd_lblParameter);
		lblParameter.setText(Messages.PARAMETER);

		parameterTextBox = new Text(composite, SWT.BORDER);
		parameterTextBox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		parameterTextBox.setEnabled(mappingSheetRow.isWholeOperationParameter());

		parameterTextBox.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				Text text = (Text) e.widget;
				mappingSheetRow.setWholeOperationParameterValue(text.getText());
			}
		});

		if (mappingSheetRow.getWholeOperationParameterValue() != null)
			parameterTextBox.setText(mappingSheetRow.getWholeOperationParameterValue());
		Composite composite_4 = new Composite(mainComposite, SWT.NONE);
		composite_4.setLayout(new GridLayout(1, false));
		GridData gd_composite_4 = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
		gd_composite_4.widthHint = 159;
		composite_4.setLayoutData(gd_composite_4);
		new Label(composite_4, SWT.NONE);
		new Label(composite_4, SWT.NONE);
		new Label(composite_4, SWT.NONE);

		Label lblOutputField = new Label(composite_4, SWT.NONE);
		GridData gd_lblOutputField = new GridData(SWT.CENTER, SWT.BOTTOM, false, false, 1, 1);
		gd_lblOutputField.heightHint = 29;
		lblOutputField.setLayoutData(gd_lblOutputField);
		lblOutputField.setText(Messages.OUTPUT_FIELDS);

		outputFieldTextBox = new Text(composite_4, SWT.BORDER);
		GridData gd_outputFieldTextBox = new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1);
		gd_outputFieldTextBox.widthHint = 105;
		gd_outputFieldTextBox.heightHint = 20;
		outputFieldTextBox.setLayoutData(gd_outputFieldTextBox);
		if (!mappingSheetRow.getOutputList().isEmpty()) {
			if (StringUtils.isNotBlank(mappingSheetRow.getOutputList().get(0).getPropertyname()))
				outputFieldTextBox.setText(mappingSheetRow.getOutputList().get(0).getPropertyname());
		}

		ControlDecoration txtDecorator = WidgetUtility.addDecorator(outputFieldTextBox, Messages.FIELDNAME_NOT_ALPHANUMERIC_ERROR);
		txtDecorator.setMarginWidth(2);
		txtDecorator.hide();
		ListenerHelper helper = new ListenerHelper();
		helper.put(HelperType.CONTROL_DECORATION, txtDecorator);
		outputFieldTextBox.addListener(SWT.Verify, new ELTVerifyTextListener().getListener(null, helper, outputFieldTextBox));

		if (mappingSheetRow.getExpressionEditorData() != null
				&& StringUtils.isNotBlank(mappingSheetRow.getExpressionEditorData().getExpression())) {
			expressionTextBox.setText(mappingSheetRow.getExpressionEditorData().getExpression());
		}
		setAllWidgetsOnIsParamButtonForAggregateCumulate(btnIsParam);
		disabledWidgetsifWholeExpressionIsParameterForAggregateCumulate(btnIsParam,
				mappingSheetRow.isWholeOperationParameter());

		createExternalExpressionComposite();
	}

	/**
	 * Add DataTypes to the combo
	 */
	private void addDataTypes() {
		comboDataTypes.setText(Messages.DATATYPE_STRING);
		comboDataTypes.add(Messages.DATATYPE_STRING);
		comboDataTypes.add(Messages.DATATYPE_INTEGER);
		comboDataTypes.add(Messages.DATATYPE_DOUBLE);
		comboDataTypes.add(Messages.DATATYPE_FLOAT);
		comboDataTypes.add(Messages.DATATYPE_SHORT);
		comboDataTypes.add(Messages.DATATYPE_BOOLEAN);
		comboDataTypes.add(Messages.DATATYPE_DATE);
		comboDataTypes.add(Messages.DATATYPE_BIGDECIMAL);
		comboDataTypes.add(Messages.DATATYPE_LONG);
	}

	/**
	 * @param isParam
	 * @param isWholeOperationParameter
	 */
	private void disabledWidgetsifWholeExpressionIsParameterForAggregateCumulate(Button isParam,
			boolean isWholeOperationParameter) {
		if (isWholeOperationParameter) {
			Text textAccumulator = (Text) isParam.getData(Messages.TEXT_ACCUMULATOR);
			Button isParamAccumulator = (Button) isParam.getData(Messages.ISPARAM_ACCUMULATOR);
			Combo comboDataTypes = (Combo) isParam.getData(Messages.COMBODATATYPES);
			textAccumulator.setEnabled(false);
			isParamAccumulator.setEnabled(false);
			comboDataTypes.setEnabled(false);
			super.disabledWidgetsifWholeExpressionIsParameter(isParamAccumulator, isWholeOperationParameter);
		}

	}

	/**
	 * @param isParam
	 */
	private void setAllWidgetsOnIsParamButtonForAggregateCumulate(Button isParam) {
		isParam.setData(Messages.COMBODATATYPES, comboDataTypes);
		isParam.setData(Messages.TEXT_ACCUMULATOR, textAccumulator);
		isParam.setData(Messages.ISPARAM_ACCUMULATOR, isParamAccumulator);
		super.setAllWidgetsOnIsParamButton(isParam);
	}

	protected void refreshExpressionComposite(MappingSheetRow mappingSheetRow) {
		comboDataTypes.setText(mappingSheetRow.getComboDataType());
		if(mappingSheetRow.getAccumulator()==null){
			mappingSheetRow.setAccumulator("");
		}
		textAccumulator.setText(mappingSheetRow.getAccumulator());
		isParamAccumulator.setEnabled(mappingSheetRow.isAccumulatorParameter());
		super.refreshExpressionComposite(mappingSheetRow);
	}

	@Override
	protected void checkSubclass() {
	}

	/**
	 * @param component
	 * @return
	 */
	private List<FixedWidthGridRow> getInputSchema(Component component) {
		List<FixedWidthGridRow> fixedWidthGridRows = new ArrayList<>();
		for (Link link : component.getTargetConnections()) {
			ComponentsOutputSchema componentsOutputSchema = SchemaPropagation.INSTANCE.getComponentsOutputSchema(link);
			if (componentsOutputSchema != null && componentsOutputSchema.getFixedWidthGridRowsOutputFields() != null) {
				fixedWidthGridRows = componentsOutputSchema.getFixedWidthGridRowsOutputFields();
			}
			break;
		}
		return fixedWidthGridRows;
	}

	/* (non-Javadoc)
	 * @see hydrograph.ui.propertywindow.widgets.customwidgets.operational.AbstractExpressionComposite#createExpressionEditorData()
	 */
	@Override
	public ExpressionEditorData createExpressionEditorData() {
		mappingSheetRow.getExpressionEditorData().getExtraFieldDatatypeMap().clear();
		mappingSheetRow.getExpressionEditorData().getExtraFieldDatatypeMap().put(Constants.ACCUMULATOR_VARIABLE,
				DataTypes.getDataTypeClassfromString(mappingSheetRow.getComboDataType()));
		return super.createExpressionEditorData();
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.0"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>EmbASP-CSharp v7.1.0: it.unical.mat.embasp.languages.datalog.MinimalModels Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

EmbASP-CSharp v7.1.0

it

unical

mat

embasp

languages

datalog

MinimalModels

Public Member Functions |
Public Attributes |
Properties |
List of all members

it.unical.mat.embasp.languages.datalog.MinimalModels Class Reference

Inheritance diagram for it.unical.mat.embasp.languages.datalog.MinimalModels:

  <map id="it.unical.mat.embasp.languages.datalog.MinimalModels_map" name="it.unical.mat.embasp.languages.datalog.MinimalModels_map">
<area href="interfaceit_1_1unical_1_1mat_1_1parsers_1_1datalog_1_1IDatalogDataCollection.html" alt="it.unical.mat.parsers.datalog.IDatalogDataCollection" shape="rect" coords="331,0,652,24"/>
  </map>

Public Member Functions

 	MinimalModels (string @out)

 	MinimalModels (string @out, string err)

override object 	Clone ()

void 	AddMinimalModel (MinimalModel minMod)

Public Attributes

virtual string 	MinimalModelsAsString => output

Properties

virtual ISet< MinimalModel > 	Minimalmodels [get]

Constructor & Destructor Documentation

◆ MinimalModels() [1/2]

          it.unical.mat.embasp.languages.datalog.MinimalModels.MinimalModels
          (
          string @
          out	)

inline

◆ MinimalModels() [2/2]

          it.unical.mat.embasp.languages.datalog.MinimalModels.MinimalModels
          (
          string @
          out,

          string
          err

          )

inline

Member Function Documentation

◆ AddMinimalModel()

          void it.unical.mat.embasp.languages.datalog.MinimalModels.AddMinimalModel
          (
          MinimalModel
          minMod	)

inline

Implements it.unical.mat.parsers.datalog.IDatalogDataCollection.

◆ Clone()

          override object it.unical.mat.embasp.languages.datalog.MinimalModels.Clone
          (
          	)

Member Data Documentation

◆ MinimalModelsAsString

          virtual string it.unical.mat.embasp.languages.datalog.MinimalModels.MinimalModelsAsString => output

Property Documentation

◆ Minimalmodels

          virtual ISet<MinimalModel> it.unical.mat.embasp.languages.datalog.MinimalModels.Minimalmodels

get

The documentation for this class was generated from the following file:

embasp-csharp/it/unical/mat/embasp/languages/datalog/MinimalModels.cs

<address class="footer">
Generated by  1.9.0
</address>


text:
AudioLed::AudioLed(){
  pushLayer = CONFIG_LAYER;
}

void AudioLed::init(){

  for(uint8_t i=0; i<FREQ_COUNT; i++){
    data.freqAmp[i]=0;
    data.maxFreqAmp[i]=0;
    //data.collectTime = 100;
    data.rolloff = 99;
  }

  tempo.init();
  sound.init();
  effects.init();
  remote.init();
}

void AudioLed::run(){
  remote.run();
  if(remote.code != NONE){
    this->handleRemote();
  }
  data.pushLayer = pushLayer;

  data.tempo = tempo.tempo;
  sound.run(data);
  effects.run(data);
}

void AudioLed::handleRemote(){
  IrInput input = remote.code;

  switch(input){
    case PLAY_PAUSE:
      pushLayer = (++pushLayer) % (LAYER_COUNT);
      return;
    case MENUE:
      pushLayer = CONFIG_LAYER;
      return;
  }

  if(pushLayer == CONFIG_LAYER){
    this->changeConfig(input);
    return;
  }

  if(pushLayer == COLOR_LAYER || pushLayer == TEXT_LAYER){
    effects.push(input, pushLayer);
    return;
  }

  if(pushLayer == ADJUST_LAYER){
    this->changeLayer(input);
  }

}

void AudioLed::changeConfig(IrInput input){
  switch(input){
    //case UP:
      //effects.nextEffect(COLOR_LAYER);
      //break;
    //case DOWN:
      //effects.prevEffect(COLOR_LAYER);
      //break;
    case LEFT:
      effects.prevConfig();
      break;
    case RIGHT:
      effects.nextConfig();
      break;
    case CENTER:
      tempo.tap();
      if(tempo.isDoubleTap){
        this->reset();
      }
      break;
  }
}

void AudioLed::changeLayer(IrInput input){
  switch(input){
    case UP:
      effects.nextEffect(COLOR_LAYER);
      break;
    case DOWN:
      effects.prevEffect(COLOR_LAYER);
      break;
    case LEFT:
      effects.prevEffect(TEXT_LAYER);
      break;
    case RIGHT:
      effects.nextEffect(TEXT_LAYER);
      break;
    case CENTER:
      tempo.tap();
      if(tempo.isDoubleTap){
        this->reset();
      }
      break;
  }
}

void AudioLed::reset(){
  effects.reset();
}


text:
from distutils.core import setup

setup (name='igep_qa',
       version='0.1',
       description=u'IGEP Quality Assurance scripts',
       long_description=u'This is overall test software for IGEP Technology '
                        u'based devices, which defines test scope, test strategy, '
                        u'test configurations as well as test execution cycles. It '
                        u'will give readers an overview of validation activities done '
                        u'in any IGEP Technology based devices.',
       author='Enric Balletbo i Serra',
       author_email='eballetbo@iseebcn.com',
       url='',
       packages = ['igep_qa', 'igep_qa.helpers', 'igep_qa.runners', 'igep_qa.suites', 'igep_qa.tests'],
       data_files = [('igep_qa/contrib', ['contrib/dtmf.wav']),
                     ('igep_qa/contrib', ['contrib/test.wav'])],
       scripts = ['scripts/igep-qa.sh'],
       license='LICENSE',
       classifiers = [
         'Intended Audience :: Developers',
         'License :: OSI Approved :: GNU General Public License (GPL)',
         'Natural Language :: English',
         'Operating System :: OS Independent',
         'Programming Language :: Python',
         'Topic :: Software Development :: Quality Assurance',
      ],
)


text:
package org.mousephenotype.cda.solr.repositories;

import org.mousephenotype.cda.solr.service.dto.StatisticalResultDTO;
import org.springframework.data.solr.repository.SolrCrudRepository;

import java.util.List;

/**
 * Support accessing the solr index using spring data
 */
public interface StatisticalResultRepository extends SolrCrudRepository<StatisticalResultDTO, String> {

	List<StatisticalResultDTO> findByParameterStableId(String stableId);
	List<StatisticalResultDTO> findByMarkerAccessionIdAndParameterStableIdAndProcedureStableIdAndPhenotypeSexInAndMpTermIdOptionsIn(String markerAccessionId, String parameterStableId, String procedureStableId, String Sex, String mpTermId);
	List<StatisticalResultDTO> findByMarkerAccessionIdAndParameterStableIdAndProcedureStableIdAndMpTermId(String markerAccessionId, String parameterStableId, String procedureStableId, String mpTermId);
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: alan_flament
 * Date: 08/01/15
 * Time: 19:40
 */
namespace LEA\ProfBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class VisiteUnType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('dateRencontre','date',array(
                //'label' => 'Date rencontre (jj-mm-aaaa): ',
                'label' => false,
                'input' => 'string',
                'format'=> 'dd-MM-yyyy'
            ))
            ->add('adequationMission', 'textarea', array(
                //'label' => 'Le travail est-il en adéquation avec la mission confiée ? '
                'label' => false,
            ))
            ->add('integrationEtudiant', 'textarea', array(
                //'label' => "Comment s'est passé l'intégration de l'étudiant ? "
                'label' => false,
            ))
            ->add('signatureTuteur', 'checkbox', array(
                //'label'     => 'Validation du tuteur',
                'label' => false,
                'required'  => false,
            ))
            ->add('remarquesTuteur', 'textarea',array(
                //'label' => 'Remarques éventuelles :'
                'label' => false,
            ))
            ->add('signatureReferent', 'checkbox', array(
                //'label'     => 'Validation du référent',
                'label' => false,
                'required'  => false,
            ))
            ->add('remarquesReferent', 'textarea',array(
                //'label' => 'Remarques éventuelles :'
                'label' => false,
            ))
        ;

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'LEA\ProfBundle\Entity\VisiteUn'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'VisiteUnType';
    }
}


text:
'use strict';

describe('TokenService', function () {

    beforeEach(module('VoteOn-Common'));

    var tokenService;
    var routeParams;
    var localStorage;
    var httpBackend;
    var rootScope;

    var pollId = '7C7CE5F8-873D-4F1F-AF3F-D24769813ABC';
    var tokenValue = '7773206A-0A51-4381-A4F1-A53A3201F0DE';

    beforeEach(inject(function (TokenService, $routeParams, $localStorage, $httpBackend, $rootScope) {
        tokenService = TokenService;
        routeParams = $routeParams;
        localStorage = $localStorage;
        httpBackend = $httpBackend;
        rootScope = $rootScope;
    }));

    describe('Retrieve Token', function () {

        it('Returns null for a null pollId', function () {

            var nullPollId = null;

            var token = tokenService.retrieveToken(nullPollId);

            expect(token).toBe(null);
        });

        it('With a token in the route, returns the route token', function () {

            routeParams['tokenId'] = tokenValue;

            var token = tokenService.retrieveToken(pollId);

            expect(token).toBe(tokenValue);
        });

        it('With no route token, but a token in local storage, returns the local storage token', function() {
            routeParams['tokenId'] = null;
            localStorage[pollId] = { token: tokenValue };

            var token = tokenService.retrieveToken(pollId);

            expect(token).toBe(tokenValue);

        });

        it('With no route token, but an old style token in local storage, returns the local storage token', function () {
            routeParams['tokenId'] = null;
            localStorage[pollId] = tokenValue;

            var token = tokenService.retrieveToken(pollId);

            expect(token).toBe(tokenValue);

        });

        it('With no route token, nor a local storage token, returns null', function() {

            routeParams['tokenId'] = null;
            localStorage[pollId] = null;

            var token = tokenService.retrieveToken(pollId);

            expect(token).toBe(null);
        });
    });

});


text:
FROM node:onbuild

EXPOSE 8080


text:
VERSION=${1}
DOWNLOAD=${2:-/tmp/camel-release}
mkdir ${DOWNLOAD} 2>/dev/null

# The following component contain schema definitions that must be published
RUNDIR=$(cd ${0%/*} && echo $PWD)
COMPLIST=( "camel-spring-xml:spring-xml"
  "camel-cxf:cxf"
  "camel-cxf-spring-rest:cxf/jaxrs"
  "camel-cxf-spring-soap:cxf/jaxws"
  "camel-spring-integration:spring/integration"
  "camel-spring-security:spring-security"
  "karaf/camel-blueprint:blueprint"
  "karaf/camel-cxf-blueprint:cxf" )
SITE_DIR="${DOWNLOAD}/websites/production/camel"
WEBSITE_URL="https://svn.apache.org/repos/infra/websites/production/camel/content"
GIT_WEBSITE_URL="https://gitbox.apache.org/repos/asf/camel-website.git"

if [ -z "${VERSION}" -o ! -d "${DOWNLOAD}" ]
then
 echo "Usage: release-website.sh <camel-version> [temp-directory]"
 exit 1
fi

echo "Using ${SITE_DIR} as temporary checkout area."
if [ -d "${SITE_DIR}" ]
then
 echo "Temporary checkout area should not exist or should be empty."
 echo "Please remove and rerun release script."
 exit 1
fi
mkdir -p "${SITE_DIR}/${VERSION}"

echo "################################################################################"
echo "               DOWNLOADING COMPONENTS FROM APACHE REPOSITORY                    "
echo "################################################################################"
for comp in ${COMPLIST[*]}; do
  src=${comp%:*}
  dest=${comp#*:}
  wget -e robots=off --wait 3 --no-check-certificate \
    -r -np "--reject=html,txt" "--accept=xsd" "--follow-tags=" \
    -P "${DOWNLOAD}/${VERSION}" -nH "--cut-dirs=3" "--level=1" "--ignore-length" \
    "https://repository.apache.org/content/repositories/releases/org/apache/camel/${src}/${VERSION}/"
done
echo

echo "################################################################################"
echo "                           CHECKOUT CAMEL WEBSITE                               "
echo "################################################################################"
cd "${SITE_DIR}/${VERSION}" && git clone "${GIT_WEBSITE_URL}"

echo "################################################################################"
echo "                           PUBLISH CAMEL SCHEMAS                                "
echo "################################################################################"
for comp in ${COMPLIST[*]}; do
  src=${comp%:*}
  dest=${comp#*:}
  mkdir -p ${SITE_DIR}/${VERSION}/camel-website/static/schema/${dest}/
  cp ${DOWNLOAD}/${VERSION}/org/apache/camel/${src}/${VERSION}/*.xsd ${SITE_DIR}/${VERSION}/camel-website/static/schema/${dest}/
  # update_latest_released_schema("${SITE_DIR}/content/schema/${dest}/")
done
echo

echo "NOTE: Manual steps required! Check the schemas for new artifacts,"
echo "      add them to the repository as required and commit your changes. This step"
echo "      is intentionally not automated at this point to avoid errors."
echo
echo "cd ${SITE_DIR}/${VERSION}/camel-website/"
echo "git status"
echo "git add <schema-${VERSION}-qualifier>.xsd"
echo "git commit -m \"Add XML schemas for Camel ${VERSION}\""
echo "git push"
echo


text:
package summea.kanjoto.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import summea.kanjoto.data.NotesetsDataSource;
import summea.kanjoto.model.Noteset;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

/**
 * ExportDatabaseActivity is an Activity which provides users the ability to export the database.
 * <p>
 * This activity provides a way to export the program database to a file. This allows for database
 * backups and historical database archives that can later be imported back into the program if
 * desired.
 * </p>
 */
public class ExportDatabaseActivity extends Activity {
    private SharedPreferences sharedPref;
    private long apprenticeId = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        apprenticeId = Long.parseLong(sharedPref.getString(
                "pref_selected_apprentice", "1"));

        // make sure destination directory exists
        File path = Environment.getExternalStorageDirectory();
        String newDirectory = path.toString() + "/kanjoto/";
        File newFile = new File(newDirectory);

        if (!newFile.exists()) {
            newFile.mkdirs();
        }

        File externalStorage = Environment.getExternalStorageDirectory();

        if (externalStorage.canWrite()) {
            Context context = this;
            File currentDB = context.getDatabasePath("kanjoto_collection.db");
            File backupDB = new File(newFile, "kanjoto_collection_backup.db");

            // get JSON folder path
            File jsonFolder = new File(Environment.getExternalStorageDirectory(), "json_folder");

            // create JSON folder if necessary
            if (!jsonFolder.exists()) {
                jsonFolder.mkdirs();
            }

            // TODO: possibly relocate this JSON part later on...
            // export JSON test
            // get all notesets from database
            NotesetsDataSource nsds = new NotesetsDataSource(this);
            List<Noteset> allNotesets = nsds.getAllNotesets(apprenticeId);
            nsds.close();

            JSONObject mainJsonObj = new JSONObject();
            JSONArray jsonArr = new JSONArray();

            try {
                // add each noteset into JSON object
                for (Noteset noteset : allNotesets) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("id", noteset.getId());
                    jsonObj.put("emotion_id", noteset.getEmotion());
                    jsonArr.put(jsonObj);
                }

                mainJsonObj.put("notesets", jsonArr);

                // save JSON string to file
                FileOutputStream outputStream = new FileOutputStream(new File(jsonFolder,
                        "json_export.txt"));
                outputStream.write(mainJsonObj.toString().getBytes());
                outputStream.close();

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // TODO: address certain cases
            if (currentDB.exists()) {
                Log.d("MYLOG", "current database exists!");
            }

            if (backupDB.exists()) {
                Log.d("MYLOG", "new file exists!");
            }

            FileChannel src = null;
            FileChannel dst = null;

            try {
                src = new FileInputStream(currentDB).getChannel();
                dst = new FileOutputStream(backupDB).getChannel();

                // copy source file to destination
                dst.transferFrom(src, 0, src.size());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    src.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    dst.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Toast.makeText(getBaseContext(), "Database exported!",
                        Toast.LENGTH_SHORT).show();
            }
        }

        // close activity
        finish();
    }

}


text:
from models.basemodel import BaseModel
from telepat import TelepatContext

class Context(TelepatContext, BaseModel):
    _ignored_fields = ["object_id", "model"]


text:
using UnityEngine;

namespace Fungus
{
    /// <summary>
    /// Base class for all simple Unary
    /// </summary>
    [AddComponentMenu("")]
    public abstract class BaseUnaryMathCommand : Command
    {
        [Tooltip("Value to be passed in to the function.")]
        [SerializeField]
        protected FloatData inValue;

        [Tooltip("Where the result of the function is stored.")]
        [SerializeField]
        protected FloatData outValue;

        public override Color GetButtonColor()
        {
            return new Color32(235, 191, 217, 255);
        }

        public override string GetSummary()
        {
            return "in: " + (inValue.floatRef != null ? inValue.floatRef.Key : inValue.Value.ToString()) +
                   ", out: " + (outValue.floatRef != null ? outValue.floatRef.Key : outValue.Value.ToString());
        }

        public override bool HasReference(Variable variable)
        {
            return variable == inValue.floatRef || variable == outValue.floatRef;
        }
    }
}


text:
using EDDiscovery.Controls;
using EliteDangerousCore;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace EDDiscovery.UserControls
{
    public partial class UserControlMaterialTrader : UserControlCommonBase
    {
        private string dbTraderType = "TraderType";
        private string dbTrades = "Trades";
        private string dbSplitter = "Splitter";
        private string dbLatest = "Latest";

        private Color orange = Color.FromArgb(255, 184, 85, 8);

        private uint? last_mcl = null;

        public class ElementTrade
        {
            public MaterialCommodityMicroResourceType.MaterialGroupType type;    // for display purposes, group type
            public int level;                                       // and level

            public MaterialCommodityMicroResourceType element;               // element of entry, or for trades, element received
            public int offer;
            public int receive;
            public MaterialCommodityMicroResourceType fromelement;           // only for trades, the element that offered up

            public override string ToString()                   // serialise to string
            {
                return fromelement?.FDName + "," + element?.FDName + "," + offer.ToStringInvariant() + "," + receive.ToStringInvariant();
            }

            public bool FromString(string s)                    // serialise from string
            {
                string[] parts = s.Split(',');
                if (parts.Length == 4)
                {
                    fromelement = MaterialCommodityMicroResourceType.GetByFDName(parts[0]);
                    element = MaterialCommodityMicroResourceType.GetByFDName(parts[1]);
                    return fromelement != null && element != null && parts[2].InvariantParse(out offer) && parts[3].InvariantParse(out receive);
                }
                else
                    return false;
            }
        }

        ElementTrade selected = null;         // selected entry to trade to

        List<ElementTrade> tradelist = new List<ElementTrade>();           // trades established.

        #region Init

        public UserControlMaterialTrader()
        {
            InitializeComponent();

            var enumlist = new Enum[] { EDTx.UserControlMaterialTrader_UpgradeCol, EDTx.UserControlMaterialTrader_LevelCol, EDTx.UserControlMaterialTrader_WantedCol, EDTx.UserControlMaterialTrader_ModuleCol, EDTx.UserControlMaterialTrader_MaxCol, EDTx.UserControlMaterialTrader_AvailableCol, EDTx.UserControlMaterialTrader_buttonClear };
            var enumlistcms = new Enum[] { EDTx.UserControlMaterialTrader_clearTradeToolStripMenuItem };
            var enumlisttt = new Enum[] { EDTx.UserControlMaterialTrader_checkBoxCursorToTop_ToolTip, EDTx.UserControlMaterialTrader_buttonClear_ToolTip };

            BaseUtils.Translator.Instance.TranslateControls(this, enumlist);
            BaseUtils.Translator.Instance.TranslateToolstrip(contextMenuStrip, enumlistcms, this);
            BaseUtils.Translator.Instance.TranslateTooltip(toolTip, enumlisttt, this);
        }

        public override void Init()
        {
            DBBaseName = "MaterialTrade";

            dataGridViewTrades.MakeDoubleBuffered();
            dataGridViewTrades.DefaultCellStyle.WrapMode = DataGridViewTriState.False;

            extComboBoxTraderType.Items.AddRange(new string[] { "Raw".T(EDTx.UserControlMaterialTrader_Raw), "Encoded".T(EDTx.UserControlMaterialTrader_Encoded), "Manufactured".T(EDTx.UserControlMaterialTrader_Manufactured) });
            extComboBoxTraderType.SelectedIndex = GetSetting(dbTraderType, 0);
            extComboBoxTraderType.SelectedIndexChanged += ExtComboBoxTraderType_SelectedIndexChanged;

            checkBoxCursorToTop.Checked = GetSetting(dbLatest, true);
            checkBoxCursorToTop.CheckedChanged += CheckBoxCursorToTop_CheckedChanged;

            string[] strades = GetSetting(dbTrades, "").Split(';');
            foreach (var t in strades)      // deserialise the trades and populate the trades list
            {
                ElementTrade et = new ElementTrade();
                if (et.FromString(t))
                    tradelist.Add(et);
            }

            splitContainer.SplitterDistance(GetSetting(dbSplitter, 0.75));

            discoveryform.OnThemeChanged += Discoveryform_OnThemeChanged;
            discoveryform.OnNewEntry += Discoveryform_OnNewEntry;
            discoveryform.OnHistoryChange += Discoveryform_OnHistoryChange;
        }

        public override void ChangeCursorType(IHistoryCursor thc)
        {
            uctg.OnTravelSelectionChanged -= TravelSelectionChanged;
            uctg = thc;
            uctg.OnTravelSelectionChanged += TravelSelectionChanged;
        }

        public override void LoadLayout()
        {
            dataGridViewTrades.RowTemplate.MinimumHeight = Font.ScalePixels(26);
            uctg.OnTravelSelectionChanged += TravelSelectionChanged;
            DGVLoadColumnLayout(dataGridViewTrades);
        }

        public override void Closing()
        {
            DGVSaveColumnLayout(dataGridViewTrades);
            PutSetting(dbSplitter, splitContainer.GetSplitterDistance());
            uctg.OnTravelSelectionChanged -= TravelSelectionChanged;

            discoveryform.OnThemeChanged -= Discoveryform_OnThemeChanged;
            discoveryform.OnNewEntry -= Discoveryform_OnNewEntry;
            discoveryform.OnHistoryChange -= Discoveryform_OnHistoryChange;
        }

        private void Discoveryform_OnThemeChanged()
        {
            DisplayTradeSelection();
            DisplayTradeList();
        }

        #endregion

        #region Display

        public override void InitialDisplay()
        {
            // last_mcl may be null if there is no history
            last_mcl = checkBoxCursorToTop.Checked ? discoveryform.history.GetLast?.MaterialCommodity : uctg.GetCurrentHistoryEntry?.MaterialCommodity;
            DisplayTradeSelection();
            DisplayTradeList();
        }

        private void Discoveryform_OnHistoryChange(HistoryList obj)
        {
            InitialDisplay();
        }

        private void TravelSelectionChanged(HistoryEntry he, HistoryList hl, bool selectedEntry)
        {
            if (checkBoxCursorToTop.Checked == false)
            {
                if (he != null && last_mcl != he?.MaterialCommodity)        // if changed MCL
                {
                    last_mcl = he.MaterialCommodity;
                    DisplayTradeSelection();
                    DisplayTradeList();
                }
            }
        }

        private void Discoveryform_OnNewEntry(HistoryEntry he, HistoryList hl)
        {
            if ( checkBoxCursorToTop.Checked )
            {
                if (he.journalEntry is IMaterialJournalEntry)
                {
                    last_mcl = he.MaterialCommodity;
                    DisplayTradeSelection();
                    DisplayTradeList();
                }
            }
        }

        private void DisplayTradeSelection(MaterialCommodityMicroResourceType highlight = null)  // last_he and current_mcl can be null
        {
            int sel = extComboBoxTraderType.SelectedIndex;

            var mcl = new List<Tuple<MaterialCommodityMicroResourceType.MaterialGroupType, MaterialCommodityMicroResourceType[]>>();      // list of groups vs data
            Dictionary<MaterialCommodityMicroResourceType.MaterialGroupType, string> mattxgroupnames = new Dictionary<MaterialCommodityMicroResourceType.MaterialGroupType, string>(); // translated names of groups

            foreach ( var t in Enum.GetValues(typeof(MaterialCommodityMicroResourceType.MaterialGroupType)))     // relies on MCD being in order
            {
                var matgroup = (MaterialCommodityMicroResourceType.MaterialGroupType)t;
                bool ok = (sel == 0 && matgroup >= MaterialCommodityMicroResourceType.MaterialGroupType.RawCategory1 && matgroup <= MaterialCommodityMicroResourceType.MaterialGroupType.RawCategory7);
                ok |= (sel == 1 && matgroup >= MaterialCommodityMicroResourceType.MaterialGroupType.EncodedEmissionData && matgroup <= MaterialCommodityMicroResourceType.MaterialGroupType.EncodedFirmware);
                ok |= (sel == 2 && matgroup >= MaterialCommodityMicroResourceType.MaterialGroupType.ManufacturedChemical);
                if ( ok )
                {
                    var list = MaterialCommodityMicroResourceType.Get(x => x.MaterialGroup == matgroup);
                    mcl.Add(new Tuple<MaterialCommodityMicroResourceType.MaterialGroupType, MaterialCommodityMicroResourceType[]>(matgroup,list));
                    mattxgroupnames[matgroup] = list[0].TranslatedMaterialGroup;
                }
            }

            var curmcl = last_mcl != null ? discoveryform.history.MaterialCommoditiesMicroResources.Get(last_mcl.Value) : null;       // get mcl at last_mcl position. May be null if we don't have any list

            Font titlefont = ExtendedControls.Theme.Current.GetFont;
            Font badgefont = ExtendedControls.Theme.Current.GetScaledFont(16f / 12f, max:21);

            const int hbadgemargin = 20;
            const int vbadgemargin = 12;

            extPictureTrades.ClearImageList();

            int vpos = 0;
            int maxhpos = 0;

            foreach (var t in mcl)      // for each type of material/commd
            {
                int hpos = 0;
                int nextvpos = vpos;
                int lvl = 1;

                extPictureTrades.AddOwnerDraw((g, ie) =>
                {
                    int tlen;
                    using (Brush b = new SolidBrush(orange))
                    {
                        string s = mattxgroupnames[t.Item1];
                        s = s.Substring(s.IndexOf(" ") + 1);
                        tlen = (int)(g.MeasureString(s, titlefont).Width+2);
                        g.DrawString(s, titlefont, b, new Point(ie.Location.Left, ie.Location.Top));
                    }

                    using (Pen p = new Pen(orange))
                    {
                        g.DrawLine(p, new Point(tlen, ie.Location.Top + titlefont.Height / 2), new Point(maxhpos, ie.Location.Top + titlefont.Height / 2));
                    }

                }, new Rectangle(0, vpos, 2000, 24), t.Item1.ToString());

                vpos += titlefont.Height + 6;

                string backname = "encodedbackground";
                if (t.Item1.ToString().Contains("Manu"))
                    backname = "manubackground";
                else if (t.Item1.ToString().Contains("Raw"))
                    backname = "rawbackground";

                Bitmap background = BaseUtils.Icons.IconSet.GetIcon("Controls.MaterialTrader." + backname ) as Bitmap;

                foreach ( var mat in t.Item2 )
                {
                    int offer = 0, receive = 0;
                    string name = mat.Name;

                    int mattotal = last_mcl == null ? int.MinValue : curmcl.Find(x=>x.Details.FDName == mat.FDName)?.Count ?? 0;    // find mcl in material list if there, and its count

                    if (mattotal >= 0)                                                  // if we have an he, adjust the totals by the trades
                    {
                        foreach (var trade in tradelist)
                        {
                            if (trade.fromelement.FDName == mat.FDName)
                                mattotal -= trade.offer;                              // may go negative if over offered
                            if (trade.element.FDName == mat.FDName)
                                mattotal += trade.receive;
                        }
                    }

                    Color wash = Color.Transparent;

                    if (highlight?.FDName == mat.FDName)
                        wash = Color.FromArgb(80, 0, 75, 0);

                    if (selected != null)
                    {
                        bool difflevel = selected.type != t.Item1;

                        if (lvl < selected.level)
                        {
                            offer = (int)Math.Pow(6, (selected.level - lvl) + (difflevel ? 1 : 0));
                            receive = 1;
                        }
                        else if (lvl > selected.level)
                        {
                            offer = difflevel ? 6 : 1;
                            receive = (int)Math.Pow(3, (lvl - selected.level) );
                            while( offer % 3 == 0 )
                            {
                                offer /= 3;
                                receive /= 3;
                            }
                        }
                        else if (selected.type == t.Item1)
                        {
                            name = "Cancel";
                            wash = Color.FromArgb(80, 0, 32, 0);
                        }
                        else
                        {
                            offer = 6;
                            receive = 1;

                        }

                        if (offer > mattotal)
                        {
                            wash = Color.FromArgb(80, 128, 0, 0);
                        }
                    }

                    Bitmap bmp = DrawBadge(background, badgefont, offer, receive, lvl, name, mattotal, wash);

                    var ie = extPictureTrades.AddImage(new Rectangle(hpos, vpos, background.Width, background.Height), bmp, imgowned: true);
                    ie.Tag = new ElementTrade { type = t.Item1, element = mat, level = lvl, offer = offer, receive = receive };

                    maxhpos = Math.Max(maxhpos, hpos + bmp.Width);
                    hpos += bmp.Width + hbadgemargin;
                    nextvpos = Math.Max(nextvpos, vpos+ bmp.Height + vbadgemargin);
                    lvl++;
                }

                vpos = nextvpos;
            }

            extPictureTrades.Render();
        }

        Bitmap DrawBadge(Bitmap background , Font displayfont, int offer, int receive , int level , string matname, int mattotal, Color wash)
        {

            Bitmap bmp = background.Clone() as Bitmap;
            using (Graphics g = Graphics.FromImage(bmp))
            {
                using (Brush b = new SolidBrush(orange))
                {
                    if (offer > 0 && receive > 0)
                    {
                        Bitmap arrow = BaseUtils.Icons.IconSet.GetIcon("Controls.MaterialTrader.materialexchange") as Bitmap;

                        g.DrawImage(arrow, new Point(8, 8));

                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                        g.DrawString(offer.ToStringInvariant(), displayfont, b, new Point(8, 2));
                        g.DrawString(receive.ToStringInvariant(), displayfont, b, new Point(8, 32));
                    }

                    using (StringFormat fmt = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
                    {
                        g.DrawString(matname, displayfont, b, new Rectangle(0, 100, bmp.Width, 45), fmt);

                        if ( mattotal != int.MinValue )
                            g.DrawString(mattotal.ToStringInvariant(), displayfont, b, new Rectangle(0, 75, bmp.Width, 20), fmt);
                    }

                }

                if ( level > 0)
                {
                    Bitmap petal = BaseUtils.Icons.IconSet.GetIcon("Controls.MaterialTrader.petal" + level.ToStringInvariant()) as Bitmap;
                    g.DrawImage(petal, new Point(bmp.Width/2-petal.Width/2,42-petal.Height/2));
                }

                if ( !wash.IsFullyTransparent() )
                {
                    using (Brush b = new SolidBrush(wash))
                    {
                        g.FillRectangle(b, new Rectangle(0, 0, bmp.Width, bmp.Height));
                    }
                }
            }

            return bmp;
        }

        void DisplayTradeList()
        {
            dataGridViewTrades.Rows.Clear();

            if (tradelist.Count > 0)
            {
                // last_mcl can be null
                List<MaterialCommodityMicroResource> mcl = last_mcl == null ? null : discoveryform.history.MaterialCommoditiesMicroResources.Get(last_mcl.Value);

                var totals = mcl == null ? null : MaterialCommoditiesRecipe.TotalList(mcl);                  // start with totals present, null if we don't have an mcl

                foreach (var trade in tradelist)
                {
                    var rw = dataGridViewTrades.RowTemplate.Clone() as DataGridViewRow;

                    if (mcl != null)
                    {
                        if (!totals.ContainsKey(trade.fromelement.FDName))      // make sure they are both there, so we don't crash.  the from should always be here
                            totals[trade.fromelement.FDName] = 0;
                        if (!totals.ContainsKey(trade.element.FDName))          // the to, if 0, will not
                            totals[trade.element.FDName] = 0;

                        totals[trade.fromelement.FDName] -= trade.offer;

                        if (totals[trade.fromelement.FDName] >= 0)
                        {
                            totals[trade.element.FDName] += trade.receive;

                            rw.CreateCells(dataGridViewTrades, trade.fromelement.Name, trade.offer.ToString(), totals[trade.fromelement.FDName].ToString(), trade.element.Name, trade.receive.ToString(), totals[trade.element.FDName].ToString());
                        }
                        else
                        {
                            rw.CreateCells(dataGridViewTrades, trade.fromelement.Name, trade.offer.ToString(), "- !!!", trade.element.Name, trade.receive.ToString(), "-");
                        }
                    }
                    else
                    {
                        rw.CreateCells(dataGridViewTrades, trade.fromelement.Name, trade.offer.ToString(), "-", trade.element.Name, trade.receive.ToString(), "-");
                    }

                    dataGridViewTrades.Rows.Add(rw);
                }

            }
        }

        #endregion

        private void buttonClear_Click(object sender, EventArgs e)
        {
            tradelist.Clear();
            StoreTrades();
            DisplayTradeSelection();
            DisplayTradeList();
        }

        private void ExtComboBoxTraderType_SelectedIndexChanged(object sender, EventArgs e)
        {
            PutSetting(dbTraderType, extComboBoxTraderType.SelectedIndex );
            selected = null;
            DisplayTradeSelection();
        }

        private void extPictureTrades_ClickElement(object sender, MouseEventArgs eventargs, ExtendedControls.ExtPictureBox.ImageElement i, object tag)
        {
            if (i != null && tag is ElementTrade && last_mcl != null ) // must be an element, with a tag, must have a current mcl
            {
                ElementTrade current = (ElementTrade)tag;
                System.Diagnostics.Debug.WriteLine("Clicked on " + current.type + " " + current.element.Name);

                if (selected != null)
                {
                    List<MaterialCommodityMicroResource> mcl = discoveryform.history.MaterialCommoditiesMicroResources.Get(last_mcl.Value);
                    int currenttotal = mcl.Find(x=>x.Details==current.element)?.Count ?? 0;   // current mat total. If not there, its zero
                    foreach (var trade in tradelist)
                    {
                        if (trade.fromelement.FDName == current.element.FDName)
                            currenttotal -= trade.offer;                              // may go negative if over offered
                        if (trade.element.FDName == current.element.FDName)
                            currenttotal += trade.receive;
                    }

                    if (selected.element.FDName == current.element.FDName)        // clicked on same.. deselect
                    {
                        selected = null;
                    }
                    else if ( currenttotal >= current.offer )                       // if we have enough for at least 1 trade
                    {
                        DisplayTradeSelection(current.element);

                        ExtendedControls.ConfigurableForm f = new ExtendedControls.ConfigurableForm();

                        int width = 250;
                        int margin = 20;

                        var butl = new ExtendedControls.ExtButton();
                        butl.Image = BaseUtils.Icons.IconSet.GetIcon("Controls.MaterialTrader.LeftArrow");
                        f.Add(new ExtendedControls.ConfigurableForm.Entry(butl, "less", "", new Point(margin, 64), new Size(32, 32), null));
                        var butr = new ExtendedControls.ExtButton();
                        butr.Image = BaseUtils.Icons.IconSet.GetIcon("Controls.MaterialTrader.RightArrow");
                        f.Add(new ExtendedControls.ConfigurableForm.Entry(butr, "more", "", new Point(width - margin - 32, 64), new Size(32, 32), null));

                        f.Add(new ExtendedControls.ConfigurableForm.Entry("olabel", typeof(Label), "Offer".T(EDTx.UserControlMaterialTrader_Offer), new Point(margin, 30), new Size(width - margin * 2, 20), null, 1.5f, ContentAlignment.MiddleCenter));

                        f.Add(new ExtendedControls.ConfigurableForm.Entry("offer", typeof(Label), "0/" + currenttotal.ToStringInvariant(), new Point(width / 2 - 12, 50), new Size(width / 2 - 20, 20), null, 1.2f, ContentAlignment.MiddleLeft));

                        var bar = new PictureBox();
                        bar.SizeMode = PictureBoxSizeMode.StretchImage;
                        bar.Image = BaseUtils.Icons.IconSet.GetIcon("Controls.MaterialTrader.TraderBar");
                        f.Add(new ExtendedControls.ConfigurableForm.Entry(bar, "bar", "", new Point(width / 2 - 32, 70), new Size(64, 16), null));

                        f.Add(new ExtendedControls.ConfigurableForm.Entry("receive", typeof(Label), "0", new Point(width / 2 - 12, 90), new Size(width / 2 - 20, 20), null, 1.2f, ContentAlignment.MiddleLeft));

                        f.Add(new ExtendedControls.ConfigurableForm.Entry("rlabel", typeof(Label), "Receive".T(EDTx.UserControlMaterialTrader_Receive), new Point(margin, 110), new Size(width - margin * 2, 20), null, 1.5f, ContentAlignment.MiddleCenter));

                        f.AddOK(new Point(width - margin - 80, 150), "Press to Accept".T(EDTx.UserControlModules_PresstoAccept));
                        f.AddCancel(new Point(margin, 150), "Press to Cancel".T(EDTx.UserControlModules_PresstoCancel));

                        int currentoffer = 0;
                        int currentreceive = 0;

                        f.Trigger += (dialogname, controlname, xtag) =>
                        {
                            if (controlname == "OK")
                            {
                                f.ReturnResult(DialogResult.OK);
                            }
                            else if (controlname == "Cancel" || controlname == "Close")
                            {
                                f.ReturnResult(DialogResult.Cancel);
                            }
                            else if ( controlname == "less" || controlname == "more" )
                            {
                                if (controlname == "less")
                                {
                                    if (currentoffer > 0)
                                    {
                                        currentoffer -= current.offer;
                                        currentreceive -= current.receive;
                                    }
                                }
                                else
                                {
                                    int newoffer = currentoffer + current.offer;
                                    if (newoffer <= currenttotal)
                                    {
                                        currentoffer = newoffer;
                                        currentreceive += current.receive;
                                    }
                                }

                                f.GetControl<Label>("offer").Text = currentoffer.ToStringInvariant() + "/" + currenttotal.ToStringInvariant();
                                f.GetControl<Label>("receive").Text = currentreceive.ToStringInvariant();
                            }
                        };

                        f.RightMargin = margin;

                        f.InitCentred(this.FindForm(), this.FindForm().Icon, " ", closeicon: true);

                        DialogResult res = f.ShowDialog();

                        if (res == DialogResult.OK)
                        {
                            ElementTrade t = new ElementTrade() { element = selected.element, fromelement = current.element, offer = currentoffer, receive = currentreceive };
                            tradelist.Add(t);
                            selected = null;

                            StoreTrades();

                            DisplayTradeList();
                        }

                        DisplayTradeSelection();
                    }
                }
                else
                {
                    selected = current;
                }

                DisplayTradeSelection();
            }
        }

        private void clearTradeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewTrades.RightClickRowValid)
            {
                tradelist.RemoveAt(dataGridViewTrades.RightClickRow);
                StoreTrades();
                DisplayTradeSelection();
                DisplayTradeList();
            }
        }

        private void StoreTrades()
        {
            string strades = "";
            foreach (var td in tradelist)
                strades = strades.AppendPrePad(td.ToString(), ";");

            PutSetting(dbTrades, strades);
        }

        private void CheckBoxCursorToTop_CheckedChanged(object sender, EventArgs e)
        {
            PutSetting(dbLatest, checkBoxCursorToTop.Checked);
            InitialDisplay();
        }

    }
}


text:
package com.smallchill.api.common.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.smallchill.core.constant.ConstApi;
import org.apache.commons.lang3.StringUtils;

/**
 * API请求参数过滤器
 * Created by yesong on 2015/8/10.
 */
public class ApiTokenRequestFilter implements Filter,ConstApi {

    private static String[] SKIP_URLS = new String[]{};

    public ApiTokenRequestFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        Map<String, String[]> m = new HashMap<String, String[]>(httpRequest.getParameterMap());
        request = new ParameterRequestWrapper((HttpServletRequest) request, m);

        boolean allow = true;

        String error = request.getParameter("error");
        if (StringUtils.isNotBlank(error)) {
            allow = false;
        }

        String token = request.getParameter("token");
        if (StringUtils.isBlank(token) || !token.equals(ACCESS_KEY)) {
            allow = false;
        }
        if (!allow) {
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of NumType in UD_Komi_Permyak-UH</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Komi_Permyak-UH: Features: NumType

This feature is universal but the values MultDist, OrdMult are language-specific.
It occurs with 5 different values: Card, Dist, MultDist, Ord, OrdMult.

14 tokens (1%) have a non-empty value of NumType.
11 types (2%) occur at least once with a non-empty value of NumType.
10 lemmas (2%) occur at least once with a non-empty value of NumType.
The feature is used with 3 part-of-speech tags: <tt>NUM</tt> (7; 1% instances), <tt>ADV</tt> (5; 0% instances), <tt>ADJ</tt> (2; 0% instances).

NUM

7 <tt>NUM</tt> tokens (78% of all NUM tokens) have a non-empty value of NumType.

The most frequent other feature values with which NUM and NumType co-occurred: <tt>Person</tt><tt>=EMPTY</tt> (6; 86%), <tt>Tense</tt><tt>=EMPTY</tt> (6; 86%), <tt>Case</tt><tt>=EMPTY</tt> (5; 71%), <tt>Number</tt><tt>=EMPTY</tt> (4; 57%).

NUM tokens may have the following values of NumType:

Card (5; 71% of non-empty NumType): кык, куим, öтiк

Dist (2; 29% of non-empty NumType): Кыкӧн, кыкӧнӧсь

EMPTY (2): кыка, нёляӧсь

Paradigm кык	<tt>Card</tt>	<tt>Dist</tt>

<tt>_</tt>	кык	Кыкӧн

<tt><tt>Case</tt><tt>=Nom</tt>|<tt>Number</tt><tt>=Sing</tt></tt>	кык

ADV

5 <tt>ADV</tt> tokens (6% of all ADV tokens) have a non-empty value of NumType.

ADV tokens may have the following values of NumType:

Card (1; 20% of non-empty NumType): ӧтикӧ

MultDist (2; 40% of non-empty NumType): кыкисьӧн, кыкисьӧн-куимисьӧн

OrdMult (2; 40% of non-empty NumType): дасöтiсь

EMPTY (82): кыдз, ни, сэсся, кӧр, сё, талун, чожа, эшӧ, кынымкӧ, кытӧн

ADJ

2 <tt>ADJ</tt> tokens (6% of all ADJ tokens) have a non-empty value of NumType.

The most frequent other feature values with which ADJ and NumType co-occurred: <tt>Case</tt><tt>=Nom</tt> (2; 100%), <tt>Degree</tt><tt>=EMPTY</tt> (2; 100%), <tt>Number</tt><tt>=Sing</tt> (2; 100%).

ADJ tokens may have the following values of NumType:

Ord (2; 100% of non-empty NumType): Куимӧдз, витӧдз

EMPTY (33): буржык, ыджыт, важ, честнӧй, бур, быльнӧй, веськытлань, гажаӧсь, долженöсь, долыт

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.