text:
using Audit.Core;
using Audit.NET.RavenDB.Providers;
using Moq;
using Newtonsoft.Json.Serialization;
using NUnit.Framework;
using Raven.Client.Documents;
using Raven.Client.Json.Serialization.NewtonsoftJson;
#if IS_TEXT_JSON
using Audit.JsonNewtonsoftAdapter;
#endif

namespace Audit.RavenDB.UnitTest
{
    [TestFixture]
    [Category("Integration")]
    [Category("RavenDB")]
    public class RavenDbDataProviderConfigurationTests
    {
        private const string ravenServerUrl = "http://localhost:8080";

        [Test]
        public void Test_RavenDbDataProvider_DocStore_FluentApi()
        {
            var testUrl = "http://test";
            var ds = new Mock<IDocumentStore>();
            ds.Setup(p => p.Urls).Returns(new[] { testUrl });

            var provider1 = new RavenDbDataProvider(_ => _
                .UseDocumentStore(ds.Object));
            var provider2 = new RavenDbDataProvider(_ => _
                .UseDocumentStore(ds.Object));

            Assert.IsNotNull(provider1.DocumentStore);
            Assert.IsNotNull(provider2.DocumentStore);
            Assert.AreEqual(testUrl, provider1.DocumentStore?.Urls[0]);
        }

        [Test]
        public void Test_RavenDbDataProvider_Settings_FluentApi()
        {
            var dbName = "test";

            var provider = new RavenDbDataProvider(_ => _
                .WithSettings(store => store
                    .DatabaseDefault("defaultDb")
                    .Certificate(null)
                    .Urls(ravenServerUrl)
                    .Database(_ => dbName)));

            Assert.IsNotNull(provider.DocumentStore);

            Assert.AreEqual(ravenServerUrl, provider.DocumentStore?.Urls[0]);
            Assert.AreEqual("defaultDb", provider.DocumentStore?.Database);
            Assert.AreEqual(dbName, provider.GetDatabaseName(null));
            Assert.AreEqual(null, provider.DocumentStore.Certificate);
        }

        [Test]
        public void Test_RavenDbDataProvider_Settings_NoSerialization_FluentApi()
        {
            var dbName = "test";

            var provider = new RavenDbDataProvider(_ => _
                .WithSettings(store => store
                    .DatabaseDefault("defaultDb")
                    .Urls(ravenServerUrl)
                    .Database(_ => dbName)));

            Assert.IsNotNull(provider.DocumentStore);

            Assert.AreEqual(ravenServerUrl, provider.DocumentStore?.Urls[0]);
            Assert.AreEqual("defaultDb", provider.DocumentStore?.Database);
            Assert.AreEqual(dbName, provider.GetDatabaseName(null));
            Assert.AreEqual(null, provider.DocumentStore.Certificate);
#if IS_TEXT_JSON
            Assert.IsInstanceOf<AuditContractResolver>((provider.DocumentStore.Conventions.Serialization as NewtonsoftJsonSerializationConventions)?.JsonContractResolver);
#else
            Assert.IsInstanceOf<DefaultContractResolver>((provider.DocumentStore.Conventions.Serialization as NewtonsoftJsonSerializationConventions)?.JsonContractResolver);
#endif
        }
    }
}


text:
<?php

/**
 * Load Methods parent
 */
require_once('PBAPI/Methods.php');

/**
 * Base API methods
 *
 * @package PBAPI
 * @subpackage Methods
 */
class PBAPI_Methods_base extends PBAPI_Methods {

    /**
     * Ping
     *
     * @param array $params (anything)
     */
    public function ping($params = null) {
        if (!empty($params)) $this->core->_setParamList($params);
        $this->core->_setUri('/ping');
    }

    /**
     * Search
     *
     * @param string $term [optional, default=''] search term, '' for recent
     * @param array $params array(...)
     */
    public function search($term = '', $params = null) {
        if (is_array($term) && $params == null) {
            $params = $term;
            $term = '';
        }
        $this->core->_setUri('/search/%s', $term);
        if (count($params)) $this->core->_setParamList($params);
    }

    /**
     * Featured Media
     *
     */
    public function featured() {
        $this->core->_setUri('/featured');
    }

    /**
     * User
     *
     * @param string $username [optional, default=current user token] username
     * @param array $params array(...)
     */
    public function user($username = '', $params = null) {
        if (is_array($username) && $params == null) {
            $params = $username;
            $username = '';
        }
        $this->core->_setUri('/user/%s', $username);
        $this->core->_setParamList($params);

        $this->_load('user');
    }

    /**
     * Album
     *
     * @param string $albumpath album path (username/location)
     * @param array $params array(...)
     */
    public function album($albumpath, $params = null) {
        if (!$albumpath) throw new PBAPI_Exception('albumpath required', $this->core);

        $this->core->_setUri('/album/%s', $albumpath);
        $this->core->_setParamList($params);

        $this->_load('album');
    }

    /**
     * GroupAlbum
     *
     * @param string $grouppath groupalbum path (grouphash/location)
     * @param array $params array(...)
     */
    public function group($grouppath, $params = null) {
        if (!$grouppath) throw new PBAPI_Exception('grouppath required', $this->core);

        $this->core->_setUri('/group/%s', $grouppath);
        $this->core->_setParamList($params);

        $this->_load('group');
    }

    /**
     * Media
     *
     * @param string $mediaurl media url (http://i384.photobucket.com/albums/v000/username/location/filename.gif)
     * @param array $params array(...)
     */
    public function media($mediaurl, $params = null) {
        if (!$mediaurl) throw new PBAPI_Exception('mediaurl required', $this->core);

        $this->core->_setUri('/media/%s', $mediaurl);
        $this->core->_setParamList($params);

        $this->_load('media');
    }

    /**
     * Login
     *
     * @param string $step [request|access] step of web login/auth process
     * @param array $params array(...)
     */
    public function login($step, $params = null) {
        if (!$step) throw new PBAPI_Exception('step required', $this->core);

        $this->core->_setUri('/login/%s', $step);
        $this->core->_setParamList($params);
    }

    /**
     * get accessor tokens
     *
     * @param array $params array(...)
     */
    public function accessor($params = null) {
        $this->core->_setUri('/accessor');
        $this->core->_setParamList($params);
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*!
 * @file
 * This file defines the `d2::standard_thread` class.
 */

#ifndef D2_STANDARD_THREAD_HPP
#define D2_STANDARD_THREAD_HPP

#include <d2/access.hpp>
#include <d2/core/thread_id.hpp>
#include <d2/trackable_thread.hpp>

#include <boost/config.hpp>
#include <boost/move/move.hpp>
#include <boost/utility/swap.hpp>

namespace d2 {
/*!
 * Wrapper over a standard conformant thread class to add tracking of the
 * thread's lifetime.
 *
 * @warning If the wrapped thread is not standard conformant, the behavior is
 *          undefined.
 */
template <typename Thread>
class standard_thread : private trackable_thread, public Thread {
    BOOST_MOVABLE_BUT_NOT_COPYABLE(standard_thread)
    using trackable_thread::get_thread_function;

public:
    standard_thread() BOOST_NOEXCEPT { }

#ifndef BOOST_NO_CXX11_VARIADIC_TEMPLATES
    template <typename F, typename ...Args>
    explicit standard_thread(BOOST_FWD_REF(F) f,
                             BOOST_FWD_REF(Args) ...args)
        : Thread(get_thread_function(boost::forward<F>(f)),
                                     boost::forward<Args>(args)...)
    { }
#else
    template <typename F>
    explicit standard_thread(BOOST_FWD_REF(F) f)
        : Thread(get_thread_function(boost::forward<F>(f)))
    { }

    template <typename F, typename A0>
    standard_thread(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0)
        : Thread(get_thread_function(boost::forward<F>(f)),
                                     boost::forward<A0>(a0))
    { }

    template <typename F, typename A0, typename A1>
    standard_thread(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0,
                                        BOOST_FWD_REF(A1) a1)
        : Thread(get_thread_function(boost::forward<F>(f)),
                                     boost::forward<A0>(a0),
                                     boost::forward<A1>(a1))
    { }

    template <typename F, typename A0, typename A1, typename A2>
    standard_thread(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0,
                                        BOOST_FWD_REF(A1) a1,
                                        BOOST_FWD_REF(A2) a2)
        : Thread(get_thread_function(boost::forward<F>(f)),
                                     boost::forward<A0>(a0),
                                     boost::forward<A1>(a1),
                                     boost::forward<A2>(a2))
    { }

    template <typename F, typename A0, typename A1, typename A2, typename A3>
    standard_thread(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0,
                                        BOOST_FWD_REF(A1) a1,
                                        BOOST_FWD_REF(A2) a2,
                                        BOOST_FWD_REF(A3) a3)
        : Thread(get_thread_function(boost::forward<F>(f)),
                                     boost::forward<A0>(a0),
                                     boost::forward<A1>(a1),
                                     boost::forward<A2>(a2),
                                     boost::forward<A3>(a3))
    { }
#endif // !BOOST_NO_CXX11_VARIADIC_TEMPLATES

    standard_thread(BOOST_RV_REF(standard_thread) other) BOOST_NOEXCEPT
        : trackable_thread(
            boost::move(static_cast<trackable_thread&>(other))),
          Thread(boost::move(static_cast<Thread&>(other)))
    { }

    standard_thread&
    operator=(BOOST_RV_REF(standard_thread) other) BOOST_NOEXCEPT {
        trackable_thread::operator=(
            boost::move(static_cast<trackable_thread&>(other)));
        Thread::operator=(boost::move(static_cast<Thread&>(other)));
        return *this;
    }

    void swap(standard_thread& other) BOOST_NOEXCEPT {
        boost::swap(static_cast<trackable_thread&>(*this),
                    static_cast<trackable_thread&>(other));
        boost::swap(static_cast<Thread&>(*this), static_cast<Thread&>(other));
    }

    friend void swap(standard_thread& x, standard_thread& y) BOOST_NOEXCEPT {
        x.swap(y);
    }

    void join() {
        Thread::join();
        this->notify_join();
    }

    void detach() {
        Thread::detach();
        this->notify_detach();
    }
};

/*!
 * Mixin augmenting its derived class with `d2` tractability.
 *
 * By implementing `join_impl()` and `detach_impl()` methods, the derived
 * class automatically gets augmented with `join()` and `detach()` methods
 * notifying `d2` after forwarding to the `*_impl()` implementation.
 *
 * When a new thread is created, the function executed in the new thread must
 * also be wrapped by calling `standard_thread_mixin::get_thread_function()`.
 *
 * Intended usage of this class goes as follow:
 * @code
 *
 *  class my_thread : public d2::standard_thread_mixin<my_thread> {
 *      friend class d2::access;
 *
 *      void join_impl() {
 *          // ...
 *      }
 *
 *      void detach_impl() {
 *          // ...
 *      }
 *
 *  public:
 *      template <typename Function, typename ...Args>
 *      explicit my_thread(Function&& f, Args&& ...args) {
 *          typedef d2::thread_function<Function> Function_;
 *          Function_ f_ = this->get_thread_function(
 *                                              boost::forward<Function>(f));
 *          // start the thread with Function_ and f_ normally
 *      }
 *
 *      my_thread(my_thread&& other)
 *          : standard_thread_mixin_(
 *              boost::move(static_cast<standard_thread_mixin_&>(other)))
 *      { }
 *
 *      my_thread& operator=(my_thread&& other) {
 *          standard_thread_mixin_::operator=(boost::move(other));
 *          // ...
 *      }
 *  };
 *
 * @endcode
 */
template <typename Derived>
class standard_thread_mixin : private trackable_thread {
    BOOST_MOVABLE_BUT_NOT_COPYABLE(standard_thread_mixin)

protected:
    using trackable_thread::get_thread_function;
    typedef standard_thread_mixin standard_thread_mixin_;

public:
    standard_thread_mixin() BOOST_NOEXCEPT { }

    standard_thread_mixin(BOOST_RV_REF(standard_thread_mixin) other)
                                                                BOOST_NOEXCEPT
        : trackable_thread(
            boost::move(static_cast<trackable_thread&>(other)))
    { }

    standard_thread_mixin&
    operator=(BOOST_RV_REF(standard_thread_mixin) other) BOOST_NOEXCEPT {
        trackable_thread::operator=(
            boost::move(static_cast<trackable_thread&>(other)));
        return *this;
    }

    void swap(standard_thread_mixin& other) BOOST_NOEXCEPT {
        boost::swap(static_cast<trackable_thread&>(*this),
                    static_cast<trackable_thread&>(other));
    }

    friend void
    swap(standard_thread_mixin& x, standard_thread_mixin& y) BOOST_NOEXCEPT {
        x.swap(y);
    }

    void join() {
        access::join_impl(static_cast<Derived&>(*this));
        this->notify_join();
    }

    void detach() {
        access::detach_impl(static_cast<Derived&>(*this));
        this->notify_detach();
    }
};
} // end namespace d2

#endif // !D2_STANDARD_THREAD_HPP


text:
namespace Parrot.Nancy
{
    using System.Collections.Generic;
    using Parrot.Renderers.Infrastructure;
    using global::Nancy.Bootstrapper;
    using global::Nancy.ViewEngines;

    /// <summary>
    /// Register the dependencies with Nancy
    /// </summary>
    public class ParrotRegistrations : IApplicationRegistrations
    {
        public IEnumerable<TypeRegistration> TypeRegistrations
        {
            get
            {
                yield return new TypeRegistration(typeof(IRendererFactory), typeof(DefaultRendererFactory));
                yield return new TypeRegistration(typeof(IViewEngine), typeof(ParrotViewEngine));
            }
        }
        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { return null; } }
        public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } }
    }
}


text:
<?php
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace Commercetools\Core\Model\ProductDiscount;

use Commercetools\Core\Model\Common\DiscountValue;
use Commercetools\Core\Model\Common\MoneyCollection;

/**
 * @package Commercetools\Core\Model\ProductDiscount
 * @ramlTestIgnoreFields('permyriad', 'money')
 * @link https://docs.commercetools.com/http-api-projects-productDiscounts.html#productdiscountvalue
 * @method string getType()
 * @method ProductDiscountValue setType(string $type = null)
 * @method int getPermyriad()
 * @method ProductDiscountValue setPermyriad(int $permyriad = null)
 * @method MoneyCollection getMoney()
 * @method ProductDiscountValue setMoney(MoneyCollection $money = null)
 */
class ProductDiscountValue extends DiscountValue
{
}


text:
class RecordInfo;

class Edge;
class Value;
class RawPtr;
class RefPtr;
class OwnPtr;
class Member;
class WeakMember;
class Persistent;
class Collection;

// Bare-bones visitor.
class EdgeVisitor {
 public:
  virtual void VisitValue(Value*) {}
  virtual void VisitRawPtr(RawPtr*) {}
  virtual void VisitRefPtr(RefPtr*) {}
  virtual void VisitOwnPtr(OwnPtr*) {}
  virtual void VisitMember(Member*) {}
  virtual void VisitWeakMember(WeakMember*) {}
  virtual void VisitPersistent(Persistent*) {}
  virtual void VisitCollection(Collection*) {}
};

// Recursive edge visitor. The traversed path is accessible in context.
class RecursiveEdgeVisitor : public EdgeVisitor {
 public:
  // Overrides that recursively walk the edges and record the path.
  virtual void VisitValue(Value*) override;
  virtual void VisitRawPtr(RawPtr*) override;
  virtual void VisitRefPtr(RefPtr*) override;
  virtual void VisitOwnPtr(OwnPtr*) override;
  virtual void VisitMember(Member*) override;
  virtual void VisitWeakMember(WeakMember*) override;
  virtual void VisitPersistent(Persistent*) override;
  virtual void VisitCollection(Collection*) override;

 protected:
  typedef std::deque<Edge*> Context;
  Context& context() { return context_; }
  Edge* Parent() { return context_.empty() ? 0 : context_.front(); }
  void Enter(Edge* e) { return context_.push_front(e); }
  void Leave() { context_.pop_front(); }

  // Default callback to overwrite in visitor subclass.
  virtual void AtValue(Value*);
  virtual void AtRawPtr(RawPtr*);
  virtual void AtRefPtr(RefPtr*);
  virtual void AtOwnPtr(OwnPtr*);
  virtual void AtMember(Member*);
  virtual void AtWeakMember(WeakMember*);
  virtual void AtPersistent(Persistent*);
  virtual void AtCollection(Collection*);

 private:
  Context context_;
};

// Base class for all edges.
class Edge {
 public:
  enum NeedsTracingOption { kRecursive, kNonRecursive };
  enum LivenessKind { kWeak, kStrong, kRoot };

  virtual ~Edge() {}
  virtual LivenessKind Kind() = 0;
  virtual void Accept(EdgeVisitor*) = 0;
  virtual bool NeedsFinalization() = 0;
  virtual TracingStatus NeedsTracing(NeedsTracingOption) {
    return TracingStatus::Unknown();
  }

  virtual bool IsValue() { return false; }
  virtual bool IsRawPtr() { return false; }
  virtual bool IsRawPtrClass() { return false; }
  virtual bool IsRefPtr() { return false; }
  virtual bool IsOwnPtr() { return false; }
  virtual bool IsMember() { return false; }
  virtual bool IsWeakMember() { return false; }
  virtual bool IsPersistent() { return false; }
  virtual bool IsCollection() { return false; }
};

// A value edge is a direct edge to some type, eg, part-object edges.
class Value : public Edge {
 public:
  explicit Value(RecordInfo* value) : value_(value) {};
  bool IsValue() override { return true; }
  LivenessKind Kind() override { return kStrong; }
  bool NeedsFinalization() override;
  TracingStatus NeedsTracing(NeedsTracingOption) override;
  void Accept(EdgeVisitor* visitor) override { visitor->VisitValue(this); }
  RecordInfo* value() { return value_; }

 private:
  RecordInfo* value_;
};

// Shared base for smart-pointer edges.
class PtrEdge : public Edge {
 public:
  ~PtrEdge() { delete ptr_; }
  Edge* ptr() { return ptr_; }
 protected:
  PtrEdge(Edge* ptr) : ptr_(ptr) {
    assert(ptr && "EdgePtr pointer must be non-null");
  }
 private:
  Edge* ptr_;
};

class RawPtr : public PtrEdge {
 public:
  explicit RawPtr(Edge* ptr, bool is_ptr_class)
      : PtrEdge(ptr), is_ptr_class_(is_ptr_class) { }
  bool IsRawPtr() { return true; }
  bool IsRawPtrClass() { return is_ptr_class_; }
  LivenessKind Kind() { return kWeak; }
  bool NeedsFinalization() { return false; }
  TracingStatus NeedsTracing(NeedsTracingOption) {
    return TracingStatus::Unneeded();
  }
  void Accept(EdgeVisitor* visitor) { visitor->VisitRawPtr(this); }
 private:
  bool is_ptr_class_;
};

class RefPtr : public PtrEdge {
 public:
  explicit RefPtr(Edge* ptr) : PtrEdge(ptr) { }
  bool IsRefPtr() { return true; }
  LivenessKind Kind() { return kStrong; }
  bool NeedsFinalization() { return true; }
  TracingStatus NeedsTracing(NeedsTracingOption) {
    return TracingStatus::Unneeded();
  }
  void Accept(EdgeVisitor* visitor) { visitor->VisitRefPtr(this); }
};

class OwnPtr : public PtrEdge {
 public:
  explicit OwnPtr(Edge* ptr) : PtrEdge(ptr) { }
  bool IsOwnPtr() { return true; }
  LivenessKind Kind() { return kStrong; }
  bool NeedsFinalization() { return true; }
  TracingStatus NeedsTracing(NeedsTracingOption) {
    return TracingStatus::Unneeded();
  }
  void Accept(EdgeVisitor* visitor) { visitor->VisitOwnPtr(this); }
};

class Member : public PtrEdge {
 public:
  explicit Member(Edge* ptr) : PtrEdge(ptr) { }
  bool IsMember() { return true; }
  LivenessKind Kind() { return kStrong; }
  bool NeedsFinalization() { return false; }
  TracingStatus NeedsTracing(NeedsTracingOption) {
    return TracingStatus::Needed();
  }
  void Accept(EdgeVisitor* visitor) { visitor->VisitMember(this); }
};

class WeakMember : public PtrEdge {
 public:
  explicit WeakMember(Edge* ptr) : PtrEdge(ptr) { }
  bool IsWeakMember() { return true; }
  LivenessKind Kind() { return kWeak; }
  bool NeedsFinalization() { return false; }
  TracingStatus NeedsTracing(NeedsTracingOption) {
    return TracingStatus::Needed();
  }
  void Accept(EdgeVisitor* visitor) { visitor->VisitWeakMember(this); }
};

class Persistent : public PtrEdge {
 public:
  explicit Persistent(Edge* ptr) : PtrEdge(ptr) { }
  bool IsPersistent() { return true; }
  LivenessKind Kind() { return kRoot; }
  bool NeedsFinalization() { return true; }
  TracingStatus NeedsTracing(NeedsTracingOption) {
    return TracingStatus::Unneeded();
  }
  void Accept(EdgeVisitor* visitor) { visitor->VisitPersistent(this); }
};

class Collection : public Edge {
 public:
  typedef std::vector<Edge*> Members;
  Collection(RecordInfo* info, bool on_heap, bool is_root)
      : info_(info),
        on_heap_(on_heap),
        is_root_(is_root) {}
  ~Collection() {
    for (Members::iterator it = members_.begin(); it != members_.end(); ++it) {
      assert(*it && "Collection-edge members must be non-null");
      delete *it;
    }
  }
  bool IsCollection() { return true; }
  LivenessKind Kind() { return is_root_ ? kRoot : kStrong; }
  bool on_heap() { return on_heap_; }
  bool is_root() { return is_root_; }
  Members& members() { return members_; }
  void Accept(EdgeVisitor* visitor) { visitor->VisitCollection(this); }
  void AcceptMembers(EdgeVisitor* visitor) {
    for (Members::iterator it = members_.begin(); it != members_.end(); ++it)
      (*it)->Accept(visitor);
  }
  bool NeedsFinalization();
  TracingStatus NeedsTracing(NeedsTracingOption) {
    if (is_root_)
      return TracingStatus::Unneeded();
    if (on_heap_)
      return TracingStatus::Needed();
    // For off-heap collections, determine tracing status of members.
    TracingStatus status = TracingStatus::Unneeded();
    for (Members::iterator it = members_.begin(); it != members_.end(); ++it) {
      // Do a non-recursive test here since members could equal the holder.
      status = status.LUB((*it)->NeedsTracing(kNonRecursive));
    }
    return status;
  }

 private:
  RecordInfo* info_;
  Members members_;
  bool on_heap_;
  bool is_root_;
};

#endif  // TOOLS_BLINK_GC_PLUGIN_EDGE_H_


text:
$(document).ready(function() {
        // Initialize the tooltip.
        $('#copy-button').tooltip();

        // When the copy button is clicked, select the value of the text box, attempt
        // to execute the copy command, and trigger event to update tooltip message
        // to indicate whether the text was successfully copied.
        $('#copy-button').bind('click', function() {
          var input = document.querySelector('#copy-input');
          input.setSelectionRange(0, input.value.length + 1);
          try {
            var success = document.execCommand('copy');
            if (success) {
              $('#copy-button').trigger('copied', ['Copied!']);
            } else {
              $('#copy-button').trigger('copied', ['Copy with Ctrl-c']);
            }
          } catch (err) {
            $('#copy-button').trigger('copied', ['Copy with Ctrl-c']);
          }
        });

        // Handler for updating the tooltip message.
        $('#copy-button').bind('copied', function(event, message) {
          $(this).attr('title', message)
              .tooltip('fixTitle')
              .tooltip('show')
              .attr('title', "Copy to Clipboard")
              .tooltip('fixTitle');
        });
      });


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

	<!-- Configures all supporting beans -->
	<import resource="beans.xml" />

	<!-- Configures Spring 3 MVC -->
	<import resource="mvc.xml" />

</beans>


text:
# Create GraphQL Server

This is a simple scaffolding tool for GraphQL apps, built on MongoDB.

It consists of different commands:

```bash
create-graphql-server init project-dir
```

Create the basic skeleton of a GraphQL server project. If you `yarn install` inside `project-dir`, you should be able to `npm start` it, and then browse to http://localhost:3010/graphiql to start running queries.

There isn't anything to query yet however!

To add some types, simply run one of the following alternatives:

```bash
create-graphql-server add-type path/to/input.graphql
OR:
create-graphql-server add-type path
```

Where `path/to/input.graphql` is an input GraphQL schema (see below). Or:
Where `path` will add all `type.graphql` files in the given directory path recursively.

To see what a complete generated server looks like, see the `test/output-app` folder. It has been generated from the `test/input` schema inputs.

## Creating types

You create a GraphQL type for your schema by specifying the type as input, with some special code-generation controlling directives.

For example, in `User.graphql`:

```graphql
type User {
  email: String!
  bio: String

  tweets: [Tweet!] @hasMany(as: "author")
  liked: [Tweet!] @belongsToMany

  following: [User!] @belongsToMany
  followers: [User!] @hasAndBelongsToMany(as: "following")
}
```

The above will generate a User type which is linked to other users and a tweet type via foriegn keys and which will have mutations to add, update and remove users, as well as some root queries to find a single user or all users.

The directives used control the code generation (see below).

### Directives

- `@unmodifiable` - the field will not appear in the update mutation
- `@enum` - the field's type is an enum, and can be set directly (not just by `Id`).

### Relations

If types reference each other, you should use an association directive to explain to the generator how the reference should be stored in mongo:

#### Singleton fields

If the field references a single (nullable or otherwise) instance of another type, it will be either:

- `@belongsTo` - the foreign key is stored on this type as `${fieldName}Id` [this is the default]
- `@hasOne` - the foreign key is stored on the referenced type as `${typeName}Id`. Provide the `"as": X` argument if the name is different. [NOTE: this is not yet fully implemented].

#### Paginated fields

If the field references an array (again w/ or w/o nullability) of another type, it will be either:

- `@belongsToMany` - there is a list of foreign keys stored on this type as `${fieldName}Ids` [this is the default]
- `@hasMany` - the foreign key is on the referenced type as `${typeName}Id`. Provide the `"as": X` argument if the name is different. (this is the reverse of `@belongsTo` in a 1-many situation).
- `@hasAndBelongsToMany` - the foreign key on the referenced type as `${typeName}Ids`. Provide the `"as": X` argument if the name is different. (this is the reverse of `@belongsToMany` in a many-many situation).

## Updating types

To update types, just re-run add-type again:

```bash
create-graphql-server add-type path/to/input.graphql [--force-update]
```

This overwrites your old *type* specific files from the directories: schema, model, resolvers.

It recognizes, if you've changed any code file, which will be overwritten by the generator and stops and warns. If you are sure, you want to overwrite your changes, then just use the *--force-update* option.

## Removing types

To remove types, use the following command with the path to the GraphQL file, or as alternative, just enter the type name without path.

```bash
create-graphql-server remove-type path/to/input.graphql

create-graphql-server remove-type typename

create-graphql-server remove-type path
```

This command deletes your old *type* specific files from the directories: schema, model, resolvers. It also removes the code references out of the corresponding index files.

It recognizes, if you've changed any code file, which will be overwritten by the generator and stops and warns. If you are sure, you want to overwrite your changes, then just use the *force-update* option.

## Authentication

CGS sets up a basic passport-based JWT authentication system for your app.

**NOTE**: you should ensure users connect to your server through SSL.

To use it, ensure you have a GraphQL type called `User` in your schema, with a field `email`, by which users will be looked up. When creating users, ensure that a bcrypted `hash` database field is set. For instance, if you created your users in this way:

```graphql
type User {
  email: String!
  bio: String
}
```

The generator automatically adjusts your schema and code in the following way:
It adjusts the generated `CreateUserInput` input object to take a `password` field:

```graphql
input CreateUserInput {
  email: String!
  password: String! # <- you need to add this line to the generated output
  bio: String
}
```

And in updates the generated `User` model to hash that password and store it:

```js
import bcrypt from 'bcrypt';
// Set this as appropriate
const SALT_ROUNDS = 10;

class User {
  async insert(doc) {
    // We don't want to store passwords plaintext!
    const { password, ...rest } = doc;
    const hash = await bcrypt.hash(password, SALT_ROUNDS);
    const docToInsert = Object.assign({}, rest, {
      hash,
      createdAt: Date.now(),
      updatedAt: Date.now(),
    });

    // This code is unchanged.
    const id = (await this.collection.insertOne(docToInsert)).insertedId;
    this.pubsub.publish('userInserted', await this.findOneById(id));
    return id;
  }
}
```

So the "User" type is treated differently as any other default type.

## Authorization

create-graphql-server can also handle authorizations. There are two ways to control authorizations:
* Authorization by User-Roles
* Authorization by Document-Roles

**User-Roles** are stored in the User type. They group a number of users together, having all the same authorizations, defined with their role they play. Use it to define a user as a "super-administrator", "administrator", "publisher", "editor" or a "default-user". You are free to define your own names and numbers of User-Roles.

**Document-Roles** are stored in document fields which are referencing a User._id. They are there, to define fine grained authorizations for individual documents based on single user level. Use it to define an "owner", "creator", author" or "coauthor" of a document. Define the authorization they are allowed to do with this specific document. Here, the userId will be stored in the corresponding document field instead. If a user wants the specific authorization, it is tested, if this userId is stored in the document, if so, he gains access, if not, it is not allowed.

You can combine both models to define your authorization logic.

Add authorization logic by using a simple @authorize directive within your type definition. Use the following syntax:
```javascript
type ...
@authorize(
  <role1>: [<list of authorizations>]
  <role2>: [<list of authorizations>]
  <role3>: [<list of authorizations>]
)
...
<fieldname1>: String @authRole("<role1>")   // User-Role: Stores the Role name in the User type
<fieldname2>: User @authRole("<role2>")     // Document-Role: Stores Single UserId
<fieldname3>: [User] @authRole("<role3>")   // Document-Role: Stores Multiple UserIds
...
```

A \<role\> can be any name, you want to use for, to describe the authorizations of a group of users. A user can be assigned this \<role\> in a user type of any \<fieldname\>. You have to mark the relevant field name with the directive @authRole("\<role\>").

A list of authorizations can be:
* create: role is authorized to create a record of this type.
* read: role is authorized to readOne and readMany of this type.
	* readOne: role is authorized to only readOne of this type.
	* readMany: role is authorized to readMany of this type.
* update: role is authorized to update a record of this type.
* delete: role is authorized to delete a record of this type.

You can add any number of roles within a @authorize directive.

There is one pre-defined User-Role called "world". The world role includes all users, signed-in and not signed-in anonymous users. Use this role to define an authorization-list valid for all users.

#### Example on type User
```javascript
type User

@authorize(
  admin: ["create", "read", "update", "delete"]  // User-Role
  this: ["read", "update", "delete"]             // Document-Role
)

{
  role: String @authRole("admin")
  username: String!

  bio: String
  notify: Boolean

  tweets(minLikes: Int): [Tweet!] @hasMany(as: "author")
  liked: [Tweet!] @belongsToMany

  following: [User!] @belongsToMany
  followers: [User!] @hasAndBelongsToMany(as: "following")
}
```

#### Example on type Tweet

```javascript
type Tweet

@authorize(
  admin: ["create", "read", "update", "delete"],   // User-Role
  world: ["read"]                                  // User-Role
  author: ["create", "read", "update", "delete"],  // Document-Role
  coauthors: ["read", "update"],                   // Document-Role
)

{
  author: User! @unmodifiable @belongsTo @authRole("author")
  coauthors: [User] @belongsTo @authRole("coauthors")
  body: String!

  likers: [User!] @hasAndBelongsToMany(as: "liked")
}
```

If you add these types with the create-graphql-server command-line-interface:
```bash
create-graphql-server add-type path/to/input.graphql
```

It will add automatically the authorization code in the model/\<type\>.js files. Have a look into the generated code or in the test application: "test/output-app/model/User.js".

You can manually change the code to protect also single fields of a type. Do it by the usage of this function:
```javascript
//                              userRole secretField document
docToInsert = protectFields(me, ['admin'], ['role'], docToInsert, { User: this.context.User });
```
By this, only a User (me) with role "admin" is allowed to access the field "docToInsert.role". For any other user, this field is removed from the docToInsert during the protectFields run.

## Example Implementation
[Please have a look at the example implementation.](https://github.com/tmeasday/create-graphql-server/tree/master/test/output-app)

## Client side code

To create users, simply call your generated `createUser` mutation (you may want to add authorization to the resolver, feel free to modify it).

To login on the client, you make a RESTful request to `/login` on the server, passing `email` and `password` in JSON. You'll get a JWT token back, which you should attach to the `Authorization` header of all GraphQL requests.

Here's some code to do just that:

```js
const KEY = 'authToken';
let token = localStorage.getItem(KEY);

const networkInterface = createNetworkInterface(/* as usual */);
networkInterface.use([
  {
    applyMiddleware(req, next) {
      req.options.headers = {
        authorization: token ? `JWT ${token}` : null,
        ...req.options.headers,
      };
      next();
    },
  },
]);

// Create your client as usual and pass to a provider
const client = /*...*/

// Call this function from your login form, or wherever.
const login = async function(serverUrl, email, password) {
  const response = await fetch(`${serverUrl}/login`, {
    method: 'POST',
    body: JSON.stringify({ email, password }),
    headers: { 'Content-Type': 'application/json' },
  });
  const data = await response.json();
  token = data.token;
  localStorage.setItem(KEY, token);
}
```

## Development

### Running code generation tests

You can run some basic code generation tests with `npm test`.

### Testing full app code generation

A simple test to check that using the `test/input` input files with the CGS scripts generates `test/output-app` can be run with `npm run output-app-generation-test`.

### Running end-to-end tests

You can run a set of end-to-end tests of the user/tweet app (which lives in `test/output-app`) with `npm run end-to-end-test`. This will seed the database, and run against a running server.

The test files are in `test/output-app-end-to-end`.

You need to start the standard server with `cd test/output-app; npm start`, then run `npm run end-to-end-test`.

### Creating seed database

If you need to change the fixtures for the test db

Start the server, then run
```bash
mongoexport --host 127.0.0.1:3002 --db database --collection user > seeds/User.json
mongoexport --host 127.0.0.1:3002 --db database --collection tweet > seeds/Tweet.json
```

## Maintenance

As this is a code generator, and not a library, once you run the code, you are on your own :)

By which I mean, you should feel free to read the generated code, understand it, and modify it as you see fit. Any updates to CGS will just affect future apps that you generate.

If you'd like to see improvements, or find any bugs, by all means report them via the issues, and send PRs. But workarounds should be always be possible simply by patching the generated code.


text:
    <link rel="stylesheet" type="text/css" href="style/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="style/style.css"/>

    {{currentTime | date:'HH:mm - dd/MM/yyyy' }}

                {{user.display_name}}

            <form class="form-inline" role="form" ng-submit="provideSecret()" >
                <input type="password" class="form-control" id="password_entry" placeholder="Password"
                       ng-model="password" focus-on="focusPassword"/>

                    <button type="button" class="btn btn-success dropdown-toggle" ng-disabled="disabled">
                        {{chosenSession.name}}
                    </button>

{{session.name}}

            </form>

        <alert class="animate-repeat" ng-repeat="alert in alerts" type="{{alert.type}}" >{{alert.text}}</alert>


text:
package com.example.placeautocomplete;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

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

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class DistanceApi extends AsyncTask<String, Integer, ArrayList<String>> {

	/*https://maps.googleapis.com/maps/api/directions/json?origin=chennai&destination=madurai&sensor=false
*/
	private static final String LOG_TAG = "DistanceAPI";
	private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/directions";
	private static final String OUT_JSON = "/json";
	private static final String ORIGIN = "?origin=";
	private static final String DESTINATION = "&destination=";
	private static final String SENSOR = "&sensor=false";
	private ArrayList<String> result;
	private HttpURLConnection conn;
	private StringBuilder jsonResults;
	private TextView durationText,distanceText;

	public DistanceApi(Context context) {
		distanceText = (TextView)((PlaceActivity)context).findViewById(R.id.distance);
		durationText = (TextView)((PlaceActivity)context).findViewById(R.id.duration);
	}

	@Override
	protected void onPreExecute() {
		result = new ArrayList<String>();
		conn = null;
		jsonResults = new StringBuilder();
	}

	@Override
	protected ArrayList<String> doInBackground(String... inputs) {

		try {
			StringBuilder sb = new StringBuilder(PLACES_API_BASE + OUT_JSON);
			sb.append(ORIGIN + URLEncoder.encode(inputs[0], "utf8"));
			sb.append(DESTINATION + URLEncoder.encode(inputs[1], "utf8"));
			sb.append(SENSOR);

			URL url = new URL(sb.toString());
			conn = (HttpURLConnection) url.openConnection();
			InputStreamReader in = new InputStreamReader(conn.getInputStream());

			// Load the results into a StringBuilder
			int read;
			char[] buff = new char[1024];
			while ((read = in.read(buff)) != -1) {
				jsonResults.append(buff, 0, read);
			}
		} catch (MalformedURLException e) {
			Log.e(LOG_TAG, "Error processing Places API URL", e);
			return result;
		} catch (IOException e) {
			Log.e(LOG_TAG, "Error connecting to Places API", e);
			return result;
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}

		try {
			// Create a JSON object hierarchy from the results
			JSONObject jsonObj = new JSONObject(jsonResults.toString());
			/*Log.d("JSON", jsonResults.toString());*/
			JSONArray routesJsonArray = jsonObj.getJSONArray("routes");
			JSONArray legsJsonArray = routesJsonArray.getJSONObject(0).getJSONArray("legs");
			// Extract the Place descriptions from the results

				// store Killometer in Distance
				JSONObject path = legsJsonArray.getJSONObject(0);
				JSONObject distance =  path.getJSONObject("distance");
				JSONObject duration =  path.getJSONObject("duration");
				result.add(distance.getString("text"));
				result.add(duration.getString("text"));

		} catch (JSONException e) {
			Log.e(LOG_TAG, "Cannot process JSON results", e);
		}

		return result;
	}

	@Override
	protected void onPostExecute(ArrayList<String> distance) {
		for (String string : distance) {
			Log.d("DISTANCE API OUTPUT",string);
		}
		distanceText.setText(distance.get(0));
		durationText.setText(distance.get(1));

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Policy
      xmlns="urn:oasis:names:tc:xacml:1.0:policy"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:oasis:names:tc:xacml:1.0:policy
        cs-xacml-schema-policy-01.xsd"
      PolicyId="urn:oasis:names:tc:xacml:1.0:conformance-test:IIC090:policy"
      RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides">
    <Description>
        Policy for Conformance Test IIC090.
    </Description>
    <Target>
        <Subjects>
            <AnySubject/>
        </Subjects>
        <Resources>
            <AnyResource/>
        </Resources>
        <Actions>
            <AnyAction/>
        </Actions>
    </Target>
    <Rule
          RuleId="urn:oasis:names:tc:xacml:1.0:conformance-test:IIC090:rule"
          Effect="Permit">
        <Description>
            A subject who is from Medico Corp or is at least 40 years old
            Simpson may read Bart Simpson's medical record.
        </Description>
        <Condition FunctionId="urn:oasis:names:tc:xacml:1.0:function:or">
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:rfc822Name-match">
                <AttributeValue
                      DataType="http://www.w3.org/2001/XMLSchema#string">medico.com</AttributeValue>
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:rfc822Name-one-and-only">
                    <SubjectAttributeDesignator
                          AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id"
                          DataType="urn:oasis:names:tc:xacml:1.0:data-type:rfc822Name"/>
                </Apply>
            </Apply>
            <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-greater-than-or-equal">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only">
                    <SubjectAttributeDesignator
                          AttributeId="urn:oasis:names:tc:xacml:1.0:conformance-test:age"
                          DataType="http://www.w3.org/2001/XMLSchema#integer"/>
                </Apply>
                <AttributeValue
                      DataType="http://www.w3.org/2001/XMLSchema#integer">40</AttributeValue>
            </Apply>
        </Condition>
    </Rule>
</Policy>


text:
package org.apache.commons.math3;

import java.lang.annotation.*;

/**
 * Annotation that enables test retries.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Retry {
    int value() default 2;
}


text:
Extension class for lazymofo/datagrid - adds bootstrap classes and additional input controls

Requires the following project: https://github.com/lazymofo/datagrid

Currently using the 2015 October 09 Update of the above project which can be found at the following fork: https://github.com/ais-one/datagrid

This project adds a file lmx.php that contains extensions to include bootstrap layout and additional for controls. Just include this file in the same directory as lazy_mofo.php and include the necessary resource files such as:
 * bootstrap
 * webcamjs
 * signature-pad
 * etc.


text:
#include "ignite/odbc/utility.h"
#include "ignite/odbc/system/odbc_constants.h"

#include "ignite/odbc/dsn_config.h"
#include "ignite/odbc/system/ui/window.h"
#include "ignite/odbc/system/ui/dsn_configuration_window.h"

using ignite::odbc::config::Configuration;

/**
 * Display configuration window for user to configure DSN.
 *
 * @param hwndParent Parent window handle.
 * @param config Output configuration.
 * @return True on success and false on fail.
 */
bool DisplayConfigureDsnWindow(HWND hwndParent, Configuration& config)
{
    using namespace ignite::odbc::system::ui;

    if (!hwndParent)
        return false;

    try
    {
        Window parent(hwndParent);

        DsnConfigurationWindow window(&parent, config);

        window.Create();

        window.Show();
        window.Update();

        return ProcessMessages(window) == RESULT_OK;
    }
    catch (const ignite::IgniteError& err)
    {
        std::stringstream buf;

        buf << "Message: " << err.GetText() << ", Code: " << err.GetCode();

        std::string message = buf.str();

        MessageBox(NULL, message.c_str(), "Error!", MB_ICONEXCLAMATION | MB_OK);

        SQLPostInstallerError(err.GetCode(), err.GetText());
    }

    return false;
}

/**
 * Register DSN with specified configuration.
 *
 * @param config Configuration.
 * @param driver Driver.
 * @return True on success and false on fail.
 */
bool RegisterDsn(const Configuration& config, LPCSTR driver)
{
    using namespace ignite::odbc::config;
    using ignite::common::LexicalCast;

    typedef Configuration::ArgumentMap ArgMap;

    const char* dsn = config.GetDsn().c_str();

    try
    {
        if (!SQLWriteDSNToIni(dsn, driver))
            ignite::odbc::ThrowLastSetupError();

        const ArgMap& map = config.GetMap();

        std::set<std::string> ignore;

        ignore.insert(Configuration::Key::dsn);
        ignore.insert(Configuration::Key::driver);

        for (ArgMap::const_iterator it = map.begin(); it != map.end(); ++it)
        {
            const std::string& key = it->first;
            const std::string& value = it->second;

            if (ignore.find(key) != ignore.end())
                continue;

            ignite::odbc::WriteDsnString(dsn, key.c_str(), value.c_str());
        }

        return true;
    }
    catch (ignite::IgniteError& err)
    {
        MessageBox(NULL, err.GetText(), "Error!", MB_ICONEXCLAMATION | MB_OK);

        SQLPostInstallerError(err.GetCode(), err.GetText());
    }

    return false;
}

/**
 * Unregister specified DSN.
 *
 * @param dsn DSN name.
 * @return True on success and false on fail.
 */
bool UnregisterDsn(const char* dsn)
{
    try
    {
        if (!SQLRemoveDSNFromIni(dsn))
            ignite::odbc::ThrowLastSetupError();

        return true;
    }
    catch (ignite::IgniteError& err)
    {
        MessageBox(NULL, err.GetText(), "Error!", MB_ICONEXCLAMATION | MB_OK);

        SQLPostInstallerError(err.GetCode(), err.GetText());
    }

    return false;
}

BOOL INSTAPI ConfigDSN(HWND hwndParent, WORD req, LPCSTR driver, LPCSTR attributes)
{
    using namespace ignite::odbc;

    LOG_MSG("ConfigDSN called\n");

    Configuration config;

    LOG_MSG("Attributes: %s\n", attributes);

    config.FillFromConfigAttributes(attributes);

    if (!SQLValidDSN(config.GetDsn().c_str()))
        return FALSE;

    LOG_MSG("Driver: %s\n", driver);
    LOG_MSG("Attributes: %s\n", attributes);

    LOG_MSG("DSN: %s\n", config.GetDsn().c_str());

    switch (req)
    {
        case ODBC_ADD_DSN:
        {
            LOG_MSG("ODBC_ADD_DSN\n");

            if (!DisplayConfigureDsnWindow(hwndParent, config))
                return FALSE;

            if (!RegisterDsn(config, driver))
                return FALSE;

            break;
        }

        case ODBC_CONFIG_DSN:
        {
            LOG_MSG("ODBC_CONFIG_DSN\n");

            std::string dsn = config.GetDsn();

            Configuration loaded(config);

            ReadDsnConfiguration(dsn.c_str(), loaded);

            if (!DisplayConfigureDsnWindow(hwndParent, loaded))
                return FALSE;

            if (!RegisterDsn(loaded, driver))
                return FALSE;

            if (loaded.GetDsn() != dsn && !UnregisterDsn(dsn.c_str()))
                return FALSE;

            break;
        }

        case ODBC_REMOVE_DSN:
        {
            LOG_MSG("ODBC_REMOVE_DSN\n");

            if (!UnregisterDsn(config.GetDsn().c_str()))
                return FALSE;

            break;
        }

        default:
            return FALSE;
    }

    return TRUE;
}


text:
<!DOCTYPE html>

		<title>Live LRS Demo</title>
		<link rel='stylesheet' href='../lib/nv.d3.css'/>

				<svg></svg>


text:
<md-button class="md-icon-button" aria-label="favorite"
           ng-click="dolike(likeEntity)">
    <md-icon ng-if="like"
             md-svg-icon="action:favorite"></md-icon>
    <md-icon ng-if="!like"
             md-svg-icon="action:favorite_outline"></md-icon>
</md-button>


text:
@interface BDKTableViewController () <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIRefreshControl *refreshControl;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (weak, nonatomic) BDKAutomatic *automatic;

@property (strong, nonatomic) NSDictionary *tripDict;
@property (strong, nonatomic) NSArray *sectionKeys;

- (void)tableViewDidPullToRefresh:(UIRefreshControl *)control;
- (void)logoutButtonTapped:(UIBarButtonItem *)sender;

@end

@implementation BDKTableViewController

#pragma mark - Lifecycle

+ (instancetype)viewControllerWithAutomaticAdapter:(BDKAutomatic *)adapter {
    id instance = [self new];
    [instance setAutomatic:adapter];
    return instance;
}

- (void)loadView {
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tripDict = [NSDictionary dictionary];
    self.title = @"Trips";
    self.refreshControl = [UIRefreshControl new];
    [self.refreshControl addTarget:self action:@selector(tableViewDidPullToRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:self.refreshControl];

    UIBarButtonItem *logoutButton = [[UIBarButtonItem alloc] initWithTitle:@"Logout"
                                                                     style:UIBarButtonItemStylePlain
                                                                    target:self
                                                                    action:@selector(logoutButtonTapped:)];
    self.navigationItem.leftBarButtonItem = logoutButton;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.refreshControl beginRefreshing];
    [self tableViewDidPullToRefresh:self.refreshControl];
}

#pragma mark - Properties

- (UITableView *)tableView {
    if (_tableView) return _tableView;
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    // Not so fast; we're using subtitle-styled cells
    // [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    return _tableView;
}

- (NSDateFormatter *)dateFormatter {
    if (_dateFormatter) return _dateFormatter;
    _dateFormatter = [NSDateFormatter new];
    [_dateFormatter setDateFormat:@"h:mm:ss a"];
    return _dateFormatter;
}

#pragma mark - Private methods

- (void)tableViewDidPullToRefresh:(UIRefreshControl *)control {
    [self.automatic getTrips:^(NSError *error, id responseObject) {
        if (error) {
            [[[UIAlertView alloc] initWithTitle:responseObject[@"message"]
                                        message:responseObject[@"documentation_url"]
                                       delegate:nil
                              cancelButtonTitle:@"Close"
                              otherButtonTitles:nil, nil] show];
            NSLog(@"Error! %@", responseObject);
            [control endRefreshing];
            return;
        }

        NSMutableDictionary *mTrips = [NSMutableDictionary dictionary];
        NSMutableSet *orderedKeys = [NSMutableSet set];
        NSDateFormatter *sectionDF = [NSDateFormatter new];
        [sectionDF setDateFormat:@"yyyy-MM-dd"];
        NSDateFormatter *titleDF = [NSDateFormatter new];
        [titleDF setDateFormat:@"MMMM d, yyyy"];
        [responseObject enumerateObjectsUsingBlock:^(BDKAutomaticTrip *trip, NSUInteger idx, BOOL *stop) {
            NSString *sectionString = [sectionDF stringFromDate:trip.startTime];
            [orderedKeys addObject:sectionString];
            if (mTrips[sectionString]) {
                [mTrips[sectionString][@"trips"] addObject:trip];
            } else {
                mTrips[sectionString] = @{@"title": [titleDF stringFromDate:trip.startTime],
                                          @"trips": [NSMutableArray arrayWithObject:trip]};
            }
        }];

        NSArray *ordered = [[orderedKeys allObjects] sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
        self.sectionKeys = [[ordered reverseObjectEnumerator] allObjects];
        self.tripDict = [mTrips copy];
        [control endRefreshing];

        [self.tableView reloadData];
    }];
}

- (void)logoutButtonTapped:(UIBarButtonItem *)sender {
    if (self.userDidLogout) {
        self.userDidLogout();
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.sectionKeys count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *key = self.sectionKeys[section];
    return self.tripDict[key][@"title"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *title = self.sectionKeys[section];
    return [self.tripDict[title][@"trips"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    }
    NSString *title = self.sectionKeys[indexPath.section];
    BDKAutomaticTrip *trip = self.tripDict[title][@"trips"][indexPath.row];
    cell.textLabel.text = [self.dateFormatter stringFromDate:trip.startTime];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f km", [trip.distanceInMeters floatValue] / 1000];
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BDKMapViewController *mapVC = [BDKMapViewController new];
    NSString *title = self.sectionKeys[indexPath.section];
    mapVC.trip = self.tripDict[title][@"trips"][indexPath.row];
    [self.navigationController pushViewController:mapVC animated:YES];
}

@end


text:
#include <modules/server/include/topics/bouncetopic.h>

#include <modules/server/include/connection.h>

namespace openspace {

void BounceTopic::handleJson(const nlohmann::json& json) {
    _connection->sendJson(json);
}

bool BounceTopic::isDone() const {
    return false;
}

} // namespace openspace


text:
package com.lyw.zhbj.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class NoScrollViewPager extends ViewPager {

	public NoScrollViewPager(Context context) {
		super(context);
	}

	public NoScrollViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	//Intercept½ØÈ¡ ¸Ã·½·¨ÓÐûÓÐËƺõ¶¼ÄÜʵÏÖ¹¦ÄÜ
//	@Override
//	public boolean onInterceptTouchEvent(MotionEvent ev) {
//		return false;
//	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		return false;
	}
}


text:
package org.apache.zeppelin.utils;

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

import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.junit.After;
import org.junit.Test;

public class CorsUtilsTest {

  @After
  public void cleanup() {
    ZeppelinConfiguration.reset();
  }
  @Test
  public void isInvalid() throws URISyntaxException, UnknownHostException {
    assertFalse(CorsUtils.isValidOrigin("http://127.0.1.1", ZeppelinConfiguration.create()));
  }

  @Test
  public void isInvalidFromConfig()
      throws URISyntaxException, UnknownHostException {
    assertFalse(CorsUtils.isValidOrigin("http://otherinvalidhost.com",
        ZeppelinConfiguration.create("zeppelin-site.xml")));
  }

  @Test
  public void isLocalhost() throws URISyntaxException, UnknownHostException {
    assertTrue(CorsUtils.isValidOrigin("http://localhost", ZeppelinConfiguration.create()));
  }

  @Test
  public void isLocalMachine() throws URISyntaxException, UnknownHostException {
    String origin = "http://" + InetAddress.getLocalHost().getHostName();
    assertTrue("Origin " + origin + " is not allowed. Please check your hostname.",
        CorsUtils.isValidOrigin(origin, ZeppelinConfiguration.create()));
  }

  @Test
  public void isValidFromConfig()
      throws URISyntaxException, UnknownHostException {
    assertTrue(CorsUtils.isValidOrigin("http://otherhost.com",
      ZeppelinConfiguration.create("zeppelin-site.xml")));
  }

  @Test
  public void isValidFromStar()
      throws URISyntaxException, UnknownHostException {
    assertTrue(CorsUtils.isValidOrigin("http://anyhost.com",
      ZeppelinConfiguration.create("zeppelin-site-star.xml")));
  }

  @Test
  public void nullOrigin()
      throws URISyntaxException, UnknownHostException {
    assertFalse(CorsUtils.isValidOrigin(null,
      ZeppelinConfiguration.create("zeppelin-site.xml")));
  }

  @Test
  public void nullOriginWithStar()
      throws URISyntaxException, UnknownHostException {
    assertTrue(CorsUtils.isValidOrigin(null,
      ZeppelinConfiguration.create("zeppelin-site-star.xml")));
  }

  @Test
  public void emptyOrigin()
      throws URISyntaxException, UnknownHostException {
    assertFalse(CorsUtils.isValidOrigin("",
      ZeppelinConfiguration.create("zeppelin-site.xml")));
  }

  @Test
  public void notAURIOrigin()
      throws URISyntaxException, UnknownHostException {
    assertFalse(CorsUtils.isValidOrigin("test123",
      ZeppelinConfiguration.create("zeppelin-site.xml")));
  }
}


text:
using System;

namespace FunnyBus.Infrastructure.Reflection
{
    internal interface IHandlerScanner
    {
        bool RegisterHandlerDefinitions(Action<Type> addToRegistry);
    }
}


text:
<?php

namespace com_brucemyers\CategoryWatchlistBot;

use com_brucemyers\Util\Config;
use com_brucemyers\MediaWiki\MediaWiki;
use PDO;
use PDOException;
use com_brucemyers\Util\Logger;
use Exception;

class ServiceManager
{
	const WIKI_HOST = 'CategoryWatchlistBot.wiki_host';
	const TOOLS_HOST = 'CategoryWatchlistBot.tools_host';
	const LABSDB_USERNAME = 'CategoryWatchlistBot.labsdb_username';
	const LABSDB_PASSWORD = 'CategoryWatchlistBot.labsdb_password';

	protected $dbuser;
	protected $dbpass;
	protected $wiki_host;
	protected $tools_host;

	/**
	 * Constructor
	 */
	public function __construct()
	{
     	$this->dbuser = Config::get(self::LABSDB_USERNAME);
    	$this->dbpass = Config::get(self::LABSDB_PASSWORD);
    	$this->wiki_host = Config::get(self::WIKI_HOST);
	    $this->tools_host = Config::get(self::TOOLS_HOST);
	}

	/**
	 * Get a database connection.
	 * User is responsible for setting connection to null when done.
	 *
	 * @param string $wikiname
	 * @return PDO DB connection
	 */
	public function getDBConnection($wikiname)
	{
	    try {
    		if ($wikiname == 'tools') {
    			$dbh = new PDO("mysql:host={$this->tools_host};dbname=s51454__CategoryWatchlistBot;charset=utf8mb4", $this->dbuser, $this->dbpass);

    		} else {
        		$wiki_host = $this->wiki_host;
        		if (empty($wiki_host)) $wiki_host = "$wikiname.analytics.db.svc.eqiad.wmflabs";
        		$dbh = new PDO("mysql:host=$wiki_host;dbname={$wikiname}_p;charset=utf8mb4", $this->dbuser, $this->dbpass);
    		}
	    } catch (PDOException $e) {
	        Logger::log($e->getMessage());
	        throw new Exception('Connection error, see log for details');
	    }

    	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		return $dbh;
	}

	/**
	 * Get a MediaWiki instance.
	 *
	 * @param String $domain
	 * @return MediaWiki
	 */
	public function getMediaWiki($domain)
	{
	    $url = "https://$domain/w/api.php";
	    $wiki = new MediaWiki($url);

		return $wiki;
	}

	public function getToolsHost()
	{
		return $this->tools_host;
	}

	public function getUser()
	{
		return $this->dbuser;
	}

	public function getPass()
	{
		return $this->dbpass;
	}
}


text:
<?php

namespace DigiTickets\Evo\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;
use Omnipay\Common\Message\RequestInterface;

/**
 * Evo Response
 */
class Response extends AbstractResponse implements RedirectResponseInterface
{
    /**
     * @var DigiTickets\Evo\Message\PurchaseRequest $request The purchase request object.
     */
    protected $request;

    public function __construct(RequestInterface $request, $data)
    {
        // Decode the response (it's actually very simple).
        $this->data = $this->decode($data);
        $this->request = $request;
    }

    public function isSuccessful()
    {
        // We actually want to always return false, so that the controller then checks
        // for redirection.
        return false;
    }

    public function hasToken()
    {
        return (isset($this->data['status']) && $this->data['status'] === 'ok');
    }

    public function isRedirect()
    {
        // I think we *always* redirect, but only if successful.
        return $this->hasToken();
    }

    public function getRedirectUrl()
    {
        if ($this->isRedirect()) {
            return (string) $this->request->getRedirectUrl();
        }

        return '';
    }

    public function getRedirectMethod()
    {
        return 'POST';
    }

    public function getRedirectData()
    {

        $redirectData = [
            'ClientId' => $this->request->getMerchantId(),
            'StoreType' => $this->request->getMerchantType(),
            'Token' => $this->data['msg'],
            'TranType' => 'Auth',
            'Total' => $this->request->getAmount(),
            'Currency' => $this->request->convertCurrency($this->request->getCurrency()),
            'OrderId' => $this->request->getTransactionId(),
            'ConsumerName' => $this->request->getConsumerName(),
            'ConsumerSurname' => $this->request->getConsumerSurname(),
            'okUrl' => $this->request->getOkUrl(),
            'failUrl' => $this->request->getFailUrl(),
            'pendingURL' => $this->request->getPendingUrl(),
            'lang' => 'en'
        ];

        return $redirectData;

    }

    protected function decode($data) {
        $tokenParts = [];
        parse_str($data, $tokenParts);

        return $tokenParts;
    }

    public function getMessage()
    {
        if ($this->hasToken()) {
            return null;
        }
        if (isset($this->data['msg'])) {
            return $this->data['msg'];
        }

        return 'Unable to retrieve error message';
    }
}


text:
package brooklyn.event;

import brooklyn.entity.Entity;

/**
 * A tuple representing a piece of data from a {@link Sensor} on an {@link Entity}.
 */
public interface SensorEvent<T> {
    /**
     * The {@link Entity} where the data originated.
     */
    Entity getSource();

    /**
     * The {@link Sensor} describing the data.
     */
    Sensor<T> getSensor();

    /**
     * The value for the {@link Sensor} data.
     */
    T getValue();

    /**
     * The time this data was published, as a UTC time in milliseconds (e.g. as returned
     * by {@link System#currentTimeMillis()}.
     */
    long getTimestamp();
}


text:
package com.skynav.cap2tt.app.ttml2;

import org.junit.Test;

import com.skynav.cap2tt.app.ConverterTestDriver;

public class ConverterTestCases extends ConverterTestDriver {

    @Test
    public void testConversion001Mixed() throws Exception {
        performConversionTest("test-001-mixed.cap", 0, 0);
    }

    @Test
    public void testConversion002Mixed() throws Exception {
        performConversionTest("test-002-mixed.cap", 0, 0);
    }

    @Test
    public void testConversion003ScreenAttrItalics() throws Exception {
        performConversionTest("test-003-screen-attr-italics.cap", 0, 0);
    }

    @Test
    public void testConversion004SpaceBeforeNonTextAttribute() throws Exception {
        performConversionTest("test-004-space-before-non-text-attribute.cap", 0, 1);
    }

    @Test
    public void testConversion005PlacementAndAlignmentContinuation() throws Exception {
        performConversionTest("test-005-placement-and-alignment-continuation.cap", 0, 0);
    }

    @Test
    public void testConversion006RegionPositionInitialValue() throws Exception {
        performConversionTest("test-006-region-position-initial-value.cap", 0, 0);
    }

    @Test
    public void testConversion007TateChuYoko() throws Exception {
        performConversionTest("test-007-tate-chu-yoko.cap", 0, 0);
    }

    @Test
    public void testConversion008EscapedHalfWidthSpace() throws Exception {
        performConversionTest("test-008-escaped-half-width-space.cap", 0, 0);
    }

    @Test
    public void testConversion009EscapedFullWidthSpace() throws Exception {
        performConversionTest("test-009-escaped-full-width-space.cap", 0, 0);
    }

    @Test
    public void testConversion010PlacementContinuation() throws Exception {
        performConversionTest("test-010-placement-continuation.cap", 0, 0);
    }

    @Test
    public void testConversion011PlacementAndAlignmentContinuation() throws Exception {
        performConversionTest("test-011-placement-and-alignment-continuation.cap", 0, 0);
    }

    @Test
    public void testConversion012PlacementAndAlignmentRetained() throws Exception {
        performConversionTest("test-012-placement-and-alignment-retained.cap", 0, 0);
    }

    @Test
    public void testConversion013PlacementAndAlignmentDefault() throws Exception {
        performConversionTest("test-013-placement-and-alignment-default.cap", 0, 0);
    }

    @Test
    public void testConversion014SniffUTF8NoBOM() throws Exception {
        performConversionTest("test-014-sniff-utf8-no-bom.cap", 0, 0);
    }

    @Test
    public void testConversion015RubyPosition() throws Exception {
        performConversionTest("test-015-ruby-position.cap", 0, 0);
    }

    @Test
    public void testConversion016EmphasisPosition() throws Exception {
        performConversionTest("test-016-emphasis-position.cap", 0, 0);
    }

    @Test
    public void testConversion017EmphasisMixed() throws Exception {
        performConversionTest("test-017-emphasis-mixed.cap", 0, 0);
    }

    @Test
    public void testConversion018NestedDesignations1() throws Exception {
        performConversionTest("test-018-nested-designations-1.cap", 0, 0);
    }

    @Test
    public void testConversion019SpaceInAnnotationEmphasis() throws Exception {
        performConversionTest("test-019-space-in-annotation-emphasis.cap", 0, 0);
    }

    @Test
    public void testConversion020SpaceInAnnotationIssue113() throws Exception {
        performConversionTest("test-020-space-in-annotation-issue-113.cap", 0, 0);
    }

    @Test
    public void testConversion021SpaceInAnnotationIssue112() throws Exception {
        performConversionTest("test-021-space-in-annotation-issue-112.cap", 0, 0);
    }

    @Test
    public void testConversion022MultipleSpacesIssue110() throws Exception {
        performConversionTest("test-022-multiple-spaces-issue-110.cap", 0, 0);
    }

    @Test
    public void testConversion023SpaceInAnnotationIssue133Case1() throws Exception {
        performConversionTest("test-023-space-in-annotation-issue-133-case-1.cap", 0, 0);
    }

    @Test
    public void testConversion024SpaceInAnnotationIssue133Case2() throws Exception {
        performConversionTest("test-024-space-in-annotation-issue-133-case-2.cap", 0, 0);
    }

    @Test
    public void testConversion025FalseScreenNumberIssue138Case1() throws Exception {
        performConversionTest("test-025-false-screen-number-issue-138-case-1.cap", 0, 0);
    }

    @Test
    public void testConversion026FalseScreenNumberIssue138Case2() throws Exception {
        performConversionTest("test-026-false-screen-number-issue-138-case-2.cap", 0, 0);
    }

    @Test
    public void testConversion027FalseScreenNumberIssue138Case3() throws Exception {
        performConversionTest("test-027-false-screen-number-issue-138-case-3.cap", 0, 0);
    }

    @Test
    public void testConversion028FalseAttributePrefixIssue145() throws Exception {
        performConversionTest("test-028-false-attribute-prefix-issue-145.cap", 0, 0);
    }

    @Test
    public void testConversion029NestedDesignations2() throws Exception {
        performConversionTest("test-029-nested-designations-2.cap", 0, 0);
    }

}


text:
var RequestHttpCache = require('..');
var request = require('request');
var assert = require('assert');
var mockStats = require('./mock-stats');

describe('integration-test', function() {

  var httpRequestCache;

  before(function() {
    stats = mockStats();

    httpRequestCache = new RequestHttpCache({
      backend: 'redis',
      redisPrefix: 'hc:' + Date.now() + ":",
      stats: stats
    });
  });

  it('should return different values for different people', function(done) {
    function makeRequest(token, user, hit, callback) {
      stats.reset();

      httpRequestCache.extension({
        method: 'GET',
        url: 'https://api.github.com/user',
        headers: {
          Authorization: 'token ' + token,
          'User-Agent': 'request-http-cache-test/1.0',
        },
        json: true
      }, function(err, response, body) {
        if (err) return done(err);
        if (response.statusCode !== 200) return done(new Error('HTTP ' + response.statusCode + ': ' + JSON.stringify(body)));

        if (hit) {
          assert.strictEqual(stats.incs.hit, 1);
        } else {
          assert(!stats.incs.hit);
        }

        assert.strictEqual(body.login, user);
        callback();
      }, request);
    }

    makeRequest(process.env.GITHUB_TOKEN_1, 'gitterawesome', false, function() {
      makeRequest(process.env.GITHUB_TOKEN_2, 'gittertestbot', false, function() {
        makeRequest(process.env.GITHUB_TOKEN_1, 'gitterawesome', true, function() {
          makeRequest(process.env.GITHUB_TOKEN_2, 'gittertestbot', true, function() {
            done();
          });
        });
      });
    });

  });

});


text:
<?php

namespace Gerarodjbaez\Laraplans\Unit;

use Gerardojbaez\Laraplans\Feature;
use Gerardojbaez\Laraplans\Tests\TestCase;
use Gerardojbaez\Laraplans\Exceptions\InvalidPlanFeatureException;

class FeatureTest extends TestCase
{
    /**
     * Can return all configured feature codes.
     *
     * @test
     * @return void
     */
    public function it_can_get_all_features()
    {
        $features = Feature::getAllFeatures();

        $this->assertEquals([
            'SAMPLE_SIMPLE_FEATURE',
            'SAMPLE_DEFINED_FEATURE'
        ], $features);
    }

    /**
     * Can check if feature code is valid.
     *
     * @test
     * @return void
     */
    public function it_can_validate_feature_code()
    {
        $this->assertTrue(Feature::isValid('SAMPLE_SIMPLE_FEATURE'));
        $this->assertTrue(Feature::isValid('SAMPLE_DEFINED_FEATURE'));
        $this->assertFalse(Feature::isValid('dummy_feature'));
    }

    /**
     * Can generate feature reset date.
     *
     * @test
     * @return void
     */
    public function it_can_generate_feature_reset_date()
    {
        $feature = new Feature('SAMPLE_DEFINED_FEATURE');
        $feature->setResettableInterval('month');
        $feature->setResettableCount('1');

        $this->assertEquals('2016-09-16 17:14:16', (string)$feature->getResetDate('2016-08-16 17:14:16'));
    }

    /**
     * @test
     * @return void
     */
    public function it_throw_exception_on_invalid_feature()
    {
        $this->expectException(InvalidPlanFeatureException::class);

        $feature = new Feature('dummy_feature');
    }
}


text:
package uk.gov.gds.location.importer.io

import java.io.File
import com.Ostermiller.util.CSVParser
import scalax.io.{Resource, Codec}

object FileUtilities {

  implicit val code: Codec = Codec("UTF-8")

  /* wrappers for outcome of parse attempt */

  sealed abstract class Outcome(r: Boolean)

  case object Success extends Outcome(true)

  case object Failure extends Outcome(false)

  case class Result(outcome: Outcome, message: String)

  /* File utility methods */

  def loadFile(file: File) = Resource.fromFile(file)

  def writer(location: String) = Resource.fromFile(location).writer

  def fileExists(location: String) = new File(location).exists

  def deleteFile(file: File) = file.delete()

  def isDirectory(location: String) = new File(location).isDirectory

  def directoryContents(location: String) = new File(location).listFiles().toList

  def filteredDirectoryContents(location: String, fileFilter: File => Boolean) = directoryContents(location).filter(fileFilter)

  def parseCsvLine(line: String) = CSVParser.parse(line)(0).toList
}


text:
module CRE
  module Stats
    module Mappers
      class GuestMapper
        class << self
          #
          # Loads a number of guests from a comma-separated list
          #
          def load(list)
            list.split(', ')
          end
        end
      end
    end
  end
end


text:
using System;
using System.Threading.Tasks;

//For UML diagram, see ProgressSystem.uml (done in StarUML)

namespace SIL.Progress.Commands
{
	/// <summary>
	/// Delegate for a method which allows the progress range to be reset
	/// </summary>
	public delegate void InitializeProgressCallback(int minimum, int maximum);

	/// <summary>
	/// Delegate for a method which allows the progress to be updated
	/// </summary>
	public delegate void ProgressCallback(int progress);

	/// <summary>
	/// Delegate for a method which allows the status text to be updated
	/// </summary>
	public delegate void StatusCallback(string statusText);

	public abstract class BasicCommand : AsyncCommand
	{
		private InitializeProgressCallback _initializeCallback;
		private ProgressCallback _progressCallback;
		private StatusCallback _primaryStatusTextCallback;
		private StatusCallback _secondaryStatusTextCallback;

		public InitializeProgressCallback InitializeCallback
		{
			set { _initializeCallback = value; }
		}

		public ProgressCallback ProgressCallback
		{
			set { _progressCallback = value; }
		}

		public StatusCallback PrimaryStatusTextCallback
		{
			set { _primaryStatusTextCallback = value; }
		}

		public StatusCallback SecondaryStatusTextCallback
		{
			set { _secondaryStatusTextCallback = value; }
		}

		/// <summary>
		/// Implementation of the async work invoker
		/// </summary>
		protected override async Task BeginInvokeCore()
		{
			WorkInvoker worker = DoWork;
			var workTask = Task.Run(() => worker.Invoke(
				_initializeCallback,
				_progressCallback,
				_primaryStatusTextCallback,
				_secondaryStatusTextCallback));
			await EndWork(workTask).ConfigureAwait(false); //resume execution on any thread
		}

		protected override async Task BeginInvokeCore2(ProgressState progress)
		{
			WorkInvoker2 worker = DoWork2;
			var workTask = Task.Run(() => worker.Invoke(progress));
			await EndWork(workTask).ConfigureAwait(false); //resume execution on any thread
		}

		protected abstract void DoWork(
			InitializeProgressCallback initializeCallback,
			ProgressCallback progressCallback,
			StatusCallback primaryStatusTextCallback,
			StatusCallback secondaryStatusTextCallback
			);

		protected abstract void DoWork2(ProgressState progress);

		private async Task EndWork(Task workTask)
		{
			try
			{
				await workTask.ConfigureAwait(false); //resume execution on any thread
				OnFinish(EventArgs.Empty);
			}
			catch (Exception e)
			{
				// Marshal exceptions back to the UI
				OnError(new ErrorEventArgs(e));
			}
		}
	}

	/// <summary>
	/// Delegate for a worker method which provides additional callbacks
	/// </summary>
	public delegate void WorkInvoker(
		InitializeProgressCallback initializeCallback,
		ProgressCallback progressCallback,
		StatusCallback primaryStatusTextCallback,
		StatusCallback secondaryStatusTextCallback
		);

	public delegate void WorkInvoker2(ProgressState progress);

	public delegate void WorkInvoker3(
		InitializeProgressCallback initializeCallback,
		ProgressCallback progressCallback,
		StatusCallback primaryStatusTextCallback,
		StatusCallback secondaryStatusTextCallback
		);
}


text:
package com.nicholaskiraly.research.labortone;

public class LaborToneException extends Exception {

  public LaborToneException() {
    super();
  }

  public LaborToneException(String message) {
    super(message);
  }

  public LaborToneException(String message, Throwable cause) {
    super(message, cause);
  }

  public LaborToneException(Throwable cause) {
    super(cause);
  }
}


text:
package org.apache.etch.util.core.nio;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.apache.etch.util.FlexBuffer;
import org.apache.etch.util.Log;
import org.apache.etch.util.Monitor;
import org.apache.etch.util.Resources;
import org.apache.etch.util.core.Who;
import org.apache.etch.util.core.io.Session;
import org.apache.etch.util.core.io.SessionData;
import org.apache.etch.util.core.io.SessionListener;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Tests Tcp2Connection.
 */
public class TestTcp2Connection
{
	private final static MyListener lh = new MyListener();

	private final static int TIMEOUT = 4000;

	private final static SuperSelector selector = new SuperSelector();
	static
	{
		selector.start();
	}

	private final static ByteBufferPool pool = new ByteBufferPool(1024, 10, 1000, 0, 0 );

	private final static Resources r = new Resources();
	static
	{
		r.put( "bufferPool", pool );
		r.put( "selector", selector );
	}

	private final static Tcp2Listener l = new Tcp2Listener( "tcp://0.0.0.0:0", r );

	private static int port;

	/** @throws Exception */
	@BeforeClass
	public static void startListener() throws Exception
	{
		l.setSession( lh );

		// start listener
		l.start();
		l.waitUp( TIMEOUT );

		port = ((InetSocketAddress) l.localAddress()).getPort();

		Log.addSink( null );
		Log.report( "TestTcp2Connection" );
	}

	/** @throws Exception */
	@AfterClass
	public static void stopListener() throws Exception
	{
		l.stop();
		l.waitDown( TIMEOUT );
	}

	/** @throws Exception */
	@Test( expected = IllegalArgumentException.class )
	public void constructor1() throws Exception
	{
		// no host or port
		new Tcp2Connection( "tcp:", r );
	}

	/** @throws Exception */
	@Test
	public void constructor2() throws Exception
	{
		SocketChannel s = newSocketChannel( "127.0.0.1", port );
		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		r.put( "connection", s );
		Tcp2Connection c = new Tcp2Connection( "tcp:", r );
		assertNull( c.getSession() );

		s.close();
		t.close();
	}

	private static SocketChannel newSocketChannel( String host, int port )
		throws IOException
	{
		return SocketChannel.open( new InetSocketAddress( host, port )  );
	}

	/** @throws Exception */
	@Test
	public void constructor3() throws Exception
	{
		SessionData dh = new MyDataHandler();
		SocketChannel s = newSocketChannel( "127.0.0.1", port );
		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		r.put( "connection", s );
		Tcp2Connection c = new Tcp2Connection( "tcp:", r );
		c.setSession( dh );
		assertSame( dh, c.getSession() );

		s.close();
		t.close();
	}

//	/** @throws Exception */
//	@Test( expected = IllegalArgumentException.class )
//	public void constructor4() throws Exception
//	{
//		// null host
//		new Tcp2Connection( "tcp://0.0.0.0:1", null );
//	}

	/** @throws Exception */
	@Test( expected = IllegalArgumentException.class )
	public void constructor5a() throws Exception
	{
		// no port
		new Tcp2Connection( "tcp://localhost", r );
	}

	/** @throws Exception */
	@Test( expected = IllegalArgumentException.class )
	public void constructor5b() throws Exception
	{
		// zero port
		new Tcp2Connection( "tcp://localhost:0", r );
	}

	/** @throws Exception */
	@Test( expected = IllegalArgumentException.class )
	public void constructor6() throws Exception
	{
		// too big port
		new Tcp2Connection( "tcp://localhost:65536", r );
	}

	/** @throws Exception */
	@Test( expected = IllegalArgumentException.class )
	public void constructor7() throws Exception
	{
		// negative reconnect delay
		new Tcp2Connection( "tcp://localhost:1?TcpTransport.reconnectDelay=-1", r );
	}

	/** @throws Exception */
	@Test
	public void constructor8() throws Exception
	{
		Tcp2Connection c = new Tcp2Connection( "tcp://localhost:"+port, r );
		assertNull( c.getSession() );
	}

	/** @throws Exception */
	@Test
	public void constructor9() throws Exception
	{
		SessionData dh = new MyDataHandler();
		Tcp2Connection c = new Tcp2Connection( "tcp://localhost:"+port, r );
		c.setSession( dh );
		assertSame( dh, c.getSession() );
	}

	/** @throws Exception */
	@Test
	public void start1() throws Exception
	{
		SocketChannel s = newSocketChannel( "127.0.0.1", port );
		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		MyDataHandler dh = new MyDataHandler();

		r.put( "connection", s );
		Tcp2Connection c = new Tcp2Connection( "tcp:", r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		c.waitUp( TIMEOUT );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

//		c.flush();
		assertNotNull( c.remoteAddress() );
		assertNotNull( c.localAddress() );
		assertEquals( c.remoteAddress(), t.socket().getLocalSocketAddress() );
		assertEquals( c.localAddress(), t.socket().getRemoteSocketAddress() );

		t.close();

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );
	}

	/** @throws Exception */
	@Test
	public void start2() throws Exception
	{
		SocketChannel s = newSocketChannel( "127.0.0.1", port );
		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		MyDataHandler dh = new MyDataHandler();

		r.put( "connection", s );
		Tcp2Connection c = new Tcp2Connection( "tcp:", r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		assertTrue( c.isStarted() );
		c.stop();
		assertFalse( c.isStarted() );

		c.waitDown( TIMEOUT );

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	/** @throws Exception */
	@Test
	public void start3() throws Exception
	{
		SocketChannel s = newSocketChannel( "127.0.0.1", port );
		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		MyDataHandler dh = new MyDataHandler();

		r.put( "connection", s );
		Tcp2Connection c = new Tcp2Connection( "tcp:", r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		assertTrue( c.isStarted() );
		c.close();

		c.waitDown( TIMEOUT );

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	/** @throws Exception */
	@Test
	public void start4() throws Exception
	{
		SocketChannel s = newSocketChannel( "127.0.0.1", port );
		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		MyDataHandler dh = new MyDataHandler();

		r.put( "connection", s );
		Tcp2Connection c = new Tcp2Connection( "tcp:", r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		assertTrue( c.isStarted() );
		c.close( false );

		c.waitDown( TIMEOUT );

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	/** @throws Exception */
	@Test
	public void start5() throws Exception
	{
		SocketChannel s = newSocketChannel( "127.0.0.1", port );
		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		MyDataHandler dh = new MyDataHandler();

		r.put( "connection", s );
		Tcp2Connection c = new Tcp2Connection( "tcp:", r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		assertTrue( c.isStarted() );
		c.close( true );

		c.waitDown( TIMEOUT );

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	/** @throws Exception */
	@Test
	public void start6() throws Exception
	{
		MyDataHandler dh = new MyDataHandler();

		Tcp2Connection c = new Tcp2Connection( "tcp://127.0.0.1:"+port, r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		assertTrue( c.isStarted() );
		c.stop();
		assertFalse( c.isStarted() );

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	/** @throws Exception */
	@Test
	public void restart1() throws Exception
	{
		Log.report( "--- restart1 ------------------------------" );

		MyDataHandler dh = new MyDataHandler();

		Tcp2Connection c = new Tcp2Connection( "tcp://127.0.0.1:"+port+"?TcpTransport.reconnectDelay=200", r );
		c.setSession( dh );

		c.start();
		c.waitUp( TIMEOUT );

		int n = 10;
		int i = 0;
		while (++i <= n)
		{
			SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

			Log.report( "accepted", "i", i,
				"t.local", t.socket().getLocalSocketAddress(),
				"t.remote", t.socket().getRemoteSocketAddress() );

			assertWhat( What.UP, dh.what );

			assertEquals( t.socket().getLocalSocketAddress(), c.remoteAddress() );
			assertEquals( t.socket().getRemoteSocketAddress(), c.localAddress() );

			write( t, i );
			assertWhat( What.DATA, dh.what );
			assertNull( dh.xsender );
			assertNotNull( dh.xbuf );
			assertEquals( 1, dh.xbuf.length );
			assertEquals( (byte) i, dh.xbuf[0] );

			t.socket().shutdownOutput();
			t.close();
			t = null;

			assertWhat( What.DOWN, dh.what );
		}

		Thread t1 = new MonitorHarvester<SocketChannel>( lh.accepted );
		t1.start();
		Thread t2 = new MonitorHarvester<What>( dh.what );
		t2.start();

		Log.report( "stopping" );
		c.stop();
		c.waitDown( TIMEOUT );
		Log.report( "stoppped" );

		t1.join();
		t2.join();
	}

	private void write( SocketChannel t, int b ) throws IOException
	{
		ByteBuffer buf = ByteBuffer.allocate( 1 );
		buf.put( (byte) b );
		buf.flip();
		int n = t.write( buf );
		if (n != 1)
			throw new IOException( "n != 1" );
	}

	/**
	 * @param <T>
	 */
	public static class MonitorHarvester<T> extends Thread
	{
		/**
		 * @param mon
		 */
		public MonitorHarvester( Monitor<T> mon )
		{
			this.mon = mon;
		}

		private final Monitor<T> mon;

		@Override
		public void run()
		{
			try
			{
				Object t;
				while ((t = mon.waitUntilNotEqAndSet( null, TIMEOUT, null )) != null)
					Log.report( "harvested", "mon", mon, "t", t );
			}
			catch ( Exception e )
			{
				// ignore
			}
		}
	}

	/** @throws Exception */
	@Test
	public void restart2() throws Exception
	{
		Log.report( "--- restart2 ------------------------------" );

		MyDataHandler dh = new MyDataHandler();

		Tcp2Connection c = new Tcp2Connection( "tcp://127.0.0.1:"+port+"?TcpTransport.reconnectDelay=200", r );
		c.setSession( dh );

		c.start();
		c.waitUp( TIMEOUT );

		int n = 10;
		int i = 0;
		while (++i <= n)
		{
//			Log.report( "--- waitAccepted" );
			SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

			Log.report( "accepted", "i", i,
				"t.local", t.socket().getLocalSocketAddress(),
				"t.remote", t.socket().getRemoteSocketAddress() );

			assertWhat( What.UP, dh.what );
//			Log.report( "up", "c.local", c.localAddress(), "c.remote", c.remoteAddress() );

			assertEquals( t.socket().getLocalSocketAddress(), c.remoteAddress() );
			assertEquals( t.socket().getRemoteSocketAddress(), c.localAddress() );

			write( t, i );
			assertWhat( What.DATA, dh.what );
			assertNull( dh.xsender );
			assertNotNull( dh.xbuf );
			assertEquals( 1, dh.xbuf.length );
			assertEquals( (byte) i, dh.xbuf[0] );

//			Log.report( "c.shutingDownOutput" );
			c.shutdownOutput();
//			Log.report( "c.shutdownOutput" );

//			Log.report( "t.reading" );
			assertEquals( -1, read( t ) );
//			Log.report( "t.eof" );

			t.socket().shutdownOutput();
			t.close();
			t = null;

			assertWhat( What.DOWN, dh.what );
//			Log.report( "down" );
		}

		Thread t1 = new MonitorHarvester<SocketChannel>( lh.accepted );
		t1.start();
		Thread t2 = new MonitorHarvester<What>( dh.what );
		t2.start();

		Log.report( "stopping" );
		c.stop();
		c.waitDown( TIMEOUT );
		Log.report( "stopped" );

		t1.join();
		t2.join();
	}

	private int read( SocketChannel t ) throws IOException
	{
		ByteBuffer buf = ByteBuffer.allocate( 1 );
		int n = t.read( buf );
		if (n <= 0)
			return -1;
		buf.flip();
		return buf.get() & 255;
	}

	/** @throws Exception */
	@Test
	public void data1() throws Exception
	{
		MyDataHandler dh = new MyDataHandler();

		Tcp2Connection c = new Tcp2Connection( "tcp://127.0.0.1:"+port, r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		write( t, 23 );

		assertWhat( What.DATA, dh.what );
		assertNull( dh.xsender );
		assertNotNull( dh.xbuf );
		assertEquals( 1, dh.xbuf.length );
		assertEquals( (byte) 23, dh.xbuf[0] );

		assertTrue( c.isStarted() );
		c.stop();
		assertFalse( c.isStarted() );

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	/** @throws Exception */
	@Test
	public void data2() throws Exception
	{
		MyDataHandler dh = new MyDataHandler();

		Tcp2Connection c = new Tcp2Connection( "tcp://127.0.0.1:"+port, r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		byte[] buf = { 21, 22, 23 };

		write( t, buf );

		assertWhat( What.DATA, dh.what );
		assertNull( dh.xsender );
		assertNotNull( dh.xbuf );
		assertEquals( 3, dh.xbuf.length );
		assertEquals( (byte) 21, dh.xbuf[0] );
		assertEquals( (byte) 22, dh.xbuf[1] );
		assertEquals( (byte) 23, dh.xbuf[2] );

		assertTrue( c.isStarted() );
		c.stop();
		assertFalse( c.isStarted() );

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	private void write( SocketChannel t, byte[] b ) throws IOException
	{
		ByteBuffer buf = ByteBuffer.allocate( b.length );
		buf.put( b );
		buf.flip();
		int n = t.write( buf );
		if (n != b.length)
			throw new IOException( "n != b.length" );
	}

	/** @throws Exception */
	@Test
	public void data3() throws Exception
	{
		MyDataHandler dh = new MyDataHandler();

		Tcp2Connection c = new Tcp2Connection( "tcp://127.0.0.1:"+port, r );
		c.setSession( dh );

		assertFalse( c.isStarted() );
		c.start();
		assertTrue( c.isStarted() );

		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.socket().shutdownOutput();

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
		c.close();
	}

	/** @throws Exception */
	@Test
	public void data4() throws Exception
	{
		MyDataHandler dh = new MyDataHandler();

		Tcp2Connection c = new Tcp2Connection( "tcp://127.0.0.1:"+port, r );
		c.setSession( dh );

		c.start();

		SocketChannel t = lh.accepted.waitUntilNotEqAndSet( null, TIMEOUT, null );

		assertWhat( What.UP, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		c.transportData( null, new FlexBuffer( new byte[] { 21, 22, 23 } ) );
//		c.flush();

		assertEquals( 21, read( t ) );
		assertEquals( 22, read( t ) );
		assertEquals( 23, read( t ) );

		c.shutdownOutput();

		assertEquals( -1, read( t ) );

		c.close();

		assertWhat( What.DOWN, dh.what );
		assertNull( dh.xsender );
		assertNull( dh.xbuf );

		t.close();
	}

	private void assertWhat( What what, Monitor<What> mon )
		throws Exception
	{
		mon.waitUntilEqAndSet( what, TIMEOUT, null );
	}

	/**
	 * Test events.
	 */
	enum What
	{
		/** connection is up */
		UP,
		/** connection is down */
		DOWN,
		/** connection read some data */
		DATA
	}

	/**
	 * ListenerHandler for testing.
	 */
	static class MyListener implements SessionListener<SocketChannel>
	{
		/** monitor to report accepted socket */
		public Monitor<SocketChannel> accepted = new Monitor<SocketChannel>( "accepted" );

		public void sessionAccepted( SocketChannel s ) throws Exception
		{
//			Log.report( "listener.accepted",
//				"s.local", s.getLocalSocketAddress(),
//				"s.remote", s.getRemoteSocketAddress() );

			accepted.waitUntilEqAndSet( null, TIMEOUT, s );
		}

		public Object sessionQuery( Object query )
		{
			throw new UnsupportedOperationException( "unknown query "+query );
		}

		public void sessionControl( Object control, Object value )
		{
			throw new UnsupportedOperationException( "unknown control "+control );
		}

		public void sessionNotify( Object event )
		{
			if (event instanceof Exception)
				Log.report( "listener.notify", "event", event );

			System.out.println( "TestTcp2Connection.MyListener: event = " + event );
		}
	}

	/**
	 * DataHandler for testing.
	 */
	static class MyDataHandler implements SessionData
	{
		/** holds event type */
		public Monitor<What> what = new Monitor<What>( "what" );

		/** sender of the event if DATA */
		public Who xsender;

		/** data of the event if DATA */
		public byte[] xbuf;

		public void sessionData( Who sender, FlexBuffer buf ) throws Exception
		{
			xsender = sender;
			xbuf = buf.getAvailBytes();
			what.waitUntilEqAndSet( null, TIMEOUT, What.DATA );
		}

		public Object sessionQuery( Object query ) throws Exception
		{
			throw new UnsupportedOperationException( "unknown query "+query );
		}

		public void sessionControl( Object control, Object value ) throws Exception
		{
			throw new UnsupportedOperationException( "unknown control "+control );
		}

		public void sessionNotify( Object event ) throws Exception
		{
//			Log.report( "data.notify", "event", event );

			if (event.equals( Session.UP ))
			{
				xbuf = null;
				what.waitUntilEqAndSet( null, TIMEOUT, What.UP );
				return;
			}

			if (event.equals( Session.DOWN ))
			{
				xbuf = null;
				what.waitUntilEqAndSet( null, TIMEOUT, What.DOWN );
				return;
			}

			Log.report( "data.notify", "event", event );
		}
	}
}