text:
import { DateRangePicker, SingleDatePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';

export { DateRangePicker, SingleDatePicker };

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var test = require('tape');
var _ = require('lodash');
var Store = require('../src/Store');
var Dispatcher = require('flux').Dispatcher;

test('Throws warning errors', function(t) {
	var dispatcher = new Dispatcher();

	t.throws(Store);
	t.throws(Store.bind(null, 'not object', dispatcher));
	t.throws(Store.bind(null, {getInitialState() {}}, null));
	t.throws(Store.bind(null, {}, dispatcher));
	t.end();
});

test('Store has public API', function(t) {
	var dispatcher = new Dispatcher();
	var store = new Store({
		getInitialState: () => {}
	}, dispatcher);

	t.true(_.isString(store.dispatchToken));
	t.true(_.isFunction(store.getState));
	t.true(_.isFunction(store.subscribe));
	t.true(_.isFunction(store.unsubscribe));
	t.true(_.isFunction(store.waitFor));
	t.true(_.isObject(store.listeners));
	t.end();
});

test('Store is passed all option props', function(t) {
	var dispatcher = new Dispatcher();
	var store = new Store({
		getInitialState: function() {
			return {
				firstName: 'ian',
				lastName: 'williams'
			};
		},
		getFullName: function() {
			return `${this.getState().firstName} ${this.getState().lastName}`;
		},
		arbitraryProp: true
	}, dispatcher);

	t.true(store.arbitraryProp);
	t.equals(store.getFullName(), 'ian williams');
	t.end();
});

test('Sets state with getInitialState and getState returns state', function(t) {
	var dispatcher = new Dispatcher();
	var state = {
		bool: true,
		object: {
			a: 'string',
			b: function() {
				return this.a;
			}
		},
		array: [1, 3]
	};
	var store = new Store({
		getInitialState() {
			return state;
		}
	}, dispatcher);

	t.equal(store.getInitialState(), state);
	t.equal(store.getState(), state);
	t.end();
});

test('Resets state and calls reset and change listeners', function(t) {
	var dispatcher = new Dispatcher();
	var initialState = {bool: true};
	var newState = {bool: false};
	var store = new Store({
		getInitialState() {
			return initialState;
		}
	}, dispatcher);

	t.plan(4);

	// should get called once
	store.subscribe('CHANGE', function() {
		t.true(true);
	});
	// should get called once
	store.subscribe('RESET', function() {
		t.true(true);
	});

	t.equal(store.getState(), initialState);

	store.resetState(newState);
	t.equal(store.getState(), newState);
});

test('Store responds to dispatcher', function(t) {
	var dispatcher = new Dispatcher();
	var COUNT_EVENT = 'COUNT_EVENT';
	var store = new Store({
		getInitialState() {
			return {counter: 0};
		},
		[COUNT_EVENT](state, action) {
			return {counter: state.counter + 1};
		}
	}, dispatcher);

	dispatcher.dispatch({type: COUNT_EVENT});
	t.equal(store.getState().counter, 1);
	dispatcher.dispatch({type: COUNT_EVENT});
	t.equal(store.getState().counter, 2);
	t.end();
});

test('Subscribe callbacks run after dispatch', function(t) {
	var EVENT = 'EVENT';
	var dispatcher = new Dispatcher();
	var store = new Store({
		getInitialState:() => {},
		[EVENT](state, action) {
			return state;
		}
	}, dispatcher);

	t.plan(2);
	// should get called once
	store.subscribe(function() {
		t.true(true);
	});
	// should get called once
	store.subscribe(EVENT, function() {
		t.true(true);
	});
	dispatcher.dispatch({type: EVENT});
});

test('Unsubscribe removes events', function(t) {
	var dispatcher = new Dispatcher();
	var CHANGE = 'CHANGE';
	var EVENT = 'EVENT';
	var store = new Store({
		getInitialState:() => {}
	}, dispatcher);
	var callback = () => {};

	store.subscribe(callback);
	t.equal(store.listeners[CHANGE][0], callback);
	store.unsubscribe(callback);
	t.equal(store.listeners[CHANGE].length, 0);
	store.subscribe(EVENT, callback);
	t.equal(store.listeners[EVENT][0], callback);
	store.unsubscribe(EVENT, callback);
	t.equal(store.listeners[EVENT].length, 0);
	t.end();
});

test('Store ignores events that do not match an action reducer', function(t) {
	var EVENT = 'EVENT';
	var NOT_EVENT = 'NOT_EVENT';
	var dispatcher = new Dispatcher();
	var store = new Store({
		getInitialState:() => {},
		[EVENT](state, action) {
			return state;
		}
	}, dispatcher);

	t.plan(1);
	store.subscribe(EVENT, function() {
		t.true(true);
	});
	store.subscribe(NOT_EVENT, function() {
		t.true(true);
	});
	dispatcher.dispatch({type: EVENT});
	dispatcher.dispatch({type: NOT_EVENT});
});


text:
FROM java:openjdk-8

COPY opt /opt
COPY etc /etc

# The service needs 8080 available to world outside this container
EXPOSE 8080

ENTRYPOINT /opt/woin-StarSystemService/bin/run.sh


text:
import { @Route } from '@jymfony/decorators';

/**
 * @memberOf Jymfony.Component.Routing.Fixtures.Annotation
 */
export default class NothingButNameController {
    @Route({ name: "action" })
    action() {
    }
}


text:
Package.describe({
  name: 'jss:sigma',
  version: '1.0.3_1',
  summary: 'Sigma is a library dedicated to graph drawing.',
  git: 'https://github.com/JSSolutions/meteor-sigma',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.2.1');
  api.use('ecmascript');
  api.addFiles([
    // Core:
    'client/sigma.core.js',

    // Utils:
    'client/conrad.js',
    'client/utils/sigma.utils.js',
    'client/utils/sigma.polyfills.js',

    // Main classes:
    'client/sigma.settings.js',
    'client/classes/sigma.classes.dispatcher.js',
    'client/classes/sigma.classes.configurable.js',
    'client/classes/sigma.classes.graph.js',
    'client/classes/sigma.classes.camera.js',
    'client/classes/sigma.classes.quad.js',

    // Captors:
    'client/captors/sigma.captors.mouse.js',
    'client/captors/sigma.captors.touch.js',

    // Renderers:
    'client/renderers/sigma.renderers.canvas.js',
    'client/renderers/sigma.renderers.webgl.js',
    'client/renderers/sigma.renderers.def.js',

    // Sub functions per engine:
    'client/renderers/webgl/sigma.webgl.nodes.def.js',
    'client/renderers/webgl/sigma.webgl.nodes.fast.js',
    'client/renderers/webgl/sigma.webgl.edges.def.js',
    'client/renderers/webgl/sigma.webgl.edges.fast.js',
    'client/renderers/webgl/sigma.webgl.edges.arrow.js',
    'client/renderers/canvas/sigma.canvas.labels.def.js',
    'client/renderers/canvas/sigma.canvas.hovers.def.js',
    'client/renderers/canvas/sigma.canvas.nodes.def.js',
    'client/renderers/canvas/sigma.canvas.edges.def.js',
    'client/renderers/canvas/sigma.canvas.edges.curve.js',
    'client/renderers/canvas/sigma.canvas.edges.arrow.js',
    'client/renderers/canvas/sigma.canvas.edges.curvedArrow.js',

    // Middlewares:
    'client/middlewares/sigma.middlewares.rescale.js',
    'client/middlewares/sigma.middlewares.copy.js',

    // Miscellaneous:
    'client/misc/sigma.misc.animation.js',
    'client/misc/sigma.misc.bindEvents.js',
    'client/misc/sigma.misc.drawHovers.js',

    // Plugins:
    'client/plugins/sigma.layout.forceAtlas2/worker.js',
    'client/plugins/sigma.layout.forceAtlas2/supervisor.js',
    'client/plugins/sigma.plugins.dragNodes/sigma.plugins.dragNodes.js',
    'client/plugins/sigma.parsers.gexf/gexf-parser.js',
    'client/plugins/sigma.parsers.gexf/sigma.parsers.gexf.js',
    'client/plugins/sigma.parsers.json/sigma.parsers.json.js',
    'client/plugins/sigma.plugins.animate/sigma.plugins.animate.js',
    'client/plugins/sigma.plugins.filter/sigma.plugins.filter.js',
    'client/plugins/sigma.plugins.neighborhoods/sigma.plugins.neighborhoods.js',
    'client/plugins/sigma.plugins.relativeSize/sigma.plugins.relativeSize.js',
    'client/plugins/sigma.renderers.customEdgeShapes/shape-library.js',
    'client/plugins/sigma.renderers.customEdgeShapes/sigma.renderers.customEdgeShapes.js',
    'client/plugins/sigma.renderers.customShapes/shape-library.js',
    'client/plugins/sigma.renderers.customShapes/sigma.renderers.customShapes.js',
    'client/plugins/sigma.statistics.HITS/sigma.statistics.HITS.js'
  ], 'client');

  //api.export('sigma', 'client');
});


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb')

describe Jelly::Common do
  attr_reader :fixture
  before do
    @fixture = Class.new do
      include Jelly::Common
    end.new
  end

  describe "#jelly_callback_hash" do
    it "creates a hash with a method and arguments" do
      fixture.jelly_callback_hash("my_method", 1, 2, 3).should == {
        "method" => "my_method",
        "arguments" => [1, 2, 3]
      }
    end
  end

  describe "#jelly_callback_attach_hash" do
    context "when passed attachments" do
      it "creates a hash with the attach param being set to the given attachments" do
        attachments = [
          fixture.jelly_attachment_hash("Foo", 1, 2),
          fixture.jelly_attachment_hash("Bar", 3),
        ]
        fixture.jelly_callback_attach_hash(attachments).should == {
          "attach" => attachments
        }
      end
    end

    context "when not passed attachments" do
      it "creates a hash with the attach param being set to #jelly_attachments" do
        attachments = [
          fixture.jelly_attachment_hash("Foo", 1, 2),
          fixture.jelly_attachment_hash("Bar", 3),
        ]
        stub(fixture).jelly_attachments {attachments}
        fixture.jelly_callback_attach_hash.should == {
          "attach" => attachments
        }
      end
    end
  end
end


text:
package me.coley.jremapper.event;

import java.io.File;
import me.coley.event.Event;

/**
 * Event for loading mappings from a text file.
 *
 * @author Matt
 */
public class LoadMapEvent extends Event {
	private final File destination;

	public LoadMapEvent(File destination) {
		this.destination = destination;
	}

	public File getDestination() {
		return destination;
	}
}


text:
<?php

namespace TimeMachine\ICal\Dumper\Handler;

use TimeMachine\ICal\Model\ObjectInterface;
use TimeMachine\ICal\Dumper\Formatter\FormatterInterface;
use TimeMachine\ICal\Model\Property;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
class PropertyHandler implements HandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function open(ObjectInterface $object, FormatterInterface $formatter)
    {
        return $formatter->property($object->getName(), $object->getValue());
    }

    /**
     * {@inheritdoc}
     */
    public function close(ObjectInterface $object, FormatterInterface $formatter)
    {
        return $formatter->feed();
    }

    /**
     * {@inheritdoc}
     */
    public function supports(ObjectInterface $object)
    {
        return $object instanceof Property;
    }
}


text:
/**
 * config/paths/images.js
 */

var _ = require("lodash");
var commonPaths = require("../../utils/commonPaths");
var env = require("../../utils/environment");

var images = {
  files: "**/*.+(gif|ico|jpg|png)",
  manifest: "images-manifest.json"
};

// Mixin mode-specific options
_.merge(images, env.getConfig(__filename));

// Mixin common paths
_.merge(images, commonPaths(images));

module.exports = images;


text:
package org.jbb.lib.mvc;

import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.jbb.lib.commons.web.HttpServletRequestHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UrlPathHelper;

@Component
@RequiredArgsConstructor
public class PathResolver {

    public static final String API = "/api";
    public static final String API_SLASH = API + "/";
    public static final String API_HEALTH = API_SLASH + "v1/health";
    public static final String API_HEALTH_SLASH = API_HEALTH + "/";

    private final HttpServletRequestHolder httpServletRequestHolder;
    private final UrlPathHelper urlPathHelper;

    public String getRequestPathWithinApplication() {
        HttpServletRequest request = httpServletRequestHolder.getCurrentHttpRequest();
        return urlPathHelper.getPathWithinApplication(request);
    }

    public boolean isRequestToApi() {
        String path = getRequestPathWithinApplication();
        return path.equals(API) || path.equals(API_SLASH) || path.startsWith(API_SLASH);
    }

    public boolean isRequestToHealthCheck() {
        String path = getRequestPathWithinApplication();
        return path.equals(API_HEALTH) || path.equals(API_HEALTH_SLASH);

    }
}


text:
(function() {

    /**
     * Item View
     */
    Backbone.ItemView = Backbone.View.extend({
        tagName: 'tr',
        renderData: null,
        modalView: null,
        messages: {
            removeError: 'Ha sucedido un error al eliminar esta entrada.',
            confirmRemove: 'Seguro que quieres eliminar esta entrada?'
        },

        events: {}, // user defined events
        _events: { // SpecialK default events
            'click .btn-edit': 'editItem',
            'click .btn-remove': 'removeItem'
        },

        constructor: function() {
            var that = this;
            _.forOwn(this._events, function(action, event) {
                that.events[event] = action;
            });

            Backbone.View.apply(this, arguments);
        },

        initialize: function(options) {
            if (!this.model) {
                this.model = new this.Model();
            }

            this.listenTo(this.model, 'remove', this.destroy);
            this.listenTo(this.model, 'change', this.render);

            if (this.init) this.init(options);
        },

        render: function() {

            this.renderData = this.model.toJSON();

            if (this.beforeRender) this.beforeRender();
            this.$el.html(this.template(this.renderData));
            if (this.onRender) this.onRender();

            Backbone.InlineEdit(this);
            Backbone.Bindings(this);

            return this;
        },

        // remove dom item
        destroy: function() {
            var that = this;
            this.$el.hide('fast', function() {
                that.unbind();
                that.remove();
            });
        },

        removeItem: function(e) {
            e = e || {};
            var that = this;

            var remove = function() {
                that.model.destroy({
                    success: function() {
                        that.destroy();
                    },
                    error: function() {
                        SpecialK.alert(that.messages.removeError);
                    }
                });
            };

            if (e.ctrlKey) {
                remove();
            } else {
                SpecialK.confirm(this.messages.confirmRemove, function(sure) {
                    if (sure) remove();
                });
            }
        },

        editItem: function() {
            if (!this.modalView) return;
            var modal = new this.modalView({model: this.model});
            modal.render();
        }
    });

})();


text:
'use strict';

module.exports = {
  ConfigServers: require('./lib/config_servers'),
  Mongos: require('./lib/mongos'),
  ReplSet: require('./lib/replset'),
  Server: require('./lib/server'),
  Sharded: require('./lib/sharded'),
  Logger: require('./lib/logger')
};


text:
package io.luan.jerry.item.repository.impl;

import io.luan.jerry.item.data.ItemDO;
import io.luan.jerry.item.data.ItemMapper;
import io.luan.jerry.item.domain.Item;
import io.luan.jerry.item.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

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

@Repository
public class ItemRepositoryImpl implements ItemRepository {

    private final ItemMapper itemMapper;

    @Autowired
    public ItemRepositoryImpl(ItemMapper itemMapper) {
        this.itemMapper = itemMapper;
    }

    @Override
    public boolean delete(Item item) {
        var itemDO = ItemDO.fromEntity(item);
        if (itemDO.getId() != null) {
            int count = itemMapper.delete(itemDO);
            return count > 0;
        }
        return false;
    }

    @Override
    public List<Item> findAll() {
        List<Item> items = new ArrayList<>();
        for (ItemDO itemDO : itemMapper.findAll()) {
            Item item = itemDO.toEntity();
            items.add(item);
        }
        return items;
    }

    @Override
    public Item findById(Long id) {
        var itemDO = itemMapper.findById(id);
        if (itemDO != null) {
            return itemDO.toEntity();
        }
        return null;
    }

    @Override
    public Item save(Item item) {
        var itemDO = ItemDO.fromEntity(item);
        if (itemDO.getId() == null) {
            itemMapper.insert(itemDO);
            return findById(itemDO.getId());
        } else {
            itemMapper.update(itemDO);
            return item;
        }
    }

}


text:
package org.jasig.portal.concurrency.locking;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Version;

import org.apache.commons.lang.Validate;
import org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.NaturalIdCache;
import org.springframework.util.Assert;

/**
 * Used to coordinate cluster wide locking via the database. Tracks the server that currently owns the lock, when
 * the lock started, last updated and released.
 *
 * @author Eric Dalquist
 * @version $Revision$
 */
@Entity
@Table(name = "UP_MUTEX")
@SequenceGenerator(
        name="UP_MUTEX_GEN",
        sequenceName="UP_MUTEX_SEQ",
        allocationSize=1
    )
@TableGenerator(
        name="UP_MUTEX_GEN",
        pkColumnValue="UP_MUTEX_PROP",
        allocationSize=1
    )
//THIS CLASS CANNOT BE CACHED
@NaturalIdCache
public class ClusterMutex implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "UP_MUTEX_GEN")
    @Column(name="MUTEX_ID")
    private final long id;

    @Version
    @Column(name = "ENTITY_VERSION")
    private final long entityVersion;

    @NaturalId
    @Column(name="MUTEX_NAME", length=200, nullable=false)
    private final String name;

    @Column(name="LOCKED", nullable=false)
    private boolean locked = false;

    @Column(name="SERVER_ID", length=200)
    private String serverId;

    @Column(name="PREV_SERVER_ID", length=200)
    private String previousServerId;

    @Column(name="LOCK_START", nullable=false)
    private Date lockStart = new Date(0);

    @Column(name="LOCK_UPDATE", nullable=false)
    private Date lastUpdate = new Date(0);

    @Column(name="LOCK_END", nullable=false)
    private Date lockEnd = new Date(0);

    @SuppressWarnings("unused")
    private ClusterMutex() {
        this.id = -1;
        this.entityVersion = -1;
        this.name = null;
    }

    ClusterMutex(String name) {
        Validate.notNull(name, "name");

        this.id = -1;
        this.entityVersion = 0;
        this.name = name;
    }

    /**
     * @return the id
     */
    public long getId() {
        return this.id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return this.name;
    }

    /**
     * @return If the lock is currently held
     */
    public boolean isLocked() {
        return this.locked;
    }

    /**
     * @return the serverId that currently owns the lock, null if the mutex is not locked
     */
    public String getServerId() {
        return this.serverId;
    }

    /**
     * @return the serverId of the previous lock owner, null if the mutex has never been locked or is locked for the first time
     */
    public String getPreviousServerId() {
        return this.previousServerId;
    }

    /**
     * @return the lockStart
     */
    public long getLockStart() {
        return this.lockStart.getTime();
    }

    /**
     * @return the lastUpdate
     */
    public long getLastUpdate() {
        return this.lastUpdate.getTime();
    }

    /**
     * @return the lockEnd
     */
    public long getLockEnd() {
        return this.lockEnd.getTime();
    }

    /**
     * Mark the mutex as locked by the specific server
     */
    void lock(String serverId) {
        Assert.notNull(serverId);
        if (this.locked) {
            throw new IllegalStateException("Cannot lock already locked mutex: " + this);
        }
        this.locked = true;
        this.lockStart = new Date();
        this.lastUpdate = this.lockStart;
        this.serverId = serverId;
    }

    void unlock() {
        if (!this.locked) {
            throw new IllegalStateException("Cannot unlock already unlocked mutex: " + this);
        }
        this.locked = false;
        this.lockEnd = new Date();
        this.previousServerId = this.serverId;
        this.serverId = null;
    }

    /**
     * @param lastUpdate the lastUpdate to set
     */
    void updateLock() {
        this.lastUpdate = new Date();
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
        return result;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ClusterMutex other = (ClusterMutex) obj;
        if (this.name == null) {
            if (other.name != null)
                return false;
        }
        else if (!this.name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "ClusterMutex [name=" + name + ", locked=" + locked + ", serverId=" + serverId + ", previousServerId="
                + previousServerId + ", lockStart=" + lockStart + ", lastUpdate=" + lastUpdate + ", lockEnd=" + lockEnd
                + "]";
    }
}


text:
LANG_H2_ACCOUNT_MANAGEMENT=Account Management
LANG_H2_RESELLER_TOOLS=Reseller Tools
LANG_H2_EXTRA_FEATURES=Extra Features
LANG_H2_PLUGINS=Plugins

LANG_ADD_NEW_USER=Add New User
LANG_LIST_USERS=List Users
LANG_MANAGE_TICKETS=Manage Tickets
LANG_ADD_PACKAGE=Add Package
LANG_LIST_PACKAGES=Manage User Packages
LANG_CHANGE_PASSWORDS=Change Passwords
LANG_RESELLER_STATS=Reseller Statistics
LANG_IP_MANAGER=IP Management
LANG_SKIN_MANAGER=Skin Manager
LANG_USER_BACKUPS=Manage User Backups
LANG_SYSTEM_INFO=System Information
LANG_NAMESERVERS=Nameservers
LANG_MESSSAGE_ALL_USERS=Message All Users
LANG_CONTACT_ADMIN=Contact Administrator


text:
from six import PY3, text_type as unicode

import time

from robot.utils import (secs_to_timestr, timestr_to_secs,
                         IRONPYTHON, JYTHON, WINDOWS)
from robot.errors import TimeoutError, DataError, FrameworkError

if JYTHON:
    from .jython import Timeout
elif IRONPYTHON:
    from .ironpython import Timeout
elif WINDOWS:
    from .windows import Timeout
else:
    from .posix import Timeout

class _Timeout(object):

    def __init__(self, timeout=None, message='', variables=None):
        self.string = timeout or ''
        self.message = message
        self.secs = -1
        self.starttime = -1
        self.error = None
        if variables:
            self.replace_variables(variables)

    @property
    def active(self):
        return self.starttime > 0

    def replace_variables(self, variables):
        try:
            self.string = variables.replace_string(self.string)
            if not self:
                return
            self.secs = timestr_to_secs(self.string)
            self.string = secs_to_timestr(self.secs)
            self.message = variables.replace_string(self.message)
        except (DataError, ValueError) as err:
            self.secs = 0.000001 # to make timeout active
            self.error = 'Setting %s timeout failed: %s' \
                    % (self.type.lower(), unicode(err))

    def start(self):
        if self.secs > 0:
            self.starttime = time.time()

    def time_left(self):
        if not self.active:
            return -1
        elapsed = time.time() - self.starttime
        # Timeout granularity is 1ms. Without rounding some timeout tests fail
        # intermittently on Windows, probably due to threading.Event.wait().
        return round(self.secs - elapsed, 3)

    def timed_out(self):
        return self.active and self.time_left() <= 0

    def __str__(self):
        if PY3:
            return self.__unicode__()
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return self.string

    def __cmp__(self, other):
        return cmp(not self.active, not other.active) \
            or cmp(self.time_left(), other.time_left())

    def __lt__(self, other):
        key = (not self.active, self.time_left())
        other_key = (not other.active, other.time_left())
        return key < other_key

    #TODO: Necessary? Are _Timeouts ever compared with other than < ?
    ## def __eq__(self, other):
    ##     ...

    def __bool__(self):
        return bool(self.string and self.string.upper() != 'NONE')

    #PY2
    def __nonzero__(self):
        return self.__bool__()

    def run(self, runnable, args=None, kwargs=None):
        if self.error:
            raise DataError(self.error)
        if not self.active:
            raise FrameworkError('Timeout is not active')
        timeout = self.time_left()
        if timeout <= 0:
            raise TimeoutError(self.get_message())
        executable = lambda: runnable(*(args or ()), **(kwargs or {}))
        return Timeout(timeout, self._timeout_error).execute(executable)

    def get_message(self):
        if not self.active:
            return '%s timeout not active.' % self.type
        if not self.timed_out():
            return '%s timeout %s active. %s seconds left.' \
                % (self.type, self.string, self.time_left())
        return self._timeout_error

    @property
    def _timeout_error(self):
        if self.message:
            return self.message
        return '%s timeout %s exceeded.' % (self.type, self.string)

class TestTimeout(_Timeout):
    type = 'Test'
    _keyword_timeout_occurred = False

    def set_keyword_timeout(self, timeout_occurred):
        if timeout_occurred:
            self._keyword_timeout_occurred = True

    def any_timeout_occurred(self):
        return self.timed_out() or self._keyword_timeout_occurred

class KeywordTimeout(_Timeout):
    type = 'Keyword'


text:
package cmwell.build

import com.github.tkawachi.doctest.DoctestPlugin
import coursier.CoursierPlugin
import net.virtualvoid.sbt.graph.DependencyGraphPlugin
import sbt.Keys._
import sbt._

import scala.concurrent._
import scala.util.{Failure, Success, Try}

object CMWellBuild extends AutoPlugin {

	type PartialFunction2[-T1,-T2,+R] = PartialFunction[Tuple2[T1,T2],R]

	object autoImport {
//		val configSettingsResource = TaskKey[Seq[sbt.File]]("config-settings-resource", "gets the .conf resource")
		val dependenciesManager = settingKey[PartialFunction2[String, String, ModuleID]]("a setting containing versions for dependencies. if we only use it to declare dependencies, we can avoid a lot of version collisions.")
		val iTestsLightMode = settingKey[Boolean]("a flag, which if turns on, does not take cm-well down after integration tests, but rather purge everything in it, so it will be ready for next time. on startup, it checks if there is an instance running, and if so, does not re-install cm-well.")
		val peScript = TaskKey[sbt.File]("pe-script", "returns the script that executes cmwell in PE mode.")
		val uploadInitContent = TaskKey[sbt.File]("upload-init-content", "returns the script that uploads the initial content in to PE Cm-Well.")
		val packageCMWell = TaskKey[Seq[java.io.File]]("package-cmwell", "get components from dependencies and sibling projects.")
		val getLib = TaskKey[java.io.File]("get-lib", "creates a lib directory in cmwell-cons/app/ that has all cm-wll jars and their dependency jars.")
		val getCons = TaskKey[java.io.File]("get-cons", "get cons from cons project.")
		val getWs = TaskKey[java.io.File]("get-ws", "get ws from ws project.")
		val getTlog = TaskKey[java.io.File]("get-tlog", "get tlog tool tlog project.")
		val getBg = TaskKey[java.io.File]("get-bg", "get bg from batch project.")
		val getCtrl = TaskKey[java.io.File]("get-ctrl", "get ctrl from ctrl project.")
		val getDc = TaskKey[java.io.File]("get-dc", "get dc from dc project.")
		val getGremlin = TaskKey[java.io.File]("get-gremlin", "get gremlin plugin into cons.")
		val install = TaskKey[Map[Artifact, File]]("install", "build + test, much like 'mvn install'")
		val dataFolder = TaskKey[File]("data-folder", "returns the directory of static data to be uploaded")
		val printDate = TaskKey[Unit]("print-date", "prints the date")
		val fullTest = TaskKey[Unit]("full-test", "executes all tests in project in parallel (with respect to dependent tests)")
		val getData = TaskKey[Seq[java.io.File]]("get-data", "get data to upload to cm-well")
		val getExternalComponents = TaskKey[Iterable[File]]("get-external-components", "get external dependencies binaries")
	}

	import autoImport._
	import DoctestPlugin.autoImport._
	import CoursierPlugin.autoImport._

  lazy val apacheMirror = {
    val zoneID = java.util.TimeZone
      .getDefault()
      .getID
    if(zoneID.startsWith("America") || zoneID.startsWith("Pacific") || zoneID.startsWith("Etc")) "us"
    else "eu"
  }

	def fetchZookeeperApacheMirror(version: String): Future[File] = {
		val ext = "tar.gz"
		val url = s"http://www-$apacheMirror.apache.org/dist/zookeeper/zookeeper-$version/zookeeper-$version.$ext"
		fetchArtifact(url, ext)
	}

	def fetchZookeeperApacheArchive(version: String): Future[File] = {
		val ext = "tar.gz"
		val url = s"https://archive.apache.org/dist/zookeeper/zookeeper-$version/zookeeper-$version.$ext"
		fetchArtifact(url, ext)
	}

	def fetchZookeeperSourcesFromGithub(version: String, ext: String): Future[File] = {
		require(ext == "zip" || ext == "tar.gz", s"invalid sources extension [$ext]")
		alternateUnvalidatedFetchArtifact(s"https://github.com/apache/zookeeper/archive/release-$version.$ext", ext)
	}

	def fetchZookeeper(version: String, buildFromSources: Option[(String,File => Future[File])] = None) = {
		import scala.concurrent.ExecutionContext.Implicits.global
		import CMWellCommon.combineThrowablesAsCauseAsync

		fetchZookeeperApacheMirror(version).recoverWith {
			case err1: Throwable => fetchZookeeperApacheArchive(version).recoverWith {
				case err2: Throwable => {
					buildFromSources.fold(combineThrowablesAsCauseAsync[File](err1, err2){ cause =>
						new Exception("was unable to fetch zookeeper binaries, and build from sources function isn't supplied", cause)
					}) {
						case (ext, build) => fetchZookeeperSourcesFromGithub(version, ext).flatMap(build)
					}
				}
			}
		}
	}

	def fetchKafkaApacheMirror(scalaVersion: String, version: String): Future[File] = {
		val ext = "tgz"
    val url = s"http://www-$apacheMirror.apache.org/dist/kafka/$version/kafka_$scalaVersion-$version.$ext"
		fetchArtifact(url, ext)
	}

	def fetchKafkaApacheArchive(scalaVersion: String, version: String): Future[File] = {
		val ext = "tgz"
    val url = s"https://archive.apache.org/dist/kafka/$version/kafka_$scalaVersion-$version.$ext"
		fetchArtifact(url, ext)
	}

	def fetchKafkaSourcesFromGithub(version: String, ext: String): Future[File] = {
		require(ext == "zip" || ext == "tar.gz", s"invalid sources extension [$ext]")
		alternateUnvalidatedFetchArtifact(s"https://github.com/apache/kafka/archive/$version.$ext", ext)
	}

  def fetchKafka(scalaVersion: String, version: String, buildFromSources: Option[(String,File => Future[File])] = None) = {
		import scala.concurrent.ExecutionContext.Implicits.global
		import CMWellCommon.combineThrowablesAsCauseAsync

		fetchKafkaApacheMirror(scalaVersion, version).recoverWith {
			case err1: Throwable => fetchKafkaApacheArchive(scalaVersion, version).recoverWith {
				case err2: Throwable => {
					buildFromSources.fold(combineThrowablesAsCauseAsync[File](err1, err2) { cause =>
						new Exception("was unable to fetch kafka binaries, and build from sources function isn't supplied", cause)
					}) {
						case (ext, build) => fetchKafkaSourcesFromGithub(version, ext).flatMap(build)
					}
				}
			}
		}
	}

	def fetchMvnArtifact(moduleID: ModuleID, scalaVersion: String, scalaBinaryVersion: String, logger: Logger): Future[Seq[java.io.File]] = {
		import coursier._
		import java.io.File
		import scala.concurrent.Future
		import scala.concurrent.ExecutionContext.Implicits.global
		import scalaz.EitherT
		import scalaz.concurrent.Task

		val (module, version) = FromSbt.moduleVersion(moduleID, scalaVersion, scalaBinaryVersion)
		val repositories: Seq[coursier.Repository] = Seq(MavenRepository("https://repo1.maven.org/maven2"))
		val fetch = Cache.fetch()

		val tasks = FromSbt.dependencies(moduleID, scalaVersion, scalaBinaryVersion).map {
			case (_, dep) =>
				coursier.Fetch.find(repositories, module, version, fetch)
					.fold[Seq[Artifact]](
					{ errorString =>
						logger.error(s"coursier fetch mvn artifact delegation encountered an error (skipping task): $errorString")
						Seq.empty[Artifact]
					}, { case (src, p) => src.artifacts(dep, p, None) })
		}

		val farts: Future[Seq[List[File]]] = Future.traverse(tasks) { task =>
			CMWellCommon.scalazTaskAsScalaFuture(task.flatMap { arts =>
				val x = arts.map { art =>
					Cache.file(art).bimap(e => List(e), f => List(f))
				}
				if(x.isEmpty) Task[Try[List[File]]](Failure(new IllegalStateException("empty sequence")))
				else {
					val y = x.reduce[EitherT[Task, List[FileError], List[File]]] {
						case (a, b) =>
							a.flatMap(files => b.map(_ ::: files).orElse(a)).orElse(b)
					}

					y.fold({ errs =>
						Failure[List[File]](new Exception(errs.map(err => err.message + ": " + err.describe).mkString("[\n\t", ",\n\t", "\n]")))
					}, Success.apply)
				}
			})
		}

		farts.map(_.flatten)
	}

	def fetchArtifact(url: String, ext: String) = {
		import coursier.core.{Artifact, Attributes}
		val sig = Artifact(

			url + ".asc",
			Map.empty,
			Map.empty,
			Attributes("asc", ""),
			changing = false,
			authentication = None
		)

		val art = Artifact(
			url,
			Map(
				"MD5" -> (url + ".md5"),
				"SHA-1" -> (url + ".sha1")),
			Map("sig" -> sig),
			Attributes(ext, ""),
			changing = false,
			None)

		val task = coursier.Cache.file(art).fold({ err =>
			Failure[java.io.File](new Exception(err.message + ": " + err.describe))
		},Success.apply)

		CMWellCommon.scalazTaskAsScalaFuture(task)
	}

	def alternateUnvalidatedFetchArtifact(url: String, ext: String) = {
		import coursier.core.{Artifact, Attributes}

		val art = Artifact(
			url,
			Map.empty,
			Map.empty,
			Attributes(ext, ""),
			changing = false,
			None)

		val task = coursier.Cache.file(art).fold({ err =>
			Failure[java.io.File](new Exception(err.message + ": " + err.describe))
		},Success.apply)

		CMWellCommon.scalazTaskAsScalaFuture(task)
	}

	override def requires = CoursierPlugin && DoctestPlugin && DependencyGraphPlugin

	override def projectSettings = Seq(
		coursierMaxIterations := 200,
		Keys.fork in Test := true,
//		doctestWithDependencies := false,
		libraryDependencies ++= {
			val dm = dependenciesManager.value
			Seq(
				dm("org.scalatest","scalatest") % "test",
				dm("org.scalacheck","scalacheck") % "test")
		},
		testListeners := Seq(new sbt.JUnitXmlTestsListener(target.value.getAbsolutePath)),
		doctestTestFramework := DoctestTestFramework.ScalaTest,
		exportJars := true,
		shellPrompt := { s => Project.extract(s).currentProject.id + " > " },
		fullTest := {},
		install in Compile := {
			fullTest.value
			packagedArtifacts.value
		},
		concurrentRestrictions in ThisBuild ++= Seq(
			Tags.limit(CMWellCommon.Tags.ES, 1),
			Tags.limit(CMWellCommon.Tags.Cassandra, 1),
			Tags.limit(CMWellCommon.Tags.Kafka, 1),
			Tags.limit(CMWellCommon.Tags.Grid, 1),
			Tags.exclusive(CMWellCommon.Tags.IntegrationTests)
		)
	)
}


text:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    url(r'^$', 'privatebeta.views.invite', name='privatebeta_invite'),
    url(r'^sent/$', 'privatebeta.views.sent', name='privatebeta_sent'),
)


text: based on [reduceless](https://github.com/nosovsh/reduceless)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="vertical">

	<android.support.v4.view.ViewPager
		android:id="@+id/viewpager"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="center">

		<RelativeLayout
			android:layout_height="wrap_content"
			android:layout_width="wrap_content">

		</RelativeLayout>

	</android.support.v4.view.ViewPager>

</LinearLayout>

<!-- From: file:/C:/Users/qweas/Desktop/ZprogrammerTool/app/src/main/res/layout/views.xml -->


text:
using System;
using System.Windows.Forms;
using HasEvent;
using Office = Microsoft.Office.Core;

namespace ConsumeEvent {
	public partial class ThisAddIn : IObserver {

		private Office.COMAddIn hasEvent;

		public void AfterSave() {
			MessageBox.Show("Before save event fired");
		}

		private void ThisAddIn_Startup(object sender, EventArgs e) {
			Office.COMAddIn comAddin = FindComAddinByName("HasEvent");
			ISubject hd = ObtainSubject(comAddin);
			hd.Listen(this);
		}

		private Office.COMAddIn FindComAddinByName(string name) {
			foreach (Office.COMAddIn comAddIn in Application.COMAddIns) {
				if (comAddIn.Description == name) {
					return comAddIn;
				}
			}
			return null;
		}

		/// <summary>
		/// Obtains a reference to a typed ComAddin project.
		/// The type is determined in the other ComAddin project.
		/// </summary>
		/// <seealso cref="http://blogs.msdn.com/b/andreww/archive/2008/08/13/comaddins-race-condition.aspx"/>
		/// <param name="comAddin"></param>
		/// <returns></returns>
		private ISubject ObtainSubject(Office.COMAddIn comAddin) {
			object obj = null;
			int tries = 0;
			// 50 * 100 miliseconds = 5000 milliseconds == 5 seconds
			while (obj == null && tries < 50) {
				obj = comAddin.Object;
				System.Threading.Thread.Sleep(100);
				tries++;
			}
			ISubject subject = obj as ISubject;
			return subject;
		}

		private void ThisAddIn_Shutdown(object sender, EventArgs e) {
			/* nothing */
		}

		private void InternalStartup() {
			Startup += ThisAddIn_Startup;
			Shutdown += ThisAddIn_Shutdown;
		}

	}
}


text:
package ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration;

import io.dropwizard.cli.Command;
import ru.vyarus.dropwizard.guice.module.lifecycle.GuiceyLifecycle;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.ConfigurationPhaseEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.internal.EventsContext;

import java.util.List;

/**
 * Called if commands search is enabled ({@link ru.vyarus.dropwizard.guice.GuiceBundle.Builder#searchCommands()})
 * and at least one command found. Not called otherwise.
 *
 * @author Vyacheslav Rusakov
 * @since 15.06.2019
 */
public class CommandsResolvedEvent extends ConfigurationPhaseEvent {

    private final List<Command> commands;

    public CommandsResolvedEvent(final EventsContext context, final List<Command> installed) {
        super(GuiceyLifecycle.CommandsResolved, context);
        commands = installed;
    }

    /**
     * @return list of registered commands
     */
    public List<Command> getCommands() {
        return commands;
    }
}


text:
/* Stolen from https://github.com/yeldarby/offline-firebase/
   @commit c82bf075bd
*/
/*
	Extend the Firebase class.
*/
console.log("loading OFB");
function OfflineFirebase(url) {
	goog.base(this, url);
}
goog.inherits(OfflineFirebase, Firebase);

/*
	Prefix for OfflineFirebase associated localStorage.

	This is used when storing to, retrieving from, and clearing the cache.
*/
OfflineFirebase.namespace = 'ofb_';

/*
	Override the Firebase .on(...) method to allow us to hijack and cache
	data as it comes in.

	Note the cacheOffline flag that has been added to this method. In order
	to enable the offline caching, set this to true.
*/
OfflineFirebase.prototype.on = function(eventType, callback, cancelCallback, context, cacheOffline) {
	var metaCallback = callback;

	if(cacheOffline) {
		metaCallback = function(snapshot) {
			// Store value locally so we can restore it later.
			OfflineFirebase.store(snapshot);

			callback(snapshot);
		};
	}

	// Register the callback with the superclass.
	OfflineFirebase.superClass_.on.call(this, eventType, metaCallback, cancelCallback, context);
};

/*
	Also override the .once(...) method in a similar manner
*/
OfflineFirebase.prototype.once = function(eventType, callback, cancelCallback, context, cacheOffline) {
	var metaCallback = callback;

	if(cacheOffline) {
		metaCallback = function(snapshot) {
			// Store value locally so we can restore it later.
			OfflineFirebase.store(snapshot);

			callback(snapshot);
		};
	}

	// Register the callback with the superclass.
	OfflineFirebase.superClass_.once.call(this, eventType, metaCallback, cancelCallback, context);
};

/*
	Override the child method to return a subclassed OfflineFirebase instead of an instance of
	the superclass.
*/
OfflineFirebase.prototype.child = function(pathString) {
	return new OfflineFirebase(this.toString() + '/' + pathString);
};

/*
	Stores the data from a snapshot in localStorage so we can restore it
	later.

	This works by retrieving the .exportVal() from the snapshot, iterating
	over the object tree, and storing each leaf (a leaf is defined as a node
	named ".value" or ".priority") into a localStorage item.
*/
OfflineFirebase.store = function(snapshot) {
	var initialPath = snapshot.ref().toString();
	var exportVal = snapshot.exportVal();

	// We need to clear already cached data in case data has been removed.
	OfflineFirebase._clearPath(initialPath);

	OfflineFirebase._walk(initialPath, exportVal, function(path, data) {
		localStorage.setItem(OfflineFirebase.namespace + 'partial_' + path, JSON.stringify(data));	// Update individual paths
	});

	// Log this global path as saved since we need to set it at its topmost node so it can be retrieved.
	// We will recompose it from its parts when saving so that we're sure we have the freshest data.
	// Also note, that if we have already stored one of its parents, we need not set this but we do anyway.
	/*
		Note: if you set /a/b and /a/c, retrieving /a will not be cached since Firebase doesn't know that
		/a/b and /a/c make up the complete contents of /a.
	*/
	localStorage.setItem(OfflineFirebase.namespace + 'full_' + initialPath, 1);
};

/*
	Clears data for this path and all children under it from localStorage.
*/
OfflineFirebase._clearPath = function(path) {
	for(var key in localStorage) {
		var indexOfPath = key.indexOf(OfflineFirebase.namespace + 'partial_' + path);
		if(indexOfPath === 0) {
			// This is a component of the path so we need to clear it.
			localStorage.removeItem(key);
		}
	}
}

/*
	Recursively traverses a primitive JavaScript object that represents the
	exportVal() of a Firebase DataSnapshot and runs callback for each leaf node.
*/
OfflineFirebase._walk = function(path, exportVal, callback) {
	if(!exportVal) return;

	if(typeof exportVal == 'number' || typeof exportVal == 'string') {
		// Leaf node: simple type with null priority
		callback(path, exportVal);
	} else if(exportVal['.value'] && exportVal['.priority']) {
		// Leaf node: simple type with defined priority
		callback(path, {
			'.priority': exportVal['.priority'],
			'.value': exportVal['.value']
		});
	} else {
		if(exportVal['.priority']) {
			// "Leaf" node: complex type with defined priority
			/*
				Note: this is a "leaf" because it needs a node in localStorage
				to store its priority but it also has children that we need
				to iterate over. This is probably an abuse of the "leaf"
				nomenclature.
			*/
			callback(path, {
				'.priority': exportVal['.priority']
			});
		}

		// Recurse over children of this node
		for(var child in exportVal) {
			if(child == '.priority' || child == '.value') continue; // We have already accounted for this pseudo-child earlier

			var childPath = path + '/' + child;
			OfflineFirebase._walk(childPath, exportVal[child], callback);
		}
	}
};

/*
	Takes all objects stored locally and performs a Firebase set operation
	to initialize the Firebase cache on a cold bootup.

	Note: this will overwrite the server value so you should use .validate
	rules to ensure that the proper data is used in the event of a merge
	conflict.

	Eg, in the case of high-scores, your .validate should enforce that the
	new value is higher than the old value. Or store a timestamp that takes
	the newest value of the 2.

	Currently O(n^2) on number of items in localStorage but I suspect we can
	do better... hasn't become a bottleneck for me yet, though.
*/
OfflineFirebase.restore = function() {
	for(var key in localStorage) {
		if(key && key.indexOf(OfflineFirebase.namespace + 'full_') === 0) {
			// This is one of our cached values

			var url = key.substring( (OfflineFirebase.namespace + 'full_' ).length );	// Remove the namespace to retrieve the URL
			var val = OfflineFirebase._reconstitute(url);
			var ref = new OfflineFirebase(url);
			ref.on('value', function() {}); // Register a callback so Firebase will cache this location
			ref.set(val); // Populate it with a value
		}
	}
}

/*
	Reconstitute a value from the sum of its parts (which are residing in localStorage).
*/
OfflineFirebase._reconstitute = function(path) {
	var ret = {};

	for(var key in localStorage) {
		var indexOfPath = key.indexOf(OfflineFirebase.namespace + 'partial_' + path);
		if(indexOfPath === 0) {
			// This is a component of the path so we need to add it to ret.

			var val = JSON.parse(localStorage[key]);
			var subKey = key.substring( (OfflineFirebase.namespace + 'partial_' + path).length ); // The path to this node relative to our root.

			// Create the nested object for this fragment if it doesn't already exist
			var currentTarget = ret;
			if(subKey) {
				var parts = subKey.split('/');

				for(var i=0; i<parts.length; i++) {
					if(!parts[i]) continue;
					if(typeof currentTarget[parts[i]] == 'undefined') currentTarget[parts[i]] = {};
					currentTarget = currentTarget[parts[i]];
				}
			}

			// Set the priority and value for our nested object
			if(typeof val == 'object') {
				if(val['.priority']) {
					currentTarget['.priority'] = val['.priority'];
				} else {
					currentTarget['.priority'] = null;
				}

				if(val['.value']) {
					// If this also contains a value primitive, escalate that.
					val = val['.value'];
				} else {
					// Otherwise we don't need to set any data for this node, just its priority.
					continue;
				}
			}

			currentTarget['.value'] = val;
		}
	}

	return ret;
};

/*
	Clear the localStorage of all OfflineFirebase related items.

	Note: these items will still be stored by Firebase's internal cache if
	they have been requested (or stored) already on this page-load.
*/
OfflineFirebase.clear = function() {
	for(var key in localStorage) {
		if(key && key.indexOf(OfflineFirebase.namespace) === 0) {
			// This is one of our cached values so remove it.
			localStorage.removeItem(key);
		}
	}
};


text:
package net.runelite.deob.updater;

import net.runelite.asm.ClassFile;
import net.runelite.asm.ClassGroup;
import net.runelite.asm.Field;
import net.runelite.asm.Method;
import net.runelite.asm.attributes.Annotations;
import net.runelite.asm.attributes.annotation.Annotation;
import net.runelite.deob.DeobAnnotations;
import net.runelite.deob.deobfuscators.Renamer;
import net.runelite.deob.util.NameMappings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AnnotationRenamer
{
	private static final Logger logger = LoggerFactory.getLogger(AnnotationRenamer.class);

	private ClassGroup group;

	public AnnotationRenamer(ClassGroup group)
	{
		this.group = group;
	}

	public void run()
	{
		NameMappings mappings = buildMappings();

		Renamer renamer = new Renamer(mappings);
		renamer.run(group);
	}

	private NameMappings buildMappings()
	{
		NameMappings mappings = new NameMappings();

		for (ClassFile cf : group.getClasses())
		{
			String name = getImplements(cf.getAnnotations());
			if (name != null)
				mappings.map(cf.getPoolClass(), name);

			for (Field f : cf.getFields())
			{
				name = DeobAnnotations.getExportedName(f.getAnnotations());
				if (name != null)
					mappings.map(f.getPoolField(), name);
			}

			for (Method m : cf.getMethods())
			{
				name = DeobAnnotations.getExportedName(m.getAnnotations());
				if (name != null)
					mappings.map(m.getPoolMethod(), name);
			}
		}

		return mappings;
	}

	private String getImplements(Annotations annotations)
	{
		Annotation an = annotations.find(DeobAnnotations.IMPLEMENTS);
		return an != null ? an.getElement().getString() : null;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 25(5/6): 455 (1927)

#### Original name
Irenina hyptidicola var. hyptidicola (F. Stevens) F. Stevens

### Remarks
null


text:
/**
 * Finds quadratic equation roots. Possible roots are 0, 1 or 2.
 * @param a {number}
 * @param b {number}
 * @param c {number}
 * @returns {string}
 */
const quadraticEquation = (a, b, c) => {
  const discriminant = (b * b) - (4 * a * c);
  const x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
  const x2 = (-b - Math.sqrt(discriminant)) / (2 * a);

  if (typeof a !== 'number' || typeof b !== 'number' || typeof c !== 'number') {
    throw new Error('All arguments must be of type number');
  }

  if (discriminant < 0) return 'no real roots';

  return x1 === x2 ? `x1=x2=${x1}` : `x1=${x1} x2=${x2}`;
};

export default quadraticEquation;


text:
require 'camping'

Camping.goes :Watch

module Watch::Models

end

module Watch::Controllers
  class Index
    def get
      render :index
    end
  end
end

module Watch::Views
  def index
    Time.now.to_s
  end
end


text:
package org.wso2.security.tools.automation.manager.handler;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Handler for HTTP requests
 *
HTTP requests are sent to the micro service APIs in containers

 */
@SuppressWarnings("unused")
public class HttpRequestHandler {

    /**
     * Sends a HTTP GET request
     *
     * @param request Requested URI
     * @return HTTP response after executing the GET command
     * @throws IOException in case of a problem or the connection was aborted
     */
    public static HttpResponse sendGetRequest(URI request) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGetRequest = new HttpGet(request);
        return httpClient.execute(httpGetRequest);
    }

    /**
     * Sends a HTTP POST request
     *
     * @param request    Requested URI
     * @param parameters URL parameters
     * @return HTTP response after executing POST command
     * @throws IOException in case of a problem or the connection was aborted
     */
    public static HttpResponse sendPostRequest(URI request, ArrayList<NameValuePair> parameters) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> urlParameters = new ArrayList<>();
        HttpPost httpPostRequest = new HttpPost(request);
        if (parameters != null) {
            for (NameValuePair parameter : parameters) {
                urlParameters.add(new BasicNameValuePair(parameter.getName(), parameter.getValue()));
            }
            httpPostRequest.setEntity(new UrlEncodedFormEntity(urlParameters));
        }
        return httpClient.execute(httpPostRequest);
    }

    /**
     * Sends a multipart POST request.
     * This method is to send files in POST request
     *
     * @param request  Requested URI
     * @param files    List of files to be sent over HTTP
     * @param textBody List of text parameters to be sent in body
     * @return HTTP response after  executing the request
     * @throws IOException in case of a problem or the connection was aborted
     */
    public static HttpResponse sendMultipartRequest(URI request, Map<String, File> files, Map<String, String>
            textBody) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();

        HttpPost uploadFile = new HttpPost(request);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (textBody != null) {
            for (Map.Entry<String, String> entry : textBody.entrySet()) {
                builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.TEXT_PLAIN);
            }
        }
        // This attaches the file to the POST:
        if (files != null) {
            for (Map.Entry<String, File> entry : files.entrySet()) {
                InputStream inputStream = new FileInputStream(entry.getValue());
                builder.addBinaryBody(
                        entry.getKey(),
                        inputStream,
                        ContentType.APPLICATION_OCTET_STREAM,
                        entry.getValue().getName()
                );

            }
        }
        HttpEntity multipart = builder.build();
        uploadFile.setEntity(multipart);
        return httpClient.execute(uploadFile);
    }

    /**
     * Reads the HTTP response and return a {@code String}
     *
     * @param response HTTP response to be read
     * @return a string of HTTP response
     * @throws IOException in case of a problem or the connection was aborted
     */
    public static String printResponse(HttpResponse response) throws IOException {
        try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        }
    }

    /**
     * Get the entity of a HTTP response and saved to a file.
     *
     * @param response        HTTP response
     * @param destinationFile Destination file path
     * @throws IOException in case of a problem or the connection was aborted
     */
    public static void saveResponseToFile(HttpResponse response, File destinationFile) throws IOException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try (InputStream inputStream = entity.getContent();
                 FileOutputStream output = new FileOutputStream(destinationFile)) {
                int l;
                byte[] tmp = new byte[2048];
                while ((l = inputStream.read(tmp)) != -1) {
                    output.write(tmp, 0, l);
                }
            }
        }
    }
}


text:
namespace lean {

struct empty {};

inline bool operator == (const empty&, const empty&) { return true; }
inline bool operator != (const empty&, const empty&) { return false; }

}

#endif


text:
import sys
from optparse import OptionParser
import pkg_resources

from . import SmtpHealthCheck

def main():
    version = pkg_resources.require('smtp-health-check')[0].version
    description = """\
Connects to a remote SMTP server, verifying that it responds with a banner code
that indicates a healthy system (e.g. 220). Each step of the connection may be
timed. The output of this health check shows the results of the check, and the
length of time taken by each piece of the operation.
"""
    op = OptionParser(usage='%prog [options] <host>', version=version,
                      description=description)
    op.add_option('-p', '--port',
                  type='int', metavar='NUM', default=25,
                  help='The port to connect to, default %default.')
    op.add_option('-s', '--ssl',
                  action='store_true', default=False,
                  help='Initiate an SSL handshake before getting the banner.')
    op.add_option('-d', '--dns-timeout',
                  type='int', metavar='SEC', default=10,
                  help='The DNS lookup failure timeout, default %default.')
    op.add_option('-c', '--connect-timeout',
                  type='int', metavar='SEC', default=10,
                  help='The connection failure timeout, default %default.')
    op.add_option('-e', '--ssl-timeout',
                  type='int', metavar='SEC', default=10,
                  help='The SSL handshake failure timeout, default %default.')
    op.add_option('-b', '--banner-timeout',
                  type='int', metavar='SEC', default=10,
                  help='The banner failure timeout, default %default.')
    options, extra = op.parse_args()

    if len(extra) < 1:
        op.error('At least one host must be provided.')

    check = SmtpHealthCheck(dns_timeout=options.dns_timeout,
                            connect_timeout=options.connect_timeout,
                            ssl_timeout=options.ssl_timeout,
                            banner_timeout=options.banner_timeout)
    for host in extra:
        check.run(host, options.port, options.ssl)
        return check.output(sys.stdout)

# vim:et:sts=4:sw=4:ts=4


text:
__all__ = ['hist','stats']

import hist
import test


text:
.. image:: https://github.com/ellmetha/django-machina/raw/master/docs/_images/banner.png
    :target: https://django-machina.readthedocs.org/

.. image:: https://readthedocs.org/projects/django-machina/badge/?version=stable
    :target: https://django-machina.readthedocs.org/en/stable/
    :alt: Documentation Status

.. image:: https://img.shields.io/pypi/l/django-machina.svg
    :target: https://pypi.python.org/pypi/django-machina/
    :alt: License

.. image:: https://img.shields.io/pypi/pyversions/django-machina.svg
    :target: https://pypi.python.org/pypi/django-machina

.. image:: https://img.shields.io/pypi/v/django-machina.svg
    :target: https://pypi.python.org/pypi/django-machina/
    :alt: Latest Version

.. image:: https://img.shields.io/travis/ellmetha/django-machina.svg
    :target: https://travis-ci.org/ellmetha/django-machina
    :alt: Build status

.. image:: https://img.shields.io/codecov/c/github/ellmetha/django-machina.svg
    :target: https://codecov.io/github/ellmetha/django-machina
    :alt: Codecov status

.. image:: https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg
   :target: https://saythanks.io/to/ellmetha

|

Django-machina is a forum framework for Django providing a way to build community-driven websites.
It offers a full-featured yet very extensible forum solution:

* Topic and post editing
* Forums tree management
* Per-forum permissions
* Anonymous posting
* Polls and attachments
* Moderation and pre-moderation
* Forum conversations search
* ...

.. image:: https://raw.githubusercontent.com/ellmetha/django-machina/master/docs/_images/machina_forum_header.png
    :target: https://django-machina.readthedocs.org/

|

Django-machina was built with integration in mind: the application is designed to be used inside
existing Django applications. It is not a standalone forum solution.

Django-machina was built with customization and extensibility in mind: each single functionality
of the application can be customized or overriden to accommodate with your needs. In fact,
django-machina uses the same techniques as those introduced by the famous django-oscar_ e-commerce
framework to allow powerfull customizations.

.. _django-oscar: https://github.com/django-oscar/django-oscar

.. contents:: Table of Contents
    :local:

Documentation
=============

Online browsable documentation is available at https://django-machina.readthedocs.org.

Head over to the documentation for all the details on how to set up your forum and how to customize
it to suit your needs.

Requirements
============

Python 2.7+ or 3.4+, Django 1.11+. Please refer to the requirements_ section of the documentation for
a full list of dependencies.

.. _requirements: https://django-machina.readthedocs.org/en/latest/getting_started.html#requirements

Demo site
=========

A demo sites can be tested at https://vanilla.machina-forum.io. It contains a standard installation
of django-machina without any customizations.

Authors
=======

Morgan Aubert (`@ellmetha <https://github.com/ellmetha>`_) and contributors_. See ``AUTHORS`` for
more details.

.. _contributors: https://github.com/ellmetha/django-machina/contributors

License
=======

BSD. See ``LICENSE`` for more details.


text:
This cookbook includes core components to be used as a foundation for other cookbooks.
The following recipes apply:

- `core::default` - includes helper modules.

It is inspired by [opscode-cookbooks/apt](https://github.com/opscode-cookbooks/apt) cookbook
by

Joshua Timberman (<joshua at opscode.com>)
Matt Ray (<matt at opscode.com>)
Seth Chisamore (<schisamo at opscode.com>)

## Requirements

This cookbook applies to the following platforms:
- `CrunchBang 11+`
- `Linux Mint 13+`
- `Ubuntu 14.04+`

#### cookbooks
- `apt`

## Attributes

#### core::default

    Key
    Type
    Description
    Default

    <tt>[:box]</tt>
    Hash
    profile data of the target node
    <tt>{}</tt>

    <tt>[:apt][:sources_path]</tt>
    String
    path to additional package repositories
    <tt>/etc/apt/sources.list.d</tt>

    <tt>[:chef_report][:recipient]</tt>
    String
    email address where chef-run reports will be send
    <tt>chefbox.coderebels@gmail.com</tt>

## Definitions

### Installing applications

`install_app` provides an easy way to manage the installation of an application,
ensuring the correct addition of external sources when nedeed.

#### Examples

    # install gimp application
    graphics = data_bag_item('apps', 'graphics')

    install_app "gimp" do
      profile graphics['profiles']['gimp']
    end

### Uninstalling applications

`uninstall_app` provides an easy way to uninstall an application,
purging all unnecessary packages.

#### Examples

    # uninstall gimp application
    graphics = data_bag_item('apps', 'graphics')

    uninstall_app "gimp" do
      profile graphics['profiles']['gimp']
    end

`uninstall_apps` provides an easy way to uninstall a set of applications,
purging all unnecessary packages.

#### Examples

    # uninstall graphics applications
    graphics = data_bag_item('apps', 'graphics')

    apps = graphics['apps']
    selected = node[:box][:apps][:graphics]
    unselected = apps - selected

    uninstall_apps "graphics" do
      apps unselected
      profiles graphics['profiles']
    end

### Autostart of applications

`autostart_app` provides an easy way to tell an application to autostart at login time.

#### Examples

    # autostart caffeine indicator
    indicators = data_bag_item('apps', 'indicators')

    autostart_app "screensaver" do
      profile indicators['profiles']['screensaver']
    end

### Creation of directories

`directory_tree` provides an easy way to create directories in a path recursively, applying same owner, group and mode.

#### Examples

    # dotfiles folder creation
    directory_tree "#{ENV['HOME']}/admin/dotfiles" do
      exclude ENV['HOME']
      owner username
      group groupname
      mode 00755
    end

### Delivery of support material

`support` delivers support material about specified subject.

#### Examples

    # delivery of support material about firewall
    support "firewall" do
      section "security"
    end

### Custom launcher creation

`launcher` provides a custom launcher for specified app.

#### Examples

    # custom launcher for backup-mgr script from template
    launcher "backup-mgr" do
      template "/jobs/backup/backup-mgr.desktop.erb"
      variables(
        :backup_script => backup_script
      )
    end

    # custom launcher for backup-mgr script from file
    launcher "backup-mgr" do
      file "/jobs/backup/backup-mgr.desktop"
    end

### Custom uninstaller creation

`uninstaller` provides a custom uninstaller script for specified app.

#### Examples

    # custom uninstaller for QCAD app
    uninstaller "qcad" do
      template "/qcad/uninstall_qcad-es.sh.erb"
      variables(
        :app     => "qcad",
        :website => qcad_website
      )
    end

## Resources/Providers

### Managing repositories

This LWRP provides an easy way to manage additional PPA repositories.
Adding a new repository will notify running the `execute[synchronize_package_index]`
resource immediately.

#### Actions

- :add:    creates a repository file and builds the repository listing
- :remove: removes the repository file

#### Attribute Parameters

- repo_name:    the name of the new source file
- uri:          the ppa uri to add
- distribution: this is usually your release's codename
- cache_build:  triggers package index synchronization (defaults true)
- clean_saved:  triggers sources backup removal (defaults true)

#### Examples

    # add the nitrux-umd repo
    core_ppa "kokoto-java-omgubuntu-stuff" do
      uri "ppa:kokoto-java/omgubuntu-stuff"
      distribution "precise"
    end

## Libraries

### module Coderebels::Chefbox::App

Provides app related functions.

#### Functions

- `app_available`     - checks if an app is available to be installed on the target os and release.
- `app_package_name`  - retrieves the package name of an app from its profile.
- `app_source`        - retrieves the source data of an app from its profile.
- `App.default`       - checks if an app is installed out-of-the-box on the target os and release.

### module Coderebels::Chefbox::Box

Provides box related functions.

#### Functions

- `memory`            - retrieves the total amount of memory of the box.
- `device`            - retrieves the vendor:device string of the device of the specified category.
- `vendor`            - retrieves the vendor of the device of the specified category.
- `platform`          - retrieves the os of the box.
- `platform_version`  - retrieves the os version.
- `platform_codename` - retrieves the code name of the currently installed distribution.
- `platform_arch`     - retrieves the processor type (i686 / x86_64).
- `platform_desktop`  - retrieves the default platform desktop.
- `virtual_box?`      - checks if target box is virtual.

### module Coderebels::Chefbox::Digest

Provides digest related functions.

#### Functions

- `sha256sum` - prints SHA256 checksum of a given file.
- `md5sum`    - prints MD5 checksum of a given file.
- `shadow`    - shadows plain text passwords.

### module Coderebels::Chefbox::Shell

Provides shell related functions.

#### Functions

- `rep` - evaluates shell commands.

## Contact

By Email:   carles.ml.dev at gmail dot com
On Twitter: [@zuzudev](https://twitter.com/zuzudev)
On Google+: [Carles Muiños](https://plus.google.com/109480759201585988691)

## License

Copyright (c) 2013,2014 Carles Muiños

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p2pchat.model.server;

import org.junit.*;
import static org.junit.Assert.*;
import p2pchat.connection.server.IConnectionManagerServer;
import p2pchat.connection.server.TransmissionRequest;
import p2pchat.mock.ConnectionManagerServerMock;
import p2pchat.mock.LoginControllerMock;
import p2pchat.mock.OnlineUserManagerServerMock;
import p2pchat.mock.RegistrationControllerMock;
import p2pchat.model.*;

/**
 *
 * @author USER
 */
public class ServerRequestHandlerTest {

    ConnectionManagerServerMock connectionManagerServer;
    RegistrationControllerMock registrationController;
    LoginControllerMock loginController;
    OnlineUserManagerServerMock onlineUserManagerServer;
    ServerRequestHandler instance;

    public ServerRequestHandlerTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
        connectionManagerServer = new ConnectionManagerServerMock();
        registrationController = new RegistrationControllerMock();
        loginController = new LoginControllerMock();
        onlineUserManagerServer = new OnlineUserManagerServerMock();
        instance = new ServerRequestHandler(connectionManagerServer, registrationController, loginController,
                onlineUserManagerServer);
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Add friend
     * request.
     */
    @Test
    public void testHandleDataAddFriendRequestMessage() {
        System.out.println("Handle Data AddFriendRequestMessage");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser1 = new User("alice", "localhost", "2010");
        onlineUserManagerServer.findOnlineUserUsername1 = "alice";
        onlineUserManagerServer.findOnlineUserUser2 = new User("bob", "localhost", "2011");
        onlineUserManagerServer.findOnlineUserUsername2 = "bob";
        Message message = MessageFactory.createAddFriendRequestMessage("alice", "bob");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 2);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.ADD_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.ACCEPT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "bob".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[1], MessageSubtype.ADD_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[2], MessageResult.ACCEPT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[3], "alice".toString());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. User who sent
     * the request can not be found
     */
    @Test
    public void testHandleDataAddFriendRequestMessageRequestorNull() {
        System.out.println("Handle Data Requestor AddFriendRequestMessage Null");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser2 = new User("bob", "localhost", "2011");
        onlineUserManagerServer.findOnlineUserUsername2 = "bob";
        Message message = MessageFactory.createAddFriendRequestMessage("alice", "bob");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.ADD_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.REJECT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[4], ErrorType.REMOTE_ACTION_UNSUCCESSFUL.getName());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. User to be
     * added cant be found
     */
    @Test
    public void testHandleDataAddFriendRequestMessageAcceptorNull() {
        System.out.println("Handle Data Acceptor Null");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser1 = new User("alice", "localhost", "2010");
        onlineUserManagerServer.findOnlineUserUsername1 = "alice";
        Message message = MessageFactory.createAddFriendRequestMessage("alice", "bob");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.ADD_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.REJECT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[4], ErrorType.REMOTE_ACTION_UNSUCCESSFUL.getName());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Requesting user
     * added himself
     */
    @Test
    public void testHandleDataAddFriendRequestMessageSameUser() {
        System.out.println("Handle Data Acceptor Null");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser1 = new User("alice", "localhost", "2010");
        onlineUserManagerServer.findOnlineUserUsername1 = "alice";
        Message message = MessageFactory.createAddFriendRequestMessage("alice", "alice");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.ADD_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.REJECT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[4], ErrorType.REMOTE_ACTION_UNSUCCESSFUL.getName());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Logout request
     * message.
     */
    @Test
    public void testHandleDataAddLogoutRequestMessage() {
        System.out.println("Handle Data AddLogoutRequestMessage");
        //Arrange
        onlineUserManagerServer.getOnlineUsers = new User[]{new User("alice", "localhost", "2010"), new User("bob", "localhost", "2011")};

        Message message = MessageFactory.createLogoutRequestMessage("alice");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 2);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.REMOVE_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.ACCEPT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[1], MessageSubtype.REMOVE_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[2], MessageResult.ACCEPT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[3], "alice".toString());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Registration request message.
     */
    @Test
    public void testHandleDataRegistrationRequestMessage() {
        System.out.println("Handle Data RegistrationRequestMessage");
        //Arrange
        Message message = MessageFactory.createRegistrationRequestMessage("alice", "password", "password");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);
        registrationController.registerReturn = true;

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(registrationController.registerInput, "alice");
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.REGISTRATION_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.ACCEPT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Registration
     * request message, registration rejected.
     */
    @Test
    public void testHandleDataRegistrationRequestMessageRejected() {
        System.out.println("Handle Data RegistrationRequestMessageRejected");
        //Arrange
        Message message = MessageFactory.createRegistrationRequestMessage("alice", "password", "password");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);
        registrationController.registerReturn = false;

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(registrationController.registerInput, "alice");
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.REGISTRATION_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.REJECT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[4], ErrorType.REMOTE_ACTION_UNSUCCESSFUL.getName());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Add friend
     * request.
     */
    @Test
    public void testHandleDataRemoveFriendRequestMessage() {
        System.out.println("Handle Data RemoveFriendRequestMessage");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser1 = new User("alice", "localhost", "2010");
        onlineUserManagerServer.findOnlineUserUsername1 = "alice";
        onlineUserManagerServer.findOnlineUserUser2 = new User("bob", "localhost", "2011");
        onlineUserManagerServer.findOnlineUserUsername2 = "bob";
        Message message = MessageFactory.createRemoveFriendRequestMessage("alice", "bob");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 2);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.REMOVE_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.ACCEPT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "bob".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[1], MessageSubtype.REMOVE_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[2], MessageResult.ACCEPT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[1].getData()[3], "alice".toString());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Add friend
     * request. The user requesting to add friend not found.
     */
    @Test
    public void testHandleDataRemoveFriendRequestMessageRequestorNull() {
        System.out.println("Handle Data RemoveFriendRequestMessageRequestorNull");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser2 = new User("bob", "localhost", "2011");
        onlineUserManagerServer.findOnlineUserUsername2 = "bob";
        Message message = MessageFactory.createRemoveFriendRequestMessage("alice", "bob");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.REMOVE_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.REJECT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[4], ErrorType.REMOTE_ACTION_UNSUCCESSFUL.getName());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Add friend
     * request. Friend request acceptor is null.
     */
    @Test
    public void testHandleDataRemoveFriendRequestMessageAcceptorNull() {
        System.out.println("Handle Data RemoveFriendRequestMessageRequestorNull");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser1 = new User("alice", "localhost", "2010");
        onlineUserManagerServer.findOnlineUserUsername1 = "alice";
        Message message = MessageFactory.createRemoveFriendRequestMessage("alice", "bob");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.REMOVE_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.REJECT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[4], ErrorType.REMOTE_ACTION_UNSUCCESSFUL.getName());
    }

    /**
     * Test of handleData method, of class ServerRequestHandler. Add friend
     * request. Requesting user and friend to be removed are same.
     */
    @Test
    public void testHandleDataRemoveFriendRequestMessageSameUser() {
        System.out.println("Handle Data RemoveFriendRequestMessageRequestorNull");
        //Arrange
        onlineUserManagerServer.findOnlineUserUser1 = new User("alice", "localhost", "2010");
        onlineUserManagerServer.findOnlineUserUsername1 = "alice";
        onlineUserManagerServer.findOnlineUserUser2 = new User("bob", "localhost", "2011");
        onlineUserManagerServer.findOnlineUserUsername2 = "bob";
        Message message = MessageFactory.createRemoveFriendRequestMessage("alice", "alice");
        TransmissionRequest request = new TransmissionRequest(2, "localhost", 2010, message);

        //Act
        instance.handleData(request);

        //Assert
        assertEquals(connectionManagerServer.sendToClientCounter, 1);
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[0], MessageType.SERVER_TO_PEER_TYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[1], MessageSubtype.REMOVE_FRIEND_RESPONSE_SUBTYPE.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[2], MessageResult.REJECT_RESULT.toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[3], "alice".toString());
        assertEquals(connectionManagerServer.sendToClientRequests[0].getData()[4], ErrorType.REMOTE_ACTION_UNSUCCESSFUL.getName());
    }
}