text:
#include "ptr_array.h"

#include <string.h>
#include <stdlib.h>
#include <assert.h>

#define array_good_size(max_size) ((max_size + 7L) & ~7L)
ptr_array ptr_array_new(size_t max_size)
{
	size_t good_size = array_good_size(max_size);
	assert(good_size >= max_size);

	ptr_array retval = (ptr_array)malloc(sizeof(struct ptr_array_t));
	if (retval == NULL)
		return NULL;

	retval->length = 0;
	retval->size = good_size;
	if (good_size != 0)
	{
		retval->array = malloc(sizeof(void*)*good_size);
		if (retval->array == NULL)
		{
			free(retval);
			return NULL;
		}
	}
	else
	{
		retval->array = NULL;
	}
	return retval;
}

void* ptr_array_remove_ordered(ptr_array self, const void *obj)
{
	size_t i;
	assert (self != NULL);

	for (i = 0; i < self->length; ++i)
		if (self->array[i] == obj)
			return ptr_array_remove_index_ordered(self, i);

	return NULL;
}

void *ptr_array_remove_fast(ptr_array self, const void *obj)
{
	size_t i;
	assert (self != NULL);

	for (i = 0; i < self->length; ++i)
		if (self->array[i] == obj)
			return ptr_array_remove_index_fast(self, i);

	return NULL;
}

void * ptr_array_get_index(const ptr_array self, size_t index)
{
	assert (self != NULL);
	assert (index < self->length);
	return (void*)self->array[index];
}

void * ptr_array_set_index(ptr_array self, size_t index, const void *value)
{
	const void * oldval;
	assert( self != NULL);
	assert(index < self->length);

	oldval = self->array[index];
	self->array[index] = value;
	return (void*)oldval;
}

void* ptr_array_remove_index_ordered(ptr_array self, size_t index)
{
	const void *retval;
	size_t i;
	assert (self != NULL);
	assert (index < self->length);

	retval = self->array[index];
	for (i = index + 1; i < self->length; ++i)
		self->array[i - 1] = self->array[i];

	self->length--;
#ifdef CLEANUP_REFERENCES
	self->array[self->length] = NULL;
#endif
	return (void*)retval;
}

void* ptr_array_remove_index_fast(ptr_array self, size_t index)
{
	const void *retval;
	assert (self != NULL);
	assert (index < self->length);

	retval = self->array[index];
	self->length--;
	self->array[index] = self->array[self->length];

#ifdef CLEANUP_REFERENCES
	self->array[self->length] = NULL;
#endif
	return (void*)retval;
}

int _ptr_array_growing_append(ptr_array self, const void *value)
{
	size_t good_size = array_good_size(self->size + 1);
	void * new_array = realloc(self->array, good_size*sizeof(void*));
	if (new_array == NULL)
		return 0;

	self->size = good_size;
	self->array = new_array;
	self->array[self->length] = value;
	self->length++;
	return 1;
}

void ptr_array_free(ptr_array self)
{
	if (self != NULL)
	{
		free(self->array);
		free(self);
	}
}

int ptr_array_contains(const ptr_array self, const void *value)
{
	int i;
	assert (self != NULL);
	for (i = 0; i < self->length; ++i)
		if (self->array[i] == value)
			return 1;

	return 0;
}

void ptr_array_clear(ptr_array self)
{
#ifdef CLEANUP_REFERENCES
	memset(self->array, 0, self->size * sizeof(void*));
#endif
	self->length = 0;
}


text:
"""
Code PyQt4

QtGui.QGridLayout()

"""
import sys, os
from PyQt4 import QtGui, QtCore

class Button(QtGui.QToolButton):
    def __init__(self, text, parent=None):
        super(Button, self).__init__(parent)

        self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                QtGui.QSizePolicy.Preferred)
        self.setText(text)

class Calculator(QtGui.QDialog):

    NumDigitButtons = 10

    def __init__(self, parent=None):
        super(Calculator, self).__init__(parent)

        self.digitButtons = []

        for i in range(Calculator.NumDigitButtons):
            self.digitButtons.append(self.createButton(str(i)))

        mainLayout = QtGui.QGridLayout()
        mainLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)

        for i in range(1, Calculator.NumDigitButtons):
            row = ((9 - i) / 3) + 2
            column = ((i - 1) % 3) + 1
            mainLayout.addWidget(self.digitButtons[i], row, column)

        mainLayout.addWidget(self.digitButtons[0], 5, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("Calculator")

    def createButton(self, text):
        button = Button(text)

        return button

def main():
    app = QtGui.QApplication(sys.argv)
    calc = Calculator()
    sys.exit(calc.exec_())

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
package net.ttddyy.dsproxy.listener.lifecycle;

import javax.sql.CommonDataSource;
import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Wrapper;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Tadaya Tsuyukubo
 */
public class JdbcLifecycleEventListenerUtils {

    private static final Map<String, Method> beforeLifecycleMethodsByMethodName = new HashMap<String, Method>();
    private static final Map<String, Method> afterLifecycleMethodsByMethodName = new HashMap<String, Method>();

    static {

        Set<String> methodNames = getDeclaredMethodNames(
                Wrapper.class,
                DataSource.class, CommonDataSource.class,
                Connection.class,
                Statement.class, PreparedStatement.class, CallableStatement.class,
                ResultSet.class);

        beforeLifecycleMethodsByMethodName.putAll(getLifecycleMethodByMethodName(methodNames, true));
        afterLifecycleMethodsByMethodName.putAll(getLifecycleMethodByMethodName(methodNames, false));
    }

    /**
     * Retrieve corresponding lifecycle methods declared in {@link JdbcLifecycleEventListener}.
     *
     * <p>Format is {@code [before|after]<MethodName>}
     *
     * @param methodNames set of method names to find
     * @param isBefore    whether to retrieve before methods or after methods
     * @return a map that key is the method name string and value is lifecycle method
     */
    private static Map<String, Method> getLifecycleMethodByMethodName(Set<String> methodNames, boolean isBefore) {
        Map<String, Method> lifecycleMethodByName = new HashMap<String, Method>();
        for (Method method : JdbcLifecycleEventListener.class.getMethods()) {
            lifecycleMethodByName.put(method.getName(), method);
        }

        Map<String, Method> result = new HashMap<String, Method>();
        for (String methodName : methodNames) {
            String lifecycleMethodName = (isBefore ? "before" : "after") + capitalize(methodName);
            Method targetLifecycleMethod = lifecycleMethodByName.get(lifecycleMethodName);
            result.put(methodName, targetLifecycleMethod);
        }
        return result;
    }

    private static String capitalize(String methodName) {
        StringBuilder sb = new StringBuilder(methodName.length());
        sb.append(Character.toUpperCase(methodName.charAt(0)));
        sb.append(methodName.substring(1));
        return sb.toString();
    }

    private static Set<String> getDeclaredMethodNames(Class<?>... classes) {
        Set<String> names = new HashSet<String>();
        for (Class<?> clazz : classes) {
            names.addAll(getDeclaredMethodNames(clazz));
        }
        return names;
    }

    private static Set<String> getDeclaredMethodNames(Class<?> clazz) {
        Set<String> names = new HashSet<String>();
        for (Method method : clazz.getDeclaredMethods()) {
            names.add(method.getName());
        }
        return names;
    }

    /**
     * Find corresponding callback method on {@link JdbcLifecycleEventListener}.
     *
     * @param invokedMethodName invoked method name
     * @param isBefore          before method or not
     * @return corresponding callback method or {@code null} if not found. (e.g.: toString, hashCode)
     */
    public static Method getListenerMethod(String invokedMethodName, boolean isBefore) {
        if (isBefore) {
            return beforeLifecycleMethodsByMethodName.get(invokedMethodName);
        } else {
            return afterLifecycleMethodsByMethodName.get(invokedMethodName);
        }
    }

}


text:
if [ "$#" -ne 2 ]; then
  echo "syntax: $0 <TYPE>"
  echo "<TYPE> should be either golang or python"
  echo "<CONFIG> config file shold be one of config the files under ./config/"
  echo "example:"
  echo "./podVertical golang ./config/golang/cluster-limits-pods-per-namespace"
  exit 1
fi

TYPE=$1
CONFIG=$2

# use the default config if it's not defined by the user
if [[ -z "$CONFIG" ]] && [[ "$TYPE" == golang ]]; then
	CONFIG=config/golang/cluster-limits-pods-per-namespace
fi
if [[ -z "$CONFIG" ]] && [[ "$TYPE" == python ]]; then
        CONFIG=config/cluster-limits-pods-per-namespace.yaml
fi

long_sleep() {
  local sleep_time=180
  echo "Sleeping for $sleep_time"
  sleep $sleep_time
}

golang_clusterloader() {
  # Export kube config
  export KUBECONFIG=${KUBECONFIG-$HOME/.kube/config}
  # loading cluster based on yaml config file
  VIPERCONFIG=$CONFIG openshift-tests run-test "[Feature:Performance][Serial][Slow] Load cluster should load the cluster [Suite:openshift]"
}

python_clusterloader() {
  ./cluster-loader.py --file=$CONFIG
}

# sleeping to gather some steady-state metrics, pre-test
long_sleep

# Run the test
if [ "$TYPE" == "golang" ]; then
  golang_clusterloader
elif [ "$TYPE" == "python" ]; then
  python_clusterloader
  # sleeping again to gather steady-state metrics after environment is loaded
  long_sleep
else
  echo "$TYPE is not a valid option, available options: golang, python"
  exit 1
fi

# sleep after test is complete to gather post-test metrics...these should be the same as pre-test
long_sleep


text:
'use strict';

describe('ngAnimate integration tests', function() {

  beforeEach(module('ngAnimate'));
  beforeEach(module('ngAnimateMock'));

  var element, html, ss;
  beforeEach(module(function() {
    return function($rootElement, $document, $animate) {
      $animate.enabled(true);

      ss = createMockStyleSheet($document);

      var body = jqLite($document[0].body);
      html = function(element) {
        body.append($rootElement);
        $rootElement.append(element);
      };
    };
  }));

  afterEach(function() {
    dealoc(element);
    ss.destroy();
  });

 it('should cancel a running and started removeClass animation when a follow-up addClass animation adds the same class',
    inject(function($animate, $rootScope, $$rAF, $document, $rootElement) {

    jqLite($document[0].body).append($rootElement);
    element = jqLite('

');
    $rootElement.append(element);

    element.addClass('active-class');

    var runner = $animate.removeClass(element, 'active-class');
    $rootScope.$digest();

    var doneHandler = jasmine.createSpy('addClass done');
    runner.done(doneHandler);

    $$rAF.flush(); // Trigger the actual animation

    expect(doneHandler).not.toHaveBeenCalled();

    $animate.addClass(element, 'active-class');
    $rootScope.$digest();

    // Cancelling the removeClass animation triggers the done callback
    expect(doneHandler).toHaveBeenCalled();
  }));

  it('should remove a class that is currently being added by a running animation when another class is added in before in the same digest',
    inject(function($animate, $rootScope, $$rAF, $document, $rootElement) {

    jqLite($document[0].body).append($rootElement);
    element = jqLite('

');
    $rootElement.append(element);

    var runner = $animate.addClass(element, 'red');

    $rootScope.$digest();

    $animate.addClass(element, 'blue');
    $animate.removeClass(element, 'red');
    $rootScope.$digest();

    $$rAF.flush();

    expect(element).not.toHaveClass('red');
    expect(element).toHaveClass('blue');
  }));

  it('should add a class that is currently being removed by a running animation when another class is removed before in the same digest',
    inject(function($animate, $rootScope, $$rAF, $document, $rootElement) {

    jqLite($document[0].body).append($rootElement);
    element = jqLite('

');
    $rootElement.append(element);
    element.addClass('red blue');

    var runner = $animate.removeClass(element, 'red');

    $rootScope.$digest();

    $animate.removeClass(element, 'blue');
    $animate.addClass(element, 'red');
    $rootScope.$digest();

    $$rAF.flush();

    expect(element).not.toHaveClass('blue');
    expect(element).toHaveClass('red');
  }));

  describe('CSS animations', function() {
    if (!browserSupportsCssAnimations()) return;

    it('should only create a single copy of the provided animation options',
      inject(function($rootScope, $rootElement, $animate) {

      ss.addRule('.animate-me', 'transition:2s linear all;');

      var element = jqLite('

');
      html(element);

      var myOptions = {to: { 'color': 'red' }};

      var spy = spyOn(window, 'copy');
      expect(spy).not.toHaveBeenCalled();

      var animation = $animate.leave(element, myOptions);
      $rootScope.$digest();
      $animate.flush();

      expect(spy).toHaveBeenCalledOnce();
      dealoc(element);
    }));

    they('should render an $prop animation',
      ['enter', 'leave', 'move', 'addClass', 'removeClass', 'setClass'], function(event) {

      inject(function($animate, $compile, $rootScope, $rootElement) {
        element = jqLite('

');
        $compile(element)($rootScope);

        var className = 'klass';
        var addClass, removeClass;
        var parent = jqLite('

');
        html(parent);

        var setupClass, activeClass;
        var args;
        var classRuleSuffix = '';

        switch (event) {
          case 'enter':
          case 'move':
            setupClass = 'ng-' + event;
            activeClass = 'ng-' + event + '-active';
            args = [element, parent];
            break;

          case 'leave':
            parent.append(element);
            setupClass = 'ng-' + event;
            activeClass = 'ng-' + event + '-active';
            args = [element];
            break;

          case 'addClass':
            parent.append(element);
            classRuleSuffix = '.add';
            setupClass = className + '-add';
            activeClass = className + '-add-active';
            addClass = className;
            args = [element, className];
            break;

          case 'removeClass':
            parent.append(element);
            setupClass = className + '-remove';
            activeClass = className + '-remove-active';
            element.addClass(className);
            args = [element, className];
            break;

          case 'setClass':
            parent.append(element);
            addClass = className;
            removeClass = 'removing-class';
            setupClass = addClass + '-add ' + removeClass + '-remove';
            activeClass = addClass + '-add-active ' + removeClass + '-remove-active';
            element.addClass(removeClass);
            args = [element, addClass, removeClass];
            break;
        }

        ss.addRule('.animate-me', 'transition:2s linear all;');

        var runner = $animate[event].apply($animate, args);
        $rootScope.$digest();

        var animationCompleted = false;
        runner.then(function() {
          animationCompleted = true;
        });

        expect(element).toHaveClass(setupClass);
        $animate.flush();
        expect(element).toHaveClass(activeClass);

        browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 2 });
        $animate.flush();

        expect(element).not.toHaveClass(setupClass);
        expect(element).not.toHaveClass(activeClass);

        $rootScope.$digest();

        expect(animationCompleted).toBe(true);
      });
    });

    it('should not throw an error if the element is orphaned before the CSS animation starts',
      inject(function($rootScope, $rootElement, $animate) {

      ss.addRule('.animate-me', 'transition:2s linear all;');

      var parent = jqLite('

');
      html(parent);

      var element = jqLite('
DOING
');
      parent.append(element);

      $animate.addClass(parent, 'on');
      $animate.addClass(element, 'on');
      $rootScope.$digest();

      // this will run the first class-based animation
      $animate.flush();

      element.remove();

      expect(function() {
        $animate.flush();
      }).not.toThrow();

      dealoc(element);
    }));

    it('should include the added/removed classes in lieu of the enter animation',
      inject(function($animate, $compile, $rootScope, $rootElement, $document) {

      ss.addRule('.animate-me.ng-enter.on', 'transition:2s linear all;');

      element = jqLite('

');

      $rootElement.append(element);
      jqLite($document[0].body).append($rootElement);

      $compile(element)($rootScope);

      $rootScope.exp = true;
      $rootScope.$digest();
      $animate.flush();

      var child = element.find('div');

      expect(child).not.toHaveClass('on');
      expect(child).not.toHaveClass('ng-enter');

      $rootScope.exp = false;
      $rootScope.$digest();

      $rootScope.exp = true;
      $rootScope.exp2 = true;
      $rootScope.$digest();

      child = element.find('div');

      expect(child).toHaveClass('on');
      expect(child).toHaveClass('ng-enter');

      $animate.flush();

      expect(child).toHaveClass('ng-enter-active');

      browserTrigger(child, 'transitionend', { timeStamp: Date.now(), elapsedTime: 2 });
      $animate.flush();

      expect(child).not.toHaveClass('ng-enter-active');
      expect(child).not.toHaveClass('ng-enter');
    }));

    it('should animate ng-class and a structural animation in parallel on the same element',
      inject(function($animate, $compile, $rootScope, $rootElement, $document) {

      ss.addRule('.animate-me.ng-enter', 'transition:2s linear all;');
      ss.addRule('.animate-me.expand', 'transition:5s linear all; font-size:200px;');

      element = jqLite('

');

      $rootElement.append(element);
      jqLite($document[0].body).append($rootElement);

      $compile(element)($rootScope);

      $rootScope.exp = true;
      $rootScope.exp2 = true;
      $rootScope.$digest();

      var child = element.find('div');

      expect(child).toHaveClass('ng-enter');
      expect(child).toHaveClass('expand-add');
      expect(child).toHaveClass('expand');

      $animate.flush();

      expect(child).toHaveClass('ng-enter-active');
      expect(child).toHaveClass('expand-add-active');

      browserTrigger(child, 'transitionend', { timeStamp: Date.now(), elapsedTime: 2 });
      $animate.flush();

      expect(child).not.toHaveClass('ng-enter-active');
      expect(child).not.toHaveClass('ng-enter');
      expect(child).not.toHaveClass('expand-add-active');
      expect(child).not.toHaveClass('expand-add');
    }));

    it('should issue a RAF for each element animation on all DOM levels', function() {
      module('ngAnimateMock');
      inject(function($animate, $compile, $rootScope, $rootElement, $document, $$rAF) {
        element = jqLite(
          '
' +
            '
' +
               '
' +
                  '{{ item }}' +
               '
' +
            '
' +
          '
'
        );

        $rootElement.append(element);
        jqLite($document[0].body).append($rootElement);

        $compile(element)($rootScope);
        $rootScope.$digest();

        var outer = element;
        var inner = element.find('div');

        $rootScope.exp = true;
        $rootScope.items = [1,2,3,4,5,6,7,8,9,10];

        $rootScope.$digest();
        expect(outer).not.toHaveClass('parent');
        expect(inner).not.toHaveClass('parent2');

        assertTotalRepeats(0);

        $$rAF.flush();
        expect(outer).toHaveClass('parent');

        assertTotalRepeats(0);

        $$rAF.flush();
        expect(inner).toHaveClass('parent2');

        assertTotalRepeats(10);

        function assertTotalRepeats(total) {
          expect(inner[0].querySelectorAll('div.ng-enter').length).toBe(total);
        }
      });
    });

    it('should add the preparation class for an enter animation before a parent class-based animation is applied', function() {
      module('ngAnimateMock');
      inject(function($animate, $compile, $rootScope, $rootElement, $document) {
        element = jqLite(
          '
' +
            '
' +
            '
' +
          '
'
        );

        ss.addRule('.ng-enter', 'transition:2s linear all;');
        ss.addRule('.parent-add', 'transition:5s linear all;');

        $rootElement.append(element);
        jqLite($document[0].body).append($rootElement);

        $compile(element)($rootScope);
        $rootScope.exp = true;
        $rootScope.$digest();

        var parent = element;
        var child = element.find('div');

        expect(parent).not.toHaveClass('parent');
        expect(parent).toHaveClass('parent-add');
        expect(child).not.toHaveClass('ng-enter');
        expect(child).toHaveClass('ng-enter-prepare');

        $animate.flush();
        expect(parent).toHaveClass('parent parent-add parent-add-active');
        expect(child).toHaveClass('ng-enter ng-enter-active');
        expect(child).not.toHaveClass('ng-enter-prepare');
      });
    });

    it('should pack level elements into their own RAF flush', function() {
      module('ngAnimateMock');
      inject(function($animate, $compile, $rootScope, $rootElement, $document) {
        ss.addRule('.inner', 'transition:2s linear all;');

        element = jqLite(
          '
' +
            '
' +
               '

' +
            '
' +
            '
' +
               '

' +
            '
' +
            '
' +
               '

' +
            '
' +
            '

' +
          '
'
        );

        $rootElement.append(element);
        jqLite($document[0].body).append($rootElement);
        $compile(element)($rootScope);
        $rootScope.$digest();

        assertGroupHasClass(query('outer'), 'on', true);
        expect(query('inner').length).toBe(0);

        $rootScope.exp = true;
        $rootScope.$digest();

        assertGroupHasClass(query('outer'), 'on', true);
        assertGroupHasClass(query('inner'), 'ng-enter', true);

        $animate.flush();

        assertGroupHasClass(query('outer'), 'on');
        assertGroupHasClass(query('inner'), 'ng-enter');

        function query(className) {
          return element[0].querySelectorAll('.' + className);
        }

        function assertGroupHasClass(elms, className, not) {
          for (var i = 0; i < elms.length; i++) {
            var assert = expect(jqLite(elms[i]));
            (not ? assert.not : assert).toHaveClass(className);
          }
        }
      });
    });

    it('should trigger callbacks at the start and end of an animation',
      inject(function($rootScope, $rootElement, $animate, $compile) {

      ss.addRule('.animate-me', 'transition:2s linear all;');

      var parent = jqLite('

');
      element = parent.find('div');
      html(parent);

      $compile(parent)($rootScope);
      $rootScope.$digest();

      var spy = jasmine.createSpy();
      $animate.on('enter', parent, spy);

      $rootScope.exp = true;
      $rootScope.$digest();

      element = parent.find('div');

      $animate.flush();

      expect(spy).toHaveBeenCalledTimes(1);

      browserTrigger(element, 'transitionend', { timeStamp: Date.now(), elapsedTime: 2 });
      $animate.flush();

      expect(spy).toHaveBeenCalledTimes(2);

      dealoc(element);
    }));

    it('should remove a class when the same class is currently being added by a joined class-based animation',
      inject(function($animate, $animateCss, $rootScope, $document, $rootElement, $$rAF) {

      ss.addRule('.hide', 'opacity: 0');
      ss.addRule('.hide-add, .hide-remove', 'transition: 1s linear all');

      jqLite($document[0].body).append($rootElement);
      element = jqLite('

');
      $rootElement.append(element);

      // These animations will be joined together
      $animate.addClass(element, 'red');
      $animate.addClass(element, 'hide');
      $rootScope.$digest();

      expect(element).toHaveClass('red-add');
      expect(element).toHaveClass('hide-add');

      // When a digest has passed, but no $rAF has been issued yet, .hide hasn't been added to
      // the element yet
      $animate.removeClass(element, 'hide');
      $rootScope.$digest();
      $$rAF.flush();

      expect(element).not.toHaveClass('hide-add hide-add-active');
      expect(element).toHaveClass('hide-remove hide-remove-active');

      //End the animation process
      browserTrigger(element, 'transitionend',
        { timeStamp: Date.now() + 1000, elapsedTime: 2 });
      $animate.flush();

      expect(element).not.toHaveClass('hide-add-active red-add-active');
      expect(element).toHaveClass('red');
      expect(element).not.toHaveClass('hide');
    }));

    it('should handle ng-if & ng-class with a class that is removed before its add animation has concluded', function() {
      inject(function($animate, $rootScope, $compile, $timeout, $$rAF) {

        ss.addRule('.animate-me', 'transition: all 0.5s;');

        element = jqLite('

');

        html(element);
        $rootScope.blue = true;
        $rootScope.red = true;
        $compile(element)($rootScope);
        $rootScope.$digest();

        var child = element.find('div');

        // Trigger class removal before the add animation has been concluded
        $rootScope.blue = false;
        $animate.closeAndFlush();

        expect(child).toHaveClass('red');
        expect(child).not.toHaveClass('blue');
      });
    });
  });

  describe('JS animations', function() {
    they('should render an $prop animation',
      ['enter', 'leave', 'move', 'addClass', 'removeClass', 'setClass'], function(event) {

      var endAnimation;
      var animateCompleteCallbackFired = true;

      module(function($animateProvider) {
        $animateProvider.register('.animate-me', function() {
          var animateFactory = {};
          animateFactory[event] = function(element, addClass, removeClass, done) {
            endAnimation = arguments[arguments.length - 2]; // the done method is the 2nd last one
            return function(status) {
              animateCompleteCallbackFired = status === false;
            };
          };
          return animateFactory;
        });
      });

      inject(function($animate, $compile, $rootScope, $rootElement) {
        element = jqLite('

');
        $compile(element)($rootScope);

        var className = 'klass';
        var addClass, removeClass;
        var parent = jqLite('

');
        html(parent);

        var args;
        switch (event) {
          case 'enter':
          case 'move':
            args = [element, parent];
            break;

          case 'leave':
            parent.append(element);
            args = [element];
            break;

          case 'addClass':
            parent.append(element);
            args = [element, className];
            break;

          case 'removeClass':
            parent.append(element);
            element.addClass(className);
            args = [element, className];
            break;

          case 'setClass':
            parent.append(element);
            addClass = className;
            removeClass = 'removing-class';
            element.addClass(removeClass);
            args = [element, addClass, removeClass];
            break;
        }

        var runner = $animate[event].apply($animate, args);
        var animationCompleted = false;
        runner.then(function() {
          animationCompleted = true;
        });

        $rootScope.$digest();

        expect(isFunction(endAnimation)).toBe(true);

        endAnimation();
        $animate.flush();
        expect(animateCompleteCallbackFired).toBe(true);

        $rootScope.$digest();
        expect(animationCompleted).toBe(true);
      });
    });

    they('should not wait for a parent\'s classes to resolve if a $prop is animation used for children',
      ['beforeAddClass', 'beforeRemoveClass', 'beforeSetClass'], function(phase) {

      var capturedChildClasses;
      var endParentAnimationFn;

      module(function($animateProvider) {
        $animateProvider.register('.parent-man', function() {
          var animateFactory = {};
          animateFactory[phase] = function(element, addClass, removeClass, done) {
            // this will wait until things are over
            endParentAnimationFn = done;
          };
          return animateFactory;
        });

        $animateProvider.register('.child-man', function() {
          return {
            enter: function(element, done) {
              capturedChildClasses = element.parent().attr('class');
              done();
            }
          };
        });
      });

      inject(function($animate, $compile, $rootScope, $rootElement) {
        element = jqLite('

');
        var child = jqLite('

');

        html(element);
        $compile(element)($rootScope);

        $animate.enter(child, element);
        switch (phase) {
          case 'beforeAddClass':
            $animate.addClass(element, 'cool');
            break;

          case 'beforeSetClass':
            $animate.setClass(element, 'cool');
            break;

          case 'beforeRemoveClass':
            element.addClass('cool');
            $animate.removeClass(element, 'cool');
            break;
        }

        $rootScope.$digest();
        $animate.flush();

        expect(endParentAnimationFn).toBeTruthy();

        // the spaces are used so that ` cool ` can be matched instead
        // of just a substring like `cool-add`.
        var safeClassMatchString = ' ' + capturedChildClasses + ' ';
        if (phase === 'beforeRemoveClass') {
          expect(safeClassMatchString).toContain(' cool ');
        } else {
          expect(safeClassMatchString).not.toContain(' cool ');
        }
      });
    });

    they('should have the parent\'s classes already applied in time for the children if $prop is used',
      ['addClass', 'removeClass', 'setClass'], function(phase) {

      var capturedChildClasses;
      var endParentAnimationFn;

      module(function($animateProvider) {
        $animateProvider.register('.parent-man', function() {
          var animateFactory = {};
          animateFactory[phase] = function(element, addClass, removeClass, done) {
            // this will wait until things are over
            endParentAnimationFn = done;
          };
          return animateFactory;
        });

        $animateProvider.register('.child-man', function() {
          return {
            enter: function(element, done) {
              capturedChildClasses = element.parent().attr('class');
              done();
            }
          };
        });
      });

      inject(function($animate, $compile, $rootScope, $rootElement) {
        element = jqLite('

');
        var child = jqLite('

');

        html(element);
        $compile(element)($rootScope);

        $animate.enter(child, element);
        switch (phase) {
          case 'addClass':
            $animate.addClass(element, 'cool');
            break;

          case 'setClass':
            $animate.setClass(element, 'cool');
            break;

          case 'removeClass':
            element.addClass('cool');
            $animate.removeClass(element, 'cool');
            break;
        }

        $rootScope.$digest();
        $animate.flush();

        expect(endParentAnimationFn).toBeTruthy();

        // the spaces are used so that ` cool ` can be matched instead
        // of just a substring like `cool-add`.
        var safeClassMatchString = ' ' + capturedChildClasses + ' ';
        if (phase === 'removeClass') {
          expect(safeClassMatchString).not.toContain(' cool ');
        } else {
          expect(safeClassMatchString).toContain(' cool ');
        }
      });
    });

    it('should not alter the provided options values in anyway throughout the animation', function() {
      var animationSpy = jasmine.createSpy();
      module(function($animateProvider) {
        $animateProvider.register('.this-animation', function() {
          return {
            enter: function(element, done) {
              animationSpy();
              done();
            }
          };
        });
      });

      inject(function($animate, $rootScope, $compile) {
        element = jqLite('

');
        var child = jqLite('

');

        var initialOptions = {
          from: { height: '50px' },
          to: { width: '100px' },
          addClass: 'one',
          removeClass: 'two',
          domOperation: undefined
        };

        var copiedOptions = copy(initialOptions);
        expect(copiedOptions).toEqual(initialOptions);

        html(element);
        $compile(element)($rootScope);

        $animate.enter(child, element, null, copiedOptions);
        $rootScope.$digest();
        expect(copiedOptions).toEqual(initialOptions);

        $animate.flush();
        expect(copiedOptions).toEqual(initialOptions);

        expect(child).toHaveClass('one');
        expect(child).not.toHaveClass('two');

        expect(child.attr('style')).toContain('100px');
        expect(child.attr('style')).toContain('50px');
      });
    });

    it('should execute the enter animation on a <form> with ngIf that has an ' +
      '<input type="email" required>', function() {

      var animationSpy = jasmine.createSpy();

      module(function($animateProvider) {
        $animateProvider.register('.animate-me', function() {
          return {
            enter: function(element, done) {
              animationSpy();
              done();
            }
          };
        });
      });

      inject(function($animate, $rootScope, $compile) {

        element = jqLite(
          '
' +
            '<form class="animate-me" ng-if="show">' +
              '<input ng-model="myModel" type="email" required />' +
            '</form>' +
          '
');

        html(element);

        $compile(element)($rootScope);

        $rootScope.show = true;
        $rootScope.$digest();

        $animate.flush();
        expect(animationSpy).toHaveBeenCalled();
      });
    });
  });
});


text:
package com.nmoncho.events;

/**
 * Defines the contract that an Event listener must comply.
 * @author nMoncho
 *
 */
public interface IEventListener<T extends IEvent> {

	/**
	 * Code runed when an event is fired
	 * @param event been fired
	 */
	public void fire(T event);
}


text:
<?php
declare(strict_types=1);
/**
 * This file is part of beotie/core_bundle
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 7.1
 *
 * @category Request
 * @package  Beotie_Core_Bundle
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace Beotie\CoreBundle\Request\Uri\StringUriElement;

use Beotie\CoreBundle\Request\Uri\StringUri;

/**
 * Path element trait
 *
 * This trait is use for decoupling the path part of the StringUri from the main class
 *
 * @category Request
 * @package  Beotie_Core_Bundle
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
trait PathElementTrait
{
    /**
     * Path
     *
     * This property store the path part of the url
     *
     * @var string
     */
    protected $path = '';

    /**
     * Return an instance with the specified path.
     *
     * This method MUST retain the state of the current instance, and return
     * an instance that contains the specified path.
     *
     * The path can either be empty or absolute (starting with a slash) or
     * rootless (not starting with a slash). Implementations MUST support all
     * three syntaxes.
     *
     * If the path is intended to be domain-relative rather than path relative then
     * it must begin with a slash ("/"). Paths not starting with a slash ("/")
     * are assumed to be relative to some base path known to the application or
     * consumer.
     *
     * Users can provide both encoded and decoded path characters.
     * Implementations ensure the correct encoding as outlined in getPath().
     *
     * @param string $path The path to use with the new instance.
     *
     * @return static A new instance with the specified path.
     * @throws \InvalidArgumentException for invalid paths.
     */
    public function withPath($path)
    {
        return $this->duplicateWith('path', $path);
    }

    /**
     * Retrieve the path component of the URI.
     *
     * The path can either be empty or absolute (starting with a slash) or
     * rootless (not starting with a slash). Implementations MUST support all
     * three syntaxes.
     *
     * Normally, the empty path "" and absolute path "/" are considered equal as
     * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
     * do this normalization because in contexts with a trimmed base path, e.g.
     * the front controller, this difference becomes significant. It's the task
     * of the user to handle both "" and "/".
     *
     * The value returned MUST be percent-encoded, but MUST NOT double-encode
     * any characters. To determine what characters to encode, please refer to
     * RFC 3986, Sections 2 and 3.3.
     *
     * As an example, if the value should include a slash ("/") not intended as
     * delimiter between path segments, that value MUST be passed in encoded
     * form (e.g., "%2F") to the instance.
     *
     * @see    https://tools.ietf.org/html/rfc3986#section-2
     * @see    https://tools.ietf.org/html/rfc3986#section-3.3
     * @return string The URI path.
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Duplicate with
     *
     * This method duplicate the current object and update a property with a given value before returning it
     *
     * @param string $property The property name to update
     * @param mixed  $value    The new property value
     *
     * @return StringUri
     */
    protected abstract function duplicateWith(string $property, $value) : StringUri;
}


text:
EXTERNAL_DOMAIN = "thebossdev.io"
EXTERNAL_FORMAT = "{machine}-test"
INTERNAL_DOMAIN = "test.boss"
NETWORK = "10.20.0.0/16"

AMI_SUFFIX = ".boss"
SCENARIO = "development"

# NOTE: The region in which the lambda is running could be found
# using the http://169.254.169.254/latest/dynamic/instance-identity/document
# url, but then the AVAILABILITY_ZONE_USAGE would not be correct.
# Also REGION is the region in which to launch the test stack, which
# can be different from the lambda's region.
REGION = "us-east-1"
AVAILABILITY_ZONE_USAGE = {
    'lambda': ['b', 'c', 'd', 'e', 'f'],
    'asg': ['b', 'c', 'd', 'e', 'f'],
    'datapipeline': ['a', 'b', 'c', 'd', 'f'],
}

AUTH_RDS = False

LAMBDA_BUCKET = "boss-lambda-env"
LAMBDA_SERVER = None # Build lambdas locally
LAMBDA_SERVER_KEY = None

ACCOUNT_ID = 256215146792
PROFILE = None # Use EC2 credentials

ALERT_TOPIC = 'ProductionMicronsMailingList'

OUTBOUND_BASTION = False

# Get the local IP of the EC2 instance, so that the machine can
# interact with the stack it is standing up, but no one else can
import urllib.request
META_URL = "http://169.254.169.254/latest/meta-data/public-ipv4"
LOCAL_IP = urllib.request.urlopen(META_URL).read().decode("utf-8")

HTTPS_INBOUND = LOCAL_IP + "/32"
SSH_INBOUND = LOCAL_IP + "/32"

SSH_KEY = "auto-build-keypair"

from pathlib import Path
if not (Path.home() / '.ssh' / (SSH_KEY + '.pem')).exists():
    SSH_KEY = None # Makes creating the keypairs easier


text:
// This file is automatically generated.

package adila.db;

/*
 * Sony Xperia C5 Ultra Dual
 *
 * DEVICE: E5533
 * MODEL: E5533
 */
final class e5533_e5533 {
    public static final String DATA = "Sony|Xperia C5 Ultra Dual|";
}


text:
* gem 'kaminari'

* gem 'ransack'

* gem 'cancan'

* gem 'simple-navigation'

* gem 'polywag'

* gem 'simple_form' >= 3.1.0

## Skin Dependencies

* gem 'adminlte-rails'

## Configuration

To change the theme for your application, create an initializer that follows the following formation:

    PageFor.configure do |config|
      config.theme = 'theme-name-here'
      config.simple_form_for :theme-name-here
    end

## Once your AcitveRecord model exists and migrations have run, you can scaffold views and controllers via

    rails g page_for:scaffold ModelName

## JS

    //= require jquery
    //= require jquery_ujs
    //= require bootstrap.min
    //= require adminlte-custom
    //= require actionsheet
    //= require page_for_adminlte
    //= require numerous-2.1.1.min

## CSS

   *= require bootstrap
   *= require font-awesome
   *= require ionicons
   *= require adminlte
   *= require page_for_adminlte
   *= require action_sheet

# editable_table_for

To add a 'Remove' button to editable_table_for instances, add '- t.delete_link_if_can'.

# Troubleshooting

If you get an exception "undefined method `has_attribute?' for ...", you likely forgot to add accepts_nested_attributes_for to your model for the has_many relationships in your form.

## Change Log

* 12/27/2014 - Kaminari looks for theme in subfolder.  For example.  app/views/kaminari/adminlte/*


text:
namespace Assets
{
    public struct Card
    {
        public readonly CardRank Rank;
        public readonly CardSuit Suit;

        public Card(CardRank rank, CardSuit suit)
        {
            Rank = rank;
            Suit = suit;
        }

        public bool IsValidCard
        {
            get
            {
                return Rank != CardRank.Unknown && Suit != CardSuit.Unknown;
            }
        }
    }
}


text:
bool spvParseUniversalLimitsOptions(const char* s, spv_validator_limit* type) {
  auto match = [s](const char* b) {
    return s && (0 == strncmp(s, b, strlen(b)));
  };
  if (match("--max-struct-members")) {
    *type = spv_validator_limit_max_struct_members;
  } else if (match("--max-struct_depth")) {
    *type = spv_validator_limit_max_struct_depth;
  } else if (match("--max-local-variables")) {
    *type = spv_validator_limit_max_local_variables;
  } else if (match("--max-global-variables")) {
    *type = spv_validator_limit_max_global_variables;
  } else if (match("--max-switch-branches")) {
    *type = spv_validator_limit_max_global_variables;
  } else if (match("--max-function-args")) {
    *type = spv_validator_limit_max_function_args;
  } else if (match("--max-control-flow-nesting-depth")) {
    *type = spv_validator_limit_max_control_flow_nesting_depth;
  } else if (match("--max-access-chain-indexes")) {
    *type = spv_validator_limit_max_access_chain_indexes;
  } else {
    // The command line option for this validator limit has not been added.
    // Therefore we return false.
    return false;
  }

  return true;
}

spv_validator_options spvValidatorOptionsCreate() {
  return new spv_validator_options_t;
}

void spvValidatorOptionsDestroy(spv_validator_options options) {
  delete options;
}

void spvValidatorOptionsSetUniversalLimit(spv_validator_options options,
                                          spv_validator_limit limit_type,
                                          uint32_t limit) {
  assert(options && "Validator options object may not be Null");
  switch(limit_type) {
#define LIMIT(TYPE, FIELD)                    \
    case TYPE:                                \
      options->universal_limits_.FIELD = limit; \
      break;
  LIMIT(spv_validator_limit_max_struct_members, max_struct_members)
  LIMIT(spv_validator_limit_max_struct_depth, max_struct_depth)
  LIMIT(spv_validator_limit_max_local_variables, max_local_variables)
  LIMIT(spv_validator_limit_max_global_variables, max_global_variables)
  LIMIT(spv_validator_limit_max_switch_branches, max_switch_branches)
  LIMIT(spv_validator_limit_max_function_args, max_function_args)
  LIMIT(spv_validator_limit_max_control_flow_nesting_depth,
        max_control_flow_nesting_depth)
  LIMIT(spv_validator_limit_max_access_chain_indexes, max_access_chain_indexes)
#undef LIMIT
  }
}


text:
from numba.types.scalars import Boolean
from tpg.action_object import ActionObject
from tpg.program import Program
from tpg.learner import Learner
from tpg.team import Team
from tpg.agent import Agent
from tpg.configuration import configurer
import random
import numpy as np
import pickle
from collections import namedtuple
import json

"""
Functionality for actually growing TPG and evolving it to be functional.
"""
class Trainer:

    """
    Create a trainer to store the various evolutionary parameters, and runs under
    them.

    Important parameters:

    actions: List of actions, typically just set as 'range(n)' (n=18 for Atari).

    teamPopSize: Initial number of teams / root teams, to be maintained through
    evolution.

    rootBasedPop: Whether population size is based on root teams. If true there
    are always roughly the same amount of root teams (uses more RAM).
    Else it ensures the total team population size is 'teamPopSize' (uses
    less RAM).

    memType: Type of memory distribution to use for writing. None or "None" if not
    using memory, otherwise "default", "cauchy1", or "cauchyHalf".

    rampancy: How often to do rampant mutation: (a, b) or (a, b, c). a is to do it every
    a'th generation (keep as zero to not do it), b and c are the range for how
    many times to repeat rampancy (b inclusive, c exclusive/not required).

    operationSet: "def" for ["ADD", "SUB", "MULT", "DIV", "NEG"], or "full" for
    ["ADD", "SUB", "MULT", "DIV", "NEG", "COS", "LOG", "EXP"]. "MEM_READ" and
    "MEM_WRITE" may be added in if applicable. May change to just including the
    list of desired operations in the future.

    traversal: "team" to traverse for an action without repeating any team visits.
    "learner" is similar but with repeat visits to teams and no repeat visits to
    learners.

    prevPops: Either a list of the the root teams from a previous population, or
    a dicitonary with the keys being the environment and the values being a list
    of root teams trained on that environment.

    doMutate: Whether to continue mutating newly created root teams below the team
    level. If true only mutates teams by changing up the learners, but doesn't
    mutate the learners or
    """
    def __init__(self, actions, teamPopSize=360, rootBasedPop=True, gap=0.5,
        inputSize=33600, nRegisters=8, initMaxTeamSize=5, initMaxProgSize=128, maxTeamSize=-1,
        pLrnDel=0.7, pLrnAdd=0.7, pLrnMut=0.3, pProgMut=0.66, pActMut=0.33,
        pActAtom=0.5, pInstDel=0.5, pInstAdd=0.5, pInstSwp=1.0, pInstMut=1.0,
        doElites=True, memType=None, memMatrixShape=(100,8), rampancy=(0,0,0),
        operationSet="def", traversal="team", prevPops=None, mutatePrevs=True,
        initMaxActProgSize=64, nActRegisters=4):

        '''
        Validate inputs
        '''
        int_greater_than_zero = {
            "teamPopSize": teamPopSize,
            "inputSize": inputSize,
            "nRegisters": nRegisters,
            "initMaxTeamSize": initMaxTeamSize,
            "initMaxProgSize": initMaxProgSize,
        }

        for entry in int_greater_than_zero.items():
            self.must_be_integer_greater_than_zero(entry[0], entry[1])

        # Validate doElites
        if type(doElites) is not bool:
            raise Exception("Invalid doElites")

        # Validate rootBasedPop
        if type(rootBasedPop) is not bool:
            raise Exception("Invalid rootBasedPop")

        # Validate Traversal
        valid_traversals = ["team", "learner"]
        if traversal not in valid_traversals:
            raise Exception("Invalid traversal")

        '''
        Gap must be a float greater than 0 but less than or equal to 1
        '''
        if type(gap) is not float or gap == 0.0 or gap > 1.0:
            raise Exception("gap must be a float greater than 0 but less than or equal to 1")

        # Validate Operation Set
        valid_operation_sets = ["def", "full", "robo"]
        if operationSet not in valid_operation_sets:
            raise Exception("Invalid operation set")

        # Validate Probability parameters
        probabilities = {
            "pLrnDel": pLrnDel,
            "pLrnAdd": pLrnAdd,
            "pLrnMut": pLrnMut,
            "pProgMut": pProgMut,
            "pActMut": pActMut,
            "pActAtom": pActAtom,
            "pInstDel": pInstDel,
            "pInstAdd": pInstAdd,
            "pInstSwp": pInstSwp,
            "pInstMut": pInstMut
        }

        for entry in probabilities.items():
            self.validate_probability(entry[0],entry[1])

        # Validate rampancy
        if (
            len(rampancy) != 3 or
            rampancy[0] < 0 or
            rampancy[2] < rampancy[1] or
            rampancy[1] < 0 or
            rampancy[2] < 0
            ):
            raise Exception("Invalid rampancy parameter!", rampancy)

        # store all necessary params

        # first store actions properly
        self.doReal = self.setUpActions(actions)

        # population params
        self.teamPopSize = teamPopSize
        # whether population size is based on root teams or all teams
        self.rootBasedPop = rootBasedPop
        self.gap = gap # portion of root teams to remove each generation

        # input to agent (must be at-least size of input/state from environment)
        self.inputSize = inputSize # defaulted to number of Atari screen pixels
        # number of local memory registers each learner will have
        self.nRegisters = nRegisters

        # params for initializing evolution
        self.initMaxTeamSize = initMaxTeamSize # size of team = # of learners
        self.initMaxProgSize = initMaxProgSize # size of program = # of instructions

        # max team size possible throughout evolution
        self.maxTeamSize = maxTeamSize

        # params for continued evolution
        self.pLrnDel = pLrnDel
        self.pLrnAdd = pLrnAdd
        self.pLrnMut = pLrnMut
        self.pProgMut = pProgMut
        self.pActMut = pActMut
        self.pActAtom = pActAtom
        self.pInstDel = pInstDel
        self.pInstAdd = pInstAdd
        self.pInstSwp = pInstSwp
        self.pInstMut = pInstMut

        # whether to keep elites
        self.doElites = doElites

        if memType == "None":
            self.memType = None
        self.memType = memType
        self.memMatrixShape = memMatrixShape

        self.rampancy = rampancy

        self.operationSet = operationSet

        self.traversal = traversal

        self.initMaxActProgSize = initMaxActProgSize
        # ensure nActRegisters is larger than the largest action length
        if self.doReal:
            nActRegisters = max(max(self.actionLengths), nActRegisters)
        self.nActRegisters = nActRegisters

        # core components of TPG
        self.teams = []
        self.rootTeams = []
        self.learners = []
        self.elites = [] # save best at each task

        self.generation = 0 # track this

        # these are to be filled in by the configurer after
        self.mutateParams = {}
        self.actVars = {}
        self.nOperations = None
        self.functionsDict = {}

        # configure tpg functions and variable appropriately now
        configurer.configure(self, Trainer, Agent, Team, Learner, ActionObject, Program,
            memType is not None, memType, self.doReal, operationSet, traversal)

        #print(self.mutateParams)
        #print(self.functionsDict)
        #print(1/0)

        self.initializePopulations()

    '''
    Validation Method
    '''
    def must_be_integer_greater_than_zero(self, name, value):
        if type(value) is not int or value <= 0:
            raise Exception(name + " must be integer greater than zero. Got " + str(value), name, value)

    '''
    Validation Method
    '''
    def validate_probability(self, name,  value):
        if type(value) is not float or value > 1.0 or value < 0.0:
            raise Exception(name + " is a probability, it must not be greater than 1.0 or less than 0.0", name, value)

    """
    Sets up the actions properly, splitting action codes, and if needed, action
    lengths. Returns whether doing real actions.
    """
    def setUpActions(self, actions):
        if isinstance(actions, int):
            # all discrete actions
            self.actionCodes = range(actions)
            doReal = False
        else: # list of lengths of each action
            # some may be real actions
            self.actionCodes = range(len(actions))
            self.actionLengths = list(actions)
            doReal = True

        return doReal

    """
    Initializes a popoulation of teams and learners generated randomly with only
    atomic actions.
    """
    def initializePopulations(self):
        for i in range(self.teamPopSize):
            # create 2 unique actions and learners
            a1,a2 = random.sample(range(len(self.actionCodes)), 2)

            l1 = Learner(self.mutateParams,
                        program=Program(maxProgramLength=self.initMaxProgSize,
                                         nOperations=self.nOperations,
                                         nDestinations=self.nRegisters,
                                         inputSize=self.inputSize,
                                         initParams=self.mutateParams),
                        actionObj=ActionObject(action=a1, initParams=self.mutateParams),
                        numRegisters=self.nRegisters)
            l2 = Learner(self.mutateParams,
                        program=Program(maxProgramLength=self.initMaxProgSize,
                                         nOperations=self.nOperations,
                                         nDestinations=self.nRegisters,
                                         inputSize=self.inputSize,
                                         initParams=self.mutateParams),
                        actionObj=ActionObject(action=a2, initParams=self.mutateParams),
                        numRegisters=self.nRegisters)

            # save learner population
            self.learners.append(l1)
            self.learners.append(l2)

            # create team and add initial learners
            team = Team(initParams=self.mutateParams)
            team.addLearner(l1)
            team.addLearner(l2)

            # add more learners
            moreLearners = random.randint(0, self.initMaxTeamSize-2)
            for i in range(moreLearners):
                # select action
                act = random.choice(range(len(self.actionCodes)))

                # create new learner
                learner = Learner(initParams=self.mutateParams,
                            program=Program(maxProgramLength=self.initMaxProgSize,
                                             nOperations=self.nOperations,
                                             nDestinations=self.nRegisters,
                                             inputSize=self.inputSize,
                                             initParams=self.mutateParams),
                            actionObj=ActionObject(action=act, initParams=self.mutateParams),
                            numRegisters=self.nRegisters)

                team.addLearner(learner)
                self.learners.append(learner)

            # save to team populations
            self.teams.append(team)
            self.rootTeams.append(team)

    """
    Gets rootTeams/agents. Sorts decending by sortTasks, and skips individuals
    who don't have scores for all skipTasks.
    """
    def getAgents(self, sortTasks=[], multiTaskType='min', skipTasks=[]):
        # remove those that get skipped
        rTeams = [team for team in self.rootTeams
                if len(skipTasks) == 0
                        or any(task not in team.outcomes for task in skipTasks)]

        if len(sortTasks) == 0: # just get all
            return [Agent(team, self.functionsDict, num=i, actVars=self.actVars)
                    for i,team in enumerate(rTeams)]
        else:

            if len(sortTasks) == 1:
                rTeams = [t for t in rTeams if sortTasks[0] in t.outcomes]
                # return teams sorted by the outcome
                return [Agent(team, self.functionsDict, num=i, actVars=self.actVars)
                        for i,team in enumerate(sorted(rTeams,
                                        key=lambda tm: tm.outcomes[sortTasks[0]], reverse=True))]

            else:
                # apply scores/fitness to root teams
                self.scoreIndividuals(sortTasks, multiTaskType=multiTaskType, doElites=False)
                # return teams sorted by fitness
                return [Agent(team, self.functionsDict, num=i, actVars=self.actVars)
                        for i,team in enumerate(sorted(rTeams,
                                        key=lambda tm: tm.fitness, reverse=True))]

    """
    Gets the single best team at the given task, regardless of if its root or not.
    """
    def getEliteAgent(self, task):

        teams = [t for t in self.teams if task in t.outcomes]

        return Agent(max([tm for tm in teams],
                        key=lambda t: t.outcomes[task]),
                     self.functionsDict, num=0, actVars=self.actVars)

    """
    Apply saved scores from list to the agents.
    """
    def applyScores(self, scores): # used when multiprocessing
        for score in scores:
            for rt in self.rootTeams:
                if score[0] == rt.id:
                    for task, outcome in score[1].items():
                        rt.outcomes[task] = outcome
                    break # on to next score

        return self.rootTeams

    """
    Evolve the populations for improvements.
    """
    def evolve(self, tasks=['task'], multiTaskType='min', extraTeams=None):
        self.scoreIndividuals(tasks, multiTaskType=multiTaskType,
                doElites=self.doElites) # assign scores to individuals
        self.saveFitnessStats() # save fitness stats
        self.select(extraTeams) # select individuals to keep
        self.generate(extraTeams) # create new individuals from those kept
        self.nextEpoch() # set up for next generation
        #self.validate_graph() # validate the tpg (for debug only)
    """
    Assigns a fitness to each agent based on performance at the tasks. Assigns
    fitness values, or just returns sorted root teams.
    """
    def scoreIndividuals(self, tasks, multiTaskType='min', doElites=True):
        # handle generation of new elites, typically just done in evolution
        if doElites:
            # get the best agent at each task
            self.elites = [] # clear old elites
            for task in tasks:
                self.elites.append(max([team for team in self.rootTeams],
                                        key=lambda t: t.outcomes[task]))

        if len(tasks) == 1: # single fitness
            for team in self.rootTeams:
                team.fitness = team.outcomes[tasks[0]]
        else: # multi fitness
            # assign fitness to each agent based on tasks and score type
            if 'pareto' not in multiTaskType or 'lexicase' not in multiTaskType:
                self.simpleScorer(tasks, multiTaskType=multiTaskType)
            elif multiTaskType == 'paretoDominate':
                self.paretoDominateScorer(tasks)
            elif multiTaskType == 'paretoNonDominated':
                self.paretoNonDominatedScorer(tasks)
            elif multiTaskType == 'lexicaseStatic':
                self.lexicaseStaticScorer(tasks)
            elif multiTaskType == 'lexicaseDynamic':
                self.lexicaseDynamicScorer(tasks)

    """
    Gets either the min, max, or average score from each individual for ranking.
    """
    def simpleScorer(self, tasks, multiTaskType='min'):
        # first find min and max in each task
        mins = []
        maxs = []
        for task in tasks:
            mins.append(min([team.outcomes[task] for team in self.rootTeams]))
            maxs.append(max([team.outcomes[task] for team in self.rootTeams]))

        # assign fitness
        if multiTaskType == 'min':
            for rt in self.rootTeams:
                rt.fitness = min([(rt.outcomes[task]-mins[i])/(maxs[i]-mins[i])
                        for i,task in enumerate(tasks)])
        elif multiTaskType == 'max':
            for rt in self.rootTeams:
                rt.fitness = max([(rt.outcomes[task]-mins[i])/(maxs[i]-mins[i])
                        for i,task in enumerate(tasks)])
        elif multiTaskType == 'average':
            for rt in self.rootTeams:
                scores = [(rt.outcomes[task]-mins[i])/(maxs[i]-mins[i])
                            for i,task in enumerate(tasks)]
                rt.fitness = sum(scores)/len(scores)

    """
    Rank agents based on how many other agents it dominates
    """
    def paretoDominateScorer(self, tasks):
        for t1 in self.rootTeams:
            t1.fitness = 0
            for t2 in self.rootTeams:
                if t1 == t2:
                    continue # don't compare to self

                # compare on all tasks
                if all([t1.outcomes[task] >= t2.outcomes[task]
                         for task in tasks]):
                    t1.fitness += 1

    """
    Rank agents based on how many other agents don't dominate it
    """
    def paretoNonDominatedScorer(self, tasks):
        for t1 in self.rootTeams:
            t1.fitness = 0
            for t2 in self.rootTeams:
                if t1 == t2:
                    continue # don't compare to self

                # compare on all tasks
                if all([t1.outcomes[task] < t2.outcomes[task]
                         for task in tasks]):
                    t1.fitness -= 1

    def lexicaseStaticScorer(self, tasks):
        stasks = list(tasks)
        random.shuffle(stasks)

        for rt in self.rootTeams:
            rt.fitness = rt.outcomes[tasks[0]]

    def lexicaseDynamicScorer(self, tasks):
        pass

    """
    Save some stats on the fitness.
    """
    def saveFitnessStats(self):
        fitnesses = []
        for rt in self.rootTeams:
            fitnesses.append(rt.fitness)

        self.fitnessStats = {}
        self.fitnessStats['fitnesses'] = fitnesses
        self.fitnessStats['min'] = min(fitnesses)
        self.fitnessStats['max'] = max(fitnesses)
        self.fitnessStats['average'] = sum(fitnesses)/len(fitnesses)

    """
    Gets stats on some task.
    """
    def getTaskStats(self, task):
        scores = []
        for rt in self.rootTeams:
            scores.append(rt.outcomes[task])

        scoreStats = {}
        scoreStats['scores'] = scores
        scoreStats['min'] = min(scores)
        scoreStats['max'] = max(scores)
        scoreStats['average'] = sum(scores)/len(scores)

        return scoreStats

    """
    Select a portion of the root team population to keep according to gap size.
    """
    def select(self, extraTeams=None):

        rankedTeams = sorted(self.rootTeams, key=lambda rt: rt.fitness, reverse=True)
        numKeep = len(self.rootTeams) - int(len(self.rootTeams)*self.gap)
        deleteTeams = rankedTeams[numKeep:]

        #print("BEFORE SELECTION:")

        pre_orphans = [learner for learner in self.learners if learner.numTeamsReferencing() == 0]

        #print("Number of orphans before selection: {}".format(len(pre_orphans)))

        orphan_teams = [team for team in self.teams if len(team.inLearners) == 0 and team not in self.rootTeams]
        #print("Number of orphan teams before selection: {}".format(len(orphan_teams)))

        #print("Learners:")
        #for cursor in self.learners:
        #   print("Learner {} -> [{}]{} inTeams:".format( cursor.id, "Atomic" if cursor.isActionAtomic() else "Team", cursor.actionObj.actionCode if cursor.isActionAtomic() else cursor.actionObj.teamAction.id))
        #    for t_id in cursor.inTeams:
        #        print("\t{}".format(t_id ))

        #for cursor in self.teams:
        #    print("Team: {} inLearners:".format(cursor.id))
        #    for l_id in cursor.inLearners:
        #        print("\t{}".format(l_id))

        #print("-----------------------------------------------------")

        # delete the team unless it is an elite (best at some task at-least)
        # don't delete elites because they may not be root - TODO: elaborate
        for team in [t for t in deleteTeams if t not in self.elites]:

            # remove learners from team and delete team from populations
            if extraTeams is None or team not in extraTeams:
                team.removeLearners()
            self.teams.remove(team)
            self.rootTeams.remove(team)

        #print("AFTER SELECTION:")
        # Find all learners that have no teams pointing to them
        orphans = [learner for learner in self.learners if learner.numTeamsReferencing() == 0]
        #print("Number of orphans after selection: {}".format(len(orphans)))

        #print("Orphans:")
        #for cursor in orphans:
        #    print("\t{}".format(cursor.id))

        #print("Learners:")
        #for cursor in self.learners:
        #    print("Learner {} -> [{}]{} inTeams:".format( cursor.id, "Atomic" if cursor.isActionAtomic() else "Team", cursor.actionObj.actionCode if cursor.isActionAtomic() else cursor.actionObj.teamAction.id))
        #    for t_id in cursor.inTeams:
        #        print("\t{}".format(t_id ))

        #for cursor in self.teams:
        #    print("Team: {} inLearners:".format(cursor.id))
        #    for l_id in cursor.inLearners:
        #        print("\t{}".format(l_id))

        #print("-----------------------------------------------------")

        # These learners will be removed, but before we can do that, we should remove
        # their ids from any team's inLearners that the orphans are pointing to.
        for cursor in orphans:
            if not cursor.isActionAtomic(): # If the orphan does NOT point to an atomic action
                # Get the team the orphan is pointing to and remove the orphan's id from the team's in learner list
                cursor.actionObj.teamAction.inLearners.remove(str(cursor.id))

        # Finaly, purge the orphans
        self.learners = [learner for learner in self.learners if learner.numTeamsReferencing() > 0]

    """
    Generates new rootTeams based on existing teams.
    """
    def generate(self, extraTeams=None):

        # extras who are already part of the team population
        protectedExtras = []
        extrasAdded = 0

        # add extras into the population
        if extraTeams is not None:
            for team in extraTeams:
                if team not in self.teams:
                    self.teams.append(team)
                    extrasAdded += 1
                else:
                    protectedExtras.append(team)

        oLearners = list(self.learners)
        oTeams = list(self.teams)

        # update generation in mutateParams
        self.mutateParams["generation"] = self.generation

        # get all the current root teams to be parents
        while (len(self.teams) < self.teamPopSize + extrasAdded or
                (self.rootBasedPop and self.countRootTeams() < self.teamPopSize)):
            # get parent root team, and child to be based on that
            parent = random.choice(self.rootTeams)
            child = Team(initParams=self.mutateParams)

            # child starts just like parent
            for learner in parent.learners:
                child.addLearner(learner)

            # then mutates
            child.mutate(self.mutateParams, oLearners, oTeams)

            self.teams.append(child)

        # remove unused extras
        if extraTeams is not None:
            for team in extraTeams:
                if team.numLearnersReferencing() == 0 and team not in protectedExtras:
                    self.teams.remove(team)

    """
    Finalize populations and prepare for next generation/epoch.
    """
    def nextEpoch(self):
        # add in newly added learners, and decide root teams
        self.rootTeams = []
        for team in self.teams:
            # add any new learners to the population
            for learner in team.learners:
                if learner not in self.learners:
                    #print("Adding {} to trainer learners".format(learner.id))
                    self.learners.append(learner)

            # maybe make root team
            if team.numLearnersReferencing() == 0 or team in self.elites:
                self.rootTeams.append(team)

        self.generation += 1

    """
    Removes hitchhikers, learners that are never used, except for the last atomic action on the team.
    teamLearnerVisists is a dict with team keys and values represending the learners that are
    actually visited on the team. Any learner on a team not in this list gets deleted.
    Evolve should be called right after to properly remove the learners from the population.
    """
    def removeHitchhikers(self, teams, visitedLearners):
        learnersRemoved = []
        teamsAffected = []

        for i, team in enumerate(teams):
            affected = False
            for learner in team.learners:
                # only remove if non atomic, or atomic and team has > 1 atomic actions
                if learner not in visitedLearners[i] and (
                        not learner.isActionAtomic() or
                            (learner.isActionAtomic() and team.numAtomicActions() > 1)):
                    affected = True
                    learnersRemoved.append(learner)
                    team.removeLearner(learner)

            if affected:
                teamsAffected.append(team)

        return learnersRemoved, teamsAffected

    '''
    Go through all teams and learners and make sure their inTeams/inLearners correspond with
    their team.learner/teamActions as expected.
    '''
    def validate_graph(self):
        print("Validating graph")

        print("Checking for broken learners")
        for cursor in self.learners:
            if cursor.isActionAtomic() and cursor.actionObj.actionCode == None:
                print("{} is an action atomic learner with no actionCode!".format(str(cursor.id)))
            if cursor.actionObj.teamAction == None and cursor.actionObj.actionCode == None:
                print("{} has no action!".format(str(cursor.id)))

        learner_map = {}
        for cursor in self.learners:
            if str(cursor.id) not in learner_map:
                learner_map[str(cursor.id)] = cursor.inTeams
            else:
                raise Exception("Duplicate learner id in trainer!")

        '''
        For every entry in the learner map check that the corresponding team has the learner
        in its learners
        '''
        for i,cursor in enumerate(learner_map.items()):
            for expected_team in cursor[1]:
                found_team = False
                for team in self.teams:
                    if str(team.id) == expected_team:
                        found_learner = 0
                        for learner in team.learners:
                            if str(learner.id) == cursor[0]:
                                found_learner += 1
                        if found_learner != 1:
                            print("found_learner = {} for learner {} in team {}".format(found_learner, cursor[0], str(team.id)))
                        found_team = True
                        break
                if found_team == False:
                    print("Could not find expected team {} in trainer".format(expected_team))
            print("learner {} inTeams valid [{}/{}]".format(cursor[0], i, len(learner_map.items())-1))

        '''
        Verify that for every inLearner in a team, the learner exists in the trainer, pointing to that team
        '''
        team_map = {}
        for cursor in self.teams:
            if str(cursor.id) not in team_map:
                team_map[str(cursor.id)] = cursor.inLearners
            else:
                raise Exception("Duplicate team id in trainer!")

        for i,cursor in enumerate(team_map.items()):
            for expected_learner in cursor[1]:
                found_learner = False
                points_to_team = False
                for learner in self.learners:
                    if str(learner.id) == expected_learner:
                        found_learner = True
                        if str(learner.actionObj.teamAction.id) == cursor[0]:
                            points_to_team = True
                            break
                if found_learner == False:
                    print("Could not find learner {} from team {} inLearners in trainer.".format(expected_learner, cursor[0]))
                if points_to_team == False:
                    print("Learner {} does not point to team {}".format(expected_learner, cursor[0]))
            print("team {} inLearners valid [{}/{}]".format(cursor[0], i, len(team_map.items())-1))
    """
    Get the number of root teams currently residing in the teams population.
    """
    def countRootTeams(self):
        numRTeams = 0
        for team in self.teams:
            if team.numLearnersReferencing() == 0:
                numRTeams += 1

        return numRTeams

    def get_graph(self):

        result = {
            "nodes":[],
            "links":[]
        }

        # First add action codes as nodes
        for actionCode in self.actionCodes:
            result["nodes"].append(
                {
                    "id": str(actionCode),
                    "type": "action"
                }
            )

        # Then add teams as nodes
        for team in self.teams:
            result["nodes"].append(
                {
                    "id": str(team.id),
                    "type": "rootTeam" if team in self.rootTeams else "team"
                }
            )

        # Then add learners as nodes
        for learner in self.learners:
            result["nodes"].append(
                {
                    "id": str(learner.id),
                    "type": "learner"
                }
            )

        # Then add links from learners to teams
        for team in self.teams:
            for learner in team.inLearners:
                result["links"].append(
                    {
                        "source": learner,
                        "target": str(team.id)
                    }
                )

        # Then add links from teams to learners
        for learner in self.learners:
            for team in learner.inTeams:
                result["links"].append(
                    {
                        "source": team,
                        "target": str(learner.id)
                    }
                )

            # Also add links to action codes
            if learner.isActionAtomic():
                result["links"].append(
                    {
                        "source": str(learner.id),
                        "target": str(learner.actionObj.actionCode)
                    }
                )

        # with open("tpg_{}.json".format(self.generation), 'w') as out_file:
        #     json.dump(result, out_file)
        return result

    """
    Function to cleanup anything that may interfere with another trainer run in
    the same thread of execution. Currently just sets tpg module functions to defaults.
    """
    def cleanup(self):
        configurer.configureDefaults(self, Trainer, Agent, Team, Learner, ActionObject, Program)

    """
    Ensures proper functions are in place for all classes. Ran after loading from a file,
    and may need to be ran in other cases such as multiprocessing (though in out typical use
    that is done at the agent level).
    """
    def configFunctions(self):
        # first set up Agent functions
        Agent.configFunctions(self.functionsDict["Agent"])

        # set up Team functions
        Team.configFunctions(self.functionsDict["Team"])

        # set up Learner functions
        Learner.configFunctions(self.functionsDict["Learner"])

        # set up ActionObject functions
        ActionObject.configFunctions(self.functionsDict["ActionObject"])

        # set up Program functions
        Program.configFunctions(self.functionsDict["Program"])

    """
    Save the trainer to the file, saving any class values to the instance.
    """
    def saveToFile(self, fileName):
        pickle.dump(self, open(fileName, 'wb'))

"""
Load some trainer from the file, returning it and repopulate class values.
"""
def loadTrainer(fileName):
    trainer = pickle.load(open(fileName, 'rb'))
    trainer.configFunctions()
    return trainer


text:
<?php

use Lechimp\Dicto\App\Config;
use Lechimp\Dicto\Report;

class ConfigTest extends \PHPUnit\Framework\TestCase
{
    public function test_smoke()
    {
        $config = new Config("/the/path", [
            [ "project" =>
                [ "root" => "/root/dir"
                , "storage" => "/data"
                , "rules" => "/rules"
                ]
            , "analysis" =>
                [ "ignore" =>
                    [ ".*\\.omit_me"
                    ]
                ]
            ]]);
        $this->assertEquals("/rules", $config->project_rules());
        $this->assertEquals("/root/dir", $config->project_root());
        $this->assertEquals("/data", $config->project_storage());
        $this->assertEquals([".*\\.omit_me"], $config->analysis_ignore());
        $this->assertEquals("/the/path", $config->path());
    }

    public function test_defaults()
    {
        $config = new Config("/the/path", [
            [ "project" =>
                [ "root" => "/root/dir"
                , "rules" => "/rules"
                ]
            ]]);

        $this->assertEquals(".", $config->project_storage());
        $this->assertEquals([], $config->analysis_ignore());
        $this->assertFalse($config->analysis_store_index());
        $this->assertTrue($config->analysis_store_results());
        $default_schemas =
            [ \Lechimp\Dicto\Rules\DependOn::class
            , \Lechimp\Dicto\Rules\Invoke::class
            , \Lechimp\Dicto\Rules\ContainText::class
            ];
        $this->assertEquals($default_schemas, $config->rules_schemas());
        $default_properties =
            [ \Lechimp\Dicto\Variables\Name::class
            , \Lechimp\Dicto\Variables\In::class
            ];
        $this->assertEquals($default_properties, $config->rules_properties());
        $default_variables =
            [ \Lechimp\Dicto\Variables\Everything::class
            , \Lechimp\Dicto\Variables\Namespaces::class
            , \Lechimp\Dicto\Variables\Classes::class
            , \Lechimp\Dicto\Variables\Interfaces::class
            , \Lechimp\Dicto\Variables\Traits::class
            , \Lechimp\Dicto\Variables\Functions::class
            , \Lechimp\Dicto\Variables\Globals::class
            , \Lechimp\Dicto\Variables\Files::class
            , \Lechimp\Dicto\Variables\Methods::class
            , \Lechimp\Dicto\Variables\ErrorSuppressor::class
            , \Lechimp\Dicto\Variables\ExitOrDie::class
            , \Lechimp\Dicto\Variables\Eval_::class
            ];
        $this->assertEquals($default_variables, $config->rules_variables());
        $this->assertEquals(false, $config->runtime_check_assertions());
    }

    public function test_overwrite_lists()
    {
        $config = new Config("/the/path", [
            [ "project" =>
                [ "root" => "/root/dir"
                , "rules" => "/rules"
                ]
            , "rules" =>
                [ "schemas" => []
                , "properties" => []
                , "variables" => []
                ]
            ]]);
        $this->assertEquals([], $config->rules_schemas());
        $this->assertEquals([], $config->rules_properties());
        $this->assertEquals([], $config->rules_variables());
    }

    public function test_runtime_config()
    {
        $config = new Config("/the/path", [
            [ "project" =>
                [ "root" => "/root/dir"
                , "storage" => "/data"
                , "rules" => "/rules"
                ]
            , "runtime" =>
                [ "check_assertions" => true
                ]
            ]]);

        $this->assertEquals(true, $config->runtime_check_assertions());
    }

    public function test_merge()
    {
        $config = new Config(
            "/the/path",
            [
                [ "project" =>
                    [ "storage" => "/data"
                    , "rules" => "/rules"
                    ]
                ]
            ,
                [ "project" =>
                    [ "root" => "/root/dir"
                    , "rules" => "/other_rules"
                    ]
                , "analysis" =>
                    [ "ignore" =>
                        [ ".*\\.omit_me"
                        ]
                    , "store_index" => true
                    ]
                ]
            ]
        );
        $this->assertEquals("/other_rules", $config->project_rules());
        $this->assertEquals("/root/dir", $config->project_root());
        $this->assertEquals("/data", $config->project_storage());
        $this->assertEquals([".*\\.omit_me"], $config->analysis_ignore());
        $this->assertTrue($config->analysis_store_index());
    }

    public function test_path_resolution()
    {
        $config = new Config("/the/path/", [
            [ "project" =>
                [ "root" => "./root/dir"
                , "storage" => "./data"
                , "rules" => "./rules"
                ]
            , "analysis" =>
                [ "ignore" =>
                    [ ".*\\.omit_me"
                    ]
                ]
            ]]);
        $this->assertEquals("/the/path", $config->path());
        $this->assertEquals("/the/path/rules", $config->project_rules());
        $this->assertEquals("/the/path/root/dir", $config->project_root());
        $this->assertEquals("/the/path/data", $config->project_storage());
    }

    public function test_reports()
    {
        $config = new Config("/the/path", [
            [ "project" =>
                [ "root" => "/root/dir"
                , "storage" => "/data"
                , "rules" => "/rules"
                ]
            , "analysis" =>
                [ "ignore" =>
                    [ ".*\\.omit_me"
                    ]
                ]
            , "reports" =>
                [
                    [ "class" => "DiffPerRule"
                    , "name" => "foobar"
                    ]
                ,   [ "class" => "\\Foo\\Bar"
                    , "name" => "foo"
                    , "source" => "foobar.php"
                    , "target" => "foobar.html"
                    , "config" => []
                    ]
                ,   [ "name" => "bar"
                    , "class" => "DiffPerRule"
                    , "target" => "default.html"
                    ]
                ]
            ]]);

        $expected =
            [ new Report\Config(
                    "/the/path",
                    "DiffPerRule",
                    null,
                    [],
                    "foobar"
                )
            , new Report\Config(
                    "/the/path",
                    "\\Foo\\Bar",
                    "foobar.html",
                    [],
                    "foo",
                    "foobar.php"
                )
            , new Report\Config(
                    "/the/path",
                    "DiffPerRule",
                    "default.html",
                    [],
                    "bar"
                )
            ];
        $this->assertEquals($expected, $config->reports());

        $r1 = $config->reports()[1];
        $this->assertEquals("\\Foo\\Bar", $r1->class_name());
        $this->assertEquals("foobar.html", $r1->target());
        $this->assertEquals([], $r1->config());
        $this->assertEquals("foo", $r1->name());
        $this->assertEquals("foobar.php", $r1->source_path());

        $r2 = $config->reports()[2];
        $this->assertEquals("bar", $r2->name());
    }
}


text:
# Hacking `hostapd`
Even if we have set up 40Mhz bandwith in IEEE 802.11, we might depressedly find that the actual speed rate is not as fast as we thought. Many blogs point out that this has something to do with `hostapd`, which strictly puts IEEE specification. When turning on debug mode, we can see the reason.

	20/40 MHz operation not permitted on channel pri=6 sec=10 based on overlapping BSSes

IEEE 802.11n specification seems to have defined the rule whether to use 40MHz mode or not. One principle is when the neighbour channel is in heavy traffic, the second channel shouldn't be enabled, that is to say falling back to 20MHz. **However,** almost all wireless routers in the market now refuse to obey this rule. In this case, we can never get chance to make use of 40MHz mode because in modern cities there are so many WiFi hotspots.

Therefore, I think we have the right not to set up our wireless network on advice of IEEE specification so strictly. Some hacking is necessary.

This instruction referred to [a blog by Anthony Wong](http://blog.anthonywong.net/2015/07/19/boost-wifi-speed-raspberry-pi-hostapd/) and [another by Li Chi](http://blog.csdn.net/subfate/article/details/52177035).

## Get the source code of `hostapd`
* If ever step in the instructions before is followed, `deb-src` source must have been added. Just type in:

		apt-get source hostapd
* Install all compilation dependencies of the source code.

		apt-get build-dep hostapd

## Modify source code
The following instruction is base on the source wpa-2.3.

In file `/src/ap/hw_features.c`,we can find out the basic logic to decide to use 20MHz or 40MHz mode:

```C
static void ieee80211n_check_scan(struct hostapd_iface *iface)
{
        struct wpa_scan_results *scan_res;
        int oper40;
        int res;

        /* Check list of neighboring BSSes (from scan) to see whether 40 MHz is
         * allowed per IEEE Std 802.11-2012, 10.15.3.2 */

        iface->scan_cb = NULL;

        scan_res = hostapd_driver_get_scan_results(iface->bss[0]);
        if (scan_res == NULL) {
                hostapd_setup_interface_complete(iface, 1);
                return;
        }

		//Pay attention HERE!
        if (iface->current_mode->mode == HOSTAPD_MODE_IEEE80211A)
                oper40 = ieee80211n_check_40mhz_5g(iface, scan_res);
        else
                oper40 = ieee80211n_check_40mhz_2g4(iface, scan_res);
        wpa_scan_results_free(scan_res);

        iface->secondary_ch = iface->conf->secondary_channel;
        if (!oper40) {
                wpa_printf(MSG_INFO, "20/40 MHz operation not permitted on "
                           "channel pri=%d sec=%d based on overlapping BSSes",
                           iface->conf->channel,
                           iface->conf->channel +
                           iface->conf->secondary_channel * 4);
                iface->conf->secondary_channel = 0;
                if (iface->drv_flags & WPA_DRIVER_FLAGS_HT_2040_COEX) {
                        /*
                         * TODO: Could consider scheduling another scan to check
                         * if channel width can be changed if no coex reports
                         * are received from associating stations.
                         */
                }
        }

        res = ieee80211n_allowed_ht40_channel_pair(iface);
        if (!res) {
                iface->conf->secondary_channel = 0;
                wpa_printf(MSG_INFO, "Fallback to 20 MHz");
        }

        hostapd_setup_interface_complete(iface, !res);
}
```

Obviously, the variant `oper40` is used as a flag. A lazy modification is of course to simply forcefully set `oper40` to 1. So, just add a line:

```C
        oper40=1;
```

Done.

## Compile and install
* Change the working directory to the source code directory, such as `~/wpa-2.3/`.
* Use `fakeroot` to get temporary permission to compile:

		fakeroot debian/rules binary
* Compilation takes some time. Just wait patiently.
* After compilation, return to the upper directory. There is a `deb` file named like `hostapd_2.3-1+deb8u3_armhf.deb`. Use `dpkg` command to install it manually.
* Reboot your Raspberry Pi and then enjoy faster network!


text:
// This file implements the ICategoryProvider Interface and Gateway for Python.
// Generated by makegw.py

#include "shell_pch.h"
#include "PyICategoryProvider.h"

// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation

PyICategoryProvider::PyICategoryProvider(IUnknown *pdisp):
	PyIUnknown(pdisp)
{
	ob_type = &type;
}

PyICategoryProvider::~PyICategoryProvider()
{
}

/* static */ ICategoryProvider *PyICategoryProvider::GetI(PyObject *self)
{
	return (ICategoryProvider *)PyIUnknown::GetI(self);
}

// @pymethod |PyICategoryProvider|CanCategorizeOnSCID|Description of CanCategorizeOnSCID.
PyObject *PyICategoryProvider::CanCategorizeOnSCID(PyObject *self, PyObject *args)
{
	ICategoryProvider *pICP = GetI(self);
	if ( pICP == NULL )
		return NULL;
	SHCOLUMNID scid;
	PyObject *obpscid;
	// @pyparm <o SHCOLUMNID>|pscid||Description for pscid
	if ( !PyArg_ParseTuple(args, "O:CanCategorizeOnSCID", &obpscid) )
		return NULL;
	BOOL bPythonIsHappy = TRUE;
	if (!PyObject_AsSHCOLUMNID(obpscid, &scid ))
		return NULL;
	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pICP->CanCategorizeOnSCID( &scid );
	PY_INTERFACE_POSTCALL;
	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pICP, IID_ICategoryProvider );
	PyObject *ret = (hr==S_OK) ? Py_True : Py_False;
	Py_INCREF(ret);
	return ret;
}

// @pymethod |PyICategoryProvider|GetDefaultCategory|Description of GetDefaultCategory.
PyObject *PyICategoryProvider::GetDefaultCategory(PyObject *self, PyObject *args)
{
	ICategoryProvider *pICP = GetI(self);
	if ( pICP == NULL )
		return NULL;
	if ( !PyArg_ParseTuple(args, ":GetDefaultCategory") )
		return NULL;
	HRESULT hr;
	GUID guid = __uuidof(NULL);
	SHCOLUMNID scid;
	PY_INTERFACE_PRECALL;
	hr = pICP->GetDefaultCategory( &guid, &scid );
	PY_INTERFACE_POSTCALL;
	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pICP, IID_ICategoryProvider );
	return Py_BuildValue("NN", PyWinObject_FromIID(guid), PyObject_FromSHCOLUMNID(&scid));
}

// @pymethod |PyICategoryProvider|GetCategoryForSCID|Description of GetCategoryForSCID.
PyObject *PyICategoryProvider::GetCategoryForSCID(PyObject *self, PyObject *args)
{
	ICategoryProvider *pICP = GetI(self);
	if ( pICP == NULL )
		return NULL;
	SHCOLUMNID scid;
	PyObject *obpscid;
	// @pyparm <o SHCOLUMNID>|pscid||Description for pscid
	if ( !PyArg_ParseTuple(args, "O:GetCategoryForSCID", &obpscid) )
		return NULL;
	BOOL bPythonIsHappy = TRUE;
	if (!PyObject_AsSHCOLUMNID( obpscid, &scid ))
		return NULL;
	HRESULT hr;
	GUID guid;
	PY_INTERFACE_PRECALL;
	hr = pICP->GetCategoryForSCID( &scid, &guid );
	PY_INTERFACE_POSTCALL;

	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pICP, IID_ICategoryProvider );
	return PyWinObject_FromIID(guid);
}

// @pymethod |PyICategoryProvider|EnumCategories|Description of EnumCategories.
PyObject *PyICategoryProvider::EnumCategories(PyObject *self, PyObject *args)
{
	ICategoryProvider *pICP = GetI(self);
	if ( pICP == NULL )
		return NULL;
	if ( !PyArg_ParseTuple(args, ":EnumCategories") )
		return NULL;
	HRESULT hr;
	IEnumGUID *penum;
	PY_INTERFACE_PRECALL;
	hr = pICP->EnumCategories( &penum );
	PY_INTERFACE_POSTCALL;
	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pICP, IID_ICategoryProvider );
	return PyCom_PyObjectFromIUnknown(penum, IID_IEnumGUID, FALSE);
}

// @pymethod |PyICategoryProvider|GetCategoryName|Description of GetCategoryName.
PyObject *PyICategoryProvider::GetCategoryName(PyObject *self, PyObject *args)
{
	ICategoryProvider *pICP = GetI(self);
	if ( pICP == NULL )
		return NULL;
	GUID guid;
	PyObject *obpguid;
	// @comm The buffer is always 1024 chars long
	WCHAR buffer[1024];
	// @pyparm <o PyIID>|guid||Description for pguid
	if ( !PyArg_ParseTuple(args, "O:GetCategoryName", &obpguid) )
		return NULL;
	BOOL bPythonIsHappy = TRUE;
	if (!PyWinObject_AsIID(obpguid, &guid ))
		return NULL;
	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pICP->GetCategoryName( &guid, buffer, sizeof(buffer)/sizeof(buffer[0]));
	PY_INTERFACE_POSTCALL;
	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pICP, IID_ICategoryProvider );
	return PyWinObject_FromWCHAR(buffer);
}

// @pymethod |PyICategoryProvider|CreateCategory|Description of CreateCategory.
PyObject *PyICategoryProvider::CreateCategory(PyObject *self, PyObject *args)
{
	ICategoryProvider *pICP = GetI(self);
	if ( pICP == NULL )
		return NULL;
	GUID guid;
	PyObject *obpguid;
	// @pyparm <o PyIID>|guid||Description for pguid
	IID riid;
	PyObject *obriid;
	// @pyparm <o PyIID>|riid||Description for riid
	if ( !PyArg_ParseTuple(args, "OO:CreateCategory", &obpguid, &obriid) )
		return NULL;
	if (!PyWinObject_AsIID(obpguid, &guid ) || !PyWinObject_AsIID(obriid, &riid))
		return NULL;
	HRESULT hr;
	void *ret;
	PY_INTERFACE_PRECALL;
	hr = pICP->CreateCategory( &guid, riid, &ret );
	PY_INTERFACE_POSTCALL;

	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pICP, IID_ICategoryProvider );
	return PyCom_PyObjectFromIUnknown((IUnknown *)ret, riid, FALSE);
}

// @object PyICategoryProvider|Description of the interface
static struct PyMethodDef PyICategoryProvider_methods[] =
{
	{ "CanCategorizeOnSCID", PyICategoryProvider::CanCategorizeOnSCID, 1 }, // @pymeth CanCategorizeOnSCID|Description of CanCategorizeOnSCID
	{ "GetDefaultCategory", PyICategoryProvider::GetDefaultCategory, 1 }, // @pymeth GetDefaultCategory|Description of GetDefaultCategory
	{ "GetCategoryForSCID", PyICategoryProvider::GetCategoryForSCID, 1 }, // @pymeth GetCategoryForSCID|Description of GetCategoryForSCID
	{ "EnumCategories", PyICategoryProvider::EnumCategories, 1 }, // @pymeth EnumCategories|Description of EnumCategories
	{ "GetCategoryName", PyICategoryProvider::GetCategoryName, 1 }, // @pymeth GetCategoryName|Description of GetCategoryName
	{ "CreateCategory", PyICategoryProvider::CreateCategory, 1 }, // @pymeth CreateCategory|Description of CreateCategory
	{ NULL }
};

PyComTypeObject PyICategoryProvider::type("PyICategoryProvider",
		&PyIUnknown::type,
		sizeof(PyICategoryProvider),
		PyICategoryProvider_methods,
		GET_PYCOM_CTOR(PyICategoryProvider));
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGCategoryProvider::CanCategorizeOnSCID(
		/* [in] */ __RPC__in const SHCOLUMNID * pscid)
{
	PY_GATEWAY_METHOD;
	PyObject *ret;
	HRESULT hr=InvokeViaPolicy("CanCategorizeOnSCID", &ret, "(N)", PyObject_FromSHCOLUMNID(pscid));
	if (FAILED(hr))
		return hr;
	hr = S_FALSE;
	if (PyInt_Check(ret)) // make a bool
		hr = PyInt_AsLong(ret) ? S_OK : S_FALSE;
	Py_DECREF(ret);
	return hr;
}

STDMETHODIMP PyGCategoryProvider::GetDefaultCategory(
		/* [out] */ __RPC__out GUID * pguid,
		/* [out] */ __RPC__out SHCOLUMNID * pscid)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	HRESULT hr=InvokeViaPolicy("GetDefaultCategory", &result);
	if (FAILED(hr)) return hr;
	// GUID is documented by MSDN as unused - but the FolderView MSDN
	// only sets *pguid (it sets 'pscid' - without the '*' - which has
	// no effect!
	PyObject *obguid, *obscid;
	if (!PyArg_ParseTuple(result, "OO:GetDefaultCategory result", &obguid, &obscid))
		hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetDefaultCategory");
	else {
		if (!PyWinObject_AsIID(obguid , pguid) || !PyObject_AsSHCOLUMNID(obscid, pscid))
			hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetDefaultCategory");
	}
	Py_DECREF(result);
	return hr;
}

STDMETHODIMP PyGCategoryProvider::GetCategoryForSCID(
		/* [in] */ __RPC__in const SHCOLUMNID * pscid,
		/* [out] */ __RPC__out GUID * pguid)
{
	PY_GATEWAY_METHOD;
	PyObject *obpscid = PyObject_FromSHCOLUMNID(pscid);
	if (obpscid==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetCategoryForSCID");
	PyObject *result;
	HRESULT hr=InvokeViaPolicy("GetCategoryForSCID", &result, "(O)", obpscid);
	Py_DECREF(obpscid);
	if (FAILED(hr)) return hr;
	if (!PyWinObject_AsIID(result, pguid))
		hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetCategoryForSCID");
	Py_DECREF(result);
	return hr;
}

STDMETHODIMP PyGCategoryProvider::EnumCategories(
		/* [out] */ __RPC__deref_out_opt IEnumGUID ** penum)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	HRESULT hr=InvokeViaPolicy("EnumCategories", &result);
	if (FAILED(hr)) return hr;
	if (result == Py_None) {
		hr = S_FALSE;
		*penum = NULL;
	} else {
		if (!PyCom_InterfaceFromPyInstanceOrObject(result, IID_IEnumGUID, (void **)penum, FALSE))
			hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("EnumCategories");
	}
	Py_DECREF(result);
	return hr;
}

STDMETHODIMP PyGCategoryProvider::GetCategoryName(
		/* [in] */ __RPC__in const GUID * pguid,
		/* [size_is][string][out] */ __RPC__out_ecount_full_string(cch) LPWSTR pszName,
		/* [in] */ UINT cch)
{
	PY_GATEWAY_METHOD;
	PyObject *obpguid = PyWinObject_FromIID(*pguid);
	if (obpguid==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetCategoryName");
	PyObject *result;
	HRESULT hr=InvokeViaPolicy("GetCategoryName", &result, "Oi", obpguid, cch);
	Py_DECREF(obpguid);
	if (FAILED(hr)) return hr;
	// ack - should be a function to convert directly into a buffer.
	WCHAR *allocd_result;
	if (!PyWinObject_AsWCHAR(result, &allocd_result, FALSE)) {
		hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("GetCategoryName");
	} else {
		wcsncpy(pszName, allocd_result, cch);
		PyWinObject_FreeWCHAR(allocd_result);
	}
	Py_DECREF(result);
	return hr;
}

STDMETHODIMP PyGCategoryProvider::CreateCategory(
		/* [in] */ __RPC__in const GUID * pguid,
		/* [in] */ __RPC__in REFIID riid,
		/* [iid_is][out] */ __RPC__deref_out_opt void ** ppv)
{
	PY_GATEWAY_METHOD;
	PyObject *obpguid = PyWinObject_FromIID(*pguid);
	if (obpguid==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("CreateCategory");
	PyObject *obriid = PyWinObject_FromIID(riid);
	if (obriid==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("CreateCategory");
	PyObject *result;
	HRESULT hr=InvokeViaPolicy("CreateCategory", &result, "OO", obpguid, obriid);
	Py_DECREF(obpguid);
	Py_DECREF(obriid);
	if (FAILED(hr)) return hr;
	if (!PyCom_InterfaceFromPyInstanceOrObject(result, riid, ppv, FALSE/* bNoneOK */))
		hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("CreateCategory");
	Py_DECREF(result);
	return hr;
}