text:
package de.hpi.bpmn2_0.factory.node;

import org.oryxeditor.server.diagram.generic.GenericShape;

import de.hpi.bpmn2_0.annotations.Property;
import de.hpi.bpmn2_0.annotations.StencilId;
import de.hpi.bpmn2_0.exceptions.BpmnConverterException;
import de.hpi.bpmn2_0.factory.AbstractActivityFactory;
import de.hpi.bpmn2_0.factory.AbstractBpmnFactory;
import de.hpi.bpmn2_0.factory.BPMNElement;
import de.hpi.bpmn2_0.factory.configuration.Configuration;
import de.hpi.bpmn2_0.factory.configuration.LinkedModel;
import de.hpi.bpmn2_0.model.AdHocOrdering;
import de.hpi.bpmn2_0.model.BaseElement;
import de.hpi.bpmn2_0.model.Definitions;
import de.hpi.bpmn2_0.model.FlowElement;
import de.hpi.bpmn2_0.model.FormalExpression;
import de.hpi.bpmn2_0.model.Process;
import de.hpi.bpmn2_0.model.activity.Activity;
import de.hpi.bpmn2_0.model.activity.AdHocSubProcess;
import de.hpi.bpmn2_0.model.activity.CallActivity;
import de.hpi.bpmn2_0.model.activity.SubProcess;
import de.hpi.bpmn2_0.model.activity.Transaction;
import de.hpi.bpmn2_0.model.activity.TransactionMethod;
import de.hpi.bpmn2_0.model.artifacts.Artifact;
import de.hpi.bpmn2_0.model.bpmndi.BPMNShape;
import de.hpi.bpmn2_0.model.extension.signavio.SignavioMetaData;
import de.hpi.bpmn2_0.transformation.Diagram2BpmnConverter;

/**
 * Factory to handle all types subprocesses in a process diagram
 *
 * @author Sven Wagner-Boysen
 *
 */
@StencilId({
	"CollapsedSubprocess",
	"Subprocess",
	"CollapsedEventSubprocess",
	"EventSubprocess"
})
public class SubprocessFactory extends AbstractActivityFactory {
//	@Override
	public BPMNElement createBpmnElement(GenericShape shape, Configuration configuration) throws BpmnConverterException {
		BPMNElement bpmnElement = super.createBpmnElement(shape, configuration);

		if(bpmnElement != null && bpmnElement.getNode() != null) {
			handleLinkedDiagrams(bpmnElement.getNode(), shape, configuration);
		}

		return bpmnElement;
	}

	// @Override
	protected BPMNShape createDiagramElement(GenericShape shape) {

		BPMNShape bpmnShape = super.createDiagramElement(shape);

		/* Mark as collapsed or expanded */
		if(shape.getStencilId().matches(".*Collapsed.*")) {
			bpmnShape.setIsExpanded(false);
		} else {
			bpmnShape.setIsExpanded(true);
		}

		return bpmnShape;
	}

	/* (non-Javadoc)
	 * @see de.hpi.bpmn2_0.factory.AbstractBpmnFactory#createProcessElement(org.oryxeditor.server.diagram.Shape)
	 */
	// @Override
	protected BaseElement createProcessElement(GenericShape shape)
			throws BpmnConverterException {
		Activity subprocess = null;
		try {
			subprocess = (Activity) this.invokeCreatorMethodAfterProperty(shape);
			this.createLoopCharacteristics(subprocess, shape);
		} catch (Exception e) {
//			throw new BpmnConverterException("Error creating subprocess elements.", e);
		}

		if(subprocess == null)
			subprocess = new SubProcess();

		this.setStandardAttributes(subprocess, shape);

		/* Mark as event subprocess */
		if(!(subprocess instanceof CallActivity)) {
			if(shape.getStencilId().matches(".*EventSubprocess.*")) {
				((SubProcess) subprocess).setTriggeredByEvent(true);
			} else {
				((SubProcess) subprocess).setTriggeredByEvent(false);
			}
		}

		subprocess.setName(shape.getProperty("name"));

		return subprocess;
	}

	@Property(name = "callacitivity", value = "true")
	public CallActivity createCallActivity(GenericShape shape) {
		CallActivity callAct = new CallActivity();
		this.setStandardAttributes(callAct, shape);
		return callAct;
	}

	@Property(name = "isatransaction", value = "true")
	public Transaction createTransaction(GenericShape shape) {
		Transaction transaction = new Transaction();
		transaction.setMethod(TransactionMethod.fromValue(shape.getProperty("transactionMethod")));
		return transaction;
	}

	@Property(name = "isadhoc", value = "true")
	public AdHocSubProcess createAdhocSubprocess(GenericShape shape) {
		AdHocSubProcess adhocSub = new AdHocSubProcess();
		/* Mapping of properties */
		String condition = shape.getProperty("adhoccompletioncondition");
		if(condition != null && !(condition.length() == 0))
			adhocSub.setCompletionCondition(new FormalExpression(condition));

		String ordering = shape.getProperty("adhocordering");
		if(ordering != null) {
			adhocSub.setOrdering(AdHocOrdering.fromValue(shape.getProperty("adhocordering")));
		}

		String cancelRemIns = shape.getProperty("adhoccancelremaininginstances");
		if(cancelRemIns != null)
			adhocSub.setCancelRemainingInstances(!cancelRemIns.equalsIgnoreCase("false"));

		return adhocSub;
	}

	/**
	 * Transforms linked diagrams of collapsed subprocess and event subprocess.
	 *
	 * @param baseElement
	 * @param shape
	 * @param config
	 */
	private void handleLinkedDiagrams(BaseElement baseElement, GenericShape shape, Configuration config) {
		if(baseElement == null
				|| !((baseElement instanceof SubProcess) || (baseElement instanceof CallActivity))
				|| !shape.getStencilId().matches(".*Collapsed.*")) {
			return;
		}

		/*
		 * Diagram Link
		 */
		String entry = shape.getProperty("entry");
		if(entry == null || entry.length() == 0) {
			return;
		}

		SignavioMetaData metaData = new SignavioMetaData("entry", entry);
		baseElement.getOrCreateExtensionElements().add(metaData);

		Definitions linkedDiagram = retrieveDefinitionsOfLinkedDiagram(entry, config);

		if(linkedDiagram == null || linkedDiagram.getRootElement().size() == 0) {
			return;
		}

		/*
		 * Handle call activity
		 */
		if(baseElement instanceof CallActivity) {
			CallActivity ca = (CallActivity) baseElement;

			/*
			 * Assign called process as called element
			 */
			for(BaseElement rootEl : linkedDiagram.getRootElement()) {
				if(rootEl instanceof Process) {
					Process p = (Process) rootEl;
					ca.setCalledElement(p);
					break;
				}
			}

			if(linkedDiagram.getDiagram().size() > 0) {
				ca._diagramElement = linkedDiagram.getDiagram().get(0);
			}

			return;
		}

		/*
		 * Handle sub process
		 */

		SubProcess subProcess = (SubProcess) baseElement;
		for(BaseElement rootEl : linkedDiagram.getRootElement()) {
			if(rootEl instanceof Process) {
				Process p = (Process) rootEl;
				subProcess.getFlowElement().addAll(p.getFlowElement());
				subProcess.getArtifact().addAll(p.getArtifact());
			}
		}

		/* Retrieve diagram elements */
		for(FlowElement element : subProcess.getFlowElement()) {
			subProcess._diagramElements.add(element._diagramElement);

//			if(element instanceof SubProcess) {
//				subProcess._diagramElements.addAll(((SubProcess) element)._diagramElements);
//			}
		}

		for(Artifact artifact : subProcess.getArtifact()) {
			subProcess._diagramElements.add(artifact._diagramElement);
		}

	}

	/**
	 * Calculation the BPMN 2.0 Definitions element of the linked diagram.
	 *
	 * @return
	 */
	protected static Definitions retrieveDefinitionsOfLinkedDiagram(String url, Configuration configuration) {
		int lastSlashIndex = url.lastIndexOf("/");
		LinkedModel linkedModel = configuration.getLinkedModels().get(url.substring(lastSlashIndex + 1));
		if(linkedModel == null || linkedModel.getDiagram() == null || !linkedModel.getDiagram().getStencilsetRef().getNamespace().matches("http://b3mn\\.org/stencilset/bpmn2\\.0.*")) {
			return null;
		}

		Diagram2BpmnConverter converter = new Diagram2BpmnConverter(linkedModel.getLinkedModels(), linkedModel.getDiagram(), AbstractBpmnFactory.getFactoryClasses());

		try {
			return converter.getDefinitionsFromDiagram();
		} catch (BpmnConverterException e) {
			e.printStackTrace();
			return null;
		}
	}

}


text:
categories:
- tumblr
- archive
- link
date: 2009-03-21T03:29:53Z
link: http://improveverywhere.com/2009/03/18/subway-art-gallery-opening/
title: Subway Art Gallery Opening at Improv Everywhere
url: /2009/03/21/link-subway-art-gallery-opening-at-improv-everywhere/
---

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import

# Import python libs
from StringIO import StringIO

# Import salt libs
import salt.utils.templates
from salt.exceptions import SaltRenderError

def render(template_file, env='', sls='', context=None, tmplpath=None, **kws):
    '''
    Render the template_file, passing the functions and grains into the
    Mako rendering system.

    :rtype: string
    '''
    tmp_data = salt.utils.templates.MAKO(template_file, to_str=True,
                    salt=__salt__,
                    grains=__grains__,
                    opts=__opts__,
                    pillar=__pillar__,
                    env=env,
                    sls=sls,
                    context=context,
                    tmplpath=tmplpath,
                    **kws)
    if not tmp_data.get('result', False):
        raise SaltRenderError(tmp_data.get('data',
            'Unknown render error in mako renderer'))
    return StringIO(tmp_data['data'])


text:
var context = "";

function describe(message) {
  return `${context} ${message}`;
}

function should(msg) {
  return `${context} should ${msg}`;
}


text:
template <typename VERTEX_LABEL, typename EDGE_LABEL> class ELGraph;
template <typename VERTEX_LABEL, typename EDGE_LABEL> class ELEdge;

template <typename VERTEX_LABEL, typename EDGE_LABEL>
class ELVertex {
public:
  ELVertex(ELGraph<VERTEX_LABEL, EDGE_LABEL>* graph, int index, VERTEX_LABEL label) {
    assert(graph != nullptr);
    assert(index >= 0);
    _graph = graph;
    _index = index;
    _label = label;
  }

  int index() {
    return _index;
  }

  VERTEX_LABEL label() {
    return _label;
  }

  void set_label(VERTEX_LABEL label) {
    _label = label;
  }

  // Return a pointer to the edge connecting this with v, or nullptr
  // if no such edge exists.
  ELEdge<VERTEX_LABEL, EDGE_LABEL>* connector(ELVertex<VERTEX_LABEL, EDGE_LABEL>* v);

  // Return true if v is connected to this vertex by a single edge.
  bool is_adjacent(ELVertex<VERTEX_LABEL, EDGE_LABEL>* v) {
    return (connector(v) != nullptr);
  }

  // Return a list of all edges incident to this vertex.
  std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>* incident_list();

private:
  // We need a pointer to the whole graph so connector() and
  // incident_list() can access the edge list.
  ELGraph<VERTEX_LABEL, EDGE_LABEL> *_graph;

  int _index;
  VERTEX_LABEL _label;
};

template <typename VERTEX_LABEL, typename EDGE_LABEL>
class ELEdge {
public:
  ELEdge(ELVertex<VERTEX_LABEL, EDGE_LABEL> *s,
	 ELVertex<VERTEX_LABEL, EDGE_LABEL> *t,
	 EDGE_LABEL label) {
    assert(s != nullptr);
    assert(t != nullptr);
    assert(s != t);
    _s = s;
    _t = t;
    _label = label;
  }

  ELVertex<VERTEX_LABEL, EDGE_LABEL>* s() {
    return _s;
  }

  ELVertex<VERTEX_LABEL, EDGE_LABEL>* t() {
    return _t;
  }

  EDGE_LABEL label() {
    return _label;
  }

  void set_label(EDGE_LABEL label) {
    _label = label;
  }

  bool is_incident(ELVertex<VERTEX_LABEL, EDGE_LABEL> *v) {
    return (v == _s) || (v == _t);
  }

  ELVertex<VERTEX_LABEL, EDGE_LABEL>* opposite(ELVertex<VERTEX_LABEL, EDGE_LABEL>* v) {
    assert(is_incident(v));
    if (v == _s) {
      return _t;
    } else {
      return _s;
    }
  }

private:
  ELVertex<VERTEX_LABEL, EDGE_LABEL> *_s, *_t;
  EDGE_LABEL _label;
};

template <typename VERTEX_LABEL, typename EDGE_LABEL>
class ELGraph {
  friend class ELVertex<VERTEX_LABEL, EDGE_LABEL>;
public:
  ELGraph() { }

  ~ELGraph() {
    clear();
  }

  std::list<ELVertex<VERTEX_LABEL, EDGE_LABEL>*> vertex_list() {
    // copy the whole vertex list
    return new std::list<ELVertex<VERTEX_LABEL, EDGE_LABEL>*>(_vertices);
  }

  std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*> edge_list() {
    // copy the whole edge list
    return new std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>(_edges);
  }

  ELVertex<VERTEX_LABEL, EDGE_LABEL>* add_vertex(int index, VERTEX_LABEL label) {
    ELVertex<VERTEX_LABEL, EDGE_LABEL>* v = new ELVertex<VERTEX_LABEL, EDGE_LABEL>(this, index, label);
    _vertices.push_back(v);
    return v;
  }

  void erase_vertex(ELVertex<VERTEX_LABEL, EDGE_LABEL> *v) {
    // remove v from the vertex list
    _vertices.remove(v);

    // remove any edge incident to v from the edge list
    typename std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>::iterator i = _edges.begin();
    while (i != _edges.end()) {
      if (i->is_incident(v)) {
	delete *i;
	i = _edges.erase(i);
      } else {
	++i;
      }
    }

    // finally delete the vertex object itself
    delete v;
  }

  ELEdge<VERTEX_LABEL, EDGE_LABEL>* add_edge(ELVertex<VERTEX_LABEL, EDGE_LABEL> *s,
					     ELVertex<VERTEX_LABEL, EDGE_LABEL> *t,
					     EDGE_LABEL label) {
    ELEdge<VERTEX_LABEL, EDGE_LABEL> *e = new ELEdge<VERTEX_LABEL, EDGE_LABEL>(s, t, label);
    _edges.push_back(e);
    return e;
  }

  void erase_edge(ELEdge<VERTEX_LABEL, EDGE_LABEL>* e) {
    _edges.remove(e);
    delete e;
  }

  void clear() {
    // Delete each vertex object.
    for (typename std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>::iterator i = _vertices.begin();
	 i != _vertices.end();
	 ++i) {
      delete *i;
    }

    // Delete each edge object.
    for (typename std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>::iterator i = _edges.begin();
	 i != _edges.end();
	 ++i) {
      delete *i;
    }

    // Clear the lists (which now contain dangling pointers).
    _vertices.clear();
    _edges.clear();
  }

private:
  std::list<ELVertex<VERTEX_LABEL, EDGE_LABEL>*> _vertices;
  std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*> _edges;
};

template <typename VERTEX_LABEL, typename EDGE_LABEL>
ELEdge<VERTEX_LABEL, EDGE_LABEL>* ELVertex<VERTEX_LABEL, EDGE_LABEL>::connector(ELVertex<VERTEX_LABEL, EDGE_LABEL>* v) {
  assert(v != nullptr);
  for (typename std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>::iterator i = _graph->_edges.begin();
       i != _graph->_edges.end();
       ++i) {
    if (i->is_incident(this) && i->is_incident(v)) {
      return *i;
    }
  }
  return nullptr;
}

template <typename VERTEX_LABEL, typename EDGE_LABEL>
std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>* ELVertex<VERTEX_LABEL, EDGE_LABEL>::incident_list() {
  std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>* result = new std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>();
  for (typename std::list<ELEdge<VERTEX_LABEL, EDGE_LABEL>*>::iterator i = _graph->_edges.begin();
       i != _graph->_edges.end();
       ++i) {
    if (i->is_incident(this)) {
      result->push_back(*i);
    }
  }
  return result;
}


text:
@interface Water : GameObject {
    GLRenderObject* body;

    CGPoint body_tex_offset[4];
    float bwidth,bheight,offset_ct;

    BOOL activated;

    FishGenerator *fishes;
}

+(Water*)cons_x:(float)x y:(float)y width:(float)width height:(float)height;

@end


text:
const path = require('path');
const neodoc = require('neodoc');
const assert = require('assert');
const TypeCheck = require('js-typecheck');
const Inputs = require('../Inputs');
const Settings = require('../../Settings');
const Handler = require('../../Handler');
const Reader = require('../../Reader');

// symbols used for private instance variables to avoid any potential clashing
// caused by re-implementations
const _args = Symbol('args');

/**
 * Command-line arguments reader.
 *
 * This reader is used by the {@link CommandLine} handler. It supports most of
 * the docopt specification. Also, if the reader finds an error it's capable of
 * reporting it in user-friendly way. This is used to report `-h/--help` and
 * missing arguments.
 *
 * All serializable inputs are supported by this handler, they can be displayed
 * either as `argument` or `option` element. This is done by setting the input
 * property `cliElementType` (option is the default one).
 *
 * You can define the description displayed in the help of the element by
 * setting the input property `description`.
 *
 * The `option` elements support `short option` by setting the input property
 * `cliShortOption`.
 *
 * In order to accommodate how vector values are represented in a command-line
 * interface, this reader expects vector elements to be separated by
 * the space character.
 *
 * Any {@link Bool} input specified as an `option` element behaves in a
 * special mode, since it's thread as a toogle option in command-line.
 * Therefore if the Bool input is assigned with a `true` then the option
 * gets the prefix `no-`.
 *
 * When a value is found for the input, it gets loaded via {@link Input.parseValue}
 * where each input implementation has its own way of parsing the serialized data,
 * to find out about how a value is serialized for an specific input type you could simply
 * set an arbitrary value to the input you are interested then query it back through
 * {@link Input.serializeValue}. Also, Oca provides a reference datasheet
 * about the serialization forms for the inputs bundled with it, found at {@link Reader}.
 *
 *
Options Summary

 *
 * Option Name | Description | Default Value
 * --- | --- | :---:
 * description | description about the program displayed at the header of the help \
 * | ::none::
 * parsingErrorStatusCode | Custom error status code used to identify when the \
 * command-line args could not be parsed | `700`
 *
 * @see http://docopt.org
 */
class CommandLineArgs extends Reader{

  /**
   * Creates a reader
   *
   * @param {Action} action - action that should be used by the reader
   * @param {Array<string>} args - list of command-line arguments that should be used by
   * the reader
   */
  constructor(action){
    super(action);

    // default options
    this.setOption('description', '');
    this.setOption('parsingErrorStatusCode', 700);
  }

  /**
   * Sets a list of argument values used by the reader. It must follow
   * the same pattern found at `process.argv`
   *
   * @param {Array<string>} value - argument list
   */
  setArgs(value){
    assert(TypeCheck.isList(value), 'value needs to be a list');
    assert(value.length >= 2, 'missing first argument process.execPath and second argument javaScript file being executed');

    this[_args] = value.slice(0);
  }

  /**
   * Returns a list of args used by the reader, by default it uses
   * `process.argv`.
   *
   * @return {Array<string>}
   */
  args(){
    return this[_args];
  }

  /**
   * Returns the executable name based on the args
   *
   * @return {string}
   */
  executableName(){
    return path.basename(this.args()[1]);
  }

  /**
   * Implements the command-line reader
   *
   * @param {Array<Input>} inputList - Valid list of inputs that should be used for
   * the parsing
   * @return {Promise<Object>}
   * @protected
   */
  async _perform(inputList){
    const helpElements = await this.constructor._helpElements(inputList);
    const helpString = await this._helpInterface(helpElements);

    let parsedArgs = Object.create(null);
    // it thrown an exception if something went wrong (like missing a required parameter)
    try{
      parsedArgs = neodoc.run(helpString, {
        argv: this.args().slice(2),
        dontExit: true,
        smartOptions: true,
        repeatableOptions: true,
        version: Settings.get('apiVersion'),
      });
    }
    catch(err){
      // adding a custom status code for the parsing error
      // the error does not come as an instance of error, for this reason
      // creating a new error and copying the contents
      const error = Object.assign(new Error(), err);
      error.status = this.option('parsingErrorStatusCode');
      throw error;
    }

    // however when the user asks for the help it does not raises an exception
    if ('.help' in parsedArgs){
      const error = new Error(parsedArgs['.help']);
      error.status = this.option('parsingErrorStatusCode');
      throw error;
    }

    for (const input of inputList){
      if (input instanceof Inputs.Bool && !input.isVector()){
        input.setValue(Boolean(input.value()));
      }
    }

    const alreadyParsed = [];
    const result = Object.create(null);

    // collecting the input values
    for (const elementName in parsedArgs){
      let foundInputName;

      // finding the input name
      for (const elementType in helpElements){
        for (const inputName in helpElements[elementType]){
          const inputData = helpElements[elementType][inputName];
          if (inputData.usageDisplay.split('=')[0] === elementName || inputData.shortOption === elementName){
            foundInputName = inputName;
            break;
          }
        }

        if (foundInputName){
          break;
        }
      }

      // querying the input value
      const inputNames = inputList.map(x => x.name());
      if (foundInputName && !alreadyParsed.includes(foundInputName)){
        alreadyParsed.push(foundInputName);

        const input = inputList[inputNames.indexOf(foundInputName)];

        let value;
        if (TypeCheck.isBool(parsedArgs[elementName]) && !input.isVector()){
          value = String(!input.value());
        }
        else{
          if (input.isVector() && !TypeCheck.isList(parsedArgs[elementName])){
            value = [parsedArgs[elementName]];
          }
          else{
            value = parsedArgs[elementName];
          }
        }
        result[foundInputName] = value;
      }
    }

    return result;
  }

  /**
   * Returns an object containing the elements that can be used by the commandLine
   *
   * @param {Array<Input>} inputList - list of input that should be used to build
   * query the help
   * @return {Object}
   * @private
   */
  static async _helpElements(inputList){

    const elements = {
      argument: {},
      option: {},
    };

    // building inputs
    const addedArgs = [];
    const descriptions = await Promise.all(inputList.map(x => this._computeInfoDisplay(x)));

    let currentIndex = 0;
    for (const input of inputList){

      const inputName = input.name();
      let argName = this._camelCaseToArgument(inputName);

      // in case of a boolean input that is true by default adding
      // the `no` prefix to the input name automatically. For boolean inputs they
      // work as toggles when represented through the command line
      if (input instanceof Inputs.Bool && !input.isVector() && input.value()){
        argName = `no-${argName}`;
      }

      assert(!addedArgs.includes(argName), `Ambiguous argument name (${argName}), used multiple times!`);
      addedArgs.push(argName);

      const elementType = input.property('cliElementType');

      const inputData = Object.create(null);
      inputData.description = descriptions[currentIndex];
      inputData.elementDisplay = this._elementDisplay(argName, input);
      inputData.usageDisplay = this._usageDisplay(argName, input);
      inputData.required = ((input.isRequired() && input.isEmpty()) && !(input instanceof Inputs.Bool && !input.isVector()));
      inputData.vector = input.isVector();

      if (elementType === 'option'){
        inputData.shortOptionDisplay = this._shortOptionDisplay(input);
        inputData.shortOption = this._shortOption(input);
      }

      elements[elementType][inputName] = inputData;

      currentIndex++;
    }

    return elements;
  }

  /**
   * Returns the help interface displayed when `-h\--help` is required
   *
   * @param {Object} elements - elements holder object
   * @return {string}
   * @private
   */
  _helpInterface(elements){
    let output = '';

    output += this._buildDescription(elements);
    output += this._buildUsage(elements);
    output += this.constructor._buildColumns(elements);

    return output;
  }

  /**
   * Returns a string containing the full assembled info for the input
   *
   * @param {Input} input - input that should be used
   * @return {Promise<string>}
   * @private
   */
  static async _computeInfoDisplay(input){
    let description = input.property('description') || '';
    const inputTypeName = input.property('type');

    // adding the value type to the argument
    const isBoolInput = input instanceof Inputs.Bool;
    if ((isBoolInput && input.isVector()) || !isBoolInput){

      // adding the default value as part of the description
      if (!input.isEmpty()){
        let serializedValue = await input.serializeValue();
        serializedValue = (input.isVector()) ? JSON.parse(serializedValue) : [serializedValue];
        const defaultValue = [];

        for (const value of serializedValue){

          if (TypeCheck.isString(value) && isNaN(value)){
            const scapedValue = value.replace(new RegExp('"', 'g'), '\\"');
            defaultValue.push(`"${scapedValue}"`);
          }
          else{
            defaultValue.push(value);
          }
        }

        if (description.length){
          description += ' ';
        }
        description += `[default: ${defaultValue.join(' ')}]`;
      }
    }

    const inputTypeDisplay = input.isVector() ? `${inputTypeName}[]` : inputTypeName;

    if (description.length){
      description += ' ';
    }
    description += `(${inputTypeDisplay} type).`;

    return description;
  }

  /**
   * Returns a string containing the full element display for either an option
   * or argument
   *
   * @param {string} name - element given name
   * @param {Input} input - input that should be used
   * @return {string}
   * @private
   */
  static _elementDisplay(name, input){

    let result = '';

    if (input.property('cliElementType') === 'option'){
      const shortOption = this._shortOptionDisplay(input);

      const isBoolInput = input instanceof Inputs.Bool;
      if ((isBoolInput && input.isVector()) || !isBoolInput){

        // adding short option
        if (shortOption){
          result += shortOption;

          if (input.isVector()){
            result += '...';
          }

          result += ', ';
        }

        result += this._usageDisplay(name, input);

        if (input.isVector()){
          result += '...';
        }
      }
      else{
        if (shortOption){
          result += shortOption;
          result += ', ';
        }

        result += this._usageDisplay(name, input);
      }
    }
    else{
      result = name;
    }

    return result;
  }

  /**
   * Returns a string containing the usage display for either
   * the option or argument
   *
   * @param {string} name - how the element should be called
   * @param {Input} input - input that should be used
   * @return {string}
   * @private
   */
  static _usageDisplay(name, input){
    let result = '';

    if (input.property('cliElementType') === 'option'){
      // adding long option
      result = `--${name}`;

      const isBoolInput = input instanceof Inputs.Bool;
      if ((isBoolInput && input.isVector()) || !isBoolInput){
        result = `${result}=<value>`;
      }
    }
    else{
      result = `<${name}>`;
    }

    return result;
  }

  /**
   * Returns a string containing the the short option, in case the input
   * does not have a short option property defined then null is returned instead
   *
   * @param {Input} input - input that should be used
   * @return {string|null}
   * @private
   */
  static _shortOption(input){
    const shortOption = input.property('cliShortOption');
    if (shortOption){
      return `-${shortOption}`;
    }

    return null;
  }

  /**
   * Returns a string containing the display of the short option,
   * This is used when listing the element options
   *
   * @param {Input} input - input that should be used
   * @return {string}
   * @private
   */
  static _shortOptionDisplay(input){
    let result = this._shortOption(input);
    if (result && !(input instanceof Inputs.Bool && !input.isVector())){
      result = `${result}=<value>`;
    }

    return result;
  }

  /**
   * Returns a string containing the description of the command
   *
   * @param {Object} elements - elements holder object
   * @return {string}
   * @private
   */
  _buildDescription(elements){
    let output = '';
    const description = this.option('description');
    if (description.length){
      output += description;
      if (!description.endsWith('.')){
        output += '.';
      }
      output += '\n\n';
    }

    return output;
  }

  /**
   * Builds a string containing the usage
   *
   * @param {Object} elements - elements holder object
   * @return {string}
   * @private
   */
  _buildUsage(elements){
    let output = '';

    output += `Usage: ${this.executableName()} `;

    const requiredArguments = Object.create(null);
    const optionalArguments = Object.create(null);
    const requiredOptions = Object.keys(elements.option).filter(x => elements.option[x].required);
    let requiredArgumentsOrder = [];
    let optionalArgumentsOrder = [];

    if (requiredOptions.length){
      output += requiredOptions.map(x => elements.option[x].usageDisplay).join(' ');
      output += ' ';
    }
    output += '[options]';

    // building arguments
    if (Object.keys(elements.argument).length){
      for (const inputName in elements.argument){
        if (elements.argument[inputName].required){
          requiredArguments[inputName] = elements.argument[inputName];
        }
        else{
          optionalArguments[inputName] = elements.argument[inputName];
        }
      }

      const requiredArgumentNames = Object.keys(requiredArguments);
      requiredArgumentsOrder = requiredArgumentNames.filter(x => !requiredArguments[x].vector);
      requiredArgumentsOrder = requiredArgumentsOrder.concat(requiredArgumentNames.filter(x => !requiredArgumentsOrder.includes(x)));

      // first adding the required arguments
      let hasVectorRequiredArgument = false;
      for (const inputName of requiredArgumentsOrder){
        output += ' ';
        output += requiredArguments[inputName].usageDisplay;

        if (requiredArguments[inputName].vector && Object.keys(optionalArguments).length === 0){
          if (requiredArgumentsOrder.indexOf(inputName) === requiredArgumentsOrder.length - 1){
            output += '...';
            hasVectorRequiredArgument = true;
          }
        }
      }

      // then adding the optional ones
      const optionalArgumentNames = Object.keys(optionalArguments);
      optionalArgumentsOrder = optionalArgumentNames.filter(x => !optionalArguments[x].vector);
      optionalArgumentsOrder = optionalArgumentsOrder.concat(optionalArgumentNames.filter(x => !optionalArgumentsOrder.includes(x)));

      for (const inputName in optionalArguments){
        output += ' [';
        output += optionalArguments[inputName].usageDisplay;
        output += ']';

        if (optionalArguments[inputName].vector && !hasVectorRequiredArgument){
          if (optionalArgumentsOrder.indexOf(inputName) === optionalArgumentsOrder.length - 1){
            output += '...';
          }
        }
      }
    }

    output += this._buildUsageVectorOptions(elements, requiredArgumentsOrder, requiredOptions);

    return output;
  }

  /**
   * Builds a string containing the usage for the vector options
   *
   * @param {Object} elements - elements holder object
   * @param {Array<string>} argumentNames - list of argument names
   * @param {Array<string>} requiredOptionNames - list of required option names
   * @return {string}
   * @private
   */
  _buildUsageVectorOptions(elements, argumentNames, requiredOptionNames){
    let output = '';

    // adding the usage for the vector options
    for (const inputName in elements.option){

      if (elements.option[inputName].vector){
        output += `\n       ${this.executableName()} `;

        for (const requiredArg of argumentNames){
          output += elements.argument[requiredArg].usageDisplay;
          output += ' ';
        }

        output += '[options] ';
        if (requiredOptionNames.length){
          output += requiredOptionNames.filter(y => y !== inputName).map(x => elements.option[x].usageDisplay).join(' ');
          output += ' ';
        }

        if (!requiredOptionNames.includes(inputName)){
          output += '[';
        }

        output += elements.option[inputName].usageDisplay;
        output += '...';

        if (!requiredOptionNames.includes(inputName)){
          output += ']';
        }
      }
    }

    return output;
  }

  /**
   * Builds a string containing the columns displayed by the arguments and options
   *
   * @param {Object} elements - elements holder object
   * @return {string}
   * @private
   */
  static _buildColumns(elements){
    let columns = '\n';
    const elementTypeDisplayName = Object.create(null);
    elementTypeDisplayName.option = 'Options:';
    elementTypeDisplayName.argument = 'Arguments:';

    // figuring out the element column width
    const elementTypeWidth = this._computeElementsWidth(elements);

    for (const element in elements){

      if (Object.keys(elements[element]).length){
        columns += '\n';
        columns += elementTypeDisplayName[element];
        columns += '\n';

        for (const inputName in elements[element]){

          const elementData = elements[element][inputName];

          // element
          columns += '  ';
          columns += elementData.elementDisplay;
          columns += ' '.repeat(elementTypeWidth[element] - elementData.elementDisplay.length);

          // description
          // the second separator is actually a `hair space` char, this is necessary to separate
          // the element from the description in neodoc
          columns += '  ';
          columns += elementData.description;
          columns += '\n';
        }
      }
    }

    return columns;
  }

  /**
   * Returns a plain object containing the width for each of the element types
   * (argument and option)
   *
   * @param {Object} elements - elements holder object
   * @return {Object}
   * @private
   */
  static _computeElementsWidth(elements){
    const elementTypeWidth = Object.create(null);
    for (const elementType in elements){
      for (const inputName in elements[elementType]){
        elementTypeWidth[elementType] = Math.max(elementTypeWidth[elementType] || 0,
          elements[elementType][inputName].elementDisplay.length);
      }
    }

    return elementTypeWidth;
  }

  /**
   * Converts the input text from camelCase to dash-convention used
   * in CLI applications
   *
   * @param {string} text - text that should be converted
   * @return {string}
   * @private
   */
  static _camelCaseToArgument(text){
    return text.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  }
}

// registering reader
Handler.registerReader(CommandLineArgs, 'commandLine');

module.exports = CommandLineArgs;


text:
package org.bridje.sql.impl;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bridje.sql.Column;
import org.bridje.sql.ForeignKey;
import org.bridje.sql.Index;
import org.bridje.sql.SQLDialect;
import org.bridje.sql.SQLStatement;
import org.bridje.sql.Schema;
import org.bridje.sql.Table;

class SchemaClearer
{
    private static final Logger LOG = Logger.getLogger(SchemaClearer.class.getName());

    private final Connection connection;

    private final Schema schema;

    private final SQLDialect dialect;

    public SchemaClearer(Connection connection, SQLDialect dialect, Schema schema)
    {
        this.dialect = dialect;
        this.connection = connection;
        this.schema = schema;
    }

    public void doClear() throws SQLException
    {
        clearForeignKeys(connection, schema.getForeignKeys());
        clearIndexes(connection, schema.getIndexes());
        clearTables(connection, schema.getTables());
    }

    private void clearTables(Connection connection, Table[] tables) throws SQLException
    {
        for (Table table : tables)
        {
            clearForeignKeys(connection, table);
        }

        for (Table table : tables)
        {
            clearTable(connection, table);
        }
    }

    private void clearIndexes(Connection connection, Index[] indexes) throws SQLException
    {
        for (Index index : indexes)
        {
            clearIndex(connection, index);
        }
    }

    private void clearForeignKeys(Connection connection, ForeignKey[] foreignKeys) throws SQLException
    {
        for (ForeignKey fk : foreignKeys)
        {
            clearForeignKey(connection, fk);
        }
    }

    private void clearTable(Connection connection, Table table) throws SQLException
    {
        DatabaseMetaData metaData = connection.getMetaData();
        if(tableExists(metaData, table))
        {
            clearIndexes(connection, table.getIndexes());
            createTable(connection, table);
        }
    }

    private void clearForeignKeys(Connection connection, Table table) throws SQLException
    {
        clearForeignKeys(connection, table.getForeignKeys());
    }

    private boolean tableExists(DatabaseMetaData metadata, Table table) throws SQLException
    {
        try (ResultSet resultSet = metadata.getTables(null, null, table.getName(), null))
        {
            if (resultSet.next()) return true;
        }
        return false;
    }

    private void createTable(Connection connection, Table table) throws SQLException
    {
        try
        {
            List<Object> params = new ArrayList<>();
            String sql = dialect.dropTable(table, params);
            SQLStatement sqlStmt = new SQLStatementImpl(null, sql, params.toArray(), false);
            executeStmt(connection, sqlStmt);
        }
        catch (SQLException e)
        {
            LOG.log(Level.SEVERE, String.format("Could not create table %s.", table.getName()), e);
        }
    }

    private void clearIndex(Connection connection, Index index) throws SQLException
    {
        DatabaseMetaData metadata = connection.getMetaData();
        if(indexExists(metadata, index))
        {
            try
            {
                List<Object> params = new ArrayList<>();
                String sql = dialect.dropIndex(index, params);
                SQLStatement sqlStmt = new SQLStatementImpl(null, sql, new Object[0], false);
                executeStmt(connection, sqlStmt);
            }
            catch (SQLException e)
            {
                LOG.log(Level.SEVERE, String.format("Could not create index %s on table %s.", index.getName(), index.getTable().getName()), e);
            }
        }
    }

    private boolean indexExists(DatabaseMetaData metadata, Index index) throws SQLException
    {
        List<String> columnNames = new ArrayList<>();
        for (Column<?, ?> column : index.getColumns())
        {
            columnNames.add(column.getName());
        }
        Map<String, List<String>> idxMap = new HashMap<>();
        try (ResultSet resultSet = metadata.getIndexInfo(null, null, index.getTable().getName(), false, true))
        {
            while (resultSet.next())
            {
                String indexName = resultSet.getString("INDEX_NAME");
                String colName = resultSet.getString("COLUMN_NAME");
                List<String> lst = idxMap.get(indexName);
                if(lst == null)
                {
                    lst = new ArrayList<>();
                    idxMap.put(indexName, lst);
                }
                lst.add(colName);
            }
        }
        return idxMap.values()
                    .stream()
                    .filter( v -> Arrays.equals(v.toArray(), columnNames.toArray()))
                    .count() >= 1;
    }

    private void clearForeignKey(Connection connection, ForeignKey fk) throws SQLException
    {
        DatabaseMetaData metadata = connection.getMetaData();
        if(foreignKeyExists(metadata, fk))
        {
            try
            {
                List<Object> params = new ArrayList<>();
                String sql = dialect.dropForeignKey(fk, params);
                SQLStatement sqlStmt = new SQLStatementImpl(null, sql, new Object[0], false);
                executeStmt(connection, sqlStmt);
            }
            catch (SQLException e)
            {
                LOG.log(Level.SEVERE, String.format("Could not create foreign key %s on table %s.", fk.getName(), fk.getTable().getName()), e);
            }
        }
    }

    private boolean foreignKeyExists(DatabaseMetaData metadata, ForeignKey fk) throws SQLException
    {
        try (ResultSet resultSet = metadata.getExportedKeys(null, null, fk.getReferences().getName()))
        {
            while (resultSet.next())
            {
                String fkTableName = resultSet.getString("FKTABLE_NAME");
                if(fk.getTable().getName().equals(fkTableName))
                {
                    return true;
                }
            }
        }
        return false;
    }

    private PreparedStatement prepareStatement(Connection cnn, SQLStatement sqlStmt) throws SQLException
    {
        PreparedStatement stmt;
        if(sqlStmt.isWithGeneratedKeys())
        {
            stmt = cnn.prepareStatement(sqlStmt.getSQL(), Statement.RETURN_GENERATED_KEYS);
        }
        else
        {
            stmt = cnn.prepareStatement(sqlStmt.getSQL());
        }

        Object[] params = sqlStmt.getParameters();
        for (int i = 0; i < params.length; i++)
        {
            stmt.setObject(i+1, params[i]);
        }
        return stmt;
    }

    private int executeStmt(Connection cnn, SQLStatement sqlStmt) throws SQLException
    {
        LOG.log(Level.INFO, sqlStmt.getSQL());
        try(PreparedStatement stmt = prepareStatement(cnn, sqlStmt))
        {
            return stmt.executeUpdate();
        }
    }
}


text:
const webpack = require('webpack');
const config = require('../webpack.config');
const compiler = webpack(config);
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

module.exports = (app) =>{

	app.use(webpackDevMiddleware(compiler, {
	  publicPath: config.output.publicPath,
	  stats: {
	    colors: true
	  },
	  noInfo: true
	}));

	app.use(webpackHotMiddleware(compiler, {
	    log: console.log
	}));

};


text:
/** The filter parameters for set filter */

module awk.grid {

    export interface SetFilterParameters {

        /** Same as cell renderer for grid (you can use the same one in both locations). Setting it separatly here allows for the value to be rendered differently in the filter. */
        cellRenderer ?: Function;

        /** The height of the cell. */
        cellHeight ?: number;

        /** The values to display in the filter. */
        values ?: any;

        /**  What to do when new rows are loaded. The default is to reset the filter, as the set of values to select from can have changed. If you want to keep the selection, then set this value to 'keep'. */
        newRowsAction ?: string;

        /** If true, the filter will not remove items that are no longer availabe due to other filters. */
        suppressRemoveEntries ?: boolean;
    }

}


text:
'use strict';
module.exports = function(sequelize, DataTypes) {
  var Project = sequelize.define('Project', {
    title: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        Project.hasMany(models.Sprint, {
          as: 'sprints',
          foreignKey: {
            name: 'project_id',
            allowNull: false
          },
          onDelete: 'CASCADE'
        });

        Project.hasMany(models.Ticket, {
          as: 'tickets',
          foreignKey: {
            name: 'project_id',
            allowNull: false
          },
          onDelete: 'CASCADE'
        });

        Project.belongsTo(models.User, {
          as: 'creator',
          foreignKey: {
            name: 'creator_id',
            allowNull: true
          }
        });
      }
    }
  });
  return Project;
};


text:
package org.apereo.portal.events.tincan.converters;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import java.util.List;
import java.util.Locale;
import org.apereo.portal.events.PortalEvent;
import org.apereo.portal.events.PortletExecutionEvent;
import org.apereo.portal.events.aggr.portlets.AggregatedPortletLookupDao;
import org.apereo.portal.events.aggr.portlets.AggregatedPortletMapping;
import org.apereo.portal.events.tincan.om.LocalizedString;
import org.apereo.portal.events.tincan.om.LrsObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;

/**
 * Generic xApi converter for PortletExecutionEvents.
 *
 * @author Josh Helmer, jhelmer@unicon.net
 */
public class PortletExecutionEventConverter extends AbstractPortalEventToLrsStatementConverter {
    private AggregatedPortletLookupDao aggregatedPortletLookupDao;
    private List<Class<? extends PortletExecutionEvent>> supportedEventTypes;
    private List<String> filterFNames;
    private FNameFilterType fnameFilterType = FNameFilterType.Blacklist;

    @Required
    public void setSupportedEventTypes(
            List<Class<? extends PortletExecutionEvent>> supportedEventTypes) {
        this.supportedEventTypes = supportedEventTypes;
    }

    public void setFilterFNames(List<String> filterFNames) {
        this.filterFNames = filterFNames;
    }

    public void setFnameFilterType(FNameFilterType fnameFilterType) {
        this.fnameFilterType = fnameFilterType;
    }

    @Autowired
    public void setAggregatedPortletLookupDao(
            final AggregatedPortletLookupDao aggregatedPortletLookupDao) {
        this.aggregatedPortletLookupDao = aggregatedPortletLookupDao;
    }

    @Override
    public boolean supports(PortalEvent event) {
        boolean postEvent = false;
        for (Class<?> cls : supportedEventTypes) {
            if (cls.isAssignableFrom(event.getClass())) {
                postEvent = true;
                break;
            }
        }

        if (postEvent && filterFNames != null) {

            PortletExecutionEvent execEvent = (PortletExecutionEvent) event;
            boolean foundFName = false;
            for (String fname : filterFNames) {
                if (fname != null && fname.equalsIgnoreCase(execEvent.getFname())) {
                    foundFName = true;
                    break;
                }
            }

            postEvent = fnameFilterType == FNameFilterType.Whitelist ? foundFName : !foundFName;
        }

        return postEvent;
    }

    @Override
    protected LrsObject getLrsObject(PortalEvent event) {
        final String fname = ((PortletExecutionEvent) event).getFname();
        final AggregatedPortletMapping mappedPortletForFname =
                this.aggregatedPortletLookupDao.getMappedPortletForFname(fname);

        final Builder<String, LocalizedString> definitionBuilder = ImmutableMap.builder();
        definitionBuilder.put(
                "name", new LocalizedString(Locale.US, mappedPortletForFname.getName()));

        return new LrsObject(
                buildUrn("portlet", fname), getDefaultObjectType(), definitionBuilder.build());
    }

    public static enum FNameFilterType {
        Whitelist,
        Blacklist
    }
}


text:
import os, sys
from _ast import TryExcept
from httplib import EXPECTATION_FAILED
lib_path = os.path.abspath('../all')
sys.path.append(lib_path)

from SetupTest import *
import unittest

class TestCredit(unittest.TestCase):

    def testSimpleCreditWithCard(self):
        credit = litleXmlFields.credit()
        credit.amount = 106
        credit.orderId = "12344"
        credit.orderSource = 'ecommerce'

        card = litleXmlFields.cardType()
        card.type = 'VI'
        card.number = "4100000000000001"
        card.expDate = "1210"
        credit.card = card

        litleXml =  litleOnlineRequest(config)
        response = litleXml.sendRequest(credit)
        self.assertEquals("Approved", response.message)

    def testSimpleCreditWithPaypal(self):
        credit = litleXmlFields.credit()
        credit.amount = 106
        credit.orderId = "123456"
        credit.orderSource = 'ecommerce'

        paypal = litleXmlFields.payPal()
        paypal.payerId = "1234"
        credit.paypal = paypal

        litleXml =  litleOnlineRequest(config)
        response = litleXml.sendRequest(credit)
        self.assertEquals("Approved", response.message)

    def testSimpleCreditWithCardAndSecondaryAmount(self):
        credit = litleXmlFields.credit()
        credit.amount = 106
        credit.secondaryAmount = 10
        credit.orderId = "12344"
        credit.orderSource = 'ecommerce'

        card = litleXmlFields.cardType()
        card.type = 'VI'
        card.number = "4100000000000001"
        card.expDate = "1210"
        credit.card = card

        litleXml =  litleOnlineRequest(config)
        response = litleXml.sendRequest(credit)
        self.assertEquals("Approved", response.message)

    def testsimpleCreditWithTxnAndSecondaryAmount(self):
        credit = litleXmlFields.credit()
        credit.amount = 106
        credit.secondaryAmount = 10
        credit.orderId = "12345"
        credit.orderSource = 'ecommerce'

        card = litleXmlFields.cardType()
        card.type = 'VI'
        card.number = "4100000000000001"
        card.expDate = "1210"
        credit.card = card

        litleXml =  litleOnlineRequest(config)
        response = litleXml.sendRequest(credit)
        self.assertEquals("Approved", response.message)

    def simpleCreditConflictWithTxnAndOrderId(self):
        credit = litleXmlFields.credit()
        credit.orderId = "12344"
        credit.amount = 106
        credit.secondaryAmount = 10
        credit.litleTxnId = "12345"

        litleXml =  litleOnlineRequest(config)
        try:
            response = litleXml.sendRequest(credit)
            self.fail("Litle Txn and Order Id should conflict, fail to throw a exception")
        except Exception:
            self.assertTrue(response.message.startswith("Error validating xml data against the schema"),"Error in validating")

    def testPaypalNotes(self):
        credit = litleXmlFields.credit()
        credit.amount = 106
        credit.orderId = "12344"
        credit.payPalNotes = "Hello"
        credit.orderSource = 'ecommerce'

        card = litleXmlFields.cardType()
        card.type = 'VI'
        card.number = "4100000000000001"
        card.expDate = "1210"
        credit.card = card

        litleXml =  litleOnlineRequest(config)
        response = litleXml.sendRequest(credit)
        self.assertEquals("Approved", response.message)

    def testProcessingInstructionAndAmexData(self):
        credit = litleXmlFields.credit()
        credit.amount = 2000
        credit.orderId = "12344"
        credit.orderSource = 'ecommerce'

        pI = litleXmlFields.processingInstructions()
        pI.bypassVelocityCheck = True
        credit.processingInstructions = pI

        card = litleXmlFields.cardType()
        card.type = 'VI'
        card.number = "4100000000000001"
        card.expDate = "1210"
        credit.card = card

        litleXml =  litleOnlineRequest(config)
        response = litleXml.sendRequest(credit)

        self.assertEquals("Approved", response.message)

def suite():
    suite = unittest.TestSuite()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestCredit)
    return suite

if __name__ =='__main__':
    unittest.main()


text:
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";

    var sampleTitle = "Simple imaging JS sample";

    var scenarios = [
        { url: "/html/scenario1.html", title: "Image properties (FileProperties)" },
        { url: "/html/scenario2.html", title: "Image transforms/encode (BitmapDecoder)" },
    ];

    WinJS.Namespace.define("SdkSample", {
        sampleTitle: sampleTitle,
        scenarios: new WinJS.Binding.List(scenarios)
    });
})();


text:
package com.facebook.buck.core.artifact;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.google.devtools.build.lib.syntax.Printer;
import com.google.devtools.build.lib.syntax.Runtime;
import java.nio.file.Paths;
import org.junit.Test;

public class SourceArtifactImplTest {
  @Test
  public void skylarkFunctionsWork() {
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();

    SourceArtifactImpl artifact =
        ImmutableSourceArtifactImpl.of(PathSourcePath.of(filesystem, Paths.get("foo", "bar.cpp")));

    String expectedShortPath = Paths.get("foo", "bar.cpp").toString();

    assertEquals("bar.cpp", artifact.getBasename());
    assertEquals("cpp", artifact.getExtension());
    assertEquals(Runtime.NONE, artifact.getOwner());
    assertEquals(expectedShortPath, artifact.getShortPath());
    assertTrue(artifact.isSource());
    assertEquals(String.format("<source file '%s'>", expectedShortPath), Printer.repr(artifact));
  }
}


text:
package com.qxcmp.spider;

import com.qxcmp.web.view.annotation.table.EntityTable;
import com.qxcmp.web.view.annotation.table.RowAction;
import com.qxcmp.web.view.annotation.table.TableField;
import com.qxcmp.web.view.modules.form.FormMethod;
import com.qxcmp.web.view.support.Color;
import lombok.Data;
import us.codecraft.webmagic.Spider;

import static com.qxcmp.core.QxcmpConfiguration.QXCMP_ADMIN_URL;

/**
 * 蜘蛛运行时信息
 * <p>
 * 存放了一个正在运行的蜘蛛信息
 *
 * @author aaric
 */
@EntityTable(value = "蜘蛛运行状态", action = QXCMP_ADMIN_URL + "/spider/status", entityIndex = "name",
        rowActions = @RowAction(value = "终止", action = "stop", method = FormMethod.POST, color = Color.RED))
@Data
public class SpiderRuntime {

    @TableField("蜘蛛组")
    private String group;

    @TableField("蜘蛛名称")
    private String name;

    private Spider spider;

    private SpiderPageProcessor spiderPageProcessor;

    public SpiderRuntime(String group, String name, Spider spider, SpiderPageProcessor spiderPageProcessor) {
        this.group = group;
        this.name = name;
        this.spider = spider;
        this.spiderPageProcessor = spiderPageProcessor;
    }
}


text:
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

<?php echo Yii::t('SpaceModule.views_space_requestMembershipSave', "Request space membership"); ?>

                <?php echo Yii::t('SpaceModule.views_space_requestMembershipSave', 'Your request was successfully submitted to the space administrators.'); ?>

            <button type="button" class="btn btn-primary"
                    data-dismiss="modal"><?php echo Yii::t('SpaceModule.views_space_requestMembershipSave', 'Close'); ?></button>


text:
import React from 'react';
import AddFishForm from './AddFishForm';
import base from '../base';

class Inventory extends React.Component {
  constructor() {
    super();
    this.renderInventory = this.renderInventory.bind(this);
    this.renderLogin = this.renderLogin.bind(this);
    this.authenticate = this.authenticate.bind(this);
    this.logout = this.logout.bind(this);
    this.authHandler = this.authHandler.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      uid: null,
      owner: null
    }
  }

  componentDidMount() {
    base.onAuth((user) => {
      if (user) {
        this.authHandler(null, { user });
      }
    })
  }

  handleChange(e, key) {
    const fish = this.props.fishes[key];
    // take a copy of that fish and update it with the new data
    const updatedFish = {
      ...fish,
      [e.target.name]: e.target.value
    };
    this.props.updateFish(key, updatedFish);
  }

  authenticate(provider) {
    console.log(`Trying to log in with ${provider}`);
    base.authWithOAuthPopup(provider, this.authHandler);
  }

  logout() {
    base.unauth();
    this.setState({ uid: null })
  }

  authHandler(err, authData) {
    console.log(authData);
    if (err) {
      console.error(err);
      return;
    }

    // grab the store info
    const storeRef = base.database().ref(this.props.storeId);
    // query the firebase once for the store data
    storeRef.once('value', (snapshot) => {
      const data = snapshot.val() || {};

      // claim it as our own if there is no owner already
      if (!data.owner) {
        storeRef.set({
          owner: authData.user.uid
        });
      }

      this.setState({
        uid: authData.user.uid,
        owner: data.owner || authData.user.uid
      });
    })

  }

  renderLogin() {
    return(

Inventory

Sign in to manage your store's inventory

        <button className="github" onClick={() => this.authenticate('github')}>Log In With Github</button>
        <button className="facebook" onClick={() => this.authenticate('facebook')}>Log In With Facebook</button>
        <button className="twitter" onClick={() => this.authenticate('twitter')}>Log In With Twitter</button>

    )
  }

  renderInventory(key) {
    const fish = this.props.fishes[key];
    return (

        <input type="text" name="name" value={fish.name} placeholder="Fish Name"  onChange={(e) => this.handleChange(e, key)}/>
        <input type="text" name="price" value={fish.price} placeholder="Fish Price" onChange={(e) => this.handleChange(e, key)}/>
        <select name="status" value={fish.status} onChange={(e) => this.handleChange(e, key)}>
          <option value="available">Fresh!</option>
          <option value="unavailable">Sold Out!</option>
        </select>
        <textarea name="desc" value={fish.desc} placeholder="Fish Desc" onChange={(e) => this.handleChange(e, key)}></textarea>
        <input type="text" name="image" value={fish.image} placeholder="Fish Image" onChange={(e) => this.handleChange(e, key)}/>
        <button onClick={() => this.props.removeFish(key)}>Remove Fish</button>

    )
  }

  render() {
    const logout = <button onClick={this.logout}>Log Out!</button>;

    // check if they are not logged in at all
    if(!this.state.uid) {
      return
{this.renderLogin()}

    }

    // check if they are the owner of the current store
    if(this.state.uid !== this.state.owner) {
      return (

Sorry you aren't the owner of this store!

          {logout}

      )
    }

    return (

Inventory

        {logout}
        {Object.keys(this.props.fishes).map(this.renderInventory)}
        {/* pass things down via props, so addFish is on the Inventory props obj*/}
        <AddFishForm addFish={this.props.addFish} />
        <button onClick={this.props.loadSamples}>Load Sample Fishes</button>

    )
  }
}

Inventory.propTypes = {
  fishes: React.PropTypes.object.isRequired,
  updateFish: React.PropTypes.func.isRequired,
  removeFish: React.PropTypes.func.isRequired,
  addFish: React.PropTypes.func.isRequired,
  loadSamples: React.PropTypes.func.isRequired,
  storeId: React.PropTypes.string.isRequired,
}

export default Inventory;


text: Error while reading logfile:  -


text: A set of utilities for use during unit and integration testing.


text:
import { assert, JSData } from '../../_setup'

describe('Mapper#getAdapter', function () {
  it('should get an adapter', function () {
    const Mapper = JSData.Mapper
    const mapper = new Mapper({ name: 'user' })
    assert.equal(typeof mapper.getAdapter, 'function')
    assert.strictEqual(mapper.getAdapter, Mapper.prototype.getAdapter)

    const adapter = {}
    mapper.registerAdapter('foo', adapter)
    mapper.registerAdapter('bar', adapter, { default: true })
    assert.strictEqual(mapper.getAdapter('foo'), adapter)
    assert.strictEqual(mapper.getAdapter('bar'), adapter)
    assert.equal(mapper.defaultAdapter, 'bar')
    assert.throws(() => {
      mapper.getAdapter()
    }, Error, '[Mapper#getAdapter:name] expected: string, found: undefined\nhttp://www.js-data.io/v3.0/docs/errors#400')
  })
})


text:
import java.util.Arrays;
import java.util.List;

public class Collections {
    void test() {
        List<String> x = List.of(null);
        List<String> y = List.of("C", null);
        List<String> z = Arrays.asList(null);
    }
}


text:
import numpy as np
from .executor import Executor

def eval_numerical_grad(f, feed_dict, wrt, h=1e-5):
    wrt_val = feed_dict[wrt]
    grad = np.zeros_like(wrt_val)

    it = np.nditer(wrt_val, flags=['multi_index'], op_flags=['readwrite'])
    while not it.finished:
        ix = it.multi_index
        old_val = wrt_val[ix]
        wrt_val[ix] = old_val + h
        executor = Executor([f])
        feed_dict[wrt] = wrt_val

        result_plus, = executor.run(feed_shapes=feed_dict)
        wrt_val[ix] = old_val - h
        executor = Executor([f])

        feed_dict[wrt] = wrt_val
        result_minus, = executor.run(feed_shapes=feed_dict)

        grad[ix] = np.sum((result_plus - result_minus) / (2.0 * h))

        wrt_val[ix] = old_val
        feed_dict[wrt] = wrt_val
        it.iternext()
    return grad


text:
angular.module('starter', [
	'ionic',
	'ionic.service.core',
	'config',
	'supermodular.common',
	'supermodular.menu',
	'supermodular.home',
	'supermodular.canvasmarque',
	'supermodular.canvasmove',
	'ngCordova'
])

.value('_', window._)

.run(function($ionicPlatform) {
	$ionicPlatform.ready(function() {
		// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
		// for form inputs)

		if (window.cordova && window.cordova.plugins.Keyboard) {
			window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
		}
		if (window.StatusBar) {
			// org.apache.cordova.statusbar required
			StatusBar.styleDefault();
		}
	});
})

.config(function($urlRouterProvider, $compileProvider) {
	$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|blob|cdvfile|content):|data:image\//);
	// if none of the above states are matched, use this as the fallback
	$urlRouterProvider.otherwise('/app/home');
});


text:
A jQuery plugin that makes writing in different markup dialects a doddle.

_This is a work in progress, and currently only the Textile language is being developed._


text:
package midi.pad.ui.widgets;

import midi.pad.ui.Color;
import midi.pad.ui.Graphic;
import midi.pad.ui.Widget;
import midi.pad.ui.event.Event;
import midi.pad.ui.event.PadEvent;
import midi.pad.ui.event.PadEvent.EVENT_TYPE;
import midi.pad.ui.event.Runtime;

/**
 * @author oliver
 *
 */
public class ChannelSelection extends Widget {

	private int currentChannel;
	private final UsedProvider usedProvider;
	private final Runnable pressRunner;

	/**
	 *
	 */
	public ChannelSelection(final int x, final int y, final int currentChannel,
			final UsedProvider usedProvider, final Runnable pressRunner) {
		bounds.x = x;
		bounds.y = y;
		bounds.width = 8;
		bounds.height = 2;
		this.currentChannel = currentChannel;
		this.usedProvider = usedProvider;
		this.pressRunner = pressRunner;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see midi.pad.ui.Widget#paint(midi.pad.ui.Graphic)
	 */
	@Override
	public void paint(final Graphic g) {
		final boolean[] usedMatrix = usedProvider.getUsed();
		for (int y = 0; y < 2; ++y) {
			for (int x = 0; x < 8; ++x) {
				final int chn = y * 8 + x;
				if (chn == currentChannel) {
					g.setPixel(x, y, Color.FULL_GREEN);
				} else if (usedMatrix[chn]) {
					g.setPixel(x, y, Color.FULL_RED);
				} else {
					g.setPixel(x, y, Color.FULL_AMBER);
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see midi.pad.ui.Widget#eventOccured(midi.pad.ui.event.Event)
	 */
	@Override
	public boolean eventOccured(final Event event) {
		if (EVENT_TYPE.PAD_RELEASED.equals(event.getEventType())) {
			final PadEvent padEvent = (PadEvent) event;
			final boolean[] usedMatrix = usedProvider.getUsed();
			final int chn = padEvent.getY() * 8 + padEvent.getX();
			if (!usedMatrix[chn]) {
				usedMatrix[currentChannel] = false;
				usedMatrix[chn] = true;
				currentChannel = chn;
				Runtime.getRuntime().schedule(pressRunner);
			}
		}
		return true;
	}

	/**
	 * @return the currentChannel
	 */
	public int getCurrentChannel() {
		return currentChannel;
	}

	public interface UsedProvider {
		boolean[] getUsed();
	}
}


text:
<?xml version='1.0' encoding='UTF-8' ?>
<beans
		xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:p="http://www.springframework.org/schema/p"
		xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
>

	<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

	<!-- Most controllers will use the ControllerClassNameHandlerMapping above, but for the index controller we are using ParameterizableViewController,
		so we must define an explicit mapping for it. -->
	<bean
			id="urlMapping"
			class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
	>
		<property name="mappings">
			<props>
				<!--<prop key="index.htm">IndexController</prop>-->
				<prop key="three_d_result_fail.htm">ThreeDResultFailController</prop>
				<prop key="three_d_result_success.htm">ThreeDResultSuccessController</prop>
				<prop key="bin_inquiry.htm">BinInquiryController</prop>
				<prop key="api_payment.htm">ApiPaymentController</prop>
				<prop key="one_step_payment.htm">OneStepPaymentController</prop>
				<prop key="payment_inqury.htm">PaymentInquryController</prop>
				<prop key="payment_inqury_with_time.htm">PaymentInquryWithTimeController</prop>
				<prop key="add_card_to_wallet.htm">AddCardToWalletController</prop>
				<prop key="get_card_from_wallet.htm">GetCardFromWalletController</prop>
				<prop key="delete_card_from_wallet.htm">DeleteCardFromWalletController</prop>
				<prop key="api_payment_with_wallet.htm">ApiPaymentWithWalletController</prop>
				<prop key="create_link_payment.htm">CreateLinkPaymentController</prop>
				<prop key="link_payment_list.htm">LinkPaymentListController</prop>
				<prop key="link_payment_delete.htm">LinkPaymentDeleteController</prop>
				<prop key="create_payment_refund.htm">CreatePaymentRefund</prop>
				<prop key="payment_refund_inquiry.htm">PaymentRefundInquiry</prop>
			</props>
		</property>
	</bean>

	<bean
			id="viewResolver"
			class="org.springframework.web.servlet.view.InternalResourceViewResolver"
			p:prefix="/WEB-INF/jsp/"
			p:suffix=".jsp" />

	<!-- The index controller. -->
	<!--<bean
			name="IndexController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="index" /> -->

	<bean
			name="ThreeDResultFailController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="three_d_result_fail" />

	<bean
			name="ThreeDResultSuccessController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="three_d_result_success" />

	<bean
			name="BinInquiryController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="bin_inquiry" />

	<bean
			name="ApiPaymentController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="api_payment" />

	<bean
			name="OneStepPaymentController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="one_step_payment" />
	<bean
			name="CreateLinkPaymentController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="create_link_payment" />
	<bean
			name="LinkPaymentListController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="link_payment_list" />

	<bean
			name="PaymentRefundInquiry"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="payment_refund_inquiry"/>
	<bean
			name="CreatePaymentRefund"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="create_payment_refund"/>

	<bean
			name="LinkPaymentDeleteController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="link_payment_delete" />

	<bean
			name="PaymentInquryController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="payment_inqury" />

	<bean
			name="PaymentInquryWithTimeController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="payment_inqury_with_time" />

	<bean
			name="AddCardToWalletController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="add_card_to_wallet" />

	<bean
			name="GetCardFromWalletController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="get_card_from_wallet" />

	<bean
			name="DeleteCardFromWalletController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="delete_card_from_wallet" />

	<bean
			name="ApiPaymentWithWalletController"
			class="org.springframework.web.servlet.mvc.ParameterizableViewController"
			p:viewName="api_payment_with_wallet" />

</beans>


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28528_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans436.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Ml??? Company: Whting Oil and Gas Job Number: Calculation Method Minimum Curvature "lleulk

Field: Sanish Magnetic Decl.: 7.52 Proposed Azimuth 279.21 ""'"' Cty/Blk/Par: Mountrail Co. North Dakota Grid Corr.: Depth Reference KB 2186 Well Name: Peterson 41—33XH Total Survey Corr.: 7.52 Tie Into G ro Data services Rig: Nabors 112 Target Info:
Middle Bakken Surveys Tool Survey Incl Azimuth Cours TVD VS Coordinates DLS Bld Rate Wlk Rate No. Type Depth (ft) (°) °) gth ft (ft) (ft) N/S ft) E/W ft) (°/100') (°/100') (°/100') Remarks
—

ma— mm— _ vwn — — vwa 39.30 film— .19— Mwo 52.44 10.8 m— .m— M_ — 10.4 m— _ m— — — .m— 111 MWD 283.94— — m— m vwo . — 90.07 — 116 M D . -

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans398.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
using Xamarin.Forms;
using Styr.Core.Input;

namespace Styr.App
{
	public delegate void OnInputCharEventHandler(char c);
	public delegate void OnKeyPressEventHandler(KeyboardKey key);

	public class KeyboardEditor : Editor
	{
		public event OnInputCharEventHandler InputChar;
		public event OnKeyPressEventHandler KeyPress;

		public void OnInputChar(char c) => InputChar?.Invoke(c);

		public void OnKeyPress(KeyboardKey key) => KeyPress?.Invoke(key);
	}
}


text:
package cloud

import (
	"errors"
	"fmt"

	"github.com/kelda/kelda/blueprint"
	"github.com/kelda/kelda/cloud/acl"
	"github.com/kelda/kelda/cloud/foreman"
	"github.com/kelda/kelda/db"
	"github.com/kelda/kelda/join"

	log "github.com/sirupsen/logrus"
)

var isConnected = foreman.IsConnected

type joinResult struct {
	acls []acl.ACL

	boot      []db.Machine
	terminate []db.Machine
	updateIPs []db.Machine
}

var cloudJoin = joinImpl

func joinImpl(cld cloud) (joinResult, error) {
	res := joinResult{}

	machines, err := cld.provider.List()
	if err != nil {
		log.WithError(err).Error("Failed to list machines")
		return res, err
	}
	machines = getMachineRoles(machines)

	err = cld.conn.Txn(db.BlueprintTable,
		db.MachineTable).Run(func(view db.Database) error {
		bp, err := view.GetBlueprint()
		if err != nil {
			log.WithError(err).Error("Failed to get blueprint")
			return err
		}

		if cld.namespace != bp.Namespace {
			err := errors.New("namespace change during a cloud run")
			log.WithError(err).Debug("Cloud run abort")
			return err
		}

		cld.updateDBMachines(view, machines)
		res.boot, res.terminate, res.updateIPs = cld.planUpdates(view)

		// Regions with no machines in them should have their ACLs cleared.
		if len(machines) > 0 {
			for acl := range cld.desiredACLs(bp) {
				res.acls = append(res.acls, acl)
			}
		}

		return nil
	})
	return res, err
}

func (cld cloud) updateDBMachines(view db.Database, cloudMachines []db.Machine) {
	dbms := cld.selectMachines(view)

	pairs, dbmis, cmis := join.Join(dbms, cloudMachines, machineScore)

	for _, cmi := range cmis {
		pairs = append(pairs, join.Pair{L: view.InsertMachine(), R: cmi})
	}

	for _, dbmi := range dbmis {
		view.Remove(dbmi.(db.Machine))
	}

	for _, pair := range pairs {
		dbm := pair.L.(db.Machine)
		cm := pair.R.(db.Machine)

		// Providers don't know about some fields, so we don't overwrite them.
		cm.ID = dbm.ID
		cm.Status = dbm.Status
		cm.SSHKeys = dbm.SSHKeys
		cm.PublicKey = dbm.PublicKey
		view.Commit(cm)
	}
}

func (cld cloud) planUpdates(view db.Database) (boot, stop, updateIPs []db.Machine) {
	bp, err := view.GetBlueprint()
	if err != nil {
		// Already got the blueprint earlier in this transaction.
		panic(fmt.Sprintf("Unreachable error: %v", err))
	}

	bpms := cld.desiredMachines(bp.Blueprint.Machines)
	dbms := cld.selectMachines(view)

	pairs, bpmis, dbmis := join.Join(bpms, dbms, machineScore)

	for _, p := range pairs {
		bpm := p.L.(db.Machine)
		dbm := p.R.(db.Machine)

		// Write the SSH keys into the database machine to ensure that the
		// database contains the most up to date SSH keys. If we didn't,
		// changes to the SSH keys in the blueprint would never get synced.
		// Similarly, the SSH keys would not be properly synced if the daemon
		// restarted when machines were already running in the cloud.
		dbm.SSHKeys = bpm.SSHKeys
		status := connectionStatus(dbm)
		if status != "" {
			dbm.Status = status
		}
		view.Commit(dbm)

		if bpm.FloatingIP != dbm.FloatingIP {
			dbm.FloatingIP = bpm.FloatingIP
			updateIPs = append(updateIPs, dbm)
		}
	}

	for _, dbmi := range dbmis {
		dbm := dbmi.(db.Machine)
		dbm.Status = db.Stopping
		view.Commit(dbm)

		stop = append(stop, dbm)
	}

	for _, bpmi := range bpmis {
		bpm := bpmi.(db.Machine)
		dbm := view.InsertMachine()
		bpm.ID = dbm.ID
		bpm.Status = db.Booting
		view.Commit(bpm)

		boot = append(boot, bpm)
	}

	return
}

func machineScore(left, right interface{}) int {
	l := left.(db.Machine)
	r := right.(db.Machine)

	switch {
	case l.Provider != r.Provider || l.Region != r.Region:
		// The caller should assure that this condition is met between all pairs.
		panic("Invalid Provider or Region")
	case l.Preemptible != r.Preemptible:
		return -1
	case l.Size != r.Size:
		return -1
	case l.DiskSize != 0 && r.DiskSize != 0 && l.DiskSize != r.DiskSize:
		return -1
	case l.Role != db.None && r.Role != db.None && l.Role != r.Role:
		return -1
	case l.CloudID != "" && r.CloudID != "" && l.CloudID == r.CloudID:
		return 0
	case l.FloatingIP != "" && r.FloatingIP != "" && l.FloatingIP == r.FloatingIP:
		return 1
	case l.Role != db.None && r.Role != db.None:
		return 2 // Prefer to match pairs that have a role assigned.
	default:
		return 3
	}
}

func (cld cloud) desiredMachines(bpms []blueprint.Machine) []db.Machine {
	var dbms []db.Machine
	for _, bpm := range bpms {
		region := bpm.Region
		if bpm.Provider != string(cld.providerName) || region != cld.region {
			continue
		}

		role, err := db.ParseRole(bpm.Role)
		if err != nil {
			log.WithError(err).Error("Parse error: ", bpm.Role)
			continue
		}

		dbm := db.Machine{
			Region:      region,
			FloatingIP:  bpm.FloatingIP,
			Role:        role,
			Provider:    db.ProviderName(bpm.Provider),
			Preemptible: bpm.Preemptible,
			Size:        bpm.Size,
			DiskSize:    bpm.DiskSize,
			SSHKeys:     bpm.SSHKeys,
		}

		if dbm.DiskSize == 0 {
			dbm.DiskSize = defaultDiskSize
		}

		if adminKey != "" {
			dbm.SSHKeys = append(dbm.SSHKeys, adminKey)
		}

		dbms = append(dbms, dbm)
	}
	return dbms
}

func connectionStatus(m db.Machine) string {
	// "Connected" takes priority over other statuses.
	connected := m.PublicIP != "" && isConnected(m.CloudID)
	if connected {
		return db.Connected
	}

	// If we had previously connected, and we are not currently connected, show
	// that we are attempting to reconnect.
	if m.Status == db.Connected || m.Status == db.Reconnecting {
		return db.Reconnecting
	}

	// If we've never successfully connected, but have booted enough to have a
	// public IP, show that we are attempting to connect.
	if m.PublicIP != "" {
		return db.Connecting
	}

	return ""
}

func (cld cloud) desiredACLs(bp db.Blueprint) map[acl.ACL]struct{} {
	aclSet := map[acl.ACL]struct{}{}

	// Always allow traffic from the Kelda controller, so we append local.
	for _, cidr := range append(bp.AdminACL, "local") {
		acl := acl.ACL{
			CidrIP:  cidr,
			MinPort: 1,
			MaxPort: 65535,
		}
		aclSet[acl] = struct{}{}
	}

	for _, conn := range bp.Connections {
		if conn.From == blueprint.PublicInternetLabel {
			acl := acl.ACL{
				CidrIP:  "0.0.0.0/0",
				MinPort: conn.MinPort,
				MaxPort: conn.MaxPort,
			}
			aclSet[acl] = struct{}{}
		}
	}

	return aclSet
}

func (cld cloud) selectMachines(view db.Database) []db.Machine {
	return view.SelectFromMachine(func(dbm db.Machine) bool {
		return dbm.Provider == cld.providerName && dbm.Region == cld.region
	})
}

func getMachineRoles(machines []db.Machine) (withRoles []db.Machine) {
	for _, m := range machines {
		m.Role = getMachineRole(m.CloudID)
		withRoles = append(withRoles, m)
	}
	return withRoles
}


text:
package com.actitrack.config;

import static spark.Spark.before;
import static spark.Spark.get;
import static spark.Spark.halt;
import static spark.Spark.post;
import static spark.SparkBase.staticFileLocation;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.UrlEncoded;

import com.actitrack.model.LoginResult;
import com.actitrack.model.Message;
import com.actitrack.model.ActionItem;
import com.actitrack.model.User;
import com.actitrack.service.impl.ActiTrackService;

import spark.ModelAndView;
import spark.Request;
import spark.template.freemarker.FreeMarkerEngine;
import spark.utils.StringUtils;

public class WebConfig {

	private static final String USER_SESSION_ID = "user";
	private ActiTrackService service;

	public WebConfig(ActiTrackService service) {
		this.service = service;
		staticFileLocation("/public");
		setupRoutes();
	}

	private void setupRoutes() {
		/*
		 * Shows a users timeline or if no user is logged in,
		 *  it will redirect to the public timeline.
		 *  This timeline shows the user's messages as well
		 *  as all the messages of followed users.
		 */
	/*	get("/timeline", (req, res) -> {
			User user = getAuthenticatedUser(req);
			Map<String, Object> map = new HashMap<>();
			map.put("pageTitle", "Timeline");
			map.put("user", user);
			List<Message> messages = service.getUserFullTimelineMessages(user);
			map.put("messages", messages);
			return new ModelAndView(map, "timeline.ftl");
        }, new FreeMarkerEngine());
		before("/", (req, res) -> {
			User user = getAuthenticatedUser(req);
			if(user == null) {
				res.redirect("/login");
				halt();
			}
		});
*/
        /* Create an action item */
		get("/create", (req, res) -> {
			User user = getAuthenticatedUser(req);
			Map<String, Object> map = new HashMap<>();
			map.put("pageTitle", "Create Action item");
			map.put("user", user);
			List<User> users = service.getUsers();
			map.put("users", users);
			return new ModelAndView(map, "create.ftl");
        }, new FreeMarkerEngine());

		before("/create", (req, res) -> {
			User user = getAuthenticatedUser(req);
			if(user == null) {
				res.redirect("/login");
				halt();
			}
		});

        post("/create", (req, res) -> {
            User user = getAuthenticatedUser(req);
            MultiMap<String> params = new MultiMap<String>();
            UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
            ActionItem a = new ActionItem();
            a.setCreatedBy(user.getId());
            a.setCreatedOn(1);
            //a.setAssignedTo(user.getId());
            //m.setPubDate(new Date());
            BeanUtils.populate(a, params);
            service.addActionItem(a);
            res.redirect("/");
            return null;
        });

        /* Lists Action Items assigned to me */
		get("/", (req, res) -> {
			User user = getAuthenticatedUser(req);
			Map<String, Object> map = new HashMap<>();
			map.put("pageTitle", "Action Items Assigned to me");
			map.put("user", user);
			List<ActionItem> items = service.getAssignedItems(user);
			map.put("items", items);
			return new ModelAndView(map, "assigned.ftl");
        }, new FreeMarkerEngine());
		before("/", (req, res) -> {
			User user = getAuthenticatedUser(req);
			if(user == null) {
				res.redirect("/login");
				halt();
			}
		});

     /* Lists Action Items submitted by me */
		get("/submitted", (req, res) -> {
			User user = getAuthenticatedUser(req);
			Map<String, Object> map = new HashMap<>();
			map.put("pageTitle", "Submitted Action Items");
			map.put("user", user);
			List<ActionItem> items = service.getSubmittedItems(user);
			map.put("items", items);
			return new ModelAndView(map, "assigned.ftl");
        }, new FreeMarkerEngine());
		before("/submitted", (req, res) -> {
			User user = getAuthenticatedUser(req);
			if(user == null) {
				res.redirect("/login");
				halt();
			}
		});

		/*
		 * Displays the latest messages of all users.
		 */
/*		get("/public", (req, res) -> {
			User user = getAuthenticatedUser(req);
			Map<String, Object> map = new HashMap<>();
			map.put("pageTitle", "Public Timeline");
			map.put("user", user);
			List<Message> messages = service.getPublicTimelineMessages();
			map.put("messages", messages);
			return new ModelAndView(map, "timeline.ftl");
        }, new FreeMarkerEngine());

*/
		/*
		 * Displays a user's tweets.
		 */
/*		get("/t/:username", (req, res) -> {
			String username = req.params(":username");
			User profileUser = service.getUserbyUsername(username);

			User authUser = getAuthenticatedUser(req);
			boolean followed = false;
			if(authUser != null) {
				followed = service.isUserFollower(authUser, profileUser);
			}
			List<Message> messages = service.getUserTimelineMessages(profileUser);

			Map<String, Object> map = new HashMap<>();
			map.put("pageTitle", username + "'s Timeline");
			map.put("user", authUser);
			map.put("profileUser", profileUser);
			map.put("followed", followed);
			map.put("messages", messages);
			return new ModelAndView(map, "timeline.ftl");
        }, new FreeMarkerEngine());
		/*
		 * Checks if the user exists
		 */
/*		before("/t/:username", (req, res) -> {
			String username = req.params(":username");
			User profileUser = service.getUserbyUsername(username);
			if(profileUser == null) {
				halt(404, "User not Found");
			}
		});
*/

		/*
		 * Adds the current user as follower of the given user.
		 */
/*		get("/t/:username/follow", (req, res) -> {
			String username = req.params(":username");
			User profileUser = service.getUserbyUsername(username);
			User authUser = getAuthenticatedUser(req);

			service.followUser(authUser, profileUser);
			res.redirect("/t/" + username);
			return null;
        });
		/*
		 * Checks if the user is authenticated and the user to follow exists
		 */
/*		before("/t/:username/follow", (req, res) -> {
			String username = req.params(":username");
			User authUser = getAuthenticatedUser(req);
			User profileUser = service.getUserbyUsername(username);
			if(authUser == null) {
				res.redirect("/login");
				halt();
			} else if(profileUser == null) {
				halt(404, "User not Found");
			}
		});
*/

		/*
		 * Removes the current user as follower of the given user.
		 */
/*		get("/t/:username/unfollow", (req, res) -> {
			String username = req.params(":username");
			User profileUser = service.getUserbyUsername(username);
			User authUser = getAuthenticatedUser(req);

			service.unfollowUser(authUser, profileUser);
			res.redirect("/t/" + username);
			return null;
        });
		/*
		 * Checks if the user is authenticated and the user to unfollow exists
		 */
/*		before("/t/:username/unfollow", (req, res) -> {
			String username = req.params(":username");
			User authUser = getAuthenticatedUser(req);
			User profileUser = service.getUserbyUsername(username);
			if(authUser == null) {
				res.redirect("/login");
				halt();
			} else if(profileUser == null) {
				halt(404, "User not Found");
			}
		});

		/*
		 * Presents the login form or redirect the user to
		 * her timeline if it's already logged in
		 */
		get("/login", (req, res) -> {
			Map<String, Object> map = new HashMap<>();
			if(req.queryParams("r") != null) {
				map.put("message", "You were successfully registered and can login now");
			}
			return new ModelAndView(map, "login.ftl");
        }, new FreeMarkerEngine());
		/*
		 * Logs the user in.
		 */
		post("/login", (req, res) -> {
			Map<String, Object> map = new HashMap<>();
			User user = new User();
			try {
				MultiMap<String> params = new MultiMap<String>();
				UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
				BeanUtils.populate(user, params);
			} catch (Exception e) {
				halt(501);
				return null;
			}
			LoginResult result = service.checkUser(user);
			if(result.getUser() != null) {
				addAuthenticatedUser(req, result.getUser());
				res.redirect("/");
				halt();
			} else {
				map.put("error", result.getError());
			}
			map.put("username", user.getUsername());
			return new ModelAndView(map, "login.ftl");
        }, new FreeMarkerEngine());
		/*
		 * Checks if the user is already authenticated
		 */
		before("/login", (req, res) -> {
			User authUser = getAuthenticatedUser(req);
			if(authUser != null) {
				res.redirect("/");
				halt();
			}
		});

		/*
		 * Presents the register form or redirect the user to
		 * her timeline if it's already logged in
		 */
		get("/register", (req, res) -> {
			Map<String, Object> map = new HashMap<>();
			return new ModelAndView(map, "register.ftl");
        }, new FreeMarkerEngine());
		/*
		 * Registers the user.
		 */
		post("/register", (req, res) -> {
			Map<String, Object> map = new HashMap<>();
			User user = new User();
			try {
				MultiMap<String> params = new MultiMap<String>();
				UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
				BeanUtils.populate(user, params);
			} catch (Exception e) {
				halt(501);
				return null;
			}
			String error = user.validate();
			if(StringUtils.isEmpty(error)) {
				User existingUser = service.getUserbyUsername(user.getUsername());
				if(existingUser == null) {
					service.registerUser(user);
					res.redirect("/login?r=1");
					halt();
				} else {
					error = "The username is already taken";
				}
			}
			map.put("error", error);
			map.put("username", user.getUsername());
			map.put("email", user.getEmail());
			return new ModelAndView(map, "register.ftl");
        }, new FreeMarkerEngine());
		/*
		 * Checks if the user is already authenticated
		 */
		before("/register", (req, res) -> {
			User authUser = getAuthenticatedUser(req);
			if(authUser != null) {
				res.redirect("/");
				halt();
			}
		});

		/*
		 * Registers a new message for the user.
		 */
/*		post("/message", (req, res) -> {
			User user = getAuthenticatedUser(req);
			MultiMap<String> params = new MultiMap<String>();
			UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
			Message m = new Message();
			m.setUserId(user.getId());
			m.setPubDate(new Date());
			BeanUtils.populate(m, params);
			service.addMessage(m);
			res.redirect("/");
			return null;
        });
		/*
		 * Checks if the user is authenticated
		 */
/*		before("/message", (req, res) -> {
			User authUser = getAuthenticatedUser(req);
			if(authUser == null) {
				res.redirect("/login");
				halt();
			}
		});

		/*
		 * Logs the user out and redirects to the public timeline
		 */
		get("/logout", (req, res) -> {
			removeAuthenticatedUser(req);
			res.redirect("/login");
			return null;
        });
	}

	private void addAuthenticatedUser(Request request, User u) {
		request.session().attribute(USER_SESSION_ID, u);

	}

	private void removeAuthenticatedUser(Request request) {
		request.session().removeAttribute(USER_SESSION_ID);

	}

	private User getAuthenticatedUser(Request request) {
		return request.session().attribute(USER_SESSION_ID);
	}
}


text:
package fr.ourten.brokkgui.paint;

import fr.ourten.brokkgui.internal.IGuiRenderer;

public class Background
{
    private Color   color;
    private Texture texture;

    public Background(final Color color, final Texture texture)
    {
        super();
        this.color = color;
        this.texture = texture;
    }

    public Background(final Color color)
    {
        this(color, new Texture());
    }

    public Background()
    {
        this(Color.ALPHA);
    }

    public void renderBackground(final IGuiRenderer renderer, final float x, final float y, final float width,
            final float height, final float zLevel)
    {
        if (!this.texture.isEmpty())
        {
            renderer.getHelper().bindTexture(this.texture);
            renderer.getHelper().drawTexturedModalRect(renderer, x, y, this.texture.getU(), this.texture.getV(),
                    this.texture.getS(), this.texture.getT(), width, height, zLevel);
        }
        if (this.color.getAlpha() != 0)
            renderer.getHelper().drawColoredRect(renderer, x, y, width, height, zLevel, this.color);
    }

    public Color getColor()
    {
        return this.color;
    }

    public void setColor(final Color color)
    {
        this.color = color;
    }

    public Texture getTexture()
    {
        return this.texture;
    }

    public void setTexture(final Texture texture)
    {
        this.texture = texture;
    }
}


text:
export DEBIAN_FRONTEND=noninteractive

# Update all packages.
sudo apt-get update
sudo apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade

export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

sudo locale-gen en_US.UTF-8
sudo dpkg-reconfigure locales
sudo touch /root/.locale-fixed
sudo /usr/sbin/update-locale

sudo apt-get install -y curl

# Install Chef
curl -L https://www.opscode.com/chef/install.sh | sudo bash


text:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soap:Header>
        <tns:SessionHeader xmlns:tns="urn:enterprise.soap.sforce.com">
            <tns:sessionId>${SessionHeader.sessionId}</tns:sessionId>
        </tns:SessionHeader>
        <tns:PackageVersionHeader xmlns:tns="urn:enterprise.soap.sforce.com">
#foreach($packageVersions in $PackageVersionHeader.packageVersions)
            <tns:packageVersions>
                <tns:majorNumber>${packageVersions.majorNumber}</tns:majorNumber>
                <tns:minorNumber>${packageVersions.minorNumber}</tns:minorNumber>
                <tns:namespace>${packageVersions.namespace}</tns:namespace>
            </tns:packageVersions>
#end
        </tns:PackageVersionHeader>
        <tns:LocaleOptions xmlns:tns="urn:enterprise.soap.sforce.com">
            <tns:language>${LocaleOptions.language}</tns:language>
        </tns:LocaleOptions>
    </soap:Header>
    <soap:Body>
        <tns:describeSObject xmlns:tns="urn:enterprise.soap.sforce.com">
            <tns:sObjectType>${describeSObject.sObjectType}</tns:sObjectType>
        </tns:describeSObject>
    </soap:Body>
</soap:Envelope>


text:
<?php

namespace Nerdstorm\GoogleBooks\Enum;

use Eloquent\Enumeration\AbstractEnumeration;

/**
 * Class ViewabilityEnum
 *
 * Possible values are PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN.
 *
 * This value depends on the country listed above. A value of PARTIAL means that the publisher has allowed
 * some portion of the volume to be viewed publicly, without purchase. This can apply to eBooks as
 * well as non-eBooks. Public domain books will always have a value of ALL_PAGES.
 */
final class ViewabilityEnum extends AbstractEnumeration
{
    const PARTIAL   = 'PARTIAL';
    const ALL_PAGES = 'ALL_PAGES';
    const NO_PAGES  = 'NO_PAGES';
    const UNKNOWN   = 'UNKNOWN';
}


text:
package com.jufan.cloud.center;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class CloudCenterApp {

	public static void main(String[] args) {
		SpringApplication.run(CloudCenterApp.class, args);
	}
}


text:
'''
init: initialize a new container competition

The MIT License (MIT)

Copyright (c) 2016-2017 Vanessa Sochat

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

'''

from glob import glob
import argparse
import sys
import os

from cftw.logger import bot
from cftw.utils import (
    mkdir_p,
    tree,
    write_json
)

from .template import (
    get_template,
    sub_template
)

import sys
import os

def generate_base(template, name, output_folder=None):
    '''generation of a base means copying an entire template
    into the user's output folder. If None is specified, $PWD
    is used
    '''
    if output_folder is None:
        output_folder = os.getcwd()

    bot.newline()
    bot.debug("Starting base generation in %s" %output_folder)
    template = get_template(template,output_folder,name)
    tree("%s/%s" %(output_folder,template))

    # The result folder is specific to the competition
    results = '%s/analysis/results' %(template)
    mkdir_p(results)
    result_template = get_template(template='leaderboard',
                                   template_type='results',
                                   name=name,
                                   output_folder=results)

    # Substitute competition name in Singularity file,
    # template
    files = [ "%s/Singularity" %template,
              "%s/.travis.yml" %template,
              "%s/index.html" %result_template ]

    for filey in files:
        sub_template(filey,{"COMPETITION_NAME":name})

    bot.debug("Finished generation.")
    return template

def main(args,parser):

    if args.template is None:
        from .template import list_templates
        available = "\n".join(list_templates())
        subcommand_help("Please provide a base template with --template/-t. Available templates are: \n%s" %available,"init")

    base = generate_base(template=args.template,
                         output_folder=args.out,
                         name=args.name)

def subcommand_help(message,command):
    from cftw.logger import bot
    bot.info(message)
    bot.info("-------------------------------------------------------------")
    bot.info("For help with %s, cftw %s --help" %(command,command))
    sys.exit(1)

if __name__ == '__main__':
    main()