text:
<?php

class ApiUserController extends ApiController
{
    const ACTION_LOGIN = 'login';
    const ACTION_MERGE = 'merge';
    const ACTION_IMPORT = 'import';

    public function actionLogin()
    {
        $request = Yii::app()->request;

        // Create user validation entity
        $user = new User;
        $user->email = $request->getPost('email');
        $user->password = $request->getPost('password');

        // Validate user input and redirect to the previous page if valid
        if ($user->login()) {
            // Check promoter account
            if ($user->role == User::ROLE_PROMOTER) {
                if (isset(Yii::app()->request->cookies['account']) && !empty(Yii::app()->request->cookies['account'])) {
                    $account = Yii::app()->request->cookies['account'];
                    if ($account = Promoter::getByAccount($account)) {
                        PromoterApi::updateByAccount($account);
                    }
                }
            }

            // Send response
            $result = array(
                'result'    => ApiStatus::SUCCESS,
                'data'      => $user->getEntity()->getNormalizedData(true, true)
            );
        } else {
            $result = array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Could not find user with given credentials'
            );
        }

        $this->renderJSON($result);
    }

    public function actionSwitch()
    {
        if ($user = UserApi::switchRole()) {
            $result = array(
                'result'    => ApiStatus::SUCCESS,
                'message'   => 'Your account was succesfully switched',
                'data'      => $user
            );
        } else {
            $result = array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Can\'t switch your account. Please contact to support'
            );
        }
        $this->renderJSON($result);
    }

    public function actionLogout()
    {
        Yii::app()->user->logout();
        $result = array('result' => ApiStatus::SUCCESS);

        $this->renderJSON($result);
    }

    /**
     * Register new user
     * @TODO: Decrease Cyclomatic complexity
     * @TODO: Split method for submethods, decrease the number of lines
     */
    public function actionRegister()
    {
        $artist = $promoter = $already_registered = null;
        $request = Yii::app()->request;

        // Get base params
        $role = $request->getPost('role');
        $name = $request->getPost('name');
        $email = trim(strtolower($request->getPost('email')));
        $password = $request->getPost('password');
        $account = isset($request->cookies['account']) ? $request->cookies['account'] : null;

        // Check already registered user
        $user = User::model()->find('email = :email', array(':email' => $email));
        if ($user) {
            if ($user->validatePassword($password) && $user->login()) {
                if ($role == User::ROLE_PROMOTER) {
                    $already_registered = true;
                    $promoter = $user->promoter();
                } else {
                    $artist = $user->artist();
                }
            } else {
                $this->renderJSON(array(
                    'result'    => ApiStatus::INVALID,
                    'errors'    => array(
                        array('field' => 'register-password', 'message' => 'Password does not match')
                    ),
                    'message'   => 'This email already registered'
                ));
                return;
            }
        }

        // Check user role and create/update appropriate profile
        try {
            if ($role == User::ROLE_PROMOTER) {
                if (!$already_registered) {
                    if ($account) {
                        $promoter = Promoter::getByAccount($account);
                    }
                    if (!$promoter) {
                        $promoter = new Promoter;
                    }
                    $promoter->attributes = array(
                        'name'      => $request->getPost('name'),
                        'latitude'  => $request->getPost('latitude'),
                        'longitude' => $request->getPost('longitude'),
                        'radius'    => $request->getPost('radius')
                    );
                    $promoter->bindRelatedParams(array(
                        'email'     => $email,
                        'password'  => $password,
                        'role'      => $request->getPost('role', 1),
                        'create_date' => date('Y-m-d')
                    ));
                }

                if ($promoter->save()) {
                    $promoter->user->login();

                    if ($account = Promoter::getByAccount($account)) {
                        PromoterApi::updateByAccount($account);
                    } else {
                        Mailer::sendRegisterEmail(array('email' => $email, 'name' => $name));
                    }

                    $result = array(
                        'result'    => ApiStatus::SUCCESS,
                        'data'      => $promoter->user->getNormalizedData(),
                        'message'   => $account ?
                            'Your booking request has just been send.

                             Booked artist will be likely to respond positively, if you fill up your profile
                             with true and up-to-date information.

                             Please, take time to fill up your profile.' : ''
                    );
                } else {
                    $result = array(
                        'result'    => ApiStatus::INVALID,
                        'errors'    => $promoter->getErrors()
                    );
                }
            } else {
                $artist = $artist ? $artist : new Artist;

                $artist->attributes = array(
                    'name'      => $request->getPost('name'),
                    'latitude'  => $request->getPost('latitude'),
                    'longitude' => $request->getPost('longitude')
                );
                $artist->bindRelatedParams(array(
                    'email'     => $email,
                    'password'  => $password,
                    'role'      => $request->getPost('role'),
                ));

                if ($artist->save()) {
                    $artist->user->login();
                    $result = array(
                        'result'    => ApiStatus::SUCCESS,
                        'data'      => $artist->user->getNormalizedData()
                    );
                } else {
                    $result = array(
                        'result'    => ApiStatus::INVALID,
                        'errors'    => $artist->getErrors()
                    );
                }
            }
        } catch (CException $e) {
            $result = array(
                'result'    => ApiStatus::ERROR,
                'message'   => $e->getMessage()
            );
        }

        $this->renderJSON($result);
    }

    public function actionRestore()
    {
        // Get request
        $request = Yii::app()->request;

        // Create user
        $email = trim(strtolower($request->getPost('email')));
        if (!empty($email)) {
            $user = User::model()->find('email = :email', array(':email' => $email));

            // Generate reset link and try to send it
            $link = $user ? $user->generateResetPasswordLink() : false;
            $name = $user->promoters ? $user->promoters[0]->name :
                $user->artists ? $user->artists[0]->name : null;

            if ($link) {
                if (Mailer::sendResetPasswordEmail(array('name' => $name, 'email' => $email, 'link' => $link))) {
                    $result = array(
                        'result'    => ApiStatus::SUCCESS,
                        'message'   => 'Please check your email.'
                    );
                } else {
                    $result = array(
                        'result'    => ApiStatus::ERROR,
                        'message'   => 'Could not send email, please try later'
                    );
                }
            } else {
                $result = array(
                    'result'    => ApiStatus::ERROR,
                    'message'   => 'Could not find user with given credentials'
                );
            }
        } else {
            $result = array(
                'result'    => ApiStatus::INVALID,
                'errors'    => array('email' => 'Email could not be empty')
            );
        }

        $this->renderJSON($result);
    }

    /**
     * Check restore password hash
     */
    public function actionCheckhash()
    {
        // Get request
        $request = Yii::app()->request;

        // Get hash and check it
        $hash = $request->getPost('hash');
        if (!empty($hash)) {
            $user = User::model()->find('reset_hash = :reset_hash', array(':reset_hash' => $hash));
            if ($user) {
                $result = array(
                    'result'    => ApiStatus::SUCCESS
                );
            } else {
               $result = array(
                    'result'    => ApiStatus::ERROR,
                    'message'   => 'Your reset link expired, please try again'
                );
            }
        } else {
            $result = array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Invalid restore link, please try again'
            );
        }

        $this->renderJSON($result);
    }

    /**
     * Set new user password
     */
    public function actionNewpass()
    {
        // Get request
        $request = Yii::app()->request;

        // Get hash and check it
        $hash = $request->getPost('hash');
        if (!empty($hash)) {
            $user = User::model()->find('reset_hash = :reset_hash', array(':reset_hash' => $hash));
            if ($user) {
                $password = $request->getPost('password');
                $password2 = $request->getPost('password2');

                if ($password == $password2) {
                    if ($user->setNewPass($password)) {
                        $result = array(
                            'result'    => ApiStatus::SUCCESS,
                            'message'   => 'You password has been changed. Now you can login with him'
                        );
                    } else {
                        $result = array(
                            'result'    => ApiStatus::ERROR,
                            'message'   => 'Something went wrong, please try later'
                        );
                    }
                } else {
                    $result = array(
                        'result'    => ApiStatus::ERROR,
                        'message'   => 'Passwords did not match'
                    );
                }
            } else {
                $result = array(
                    'result'    => ApiStatus::ERROR,
                    'message'   => 'Your reset link expired, please try again'
                );
            }
        } else {
            $result = array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Invalid restore link, please try again'
            );
        }

        $this->renderJSON($result);
    }

    public function actionUpgrade()
    {
        // Get upgrade plan
        $plan = Yii::app()->request->getPost('plan');

        if ($user_id = Yii::app()->user->getId()) {
            if ($artists = UserApi::upgrade($user_id, $plan)) {
                $result = array(
                    'result'    => ApiStatus::SUCCESS,
                    'message'   => 'Your account plan was succesfully updated',
                    'user'      => User::getLogged()->getNormalizedData(true, true)
                );
            } else {
                $result = array(
                    'result'    => ApiStatus::ERROR,
                    'message'   => 'Can\'t upgrade your plan. Please contact to support'
                );
            }
        } else {
            $result = array(
                'result'    => ApiStatus::REQ_LOGIN,
                'message'   => 'Please login first'
            );
        }

        $this->renderJSON($result);
    }

    public function actionFBLogin()
    {
        $r = Yii::app()->request;

        // Get data
        $fb_id = $r->getPost('userID');
        $email = $r->getPost('email');

        // Check required data
        if (!$fb_id) {
            $this->renderJSON(array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Facebook authentication failed. Please contact to support.'
            ));
            return;
        }

        // Check existing record in DB
        $users = UserApi::getByFacebookIdOrEmail($fb_id, $email);
        if (count($users)) {
            $user = reset($users);
            if (count($users) == 1 && isset($user['auth_token']) && !empty($user['auth_token'])) {
                $user = User::model()->findByPk($user['id']);
                if ($user->login()) {
                    $result = array(
                        'result'    => ApiStatus::SUCCESS,
                        'type'      => self::ACTION_LOGIN,
                        'data'      => User::getLogged()->getNormalizedData(true, true)
                    );
                } else {
                    $result = array(
                        'result'    => ApiStatus::ERROR,
                        'message'   => 'Login failed. Please contact to support.',
                    );
                }
            } else {
                $data = array();
                foreach ($users as $user) {
                    $data[] = User::model()->findByPk($user['id'])->getNormalizedData(true, true);
                }
                $result = array(
                    'result'    => ApiStatus::SUCCESS,
                    'type'      => self::ACTION_MERGE,
                    'data'      => $data
                );
            }
        } else {
            // Get or create user entity by email
            $user = new User;
            $user->email = $email;
            $user->setRandomPass();
            $user->save();

            // Compile result
            $result = array(
                'result'    => ApiStatus::SUCCESS,
                'type'      => self::ACTION_IMPORT,
                'data'      => $user->getNormalizedData(true)
            );
        }

        $this->renderJSON($result);
    }

    public function actionFBImport()
    {
        $r = Yii::app()->request;

        // Check existing record in DB
        $user_id = $r->getPost('user_id');
        $user = User::model()->findByPk($user_id);

        if (!$user) {
            $this->renderJSON(array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Import failed. Please contact to support.',
            ));
            return;
        }

        // Check pass for imported user
        $password = $r->getPost('password');
        if (empty($password) && $r->getPost('type') == ApiUserController::ACTION_IMPORT) {
            $this->renderJSON(array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Password required.',
            ));
            return;
        }

        // Begin transaction
        $connection = Yii::app()->db;
        $transaction = $connection->beginTransaction();

        // Update user
        $user->email = $r->getPost('email');
        $user->role = $r->getPost('role', User::ROLE_PROMOTER);
        $user->auth_token = $r->getPost('auth_token');

        $password = $r->getPost('password');
        if ($password) {
            $user->password = CPasswordHelper::hashPassword($password);
        }

        if (!$user->save()) {
            $transaction->rollback();
            $this->renderJSON(array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Can\' update user record. Please contact to support.'
            ));
            return;
        }

        // Check role and update appropriate entity
        if ($user->role == User::ROLE_PROMOTER) {
            $promoter = $user->promoter();
            if (!$promoter) {
                $promoter = new Promoter();
                $promoter->user_id = $user->id;
            }

            $promoter->fb_id = $r->getPost('fb_id');

            $promoter->name = $r->getPost('name');
            $promoter->address = $r->getPost('address');

            $promoter->latitude = $r->getPost('latitude', Model::DEFAULT_LATITUDE);
            $promoter->longitude = $r->getPost('longitude', Model::DEFAULT_LONGITUDE);
            $promoter->radius = Model::DEFAULT_RADIUS;

            $promoter->facebook = $r->getPost('facebook');
            $promoter->homepage = $r->getPost('homepage');

            if (!$promoter->save()) {
                $transaction->rollback();
                $this->renderJSON(array(
                    'result'    => ApiStatus::ERROR,
                    'message'   => 'Can\' update promoter record. Please contact to support.'
                ));
                return;
            }
        } else {
            $artist = $user->artist();
            if (!$artist) {
                $artist = new Artist();
                $artist->user_id = $user->id;
            }

            $artist->fb_id = $r->getPost('fb_id');

            $artist->name = $r->getPost('name');
            $artist->description = $r->getPost('address');

            $artist->latitude = $r->getPost('latitude', Model::DEFAULT_LATITUDE);
            $artist->longitude = $r->getPost('longitude', Model::DEFAULT_LONGITUDE);

            if (!$artist->save()) {
                $transaction->rollback();
                $this->renderJSON(array(
                    'result'    => ApiStatus::ERROR,
                    'message'   => 'Can\' update artist record. Please contact to support.'
                ));
                return;
            }
        }

        // Apply all changes
        $transaction->commit();

        // Try to login
        if (!$user->login()) {
            $this->renderJSON(array(
                'result'    => ApiStatus::ERROR,
                'message'   => 'Can\' login to portal. Please contact to support.'
            ));
        }

        // Return data
        $this->renderJSON(array(
            'result'    => ApiStatus::SUCCESS,
            'message'   => 'Your profile was successfully created.',
            'data'      => $user->getNormalizedData(true, true)
        ));
    }
}


text:
package org.apache.geode.internal.cache;

// DO NOT modify this class. It was generated from LeafRegionEntry.cpp

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

import org.apache.geode.cache.EntryEvent;

import org.apache.geode.internal.cache.lru.EnableLRU;

import org.apache.geode.internal.cache.lru.LRUClockNode;
import org.apache.geode.internal.cache.lru.NewLRUClockHand;

import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.versions.VersionSource;
import org.apache.geode.internal.cache.versions.VersionStamp;
import org.apache.geode.internal.cache.versions.VersionTag;

import org.apache.geode.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry;

// macros whose definition changes this class:
// disk: DISK
// lru: 1
// stats: STATS
// versioned: 1
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: KEY_OBJECT
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: 1
// key string2: KEY_STRING2

/**
 * Do not modify this class. It was generated. Instead modify LeafRegionEntry.cpp and then run
 * ./dev-tools/generateRegionEntryClasses.sh (it must be run from the top level directory).
 */
public class VersionedThinLRURegionEntryHeapStringKey1 extends VersionedThinLRURegionEntryHeap {
  public VersionedThinLRURegionEntryHeapStringKey1(RegionEntryContext context, String key,

      Object value

      , boolean byteEncode

  ) {
    super(context,

        value

    );
    // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

    // caller has already confirmed that key.length <= MAX_INLINE_STRING_KEY
    long tmpBits1 = 0L;
    if (byteEncode) {
      for (int i = key.length() - 1; i >= 0; i--) {
        // Note: we know each byte is <= 0x7f so the "& 0xff" is not needed. But I added it in to
        // keep findbugs happy.
        tmpBits1 |= (byte) key.charAt(i) & 0xff;
        tmpBits1 <<= 8;
      }
      tmpBits1 |= 1 << 6;
    } else {
      for (int i = key.length() - 1; i >= 0; i--) {
        tmpBits1 |= key.charAt(i);
        tmpBits1 <<= 16;
      }
    }
    tmpBits1 |= key.length();
    this.bits1 = tmpBits1;

  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  // common code
  protected int hash;
  private HashEntry<Object, Object> next;
  @SuppressWarnings("unused")
  private volatile long lastModified;
  private static final AtomicLongFieldUpdater<VersionedThinLRURegionEntryHeapStringKey1> lastModifiedUpdater =
      AtomicLongFieldUpdater.newUpdater(VersionedThinLRURegionEntryHeapStringKey1.class,
          "lastModified");

  private volatile Object value;

  @Override
  protected Object getValueField() {
    return this.value;
  }

  @Override
  protected void setValueField(Object v) {
    this.value = v;
  }

  protected long getLastModifiedField() {
    return lastModifiedUpdater.get(this);
  }

  protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
    return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
  }

  /**
   * @see HashEntry#getEntryHash()
   */
  public int getEntryHash() {
    return this.hash;
  }

  protected void setEntryHash(int v) {
    this.hash = v;
  }

  /**
   * @see HashEntry#getNextEntry()
   */
  public HashEntry<Object, Object> getNextEntry() {
    return this.next;
  }

  /**
   * @see HashEntry#setNextEntry
   */
  public void setNextEntry(final HashEntry<Object, Object> n) {
    this.next = n;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  // lru code
  @Override
  public void setDelayedDiskId(LocalRegion r) {

    // nothing needed for LRUs with no disk

  }

  public synchronized int updateEntrySize(EnableLRU capacityController) {
    return updateEntrySize(capacityController, _getValue()); // OFHEAP: _getValue ok w/o incing
                                                             // refcount because we are synced and
                                                             // only getting the size
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  public synchronized int updateEntrySize(EnableLRU capacityController, Object value) {
    int oldSize = getEntrySize();
    int newSize = capacityController.entrySize(getKeyForSizing(), value);
    setEntrySize(newSize);
    int delta = newSize - oldSize;
    return delta;
  }

  public boolean testRecentlyUsed() {
    return areAnyBitsSet(RECENTLY_USED);
  }

  @Override
  public void setRecentlyUsed() {
    setBits(RECENTLY_USED);
  }

  public void unsetRecentlyUsed() {
    clearBits(~RECENTLY_USED);
  }

  public boolean testEvicted() {
    return areAnyBitsSet(EVICTED);
  }

  public void setEvicted() {
    setBits(EVICTED);
  }

  public void unsetEvicted() {
    clearBits(~EVICTED);
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  private LRUClockNode nextLRU;
  private LRUClockNode prevLRU;
  private int size;

  public void setNextLRUNode(LRUClockNode next) {
    this.nextLRU = next;
  }

  public LRUClockNode nextLRUNode() {
    return this.nextLRU;
  }

  public void setPrevLRUNode(LRUClockNode prev) {
    this.prevLRU = prev;
  }

  public LRUClockNode prevLRUNode() {
    return this.prevLRU;
  }

  public int getEntrySize() {
    return this.size;
  }

  protected void setEntrySize(int size) {
    this.size = size;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  @Override
  public Object getKeyForSizing() {

    // inline keys always report null for sizing since the size comes from the entry size
    return null;

  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  // versioned code
  private VersionSource memberID;
  private short entryVersionLowBytes;
  private short regionVersionHighBytes;
  private int regionVersionLowBytes;
  private byte entryVersionHighByte;
  private byte distributedSystemId;

  public int getEntryVersion() {
    return ((entryVersionHighByte << 16) & 0xFF0000) | (entryVersionLowBytes & 0xFFFF);
  }

  public long getRegionVersion() {
    return (((long) regionVersionHighBytes) << 32) | (regionVersionLowBytes & 0x00000000FFFFFFFFL);
  }

  public long getVersionTimeStamp() {
    return getLastModified();
  }

  public void setVersionTimeStamp(long time) {
    setLastModified(time);
  }

  public VersionSource getMemberID() {
    return this.memberID;
  }

  public int getDistributedSystemId() {
    return this.distributedSystemId;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  public void setVersions(VersionTag tag) {
    this.memberID = tag.getMemberID();
    int eVersion = tag.getEntryVersion();
    this.entryVersionLowBytes = (short) (eVersion & 0xffff);
    this.entryVersionHighByte = (byte) ((eVersion & 0xff0000) >> 16);
    this.regionVersionHighBytes = tag.getRegionVersionHighBytes();
    this.regionVersionLowBytes = tag.getRegionVersionLowBytes();
    if (!(tag.isGatewayTag()) && this.distributedSystemId == tag.getDistributedSystemId()) {
      if (getVersionTimeStamp() <= tag.getVersionTimeStamp()) {
        setVersionTimeStamp(tag.getVersionTimeStamp());
      } else {
        tag.setVersionTimeStamp(getVersionTimeStamp());
      }
    } else {
      setVersionTimeStamp(tag.getVersionTimeStamp());
    }
    this.distributedSystemId = (byte) (tag.getDistributedSystemId() & 0xff);
  }

  public void setMemberID(VersionSource memberID) {
    this.memberID = memberID;
  }

  @Override
  public VersionStamp getVersionStamp() {
    return this;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  public VersionTag asVersionTag() {
    VersionTag tag = VersionTag.create(memberID);
    tag.setEntryVersion(getEntryVersion());
    tag.setRegionVersion(this.regionVersionHighBytes, this.regionVersionLowBytes);
    tag.setVersionTimeStamp(getVersionTimeStamp());
    tag.setDistributedSystemId(this.distributedSystemId);
    return tag;
  }

  public void processVersionTag(LocalRegion r, VersionTag tag, boolean isTombstoneFromGII,
      boolean hasDelta, VersionSource thisVM, InternalDistributedMember sender,
      boolean checkForConflicts) {
    basicProcessVersionTag(r, tag, isTombstoneFromGII, hasDelta, thisVM, sender, checkForConflicts);
  }

  @Override
  public void processVersionTag(EntryEvent cacheEvent) {
    // this keeps Eclipse happy. without it the sender chain becomes confused
    // while browsing this code
    super.processVersionTag(cacheEvent);
  }

  /** get rvv internal high byte. Used by region entries for transferring to storage */
  public short getRegionVersionHighBytes() {
    return this.regionVersionHighBytes;
  }

  /** get rvv internal low bytes. Used by region entries for transferring to storage */
  public int getRegionVersionLowBytes() {
    return this.regionVersionLowBytes;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  // key code

  private final long bits1;

  private int getKeyLength() {
    return (int) (this.bits1 & 0x003fL);
  }

  private int getEncoding() {
    // 0 means encoded as char
    // 1 means encoded as bytes that are all <= 0x7f;
    return (int) (this.bits1 >> 6) & 0x03;
  }

  @Override
  public Object getKey() {
    int keylen = getKeyLength();
    char[] chars = new char[keylen];
    long tmpBits1 = this.bits1;
    if (getEncoding() == 1) {
      for (int i = 0; i < keylen; i++) {
        tmpBits1 >>= 8;
        chars[i] = (char) (tmpBits1 & 0x00ff);
      }
    } else {
      for (int i = 0; i < keylen; i++) {
        tmpBits1 >>= 16;
        chars[i] = (char) (tmpBits1 & 0x00FFff);
      }
    }
    return new String(chars);
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  @Override
  public boolean isKeyEqual(Object k) {
    if (k instanceof String) {
      String str = (String) k;
      int keylen = getKeyLength();
      if (str.length() == keylen) {
        long tmpBits1 = this.bits1;
        if (getEncoding() == 1) {
          for (int i = 0; i < keylen; i++) {
            tmpBits1 >>= 8;
            char c = (char) (tmpBits1 & 0x00ff);
            if (str.charAt(i) != c) {
              return false;
            }
          }
        } else {
          for (int i = 0; i < keylen; i++) {
            tmpBits1 >>= 16;
            char c = (char) (tmpBits1 & 0x00FFff);
            if (str.charAt(i) != c) {
              return false;
            }
          }
        }
        return true;
      }
    }
    return false;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/methods', __FILE__)

describe "Time#usec" do
  it "returns the microseconds for time" do
    Time.at(0).usec.should == 0
    (Time.at(1.1) + 0.9).usec.should == 0
    (Time.at(1.1) - 0.2).usec.should == 900000
  end

  ruby_version_is "1.9" do
    it "returns the microseconds for time created by Time#local" do
      Time.local(1,2,3,4,5,Rational(6.78)).usec.should == 780000
    end
  end
end


text:
import { handleActions } from 'redux-actions';
import { SAVE_COMMENT } from '../actions/types';

export default handleActions({
    [SAVE_COMMENT]: (state, { payload }) => [...state, payload]
}, []);


text:
class ManageIQ::Providers::<%= class_name %>::CloudManager::EventCatcher::Runner < ManageIQ::Providers::BaseManager::EventCatcher::Runner
  def stop_event_monitor
    event_monitor_handle.stop
  end

  def monitor_events
    event_monitor_handle.start
    event_monitor_running
    event_monitor_handle.poll do |event|
      @queue.enq event
    end
  ensure
    stop_event_monitor
  end

  def queue_event(event)
    _log.info "#{log_prefix} Caught event [#{event[:id]}]"
    event_hash = event_to_hash(event, @cfg[:ems_id])
    EmsEvent.add_queue('add', @cfg[:ems_id], event_hash)
  end

  private

  def event_to_hash(event, ems_id)
    {
      :event_type => "DUMMY_PROVIDER_#{event[:name]}",
      :source     => 'DUMMY_PROVIDER',
      :timestamp  => event[:timestamp],
      :vm_ems_ref => event[:vm_ems_ref],
      :full_data  => event,
      :ems_id     => ems_id
    }
  end

  def event_monitor_handle
    @event_monitor_handle ||= begin
      self.class.parent::Stream.new(
        @ems,
        :poll_sleep => worker_settings[:poll]
      )
    end
  end
end


text:
package com.zaxxer.nuprocess.osx;

import java.nio.file.Path;

import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.StringArray;
import com.sun.jna.ptr.IntByReference;
import com.zaxxer.nuprocess.NuProcessHandler;
import com.zaxxer.nuprocess.internal.BasePosixProcess;
import com.zaxxer.nuprocess.internal.LibC;
import com.zaxxer.nuprocess.internal.LibC.SyscallLibrary;

/**
 * @author Brett Wooldridge
 */
public class OsxProcess extends BasePosixProcess
{
   static {
      for (int i = 0; i < processors.length; i++) {
         processors[i] = new ProcessKqueue();
      }

      // Setup a private signal for waking up the kqueue processing threads
      LibC.signal(LibC.SIGUSR2, LibC.SIG_IGN);
   }

   public OsxProcess(NuProcessHandler processListener) {
      super(processListener);
   }

   void stdinClose()
   {
      int fd = stdin.getAndSet(-1);
      if (fd != -1) {
         LibC.close(fd);
      }
   }

   @Override
   protected short getSpawnFlags()
   {
      // Start the spawned process in suspended mode
      return LibC.POSIX_SPAWN_START_SUSPENDED | LibC.POSIX_SPAWN_CLOEXEC_DEFAULT;
   }

   @Override
   protected Pointer createPosixSpawnFileActions()
   {
      return new Memory(Pointer.SIZE);
   }

   @Override
   protected Pointer createPosixSpawnAttributes()
   {
      return new Memory(Pointer.SIZE);
   }

   @Override
   protected int spawnWithCwd(final IntByReference restrict_pid,
                              final String restrict_path,
                              final Pointer file_actions,
                              final Pointer /*const posix_spawnattr_t*/ restrict_attrp,
                              final StringArray /*String[]*/ argv,
                              final Pointer /*String[]*/ envp,
                              final Path cwd)
   {
      int cwdBufSize = 1024;
      long peer = Native.malloc(cwdBufSize);
      Pointer oldCwd = new Pointer(peer);
      LibC.getcwd(oldCwd, cwdBufSize);
      String newCwd = cwd.toAbsolutePath().toString();
      int rc = LibC.SYSCALL.syscall(SyscallLibrary.SYS___pthread_chdir, newCwd);
      checkReturnCode(rc, "syscall(SYS__pthread_chdir) failed to set current directory");

      try {
         return LibC.posix_spawnp(restrict_pid, restrict_path, file_actions, restrict_attrp, argv, envp);
      }
      finally {
         rc = LibC.SYSCALL.syscall(SyscallLibrary.SYS___pthread_chdir, oldCwd);
         Native.free(Pointer.nativeValue(oldCwd));
         checkReturnCode(rc, "syscall(SYS__pthread_chdir) failed to restore current directory");
      }
   }

   @Override
   protected void singleProcessContinue()
   {
      // Signal the spawned process to continue (unsuspend)
      LibC.kill(pid, LibC.SIGCONT);
   }
}


text:
import { vi, describe, it, expect, afterEach, beforeEach } from 'vitest'
import { launch, cmdArgs } from '../src/commands/run.js'
import Launcher from '../src/launcher.js'

vi.mock('../src/launcher', () => ({
    default: vi.fn().mockImplementation((conf, result) => ({
        run: () => Number.isInteger(result) ? Promise.resolve(result) : Promise.reject(result)
    }))
}))

describe('launch', () => {
    beforeEach(() => {
        vi.spyOn(console, 'error').mockImplementation(() => {})
    })

    it('should exit with code 0', async () => {
        // @ts-ignore mock feature
        await launch('configFile', 0)
        expect(Launcher).toBeCalledWith('configFile', 0)
        expect(vi.mocked(Launcher).mock.instances).toHaveLength(1)
    })

    it('should exit with code 1', async () => {
        // @ts-ignore mock feature
        await launch('configFile', 1)
        expect(Launcher).toBeCalledWith('configFile', 1)
        expect(vi.mocked(Launcher).mock.instances).toHaveLength(1)
    })

    it('should catch errors', async () => {
        // @ts-ignore mock feature
        await launch('configFile', 'foobar')
        expect(Launcher).toBeCalledWith('configFile', 'foobar')
        expect(vi.mocked(Launcher).mock.instances).toHaveLength(1)
        expect(console.error).toBeCalledWith('foobar')
    })

    afterEach(() => {
        vi.mocked(Launcher).mockClear()
        vi.mocked(console.error).mockRestore()
    })
})

describe('cmdArgs', () => {
    it('should not have default', () => {
        Object.values(cmdArgs).forEach(cmdArg => {
            // @ts-ignore test undefined property
            expect(cmdArg.default).toBeUndefined()
        })
    })
})


text:
package ws.epigraph.client.http;

import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.nio.client.HttpAsyncClient;
import org.jetbrains.annotations.NotNull;
import ws.epigraph.invocation.OperationInvocationContext;
import ws.epigraph.projections.StepsAndProjection;
import ws.epigraph.schema.operations.DeleteOperationDeclaration;
import ws.epigraph.service.operations.DeleteOperationRequest;
import ws.epigraph.util.HttpStatusCode;

import java.nio.charset.Charset;

/**
 * @author Konstantin Sobolev
 */
public class RemoteDeleteOperationInvocation
    extends AbstractRemoteOperationInvocation<DeleteOperationRequest, DeleteOperationDeclaration> {

  public RemoteDeleteOperationInvocation(
      final @NotNull HttpHost host,
      final @NotNull HttpAsyncClient httpClient,
      final @NotNull String resourceName,
      final @NotNull DeleteOperationDeclaration operationDeclaration,
      final @NotNull ServerProtocol serverProtocol,
      final @NotNull Charset charset) {

    super(host, httpClient, resourceName, operationDeclaration, serverProtocol, charset, HttpStatusCode.OK);
  }

  @Override
  protected HttpRequest composeHttpRequest(
      final @NotNull DeleteOperationRequest operationRequest,
      final @NotNull OperationInvocationContext operationInvocationContext) {

    String uri = UriComposer.composeDeleteUri(
        resourceName,
        operationRequest.path(),
        new StepsAndProjection<>(0, operationRequest.deleteProjection()),
        operationRequest.outputStepsAndProjection()
    );

    return new HttpDelete(uri);
  }

}


text:
#pragma once
#include <aws/auditmanager/AuditManager_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace AuditManager
{
namespace Model
{

  /**
   *
 Indicates that the request has invalid or missing parameters for the field.
   *

See Also:
   AWS
   * API Reference

   */
  class AWS_AUDITMANAGER_API ValidationExceptionField
  {
  public:
    ValidationExceptionField();
    ValidationExceptionField(Aws::Utils::Json::JsonView jsonValue);
    ValidationExceptionField& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 The name of the validation error.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
 The name of the validation error.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
 The name of the validation error.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
 The name of the validation error.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
 The name of the validation error.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
 The name of the validation error.

     */
    inline ValidationExceptionField& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
 The name of the validation error.

     */
    inline ValidationExceptionField& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
 The name of the validation error.

     */
    inline ValidationExceptionField& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
 The body of the error message.

     */
    inline const Aws::String& GetMessage() const{ return m_message; }

    /**
     *
 The body of the error message.

     */
    inline bool MessageHasBeenSet() const { return m_messageHasBeenSet; }

    /**
     *
 The body of the error message.

     */
    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    /**
     *
 The body of the error message.

     */
    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    /**
     *
 The body of the error message.

     */
    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    /**
     *
 The body of the error message.

     */
    inline ValidationExceptionField& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    /**
     *
 The body of the error message.

     */
    inline ValidationExceptionField& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    /**
     *
 The body of the error message.

     */
    inline ValidationExceptionField& WithMessage(const char* value) { SetMessage(value); return *this;}

  private:

    Aws::String m_name;
    bool m_nameHasBeenSet = false;

    Aws::String m_message;
    bool m_messageHasBeenSet = false;
  };

} // namespace Model
} // namespace AuditManager
} // namespace Aws


text:
// -*- C++ -*-

// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING.  If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.

// As a special exception, you may use this file as part of a free
// software library without restriction.  Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License.  This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file types_traits.hpp
 * Contains a traits class of types used by containers.
 */

#ifndef PB_DS_TYPES_TRAITS_HPP
#define PB_DS_TYPES_TRAITS_HPP

#include <ext/pb_ds/detail/basic_types.hpp>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <utility>

namespace pb_ds
{
  namespace detail
  {
    template<typename Key, typename Mapped, typename Alloc, bool Store_Extra>
    struct vt_base_selector
    {
      typedef value_type_base<Key, Mapped, Alloc, Store_Extra> type;
    };

    template<typename Key, typename Mapped, typename Alloc, bool Store_Extra>
    struct types_traits
    : public vt_base_selector<Key, Mapped, Alloc, Store_Extra>::type
    {
      typedef typename Alloc::template rebind<Key>::other key_allocator;
      typedef typename key_allocator::value_type key_type;
      typedef typename key_allocator::pointer key_pointer;
      typedef typename key_allocator::const_pointer const_key_pointer;
      typedef typename key_allocator::reference key_reference;
      typedef typename key_allocator::const_reference const_key_reference;
      typedef typename Alloc::size_type size_type;

      // Extra value (used when the extra value is stored with each value).
      typedef std::pair<size_type, size_type> comp_hash;

      integral_constant<int, Store_Extra> m_store_extra_indicator;
      typename no_throw_copies<Key, Mapped>::indicator m_no_throw_copies_indicator;
    };
  } // namespace detail
} // namespace pb_ds

#endif


text:
@class NSString;

@interface LBSLifeActionBooking : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) NSString *title; // @dynamic title;
@property(nonatomic) unsigned int type; // @dynamic type;
@property(retain, nonatomic) NSString *url; // @dynamic url;

@end


text:
<?php

namespace liquorwise;

use Carbon\Carbon;

class ThemeSettings
{

    protected $file;

    protected $output_file;

    protected $pid_file;

    public function __construct()
    {
        // Set file locations
        $this->file = __DIR__ . "/../assets/styles/common/_theme-settings.scss";
        $this->output_file = __DIR__ . "/../liquorwise/log/FIXME-output.txt";
        $this->pid_file = __DIR__ . "/../liquorwise/log/FIXME-pid.txt";

    }

    public function registerThemeSettingsPages()
    {
        // Register theme options page
        if (function_exists('acf_add_options_page')) {
            acf_add_options_page([
                'page_title' => 'Theme General Settings',
                'menu_title' => 'Theme General Settings',
                'menu_slug'  => 'theme-general-settings',
                'capability' => 'edit_posts',
                'redirect'   => false,
            ]);
        }
    }

    public function compileAssetsAfterThemeSettingsSave($post_id)
    {
        $screen = get_current_screen();
        $slug = "theme-general-settings";

        if (preg_match("/".$slug."/", $screen->id)) {
            $time = Carbon::now('Europe/London')->timestamp;

            $output_file = str_replace('FIXME', $time, $this->output_file);
            $pid_file = str_replace('FIXME', $time, $this->pid_file);

            // Get new value
            $main_site_color = get_field('main_site_color');
            $border_shadow_color = get_field('secondary_site_color');
            $foreground = get_field('foreground');
            $background = get_field('background');
            $section_background = get_field('section_background');
            $section_separator = get_field('section_separator');

            $content = "// DO NOT EDIT THIS FILE! IT IS AUTOMATICALLY GENERATED WHEN YOU SAVE THEME SETTINGS!\n";

            if (!empty($main_site_color)) {
                $content .= "\$red: {$main_site_color};\n";
            }

            if (!empty($border_shadow_color)) {
                $content .= "\$red-bg: {$border_shadow_color};\n";
            }

            if (!empty($foreground)) {
                $content .= "\$white: {$foreground};\n";
            }

            if (!empty($background)) {
                $content .= "\$black: {$background};\n";
            }

            if (!empty($section_background)) {
                $content .= "\$gray-bg: {$section_background};\n";
            }

            if (!empty($section_separator)) {
                $content .= "\$gray: {$section_separator};";
            }

            if (!file_exists($this->file)) {
                file_put_contents($this->file, '');
                chmod($this->file, 0777);
            }

            file_put_contents($this->file, $content);

            $gulp = exec('which gulp');
            $theme_dir = get_template_directory();

            $command = "cd {$theme_dir} && {$gulp} --production";

            exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $command, $output_file, $pid_file));
        }
    }
}


text:
using System;
using System.Configuration.Provider;

namespace SharedCache.WinServiceCommon.Provider.Server
{
	/// <summary>
	/// Represents a collection of provider objects that inherit from System.Configuration.Provider.ProviderCollection
	/// </summary>
	public class IndexusServerProviderCollection : ProviderCollection
	{
		/// <summary>
		/// Gets the <see cref="SharedCache.WinServiceCommon.Provider.Cache.IndexusProviderBase"/> with the specified name.
		/// </summary>
		/// <value></value>
		public new IndexusServerProviderBase this[string name]
		{
			get
			{
				return (IndexusServerProviderBase)base[name];
			}
		}

		/// <summary>
		/// Adds a provider to the collection.
		/// </summary>
		/// <param name="provider">The provider to be added.</param>
		/// <exception cref="T:System.ArgumentException">The <see cref="P:System.Configuration.Provider.ProviderBase.Name"></see> of provider is null.- or -The length of the <see cref="P:System.Configuration.Provider.ProviderBase.Name"></see> of provider is less than 1.</exception>
		/// <exception cref="T:System.ArgumentNullException">provider is null.</exception>
		/// <exception cref="T:System.NotSupportedException">The collection is read-only.</exception>
		/// <PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/></PermissionSet>
		public override void Add(ProviderBase provider)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("IndexusProviderBase");
			}

			if (!(provider is IndexusServerProviderBase))
			{
				throw new ArgumentException("Invalid provider type", "IndexusProviderBase");
			}

			base.Add(provider);
		}
	}
}


text:
import app from '~/app';
import _ from 'lodash';
import 'ng-breadcrumbs';
import 'cbd-forums';
import '~/services/main';

    export { default as template } from './post-list-view.html';
export default ["$scope", "$http", "$q", "$route", "$routeParams","commonjs","$rootScope",'breadcrumbs',
     function($scope, $http, $q, $route, $routeParams, commonjs, $rootScope, breadcrumbs) {

        if (!$route.current.$$route.forumListUrl) {
            throw 'Forum list URL not specified in route, please forumListUrl attribute in routes'
        } else
            $scope.forumListUrl = $route.current.$$route.forumListUrl;

        $scope.forum = $route.current.$$route.text;
        $scope.forumId = $route.current.$$route.forumId
        $scope.threadId = $routeParams.threadId;

        var thread = $http.get('/api/v2014/discussions/threads/' + $scope.threadId);
        $q.when(thread).then(function(response) {

            $scope.threadSubject = response.data.subject;

            console.log(breadcrumbs);

            breadcrumbs.options = {'thread_subject': response.data.subject};

        });

        $scope.isAdmin = function(){
            return roleService.isAdministrator();

        }

        $scope.$on('signIn', function(evt, user){
           $route.reload();
        });

    }];


text:
/*!
** \file drwnVarAssignment.h
** \anchor drwnVarAssignment
** \brief Data structures and utilities for encoding assignments to variables.
*/

#pragma once

#include <cstdlib>
#include <cassert>
#include <vector>
#include <map>

#include "drwnGraphUtils.h"
#include "drwnVarUniverse.h"

using namespace std;

// drwnFullAssignment ------------------------------------------------------
//! defines a complete assignment to all variables in the universe

typedef std::vector<int> drwnFullAssignment;

// drwnPartialAssignment ---------------------------------------------------
//! defines an assignment to a subset of the variables

class drwnPartialAssignment : public std::map<int, int> {
 public:
    //! construct an empty partial assignment
    drwnPartialAssignment() { /* do nothing */ }
    //! construct a partial assignment from a full assignment (values of -1
    //! in the full assignment are ignored)
    explicit drwnPartialAssignment(const drwnFullAssignment& a) {
        for (int i = 0; i < (int)a.size(); i++) {
            if (a[i] >= 0) {
                this->insert(make_pair(i, a[i]));
            }
        }
    }

    //! construct a partial assignment from a full assignment over a subset
    //! of the variables
    drwnPartialAssignment(const drwnFullAssignment& a, const drwnClique& c) {
        for (drwnClique::const_iterator it = c.begin(); it != c.end(); ++it) {
            if (a[*it] >= 0) {
                this->insert(make_pair(*it, a[*it]));
            }
        }
    }

    //! return the clique of variables over which the partial
    //! assignment is defined
    drwnClique getClique() const {
        drwnClique c;
        for (const_iterator it = begin(); it != end(); ++it) {
            c.insert(it->first);
        }
        return c;
    }

    //! typecast a partial assignment to a full assignment (missing values
    //! are assigned -1)
    operator drwnFullAssignment() const {
        drwnFullAssignment a(this->rbegin()->first + 1, -1);
        for (const_iterator it = begin(); it != end(); ++it) {
            a[it->first] = it->second;
        }
        return a;
    }
};

// utility functions -------------------------------------------------------

//! next full assignment
void successor(drwnFullAssignment& assignment, const drwnVarUniverse& universe);
//! previous full assignment
void predecessor(drwnFullAssignment& assignment, const drwnVarUniverse& universe);
//! next partial assignment
void successor(drwnPartialAssignment& assignment, const drwnVarUniverse& universe);
//! previous partial assignment
void predecessor(drwnPartialAssignment& assignment, const drwnVarUniverse& universe);


text:
var ReactInstanceMap = require('ReactInstanceMap');

var emptyObject = require('fbjs/lib/emptyObject');
var invariant = require('fbjs/lib/invariant');

var getContextFiber = function getContextFiber(arg) {
  invariant(false, 'Missing injection for fiber getContextForSubtree');
};

function getContextForSubtree(parentComponent) {
  if (!parentComponent) {
    return emptyObject;
  }

  var instance = ReactInstanceMap.get(parentComponent);
  if (typeof instance.tag === 'number') {
    return getContextFiber(instance);
  } else {
    return instance._processChildContext(instance._context);
  }
}

getContextForSubtree._injectFiber = function (fn) {
  getContextFiber = fn;
};

module.exports = getContextForSubtree;


text:
/* http://keith-wood.name/countdown.html
   Dutch initialisation for the jQuery countdown extension
   Written by Mathias Bynens <http://mathiasbynens.be/> Mar 2008. */
(function($) {
	$.countdown.regionalOptions['nl'] = {
		labels: ['Jaren', 'Maanden', 'Weken', 'Dagen', 'Uren', 'Minuten', 'Seconden'],
		labels1: ['Jaar', 'Maand', 'Week', 'Dag', 'Uur', 'Minuut', 'Seconde'],
		compactLabels: ['j', 'm', 'w', 'd'],
		whichLabels: null,
		digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
		timeSeparator: ':', isRTL: false};
	$.countdown.setDefaults($.countdown.regionalOptions['nl']);
})(jQuery);


text:
/**
* (c) Daniel Lemire, 2008
*This C++ library implements fast nearest-neighbor retrieval under the dynamic time warping (DTW).
* This library includes the dynamic programming solution, a fast implementation of the LB_Keogh
*  lower bound, as well as a improved lower bound called LB_Improved. This library was used to show
*  that LB_Improved can be used to retrieve nearest neighbors three times on several data sets
* including random walks time series or shape time series.
*
* See the classes LB_Keogh and LB_Improved for usage.
*
* Time series are represented using STL vectors.
*/

#ifndef DTW
#define DTW

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <deque>
#include <cassert>
#include <sstream>

// was
//typedef double floattype;
typedef float floattype;
typedef unsigned int uint;
using namespace std;

class MathUtil {
  public:
    static inline int min (int x, int y ) { return x < y ? x : y;}
    static inline int max (int x, int y ) { return x > y ? x : y;}
};

/**
* You do not need this class, used by LB_Keogh and LB_Improved later.
* It computes the DTW using dynamic programmming.
*/
class dtw {
    public:

enum{ verbose = false,
   vverbose = false, INF = 100000000, fast=true};
static inline floattype max (floattype x, floattype y ) { return x > y ? x : y;}
static inline floattype min (floattype x, floattype y ) { return x < y ? x : y;}

    dtw(uint n, uint constraint): mGamma(n,vector<floattype>(n,INF)),mN(n),mConstraint(constraint) {
    }
    /*
    * hardcoded l1 norm (for speed)
    */
    inline floattype fastdynamic(const vector<floattype> &  v, const vector<floattype> & w) {
        if(! fast) return dynamic(v,w,mConstraint,1);
        assert(static_cast<int>(v.size()) == mN);
        assert(static_cast<int>(w.size()) == mN);
        assert(static_cast<int>(mGamma.size()) == mN);
        floattype Best(INF);
        for (int i = 0; i < mN;++i) {
            assert(static_cast<int>(mGamma[i].size()) == mN);
            for (int j = max(0,i-mConstraint); j < min(mN,i+mConstraint+1);++j) {
                Best = INF;
                if(i>0) Best = mGamma[i-1][j];
                if(j>0) Best = min(Best, mGamma[i][j-1]);
                if( (i > 0) && (j > 0) )
                 Best = min(Best, mGamma[i-1][j-1]);
                if((i==0) && (j==0))
                  mGamma[i][j] = fabs(v[i]-w[j]);
                else
                  mGamma[i][j] = Best + fabs(v[i]-w[j]);
            }
        }
         return mGamma[mN-1][mN-1];
    }

    vector<vector<floattype> > mGamma;

    int mN, mConstraint;

    static inline floattype dynamic(const vector<floattype> &  v, const vector<floattype> & w,
      int constraint=INF, int p=2) {
          assert(v.size() == w.size());
        int n ( (int)v.size() );
        vector<vector<floattype> > gamma(n, vector<floattype>(n,0.0));
        for (int i = 0; i < n;++i) {
            for (int j = 0; j < n;++j) {
                if(abs(i-j) > constraint) {
                  gamma[i][j] = INF; continue;
                }
                vector<floattype> previous(0);
                if(i>0) previous.push_back(gamma[i-1][j]);
                if(j>0) previous.push_back(gamma[i][j-1]);
                if( (i > 0) && (j > 0) )
                 previous.push_back(gamma[i-1][j-1]);
                floattype smallest = *min_element(previous.begin(),previous.end());
                if (p != INF)
                  gamma[i][j] = pow(fabs(v[i]-w[j]),p)+smallest;
                else
                  gamma[i][j] = max(fabs(v[i] - w[j]), smallest);

            }
        }
        if(p != INF)
         return pow(gamma[n-1][n-1],1.0/p);
        else
         return gamma[n-1][n-1];
      }
};

/**
* You do not need this function, used by LB_Keogh and LB_Improved later.
*/
void computeEnvelope(const vector<floattype> & array, uint constraint, vector<floattype> & maxvalues, vector<floattype> & minvalues) {
        uint width = 1+  2 * constraint;
        deque<int> maxfifo, minfifo;
        maxfifo.push_back(0);
        minfifo.push_back(0);
        for(uint i = 1; i < array.size(); ++i) {
          if(i >=constraint+1) {
            maxvalues[i-constraint-1] = array[maxfifo.front()];
            minvalues[i-constraint-1] = array[minfifo.front()];
          }
          if(array[i] > array[i-1]) { //overshoot
            maxfifo.pop_back();
            while(maxfifo.size() > 0) {
              if(array[i] <= array[maxfifo.back()]) break;
              maxfifo.pop_back();
            }
          } else {
            minfifo.pop_back();
            while(minfifo.size() > 0) {
              if(array[i] >= array[minfifo.back()]) break;
              minfifo.pop_back();
            }
          }
          maxfifo.push_back(i);
          minfifo.push_back(i);
         if(i==  width+maxfifo.front()) maxfifo.pop_front();
         else if(i==  width+minfifo.front()) minfifo.pop_front();
        }
        for(uint i = (uint)array.size(); i <= array.size() + constraint; ++i) {
              maxvalues[i-constraint-1] = array[maxfifo.front()];
              minvalues[i-constraint-1] = array[minfifo.front()];
              if(i-maxfifo.front() >= width) maxfifo.pop_front();
              if(i-minfifo.front() >= width) minfifo.pop_front();
        }
}

class NearestNeighbor {
    public:
        NearestNeighbor(const vector<floattype> &  v, int constraint) : mDTW((uint)v.size(),constraint) {}
        virtual floattype test(const vector<floattype> & candidate) {return 0;}//= 0;
        virtual floattype getLowestCost() {return 0;}
        virtual ~NearestNeighbor() {};
        virtual int getNumberOfDTW(){return 0;}
        virtual int getNumberOfCandidates(){return 0;}
        dtw mDTW;
};

class NaiveNearestNeighbor :  public NearestNeighbor {
    public:
    NaiveNearestNeighbor(const vector<floattype> &  v, int constraint) : NearestNeighbor(v,constraint), lb_keogh(0),full_dtw(0),
     V(v),
    bestsofar(dtw::INF) {
    }

    floattype test(const vector<floattype> & candidate) {
        ++lb_keogh;++full_dtw;
        const floattype trueerror = mDTW.fastdynamic(V,candidate);//,mConstraint,1);
        if(trueerror < bestsofar) bestsofar = trueerror;
        return bestsofar;
    }

    void resetStatistics() {
        lb_keogh = 0;
        full_dtw = 0;
    }
    floattype getLowestCost(){return bestsofar;}

    int getNumberOfDTW(){return full_dtw;}

    int getNumberOfCandidates(){return lb_keogh;}

    private:
    int lb_keogh;
    int full_dtw;

    const vector<floattype>   V;
    floattype bestsofar;

};

/**
* Usage: create the object using the time series you want to match again the
* database and some DTW time constraint parameter. Then repeatedly apply
* the test function on the various candidates. The function returns the
* matching cost with the best candidate so far. By keeping track of when
* the cost was lowered, you can find the nearest neighbor in a database.
*
* Only the l1 norm is used.
*/
class LB_Keogh :  public NearestNeighbor{
    public:
    LB_Keogh(const vector<floattype> &  v, int constraint) : NearestNeighbor(v,constraint), lb_keogh(0), full_dtw(0), V(v), mConstraint(constraint),
    bestsofar(dtw::INF), U(V.size(),0), L(V.size(),0) {
        assert(mConstraint>=0);
        assert(mConstraint<static_cast<int>(V.size()));
        computeEnvelope(V,mConstraint,U,L);
    }

    floattype justlb(const vector<floattype> & candidate) {
        floattype error (0.0);
        for(uint i = 0; i < V.size();++i) {
            if(candidate[i] > U[i])
              error += candidate[i] - U[i];
            else if(candidate[i] < L[i])
              error += L[i] - candidate[i];
        }
        return error;
    }
    floattype test(const vector<floattype> & candidate) {
        ++lb_keogh;
        floattype error (0.0);
        for(uint i = 0; i < V.size();++i) {
            if(candidate[i] > U[i])
              error += candidate[i] - U[i];
            else if(candidate[i] < L[i])
              error += L[i] - candidate[i];
        }
        //cout << "lb keogh = "<<error<<endl;
        if(error < bestsofar) {
            ++full_dtw;
            const floattype trueerror = mDTW.fastdynamic(V,candidate);//,mConstraint,1);
            if(trueerror < bestsofar) bestsofar = trueerror;
        }
        return bestsofar;
    }

    int getNumberOfDTW(){return full_dtw;}

    int getNumberOfCandidates(){return lb_keogh;}

    floattype getLowestCost(){return bestsofar;}

    void resetStatistics() {
        lb_keogh = 0;
        full_dtw = 0;
    }

    private:

    int lb_keogh;
    int full_dtw;
    const vector<floattype>   V;
    int mConstraint;
    floattype bestsofar;
    vector<floattype>   U;
    vector<floattype>   L;

};

class LB_KeoghEarly :  public NearestNeighbor{
    public:
    LB_KeoghEarly(const vector<floattype> &  v, int constraint) : NearestNeighbor(v,constraint), lb_keogh(0), full_dtw(0), V(v), mConstraint(constraint),
    bestsofar(dtw::INF), U(V.size(),0), L(V.size(),0) {
        assert(mConstraint>=0);
        assert(mConstraint<static_cast<int>(V.size()));
        computeEnvelope(V,mConstraint,U,L);
    }

    floattype test(const vector<floattype> & candidate) {
        ++lb_keogh;
        floattype error (0.0);
        for(uint i = 0; i < V.size();++i) {
            if(candidate[i] > U[i])
              error += candidate[i] - U[i];
            else if(candidate[i] < L[i])
              error += L[i] - candidate[i];
            if(error > bestsofar) return bestsofar;
        }
            ++full_dtw;
            const floattype trueerror = mDTW.fastdynamic(V,candidate);//,mConstraint,1);
            if(trueerror < bestsofar) bestsofar = trueerror;
        return bestsofar;
    }

    int getNumberOfDTW(){return full_dtw;}

    int getNumberOfCandidates(){return lb_keogh;}

    floattype getLowestCost(){return bestsofar;}

    void resetStatistics() {
        lb_keogh = 0;
        full_dtw = 0;
    }

    private:

    int lb_keogh;
    int full_dtw;
    const vector<floattype>   V;
    int mConstraint;
    floattype bestsofar;
    vector<floattype>   U;
    vector<floattype>   L;

};

/**
* Usage (same as LB_Keogh): create the object using the time series you want to match again the
* database and some DTW time constraint parameter. Then repeatedly apply
* the test function on the various candidates. The function returns the
* matching cost with the best candidate so far. By keeping track of when
* the cost was lowered, you can find the nearest neighbor in a database.
*
* Only the l1 norm is used.
*/
class LB_Improved : public  NearestNeighbor{
    public:
    LB_Improved(const vector<floattype> &  v, int constraint) : NearestNeighbor(v,constraint), lb_keogh(0), full_dtw(0), V(v), buffer(v), mConstraint(constraint),
    bestsofar(dtw::INF), U(V.size(),0), L(V.size(),0), U2(V.size(),0), L2(V.size(),0) {
        assert(mConstraint>=0);
        assert(mConstraint<static_cast<int>(V.size()));
        computeEnvelope(V,mConstraint,U,L);
    }

    void resetStatistics() {
        lb_keogh = 0;
        full_dtw = 0;
    }

    floattype justlb(const vector<floattype> & candidate) {
        floattype error (0.0);
        buffer = candidate;
        for(uint i = 0; i < V.size();++i) {
            if(candidate[i] > U[i])
              error += candidate[i] - U[i];
            else if(candidate[i] < L[i])
              error += L[i] - candidate[i];
        }
        computeEnvelope(buffer,mConstraint,U2,L2);
        for(uint i = 0; i < V.size();++i) {
                if(V[i] > U2[i]) {
                      error += V[i] - U2[i];
                } else if(V[i] < L2[i]) {
                      error += L2[i] - V[i];
                }
        }
        return error;
    }

    floattype test(const vector<floattype>  &candidate) {
        //memcpy(&buffer[0], &candidate[0],buffer.size()*sizeof(floattype));// = candidate;
        //buffer = candidate;
        //vector<floattype> & buffer(candidate);// no need for a copy
        ++lb_keogh;
        floattype error (0.0);
        for(uint i = 0; i < V.size();++i) {
            const floattype & cdi (candidate[i]);
            if(cdi > U[i]) {
              error += cdi - (buffer[i] = U[i]);
            } else if(cdi < L[i]) {
              error += (buffer[i] = L[i]) - cdi;
            } else buffer[i] = cdi;
        }
        if(error < bestsofar) {
            computeEnvelope(buffer,mConstraint,U2,L2);
            //env.compute(buffer,mConstraint,U2,L2);
            for(uint i = 0; i < V.size();++i) {
                if(V[i] > U2[i]) {
                      error += V[i] - U2[i];
                } else if(V[i] < L2[i]) {
                      error += L2[i] - V[i];
                }
            }
            if(error < bestsofar) {
                ++full_dtw;
                const floattype trueerror = mDTW.fastdynamic(V,candidate);//,mConstraint,1);
                if(trueerror < bestsofar) bestsofar = trueerror;
            }
        }
        return bestsofar;
    }

    /**
    * for plotting purposes
    */
    string dumpTextDescriptor(const vector<floattype>  &candidate) {
        //memcpy(&buffer[0], &candidate[0],buffer.size()*sizeof(floattype));// = candidate;
        buffer = candidate;
        //vector<floattype> & buffer(candidate);// no need for a copy
        ++lb_keogh;
        floattype error (0.0);
        for(uint i = 0; i < V.size();++i) {
            if(candidate[i] > U[i]) {
              error += candidate[i] - U[i];
              buffer[i] = U[i];
            } else if(candidate[i] < L[i]) {
              error += L[i] - candidate[i];
              buffer[i] = L[i];
            }
            assert((buffer[i]== L[i]) or (buffer[i] == U[i]) or (buffer[i] == candidate[i]));

        }
        vector<floattype> lbimprovedarray;
        computeEnvelope(buffer,mConstraint,U2,L2);
        for(uint i = 0; i < V.size();++i) {
                if(V[i] > U2[i]) {
                      error += V[i] - U2[i];
                      lbimprovedarray.push_back(U2[i]);
                } else if(V[i] < L2[i]) {
                      error += L2[i] - V[i];
                      lbimprovedarray.push_back(L2[i]);
                } else
                    lbimprovedarray.push_back(V[i]);

        }
        stringstream ss;
        for(uint k = 0; k <V.size(); ++k) {
            assert((lbimprovedarray[k]== L2[k]) or (lbimprovedarray[k] == U2[k]) or (lbimprovedarray[k] == V[k]));
            assert((buffer[k]== L[k]) or (buffer[k] == U[k]) or (buffer[k] == candidate[k]));
            ss<<k<<" "<<V[k]<<" "<<candidate[k]<<" "<<buffer[k]<<" "<<lbimprovedarray[k]<<" "<<L[k]<<" "<<U[k]<<" "<<L2[k]<<" "<<U2[k]<<endl;
        }
        //string ans;
        //ss>>ans;
        ///cout<<ss.str()<<endl;
        return ss.str();
    }

    int getNumberOfDTW(){return full_dtw;}

    int getNumberOfCandidates(){return lb_keogh;}

    floattype getLowestCost(){return bestsofar;}
    private:

    int lb_keogh;
    int full_dtw;
    const vector<floattype>   V;
    vector<floattype> buffer;
    int mConstraint;
    floattype bestsofar;
    vector<floattype>   U;
    vector<floattype>   L;
    vector<floattype>   U2;
    vector<floattype>   L2;

};

class LB_ImprovedEarly : public  NearestNeighbor{
    public:
    LB_ImprovedEarly(const vector<floattype> &  v, int constraint) : NearestNeighbor(v,constraint), lb_keogh(0), full_dtw(0), V(v), buffer(v), mConstraint(constraint),
    bestsofar(dtw::INF), U(V.size(),0), L(V.size(),0), U2(V.size(),0), L2(V.size(),0) {
        assert(mConstraint>=0);
        assert(mConstraint<static_cast<int>(V.size()));
        computeEnvelope(V,mConstraint,U,L);
    }

    void resetStatistics() {
        lb_keogh = 0;
        full_dtw = 0;
    }

    floattype test(const vector<floattype>  &candidate) {
        //memcpy(&buffer[0], &candidate[0],buffer.size()*sizeof(floattype));// = candidate;
        //buffer = candidate;
        //vector<floattype> & buffer(candidate);// no need for a copy
        ++lb_keogh;
        floattype error (0.0);
        for(uint i = 0; i < V.size();++i) {
            const floattype & cdi (candidate[i]);
            if(cdi > U[i]) {
              error += cdi - (buffer[i] = U[i]);
            } else if(cdi < L[i]) {
              error += (buffer[i] = L[i]) - cdi;
            } else buffer[i] = cdi;
            if(error>bestsofar) return bestsofar;
        }
        if(error < bestsofar) {
            computeEnvelope(buffer,mConstraint,U2,L2);
            //env.compute(buffer,mConstraint,U2,L2);
            for(uint i = 0; i < V.size();++i) {
                if(V[i] > U2[i]) {
                      error += V[i] - U2[i];
                } else if(V[i] < L2[i]) {
                      error += L2[i] - V[i];
                }
                if(error>bestsofar) return bestsofar;

            }
            if(error < bestsofar) {
                ++full_dtw;
                const floattype trueerror = mDTW.fastdynamic(V,candidate);//,mConstraint,1);
                if(trueerror < bestsofar) bestsofar = trueerror;
            }
        }
        return bestsofar;
    }

    int getNumberOfDTW(){return full_dtw;}

    int getNumberOfCandidates(){return lb_keogh;}

    floattype getLowestCost(){return bestsofar;}
    private:

    int lb_keogh;
    int full_dtw;
    const vector<floattype>   V;
    vector<floattype> buffer;
    int mConstraint;
    floattype bestsofar;
    vector<floattype>   U;
    vector<floattype>   L;
    vector<floattype>   U2;
    vector<floattype>   L2;

};

void piecewiseSumReduction(const vector<floattype> & array, vector<floattype> & out) {
    // the length of out gives out the desired output length
    assert(out.size()>0);
    const uint sizeofpieces = (uint)array.size()/out.size();
    assert(sizeofpieces>0);
    //sum_up<floattype> s;
    for(uint k = 0; k<out.size()-1;++k) {
        //s.reset();
        out[k] = 0;
        for(uint j = k*sizeofpieces; j < (k+1)*sizeofpieces; ++j)
          out[k] += array[j];
    }
    uint k=(uint)out.size()-1;
    out[k] = 0;
    for(uint j = k*sizeofpieces; j < array.size(); ++j)
          out[k] += array[j];
}

/**
* for debugging purposes
*/
class DimReducedLB_Keogh :  public NearestNeighbor{
    public:
    DimReducedLB_Keogh(const vector<floattype> &  v, int constraint, int reduced) : NearestNeighbor(v,constraint), lb_keogh(0), full_dtw(0), V(v), mConstraint(constraint),
    bestsofar(dtw::INF), U(V.size(),0), L(V.size(),0),Ured(reduced,0),Lred(reduced) {
        assert(mConstraint>=0);
        assert(mConstraint<static_cast<int>(V.size()));
        computeEnvelope(V,mConstraint,U,L);
        piecewiseSumReduction(U, Ured);
        piecewiseSumReduction(L, Lred);
    }

    floattype test(const vector<floattype> & candidate) {
        vector<floattype> reducedCandidate(Ured.size());
        piecewiseSumReduction(candidate, reducedCandidate);
        floattype smallerror (0.0);
        for(uint i = 0; i < Ured.size();++i) {
            if(reducedCandidate[i] > Ured[i])
              smallerror += reducedCandidate[i] - Ured[i];
            else if(reducedCandidate[i] < Lred[i])
              smallerror += Lred[i] - reducedCandidate[i];
        }
        if(smallerror > bestsofar) return bestsofar;
        ++lb_keogh;
        floattype error (0.0);
        for(uint i = 0; i < V.size();++i) {
            if(candidate[i] > U[i])
              error += candidate[i] - U[i];
            else if(candidate[i] < L[i])
              error += L[i] - candidate[i];
        }
        if(error < bestsofar) {
            ++full_dtw;
            const floattype trueerror = mDTW.fastdynamic(V,candidate);//,mConstraint,1);
            if(trueerror < bestsofar) bestsofar = trueerror;
        }
        return bestsofar;
    }

    int getNumberOfDTW(){return full_dtw;}

    int getNumberOfCandidates(){return lb_keogh;}

    floattype getLowestCost(){return bestsofar;}

    private:

    int lb_keogh;
    int full_dtw;
    const vector<floattype>   V;
    int mConstraint;
    floattype bestsofar;
    vector<floattype>   U,L;
    vector<floattype>   Ured,Lred;

};

/**
* this class is not used?
*/
class Envelope {
    public:
    Envelope() : maxfifo(), minfifo(){}
    virtual ~Envelope() {}
    void compute(const vector<floattype> & array, uint constraint, vector<floattype> & maxvalues, vector<floattype> & minvalues) {
        const uint width = 1 +  2 * constraint;
        maxfifo.clear();minfifo.clear();
        for(uint i = 1; i < array.size(); ++i) {
          if(i >=constraint+1) {
            maxvalues[i-constraint-1] = array[maxfifo.size()>0 ? maxfifo.front():i-1];
            minvalues[i-constraint-1] = array[minfifo.size()>0 ? minfifo.front(): i-1];
          }
          if(array[i] > array[i-1]) { //overshoot
            minfifo.push_back(i-1);
            if(i ==  width+minfifo.front()) minfifo.pop_front();
            while(maxfifo.size() > 0) {
              if(array[i] <= array[maxfifo.back()]) {
                if (i==  width+maxfifo.front()) maxfifo.pop_front();
                break;
              }
              maxfifo.pop_back();
            }
          } else {
            maxfifo.push_back(i-1);
            if (i==  width+maxfifo.front()) maxfifo.pop_front();
            while(minfifo.size() > 0) {
              if(array[i] >= array[minfifo.back()]) {
                if(i==  width+minfifo.front()) minfifo.pop_front();
                break;
              }
              minfifo.pop_back();
            }
          }
        }
        for(uint i = (uint)array.size(); i <= array.size() + constraint; ++i) {
              if(maxfifo.size()>0) {
                  maxvalues[i-constraint-1] = array[maxfifo.front()];
                if(i-maxfifo.front() >= width) {
                    maxfifo.pop_front();}
              } else {
                  maxvalues[i-constraint-1] = array[array.size()-1];
              }
              if(minfifo.size() > 0) {
                  minvalues[i-constraint-1] = array[minfifo.front()];
                  if(i-minfifo.front() >= width) {
                      minfifo.pop_front();}
              } else {
                  minvalues[i-constraint-1] = array[array.size()-1];
              }
        }
 }
        deque<int> maxfifo, minfifo;

};

// only used for unit testing
floattype l1diff(const vector<floattype> &  v, const vector<floattype> & w) {
    floattype ans(0);
    for(uint k = 0; k<v.size();++k)
      ans+=abs(v[k]-w[k]);
    return ans;
}
#endif


text:
'use strict';
var chai = require('chai'),
	expect = chai.expect,
	sinon = require('sinon'),
	sandbox = require('sandboxed-module');
chai.use(require('sinon-chai'));

describe('Server', () => {
	var env = {};
	beforeEach(() => {
		env = {};
        env.log = sandbox.require('../mocks/log')();
        env.config = {
            port: 8888
        };
        env.restifyServer = {
			use: sinon.stub(),
	        get: sinon.stub(),
	        post: sinon.stub(),
            put: sinon.stub(),
            del: sinon.stub(),
	        close: sinon.stub(),
	        listen: sinon.stub()
		};
		env.restify = {
			createServer: sinon.stub().returns(env.restifyServer),
			authorizationParser: sinon.stub().returns('authorizationparser'),
	        queryParser: sinon.stub().returns('queryparser'),
	        bodyParser: sinon.stub().returns('bodyparser'),
	        gzipResponse: sinon.stub().returns('gzipresponse')
		};
        env.router = {
            register: sinon.stub()
        };

        env.server = sandbox.require('../../src/server', {
			requires: {
                'config': env.config,
                'restify': env.restify,
                './lib/router': env.router,
                './lib/log': env.log
            }
		});
    });
    afterEach(() => {
        env.server.stop();
    });

    describe('start', () => {
        describe('success', () => {
            beforeEach((done) => {
                env.router.register.returns(Promise.resolve());
                env.restifyServer.listen.yields(null);
                env.server.start()
    			.then(() => { done(); })
    			.catch(done);
            });
            it('should create the restify server', () => {
                expect(env.restify.createServer).to.have.been.calledOnce;
            });
			it('should use the authorization parser', () => {
                expect(env.restify.authorizationParser).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('authorizationparser');
            });
            it('should use the query parser', () => {
                expect(env.restify.queryParser).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('queryparser');
            });
            it('should use the body parser', () => {
                expect(env.restify.bodyParser).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('bodyparser');
            });
            it('should use the gzip response', () => {
                expect(env.restify.gzipResponse).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('gzipresponse');
            });
            it('should register the routes', () => {
                expect(env.router.register).to.have.been.calledOnce;
            });
            it('should listen on the proper port', () => {
                expect(env.restifyServer.listen).to.have.been.calledOnce;
                expect(env.restifyServer.listen).to.have.been.calledWith(env.config.port);
            });
        });

        describe('invalid routes', () => {
            beforeEach((done) => {
                env.router.register.returns(Promise.reject('bad things, man'));
                env.server.start()
    			.then(() => { done('should have throw an exception'); })
    			.catch((err) => { expect(err).to.equal('bad things, man'); done();});
            });
            it('should create the restify server', () => {
                expect(env.restify.createServer).to.have.been.calledOnce;
            });
            it('should use the query parser', () => {
                expect(env.restify.queryParser).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('queryparser');
            });
            it('should use the body parser', () => {
                expect(env.restify.bodyParser).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('bodyparser');
            });
            it('should use the gzip response', () => {
                expect(env.restify.gzipResponse).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('gzipresponse');
            });
            it('should register the routes', () => {
                expect(env.router.register).to.have.been.calledOnce;
            });
            it('should not listen on the port', () => {
                expect(env.restifyServer.listen).to.not.have.been.called;
            });
        });

        describe('port conflict', () => {
            beforeEach((done) => {
                env.router.register.returns(Promise.resolve());
                env.restifyServer.listen.throws('port conflict');
                env.server.start()
    			.then(() => { done('should have throw an exception'); })
    			.catch((err) => { expect(err.name).to.equal('port conflict'); done();});
            });
            it('should create the restify server', () => {
                expect(env.restify.createServer).to.have.been.calledOnce;
            });
            it('should use the query parser', () => {
                expect(env.restify.queryParser).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('queryparser');
            });
            it('should use the body parser', () => {
                expect(env.restify.bodyParser).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('bodyparser');
            });
            it('should use the gzip response', () => {
                expect(env.restify.gzipResponse).to.have.been.calledOnce;
                expect(env.restifyServer.use).to.have.been.calledWith('gzipresponse');
            });
            it('should register the routes', () => {
                expect(env.router.register).to.have.been.calledOnce;
            });
            it('should listen on the proper port', () => {
                expect(env.restifyServer.listen).to.have.been.calledOnce;
                expect(env.restifyServer.listen).to.have.been.calledWith(env.config.port);
            });
        });

        //it('should accept connections');
    });

    describe('stop', () => {
        beforeEach(() => {
            env.router.register.returns(Promise.resolve());
            env.restifyServer.listen.yields(null);
            env.restifyServer.close.yields(null);
            return env.server.start()
            .then(() => {
                return env.server.stop();
            });
        });
        it('should stop listening', () => {
            expect(env.restifyServer.close).to.have.been.calledOnce;
        });
    });
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class java.rmi.activation.ActivationGroupDesc.CommandEnvironment (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

Uses of Class
java.rmi.activation.ActivationGroupDesc.CommandEnvironment

Packages that use ActivationGroupDesc.CommandEnvironment

Package
Description

java.rmi.activation

Provides support for RMI Object Activation.

Uses of ActivationGroupDesc.CommandEnvironment in java.rmi.activation

Methods in java.rmi.activation that return ActivationGroupDesc.CommandEnvironment

Modifier and Type
Method and Description

ActivationGroupDesc.CommandEnvironment
ActivationGroupDesc.getCommandEnvironment()

Returns the group's command-environment control object.

Constructors in java.rmi.activation with parameters of type ActivationGroupDesc.CommandEnvironment

Constructor and Description

ActivationGroupDesc(Properties overrides,
                   ActivationGroupDesc.CommandEnvironment cmd)

Constructs a group descriptor that uses the system defaults for group
 implementation and code location.

ActivationGroupDesc(String className,
                   String location,
                   MarshalledObject<?> data,
                   Properties overrides,
                   ActivationGroupDesc.CommandEnvironment cmd)

Specifies an alternate group implementation and execution
 environment to be used for the group.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
<?php

class HistoryControllerCore extends FrontController
{
	public $auth = true;
	public $php_self = 'history';
	public $authRedirection = 'history';
	public $ssl = true;

	public function setMedia()
	{
		parent::setMedia();
		$this->addCSS(_THEME_CSS_DIR_.'history.css');
		$this->addCSS(_THEME_CSS_DIR_.'addresses.css');
		$this->addJqueryPlugin('scrollTo');
		$this->addJS(array(
					_THEME_JS_DIR_.'history.js',
					_THEME_JS_DIR_.'tools.js')
					);
	}

	/**
	 * Assign template vars related to page content
	 * @see FrontController::initContent()
	 */
	public function initContent()
	{
		parent::initContent();

		if ($orders = Order::getCustomerOrders($this->context->customer->id))
			foreach ($orders as &$order)
			{
				$myOrder = new Order((int)$order['id_order']);
				if (Validate::isLoadedObject($myOrder))
					$order['virtual'] = $myOrder->isVirtual(false);
			}
		$this->context->smarty->assign(array(
			'orders' => $orders,
			'invoiceAllowed' => (int)(Configuration::get('PS_INVOICE')),
			'slowValidation' => Tools::isSubmit('slowvalidation')
		));

		$this->setTemplate(_PS_THEME_DIR_.'history.tpl');
	}
}


text:
package com.hs.mail.pop3.processor;

import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.collections.CollectionUtils;

import com.hs.mail.container.server.socket.TcpTransport;
import com.hs.mail.imap.message.MessageMetaData;
import com.hs.mail.pop3.POP3Exception;
import com.hs.mail.pop3.POP3Session;

/**
 * Handler for STAT command.
 *
 * Returns the number of messages in the mailbox and its aggregate size.
 *
 * @author Won Chul Doh
 * @since April 12, 2018
 *
 */
public class StatProcessor extends AbstractPOP3Processor {

	@Override
	protected void doProcess(POP3Session session, TcpTransport trans,
			StringTokenizer st) {
		if (session.getState() == POP3Session.State.TRANSACTION) {
			List<MessageMetaData> uidList = session.getUidList();
			List<Long> deletedUidList = session.getDeletedUidList();
            long size = 0;
            int count = 0;
			if (CollectionUtils.isNotEmpty(uidList)) {
				for (MessageMetaData data : uidList) {
					if (!deletedUidList.contains(data.getUid())) {
						size += data.getSize();
						count++;
					}
				}
			}
			StringBuilder responseBuffer = new StringBuilder(32)
					.append(OK_RESPONSE)
					.append(" ")
					.append(count)
					.append(" ")
					.append(size);
			session.writeResponse(responseBuffer.toString());
		} else {
			throw new POP3Exception();
		}
	}

}


text:
Once you have forked the repository and created your local clone you need to download
these additional development software tools.

* Apache Ant 1.9.2 or later: The build uses Ant, the version it has been tested with is 1.9.4 and 1.9.2. - https://ant.apache.org/
* JUnit 4.10: Java unit tests are written using JUnit, tested at version 4.10. - http://junit.org/
* Jacoco 0.7.5: The JUnit tests have code coverage enabled by default, using Jacoco, tested with version 0.7.5. - http://www.eclemma.org/jacoco/
* Python 3.5: Required to provide support for Python.
* Scala - Optional, Scala support will be built if SCALA_HOME is set. Development was done with 2.11.7 - http://www.scala-lang.org/

The Apache Ant `build.xml` files are setup to assume that the Junit and Jacoco jars are copied into `$HOME/.ant/lib`.
```
> ls $HOME/.ant/lib
jacocoagent.jar  jacocoant.jar  junit-4.10.jar
```

The project also requires a local install of IBM InfoSphere Streams 4.x (>= 4.0.1.0), with the environment variable `STREAMS_INSTALL` set to the root of the install. The recommended setup is to source the `bin/streamsprofile.sh` script in the Streams install.
```
> source /opt/ibm/InfoSphere_Streams/4.0.1.0/bin/streamsprofile.sh
InfoSphere Streams environment variables have been set.
```

For building the documentation for the Python support Sphinx must be installed:

```
pip install sphinx
pip install sphinx_rtd_theme
```

The Python documentation is only invoked through the top-level `release`
target or the default target in `python/build.xml`.
Creation of the Python documentation can be skipped by setting the property
`topology.build.sphinx=no`, e.g.

```
ant -Dtopology.build.sphinx=no release
```

For further information on writing Python docstrings, see [Python Docstring conventions](#python-docstring-conventions).

### Building

The top-level Ant file `streamsx.topology/build.xml` has these main targets:
* `all` (default) : Build the project, including the Java code for the Java Application API, the SPL `com.ibm.streamsx.topology` SPL toolkit and the sample applications. If SCALA_HOME is set then Scala support is also built.
* `clean` : Clean the project
* `test` : Run the JUnit tests, most of the tests are run twice, once in embedded mode (within the JVM) and once in Streams standalone mode.
* `test.report` : Build a test report for the JUnit test runs. This is invoked automatically when the `test` target passes, but in case of a failure, this may be invoked to produce a test report to easily display the failure(s).
* `test.quick` : Run the Junit tests quickly as a sanity check, this runs a subset of the tests, avoiding SPL generation & compilation and code coverage. *This target currently may still invoke some SPL compilation (sc) so may not be a quick as it could be.*

### Implementing toolkit messages
This toolkit supports globalized messages with unique message IDs. The guidelines for implementing a message bundle are described in [Messages and National Language Support for Toolkits](https://github.com/IBMStreams/administration/wiki/Messages-and-National-Language-Support-for-toolkits).

### Distributed testing

By default the Ant `test` target does not run the tests against a Streams instance (distributed), as it requires an instance to be running, which may not always be the case. A sub-set of the tests can also be run against a Streams instance like this:
```
cd test/java
ant unittest.distributed
```
This requires that your environment is setup so that `streamtool submitjob` submit jobs to an instance without requiring any authentication. This is the case for the [Streams Quicksttart VM image](http://www-01.ibm.com/software/data/infosphere/stream-computing/trials.html).

### IBM Bluemix Streaming Analytics service testing

Tests are run against the service if these environment variables are set:

* `topology_test_vcap_services` - File containing JSON VCAP services
* `topology_test_vcap_service_name` - Name of Streaming Analytics service to use

e.g.

```
export topology_test_vcap_services=$HOME/vcap/my_vcap
export topology_test_vcap_service_name=debrunne-streams2
```

The tests are run with this target:

```
cd test/python
ant test.application.api
```

They can be run alone by (need to set environment variable `PYTHONPATH`):

```
cd test/python/topology
python3 -m unittest test_streaming_analytics_service
```

### Test reports

Running the test targets produces two reports:
* `test/java/report/junit/index.html` - JUnit test report
* `test/java/report/coverage/index.html` - Code soverage report. Full coverage numbers are obtained by running the top-level `test` and `unittest.distributed` targets.

### Python Docstring conventions

Python docstrings use the Google style: http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html

How to cross reference Python classes, modules, methods, functions etc: http://www.sphinx-doc.org/en/stable/domains.html#cross-referencing-python-objects

When creating cross reference to entity in another module, display the name in short form(~):
```python
    def function(arg1):
        """Calls :py:func:`~.othermodule.tool`"""
        from othermodule import tool
        tool()
```

When referencing function arguments, use a single backquote(`):
```python
    def function(arg1):
        """function summary
        Args:
            arg1 (str): argument 1
        Returns:
            str: return `arg1`
        """
        return arg1
```

When referencing environment variable, use bold(**):
```python
    """
    **VCAP_SERVICE** is an environment variable
    """
```

When referencing types in Args or Returns, use the type name directly.  Sphinx would convert the reference into hyperlinks, and this ensures the builtin help() will display the arguments and return nicely.
```python
    def function(arg1):
        """function summary
        Args:
            arg1 (UserType1): argument 1
        Returns:
            UserType2: return something
        """
```

Container types such as lists and dictionaries can use the following syntax:
```python
    def function(arg1, arg2):
        """function summary
        Args:
            arg1 (list(int)): list of integers
            arg2 (dict(str, int)): mapping of str to int
        Returns:
            tuple(float, float): returns two float tuples
        """
```

The `__init__` method should be documented on the `__init__` method itself (not in the class level docstring).  This results in better rendering for the builtin help() function.

## Proposing changes
Please submit changes through a pull request (PR), typically against `master` or a feature branch.

For a pull request:

 * **Restrict to a single issue**, this speeds up acceptance and makes it easier to merge across release branches if needed.
    * Don't lump several unrelated fixes/features into a single PR
    * Don't fix/change formatting in unrelated code in the same PR
    * Don't fix unrelated documentation/comments in the same PR
    * Propose such unrelated fixes in new PRs, it's git, branches are cheap.
    * If unsure if something is related, just ask!
 * Features and defect fixes are typically associated with an issue.
    * For a defect, create an issue that describes the problem as its summary (not the fix).
 * Describe what changes you made in the PR summary (or indirectly in the associated issue)
    * Help out reviewers with explanations, don't make them have to make assumuptions to review the code.
 * Describe what tests were run.

 It's recommended that you use branches for your development, modifying the target branch (e.g. `master` or the feature branch) directly (even locally in the clone) is not recommended, as multiple changes by other developers may be made to the official copy before you have a chance to merge.


text: int snd_cobalt_pcm_create(struct snd_cobalt_card *cobsc);