text:
USING_NS_CC;
PanelLayer::PanelLayer(void)
{

}

PanelLayer::~PanelLayer(void)
{

}
bool PanelLayer::init()
{
	if(!CCLayer::init())
	{
		return false;
	}

	_goldCounter = GoldCounterLayer::create(0);
	addChild(_goldCounter);
	_goldCounter->setPosition(ccp(700, 30));

	int maxTime =10;
	ScheduleCountDown *countDown =ScheduleCountDown::create(this,maxTime,true);
	addChild(countDown,0, 99);
	_scheduleLabel=CCLabelAtlas::create(CCString::createWithFormat("%d",maxTime)->getCString(),"baoshiyu_shuzi_02-ipadhd.png",50,54,'0');
	addChild(_scheduleLabel);
	_scheduleLabel->setPosition(ccp(550,30));
    return true;
}
void PanelLayer::scheduleTimeUp()
{
	((GameScene *)getParent())->alterGold(200);
	ScheduleCountDown *countDown =(ScheduleCountDown *)getChildByTag(99);
	if(countDown->getLoop()==false)
	{
		_scheduleLabel->setVisible(false);
	}
}
void PanelLayer::setScheduleNumber(int number)
{
	//CCLabelAtlas *label =(CCLabelAtlas *)getChildByTag(99);
	_scheduleLabel->setString(CCString::createWithFormat("%d",number)->getCString());
}


text:
package de.tototec.cmdoption.internal;

public interface Procedure1<P> {
	public void apply(P param);
}

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include "httpd.h"
#include "apr_thread_proc.h"

#include "websocket_plugin.h"

typedef struct _DumbIncrementData {
  const WebSocketServer *server;
  apr_pool_t *pool;
  apr_thread_t *thread;
  int counter;
  int active;
} DumbIncrementData;

void* APR_THREAD_FUNC dumb_increment_run(apr_thread_t *thread, void *data)
{
  char buffer[64];
  DumbIncrementData *dib = (DumbIncrementData *) data;

  if (dib != NULL) {
    /* Keep sending messages as long as the connection is active */
    while (dib->active) {
      apr_sleep(50000); /* 50ms */
      sprintf(buffer,"%d", dib->counter++);
      dib->server->send(dib->server, MESSAGE_TYPE_TEXT, (unsigned char *)buffer, strlen(buffer));
    }
  }
  return NULL;
}

void * CALLBACK dumb_increment_on_connect(const WebSocketServer *server)
{
  DumbIncrementData *dib = NULL;

  if ((server != NULL) && (server->version == WEBSOCKET_SERVER_VERSION_1)) {
    /* Get access to the request_rec strucure for this connection */
    request_rec *r = server->request(server);

    if (r != NULL) {
      apr_pool_t *pool = NULL;
      size_t i, count = server->protocol_count(server);

      /* Only support "dumb-increment-protocol" */
      for (i = 0; i < count; i++) {
        const char *protocol = server->protocol_index(server, i);

        if ((protocol != NULL) &&
            (strcmp(protocol, "dumb-increment-protocol") == 0)) {
          /* If the client can speak the protocol, set it in the response */
          server->protocol_set(server, protocol);
          break;
        }
      }
      /* If the protocol negotiation worked, create a new memory pool */
      if ((i < count) &&
          (apr_pool_create(&pool, r->pool) == APR_SUCCESS)) {
        /* Allocate memory to hold the dumb increment state */
        if ((dib = (DumbIncrementData *) apr_palloc(pool, sizeof(DumbIncrementData))) != NULL) {
          apr_thread_t *thread = NULL;
          apr_threadattr_t *thread_attr = NULL;

          dib->server = server;
          dib->pool = pool;
          dib->thread = NULL;
          dib->counter = 0;
          dib->active = 1;

          /* Create a non-detached thread that will perform the work */
          if ((apr_threadattr_create(&thread_attr, pool) == APR_SUCCESS) &&
              (apr_threadattr_detach_set(thread_attr, 0) == APR_SUCCESS) &&
              (apr_thread_create(&thread, thread_attr, dumb_increment_run, dib, pool) == APR_SUCCESS)) {
            dib->thread = thread;
            /* Success */
            pool = NULL;
          } else {
            dib = NULL;
          }
        }
        if (pool != NULL) {
          apr_pool_destroy(pool);
        }
      }
    }
  }
  return dib;
}

static size_t CALLBACK dumb_increment_on_message(void *plugin_private, const WebSocketServer *server,
    const int type, unsigned char *buffer, const size_t buffer_size)
{
  DumbIncrementData *dib = (DumbIncrementData *) plugin_private;

  if ((dib != 0) &&
      (buffer != 0) && (buffer_size == 6) &&
      (buffer[0] == 'r') &&
      (buffer[1] == 'e') &&
      (buffer[2] == 's') &&
      (buffer[3] == 'e') &&
      (buffer[4] == 't') &&
      (buffer[5] == '\n')) {
    /* If a message containing "reset\n" is received, reset the counter */
    dib->counter = 0;
  }
  return 0;
}

void CALLBACK dumb_increment_on_disconnect(void *plugin_private, const WebSocketServer *server)
{
  DumbIncrementData *dib = (DumbIncrementData *) plugin_private;

  if (dib != 0) {
    /* When disconnecting, inform the thread that it is time to stop */
    dib->active = 0;
    if (dib->thread) {
      apr_status_t status;

      /* Wait for the thread to finish */
      status = apr_thread_join(&status, dib->thread);
    }
    apr_pool_destroy(dib->pool);
  }
}

/*
 * Since we are returning a pointer to static memory, there is no need for a
 * "destroy" function.
 */

static WebSocketPlugin s_plugin = {
  sizeof(WebSocketPlugin),
  WEBSOCKET_PLUGIN_VERSION_0,
  NULL, /* destroy */
  dumb_increment_on_connect,
  dumb_increment_on_message,
  dumb_increment_on_disconnect
};

extern EXPORT WebSocketPlugin * CALLBACK dumb_increment_init()
{
  return &s_plugin;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Res. 94(4): 453 (1990)

#### Original name
Hygrocybe melleofusca Lodge & Pegler

### Remarks
null


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=fn.support_map_against_support_map_with_params.html">

Redirecting to fn.support_map_against_support_map_with_params.html...


text:
'use strict'

const tap = require('tap')
const url = require('url')
const nock = require('nock')
const supertest = require('supertest')
const proxyquire = require('proxyquire')
const lolex = require('lolex')
const readFixture = require('../read-fixture')

const app = proxyquire('../../app', {
  './github-secret': {
    isValid: () => true,

    // necessary to make makes proxyquire return this stub
    // whenever *any* module tries to require('./github-secret')
    '@global': true
  }
})

tap.test('Sends POST request to https://ci.nodejs.org', (t) => {
  const clock = lolex.install()

  const originalJobUrlValue = process.env.JENKINS_JOB_URL_NODE
  const originalTokenValue = process.env.JENKINS_BUILD_TOKEN_NODE
  process.env.JENKINS_JOB_NODE = 'node-test-pull-request-lite-pipeline'
  process.env.JENKINS_BUILD_TOKEN_NODE = 'myToken'

  const webhookPayload = readFixture('pull-request-opened.json')
  const pipelineUrl = 'https://ci.nodejs.org/blue/organizations/jenkins/node-test-pull-request-lite-pipeline/detail/node-test-pull-request-lite-pipeline/1/pipeline'

  const collaboratorsScope = nock('https://api.github.com')
    .filteringPath(ignoreQueryParams)
    .get('/repos/nodejs/node/collaborators/phillipj')
    .reply(200, { permission: 'admin' })
  const ciJobScope = nock('https://ci.nodejs.org')
    .filteringPath(ignoreQueryParams)
    .post('/blue/rest/organizations/jenkins/pipelines/node-test-pull-request-lite-pipeline/runs/')
    .reply(200, { id: 1 }, {})

  const commentScope = nock('https://api.github.com')
    .filteringPath(ignoreQueryParams)
    .post('/repos/nodejs/node/issues/19/comments', { body: `@phillipj build started: ${pipelineUrl}` })
    .reply(200)

  t.plan(1)
  t.tearDown(() => collaboratorsScope.done() && ciJobScope.done() && commentScope.done() && clock.uninstall())

  supertest(app)
    .post('/hooks/github')
    .set('x-github-event', 'pull_request')
    .send(webhookPayload)
    .expect(200)
    .end((err, res) => {
      process.env.JENKINS_JOB_URL_NODE = originalJobUrlValue
      process.env.JENKINS_BUILD_TOKEN_NODE = originalTokenValue
      clock.runAll()
      t.equal(err, null)
    })
})

function ignoreQueryParams (pathAndQuery) {
  return url.parse(pathAndQuery, true).pathname
}


text:
<!DOCTYPE html>
<html>
<head>
  <title>Test page for MediaSession.java</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
</head>
<body>
  <audio id='very-short-audio' controls>
    <source src='audio-1second.ogg'>
  </audio>
  <audio id='short-audio' controls>
    <source src='audio-4seconds.ogg'>
  </audio>
  <audio id='long-audio' controls>
    <source src='audio-6seconds.ogg'>
  </audio>
  <video id='very-short-video' controls>
    <source src='video-1second.webm'>
  </video>
  <video id='short-video' controls>
    <source src='video-4seconds.webm'>
  </video>
  <video id='long-video' controls>
    <source src='video-6seconds.webm'>
  </video>
  <video id='long-video-silent' controls>
    <source src='video-6seconds-silent.webm'>
  </video>
</body>
</html>


text:
<?php

/**
 * API2 attributes grid container block
 *
 * @category   Mage
 * @package    Mage_Api2
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Api2_Block_Adminhtml_Attribute extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    /**
     * Construct grid container
     */
    public function __construct()
    {
        parent::__construct();

        $this->_blockGroup = 'api2';
        $this->_controller = 'adminhtml_attribute';
        $this->_headerText = $this->__('REST Attributes');
        $this->_removeButton('add');
    }
}


text:
<?php

namespace Helix\UserBundle\Security\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Helix\UserBundle\Security\Authentication\Token\PrismToken;

class PrismProvider implements AuthenticationProviderInterface
{
  protected $userProvider;

  public function __construct(UserProviderInterface $userProvider)
  {
    $this->userProvider = $userProvider;
  }

  public function authenticate(TokenInterface $token)
  {
    $user = $this->userProvider->loadUserByUsername($token->getUsername());
    if ($user && $this->validate($token)) {
      $authenticatedToken = new PrismToken($user->getRoles());
      $authenticatedToken->setUser($user);
      return $authenticatedToken;
    }

    throw new AuthenticationException('The Prism authentication failed.');
  }

  protected function validate($token)
  {
    return true;
  }

  public function supports(TokenInterface $token)
  {
    return $token instanceof PrismToken;
  }
}


text:
PrefServiceSyncable* PrefServiceSyncable::FromProfile(Profile* profile) {
  return static_cast<PrefServiceSyncable*>(profile->GetPrefs());
}

// static
PrefServiceSyncable* PrefServiceSyncable::IncognitoFromProfile(
    Profile* profile) {
  return static_cast<PrefServiceSyncable*>(profile->GetOffTheRecordPrefs());
}

PrefServiceSyncable::PrefServiceSyncable(
    PrefNotifierImpl* pref_notifier,
    PrefValueStore* pref_value_store,
    PersistentPrefStore* user_prefs,
    user_prefs::PrefRegistrySyncable* pref_registry,
    base::Callback<void(PersistentPrefStore::PrefReadError)>
        read_error_callback,
    bool async)
  : PrefService(pref_notifier,
                pref_value_store,
                user_prefs,
                pref_registry,
                read_error_callback,
                async),
    pref_sync_associator_(syncer::PREFERENCES),
    priority_pref_sync_associator_(syncer::PRIORITY_PREFERENCES) {
  pref_sync_associator_.SetPrefService(this);
  priority_pref_sync_associator_.SetPrefService(this);

  // Let PrefModelAssociators know about changes to preference values.
  pref_value_store->set_callback(
      base::Bind(&PrefServiceSyncable::ProcessPrefChange,
                 base::Unretained(this)));

  // Add already-registered syncable preferences to PrefModelAssociator.
  for (PrefRegistry::const_iterator it = pref_registry->begin();
       it != pref_registry->end(); ++it) {
    const std::string& path = it->first;
    AddRegisteredSyncablePreference(path,
                                    pref_registry_->GetRegistrationFlags(path));
  }

  // Watch for syncable preferences registered after this point.
  pref_registry->SetSyncableRegistrationCallback(
      base::Bind(&PrefServiceSyncable::AddRegisteredSyncablePreference,
                 base::Unretained(this)));
}

PrefServiceSyncable::~PrefServiceSyncable() {
  // Remove our callback from the registry, since it may outlive us.
  user_prefs::PrefRegistrySyncable* registry =
      static_cast<user_prefs::PrefRegistrySyncable*>(pref_registry_.get());
  registry->SetSyncableRegistrationCallback(
      user_prefs::PrefRegistrySyncable::SyncableRegistrationCallback());
}

PrefServiceSyncable* PrefServiceSyncable::CreateIncognitoPrefService(
    PrefStore* incognito_extension_prefs) {
  pref_service_forked_ = true;
  PrefNotifierImpl* pref_notifier = new PrefNotifierImpl();
  OverlayUserPrefStore* incognito_pref_store =
      new OverlayUserPrefStore(user_pref_store_.get());
  PrefsTabHelper::InitIncognitoUserPrefStore(incognito_pref_store);

  scoped_refptr<user_prefs::PrefRegistrySyncable> forked_registry =
      static_cast<user_prefs::PrefRegistrySyncable*>(
          pref_registry_.get())->ForkForIncognito();
  PrefServiceSyncable* incognito_service = new PrefServiceSyncable(
      pref_notifier,
      pref_value_store_->CloneAndSpecialize(NULL,  // managed
                                            NULL,  // supervised_user
                                            incognito_extension_prefs,
                                            NULL,  // command_line_prefs
                                            incognito_pref_store,
                                            NULL,  // recommended
                                            forked_registry->defaults().get(),
                                            pref_notifier),
      incognito_pref_store,
      forked_registry.get(),
      read_error_callback_,
      false);
  return incognito_service;
}

bool PrefServiceSyncable::IsSyncing() {
  return pref_sync_associator_.models_associated();
}

bool PrefServiceSyncable::IsPrioritySyncing() {
  return priority_pref_sync_associator_.models_associated();
}

bool PrefServiceSyncable::IsPrefSynced(const std::string& name) const {
  return pref_sync_associator_.IsPrefSynced(name) ||
         priority_pref_sync_associator_.IsPrefSynced(name);
}

void PrefServiceSyncable::AddObserver(PrefServiceSyncableObserver* observer) {
  observer_list_.AddObserver(observer);
}

void PrefServiceSyncable::RemoveObserver(
    PrefServiceSyncableObserver* observer) {
  observer_list_.RemoveObserver(observer);
}

syncer::SyncableService* PrefServiceSyncable::GetSyncableService(
    const syncer::ModelType& type) {
  if (type == syncer::PREFERENCES) {
    return &pref_sync_associator_;
  } else if (type == syncer::PRIORITY_PREFERENCES) {
    return &priority_pref_sync_associator_;
  } else {
    NOTREACHED() << "invalid model type: " << type;
    return NULL;
  }
}

void PrefServiceSyncable::UpdateCommandLinePrefStore(
    PrefStore* cmd_line_store) {
  // If |pref_service_forked_| is true, then this PrefService and the forked
  // copies will be out of sync.
  DCHECK(!pref_service_forked_);
  PrefService::UpdateCommandLinePrefStore(cmd_line_store);
}

void PrefServiceSyncable::AddSyncedPrefObserver(
    const std::string& name,
    SyncedPrefObserver* observer) {
  pref_sync_associator_.AddSyncedPrefObserver(name, observer);
  priority_pref_sync_associator_.AddSyncedPrefObserver(name, observer);
}

void PrefServiceSyncable::RemoveSyncedPrefObserver(
    const std::string& name,
    SyncedPrefObserver* observer) {
  pref_sync_associator_.RemoveSyncedPrefObserver(name, observer);
  priority_pref_sync_associator_.RemoveSyncedPrefObserver(name, observer);
}

void PrefServiceSyncable::AddRegisteredSyncablePreference(
    const std::string& path,
    uint32 flags) {
  DCHECK(FindPreference(path));
  if (flags & user_prefs::PrefRegistrySyncable::SYNCABLE_PREF) {
    pref_sync_associator_.RegisterPref(path.c_str());
  } else if (flags &
             user_prefs::PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF) {
    priority_pref_sync_associator_.RegisterPref(path.c_str());
  }
}

void PrefServiceSyncable::OnIsSyncingChanged() {
  FOR_EACH_OBSERVER(PrefServiceSyncableObserver, observer_list_,
                    OnIsSyncingChanged());
}

void PrefServiceSyncable::ProcessPrefChange(const std::string& name) {
  pref_sync_associator_.ProcessPrefChange(name);
  priority_pref_sync_associator_.ProcessPrefChange(name);
}


text:
const config = {
  apiKey: 'AIzaSyD96bU6vE86pPVuM4Fzy_eZ6ZxvAYtmn7o',
  baseUrl: 'https://maps.googleapis.com/maps/api/place/',
};

export default config;


text:
import {ResourceAbstract} from './resource';

export class CompaniesAPI extends ResourceAbstract {

  endpoint = 'api/v1.0/companies';

  resourceName = 'companies';
}


text:
#import "NSObject.h"

// Not exported
@interface PBBulletProperties : NSObject
{
}

+ (void)writeBulletProperties:(id)arg1 toBulletStyle:(struct PptParaProperty9 *)arg2 state:(id)arg3;
+ (id)readBulletProperties:(struct PptParaProperty9 *)arg1 state:(id)arg2;

@end


text:
import sys

import recipe_util  # pylint: disable=F0401

# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=W0232
class DepotTools(recipe_util.Recipe):
  """Basic Recipe class for DepotTools."""

  @staticmethod
  def fetch_spec(props):
    url = 'http://github.com/npe9/depot_tools.git',
    solution = {
        'name'        : 'depot_tools',
        'url'         : url,
        'deps_file'   : 'DEPS',
        'managed'     : False,
    }
    spec = {
      'solutions': [solution],
      'auto': True,
    }
    checkout_type = 'gclient_git_svn'
    if props.get('nosvn'):
      checkout_type = 'gclient_git'
    spec_type = '%s_spec' % checkout_type
    return {
      'type': checkout_type,
      spec_type: spec,
    }

  @staticmethod
  def expected_root(_props):
    return 'depot_tools'

def main(argv=None):
  return DepotTools().handle_args(argv)

if __name__ == '__main__':
  sys.exit(main(sys.argv))


text:
#ifndef SimTK_SimTKCOMMON_MEASURE_H_
#define SimTK_SimTKCOMMON_MEASURE_H_

/** @file
 *
 * This file declares the base class AbstractMeasure for all derived Measure
 * handle classes, and the handle classes for built-in Measures. Measure
 * handles provide the end user API, while the implementations of Measures
 * derive from the abstract Measure::Implementation class defined in
 * MeasureImplementation.h. Measure Implementation classes provide the Measure
 * developer's API.
 */

#include "SimTKcommon/basics.h"
#include "SimTKcommon/Simmatrix.h"

#include <cassert>

/**
 * Every concrete measure handle class "MH" derived from a parent handle "PH"
 * that derives directly or indirectly from the AbstractMeasure handle class
 * should include the macro SimTK_MEASURE_HANDLE_PREAMBLE(MH,PH) at the
 * beginning of the public section of its declaration. It performs the following
 * declarations:
 *

 *   MH::Implementation         the handle's local implementation class
 *   MH::MH()                   default constructor creates an empty handle
 *   MH::MH(Implementation*)    create a handle referencing an existing object
 *   MH::MH(Subsystem&, Implementation*)
 *                              create a handle referencing an existing but
 *                                unowned object, then installs that in the
 *                                given Subsystem which becomes the owner
 *

 *
 * MH::Implementation must be defined elsewhere as a class derived
 * from Measure::Implementation.
 */

// Helper macro shared by SimTK_MEASURE_HANDLE_PREAMBLE and
// SimTK_MEASURE_HANDLE_PREAMBLE_ABSTRACT.
#define SimTK_MEASURE_HANDLE_PREAMBLE_BASE(MH,PH) \
    class Implementation;                                           \
    explicit MH(Implementation* imp) : PH(imp) {}                   \
    MH(SimTK::Subsystem& sub, Implementation* imp,                  \
       const SimTK::AbstractMeasure::SetHandle& sh)                 \
    :   PH(sub,imp,sh) {}                                           \
    MH& operator=(const MH& src) {PH::operator=(src); return *this;}\
    MH& shallowAssign(const MH& src) {PH::shallowAssign(src); return *this;}\
    MH& deepAssign(const MH& src) {PH::deepAssign(src); return *this;}

// The default constructor for concrete classes should instantiate
// a default-constructed Implementation object if no Implementation object
// is provided.
#define SimTK_MEASURE_HANDLE_PREAMBLE(MH,PH)    \
    SimTK_MEASURE_HANDLE_PREAMBLE_BASE(MH,PH)   \
    MH() : PH(new Implementation()) {}          \
    explicit MH(SimTK::Subsystem& sub)          \
    : PH(sub,new Implementation(), typename PH::SetHandle()) {}

// The default constructor for a still-abstract derived class can't
// instantiate an Implementation.
#define SimTK_MEASURE_HANDLE_PREAMBLE_ABSTRACT(MH,PH)   \
    SimTK_MEASURE_HANDLE_PREAMBLE_BASE(MH,PH)           \
    MH() : PH() {}

/**
 * Every measure handle class "MH" derived directly or indirectly from the
 * abstract measure handle class "Measure" should include this macro at
 * the end of the "public" section of its declaration. The macro expects
 * there to be a local class, MH::Implementation,
 * already declared. (MH::Implementation is the type of MH's
 * implementation object to be derived from Measure::Implementation
 * and defined elsewhere.) Then the following
 * type-safe downcast methods will be added to MH's definition:
 *

 *   MH::getAs(const AbstractMeasure&)  generic handle to const MH (static)
 *   MH::updAs(AbstractMeasure&)        generic handle to writable MH (static)
 *   MH::isA(AbstractMeasure&)          test if generic handle is of type MH
 *   getImpl()  generic implementation to const MH::Implementation
 *   updImpl()  generic implementation to writable MH::Implementation
 *

 * Type checking for the handle class conversions is done only in Debug
 * builds.
 */
#define SimTK_MEASURE_HANDLE_POSTSCRIPT(MH,PH) \
    static bool isA(const SimTK::AbstractMeasure& m)                        \
    {   return dynamic_cast<const Implementation*>(&m.getImpl()) != 0; }    \
    static const MH& getAs(const SimTK::AbstractMeasure& m)                 \
    {   assert(isA(m)); return static_cast<const MH&>(m); }                 \
    static MH& updAs(SimTK::AbstractMeasure& m)                             \
    {   assert(isA(m)); return static_cast<MH&>(m); }                       \
    const Implementation& getImpl() const                                   \
    {   return SimTK_DYNAMIC_CAST_DEBUG<const Implementation&>              \
                    (SimTK::AbstractMeasure::getImpl());}                   \
    Implementation& updImpl()                                               \
    {   return SimTK_DYNAMIC_CAST_DEBUG<Implementation&>                    \
                    (SimTK::AbstractMeasure::updImpl());}

namespace SimTK {

class State;
class Subsystem;
class System;
class EventId;

/// Define a unique integral type for safe indexing of Measures.
SimTK_DEFINE_UNIQUE_INDEX_TYPE(MeasureIndex);

//==============================================================================
//                            ABSTRACT MEASURE
//==============================================================================
/** This is the base class for all Measure handle classes. This class is not
templatized, and represents a Measure generically without knowledge of its
value type. This is useful for most of the basic operations that are
performed on measures, such as realization, adoption by a Subsystem, and
other bookkeeping tasks. For most user purposes, the still-generic derived
class Measure_<T> is a more useful handle since its value, of known type T,
can be obtained. All the built-in concrete Measure types derive from
Measure_<T> rather than AbstractMeasure. The various concrete Measures,
built in or otherwise, may set restrictions on the kinds of types that
are allowable as the template argument.

Note that handles always consist of exactly one pointer, and handle classes
are always concrete (meaning they have no virtual methods). **/
class SimTK_SimTKCOMMON_EXPORT AbstractMeasure {
protected:
	/// An object of this type is used as a dummy argument to make sure the
    /// automatically-generated handle constructor's signature doesn't conflict
    /// with an explicitly-defined one.
	class SetHandle {};

public:
    class Implementation; // local; name is AbstractMeasure::Implementation

    /// Provide an Implementation for this AbstractMeasure and bump its
    /// reference count. This is also the default constructor for the
    /// base class producing an empty handle.
    explicit AbstractMeasure(Implementation* g=0);

    /// Construct this handle with a given Implementation object (whose
    /// reference count will be bumped) and then let the given Subsystem
    /// adopt this Measure (which will again bump the Implementation's
    /// reference count, leaving us with two new handles).
    AbstractMeasure(Subsystem&, Implementation* g, const SetHandle&);

    /// Shallow copy constructor copies the pointer from the source
    /// Implementation object and bumps its reference count.
    AbstractMeasure(const AbstractMeasure&);

    /// Shallow assignment operator results in this handle referencing
    /// the same Implementation object as does the source.
    /// @see shallowAssign for more details
    AbstractMeasure& operator=(const AbstractMeasure& source)
    {   return shallowAssign(source); }

    /// Destructor decrements the Implementation's reference count and
    /// deletes the object if the count goes to zero.
    ~AbstractMeasure();

    /// Shallow assignment operator destructs the current Implementation
    /// object (meaning its reference count is decremented and the object
    /// actually deleted only if the count goes to zero), then copies the
    /// Implementation pointer from the source and bumps its reference count.
    /// This is what the copy assignment operator= does for this class.
    AbstractMeasure& shallowAssign(const AbstractMeasure&);

    /// Deep assignment clones the Implementation object pointed to by
    /// the source handle, so that this handle ends up pointing to a
    /// new Measure object similar to the original but not yet contained
    /// in any Subsystem.
    AbstractMeasure& deepAssign(const AbstractMeasure& source);

    /// Every Measure can produce a value, and some can provide one or
    /// more total derivatives with respect to time of that value. This
    /// method reports how many are available: 1 -> first derivative
    /// d/dt is available, 2 -> first and second derivative d^2/dt^2
    /// are available, etc. We interpret the "0th derivative" to be the
    /// Measure's value.
    /// @return The maximum available derivative order.
    int getNumTimeDerivatives() const;

    /// At what Stage can we expect the value of this AbstractMeasure or
    /// one of its time derivatives to be available? Users of Measures will
    /// typically impose restrictions on the levels they will accept.
    /// @param[in] derivOrder
    ///     Which derivative level is to be checked: 0 -> the value,
    ///     1 -> the 1st time derivative, etc. Must not be higher than the
    ///     value returned by getNumTimeDerivatives().
    /// @return The Stage after which this value is available.
    Stage getDependsOnStage(int derivOrder=0) const;

    /// There can be multiple handles on the same Measure.
    bool isSameMeasure(const AbstractMeasure& other) const
    {   return impl && impl==other.impl;}

    bool isEmptyHandle() const {return !hasImpl();}

    /// Test whether this Measure object has been adopted by a Subsystem.
    bool isInSubsystem() const;
    /// Return a reference to the Subsystem that owns this Measure. Will
    /// throw an exception if the Measure is not currently owned by any
    /// Subsystem.
    const Subsystem& getSubsystem()  const;
    /// Return the MeasureIndex by which this Measure is known to the Subsystem
    /// that owns it. Will throw an exception if the Measure is not currently
    /// owned by any Subsystem.
    MeasureIndex getSubsystemMeasureIndex() const;

    // Internal use only

    // dynamic_cast the returned reference to a reference to your concrete
    // Implementation class.
    const Implementation& getImpl() const {assert(impl); return *impl;}
    Implementation&       updImpl()       {assert(impl); return *impl;}
    bool                  hasImpl() const {return impl!=0;}

    int getRefCount() const;
private:
    // This is the only data member in this class. Also, any class derived
    // from AbstractMeasure must have *NO* data members at all (data goes
    // in the Implementation class).
    Implementation* impl;

friend class Implementation;
};

//==============================================================================
//                               MEASURE <T>
//==============================================================================
/** This is the base handle class for all Measures whose value type is known,
including all the Simbody built-in %Measure types. **/
template <class T>
class Measure_ : public AbstractMeasure {
public:
    /** This class is still abstract so we don't want it to allocate an
    Implementation object in its default constructor. **/
    SimTK_MEASURE_HANDLE_PREAMBLE_ABSTRACT(Measure_, AbstractMeasure);

    /** Retrieve the Value of this Measure or one of its time derivatives,
    assuming the supplied State has been realized to at least the required
    stage for the selected value or derivative, as reported by
    getDependsOnStage(). If the stage is sufficient but the corresponding
    value has not yet been computed, it will be computed first with its
    value going into this State's cache so that subsequent calls do not
    require further computation. **/
    const T& getValue(const State& s, int derivOrder=0) const
    {   return getImpl().getValue(s,derivOrder); }

    /** Change the default value associated with this %Measure. How this is
    used varies with the %Measure type but generally it is the value that
    the %Measure will have before any calculations are performed. Note
    that this does not require a State since it is a Topology-stage
    change; you have to call realizeTopology() again if you call this
    method. **/
    Measure_& setDefaultValue(const T& defaultValue)
    {   updImpl().setDefaultValue(defaultValue); return *this; }

    /** Obtain a reference to the default value associated with
    this %Measure. **/
    const T& getDefaultValue() const
    {   return getImpl().getDefaultValue(); }

    // These are built-in Measures with local class names.

    // Templatized measures may have restrictions on the allowable template
    // type and may be specialized for particular types.
    class Zero;         // T is any numerical type
    class One;          // T is any numerical type
    class Constant;     // T is any assignable type
    class Time;         // T is any type for which T(t) makes sense.
    class Variable;     // T is any assignable type (state)
    class Result;       // T is any assignable type (cache)
    class SampleAndHold;// T is any assignable type
    class Delay;        // T is any assignable type

    // This requires any numerical type.
    class Plus;
    class Minus;
    class Scale;
    class Differentiate;

    // These find extreme values *in time*, not among inputs at the same
    // time. They perform elementwise on aggregate types.
    class Extreme;  // base class for min/max/minabs/maxabs
    class Minimum;  // most positive value
    class Maximum;  // most negative value
    class MinAbs;   // the signed quantity whose absolute value was min
    class MaxAbs;   // the signed quantity whose absolute value was max

    // These accept floating point numerical template arguments only.
    class Integrate;
    class Sinusoid;

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Measure_, AbstractMeasure);
};

/** This typedef is a convenient abbreviation for the most common kind of
%Measure -- one that returns a single Real result; the underlying class is
Measure_; look there for documentation. **/
typedef Measure_<Real> Measure;

//==============================================================================
//                                CONSTANT
//==============================================================================
/** This creates a Measure whose value is a Topology-stage constant of any
type T. This does not have to be part of a Subsystem, but if it is then changing
the constant's value invalidates the containing Subsystem's Topology.
@tparam T   This can be any type that supports copy construction. **/
template <class T>
class Measure_<T>::Constant : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Constant, Measure_<T>);

    /** Create a constant measure that is not part of any Subsystem, and
    provide the constant value. **/
    explicit Constant(const T& value)
    :   Measure_<T>(new Implementation(value)) {}

    /** Create a constant measure with the given \a value and install it into
    the given Subsystem. **/
    Constant(Subsystem& sub, const T& value)
    :   Measure_<T>(sub, new Implementation(value),
                    AbstractMeasure::SetHandle()) {}

    /** Change the value returned by this %Measure. Note that this does not
    require a State since it is a Topology-stage change. **/
    Constant& setValue(const T& value)
    {   updImpl().setValue(value); return *this; }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Constant, Measure_<T>);
};

//==============================================================================
//                                   ZERO
//==============================================================================
/** This creates a Measure::Constant whose value is always T(0) and can't be
changed. This class is specialized for Vector so that you must provide a
size at construction. **/
template <class T>
class Measure_<T>::Zero : public Measure_<T>::Constant {
public:
    Zero();
    explicit Zero(Subsystem& sub);
};

template <>
class Measure_< Vector >::Zero : public Measure_< Vector >::Constant {
public:
    explicit Zero(int size);
    Zero(Subsystem& sub, int size);
};

//==============================================================================
//                                    ONE
//==============================================================================
/** This creates a Measure::Constant whose value is always T(1) and can't be
changed. This class is specialized for Vector so that you must provide a
size at construction. **/
template <class T>
class Measure_<T>::One : public Measure_<T>::Constant {
public:
    One();
    explicit One(Subsystem& sub);
};

template <>
class Measure_< Vector >::One : public Measure_< Vector >::Constant {
public:
    explicit One(int size);
    One(Subsystem& sub, int size);
};

//==============================================================================
//                                   TIME
//==============================================================================
/** This creates a Measure::Time whose value is always T(time). **/
template <class T>
class Measure_<T>::Time : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Time, Measure_<T>);

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Time, Measure_<T>);
};

//==============================================================================
//                                 VARIABLE
//==============================================================================
/** This creates a Measure whose value is a discrete State variable of any
type T. **/
template <class T>
class Measure_<T>::Variable : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Variable, Measure_<T>);

    // TODO: should not require invalidated Stage here. Instead,
    // should have a unique "generation" counter for this variable
    // and allow subsequent users to check it.
    Variable(Subsystem& sub, Stage invalidates, const T& defaultValue)
    :   Measure_<T>(sub, new Implementation(invalidates, defaultValue),
                    AbstractMeasure::SetHandle()) {}

    void setValue(State& state, const T& value) const
    {   getImpl().setValue(state, value); }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Variable, Measure_<T>);
};

//==============================================================================
//                                 RESULT
//==============================================================================
/** This Measure holds the result of some externally-determined computation,
and helps to coordinate the validity of that computation with respect
to the state variables. The value must be set manually and explicitly
marked valid when it is complete. The value will be automatically
invalidated after a state change at or below a specified Stage, and changing
the value here will automatically invalidate a specified Stage and above.

In constrast to Measure::Variable, Measure::Result is not a state variable;
it is a cache variable meaning that it works with a const State. It is
expected that the result can be recalculated from the state variables when
needed, or contains ephemeral information that can be discarded.

No provision for derivatives is made; there is only the one result. **/
template <class T>
class Measure_<T>::Result : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Result, Measure_<T>);

    // TODO: should not require invalidated Stage here. Instead,
    // should have a unique "generation" counter for this cache entry
    // and allow subsequent users of the value to check it.

    /// Create a new Result measure and add it to the indicated
    /// subsystem. The Result measure's value depends on earlier
    /// values calculated at \a dependsOn stage, so whenever that
    /// stage or earlier is invalidated, so is the value here.
    /// In addition, any change made to the value here will invalidate
    /// stage \a invalidated and all subsequent stages. The
    /// \a invalidated stage must be later than the \a dependsOn stage,
    /// and you cannot update the value here in a state that hasn't
    /// already been realized to the dependsOn stage.
    /// Set \a dependsOn = Stage::Empty if your value computation doesn't
    /// depend on anything else (that will be interpreted as Stage::Topology,
    /// however, since space for the value gets allocated then).
    /// Set \a invalidated = Stage::Infinity if you don't want anything
    /// invalidated when this value is changed.
    Result(Subsystem& sub, Stage dependsOn, Stage invalidated)
    :   Measure_<T>(sub, new Implementation(dependsOn, invalidated),
                    AbstractMeasure::SetHandle()) {}

    /// Get the \a dependsOn stage for this measure's value.
    Stage getDependsOnStage() const {return getImpl().getDependsOnStage();}
    /// Get the \a invalidated stage for this measure's value.
    Stage getInvalidatedStage() const {return getImpl().getInvalidatedStage();}
    /// Change the \a dependsOn stage for this measure's value, which must
    /// be strictly less than the current setting for the \a invalidated
    /// stage. If you set the dependsOn stage to Stage::Empty it will be
    /// interpreted as Stage::Topology since the value must always depend
    /// on at least topology. Setting the dependsOn stage is itself a
    /// topological change requiring reallocation of the value if it has
    /// already been allocated; you must call realizeTopology() again.
    Result& setDependsOnStage(Stage dependsOn)
    {   updImpl().setDependsOnStage(dependsOn); return *this; }
    /// Change the \a invalidated stage for this measure's value, which must
    /// be strictly greater than the current setting for the \a dependsOn
    /// stage. This is a topological change requiring reallocation of the
    /// value if it has already been allocated; you must call
    /// realizeTopology() again.
    Result& setInvalidatedStage(Stage invalidated)
    {   updImpl().setInvalidatedStage(invalidated); return *this; }

    /// Normally a Result measure's value is not considered valid unless
    /// we are notified explicitly that it is, via a call to markAsValid()
    /// or setValue(); this method allows the value to be assumed valid
    /// after the \a dependsOn stage has been realized. The reason this
    /// exists is that in some cases it is difficult to find a place from
    /// which to call markAsValid(). That means you must set the value during
    /// realization of the dependsOn stage, but there is no way for this to
    /// be checked automatically. Thus use of this feature can lead
    /// to very difficult-to-find bugs; you should try hard to find a place
    /// to call markAsValid() before resorting to this method. This is a
    /// topological change requiring reallocation of the value if it has
    /// already been allocated; you must call realizeTopology() again.
    Result& setIsPresumedValidAtDependsOnStage(bool presume)
    {   updImpl().setIsPresumedValidAtDependsOnStage(presume); return *this; }

    /// Return the value of the "presumed valid at dependsOn stage" flag.
    /// @see setIsPresumedValidAtDependsOnStage() for a discussion.
    bool getIsPresumedValidAtDependsOnStage() const
    {   return getImpl().getIsPresumedValidAtDependsOnStage(); }

    /// Obtain write access to the Measure's value in order to modify it.
    /// Calling this method marks the result invalid; you must explicitly
    /// validate it when you're done. Also, if this Measure was created with
    /// an \a invalidates stage, then that stage and all later stages in
    /// the given state are marked invalid also.
    T& updValue(const State& state) const
    {   return getImpl().updValue(state); }

    /// Mark the current value as valid. This is done automatically if you
    /// call setValue() but must be done manually if you use updValue() to
    /// access the value. Note that you cannot mark this valid if
    /// \a state hasn't been realized already to at least the stage prior
    /// to this measure's \a dependsOn stage; that is, you must at least
    /// be working on the dependsOn stage at the time this is called.
    void markAsValid(const State& state) const {getImpl().markAsValid(state);}

    /// Check whether the value contained in this Measure is currently
    /// valid. If true, you can call getValue() to obtain it. If false,
    /// calling getValue() will throw an exception.
    bool isValid(const State& state) const {return getImpl().isValid(state);}

    /// Manually mark the contained value as invalid. This will also
    /// invalidate any stages in \a state that depend on this value. This
    /// is called automatically whenever the updValue() method is invoked,
    /// and the value starts out invalid. The value becomes valid either
    /// by calling markAsValid() explicitly or calling setValue().
    /// @warning If you have set this Result measure to be presumed valid
    /// at dependsOn stage, this method will have no effect.
    void markAsNotValid(const State& state) const
    {   getImpl().markAsNotValid(state); }

    /// Set a new value and mark it as valid. For more flexibility, use the
    /// updValue() method and markAsValid() manually when you are done with
    /// the new value.
    void setValue(const State& state, const T& value) const
    {   updValue(state) = value; markAsValid(state); }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Result, Measure_<T>);
};

//==============================================================================
//                                 SINUSOID
//==============================================================================
/** This measure produces a sinusoidal function of time:

     m(t) = a*sin(w*t+p)

where a=amplitude in arbitrary units, w=frequency in rad/unit time, p=phase
in radians. **/
template <class T>
class Measure_<T>::Sinusoid : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Sinusoid, Measure_<T>);

    Sinusoid(Subsystem& sub,
             const T& amplitude,
             const T& frequency,
             const T& phase=T(0))
    :   Measure_<T>(sub, new Implementation(amplitude,frequency,phase),
                    AbstractMeasure::SetHandle()) {}

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Sinusoid, Measure_<T>);
};

//==============================================================================
//                                   PLUS
//==============================================================================
/** This Measure is the sum of two Measures of the same type T.
@tparam T    Any type that supports a plus operator that returns a sum
             as another object of type T. In particular, Real, Vec<N>,
             and Vector will work. **/
template <class T>
class Measure_<T>::Plus : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Plus, Measure_<T>);

    Plus(Subsystem& sub, const Measure_<T>& left, const Measure_<T>& right)
    :   Measure_<T>(sub, new Implementation(left, right),
                    AbstractMeasure::SetHandle())
    {   SimTK_ERRCHK_ALWAYS
           (   this->getSubsystem().isSameSubsystem(left.getSubsystem())
            && this->getSubsystem().isSameSubsystem(right.getSubsystem()),
            "Measure_<T>::Plus::ctor()",
            "Arguments must be in the same Subsystem as this Measure.");
    }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Plus, Measure_<T>);
};

//==============================================================================
//                                   MINUS
//==============================================================================
/** This Measure is the difference of two Measures of the same type T.
@tparam T    Any type that supports a subtract operator that returns the
             difference as another object of type T. In particular, Real,
             Vec<N>, and Vector will work. **/
template <class T>
class Measure_<T>::Minus : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Minus, Measure_<T>);

    Minus(Subsystem& sub, const Measure_<T>& left, const Measure_<T>& right)
    :   Measure_<T>(sub, new Implementation(left, right),
                    AbstractMeasure::SetHandle())
    {   SimTK_ERRCHK_ALWAYS
           (   this->getSubsystem().isSameSubsystem(left.getSubsystem())
            && this->getSubsystem().isSameSubsystem(right.getSubsystem()),
            "Measure_<T>::Minus::ctor()",
            "Arguments must be in the same Subsystem as this Measure.");
    }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Minus, Measure_<T>);
};

//==============================================================================
//                                   SCALE
//==============================================================================
/** This Measure multiplies some other Measure by a Real scale factor.
@tparam T    Any type that supports a scalar multiply, with the scalar on
             the left, that returns the product as another object of type T.
             In particular, Real, Vec<N>, and Vector will work. **/
template <class T>
class Measure_<T>::Scale : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Scale, Measure_<T>);

    Scale(Subsystem& sub, Real factor, const Measure_<T>& operand)
    :   Measure_<T>(sub, new Implementation(factor, operand),
                    AbstractMeasure::SetHandle())
    {   SimTK_ERRCHK_ALWAYS
           (this->getSubsystem().isSameSubsystem(operand.getSubsystem()),
            "Measure_<T>::Scale::ctor()",
            "Argument must be in the same Subsystem as this Measure.");
    }

    /** Get the operand (thing being scaled) measure for this measure. **/
    const Measure_<T>& getOperandMeasure() const
    { return getImpl().getOperandMeasure(); }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Scale, Measure_<T>);
};

//==============================================================================
//                                 INTEGRATE
//==============================================================================
/** This measure yields the time integral of a given derivative measure,
initializing with an initial condition measure of the same type T. The type
T can be Real or a fixed size Vec type like Vec<3>, or a variable-size
Vector. But in the case of a Vector you must say at construction what size
the Vector will be during the simulation, so that an appropriate number
of state variables can be allocated. **/
template <class T>
class Measure_<T>::Integrate : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Integrate, Measure_<T>);

    /** Create a new measure that will use %Measure \a ic's value for initial
    conditions, and then integrate the \a deriv %Measure. If type T is a
    variable-length Vector you must also provide a const Vector to be used
    to size and initialized the number of state variables at allocation. In
    that case both the \a ic and \a deriv measures must return Vector values
    of the same size as the allocation constant. **/
    Integrate(Subsystem&            subsystem,
              const Measure_<T>&    deriv,
              const Measure_<T>&    ic,
              const T&              initAlloc=T(0))
    :   Measure_<T>(subsystem, new Implementation(deriv,ic,initAlloc),
                    AbstractMeasure::SetHandle()) {}

    /** Set the current value of this measure by modifying the state variables
    that hold the integral. **/
    void setValue(State& s, const T& value) const
    {   return getImpl().setValue(s, value); }

    /** Get the integrand (derivative) measure for this integral. **/
    const Measure_<T>& getDerivativeMeasure() const

    {   return getImpl().getDerivativeMeasure(); }
    /** Get the measure whose value is used as an initial condition for the
    integral at the start of an integration. **/
    const Measure_<T>& getInitialConditionMeasure() const
    {   return getImpl().getInitialConditionMeasure(); }

    Integrate& setDerivativeMeasure(const Measure_<T>& d)
    {   updImpl().setDerivativeMeasure(d); return *this; }
    Integrate& setInitialConditionMeasure(const Measure_<T>& ic)
    {   updImpl().setInitialConditionMeasure(ic); return *this; }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Integrate, Measure_<T>);
};

//==============================================================================
//                               DIFFERENTIATE
//==============================================================================
/** This Measure operator returns the time derivative of its operand measure,
or a numerical approximation of the time derivative if an analytic one is not
available.

If the operand measure provides its own derivative measure, then the value of
the Differentiate operator is just the value of the operand's derivative
measure, and this measure will have one fewer available derivatives than does
the operand. If the operand does not have a derivative, then we will estimate
it by the following method:
    - retrieve the previous value f0 and previous derivative fdot0 of the
      operand measure, and their sample time t0
    - obtain the current value f(t) of the operand
    - estimate fdot(t)=2(f-f0)/(t-t0) - fdot0  (fit a quadratic)
    - record new samples f(t), fdot(t) with timestamp t

Special cases:
    - if t==t0 then fdot(t)=fdot0 (if available) else fdot(t)=0
    - if fdot0 not available, fdot(t)=(f-f0)/(t-t0) (first order estimate)

At initialization of a timestepping study beginning at t=t0, we sample the
operand and record its initial value f0 at t0, and set fdot0=NaN. This
ensures that we'll return zero as the initial derivative (for lack of anything
better) and then use the first order method for the first step's derivative.
**/
template <class T>
class Measure_<T>::Differentiate : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Differentiate, Measure_<T>);

    /** Create a measure whose value is the time derivative of the given
    \a operand measure.
    @param  subsystem   The Subsystem into which this measure will be placed.
    @param  operand     The Measure to be differentiated. **/
    Differentiate(Subsystem& subsystem, const Measure_<T>& operand)
    :   Measure_<T>(subsystem, new Implementation(operand),
                    AbstractMeasure::SetHandle()) {}

    /** Test whether the derivative returned as the value of this measure is
    being estimated numerically, either because the operand measure is unable
    to supply its derivative or because setForceUseApproximation(true) has
    been called. **/
    bool isUsingApproximation() const
    {   return getImpl().isUsingApproximation(); }

    /** Get a reference to the measure that is being differentiated by this
    measure. **/
    const Measure_<T>& getOperandMeasure() const
    {   return getImpl().getOperandMeasure(); }

    /** Set the measure that is to be differentiated by this measure. This is
    a topology-stage change so you'll have to call realizeTopology() again on
    the enclosing System before using it. **/
    Differentiate& setOperandMeasure(const Measure_<T>& operand)
    {   updImpl().setOperandMeasure(operand); return *this; }

    /** Force use of numerical approximation for the derivative, even if the
    operand measure can supply its own derivative. This is not recommended!
    This is a Topology-stage change. **/
    void setForceUseApproximation(bool mustApproximate)
    {   updImpl().setForceUseApproximation(mustApproximate); }

    /** Check the current value of the flag which forces this measure to use
    numerical approximation regardless of whether the operand can supply its
    own derivative. Note that even if the flag is currently false (the default)
    we may still have to use approximation; see isUsingApproximation(). **/
    bool getForceUseApproximation() const
    {   return getImpl().getForceUseApproximation(); }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Differentiate, Measure_<T>);
};

//==============================================================================
//                 EXTREME, MINIMUM, MAXIMUM, MINABS, MAXABS
//==============================================================================
/** This Measure tracks extreme values attained by the elements of its source
operand since the last initialize() call or explicit call to setValue(). The
extreme is either minimum or maximum and may be determined by the actual or
absolute value of the operand. In any case the value of the %Extreme measure is
the actual extreme value of the operand, not its absolute value.

The template type T must be the same as the template type of the operand
measure. If T is a Vec or Vector type, each element is treated separately.

Normally %Extreme is not used directly; it is the common implementation
underlying the Minimum, Maximum, MinAbs, and MaxAbs measures.

Information available from this Measure:
    - the current extreme value (at the source's stage)
    - the value at the start of the current step (Time stage)
    - time of last change
    - the DiscreteVariableIndex holding the previous value
    - the CacheEntryIndex designated for the current/next value
    - a reference to the source Measure

The time derivative fdot of f(t)=min_t0_t(s(t')) where s is the
source measure and t0 <= t' <= t is

     fdot(t) = s(t) < f(ti) && sdot(t) < 0 ? sdot(t) : 0

where ti is the time at the start of the current step.

At the start of a continuous interval, the updated value (if any)
replaces the stored value.

Extreme isolation (not implemented yet)

If the time derivative of the
source operand is available, the measure will arrange to ensure
precise isolation of the minimum values by defining a triggered
event that watches for negative-to-positive sign changes of the derivative.
Then if you output reporting data upon the occurrence of triggered
events (as well as your regularly scheduled output) your data will
include the precise minimum (to within a specifiable isolation time window).

Additional information available in this case:
    - the EventId of the extreme-trapping event if there is one
    - the time derivative of the Extreme measure
**/
template <class T>
class Measure_<T>::Extreme : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(Extreme, Measure_<T>);

    enum Operation {
        MaxAbs, // default
        Maximum,
        MinAbs,
        Minimum
    };

    /** Default behavior for the %Extreme measure is to find the operand's
    value that is of maximum absolute value. You can change that to minimum
    and/or actual value. **/
    Extreme(Subsystem& sub, const Measure_<T>& operand, Operation op=MaxAbs)
    :   Measure_<T>(sub, new Implementation(operand, op),
                    AbstractMeasure::SetHandle()) {}

    /** Set the operation to be performed. The default operation is MaxAbs. **/
    Extreme& setOperation(Operation op)
    {   updImpl().setOperation(op); return *this; }

    /** Return the operation currently being performed by this measure. **/
    Operation getOperation() const {return getImpl().getOperation();}

    /** Return the time at which the reported extreme value first occurred.
    This is the current time if the operand is at its extreme value now,
    otherwise it is the time that the extreme value first occurred during a
    time stepping study. The \a state must be realized to the level required
    to evaluate the operand measure. **/
    Real getTimeOfExtremeValue(const State& state) const
    {   return getImpl().getTimeOfExtremeValue(state); }

    void setValue(State& s, const T& value) const
    {   return getImpl().setValue(s, value); }

    const Measure_<T>& getOperandMeasure() const
    {   return getImpl().getOperandMeasure(); }

    Extreme& setOperandMeasure(const Measure_<T>& s)
    {   updImpl().setOperandMeasure(s); return *this; }

    SimTK_MEASURE_HANDLE_POSTSCRIPT(Extreme, Measure_<T>);
};

/** Track the minimum value of the operand (signed).
@see Measure_::Extreme **/
template <class T>
class Measure_<T>::Minimum : public Measure_<T>::Extreme {
    typedef typename Measure_<T>::Extreme Super;
public:
    Minimum(Subsystem& sub, const Measure_<T>& operand)
    :   Super(sub, operand, Super::Minimum) {}
};

/** Track the maximum value of the operand (signed).
@see Measure_::Extreme **/
template <class T>
class Measure_<T>::Maximum : public Measure_<T>::Extreme {
    typedef typename Measure_<T>::Extreme Super;
public:
    Maximum(Subsystem& sub, const Measure_<T>& operand)
    :   Super(sub, operand, Super::Maximum) {}
};

/** Track the value of the operand that is of maximum absolute value.
@see Measure_::Extreme **/
template <class T>
class Measure_<T>::MaxAbs : public Measure_<T>::Extreme {
    typedef typename Measure_<T>::Extreme Super;
public:
    MaxAbs(Subsystem& sub, const Measure_<T>& operand)
    :   Super(sub, operand, Super::MaxAbs) {}
};

/** Track the value of the operand that is of minimum absolute value (not very
useful).
@see Measure_::Extreme **/
template <class T>
class Measure_<T>::MinAbs : public Measure_<T>::Extreme {
    typedef typename Measure_<T>::Extreme Super;
public:
    MinAbs(Subsystem& sub, const Measure_<T>& operand)
    :   Super(sub, operand, Super::MinAbs) {}
};

//==============================================================================
//                                 DELAY
//==============================================================================
/** (CAUTION: still under development)
This is a %Measure whose value at time t is the value that its
\a source operand had at time t-delay for a specified \a delay. For times prior
to the start of a simulation this %Measure behaves as though the source value
had been constant at its initial value.

When the \a source %Measure can provide a time derivative dvalue we use saved
(t,value,dvalue) triples surrounding the required time to construct a cubic
Hermite interpolant giving a third-order accurate estimate of the delayed
value. Otherwise we use more data points to construct the cubic interpolant but
the accuracy cannot be guaranteed. If there aren't enough data points, then
linear interpolation is used instead. There is an option to force use of linear
interpolation if you prefer.

In the case where the delayed time is within the current step, we would need
the current \a source value in order to interpolate. We assume that is not
available (commonly the current value depends on the delayed value) so have to
extrapolate beyond the last buffered value in that case. Extrapolation is
considerably less accurate than interpolation, so when step sizes are large
compared to delay times the accuracy of the delayed value is reduced. In cases
where the \a source does not depend on its delayed value, you can request that
the current value be used if necessary, ensuring consistent accuracy.
Alternatively, you can set the maximum integrator step size to be just less
than the minimum delay time, guaranteeing that there will always be an entry
already in the buffer that is later than any requested delayed time. That
could have a substantial performance penalty if steps much larger than the
delay would otherwise have been taken.

%Implementation

This %Measure maintains a variable-sized buffer holding values that the
\a source measure and its time derivative (if available) had at each time step
starting just prior to t-delay until just before the current time t. New values
are added to the end of the buffer as integrator steps are completed, and old
values that are no longer needed are removed from the beginning. When a value is
requested at current time t, the %Measure interpolates using values from just
prior to t-delay and just afterwards to approximate the value at t-delay.

@bug Only linear interpolation implemented so far.
@bug There should be an option for the measure to specify a sampling interval
that would force the integrator to provide interpolated states at least that
often.
@bug The current implementation involves a lot of unnecessary copying because
it uses an auto-update state variable and cache entry. It should be using
an end-of-step event handler to update the buffer directly in the state.

@see Measure_::Integrate, Measure_::Differentiate **/
template <class T>
class Measure_<T>::Delay : public Measure_<T> {
public:
    /** @cond **/
    SimTK_MEASURE_HANDLE_PREAMBLE(Delay, Measure_<T>);
    /** @endcond **/

    /** Create a %Measure whose output is the same as the given \a source
    measure but delayed by a time \a delay. **/
    Delay(Subsystem& sub, const Measure_<T>& source, Real delay)
    :   Measure_<T>(sub, new Implementation(source, delay),
                    AbstractMeasure::SetHandle()) {}

    /** (Advanced) Restrict the %Delay measure to use only linear interpolation
    to estimate delayed values. By default it uses cubic interpolation whenever
    possible. Cubic interpolation will almost always be better but can be
    unstable in some circumstances. Despite its name this flag also applies
    to extrapolation if we have to do any. This is a topological change. **/
    Delay& setUseLinearInterpolationOnly(bool linearOnly)
    {   updImpl().setUseLinearInterpolationOnly(linearOnly); return *this; }

    /** (Advanced) Allow the %Delay measure to refer to the current
    value when estimating the delayed value. Normally we expect that the current
    value might depend on the delayed value so is not available at the time
    we ask for the delayed value. That means that if the delayed time is
    between the current time and the last saved time (that is, it is a time
    during the current integration step), the measure will have to
    extrapolate from the last-saved values to avoid requiring the current
    value to be available. With this approach the "depends on" time for a %Delay
    measure is just Time stage since it does not depend on any current
    calculations. However, \e extrapolation is much less accurate than
    \e interpolation so if you don't mind the "depends on" stage for a %Delay
    measure being the same stage as for its \a source measure, then you can get
    nicer interpolated values. This is a topological change. **/
    Delay& setCanUseCurrentValue(bool canUseCurrentValue)
    {   updImpl().setCanUseCurrentValue(canUseCurrentValue); return *this; }

    /** Replace the \a source measure. This is a topological change. **/
    Delay& setSourceMeasure(const Measure_<T>& source)
    {   updImpl().setSourceMeasure(source); return *this; }

    /** Change the \a delay time. This is a topological change. **/
    Delay& setDelay(Real delay)
    {   updImpl().setDelay(delay); return *this; }

    /** Return the value of the "use linear interpolation only" flag. **/
    bool getUseLinearInterpolationOnly() const
    {   return getImpl().getUseLinearInterpolationOnly(); }

    /** Return the value of the "can use current value" flag. **/
    bool getCanUseCurrentValue() const
    {   return getImpl().getCanUseCurrentValue(); }

    /** Obtain a reference to the \a source %Measure. **/
    const Measure_<T>& getSourceMeasure() const
    {   return getImpl().getSourceMeasure(); }

    /** Get the amount of time by which this %Measure is delaying its
    \a source %Measure. **/
    Real getDelay() const
    {   return getImpl().getDelay(); }

    /** @cond **/
    SimTK_MEASURE_HANDLE_POSTSCRIPT(Delay, Measure_<T>);
    /** @endcond **/
};

//==============================================================================
//                              SAMPLE AND HOLD
//==============================================================================
/** NOT IMPLEMENTED YET --
This is a Measure operator which, upon occurrence of a designated event,
samples its source Measure and then holds its value in a discrete state
variable until the next occurrence of the event. Any type of data can be
sampled this way.

Information available from this Measure:
 - the held value (Time stage)
 - time of last sample
 - the DiscreteVariableIndex holding the sampled value
 - a reference to the operand Measure

Study initialization is always considered a sampling event.
This measure has no time derivative. **/
template <class T>
class Measure_<T>::SampleAndHold : public Measure_<T> {
public:
    SimTK_MEASURE_HANDLE_PREAMBLE(SampleAndHold, Measure_<T>);

    SampleAndHold(Subsystem& sub, const Measure_<T>& source, EventId e);

    /// Set the held value to a particular value, unrelated to the source.
    /// The time stamp will be taken from the supplied State.
    void setValue(State& s, const T& value) const;

    /// Force this Measure to sample its input at the current time.
    void sample(State& s) const;

    const Measure_<T>& getSource() const;
    EventId            getEventId() const;

    SampleAndHold& setSource(const Measure_<T>& s);
    SampleAndHold& setEventId(EventId);

    SimTK_MEASURE_HANDLE_POSTSCRIPT(SampleAndHold, Measure_<T>);
};

} // namespace SimTK

#endif // SimTK_SimTKCOMMON_MEASURE_H_


text:
NSString *const JKDomain = @"JK";

@implementation NSError (JKAdd)

+ (NSError *)errorWithReason:(NSString *)reason
{
    NSError *error = [[NSError alloc] initWithDomain:JKDomain
                                                code:JKErrorCodeDefault
                                            userInfo:@{NSLocalizedDescriptionKey :reason}];
    return error;
}

@end


text:
let fs = require("fs");
let vm = require("vm");

let stub_path = "./bin/stub.js";
let stub = require(stub_path);

let stdlib = require("./stdlib");

let input = fs.readFileSync("./src/index.jsm", "utf-8");

console.log("Recompiling..");

let result = null;
try {
  result = stub.compile(input, stdlib);
  // add a fake module.exports to the vm ctx
  stdlib.module = {exports:{}};
  // test the recompiled compiler in a vm
  // if we succeed then overwrite the latest stub
  vm.runInNewContext(result, stdlib);
  stdlib.module.exports.compile(input, stdlib);
} catch (e) {
  console.log(e);
  return void 0;
}

fs.writeFileSync(stub_path, result, "utf-8");
console.log("Successfully recompiled into " + stub_path);


text:
package net.jackofalltrades.workflow.model.structure;

import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.ide.structureView.xml.XmlStructureViewBuilderProvider;
import com.intellij.psi.xml.XmlFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Implementation of XmlStructureViewBuilderProvider to creating the structure view of the workflow files.
 *
 * @author bhandy
 */
public class WorkflowStructureViewBuilderProvider implements XmlStructureViewBuilderProvider {

    @Nullable
    @Override
    public StructureViewBuilder createStructureViewBuilder(@NotNull XmlFile file) {
        return new WorkflowStructureViewBuilder(file);
    }

}


text:
/**
 * Module dependencies
 */

var types = require('../utils/types');

/**
 * Builds a Schema Object from an attributes
 * object in a model.
 *
 * Loops through an attributes object to build a schema
 * containing attribute name as key and a type for casting
 * in the database. Also includes a default value if supplied.
 *
 * Example:
 *
 * attributes: {
 *   name: 'string',
 *   phone: {
 *     type: 'string',
 *     defaultsTo: '555-555-5555'
 *   }
 * }
 *
 * Returns: {
 *   name: { type: 'string' },
 *   phone: { type: 'string, defaultsTo: '555-555-5555' }
 * }
 *
 * @param {Object} context
 * @return {Object}
 */

var Schema = module.exports = function(context) {
  this.context = context || {};
  this.schema = {};

  return this;
};

/**
 * Initialize the internal schema object
 *
 * @param {Object} attrs
 * @param {Boolean} hasSchema
 */

Schema.prototype.initialize = function(attrs, hasSchema, reservedAttributes) {
  var self = this;

  for(var key in attrs) {
    this.schema[key] = this.objectAttribute(attrs[key]);
  }

  if(Array.isArray(reservedAttributes)) {
    reservedAttributes.forEach(function(key) {
      self.schema[key] = {};
    });
  }

  // Set hasSchema to determine if values should be cleansed or not
  this.hasSchema = typeof hasSchema !== 'undefined' ? hasSchema : true;

  // Add Auto Created Attributes
  this.addAutoAttributes();
};

/**
 * Handle the building of an Object attribute
 *
 * @param {Object} value
 * @return {Object}
 */

Schema.prototype.objectAttribute = function(value) {
  var attr = {};

  for(var key in value) {
    switch(key) {
      // Set schema[attribute].type
      case 'type':
        // Allow validation types in attributes and transform them to strings
        attr.type = ~types.indexOf(value[key]) ? value[key] : 'string';
        break;

      // Set schema[attribute].defaultsTo
      case 'defaultsTo':
        attr.defaultsTo = value[key];
        break;

      // Set schema[attribute].primaryKey
      case 'primaryKey':
        attr.primaryKey = value[key];
        attr.unique = true;
        break;

      // Set schema[attribute].autoIncrement
      case 'autoIncrement':
        attr.autoIncrement = value[key];
        attr.type = 'integer';
        break;

      // Set schema[attribute].unique
      case 'unique':
        attr.unique = value[key];
        break;

      // Set schema[attribute].index
      case 'index':
        attr.index = value[key];
        break;

      // Set schema[attribute].enum
      case 'enum':
        attr.enum = value[key];
        break;

      // Set schema[attribute].size
      case 'size':
        attr.size = value[key];
        break;
    }
  }

  return attr;
};

/**
 * Add Auto Attributes
 *
 * Mixes in primaryKey, createdAt, updatedAt attributes
 * if they are set as auto keys.
 */

Schema.prototype.addAutoAttributes = function() {
  var defined = false;

  // Check another property hasn't set itself as a primary key
  for(var key in this.schema) {
    if(this.schema[key].hasOwnProperty('primaryKey')) defined = true;
  }

  // If id is not defined, add it
  if(!defined && this.context.autoPK && !this.schema.id) {
    this.schema.id = {
      type: 'integer',
      autoIncrement: true,
      defaultsTo: 'AUTO_INCREMENT',
      primaryKey: true,
      unique: true
    };
  }

  // If the adapter config allows it, and they aren't already specified,
  // extend definition with autoUpdatedAt and autoCreatedAt
  var now = { type: 'datetime', 'default': 'NOW' };
  if(this.context.autoCreatedAt && !this.schema.createdAt) this.schema.createdAt = now;
  if(this.context.autoUpdatedAt && !this.schema.updatedAt) this.schema.updatedAt = now;
};

/**
 * Clean Values
 *
 * Takes user inputted data and strips out any values not defined in
 * the schema.
 *
 * This is run after all the validations and right before being sent to the
 * adapter. This allows you to add temporary properties when doing validation
 * callbacks and have them stripped before being sent to the database.
 *
 * @param {Object} values to clean
 * @return {Object} clone of values, stripped of any extra properties
 */

Schema.prototype.cleanValues = function(values) {
  var clone = {};

  // Return if hasSchema === false
  if(!this.hasSchema) return values;

  for(var key in values) {
    if(this.schema.hasOwnProperty(key)) clone[key] = values[key];
  }

  return clone;
};


text:
<?php

namespace Rhubarb\Stem\Tests\unit\Schema\Columns;

use Rhubarb\Crown\Encryption\EncryptionProvider;
use Rhubarb\Crown\Tests\Fixtures\TestCases\RhubarbTestCase;
use Rhubarb\Crown\Tests\unit\Encryption\UnitTestingAes256EncryptionProvider;
use Rhubarb\Stem\Models\Model;
use Rhubarb\Stem\Schema\Columns\EncryptedStringColumn;
use Rhubarb\Stem\Schema\ModelSchema;

class EncryptedStringTest extends RhubarbTestCase
{
    protected function setUp()
    {
        parent::setUp();

        EncryptionProvider::setProviderClassName(UnitTestingAes256EncryptionProvider::class);
    }

    public function testEncryption()
    {
        $model = new TestModel();
        $model->SecureColumn = "plain text";

        $aes = new UnitTestingAes256EncryptionProvider();

        $this->assertEquals($aes->encrypt("plain text", "SecureColumn"), $model->exportRawData()["SecureColumn"]);
    }

    public function testDecryption()
    {
        $model = new TestModel();
        $model->SecureColumn = "plain text";

        // Assuming the encryption test passed, then this simple code will test the decryption.

        $this->assertEquals("plain text", $model->SecureColumn);
    }
}

class TestModel extends Model
{
    /**
     * Returns the schema for this data object.
     *
     * @return \Rhubarb\Stem\Schema\ModelSchema
     */
    protected function createSchema()
    {
        $schema = new ModelSchema("Test");
        $schema->addColumn(new EncryptedStringColumn("SecureColumn", 100));

        return $schema;
    }
}


text:
package SimCity.restaurants.restaurant_tenno;

import SimCity.restaurants.restaurant_tenno.gui.CustomerGui;
import SimCity.restaurants.restaurant_tenno.interfaces.Cashier;
import SimCity.restaurants.restaurant_tenno.interfaces.Customer;
import SimCity.restaurants.restaurant_tenno.interfaces.Waiter;
import agent.Agent;
import SimCity.restaurants.restaurant_tenno.WaiterAgent.Menu;
import role.Role;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;

/**
 * Restaurant customer agent.
 */
public class CustomerAgent extends Role implements Customer {
	private String name;
	private int hungerLevel = 10;        // determines length of meal
	Timer timer = new Timer();
	private CustomerGui customerGui;
	private Semaphore atLocation = new Semaphore(0,true) ;

	// For pausing gui
	private boolean ispaused = false ;

	// to determine if this is a jerk customer who doesn't pay
	public enum CustomerAspects {jerk, cheap, wontreorder, low, quick, normal}
	private CustomerAspects aspects = CustomerAspects.normal ;
	private double previoustab = 0 ;

	// agent correspondents
	private HostAgent host;
	private Waiter waiter ;
	private Cashier cashier ;
	private Menu menu ;

	double money = 20 ;
	double bill = 0 ;

	String choice = "null"; // What he wants to eat

	// States and stuff
	public enum AgentState
	{nothungry, waiting, fedup, seated, readytoorder, needstoreorder, toomuch, ranoutofchoice, ordered, eating, doneeat, readyforcheck, paying, left}
	private AgentState state = AgentState.nothungry;//The start state

	public enum AgentEvent
	{none, gotHungry, followWaiter, seated, ordered, doneEating, gotcheck, gotchange, gotkickedout, doneLeaving};
	AgentEvent event = AgentEvent.none;

	/**
	 * Constructor for CustomerAgent class
	 *
	 * @param name name of the customer
	 * @param gui  reference to the customergui so the customer can send it messages
	 */
	public CustomerAgent(String name){
		super();
		this.name = name;
		this.menu = null ;
	}
	public CustomerAgent(CustomerAgent c) {
		super();
		this.name = c.name ;
		this.menu = c.menu ;
		this.choice = c.choice ;
		this.customerGui = c.customerGui ;
		this.event = c.event ;
		this.state = c.state ;
		this.host = c.host ;
		this.hungerLevel = c.hungerLevel ;
		this.waiter = c.waiter ;
	}

	/**
	 * hack to establish connection to Host agent.
	 */
	public void setHost(HostAgent host) {
		this.host = host;
	}
	public void setWaiter(Waiter waiter) {
		this.waiter = waiter ;
		this.menu = ((WaiterAgent)waiter).menu ;
	}

	public String getCustomerName() {
		return getRoleName();
	}
	// Messages

	public void gotHungry() {//from animation buttons
		Do("I'm hungry");
		event = AgentEvent.gotHungry;
		stateChanged();
	}

	public void msgRestaurantIsFull() {
		final CustomerAgent temp = this ;
		if(this.aspects == CustomerAspects.quick) {
			timer.schedule(new TimerTask() {
				public void run() {
					temp.state = AgentState.fedup ;
					stateChanged();
				}
			}, 3000);
		}
		stateChanged();
	}

	public void msgReorder() {
		this.choice = "null" ;
		state = AgentState.needstoreorder ;
		event = AgentEvent.seated ;
		stateChanged() ;
	}

	public void msgFollowMe(Waiter w) {
		print("Received msgFollowMe");
		setWaiter(w) ;
		event = AgentEvent.followWaiter;
		stateChanged();
	}

	public void msgAnimationFinishedGoToSeat() {
		//from animation
		event = AgentEvent.seated;
		stateChanged();
	}

	public void msgWhatFood() {
		print("Received msgWhatFood");
		this.state = AgentState.ordered ;
		stateChanged();
	}

	public void msgGiveFood() {
		print("Received msgGiveFood");
		this.state = AgentState.eating ;
		stateChanged();
	}

	public void msgGiveCheck(double amount) {
		Do("Received Check - " + amount) ;
		this.bill = amount ;
		this.event = AgentEvent.gotcheck ;
		stateChanged();
	}

	public void msgGiveChange(double amount) {
		Do("Received Change from Bill - " + amount) ;
		this.bill = 0 ;
		this.money = amount ;
		this.event = AgentEvent.gotchange ;
		stateChanged();
	}

	public void msgYouOweThis(double amount) {
		previoustab = amount ;
		this.event = AgentEvent.gotkickedout ;
		stateChanged();
	}

	public void msgAnimationFinishedGoToHost() {
		//from animation
		atLocation.release();
		stateChanged();
	}

	public void msgAnimationFinishedLeaveRestaurant() {
		//from animation
		event = AgentEvent.doneLeaving;
		stateChanged();
	}

	public void msgAnimationFinishedGoToCashier() {
		//from animation
		timer.schedule(new TimerTask() {
			public void run() {
				atLocation.release();
				stateChanged();
			}
		}, 5000);
	}

	/**
	 * Scheduler.  Determine what action is called for, and do it.
	 */
	public boolean pickAndExecuteAnAction() {
		if (state == AgentState.nothungry && event == AgentEvent.gotHungry ){
			state = AgentState.waiting;
			goToRestaurant();
			return true;
		}
		if (state == AgentState.fedup && aspects == CustomerAspects.quick ){
			state = AgentState.left ;
			waitedtooLong() ;
			return true;
		}
		if (state == AgentState.waiting && event == AgentEvent.followWaiter ){
			Do("Being seated. Going to table");
			this.state = AgentState.seated;
			return true ;
		}
		if (state == AgentState.seated && event == AgentEvent.seated){
			state = AgentState.readytoorder;
			//Function to Order Food
			timer.schedule(new TimerTask() {
				public void run() {
					TellWaiter() ;
				}
			}, this.getHungerLevel()*500);
			return true;
		}

		if (state == AgentState.needstoreorder && event == AgentEvent.seated ){
			if(aspects == CustomerAspects.normal) {
				state = AgentState.readytoorder;
				TellWaiter() ;
			}
			else if(aspects == CustomerAspects.wontreorder)
				state = AgentState.ranoutofchoice ;
			else if(aspects == CustomerAspects.cheap)
				state = AgentState.toomuch ;
			else if(aspects == CustomerAspects.low) {
				state = AgentState.toomuch ;
				aspects = CustomerAspects.cheap ;
			}
			return true;
		}

		if (state == AgentState.toomuch && event == AgentEvent.seated ){
			state = AgentState.left ;
			costTooMuch() ;
			return true;
		}

		if (state == AgentState.ranoutofchoice && event == AgentEvent.seated ){
			state = AgentState.left ;
			ranOutOfChoice() ;
			return true;
		}

		if (state == AgentState.ordered && event == AgentEvent.seated){
			OrderFood() ;
			return true;
		}

		if (state == AgentState.eating && event == AgentEvent.ordered){
			EatFood() ;
			return true;
		}

		if (state == AgentState.doneeat && event == AgentEvent.doneEating){
			state = AgentState.readyforcheck;
			readyForCheck() ;
			return true;
		}

		if (state == AgentState.paying && event ==  AgentEvent.gotchange){
			state = AgentState.left ;
			leaveTable();
			return true;
		}

		if (state == AgentState.paying && event ==  AgentEvent.gotkickedout){
			state = AgentState.left ;
			LeaveInShame();
			return true;
		}

		if (state == AgentState.readyforcheck && event == AgentEvent.gotcheck){
			Do("Paying Bill") ;
			state = AgentState.paying ;
			PayCheck() ;
			return true;
		}

		if (state == AgentState.left && event == AgentEvent.doneLeaving){
			state = AgentState.nothungry;
			//no action
			return true;
		}
		return false;
	}

	// Actions

	private void PayCheck() {
		customerGui.DoGoToCashier();
		try {
			atLocation.acquire();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cashier.msgPayCheck(this, this.money);
	}

	private void waitedtooLong() {
		Do("Not waiting any more - Leaving.") ;
		host.msgLeaving(this);
		leaveNotFast();
	}

	private void goToRestaurant() {
		Do("Going to restaurant");
		customerGui.DoGoToHost();
		try {
			atLocation.acquire();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		final CustomerAgent temp = this ;
		timer.schedule(new TimerTask() {
			public void run() {
				host.msgIWantFood(temp);
				customerGui.DoGetInLine();
			}
		}, 1500);
		//send our instance, so he can respond to us
	}

	private void costTooMuch() {
		Do("Food is too expensive") ;
		waiter.msgCustLeaving(this) ;
		leaveTable();
	}

	private void ranOutOfChoice() {
		Do("You ran out of my choice") ;
		waiter.msgCustLeaving(this) ;
		leaveTable();
	}

	private void TellWaiter()
	{
		if(this.choice.equals("null"))
			PickFood() ;
		if(this.choice.equals("none")) {
			this.state = AgentState.toomuch ;
			stateChanged() ;
		}
		else {
			Do("Telling Waiter " + waiter.getName() + " I am ready to order");
			waiter.msgReadyToOrder(this) ;
		}
	}

	private void PickFood() {
		choice = this.menu.PickFood(this.money, this.aspects == CustomerAspects.jerk) ;
	}

	private void OrderFood() {
		Do("Ordering " + choice);
		event = AgentEvent.ordered ;
		waiter.msgIWantThis(choice, this) ;
	}

	private void EatFood() {
		Do("Eating food " + choice);
		state = AgentState.doneeat ;
		//This next complicated line creates and starts a timer thread.
		//We schedule a deadline of getHungerLevel()*1000 milliseconds.
		//When that time elapses, it will call back to the run routine
		//located in the anonymous class created right there inline:
		//TimerTask is an interface that we implement right there inline.
		//Since Java does not all us to pass functions, only objects.
		//So, we use Java syntactic mechanism to create an
		//anonymous inner class that has the public method run() in it.
		timer.schedule(new TimerTask() {
			Object cookie = 1;
			public void run() {
				print("Done eating, cookie=" + cookie);
				event = AgentEvent.doneEating;
				stateChanged();
			}
		},
		this.getHungerLevel()*1000);//how long to wait before running task
	}

	private void readyForCheck() {
		waiter.msgDoneEating(this);
	}

	private void leaveTable() {
		Do("Leaving.");
		customerGui.DoExitRestaurant();
	}

	private void leaveNotFast() {
		Do("Leaving.");
		customerGui.DoQuickCustomer();
	}

	private void LeaveInShame() {
		Do("Leaving in shame.");
		this.previoustab = this.bill ;
		customerGui.DoLeaveInShame();
	}

	// Accessors, etc.

	protected String getRoleName() {
		return name ;
	}

	public void setCashier(Cashier c){
		this.cashier = c ;
	}

	public void setJerkCustomer(){
		aspects = CustomerAspects.jerk ;
		this.money = 1 ;
	}

	public void setCheapCustomer(){
		aspects = CustomerAspects.cheap ;
		this.money = 1 ;
	}

	public void setLowCustomer(){
		aspects = CustomerAspects.low ;
		this.money = 6 ;
	}

	public void setQuickCustomer() {
		aspects = CustomerAspects.quick ;
	}

	public boolean getQuick() {
		if(this.aspects == CustomerAspects.quick)
			return true ;
		else
			return false ;
	}

	public boolean getcheap(){
		return (aspects == CustomerAspects.cheap) ;
	}

	public String getName() {
		return myPerson.getName();
	}

	public int getHungerLevel() {
		return hungerLevel;
	}

	public double getWallet() {
		return this.money ;
	}

	public void setWallet(double amount) {
		this.money = amount ;
	}

	public void setHungerLevel(int hungerLevel) {
		this.hungerLevel = hungerLevel;
		//could be a state change. Maybe you don't
		//need to eat until hunger lever is > 5?
	}

	public String toString() {
		return "customer " + getName();
	}

	public void setGui(CustomerGui g) {
		customerGui = g;
	}

	public CustomerGui getGui() {
		return customerGui;
	}

	// Hack used in GUI to get customer position in line
	public HostAgent getHost() {
		return this.host ;
	}

	public void resetmoney() {
		this.money = 20 ;
	}

	public AgentState getstate() {
		return this.state ;
	}

	public String getchoice() {
		String temp = choice.substring(0, 2) ;
		temp = temp.toUpperCase() ;
		return temp ;
	}

	public String getOrderChoice() {
		return choice ;
	}

	public void setChoice(String c, boolean leaveifnochoice) {
		this.choice = c ;
		if(leaveifnochoice)
			aspects = CustomerAspects.wontreorder ;
	}

	public boolean ispaused() {
		return ispaused ;
	}

	public int getCashierPositionInLine() {
		return ((CashierAgent) cashier).getPositonInLine(this) ;
	}

}


text:
tool
====

programming tools developed by myself
In developing...


text:
using System;

namespace Hydra.Framework.Mapping.Converters.WellKnownBinary
{
    //
    // **********************************************************************
    /// <summary>
    /// Specifies the specific binary encoding (NDR or XDR) used for a geometry byte stream
    /// </summary>
    // **********************************************************************
    //
    public enum WkbByteOrder
        : byte
    {
        //
        // **********************************************************************
        /// <summary>
        /// XDR (Big Endian) Encoding of Numeric Types
        /// </summary>
        /// <remarks>
        /// <para>The XDR representation of an Unsigned Integer is Big Endian (most significant byte first).</para>
        /// <para>The XDR representation of a Double is Big Endian (sign bit is first byte).</para>
        /// </remarks>
        // **********************************************************************
        //
        Xdr = 0,

        //
        // **********************************************************************
        /// <summary>
        /// NDR (Little Endian) Encoding of Numeric Types
        /// </summary>
        /// <remarks>
        /// <para>The NDR representation of an Unsigned Integer is Little Endian (least significant byte first).</para>
        /// <para>The NDR representation of a Double is Little Endian (sign bit is last byte).</para>
        /// </remarks>
        // **********************************************************************
        //
        Ndr = 1
    }
}


text:
export { NavComponent } from './nav.component';
export { FooterComponent } from './footer.component';
export { NotFoundComponent } from './not-found.component';


text:
static __inline__ long int
random (void)
{
  extern int rand(void);

  return rand ();
}

static __inline__ void
srandom (unsigned int seed)
{
  void srand(unsigned int seed);

  srand (seed);
}


text:
import psycopg2 as pg
from scipy.io import loadmat
import numpy
from numpy import squeeze, isnan
from os import path
import os
import math
import sys
import re

def sq(thang):
    return map(squeeze, thang)

def intNan(f):
    if math.isnan(f):
        return None
    else:
        return int(f)

def csvrep(x):
    if numpy.isnan(x):
        return '""'
    elif x.dtype.kind == 'U':
        return '"%s"' % x
    else:
        return '%s' % x

def dump_mat_field(file,field):
    l = loadmat(path.join('../exampleData/annotation/',file))

    for row in l[field]:
        print ','.join([csvrep(squeeze(c)) for c in row])

def manual2tuples(path):
    lid = re.sub('.*/(.*).mat','\\1',path)
    l = loadmat(path)
    try:
        cols = map(str,sq(l['list_titles'][0]))
        annotations = sq(l['classlist'])
        manual_classes = [None] + sq(l['class2use_manual'][0])
        auto_classes = [None] + sq(l['class2use_auto'][0])
        sub_classes = {}
        for n,sub_col in zip(range(4,len(cols)+1),cols[3:]):
            field = 'class2use_sub%d' % n
            if field in l:
                sub_classes[sub_col] = sq(l[field][0])

        for annotation in annotations:
            (roi, manual, svm_auto) = map(intNan, annotation[:3])
            subs = {}
            for n,sub in zip(range(3,len(annotation)),annotation[3:]):
                if not isnan(sub):
                    col = cols[n]
                    subs[cols[n]] = str(sub_classes[cols[n]][int(sub)-1])
            yield (lid, '%s_%05d' % (lid, roi), str(manual_classes[manual-1]) if manual is not None else None, str(auto_classes[svm_auto-1]) if svm_auto is not None else None, subs)
    except:
        if not 'class2use_sub4' in l:
            print 'missing class2use_sub4 on %s' % lid
        else:
            print l
            print l.keys()
            print cols
            print n
            print annotation
            print sub
            print sub_classes
            raise

#dump_mat_field('manual_list.mat','manual_list')
#dump_mat_field('IFCB1_2006_158_000036.mat','classlist')
#manual2csv('../exampleData/annotation/IFCB1_2006_158_000036.mat')

def sqlize_str(value):
    if value is None:
        return None
    else:
        return str(value)

if __name__=='__main__':
    PSQL_DB = 'ifcb'
    PSQL_USER = 'jfutrelle'
    PSQL_PASSWORD = 'vNLH814i'

    conn = pg.connect('dbname=%s user=%s password=%s' % (PSQL_DB,PSQL_USER,PSQL_PASSWORD))

    db = conn.cursor()

    #manual2csv(sys.argv[1])
    #manual2csv('../exampleData/annotation/IFCB1_2006_158_000036.mat')
    dir = '/Users/jfutrelle/dev/ifcb/manual'
    for f in os.listdir(dir):
        if re.match('IFCB._[\d_]+\\.mat',f):
            bin_lid = re.sub('\\.mat','',f)
            db.execute("select count(*) from manual where bin_lid = %s",(bin_lid,))
            count = db.fetchone()[0]
            if count > 0:
                #print 'skipping %s...' % f
                pass
            else:
                p = os.path.join(dir,f)
                print 'processing %s...' % f
                try:
                    for (bin_lid, roi_lid, manual, svm_auto, subs) in manual2tuples(p):
                        if manual is not None: # for now, just ones with manual class
                            (bin_lid, roi_lid, manual, svm_auto) = map(sqlize_str,(bin_lid, roi_lid, manual, svm_auto))
                            db.execute("INSERT INTO manual (bin_lid, roi_lid, manual, svm_auto) VALUES (%s,%s,%s,%s)",(bin_lid,roi_lid,manual,svm_auto))
                            for key,value in subs.items():
                                db.execute("INSERT INTO manual_sub (bin_lid, roi_lid, sub_column, sub_class) VALUES (%s,%s,%s,%s)",(bin_lid,roi_lid,key,value))
                    conn.commit()
                except:
                    #raise
                    pass


text:
<form class="form-inline" (ngSubmit)="onSubmit(searchForm)" #searchForm="ngForm">
  <div class="form-group mr-1">
    <input
      type="text"
      class="form-control"
      [(ngModel)]="coursesSearchForm.searchQuery"
      placeholder="{{ coursesSearchForm.searchPlaceholder }}"
      name="searchQuery">
  </div>
  <button type="submit" class="btn btn-primary">Search</button>
</form>


text:
package testing;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.terapico.naf.parameter.ParameterManager;
public class GenericTest {
	  List<String> stringList = new ArrayList<String>();
	    List<Integer> integerList = new ArrayList<Integer>();

	    public static void main2(String... args) throws Exception {
	        Field stringListField = GenericTest.class.getDeclaredField("stringList");
	        ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
	        Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
	        System.out.println(stringListClass); // class java.lang.String.

	        Field integerListField = GenericTest.class.getDeclaredField("integerList");
	        ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType();
	        Class<?> integerListClass = (Class<?>) integerListType.getActualTypeArguments()[0];
	        System.out.println(integerListClass); // class java.lang.Integer.

	    }
	    public static void main(String... args) throws Exception {

	        Field integerListField = GenericTest.class.getDeclaredField("integerList");
	        ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType();
	        Class<?> integerListClass = (Class<?>) integerListType.getActualTypeArguments()[0];
	        System.out.println(integerListClass); // class java.lang.Integer.

	    }
}


text:
if (NOT TARGET dependencies::boost)

	include(dependencies/common)
	option(WITH_SYSTEM_BOOST "Don't build boost with the project" ON)
	option(BOOST_STATIC_CRT  "Use static runtime libraries" ON)

	add_library(dependencies::boost UNKNOWN IMPORTED)

	add_library(dependencies::boost::system UNKNOWN IMPORTED)
	add_dependencies(dependencies::boost::system dependencies::boost)

	add_library(dependencies::boost::filesystem UNKNOWN IMPORTED)
	add_dependencies(dependencies::boost::filesystem dependencies::boost)

	if (WITH_SYSTEM_BOOST)

		if(NOT BOOST_ROOT)
			set(BOOST_ROOT $ENV{BOOST_ROOT})
		endif()
		find_package(Boost 1.47.0 COMPONENTS system filesystem REQUIRED)

	else()
		if (BOOST_STATIC_CRT)
			set(EXTRA_FLAGS ${EXTRA_FLAGS} "runtime-link=static")
		endif()

		if (NOT WIN32)
			set(BOOTSTRAP_CMD "./bootstrap.sh")
			if (TARGET dependencies::openssl)
				get_property(OPENSSL_INCLUDE_DIR TARGET dependencies::openssl
					PROPERTY INTERFACE_INCLUDE_DIRECTORIES)
				set(EXTRA_FLAGS ${EXTRA_FLAGS}
						"cflags=-I${OPENSSL_INCLUDE_DIR}"
			                        "cxxflags=-I${OPENSSL_INCLUDE_DIR}")
				set_property(TARGET dependencies::boost  APPEND PROPERTY
					INTERFACE_INCLUDE_DIRECTORIES ${OPENSSL_INCLUDE_DIR})

				get_property(OPENSSL_SSL_LIBRARY TARGET dependencies::openssl::ssl
					PROPERTY IMPORTED_LOCATION)
				get_property(OPENSSL_CRYPTO_LIBRARY TARGET dependencies::openssl::crypto
					PROPERTY IMPORTED_LOCATION)
				get_property(OPENSSL_LIB_DEPENDENCIES TARGET dependencies::openssl
					PROPERTY INTERFACE_LINK_LIBRARIES)
				set_property(TARGET dependencies::boost APPEND PROPERTY
					INTERFACE_LINK_LIBRARIES ${OPENSSL_SSL_LIBRARY}
			                                         ${OPENSSL_CRYPTO_LIBRARY}
			                                         ${OPENSSL_LIB_DEPENDENCIES})
				set(DEPENDENCIES dependencies::openssl)
			endif()
		else()
			add_definitions(-DBOOST_ALL_NO_LIB)
			set(BOOTSTRAP_CMD "bootstrap.bat")
			if (TARGET dependencies::libressl)
				get_property(LIBRESSL_INCLUDE_DIR TARGET dependencies::libressl
					PROPERTY INTERFACE_INCLUDE_DIRECTORIES)
				set(EXTRA_FLAGS ${EXTRA_FLAGS}
						"cflags=-I${LIBRESSL_INCLUDE_DIR}"
			                        "cxxflags=-I${LIBRESSL_INCLUDE_DIR}")
				set_property(TARGET dependencies::boost  APPEND PROPERTY
					INTERFACE_INCLUDE_DIRECTORIES ${LIBRESSL_INCLUDE_DIR})

				get_property(LIBRESSL_SSL_LIBRARY TARGET dependencies::libressl::ssl
					PROPERTY IMPORTED_LOCATION)
				get_property(LIBRESSL_CRYPTO_LIBRARY TARGET dependencies::libressl::crypto
					PROPERTY IMPORTED_LOCATION)
				get_property(LIBRESSL_LIB_DEPENDENCIES TARGET dependencies::libressl
					PROPERTY INTERFACE_LINK_LIBRARIES)
				set_property(TARGET dependencies::boost APPEND PROPERTY
					INTERFACE_LINK_LIBRARIES ${LIBRESSL_SSL_LIBRARY}
			                                         ${LIBRESSL_CRYPTO_LIBRARY}
			                                         ${LIBRESSL_LIB_DEPENDENCIES})
				set(DEPENDENCIES dependencies::libressl)
			endif()
		endif()

		sources_url(BOOST
			"boost.org/boost/boost_1_64_0.tar.gz"
			"https://dl.bintray.com/boostorg/release/1.64.0/source/:boost_1_64_0.tar.gz")
		ExternalProject_Add(dependencies_boost
			URL ${BOOST_URL}
			DOWNLOAD_NAME boost_1_64_0.tar.gz
			URL_HASH SHA256=0445c22a5ef3bd69f5dfb48354978421a85ab395254a26b1ffb0aa1bfd63a108
			CONFIGURE_COMMAND ${BOOTSTRAP_CMD}
			PATCH_COMMAND "cmake" -E tar zxf "${CMAKE_CURRENT_SOURCE_DIR}/cmake/dependencies/misc/boost_1_64_libressl.patch.tar.gz"
			BUILD_COMMAND "./b2" ${EXTRA_FLAGS} link=static include=static variant=release threading=multi --with-system --with-filesystem --prefix=<INSTALL_DIR> --layout=system --ignore-site-config install
			INSTALL_COMMAND ""
			BUILD_IN_SOURCE 1
			INSTALL_DIR "${STAGING_DIR}"
			LOG_DOWNLOAD 1
			LOG_UPDATE 1
			LOG_CONFIGURE 1
			LOG_BUILD 1
			LOG_TEST 1
			LOG_INSTALL 1
		)
		add_dependencies(dependencies::boost dependencies_boost)
		add_dependencies(dependencies_boost ${DEPENDENCIES})
		set(Boost_INCLUDE_DIRS "${STAGING_DIR}/include")
		set(Boost_SYSTEM_LIBRARY     "${STAGING_DIR}/lib/libboost_system${CMAKE_STATIC_LIBRARY_SUFFIX}")
		set(Boost_FILESYSTEM_LIBRARY "${STAGING_DIR}/lib/libboost_filesystem${CMAKE_STATIC_LIBRARY_SUFFIX}")

	endif()

	set_target_properties(dependencies::boost PROPERTIES
		INTERFACE_INCLUDE_DIRECTORIES ${Boost_INCLUDE_DIRS})
	set_target_properties(dependencies::boost::system PROPERTIES
		IMPORTED_LOCATION ${Boost_SYSTEM_LIBRARY})
	set_target_properties(dependencies::boost::filesystem PROPERTIES
		IMPORTED_LOCATION ${Boost_FILESYSTEM_LIBRARY})

	find_package(Threads)
	set_property(TARGET dependencies::boost APPEND PROPERTY
		INTERFACE_LINK_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}
	                             ${CMAKE_DL_LIBS})

endif()