text:
package org.apache.polygene.migration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.json.JsonArrayBuilder;
import javax.json.JsonException;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;
import org.apache.polygene.api.activation.ActivatorAdapter;
import org.apache.polygene.api.activation.Activators;
import org.apache.polygene.api.configuration.Configuration;
import org.apache.polygene.api.injection.scope.Service;
import org.apache.polygene.api.injection.scope.Structure;
import org.apache.polygene.api.injection.scope.This;
import org.apache.polygene.api.injection.scope.Uses;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.service.ServiceDescriptor;
import org.apache.polygene.api.service.ServiceReference;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.api.unitofwork.UnitOfWorkFactory;
import org.apache.polygene.migration.assembly.EntityMigrationRule;
import org.apache.polygene.migration.assembly.MigrationBuilder;
import org.apache.polygene.migration.assembly.MigrationContext;
import org.apache.polygene.migration.assembly.MigrationRule;
import org.apache.polygene.serialization.javaxjson.JavaxJsonFactories;
import org.apache.polygene.spi.entitystore.EntityStore;
import org.apache.polygene.spi.entitystore.helpers.JSONKeys;
import org.apache.polygene.spi.entitystore.helpers.Migration;
import org.apache.polygene.spi.entitystore.helpers.StateStore;
import org.apache.polygene.spi.serialization.JsonSerialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.util.Arrays.asList;

/**
 * Migration service. This is used by MapEntityStore EntityStore implementations to
 * migrate JSON state for Entities. To use it register the service so that the EntityStore
 * can access it, and then create MigrationRules during the assembly of your application,
 * which is registered as metainfo for this service.
 *
 * The rules invoke operations, which in turn invoke the Migrator interface to perform the actual
 * migration. If the Migrator accepts a migration command the change is performed, and an event
 * is triggered. These events can be received by implementing the MigrationEvents interface in a service
 * that is visible by this MigrationService.
 */
@Mixins( MigrationService.MigrationMixin.class )
@Activators( MigrationService.Activator.class )
public interface MigrationService
    extends Migration
{
    void initialize()
        throws Exception;

    class Activator
        extends ActivatorAdapter<ServiceReference<MigrationService>>
    {
        @Override
        public void afterActivation( ServiceReference<MigrationService> activated )
            throws Exception
        {
            activated.get().initialize();
        }
    }

    class MigrationMixin
        implements MigrationService, Migrator
    {
        private static final Logger LOGGER = LoggerFactory.getLogger( MigrationService.class );

        @Structure
        private Application app;

        @This
        private Configuration<MigrationConfiguration> config;

        @Uses
        private ServiceDescriptor descriptor;

        @Service
        private StateStore store;

        @Service
        private EntityStore entityStore;

        @Service
        private JsonSerialization serialization;

        @Service
        private JavaxJsonFactories jsonFactories;

        @Structure
        private UnitOfWorkFactory uowf;

        @This
        private Migrator migrator;

        @Service
        private Iterable<MigrationEvents> migrationEvents;

        private MigrationBuilder builder;

        @Override
        public void initialize()
            throws Exception
        {
            builder = descriptor.metaInfo( MigrationBuilder.class );

            String version = app.version();
            String lastVersion = config.get().lastStartupVersion().get();

            // Run general rules if version has changed
            if( !app.version().equals( lastVersion ) )
            {
                Iterable<MigrationRule> rules = builder.migrationRules().rulesBetweenVersions( lastVersion, version );
                List<MigrationRule> executedRules = new ArrayList<>();
                try
                {
                    if( rules != null )
                    {
                        for( MigrationRule rule : rules )
                        {
                            rule.upgrade( store, this );
                            executedRules.add( rule );
                            LOGGER.debug( rule.toString() );
                        }

                        LOGGER.info( "Migrated to " + version );
                    }

                    config.get().lastStartupVersion().set( version );
                    config.save();
                }
                catch( Exception e )
                {
                    LOGGER.error( "Upgrade failed", e );

                    // Downgrade the migrated rules
                    for( MigrationRule executedRule : executedRules )
                    {
                        executedRule.downgrade( store, this );
                    }
                }
            }
        }

        @Override
        public JsonObject migrate( final JsonObject state, String toVersion, StateStore stateStore )
            throws JsonException
        {
            // Get current version
            String fromVersion = state.getString( JSONKeys.APPLICATION_VERSION, "0.0" );

            Iterable<EntityMigrationRule> matchedRules = builder.entityMigrationRules()
                                                                .rulesBetweenVersions( fromVersion, toVersion );

            JsonObject migratedState = state;
            boolean changed = false;
            List<String> failures = new ArrayList<>();
            if( matchedRules != null )
            {
                for( EntityMigrationRule matchedRule : matchedRules )
                {
                    MigrationContext context = new MigrationContext();

                    migratedState = matchedRule.upgrade( context, migratedState, stateStore, migrator );

                    if( context.isSuccess() && context.hasChanged() && LOGGER.isDebugEnabled() )
                    {
                        LOGGER.debug( matchedRule.toString() );
                    }

                    failures.addAll( context.failures() );
                    changed = context.hasChanged() || changed;
                }
            }

            JsonObjectBuilder appVersionBuilder = jsonFactories.builderFactory().createObjectBuilder();
            for( Map.Entry<String, JsonValue> entry : migratedState.entrySet() )
            {
                appVersionBuilder.add( entry.getKey(), entry.getValue() );
            }
            appVersionBuilder.add( JSONKeys.APPLICATION_VERSION, toVersion );
            migratedState = appVersionBuilder.build();

            if( failures.size() > 0 )
            {
                LOGGER.warn( "Migration of {} from {} to {} aborted, failed operation(s):\n{}",
                             state.getString( JSONKeys.IDENTITY ), fromVersion, toVersion,
                             String.join( "\n\t", failures ) );
                return state;
            }

            if( changed )
            {
                LOGGER.info( "Migrated {} from {} to {}",
                             migratedState.getString( JSONKeys.IDENTITY ), fromVersion, toVersion );
                return migratedState;
            }

            // Nothing done
            return state;
        }

        // Migrator implementation
        @Override
        public JsonObject addProperty( MigrationContext context, JsonObject state, String name, Object defaultValue )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( !valueState.containsKey( name ) )
            {
                valueState = jsonFactories.cloneBuilder( valueState )
                                          .add( name, serialization.toJson( defaultValue ) )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();

                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.propertyAdded( state.getString( JSONKeys.IDENTITY ), name, defaultValue );
                }

                return migratedState;
            }
            else
            {
                context.addFailure( "Add property " + name + ", default:" + defaultValue );
                return state;
            }
        }

        @Override
        public JsonObject removeProperty( MigrationContext context, JsonObject state, String name )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( valueState.containsKey( name ) )
            {
                valueState = jsonFactories.cloneBuilderExclude( valueState, name ).build();
                JsonObject migratedState = jsonFactories
                    .cloneBuilderExclude( state, JSONKeys.VALUE )
                    .add( JSONKeys.VALUE, valueState )
                    .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.propertyRemoved( state.getString( JSONKeys.IDENTITY ), name );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Remove property " + name );
                return state;
            }
        }

        @Override
        public JsonObject renameProperty( MigrationContext context, JsonObject state, String from, String to )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( valueState.containsKey( from ) )
            {
                JsonValue jsonValue = valueState.get( from );
                valueState = jsonFactories.cloneBuilderExclude( valueState, from )
                                          .add( to, jsonValue )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.propertyRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Rename property " + from + " to " + to );
                return state;
            }
        }

        @Override
        public JsonObject addAssociation( MigrationContext context, JsonObject state, String name,
                                          String defaultReference )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( !valueState.containsKey( name ) )
            {
                valueState = jsonFactories.cloneBuilder( valueState )
                                          .add( name, defaultReference )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.associationAdded( state.getString( JSONKeys.IDENTITY ), name, defaultReference );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Add association " + name + ", default:" + defaultReference );
                return state;
            }
        }

        @Override
        public JsonObject removeAssociation( MigrationContext context, JsonObject state, String name )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( valueState.containsKey( name ) )
            {
                valueState = jsonFactories.cloneBuilderExclude( valueState, name ).build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.associationRemoved( state.getString( JSONKeys.IDENTITY ), name );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Remove association " + name );
                return state;
            }
        }

        @Override
        public JsonObject renameAssociation( MigrationContext context, JsonObject state, String from, String to )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( valueState.containsKey( from ) )
            {
                JsonValue jsonValue = valueState.get( from );
                valueState = jsonFactories.cloneBuilderExclude( valueState, from )
                                          .add( to, jsonValue )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.associationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Rename association " + from + " to " + to );
                return state;
            }
        }

        @Override
        public JsonObject addManyAssociation( MigrationContext context, JsonObject state, String name,
                                              String... defaultReferences )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( !valueState.containsKey( name ) )
            {
                JsonArrayBuilder refArrayBuilder = jsonFactories.builderFactory().createArrayBuilder();
                for( String ref : defaultReferences )
                {
                    refArrayBuilder.add( ref );
                }
                valueState = jsonFactories.cloneBuilder( valueState )
                                          .add( name, refArrayBuilder.build() )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.manyAssociationAdded( state.getString( JSONKeys.IDENTITY ), name,
                                                         defaultReferences );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Add many-association " + name + ", default:" + asList( defaultReferences ) );
                return state;
            }
        }

        @Override
        public JsonObject removeManyAssociation( MigrationContext context, JsonObject state, String name )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( valueState.containsKey( name ) )
            {
                valueState = jsonFactories.cloneBuilderExclude( valueState, name ).build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.manyAssociationRemoved( state.getString( JSONKeys.IDENTITY ), name );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Remove many-association " + name );
                return state;
            }
        }

        @Override
        public JsonObject renameManyAssociation( MigrationContext context, JsonObject state, String from, String to )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( valueState.containsKey( from ) )
            {
                JsonValue jsonValue = valueState.get( from );
                valueState = jsonFactories.cloneBuilderExclude( valueState, from )
                                          .add( to, jsonValue )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.manyAssociationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Rename many-association " + from + " to " + to );
                return state;
            }
        }

        @Override
        public JsonObject addNamedAssociation( MigrationContext context, JsonObject state, String name,
                                               Map<String, String> defaultReferences )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( !valueState.containsKey( name ) )
            {
                JsonObjectBuilder refBuilder = jsonFactories.builderFactory().createObjectBuilder();
                for( Map.Entry<String, String> entry : defaultReferences.entrySet() )
                {
                    refBuilder.add( entry.getKey(), entry.getValue() );
                }
                valueState = jsonFactories.cloneBuilder( valueState )
                                          .add( name, refBuilder.build() )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.namedAssociationAdded( state.getString( JSONKeys.IDENTITY ), name,
                                                          defaultReferences );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Add named-association " + name + ", default:" + defaultReferences );
                return state;
            }
        }

        @Override
        public JsonObject removeNamedAssociation( MigrationContext context, JsonObject state, String name )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( !valueState.containsKey( name ) )
            {
                valueState = jsonFactories.cloneBuilderExclude( valueState, name ).build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.namedAssociationRemoved( state.getString( JSONKeys.IDENTITY ), name );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Remove named-association " + name );
                return state;
            }
        }

        @Override
        public JsonObject renameNamedAssociation( MigrationContext context, JsonObject state, String from, String to )
            throws JsonException
        {
            JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
            if( valueState.containsKey( from ) )
            {
                JsonValue jsonValue = valueState.get( from );
                valueState = jsonFactories.cloneBuilderExclude( valueState, from )
                                          .add( to, jsonValue )
                                          .build();
                JsonObject migratedState = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                                                        .add( JSONKeys.VALUE, valueState )
                                                        .build();
                context.markAsChanged();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.namedAssociationRenamed( state.getString( JSONKeys.IDENTITY ), from, to );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Rename named-association " + from + " to " + to );
                return state;
            }
        }

        @Override
        public JsonObject changeEntityType( MigrationContext context, JsonObject state,
                                            String fromType, String toType )
            throws JsonException
        {
            String currentType = state.getString( JSONKeys.TYPE );
            if( fromType.equals( currentType ) )
            {
                JsonObject migratedState = jsonFactories.cloneBuilder( state )
                                                        .add( JSONKeys.TYPE, toType )
                                                        .build();
                for( MigrationEvents migrationEvent : migrationEvents )
                {
                    migrationEvent.entityTypeChanged( state.getString( JSONKeys.IDENTITY ), toType );
                }
                return migratedState;
            }
            else
            {
                context.addFailure( "Change entity type from " + fromType + " to " + toType );
                return state;
            }
        }
    }
}


text:
package org.tylproject.vaadin.addon.datanav;

import com.vaadin.ui.*;
import org.tylproject.vaadin.addon.datanav.events.CurrentItemChange;
import org.tylproject.vaadin.addon.datanav.resources.Strings;

import javax.annotation.Nonnull;
import javax.swing.*;
import java.util.ResourceBundle;

/**
 * Created by evacchi on 04/12/14.
 */
public abstract class AbstractButtonBar extends CustomComponent implements DataNavigationBar {

    private final HorizontalLayout buttonLayout = new HorizontalLayout();

    private Panel focusPanel;
    private FocusManager focusManager;
    private @Nonnull DataNavigation navigation;

    protected AbstractButtonBar(DataNavigation navigation) {
        this.navigation = navigation;
        setCompositionRoot(this.getLayout());
        this.setSizeUndefined();
    }

    @Override
    public void setNavigation(@Nonnull DataNavigation nav) {
        detachNavigation(this.navigation);
        this.navigation = nav;
        attachNavigation(nav);
    }

    public DataNavigation getNavigation() {
        return this.navigation;
    }

    @Override
    public Layout getLayout() {
        return buttonLayout;
    }

    protected static final ResourceBundle resourceBundle =
            ResourceBundle.getBundle(Strings.class.getCanonicalName());

    protected abstract void detachNavigation(@Nonnull DataNavigation nav) ;

    protected abstract void attachNavigation(@Nonnull DataNavigation nav) ;

    protected Button button(String labelIdentifier) {
        return new Button(resourceBundle.getString(labelIdentifier));
    }
    protected void enable(Button... btns) {
        for (Button btn: btns) btn.setEnabled(true);
    }
    protected void disable(Button... btns) {
        for (Button btn: btns) btn.setEnabled(false);
    }

}

redpajama_set_name: RedPajamaGithub


text:
require "spec_helper"

describe "brightbox servers" do
  let(:output) { FauxIO.new { Brightbox.run(argv) } }
  let(:stdout) { output.stdout }
  let(:stderr) { output.stderr }

  let(:resource_class) { Brightbox::Server }
  let(:resource_id) { "srv-12345" }
  let(:resource) { double(resource_class, :to_s => resource_id) }

  let(:resource_ids) { [resource_id] }
  let(:results) { [resource] }

  before do
    config = config_from_contents(USER_APP_CONFIG_CONTENTS)
    cache_access_token(config, "f83da712e6299cda953513ec07f7a754f747d727")
  end

  describe "reboot" do
    context "when resource is known" do
      let(:argv) { %w[servers reboot srv-12345] }

      before do
        expect(resource_class).to receive(:find_or_call).with(resource_ids).and_return(results)
        expect(resource).to receive(:reboot).with(false)
      end

      it "outputs notice to STDERR" do
        expect(stderr).to match("Sending reboot to #{resource_id}")
      end
    end

    context "when resource is unknown" do
      let(:argv) { %w[servers reboot srv-12345] }

      before do
        expect(resource_class).to receive(:find).with(resource_id).and_raise(Brightbox::Api::NotFound)
      end

      it "outputs error to STDERR" do
        expect(stderr).to match("ERROR: Couldn't find #{resource_id}")
      end
    end

    context "when no arguments are passed" do
      let(:argv) { %w[servers reboot] }

      it "outputs error to STDERR" do
        expect(stderr).to match("ERROR: You must specify servers to reboot")
      end
    end
  end
end


text:
class ContactType < ActiveModel::Type::Value
  def cast(value)
    if value.is_a?(Nomis::Contact)
      value
    else
      Nomis::Contact.new(value)
    end
  end
end


text:
<?php

/**
 * sql backend class for the addressbook
 *
 * @package     Addressbook
 */
class Addressbook_Backend_List extends Tinebase_Backend_Sql_Abstract
{
    /**
     * Table name without prefix
     *
     * @var string
     */
    protected $_tableName = 'addressbook_lists';

    /**
     * Model name
     *
     * @var string
     */
    protected $_modelName = 'Addressbook_Model_List';

    /**
     * if modlog is active, we add 'is_deleted = 0' to select object in _getSelect()
     *
     * @var boolean
     */
    protected $_modlogActive = TRUE;

    /**
     * default column(s) for count
     *
     * @var string
     */
    protected $_defaultCountCol = 'id';

    /**
     * foreign tables
     * name => array(table, joinOn, field)
     *
     * @var array
     */
    protected $_foreignTables = array(
        'members'    => array(
            'table'  => 'addressbook_list_members',
            'field'  => 'contact_id',
            'joinOn' => 'list_id',
            'preserve' => TRUE,
        ),
        'group_id'    => array(
            'table'        => 'groups',
            'field'        => 'id',
            'joinOn'       => 'list_id',
        // use first element of result array
            'singleValue'  => TRUE,
        )
    );

    /**
     * converts record into raw data for adapter
     *
     * @param  Tinebase_Record_Abstract $_record
     * @return array
     */
    protected function _recordToRawData($_record)
    {
        $result = parent::_recordToRawData($_record);

        // stored in foreign key
        unset($result['members']);
        unset($result['group_id']);

        return $result;
    }

    /**
     * add new members to list
     *
     * @param  mixed  $_listId
     * @param  mixed  $_newMembers
     * @return Addressbook_Model_List
     */
    public function addListMember($_listId, $_newMembers)
    {
        $list = $this->get($_listId);

        if (empty($_newMembers)) {
            return $list;
        }

        $newMembers = $this->_getIdsFromMixed($_newMembers);
        $idsToAdd   = array_diff($newMembers, $list->members);

        $listId     = Tinebase_Record_Abstract::convertId($_listId, $this->_modelName);

        $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());

        foreach ($idsToAdd as $id) {
            $recordArray = array (
                $this->_foreignTables['members']['joinOn'] => $listId,
                $this->_foreignTables['members']['field']  => $id
            );
            $this->_db->insert($this->_tablePrefix . $this->_foreignTables['members']['table'], $recordArray);
        }

        Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);

        return $this->get($_listId);
    }

    /**
     * Delete all lists returned by {@see getAll()} using {@see delete()}
     * @return void
     */
    public function deleteAllLists()
    {
        $lists = $this->getAll();

        if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Deleting ' . count($lists) .' lists');

        if(count($lists) > 0) {
            $this->delete($lists->getArrayOfIds());
        }
    }

    /**
     * remove members from list
     *
     * @param  mixed  $_listId
     * @param  mixed  $_newMembers
     * @return Addressbook_Model_List
     */
    public function removeListMember($_listId, $_oldMembers)
    {
        $list = $this->get($_listId);

        if (empty($_oldMembers)) {
            return $list;
        }

        $oldMembers  = $this->_getIdsFromMixed($_oldMembers);
        $idsToRemove = array_intersect($list->members, $oldMembers);
        $listId      = Tinebase_Record_Abstract::convertId($_listId, $this->_modelName);

        $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());

        if (!empty($idsToRemove)) {
            $where = '(' .
                $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $this->_foreignTables['members']['table'] . '.' . $this->_foreignTables['members']['joinOn']) . ' = ?', $listId) .
                ' AND ' .
                $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $this->_foreignTables['members']['table'] . '.' . $this->_foreignTables['members']['field']) . ' IN (?)', $idsToRemove) .
            ')';

            $this->_db->delete($this->_tablePrefix . $this->_foreignTables['members']['table'], $where);
        }

        Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);

        return $this->get($_listId);
    }

    /**
    * set all lists an user is member of
    *
    * @param  string  $contactId
    * @param  mixed  $listIds
    * @return array
    */
    public function setMemberships($contactId, $listIds)
    {
        $contactId = Tinebase_Record_Abstract::convertId($contactId, 'Addressbook_Model_Contact');

        if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__
            . ' Set ' . count($listIds) . ' list memberships for contact ' . $contactId);

        if ($listIds instanceof Tinebase_Record_RecordSet) {
            $listIds = $listIds->getArrayOfIds();
        }

        $listMemberships = $this->getMemberships($contactId);

        $removeListMemberships = array_diff($listMemberships, $listIds);
        $addListMemberships    = array_diff($listIds, $listMemberships);

        if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' current memberships: ' . print_r($listMemberships, true));
        if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' new memberships: ' . print_r($listIds, true));
        if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' added memberships: ' . print_r($addListMemberships, true));
        if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' removed memberships: ' . print_r($removeListMemberships, true));

        foreach ($addListMemberships as $listId) {
            $this->addListMember($listId, $contactId);
        }

        foreach ($removeListMemberships as $listId) {
            $this->removeListMember($listId, $contactId);
        }

        return $this->getMemberships($contactId);
    }

    /**
     * get group memberships of contact id
     *
     * @param mixed $contactId
     * @return array
     */
    public function getMemberships($contactId)
    {
        $contactId = Tinebase_Record_Abstract::convertId($contactId, 'Addressbook_Model_Contact');

        $select = $this->_db->select()
            ->from($this->_tablePrefix . $this->_foreignTables['members']['table'], 'list_id')
            ->where($this->_db->quoteIdentifier('contact_id') . ' = ?', $contactId);

        $stmt = $this->_db->query($select);
        $rows = (array) $stmt->fetchAll(Zend_Db::FETCH_ASSOC);

        $result = array();
        foreach ($rows as $membership) {
            $result[] = $membership['list_id'];
        }

        return $result;
    }

    /**
     * get list by group name
     *
     * @param string $groupName
     * @return NULL|Addressbook_Model_List
     */
    public function getByGroupName($groupName)
    {
        $filter = new Addressbook_Model_ListFilter(array(
            array('field' => 'name', 'operator' => 'equals', 'value' => $groupName),
            array('field' => 'type', 'operator' => 'equals', 'value' => Addressbook_Model_List::LISTTYPE_GROUP)
        ));

        $existingLists = $this->search($filter);

        return $existingLists->getFirstRecord();
    }
}


text:
package io.apiman.cli.managerapi.command.gateway;

import io.apiman.cli.Cli;
import io.apiman.cli.common.BaseIntegrationTest;
import io.apiman.cli.common.IntegrationTest;
import io.apiman.cli.util.AuthUtil;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runners.MethodSorters;

/**
 * @author Pete Cornish {@literal <outofcoffee@gmail.com>}
 */
@Category(IntegrationTest.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class GatewayTest extends BaseIntegrationTest {

    @Test
    public void test1_test() {
        Cli.main("manager",
                "gateway", "test",
                "--debug",
                "--server", getApimanUrl(),
                "--serverUsername", AuthUtil.DEFAULT_SERVER_USERNAME,
                "--serverPassword", AuthUtil.DEFAULT_SERVER_PASSWORD,
                "--endpoint", "http://localhost:8080/apiman-gateway-api",
                "--username", "apimanager",
                "--password", "apiman123!",
                "--type", "REST");
    }

    @Test
    public void test2_create() {
        Cli.main("manager",
                "gateway", "create",
                "--debug",
                "--server", getApimanUrl(),
                "--serverUsername", AuthUtil.DEFAULT_SERVER_USERNAME,
                "--serverPassword", AuthUtil.DEFAULT_SERVER_PASSWORD,
                "--name", "test",
                "--description", "example",
                "--endpoint", "http://localhost:1234",
                "--username", "apimanager",
                "--password", "apiman123!",
                "--type", "REST");
    }

    @Test
    public void test3_fetch() {
        Cli.main("manager",
                "gateway", "show",
                "--debug",
                "--server", getApimanUrl(),
                "--serverUsername", AuthUtil.DEFAULT_SERVER_USERNAME,
                "--serverPassword", AuthUtil.DEFAULT_SERVER_PASSWORD,
                "--name", "test");
    }

    @Test
    public void test4_list() {
        Cli.main("manager",
                "gateway", "list",
                "--debug",
                "--server", getApimanUrl(),
                "--serverUsername", AuthUtil.DEFAULT_SERVER_USERNAME,
                "--serverPassword", AuthUtil.DEFAULT_SERVER_PASSWORD);
    }
}


text:
source "$SCRIPTPATH/inc/commons.sh"
source "$SCRIPTPATH/inc/header.sh"
echo -e "${GREEN}AtoMiC $APPTITLE Uninstaller Script$ENDCOLOR"
source "$SCRIPTPATH/inc/pause.sh"
source "$SCRIPTPATH/inc/app-autostart-remove.sh"
source "$SCRIPTPATH/inc/app-file-del.sh"
source "$SCRIPTPATH/inc/app-uninstall.sh"
source "$SCRIPTPATH/inc/app-uninstall-confirmation.sh"
source "$SCRIPTPATH/inc/thankyou.sh"
source "$SCRIPTPATH/inc/exit.sh"


text:
$(document).ready(function() {
	console.log("ready");
	$("form").on("submit",function() {
		console.log("the form has been submitted")
		var valueOne = $('input[name="number-one"]').val()
		var valueTwo = $('input[name="number-two"]').val()
		console.log(valueOne, valueTwo)

	});
});


text:
@implementation SBListenListItem

@end


text:
#ifndef WEBRTC_GETUSERMEDIA_H
#define WEBRTC_GETUSERMEDIA_H

#include <nan.h>

namespace WebRTC {
  class GetUserMedia {
   public:
    static void Init(v8::Handle<v8::Object> exports);

   private:
    static NAN_METHOD(GetMediaStream);
  };
};

#endif


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>net.martenscs.osgi.mybatis.blueprint.example</groupId>
	<artifactId>net.martenscs.osgi.mybatis.blueprint.example</artifactId>
	<packaging>eclipse-plugin</packaging>
	<parent>
		<groupId>net.martenscs.osgi</groupId>
		<artifactId>mybatis.build</artifactId>
		<version>1.0.0-SNAPSHOT</version>
		<relativePath>../net.martenscs.osgi</relativePath>
	</parent>
</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
using Cumulus.Interceptors.Inbound;
using Cumulus.UnitTests.DispatcherTests.Handlers;
using Cumulus.UnitTests.DispatcherTests.MessageContracts;
using NSubstitute;
using NUnit.Framework;

namespace Cumulus.UnitTests.DispatcherTests
{
    public class WhenInboundInterceptorThrowsExceptionOnCommandHandlerExecuting
        : MessageDispatcherTestBase
    {
        [Test]
        public void TheExceptionIsBubbledBackThroughTheInterceptors()
        {
            var interceptor = Substitute.For<IInboundInterceptor>();
            interceptor
                .When(x => x.OnCommandHandlerExecuting(Arg.Any<EmptyCommand>(), Arg.Any<BrokeredMessage>()))
                .Do(x =>
                {
                    throw new Exception("Ruh roh");
                });
            var dispatcher = GetCommandMessageDispatcher<EmptyCommand, EmptyCommandHandler>(interceptor);
            var brokeredMessage = BrokeredMessageFactory.Create(new EmptyCommand()).Result;

            try
            {
                dispatcher.Dispatch(brokeredMessage).Wait();
            }
            catch (AggregateException)
            {
                // Dispatch rethrows the exception, don't care
            }

            interceptor
                .Received()
                .OnCommandHandlerError(Arg.Any<EmptyCommand>(), brokeredMessage, Arg.Any<Exception>());
        }
    }
}


text:
assignees:
- bgrant0607
- thockin

---

What is Kubernetes?

Kubernetes is an open-source platform for automating deployment, scaling, and operations of application containers across clusters of hosts. Learn more about what this means for your app.

    Read the Overview

Kubernetes Basics Interactive Tutorial

The Kubernetes Basics interactive tutorials let you try out Kubernetes features using Minikube right out of your web browser in a virtual terminal. Learn about the Kubernetes system and deploy, expose, scale, and upgrade a containerized application in just a few minutes.

    Try the Interactive Tutorials

Installing Kubernetes on Linux with kubeadm

This quickstart will show you how to install a secure Kubernetes cluster on any computers running Linux, using a tool called kubeadm. It'll work with local VMs, physical servers and/or cloud servers, either manually or as a part of your own automation. It is currently in alpha but please try it out and give us feedback!

If you are looking for a fully automated solution, note that kubeadm is intended as a building block.  Tools such as GKE and kops build on kubeadm to provision a complete cluster.

    Install Kubernetes with kubeadm

Installing Kubernetes on AWS with kops

This quickstart will show you how to bring up a complete Kubernetes cluster on AWS, using a tool called kops.

    Install Kubernetes with kops

Guided Tutorial

If you've completed one of the quickstarts, a great next step is Kubernetes 101. You will follow a path through the various features of Kubernetes, with code examples along the way, learning all of the core concepts. There's also a Kubernetes 201!

    Kubernetes 101

## Samples

MEAN Stack

Guestbook + Redis

Cloud Native Cassandra

WordPress + MySQL

Contribute to Our Docs

The docs for Kubernetes are open-source, just like the code for Kubernetes itself. The docs are on GitHub Pages, so you can fork it and it will auto-stage on username.github.io, previewing your changes!

  Write Docs for K8s

Need Help?

Try consulting our troubleshooting guides, or our FAQ. Kubernetes is also supported by a great community of contributors and experts who hang out in our Slack channel, our Google Group and Stack Overflow.

  Get Support


text:
// @flow
/*jshint esversion: 6 */
/*jslint node: true */
"use strict";

const openSshTunnel = require("open-ssh-tunnel");

const localHost = "127.0.0.1";

async function openTunnel() {
    const server = await openSshTunnel({
        host: settings.secureNodeFQDN,// SSH server //settings.secureNodeFQDN,
        port: settings.sshPort, // SSH port
        // keepAlive:true,
        username: settings.sshUsername, //settings.secureNodeUsername,
        password: settings.sshPassword, //settings.secureNodePassword,
        srcPort: settings.secureNodePort, // Arizen localhost port //settings.secureNodePort
        srcAddr: localHost, // Arizen localhost
        dstPort: settings.secureNodePort, // Service localhost port //settings.secureNodePort
        dstAddr: localHost, // Service localhost
        readyTimeout: settings.readyTimeout,
        forwardTimeout: settings.forwardTimeout,
        localPort: settings.secureNodePort, // SSH client localhost port
        localAddr: localHost // SSH client localhost
    });

    return server
}

module.exports = {
    openTunnel: openTunnel
};


text:
package com.mercury.platform.ui.adr.components.panel.ui;

import com.mercury.platform.ui.misc.AppThemeColor;
import lombok.Getter;
import lombok.Setter;
import org.pushingpixels.trident.Timeline;
import org.pushingpixels.trident.callback.TimelineCallbackAdapter;
import org.pushingpixels.trident.ease.Spline;

import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import java.awt.*;

public class MercuryLoading extends JComponent {
    @Getter
    private int value;
    @Setter
    @Getter
    private int maximum;
    @Setter
    @Getter
    private int minimum;
    private Timeline progressTl;
    @Setter
    private boolean swapEnable;

    public MercuryLoading() {
        this.setValue(0);
        this.setMaximum(3000);
        this.setForeground(AppThemeColor.TEXT_NICKNAME);
        this.setBackground(AppThemeColor.ADR_FOOTER_BG);

        this.setUI(new MercuryLoadingUi(this));

        this.progressTl = new Timeline(this);
        this.progressTl.setDuration(2400);
        this.progressTl.addPropertyToInterpolate("value", this.getMaximum(), 0);
        this.progressTl.setEase(new Spline(1));
        this.progressTl.addCallback(new TimelineCallbackAdapter() {
            @Override
            public void onTimelineStateChanged(Timeline.TimelineState oldState, Timeline.TimelineState newState, float durationFraction, float timelinePosition) {
                swapColors();
            }
        });
    }

    public void setValue(int value) {
        this.value = value;
        this.updateUI();
    }

    public void setLoadingUI(ComponentUI componentUI) {
        this.setUI(componentUI);
    }

    @Override
    public void updateUI() {
        setUI(this.ui);
    }

    public float getPercentComplete() {
        long span = maximum - minimum;
        return (value - minimum) / (span * 1f);
    }

    public void abort() {
        this.progressTl.abort();
    }

    public void playLoop() {
        this.progressTl.playLoop(Timeline.RepeatBehavior.LOOP);
    }

    public void play() {
        this.progressTl.play();
    }

    public void cancel() {
        this.progressTl.cancel();
    }

    public void swapColors() {
        if (swapEnable) {
            Color temp = new Color(this.getBackground().getRGB());
            this.setBackground(this.getForeground());
            this.setForeground(temp);
        }
    }
}


text:
package net.ssehub.easy.varModel.cstEvaluation;

import net.ssehub.easy.basics.messages.Status;
import net.ssehub.easy.basics.pool.IPoolManager;
import net.ssehub.easy.basics.pool.Pool;
import net.ssehub.easy.varModel.confModel.AssignmentState;
import net.ssehub.easy.varModel.confModel.CompoundVariable;
import net.ssehub.easy.varModel.confModel.ConfigurationException;
import net.ssehub.easy.varModel.confModel.IAssignmentState;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.cstEvaluation.EvaluationVisitor.Message;
import net.ssehub.easy.varModel.cstEvaluation.IValueChangeListener.ChangeKind;
import net.ssehub.easy.varModel.model.values.Value;

/**
 * Implements an accessor for decision variables. This class supports {@link IEvaluationInterceptor}.
 *
 * @author Holger Eichelberger
 */
class CompoundSlotAccessor extends AbstractDecisionVariableEvaluationAccessor {

    public static final Pool<CompoundSlotAccessor> POOL = new Pool<CompoundSlotAccessor>(
        new IPoolManager<CompoundSlotAccessor>() {

            public CompoundSlotAccessor create() {
                return new CompoundSlotAccessor();
            }

            public void clear(CompoundSlotAccessor instance) {
                instance.clear();
            }
        });

    private IDecisionVariable slotVariable;

    /**
     * Creates an instance. Private due to pooling.
     */
    private CompoundSlotAccessor() {
    }

    /**
     * Binds the accessor to the given variable and context.
     *
     * @param variable the underlying variable
     * @param slotName the name of the slot within value
     * @param context the evaluation context
     * @return this (builder pattern)
     */
    public CompoundSlotAccessor bind(IDecisionVariable variable, String slotName,
        EvaluationContext context) {
        super.bind(variable, context);
        slotVariable = ((CompoundVariable) variable).getNestedVariable(slotName);
        return this;
    }

    /**
     * Binds the accessor to the given variable and context.
     *
     * @param variable the underlying variable
     * @param slotName the name of the slot within value
     * @param context the evaluation context
     * @return this (builder pattern)
     */
    public CompoundSlotAccessor bind(LocalDecisionVariable variable, String slotName,
        EvaluationContext context) {
        super.bind(variable, context);
        slotVariable = variable.getNestedVariable(slotName);
        return this;
    }

    @Override
    public void clear() {
        super.clear();
        slotVariable = null;
    }

    @Override
    public Value getValue() {
        Value result;
        if (null != slotVariable) {
            result = slotVariable.getValue();
        } else {
            result = null;
        }
        return result;
    }

    @Override
    public EvaluationAccessor getValue(EvaluationAccessor accessor) {
        EvaluationAccessor result = null;
        if (null != slotVariable) {
            VariableAccessor tmp = VariableAccessor.POOL.getInstance().bind(slotVariable, getContext());
            result = tmp.getValue(accessor);
            VariableAccessor.POOL.releaseInstance(tmp);
        }
        return result;
    }

    @Override
    public boolean setValue(Value value, boolean asAssignment) {
        boolean successful = false;
        EvaluationContext context = getContext();
        if (context.allowAssignValues() && null != slotVariable) {
            if (null != value) {
                boolean assign = true;
                IAssignmentState slotState = slotVariable.getState();
                if (AssignmentState.DEFAULT == context.getAssignmentState()) {
                    if (!slotVariable.getParent().wasCreated()) {
                        // no parent value, defer until initialized
                        successful = false; // defer
                        assign = false;
                    } else if (slotState != AssignmentState.UNDEFINED && slotState != AssignmentState.FROZEN) {
                        // there is a value and it is not frozen, ignore and pretend that successful
                        assign = false;
                    }
                }
                if (assign) {
                    successful = assignValue(value, asAssignment);
                }
            }
        }
        return successful;
    }

    /**
     * Assigns the value.
     *
     * @param value the value
     * @param asAssignment does this happen through an IVML assignment operation
     * @return whether the assignment was successful or not
     */
    private final boolean assignValue(Value value, boolean asAssignment) {
        boolean successful = false;
        Value oldValue = slotVariable.getValue();
        IAssignmentState oldState = slotVariable.getState();
        if (!Value.equalsPartially(oldValue, value)
            && oldState != AssignmentState.USER_ASSIGNED) { // don't reassign / send message
            EvaluationContext context = getContext();
            IAssignmentState targetState = context.getTargetState(slotVariable);
            if (null != targetState) {
                try {
                    dereferenceIfNeeded(slotVariable, value).setValue(value, targetState, asAssignment);
                    successful = true;
                    notifyVariableChange(oldValue, oldState, ChangeKind.FULL);
                } catch (ConfigurationException e) {
                    context.addErrorMessage(e);
                }
            } else {
                context.addMessage(new Message("Assignment state conflict", Status.ERROR, slotVariable,
                    Message.CODE_ASSIGNMENT_STATE));
            }
        } else {
            successful = true;
        }
        return successful;
    }

    @Override
    public IDecisionVariable getVariable() {
        return slotVariable;
    }

    @Override
    public void release() {
        POOL.releaseInstance(this);
    }

    @Override
    public boolean isAssignable() {
        return true;
    }

}


text:
package Bucles;
//Programa que lea n pares de datos, cada par de datos corresponde a la medida de la base y la altura de un triángulo. El programa deberá informar:
//a) De cada triángulo la medida de su base, su altura y su superficie.
//b) La cantidad de triángulos cuya superficie es mayor a 12.
import java.util.*;
public class For01
{
	static Scanner leer;
	static int base, altura, superficie, mayores, cantidad;

	public static void main(String[] args)
	{
		leer = new Scanner(System.in);

		System.out.println("  -- For01 --");
		System.out.print("Nº de triangulos: ");
		cantidad = leer.nextInt();

		for(int a = 1; a<=cantidad; a++)
		{
			System.out.print("Introducir altura: ");
			altura = leer.nextInt();
			System.out.print("Introducir base: ");
			base = leer.nextInt();

			superficie = base*altura/2;
			System.out.println("La superficie es: "+superficie);

			if(superficie>12)
			{
				mayores = mayores + 1;
			}
		}

		System.out.println("Hay "+cantidad+" triangulos con superficia mayor de 12");
	}
}


text:
//
// Copyright 2013 Hans Wolff
//
// 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
//
// 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.
//

using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Threading;

namespace RedFoxMQ.Tests
{
    [TestFixture]
    public class ResponderWorkerSchedulerTests
    {
        private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(1);

        [Test]
        public void ResponderWorkerScheduler_constructor_MinThreads_negative_throws_ArgumentOutOfRangeException()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new ResponderWorkerScheduler(-1, 1));
        }

        [Test]
        public void ResponderWorkerScheduler_constructor_MaxThreads_zero_throws_ArgumentOutOfRangeException()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new ResponderWorkerScheduler(0, 0));
        }

        [Test]
        public void ResponderWorkerScheduler_constructor_MaxThreads_less_than_MinThreads_throws_ArgumentOutOfRangeException()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new ResponderWorkerScheduler(1, 0));
        }

        [Test]
        public void ResponderWorkerScheduler_number_of_MinThreads_created()
        {
            using (var scheduler = new ResponderWorkerScheduler(1, 2))
            {
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_Dispose_kills_all_threads()
        {
            using (var scheduler = new ResponderWorkerScheduler(2, 2))
            {
                scheduler.Dispose();

                Thread.Sleep(30);

                Assert.AreEqual(0, scheduler.CurrentWorkerThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_many_MinThreads_created_but_should_be_idle()
        {
            if (PlatformHelpers.IsLinux())
            {
                Assert.Inconclusive("This test is not designed to run on Linux");
            }

            var minThreads = Environment.ProcessorCount * 4;
            using (var scheduler = new ResponderWorkerScheduler(minThreads, minThreads))
            {
                Assert.AreEqual(minThreads, scheduler.CurrentWorkerThreadCount);

                var timeout = TimeSpan.FromSeconds(5);
                var started = DateTime.UtcNow;
                double oldTime;
                var time = Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;
                do
                {
                    oldTime = time;
                    Thread.Sleep(1000);
                    time = Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;

                    if (DateTime.UtcNow - started > timeout)
                        Assert.Fail("Worker threads should be idle, when no worker is added");

                } while (time - oldTime > 100);

                Assert.Pass();
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentBusyThreadCount_increased_when_busy()
        {
            var worker = new TestWorker(30);
            using (var scheduler = new ResponderWorkerScheduler(1, 1))
            {
                Assert.AreEqual(0, scheduler.CurrentBusyThreadCount);

                scheduler.AddWorker(worker, new TestMessage(), null);

                worker.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentBusyThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentBusyThreadCount_decreased_when_back_idle()
        {
            var worker = new TestWorker(30);
            using (var scheduler = new ResponderWorkerScheduler(1, 1))
            {
                scheduler.AddWorker(worker, new TestMessage(), null);

                worker.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentBusyThreadCount);

                worker.WaitCompleted(Timeout);
                Thread.Sleep(15);
                Assert.AreEqual(0, scheduler.CurrentBusyThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentBusyThreadCount_increased_then_decreased_then_increased()
        {
            using (var scheduler = new ResponderWorkerScheduler(1, 1))
            {
                var worker1 = new TestWorker(30);
                scheduler.AddWorker(worker1, new TestMessage(), null);

                worker1.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentBusyThreadCount);

                worker1.WaitCompleted(Timeout);
                Thread.Sleep(10);
                Assert.AreEqual(0, scheduler.CurrentBusyThreadCount);

                var worker2 = new TestWorker(30);
                scheduler.AddWorker(worker2, new TestMessage(), null);

                worker2.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentBusyThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentBusyThreadCount_increased_twice()
        {
            using (var scheduler = new ResponderWorkerScheduler(0, 2))
            {
                Assert.AreEqual(0, scheduler.CurrentBusyThreadCount);

                var worker1 = new TestWorker(10);
                scheduler.AddWorker(worker1, new TestMessage(), null);
                worker1.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentBusyThreadCount);

                var worker2 = new TestWorker(10);
                scheduler.AddWorker(worker2, new TestMessage(), null);
                worker2.WaitStarted(Timeout);
                Assert.AreEqual(2, scheduler.CurrentBusyThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentWorkerThreadCount_increased_when_busy()
        {
            var worker = new TestWorker(30);
            using (var scheduler = new ResponderWorkerScheduler(0, 1))
            {
                Assert.AreEqual(0, scheduler.CurrentWorkerThreadCount);

                scheduler.AddWorker(worker, new TestMessage(), null);

                worker.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentWorkerThreadCount_decreased_when_back_idle()
        {
            var worker = new TestWorker(30);
            using (var scheduler = new ResponderWorkerScheduler(0, 1, TimeSpan.FromMilliseconds(1)))
            {
                scheduler.AddWorker(worker, new TestMessage(), null);

                worker.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);

                worker.WaitCompleted(Timeout);
                Thread.Sleep(15);
                Assert.AreEqual(0, scheduler.CurrentWorkerThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentWorkerThreadCount_not_decreased_when_back_idle_before_MaxIdleTime()
        {
            var worker = new TestWorker(30);
            using (var scheduler = new ResponderWorkerScheduler(0, 1, TimeSpan.FromMilliseconds(100)))
            {
                scheduler.AddWorker(worker, new TestMessage(), null);

                worker.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);

                worker.WaitCompleted(Timeout);
                Thread.Sleep(15);
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentWorkerThreadCount_increased_then_decreased_then_increased()
        {
            using (var scheduler = new ResponderWorkerScheduler(0, 1, TimeSpan.FromMilliseconds(1)))
            {
                var worker1 = new TestWorker(30);
                scheduler.AddWorker(worker1, new TestMessage(), null);

                worker1.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);

                worker1.WaitCompleted(Timeout);
                Thread.Sleep(10);
                Assert.AreEqual(0, scheduler.CurrentWorkerThreadCount);

                var worker2 = new TestWorker(30);
                scheduler.AddWorker(worker2, new TestMessage(), null);

                worker2.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);
            }
        }

        [Test]
        public void ResponderWorkerScheduler_CurrentWorkerThreadCount_increased_twice()
        {
            using (var scheduler = new ResponderWorkerScheduler(0, 2, TimeSpan.FromMilliseconds(1)))
            {
                Assert.AreEqual(0, scheduler.CurrentWorkerThreadCount);

                var worker1 = new TestWorker(10);
                scheduler.AddWorker(worker1, new TestMessage(), null);
                worker1.WaitStarted(Timeout);
                Assert.AreEqual(1, scheduler.CurrentWorkerThreadCount);

                var worker2 = new TestWorker(10);
                scheduler.AddWorker(worker2, new TestMessage(), null);
                worker2.WaitStarted(Timeout);
                Assert.AreEqual(2, scheduler.CurrentWorkerThreadCount);
            }
        }
    }
}


text:
/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('phpbb_bots', {
    bot_id: {
      type: DataTypes.INTEGER(8),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    bot_active: {
      type: DataTypes.INTEGER(1),
      allowNull: false,
      defaultValue: "1"
    },
    bot_name: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ""
    },
    user_id: {
      type: DataTypes.INTEGER(8),
      allowNull: false,
      defaultValue: "0"
    },
    bot_agent: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ""
    },
    bot_ip: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ""
    }
  }, {
    tableName: 'phpbb_bots'
  });
};


text:
package mesosphere.marathon.upgrade

import akka.actor.{ ActorRef, ActorSystem, Props }
import akka.event.EventStream
import akka.testkit.TestActor.{ AutoPilot, NoAutoPilot }
import akka.testkit.{ ImplicitSender, TestActorRef, TestKit, TestProbe }
import akka.util.Timeout
import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.core.launchqueue.LaunchQueue
import mesosphere.marathon.health.HealthCheckManager
import mesosphere.marathon.io.storage.StorageProvider
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.state.{ AppDefinition, AppRepository, Group, MarathonStore }
import mesosphere.marathon.tasks.TaskTracker
import mesosphere.marathon.upgrade.DeploymentActor.Cancel
import mesosphere.marathon.upgrade.DeploymentManager.{ CancelDeployment, DeploymentFailed, PerformDeployment }
import mesosphere.marathon.{ MarathonConf, SchedulerActions }
import mesosphere.util.state.memory.InMemoryStore
import org.apache.mesos.SchedulerDriver
import org.rogach.scallop.ScallopConf
import org.scalatest.mock.MockitoSugar
import org.scalatest.{ BeforeAndAfter, BeforeAndAfterAll, FunSuiteLike, Matchers }

import scala.concurrent.Await
import scala.concurrent.duration._

class DeploymentManagerTest
    extends TestKit(ActorSystem("System"))
    with FunSuiteLike
    with Matchers
    with BeforeAndAfter
    with BeforeAndAfterAll
    with MockitoSugar
    with ImplicitSender {

  override protected def afterAll(): Unit = {
    super.afterAll()
    system.shutdown()
  }

  var driver: SchedulerDriver = _
  var eventBus: EventStream = _
  var taskQueue: LaunchQueue = _
  var config: MarathonConf = _
  var metrics: Metrics = _
  var taskTracker: TaskTracker = _
  var scheduler: SchedulerActions = _
  var appRepo: AppRepository = _
  var storage: StorageProvider = _
  var hcManager: HealthCheckManager = _

  before {
    driver = mock[SchedulerDriver]
    eventBus = mock[EventStream]
    taskQueue = mock[LaunchQueue]
    config = new ScallopConf(Seq("--master", "foo")) with MarathonConf
    config.afterInit()
    metrics = new Metrics(new MetricRegistry)
    taskTracker = new TaskTracker(new InMemoryStore, config, metrics)
    scheduler = mock[SchedulerActions]
    storage = mock[StorageProvider]
    appRepo = new AppRepository(
      new MarathonStore[AppDefinition](new InMemoryStore, metrics, () => AppDefinition(), prefix = "app:"),
      None,
      metrics
    )
    hcManager = mock[HealthCheckManager]
  }

  test("deploy") {
    val manager = TestActorRef[DeploymentManager](
      Props(classOf[DeploymentManager],
        appRepo, taskTracker, taskQueue, scheduler, storage, hcManager, eventBus)
    )

    val app = AppDefinition("app".toRootPath)

    val oldGroup = Group("/".toRootPath)
    val newGroup = Group("/".toRootPath, Set(app))
    val plan = DeploymentPlan(oldGroup, newGroup)

    manager ! PerformDeployment(driver, plan)

    awaitCond(
      manager.underlyingActor.runningDeployments.contains(plan.id),
      5.seconds
    )
  }

  test("StopActor") {
    val manager = TestActorRef[DeploymentManager](
      Props(classOf[DeploymentManager],
        appRepo, taskTracker, taskQueue, scheduler, storage, hcManager, eventBus)
    )
    val probe = TestProbe()

    probe.setAutoPilot(new AutoPilot {
      override def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
        case Cancel(_) =>
          system.stop(probe.ref)
          NoAutoPilot
      }
    })

    val ex = new Exception

    val res = manager.underlyingActor.stopActor(probe.ref, ex)

    Await.result(res, 5.seconds) should be(true)
  }

  test("Cancel deployment") {
    val manager = TestActorRef[DeploymentManager](
      Props(classOf[DeploymentManager],
        appRepo, taskTracker, taskQueue, scheduler, storage, hcManager, eventBus)
    )

    implicit val timeout = Timeout(1.minute)

    val app = AppDefinition("app".toRootPath)
    val oldGroup = Group("/".toRootPath)
    val newGroup = Group("/".toRootPath, Set(app))
    val plan = DeploymentPlan(oldGroup, newGroup)

    manager ! PerformDeployment(driver, plan)

    manager ! CancelDeployment(plan.id)

    expectMsgType[DeploymentFailed]
  }
}


text:
package org.staticscriptengine.typing;

import org.junit.Before;
import org.junit.Test;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

public abstract class AbstractScriptExecutorTest {
    private final String engineName;
    private final String scriptName;
    private ScriptExecutor scriptExecutor;

    public AbstractScriptExecutorTest(String engineName, String scriptName) {
        this.engineName = engineName;
        this.scriptName = scriptName;
    }

    @Before
    public void setUp() throws ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(engineName);
        InputStream scriptStream = getClass().getClassLoader().getResourceAsStream(scriptName);
        scriptEngine.eval(new InputStreamReader(scriptStream));
        scriptExecutor = new ScriptExecutor((Invocable) scriptEngine);
    }

    @Test
    public void shouldReturnABoolean() throws ScriptExecutorException {
        assertThat(scriptExecutor.returnBoolean()).isTrue();
    }

    @Test
    public void shouldReturnAString() throws ScriptExecutorException {
        assertThat(scriptExecutor.returnString()).isEqualTo("Hello World!");
    }

    @Test(expected = ScriptExecutorException.class)
    public void shouldThrowAnErrorWhenReturningABooleanAsString() throws ScriptExecutorException {
        scriptExecutor.returnBooleanAsString();
    }

    @Test(expected = ScriptExecutorException.class)
    public void shouldReturnVoidAString() throws ScriptExecutorException {
        scriptExecutor.returnVoidAsString();
    }

    @Test
    public void shouldReturnAStringArray() throws ScriptExecutorException {
        assertThat(scriptExecutor.returnStringArray()).containsExactly("a", "b");
    }

    @Test
    public void shouldReturnAnIntegerArray() throws ScriptExecutorException {
        assertThat(scriptExecutor.returnIntegerArray()).containsExactly(1, 2, 3);
    }

    @Test
    public void shouldReturnStringStringMap() throws ScriptExecutorException {
        assertThat(scriptExecutor.returnStringStringMap()).contains(entry("a", "b"), entry("c", "d"));
    }

    @Test
    public void shouldReturnStringBooleanMap() throws ScriptExecutorException {
        assertThat(scriptExecutor.returnStringBooleanMap()).contains(entry("a", true), entry("b", false));
    }
}


text:
package com.invariantproperties.project.student.util;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.invariantproperties.project.student.util.StudentUtil;

/**
 * Tests for student utilities.
 *
 * @author bgiles
 */
public class StudentUtilTest {

    @Test
    public void testValidUuid() {
        assertTrue(StudentUtil.isPossibleUuid("63c7d688-705c-4374-937c-6628952b41e1"));
    }

    @Test
    public void testInvalidUuid() {
        assertTrue(!StudentUtil.isPossibleUuid("63c7d68x-705c-4374-937c-6628952b41e1"));
        assertTrue(!StudentUtil.isPossibleUuid("63c7d68-8705c-4374-937c-6628952b41e1"));
        assertTrue(!StudentUtil.isPossibleUuid("63c7d688-705c4-374-937c-6628952b41e1"));
        assertTrue(!StudentUtil.isPossibleUuid("63c7d688-705c-43749-37c-6628952b41e1"));
        assertTrue(!StudentUtil.isPossibleUuid("63c7d688-705c-4374-937c6-628952b41e1"));
        assertTrue(!StudentUtil.isPossibleUuid("63c7d688-705c-4374-937c-6628952b41e1a"));
        assertTrue(!StudentUtil.isPossibleUuid("63c7d688-705c-4374-937c-6628952b41e"));
        assertTrue(!StudentUtil.isPossibleUuid(""));
        assertTrue(!StudentUtil.isPossibleUuid(null));
    }
}


text:
var Worker = {
  topic: 'all',
  puller: require('./redis').createClient(),
  publisher: require('./redis').createClient(),
  getQueueName: function(suffix) {
    var name = 'streamhttpd-queue-' + this.topic;
    if (suffix)
      name += suffix;
    return name;
  },
  getChannelName: function() {
    return 'streamhttpd-channel-' + this.topic;
  },
  work: function(cb) {
    this.puller.brpoplpush(this.getQueueName(), this.getQueueName('-pending'), 0, function(err, data) {
      var req = JSON.parse(data);
      var onRes = function(body) {
        var res = {id: req.id, body: body};
        this.publisher.publish(this.getChannelName(), JSON.stringify(res));
        this.puller.lrem(this.getQueueName('-pending'), 0, data, (function(err, n) {
          if (err)
            return cb(err);
          return this.work(cb);
        }).bind(this));
      }.bind(Worker);
      return cb(err, req, onRes)
    });
  }
};

module.exports = Worker;


text:
'use strict';

var chai = require('chai');
var Net = require('net');
var Socks5Client = require('socks5-client');

/* jshint unused: false */
var should = chai.should();
var expect = chai.expect;
var sinon = require('sinon');
var fs = require('fs');

var bitcore = require('bitcore-lib-cash');
var _ = bitcore.deps._;
var P2P = require('../');
var Peer = P2P.Peer;
var EventEmitter = require('events').EventEmitter;
var Messages = P2P.Messages;
var messages = new Messages();
var Networks = bitcore.Networks;

describe('Peer', function() {

  describe('Integration test', function() {
    it('parses this stream of data from a connection', function(callback) {
      var peer = new Peer('');
      var stub = sinon.stub();
      var dataCallback;
      var connectCallback;
      var expected = {
        version: 1,
        verack: 1,
        inv: 18,
        addr: 4
      };
      var received = {
        version: 0,
        verack: 0,
        inv: 0,
        addr: 0
      };
      stub.on = function() {
        if (arguments[0] === 'data') {
          dataCallback = arguments[1];
        }
        if (arguments[0] === 'connect') {
          connectCallback = arguments[1];
        }
      };
      stub.write = function() {};
      stub.connect = function() {
        connectCallback();
      };
      peer._getSocket = function() {
        return stub;
      };
      peer.on('connect', function() {
        dataCallback(fs.readFileSync('./test/data/connection.log'));
      });
      var check = function(message) {
        received[message.command]++;
        if (_.isEqual(received, expected)) {
          callback();
        }
      };
      peer.on('version', check);
      peer.on('verack', check);
      peer.on('addr', check);
      peer.on('inv', check);
      peer.connect();
    });
  });

  it('create instance', function() {
    var peer = new Peer('localhost');
    peer.host.should.equal('localhost');
    peer.network.should.equal(Networks.livenet);
    peer.port.should.equal(Networks.livenet.port);
  });

  it('create instance setting a port', function() {
    var peer = new Peer({host: 'localhost', port: 8111});
    peer.host.should.equal('localhost');
    peer.network.should.equal(Networks.livenet);
    peer.port.should.equal(8111);
  });

  it('create instance setting a network', function() {
    var peer = new Peer({host: 'localhost', network: Networks.testnet});
    peer.host.should.equal('localhost');
    peer.network.should.equal(Networks.testnet);
    peer.port.should.equal(Networks.testnet.port);
  });

  it('create instance setting port and network', function() {
    var peer = new Peer({host: 'localhost', port: 8111, network: Networks.testnet});
    peer.host.should.equal('localhost');
    peer.network.should.equal(Networks.testnet);
    peer.port.should.equal(8111);
  });

  it('create instance without new', function() {
    var peer = Peer({host: 'localhost', port: 8111, network: Networks.testnet});
    peer.host.should.equal('localhost');
    peer.network.should.equal(Networks.testnet);
    peer.port.should.equal(8111);
  });

  it('set a proxy', function() {
    var peer, peer2, socket;

    peer = new Peer('localhost');
    expect(peer.proxy).to.be.undefined();
    socket = peer._getSocket();
    socket.should.be.instanceof(Net.Socket);

    peer2 = peer.setProxy('127.0.0.1', 9050);
    peer2.proxy.host.should.equal('127.0.0.1');
    peer2.proxy.port.should.equal(9050);
    socket = peer2._getSocket();
    socket.should.be.instanceof(Socks5Client);

    peer.should.equal(peer2);
  });

  it('send pong on ping', function(done) {
    var peer = new Peer({host: 'localhost'});
    var pingMessage = messages.Ping();
    peer.sendMessage = function(message) {
      message.command.should.equal('pong');
      message.nonce.should.equal(pingMessage.nonce);
      done();
    };
    peer.emit('ping', pingMessage);
  });

  it('relay error from socket', function(done) {
    var peer = new Peer({host: 'localhost'});
    var socket = new EventEmitter();
    socket.connect = sinon.spy();
    socket.destroy = sinon.spy();
    peer._getSocket = function() {
      return socket;
    };
    var error = new Error('error');
    peer.on('error', function(err) {
      err.should.equal(error);
      done();
    });
    peer.connect();
    peer.socket.emit('error', error);
  });

  it('will not disconnect twice on disconnect and error', function(done) {
    var peer = new Peer({host: 'localhost'});
    var socket = new EventEmitter();
    socket.connect = sinon.stub();
    socket.destroy = sinon.stub();
    peer._getSocket = function() {
      return socket;
    };
    peer.on('error', sinon.stub());
    peer.connect();
    var called = 0;
    peer.on('disconnect', function() {
      called++;
      called.should.not.be.above(1);
      done();
    });
    peer.disconnect();
    peer.socket.emit('error', new Error('fake error'));
  });

  it('disconnect with max buffer length', function(done) {
    var peer = new Peer({ host: 'localhost' });
    var socket = new EventEmitter();
    socket.connect = sinon.spy();
    peer._getSocket = function() {
      return socket;
    };
    var error;
    peer.on('error', function(err) {
      error = err;
    });
    peer.disconnect = function() {
      error.should.include({
        message: 'Data buffer exceeded MAX_RECEIVE_BUFFER, disconnecting.'
      });
      done();
    };
    peer.connect();
    var buffer = Buffer.allocUnsafe(Peer.MAX_RECEIVE_BUFFER + 1);
    peer.socket.emit('data', buffer);
  });

  it('emits an error on unknown messages', function(done) {
    var peer = new Peer({ host: 'localhost' });
    var socket = new EventEmitter();
    socket.connect = sinon.spy();
    peer._getSocket = function() {
      return socket;
    };
    var error;
    peer.on('error', function(err) {
      error = err;
    });
    peer.disconnect = function() {
      error.should.include({
        message: 'Unsupported message command: unknown'
      });
      done();
    };
    peer.connect();
    var buf = Buffer.from('e3e1f3e8756e6b6e6f776e0000000000000000005df6e0e2', 'hex');
    peer.socket.emit('data', buf);
  });

  it('should send version on version if not already sent', function(done) {
    var peer = new Peer({host:'localhost'});
    var commands = {};
    peer.sendMessage = function(message) {
      commands[message.command] = true;
      if (commands.verack && commands.version) {
        done();
      }
    };
    peer.socket = {};
    peer.emit('version', {
      version: 'version',
      subversion: 'subversion',
      startHeight: 'startHeight'
    });
  });

  it('should not send version on version if already sent', function(done) {
    var peer = new Peer({host:'localhost'});
    peer.versionSent = true;
    var commands = {};
    peer.sendMessage = function(message) {
      message.command.should.not.equal('version');
      done();
    };
    peer.socket = {};
    peer.emit('version', {
      version: 'version',
      subversion: 'subversion',
      startHeight: 'startHeight'
    });
  });

  it('relay set properly', function() {
    var peer = new Peer({host: 'localhost'});
    peer.relay.should.equal(true);
    var peer2 = new Peer({host: 'localhost', relay: false});
    peer2.relay.should.equal(false);
    var peer3 = new Peer({host: 'localhost', relay: true});
    peer3.relay.should.equal(true);
  });

  it('relay setting respected', function() {
    [true,false].forEach(function(relay) {
      var peer = new Peer({host: 'localhost', relay: relay});
      var peerSendMessageStub = sinon.stub(Peer.prototype, 'sendMessage', function(message) {
        message.relay.should.equal(relay);
      });
      peer._sendVersion();
      peerSendMessageStub.restore();
    });
  });

  it('version/subversion set properly', function() {
    var peer = new Peer({ host: 'localhost' });
    should.not.exist(peer.ownSubversion);
    should.not.exist(peer.ownVersion);
    var peer2 = new Peer({
      host: 'localhost',
      subversion: '/useragent:0.0.0/'
    });
    peer2.ownSubversion.should.equal('/useragent:0.0.0/');
    should.not.exist(peer.ownVersion);
    var peer3 = new Peer({ host: 'localhost', version: 70012 });
    should.not.exist(peer.ownSubversion);
    peer3.ownVersion.should.equal(70012);
    var peer4 = new Peer({
      host: 'localhost',
      subversion: '/useragent:0.0.0/',
      version: 70012
    });
    peer4.ownSubversion.should.equal('/useragent:0.0.0/');
    peer4.ownVersion.should.equal(70012);
  });

  it('version/subversion settings respected', function(done) {
  var socket = new EventEmitter();
    var peer = new Peer({
      socket: socket,
      subversion: '/useragent:0.0.0/',
      version: 70012
    });
    peer.sendMessage = function(message) {
      message.version.should.equal(70012);
      message.subversion.should.equal('/useragent:0.0.0/');
      peer.disconnect();
    };
    peer.on('disconnect', () => {
      done();
    });
    peer.connect();
  });
});