text:
angular.module('fleetonrails.services.groups_destinations-service', [])

    .factory('GroupsDestinationsService', [ '$http', 'globalSettings', function($http, globalSettings) {
        return {
            get: function(id,success, error) {
                $http({
                    method: 'GET',
                    url: globalSettings.api_base_url + '/v1/groups/' + id + '/destinations',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                }).success(function(destinations){
                        success(destinations);
                    }).error(function(destinations) {
                        error(destinations)
                        console.log(destinations);
                    })
            },

            create: function(id,data, success, error) {
                $http({
                    method: 'POST',
                    url: globalSettings.api_base_url + '/v1/groups/' + id + '/destinations',
                    data: data,
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                }).success(function(destinations) {
                        success(destinations);
                    }).error(function(destinations) {
                        error(destinations)
                        console.log(destinations);
                    })
            },
            delete: function(id,destinationsID, success, error) {
                $http({
                    method: 'DELETE',
                    url: globalSettings.api_base_url + '/v1/groups/' + id + '/destinations/' + destinationsID,
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                }).success(function(destinations) {
                        success(destinations);
                    }).error(function(destinations) {
                        error(destinations);
                        console.log('Error',destinations);
                    })
            }
        }
    }]);


text:
{-# LANGUAGE ScopedTypeVariables #-}

-- | A module for any and all functions pertaining to creating / discovering 2A messages from the set of past received 1Bs, that conflict with something.
module Hetcons.Conflicting_2as (conflicting_2as) where

import Hetcons.Instances_1b_2a ( well_formed_2a )
import Hetcons.Signed_Message
    ( Verified
     ,Recursive_1a
     ,Recursive_1b(Recursive_1b)
       ,recursive_1b_non_recursive
       ,recursive_1b_proposal
       ,recursive_1b_conflicting_phase2as
     ,Recursive_2a(Recursive_2a)
     ,non_recursive
     ,signed
     ,original)
import Hetcons.Value
    ( Contains_Value
        ,extract_value
    , Contains_1a
        ,extract_1a
        ,extract_observer_quorums
    , Value
        ,conflicts
    )

import Charlotte_Types ( Phase_2a
                      ,default_Phase_1b
                      ,phase_1b_proposal
                      ,phase_1b_conflicting_phase2as)

import Data.Foldable ( Foldable(toList) )
import Data.Hashable (Hashable)
import qualified Data.HashSet as HashSet ( map, filter )
import Data.HashSet ( HashSet, singleton, insert, fromList, empty )

-- | Phase_2as with identical quorums to the message, but conflicting values
--   takes in old, known 1bs, and a new message, and filters the old 1Bs by quorums, and then by conflicts, and tests to see if they are a valid 2A
--   NOTE: only pariwise conflicts are handled.
conflicting_2as :: forall v f . (Value v, Eq v, Hashable v, Foldable f) => (f (Verified (Recursive_1b v))) -> (Verified (Recursive_1a v)) -> (HashSet Phase_2a)
conflicting_2as old_1bs new_message =
  let naive_1b = Recursive_1b {
                   recursive_1b_non_recursive = default_Phase_1b {phase_1b_proposal = signed new_message
                                                                 ,phase_1b_conflicting_phase2as = empty}
                  ,recursive_1b_proposal = new_message
                  ,recursive_1b_conflicting_phase2as = empty}
      quorums_1bs = filter (conflicts . (\y -> fromList [naive_1b, original y])) $ toList old_1bs -- TODO: non-pairwise conflicts
      with_both = map (\x -> filter (\y -> ((((extract_value x) :: v) == ((extract_value y) :: v)) &&
                                           ((((extract_1a x) :: Verified (Recursive_1a v)) == ((extract_1a y) :: Verified (Recursive_1a v)))))) quorums_1bs) quorums_1bs
      potential_2as = map (Recursive_2a . fromList) with_both
   in fromList $ map non_recursive $ filter (\x -> case well_formed_2a x of
                                                        Left _ -> False
                                                        Right _ -> True) potential_2as

redpajama_set_name: RedPajamaGithub


text:
package org.bitcoins.server

import com.typesafe.config.ConfigFactory
import org.bitcoins.commons.util.ServerArgParser
import org.bitcoins.testkit.BitcoinSTestAppConfig
import org.bitcoins.testkit.util.BitcoinSAsyncTest
import org.scalatest.Assertion

import scala.concurrent.Future

class ServerRunTest extends BitcoinSAsyncTest {

  // Clear log location property
  after {
    System.clearProperty("bitcoins.log.location")
  }

  // Note: on this test passing it will output a stack trace
  // because runMain calls err.printStackTrace() on failure
  it must "throw errors" in {
    //custom configuration to make peers empty
    //this should cause an exception in startBitcoinSBackend()
    val noPeersConfig =
      ConfigFactory.parseString(s"""bitcoin-s.node.peers=[]""")
    implicit val config =
      BitcoinSTestAppConfig.getNeutrinoTestConfig(noPeersConfig)
    val datadir = config.chainConf.datadir

    val invalidPort = -1
    val args = Vector("--datadir",
                      datadir.toAbsolutePath.toString,
                      "--rpcport",
                      invalidPort.toString)

    val serverArgParser = ServerArgParser(args)
    val main = new BitcoinSServerMain(serverArgParser)
    val runMainF = main.start()
    // Use Exception because different errors can occur
    val assertionF: Future[Assertion] = recoverToSucceededIf[Exception] {
      val deleteDirF = for {
        _ <- runMainF
      } yield ()

      for {
        _ <- runMainF
        _ <- deleteDirF
      } yield ()
    }

    for {
      _ <- assertionF
      _ <- main.stop()
    } yield succeed
  }

}


text:
set -e

# Only push if we've just committed to google/closure-library:master.
# Start by decrypting the deploy password, and pre-populate GitHub's
# RSA key to avoid needing to manually accept it when connecting.
if [ "$TRAVIS_REPO_SLUG" == "google/closure-library" -a \
     "$TRAVIS_PULL_REQUEST" == "false" -a \
     "$TRAVIS_BRANCH" == "master" ]; then

  # If we're on travis, use a secure $deploy_password
  if [ -n "$deploy_password" ]; then
    touch scripts/ci/deploy
    chmod 600 scripts/ci/deploy
    openssl aes-256-cbc -k "$deploy_password" -d -a \
            -in scripts/ci/deploy.enc -out scripts/ci/deploy \
            &> /dev/null
    echo -e "Host github.com\n  IdentityFile $PWD/scripts/ci/deploy" > ~/.ssh/config
    echo "github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6Tb
          Qa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsd
          lLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+S
          e8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOz
          QgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA
          8VJiS5ap43JXiUFFAaQ==" | sed 's/^ *//' | tr -d '\n' > ~/.ssh/known_hosts
  fi

  # Push the commit and delete the repo.
  export GIT_WORK_TREE="$GH_PAGES"
  export GIT_DIR="$GH_PAGES/.git"
  git push -fq origin gh-pages > /dev/null
  rm -f scripts/ci/deploy
  rm -rf "$GH_PAGES"
  echo "Published gh-pages."

fi


text:
import enum

import asynctnt.log

from .exceptions import TaskEmptyError

__all__ = (
    'Status', 'Task'
)

class Status(enum.Enum):
    READY = 'r'
    TAKEN = 't'
    EXECUTED = '-'
    BURIED = '!'
    DELAYED = '~'

class Task:
    __slots__ = (
        '_tube', '_task_id', '_status', '_data'
    )

    def __init__(self, tube, tnt_tuple):
        self._tube = tube
        if tnt_tuple is None or len(tnt_tuple) == 0:  # pragma: nocover
            raise TaskEmptyError('Tarantool Queue task is empty')

        tnt_tuple = tnt_tuple[0]
        if tnt_tuple is None or len(tnt_tuple) == 0:  # pragma: nocover
            raise TaskEmptyError('Tarantool Queue task is empty')

        self._task_id = tnt_tuple[0]
        status = tnt_tuple[1]
        try:
            self._status = Status(status)
        except ValueError:  # pragma: nocover
            asynctnt.log.logger.warning(
                "unknown status '{}' in task_id = {}".format(
                    status, self._task_id))
            self._status = status
        self._data = tnt_tuple[2]

    @property
    def tube(self):
        """
            Task's tube
        """
        return self._tube

    @property
    def task_id(self):
        """
            Task id
        """
        return self._task_id

    @property
    def status(self):
        """
            Task status

            :returns: :class:`asynctnt_queue.Status` instance
        """
        return self._status

    @property
    def data(self):
        """
            Task data
        """
        return self._data

    def __repr__(self):
        return '<Task id={} status={}>'.format(self._task_id, self._status)

    async def touch(self, increment):
        """
            Update task ttl and/or ttr by increment value

            :param increment: Seconds to add to ttr
            :return: Task instance
        """
        return await self._tube.touch(self._task_id, increment)

    async def ack(self):
        """
            Ack task

            :return: Task instance
        """
        return await self._tube.ack(self._task_id)

    async def release(self, *, delay=None):
        """
            Release task (return to queue) with delay if specified

            :param delay: Time in seconds before task will become ready again
            :return: Task instance
        """
        return await self._tube.release(self._task_id, delay=delay)

    async def peek(self):
        """
            Get task without changing its state

            :return: Task instance
        """
        return await self._tube.peek(self._task_id)

    async def bury(self):
        """
            Buries (disables) task

            :return: Task instance
        """
        return await self._tube.bury(self._task_id)

    async def delete(self):
        """
            Deletes task from queue

            :return: Task instance
        """
        return await self._tube.delete(self._task_id)


text:
var React = require('react');
var AppComponent = require('./AppComponent.js');
React.render(<AppComponent/>, document.body);


text:
ActiveSupport::Notifications.subscribe "deliver.action_mailer" do |name, start, finish, id, payload|
  if payload[:exception]
    DeadLetterOffice::DeadLetter.recover_parcel(payload)
  end
end


text:
#ifndef OPENSIM_EVENT_H_
#define OPENSIM_EVENT_H_

namespace OpenSim {

/** Struct representing an event extracted from a C3D file.                   */
struct Event {
    std::string label;
    double      time;
    int         frame;
    std::string description;
};

}

#endif


text:
require 'socket'
require 'opentsdb/logging'

module OpenTSDB
  class Client
    include Logging

    attr_reader :connection

    def initialize(options = {})
      hostname    = options[:hostname] || 'localhost'
      port        = options[:port] || 4242
      @connection = TCPSocket.new(hostname, port)
    rescue
      raise Errors::UnableToConnectError
    end

    def to_command(options)
      timestamp   = options[:timestamp].to_i
      metric_name = options[:metric]
      value       = options[:value].to_f
      tags        = options[:tags].map { |k, v| "#{k}=#{v}" }.join(' ')

      "put #{metric_name} #{timestamp} #{value} #{tags}"
    end

    def build_command(input)
      if input.is_a?(Array)
        input.collect { |unit| to_command(unit) }.join("\n")
      else
        to_command(input)
      end.chomp
    end

    def put(options = {})
      @connection.puts(build_command(options))
    end
  end
end


text:
#ifndef H_M_DATA_H
#define H_M_DATA_H

#include "nodeov.h"
#include "statedata.h"
#include "d_hhm_prob.h"
#include "nd_hhm_prob.h"
#include "mmodel_prob.h"

		/*				NOTATIONS
		Len p0 - be desired number of occurences; n0- text length;
		n - current stage of the algorithm; m - pattern length; Alp - alphabet; HH - pattern; Q - set of HMM states
		п(q',q) - probability from state q' to pass to state q
		*/

////Descriptor of node w of OvGraf in case of  HMM or Markov model

class H_M_Node:
public NodeOv
{
public:
	///////////////DESCRIPTOR OF A NODE OF OVGRAPH///////////////////////////////////////////////
	int NStates;						//Number of States
	H_M_State* *States;					//list of descriptors of states

	/////////////// SAME PARAMETERS  FOR ALL NODES OF OVGRAPH//////////////////

	static int NumAllStates;				//number of all states in HMM
	static double* BnpProbs;				// The 2-dimensional matrix of size Q*p0
									     	// BnpProbs[q][p]= Prob(B(n-m,p),q), q in Q, p = 0,..,p0-1

	static int** ConsistStMatrix;			//The array of lists. For all each state q  ConsistStMatrix[q] contains states q' (consistent with q) such that п(q',q)>0
	static int* ConsistStNums;				// The array of size NumAllStates
											//ConsistStNums[q] = (number of states consistent with q)

	static double** TransProbMatrix;		//The array of lists.
											//for all q from Q and for all states q' consistent with q
											//TransProbMatrix[q][q']=п(q',q)

	static double* TransStepProbMatrix;	    //(needed only for HHM)At the stage n of the algorithms work,
											//TransProbMatrix[q][q'] is the probability of transition from q' to q during n steps, i.e Prob(q',V^n,q).

	static double* TransStepProbList;		//(needed only for Markov)At the stage n of the algorithms work,
											//TransStepProbList[q][q'] = Prob(V^n,q).

////////METHODS////////////////
	H_M_Node();
	~H_M_Node();

	static void ProbCalc(void);					//main function for P-value computation
	static void Preprocessing(void);			//Preprocessing
	static void ClearData(void);				//Clear data structures
};

											//AUXILARY DATA

extern double** HDProbs;						//Let w be processed node, n- current stage; depth - depth of the path leading to w
												//x_0,..x_depth - overlap prefixes of w, x_depth = w
												//HDPobs[k][p] = Prob(D(n-m+|x_k|,p+1,x_k),q), p= 0,...,p0-1, k = 0, ..,depth; q in AllState(w)

extern double* PrevBnpProbs;					//list to temporarly store data from BnpProbs
extern double* PrevTransStepProbMatrix;			//list to temporarly store data from TransStepProbMatrix
extern double** OrderProbs;						//For Markov model, let t be a prefix of motif words of length len, t1,...,t_len be prefixes of t;
												//In function, CalEProbOne (see m_ovgraf)  OrderProbs[i][q] = Prob(V^{n-m}.t_i, q), q in AllState(t_i); In function CalFarProbs OrderProbs[i] = Prob(B.t_i,q+p_0 +j);

											//FUNCTIONS

extern void SubStr(string &str, int startpos, int nsymb, string &result); //takes substring of string str;
																		  //Input parameters: str - string, start - starting position, nsymb - nummber of coping symbols,
																		  //result = str[start, start+nsymb]
extern double TransitionProb(int q1, int q2);							  //computes п(q1,q2)

extern double TermCondProb(int q1, std::string &word,  int wordsize, int q2);  // computes Prob(q1,word[1,wordsize],q2)
																				//Input parameters: q1, q2 -starting and terminal states; word - word, wordsize - length of word

extern double TermProb(std::string word, int wordlen, int q);					//computes Prob(word[1,wordsize],q)
																				//Input parameters: q -starting and terminal states; word - word, wordsize - length of word

extern vector<int> ConsistStates(int q);										//list of states q' such that п(q',q) > 0

#endif // H_M_DATA_H


text:
<?php

namespace Sellsy\Criteria\Documents\SearchCriteria;

use Sellsy\Criteria\Documents\SearchCriteria;
use Sellsy\Models\Documents\Document\StepInterface;

/**
 * Class SearchOrdersCriteria
 * @package Sellsy\Criteria\Documents\SearchCriteria
 */
class SearchOrdersCriteria extends SearchCriteria
{
    /**
     * @return string
     */
    protected function getType()
    {
        return 'order';
    }

    /**
     * @return array
     */
    protected function getValidSteps()
    {
        return array(
            StepInterface::STEP_DRAFT,
            StepInterface::STEP_READ,
            StepInterface::STEP_ACCEPTED,
            StepInterface::STEP_EXPIRED,
            StepInterface::STEP_DEPOSIT,
            StepInterface::STEP_INVOICED,
            StepInterface::STEP_CANCELLED
        );
    }
}


text:
<?php namespace Phroute\Exception;

class HttpMethodNotAllowedException extends HttpException {}


text:
% Programm for the simulation of Phycoerythrin crossings through a laser beam
% adapted for simulating the inlfuence of gackground
% no diffusion, no photobleaching

close
N = 100; % total number of time steps per simulation
v = 1e3; % molecule's flow velocity in mum/sec
dt = 2.5e-5; % time step in sec
ww = 10^2; % square of waist diameter of laser beam in mum
% slit calculation
% x-axis = axis of detection
% y-axis = axis of laser beam
% z-axis = axis of capillary
L = 100; % distance between injection capillary and laser beam
z0 = -3*sqrt(ww);
told = 1; t0 = 0;
t0 = z0/v;
phif = 5e6;
bg = 10/N; % background
maxfluo = 100; % maximum number of detected photons
M = 1:maxfluo;
FAC = cumsum(log(M));
L = 1:N;

xi=sqrt(2*D*dt);
mm = [];
dist = zeros(1,maxfluo);

for k=1:1
	% random variable dr
	% with diffusion:
	x = zeros(1,N);
	y = zeros(1,N);
	z = v*dt*ones(1,N);
	% initial value
	z(1) = z0;
	% path calculation
	z = cumsum(z);
	% fluorescence
	fluo = bg + phif*exp(-2/ww*(x.^2 + z.^2));
	% bleaching sampling
	mm = sum(fluo);
	dist = dist + exp(log(mm)*M - mm - FAC);
	plot(M, dist/sum(dist)); title(['path # = ', num2str(k)]);
end

% exact laser intensity
% int=exp(-2*rho^2/(w0^2+(z*lam/pi/w0^2)^2))*(2/(w0^2+(z*lam/pi/w0^2)^2)/pi);


text:
global text
# the length of @text
global textLength
# the current position of parsing, use text[cursor] to get current character in parsed stream
global cursor

# the grammar object which contains all of rules defined for the symbol in grammar.
global grammar
# saved the original rules of the grammar.
global originalRules

# store the wrapped function to rule of the left recursive symbol with `recursive`, and before entering them, store it in grammar too.
# when entering them, `grammar[symbol]` is unwrapped to `originalRules[symbol]` or `memorizeRecursives[symbol]`
global recursiveRules
global symbolDescedentsMap

# if you would like to use just symbol itself as the hash head, remove these four lines below and other correlative stuffs.

# {symbol: tag}, from rule symbol map to a shorter memo tag, for memory efficeny
global symbolToTagMap
# {tag: True}, record tags that has been used to avoid conflict
global tags

global parseCache # {tag+start: [result, cursor]}, memorized parser result
global functionCache # memorized normal function result

# #### helper functions
# some functions is helpful to make the parser.

# **intialize**: clear global varialbes. you should call `intialize()` at first.
def initialize(aGrammar):
  global grammar, parseCache, functionCache, originalRules, recursiveRules, symbolDescedentsMap,\
         symbolToTagMap, tags
  grammar = aGrammar
  grammar.parentToChildren = {}
  parseCache = {}
  functionCache = {}
  originalRules = {}
  recursiveRules = {}
  symbolDescedentsMap = {}
  symbolToTagMap = {}
  tags = {}

# **_parse**: parse **$data** from **$root** with **$aGrammar**.

# before parsing, you should tell the informations about left recursion in grammar.
def parse(data, aGrammar, root=None):
  global text, textLength, cursor
  text = data
  textLength = len(text)
  cursor = 0
  root = root or aGrammar.rootSymbol
  return getattr(grammar, root)(0)

#
# **parse**: this is a sample parse function to demonstrate on how to write your own grammar rules yourself.

# notice that there exists indirect left recursion in the grammar.
def parseSample(text):
  # generate the matchers by the combinators in advance for better performance.

  # if you don't mind performance, you can write them in the rule directly.
  a = char('a'); b = char('b'); x = char('x')
  memoA = memo('A')
  # the grammar rules object.
  class rules:
    rootSymbol = 'A'
    def A(self,start):
      # *add `or memoResult` to prevent executing nonrecursive part more than once.*
      memoResult = m = rules.B(start)
      return (m and x(p.cur()) and m+'x' or memoResult) or a(start)
    def B(self,start): return rules.C(start)
    def C(self,start): return memoA(start) or b(start)
  initialize()
  addRecursiveCircles(rules, ['A', 'B', 'C'])
  computeLeftRecursives(rules)
  parse(text, rules)

# ##### stuffs for left recursives
# use `addParentChildren(grammar, parentChildrens)` or `addRecursiveCircles(grammar, recursiveCircles...)` to tell
# the left calling relations between symbols in the grammar

# **addParentChildrens**: add direct left call parent->children relation for **$parentChildrens** to **@symbolToParentsMap**

# e.g. `addRecursiveCircles(grammar, {A:['B'], B:['A', 'B']})`
def addParentChildrens(grammar, parentChildren):
  map = grammar.parentToChildren
  for parent, children in parentChildren:
    list = map.setdefault(parent, [])
    for name in children:
      if name not in list: list.append(name)

# **addRecursiveCircles**: add left recursive parent->children relation to `grammar.parentToChildren` for symbols in **@recursiveCircles**

# e.g. `addRecursiveCircles(grammar, ['A', 'B'], ['B'])` tell the same left recursive relations as above sample.
def addRecursiveCircles(grammar, *recursiveCircles):
  map = grammar.parentToChildren
  for circle in recursiveCircles:
    length = len(circle)
    for i in range(length):
      if i==length-1: j = 0
      else: j = i+1
      name = circle[i]
      parent = circle[j]
      list = map.setdefault(parent, [])
      if name not in list: list.append(name)

# **computeLeftRecursives**: after telling left recursive relations, compute the left recsives group and wrap symbol in
# them with `recursive` function

def computeLeftRecursives(grammar):
  global symbolDescedentsMap, originalRules
  parentToChildren = grammar.parentToChildren
  def addDescendents(symbol, meetTable, descedents):
    children =  parentToChildren[symbol]
    for child in children:
      if child not in descedents: descedents.append(child)
      if child not in meetTable: addDescendents(child, meetTable, descedents)
  symbolDescedentsMap = {}
  for symbol in parentToChildren:
    meetTable = {}; meetTable[symbol] = True
    descendents = symbolDescedentsMap[symbol] = []
    addDescendents(symbol, meetTable, descendents)
    if symbol in descendents:
      originalRules[symbol] = getattr(grammar, symbol)
      setattr(grammar, symbol, recursive(symbol))
  symbolDescedentsMap

# **recursive**: this is the key function to left recursive.

# Make **$symbol** a left recursive symbol, which means to wrap `originalRules[symbol]` with recursive.
# when recursiv(symbol)(start) is executed, first let `rule = grammar[symbol]`, `grammar[symbol] = originalRules[child]` for
# all symbols in left recursive circles and loop computing rule(start) until no changes happened, and
# restore all symbols in left recursive cirle to `recursiveRules[symbol]` at last.,
def recursive(symbol):
  rule = originalRules[symbol]
  def matcher(start):
    global cursor
    for child in symbolDescedentsMap[symbol]:
      setattr(grammar, child, originalRules[child])
    hash = symbol+str(start)
    m = parseCache.setdefault(hash, [None, -1])
    if m[1]>=0: cursor = m[1]; return m[0]
    while 1:
      result = rule(start)
      if m[1]<0:
        m[0] = result
        if result:  m[1] = cursor
        else: m[1] = start
      else:
        if m[1]==cursor: m[0] = result; return result
        elif cursor<m[1]: m[0] = result; cursor = m[1]; return result
        else: m[0] = result; m[1] = cursor
    for child in symbolDescedentsMap[symbol]:
      grammar[child] = recursiveRules[child]
    return result
  return matcher

# ##### memorization

# **memo**: lookup the memorized result and reached cursor for **$symbol** at the position of **$start**

# It is set up automaticly by `computeLeftRecursives(grammar)` for the symbols which is left recursive.

# For other symbol, you should be able to call this in rule mannually.
def memo(symbol):
  def matcher(start):
    global parseCache, cursor
    hash = symbol+str(start)
    try:
      m = parseCache[hash]
      if m: cursor = m[1]; return m[0]
    except: return
  return matcher

# **setMemorizeRules**: set the symbols in grammar which  memorize their rule's result.

# this function should be used only for the symbols which is not left recursives.

# you can do this after `initialize()` and before `parse(...)`.
def setMemorizeRules(grammar, symbols):
  for symbol in symbols:
    originalRules[symbol] = grammar[symbol]
    grammar[symbol] = memorize(symbol)

# **memorize**: memorize result and cursor for **$symbol** which is not left recursive.

# *The symbols which is left recursive should be wrapped by `recursive(symbol)`, not `memorize(symbol)`!!!*
def memorize(symbol):
  tag = symbolToTagMap[symbol]
  rule = originalRules[symbol]
  def matcher(start):
    hash = tag+start
    m = parseCache[hash]
    if m: cursor = m[1]; return m[0]
    else:
      result = rule(start)
      parseCache[hash] = [result, cursor]
      return result
  return matcher

# **setMemoTag**: find a shorter part of symbol as the head of hash tag to index **@parseCache**

# It exists just for performance reason. If you don't like this idea, you can remove the stuffs about memo tag yourself and
# just use symbol itself as the head of hash tag.
def setMemoTag(symbol):
  for i in range(len(symbol)):
    if symbol[0:i] not in tags: break
  tag = symbol[0:i]
  symbolToTagMap[symbol] = tag
  tags[tag] = True

# #### matchers and matcher combinators

# A **matcher** is a function which read the text being parsed and move cursor directly.

# All matcher should return truth value on succeed, and return falsic value on fail.

# A **combinator** is a function which receive zero or more matchers as parameter(maybe plus some other parameters
# which are not matchers), and generate a new matchers.

# there are other matcher generator besides the standard combinators described as above, like `recursive`, `memo`, `memorize`,
# which we have met above.

def isMatcher(item):  return hasattr(obj, '__call__')

# combinator **andp**

# execute item(cursor) in sequence, return the result of the last one.

# when `andp` is used to combined of the matchers, the effect is the same as by using the Short-circuit evaluation, like below:

# `item1(start) and item2(cursor] ... and itemn(cursor).`

# In fact, you maybe would rather like to use `item1(start) and item2(cursor) ..` when you write the grammar rule in the
# manner of Peasy. That would be simpler, faster and more elegant.

# And in that manner, you would have more control on your grammar rule, say like below:

# `if (x=item1(start) and (x>100) and item2(cursor) and not item3(cursor) and (y = item(cursor)): doSomething()`
def andp(items):
  items1 = []
  for item in items:
    if not isMatcher(item): items1.append(literal(item))
    else: items1.append(item)
  def matcher(start):
    global cursor
    cursor = start
    for item in items1:
      result = item(cursor)
      if not(result): return
    return result

# combinator **orp**

# execute `item(start)` one by one, until the first item which is evaluated to truth value and return the value.

# when orp is used to combined of the matchers, the effect is the same as by using the Short-circuit evaluation, like below:

# item1(start) or item2(cursor] ... or itemn(cursor)

# In fact, you maybe would rather like to use `item1(start) or item2(cursor) ..` when you write the grammar rule in the
# manner of Peasy. That would be simpler, faster and more elegant.

# And in that manner, you would have more control on your grammar rule, say like below:

# `if ((x=item1(start) and (x>100)) or (item2(cursor) and not item3(cursor)) or (y = item(cursor)): doSomething()`
def orp(*items):
  items1 = []
  for item in items:
    if not isMatcher(item): items1.append(literal(item))
    else: items1.append(item)
  def matcher(start):
    for item in items1:
      result = item(start)
      if result: return result
    return result

# combinator **notp**

# `notp` is not useful except being used in other combinators, just like this: `andp(item1, notp(item2))`.

# *It's unnessary, low effecient and ugly to write `notp(item)(start)`, just write `not item(start)`.*
def notp(item):
  if not isMatcher(item): item = literal(item)
  def matcher(start): return not item(start)
  return matcher

# combinator **any**: zero or more times of `item(cursor)`
def any(item):
  if not isMatcher(item): item = literal(item)
  def matcher(start):
    global cursor
    result = []; cursor = start
    while 1:
      x = item(cursor)
      if x: result.append(x)
      else: break
    return result
  return matcher

# combinator **some**: one or more times of `item(cursor)`
def some(item):
  if not isMatcher(item): item = literal(item)
  def matcher(start):
    global cursor
    result = []; cursor = start
    x = item(cursor)
    if not x: return x
    while 1:
      result.append(x)
      x = item(cursor)
      if not x: break
    return result
  return matcher

# combinator  **may**: a.k.a optional

# try to match `item(cursor)`, wether `item(cursor)` succeed or not, `maybe(item)(start)` succeed.
def optional(item):
  if not isMatcher(item): item = literal(item)
  def matcher(start):
    global cursor
    cursor = start
    x = item(cursor)
    if x: return x
    else: cursor = start; return True
  return matcher

# combinator **follow**

# try to match `item(start)`, if succeed, reset cursor and return the value of item(start)

# whether succeed or not, cursor is reset to start
def follow(item):
  if not isMatcher(item): item = literal(item)
  def matcher(start):
    global cursor
    cursor = start
    x = item(cursor)
    if x: cursor = start; return x
  return matcher

# combinator **times**: match **$n** times item(cursor), n>=1
def times(item, n):
  if not isMatcher(item): item = literal(item)
  def matcher(start):
    global cursor
    cursor = start
    for i in range(n):
      x = item(cursor)
      if x: result.append(x)
      else: return
    return result
  return matcher

# combinator **seperatedList**: some times item(cursor), separated by @separator
def seperatedList(item, separator=None):
  if separator is None: separator = spaces
  if not isMatcher(item): item = literal(item)
  if not isMatcher(separator): separator = literal(separator)
  def matcher(start):
    global cursor
    cursor = start
    result = []
    x = item(cursor)
    if not x: return
    while 1:
      result.append(x)
      x = item(cursor)
      if not(x): break
    return result
  return matcher

# combinator **timesSeperatedList**: given @n times $item separated by @separator, n>=1
def timesSeperatedList(item, n, separator=None):
  if separator is None: separator = spaces
  if not isMatcher(item): item = literal(item)
  if not isMatcher(separator): separator = literal(separator)
  def matcher(start):
    global cursor
    cursor = start
    result = []
    x = item(cursor)
    if not x: return
    for i in ranges(n-1):
      result.append(x)
      x = item(cursor)
      if not x: break
    return result
  return matcher

# As the same as andp, orp, in the manner of Peasy, you would rather to write youself a loop to do the things, instead
# of useing the combinators like any, some, times, seperatedList,etc. and that would be simpler, faster and more elegant.

# And in that manner, you would have more control on your grammar rule so that we can do other things include lexer,
# error report, errer recovery, semantic operatons, and any other things you would like to do.

# It is for three motives to put all of the stuffs abve here:
# * 1. to demonstrate how to write matcher and grammar rules in the method brought by Peasy
# * 2. to demonstrate that Peasy can implement any component that other combinational parser libaries like pyparsing,
# parsec too, but in a simpler, faster manner.
# * 3. to show that it is how easy to write the matchers in the manner of Peasy.

# As you have seen above, all of these utilities is so simple that you can write them at home by hand easily. In fact,
# you can write yourself all of the grammar rules in the same manner as above.

# If you like, you can add a faster version for every matcher, which do not pass $start as parameter around.

# Some of the matchers below have two version, to demonstrate how to do that.
# *Don't use the faster version in orp, any, some, times, separatedList, timesSeparatedList.*

# #### some other matchers, combinators and predicate

# A **predicate** is a function which return True or False, usually according to its parameter, but not look at parsed object.
# below is some little utilities may be useful. Three version of some of them is provided.

# just remove them if you don't need them, except **literal**, which is depended by the matchers above.

# matcher **literal**, normal version

# match a text string.

# `notice: some combinators like andp, orp, notp, any, some, etc. use literal to wrap a object which is not a matcher.

def literal(string):
  def matcher(start):
    global cursor
    len = string.length
    stop = start+len
    if text[start:stop]==string: cursor = stop; return True

# matcher **literal_**, faster version

# match a text string.
def iteral_(string):
  def matcher(start):
    global cursor
    len = string.length
    if text.slice(cursor,  stop = cursor+len)==string:
      cursor = stop; return True
  return matcher

# matcher **char**, normal version

# match one character
def char(c):
  def matcher(start):
    global cursor
    if start>=textLength: return
    if text[start]==c: cursor = start+1; return c
  return matcher

# matcher **char_**, normal version

# match one character
def char_(c):
  def matcher():
    global cursor
    if text[cursor]==c: cursor += 1; return c
  return matcher

# In spaces, spaces_, spaces1, spaces1_, a tat('\t') is seen as tabWidth spaces,

# which is used in indent style language, such as coffeescript, python, haskell, etc.

# If you don't need this feature, you can easily rewrite these utilities to remove the code about tab width yourself.

# matcher **spaces**, normal version

# zero or more whitespaces, ie. space or tab.

def spaces(start):
  global cursor
  len = 0
  cursor = start
  text = text
  while 1:
    c = text[cursor]
    cursor += 1
    if c==' ': len += 1
    elif c=='\t': len += tabWidth
    else: break
  return len

# matcher **spaces_**, faster version

# zero or more whitespaces, ie. space or tab.
def spaces_():
  global cursor
  len = 0
  text = text
  while 1:
    c = text[cursor]
    cursor += 1
    if c==' ': len += 1
    elif c=='\t': len += tabWidth
    else: break
  return len

# matcher **spaces1**, normal version

# one or more whitespaces, ie. space or tab.

def spaces1(start):
  global cursor
  len = 0
  cursor = start
  text = text
  while 1:
    c = text[cursor]
    cursor += 1
    if c==' ': len += 1
    elif c=='\t': len += tabWidth
    else: break
  if len: return len

# matcher **spaces1_**, faster version

# one or more whitespaces, ie. space or tab.
def spaces1_():
  global cursor
  len = 0
  while 1:
    c = text[cursor]
    cursor += 1
    if c==' ': len += 1
    elif c=='\t': len += tabWidth
    else: break
  if len: return len

# matcher **wrap**, normal version

# match left,: match item, match right at last
def wrap(item, left=spaces, right=spaces):
  if not isMatcher(item): item = literal(item)
  def matcher(start):
    global cursor
    if not left(start): return
    result = item(cursor)
    if result and right(cursor): return result
  return matcher

# matcher **identifierLetter**: normal version

# is a letter than can be used in identifer?

# javascript style, '$' is a identifierLetter_

def identifierLetter(start):
  global cursor
  cursor = start
  c = text[cursor]
  if c is '$' or c is '_' or 'a'<=c<'z' or 'A'<=c<='Z' or '0'<=c<='9':
    cursor += 1;
    return True

# matcher **identifierLetter_**, version

# is a letter that can be used in identifer?

# javascript style, '$' is a identifierLetter_
def identifierLetter_():
  global cursor
  c = text[cursor]
  if c is '$' or c is '_' or 'a'<=c<'z' or 'A'<=c<='Z' or '0'<=c<='9':
    cursor += 1;
    return True

# matcher **followIdentifierLetter_**, faster version

# lookahead whether the following character is a letter used in identifer. don't change cursor.

# javascript style, '$' is a identifierLetter_
def followIdentifierLetter_():
  c = text[cursor]
  return c is '$' or c is '_' or 'a'<=c<'z' or 'A'<=c<='Z' or '0'<=c<='9'

def isIdentifierLetter(c): return 'a'<=c<='z' or 'A'<=c<='Z' or '0'<=c<='9' or 'c'=='$' or 'c'=='_'

# predicate isdigit

def isdigit(c): return '0'<=c<='9'
# matcher digit, normal version

def digit(start):
  global cursor
  c = text[start];
  if '0'<=c<='9': cursor = start+1; return True
# matcher digit_, faster version

def digit_():
  global cursor
  c = text[cursor];
  if '0'<=c<='9': cursor += 1; return True

# predicate isletter

def isalpha(c): return 'a'<=c<='z' or 'A'<=c<='Z'
isletter = isalpha
# matcher letter, normal version

def alpha(start):
  global cursor
  c = text[start];
  if 'a'<=c<='z' or 'A'<=c<='Z': cursor = start+1; return True
letter = alpha

# matcher letter, faster version

def alpha_():
  global cursor
  c = text[cursor];
  if 'a'<=c<='z' or 'A'<=c<='Z': cursor += 1; return True
letter_ = alpha_

# predicate: islower
def islower(c): return 'a'<=c<='z'
# matcher lower, normal version
def lower(start):
  global cursor
  c = text[start];
  if 'a'<=c<='z': cursor = start+1; return True
#matcher lower_, faster version
def lower_():
  global cursor
  c = text[cursor];
  if 'a'<=c<='z': cursor += 1; return True

def isupper(c): return 'A'<=c<='Z'
# matcher upper, normal version
def upper(start):
  global cursor
  c = text[start];
  if 'A'<=c<='Z': cursor = start+1
#matcher upper_, faster version
def upper_(start):
  global cursor
  c = text[cursor];
  if 'A'<=c<='Z': cursor += 1

# matcher identifier, normal version
def identifier(start):
  global cursor
  cursor = start
  c = text[cursor]
  if 'a'<=c<='z' or 'A'<=c<='Z' or 'c'=='$' or 'c'=='_': cursor += 1
  else: return
  while 1:
    c = text[cursor]
    if 'a'<=c<='z' or 'A'<=c<='Z' or '0'<=c<='9' or 'c'=='$' or 'c'=='_': cursor += 1
    else: break
  True

# matcher identifier_, faster version
def identifier_(start):
  global cursor
  c = text[cursor]
  if 'a'<=c<='z' or 'A'<=c<='Z' or 'c'=='$' or 'c'=='_': cursor += 1
  else: return
  while 1:
    c = text[cursor]
    if 'a'<=c<='z' or 'A'<=c<='Z' or '0'<=c<='9' or 'c'=='$' or 'c'=='_': cursor += 1
    else: break
  True

# The utilites above is just for providing some examples on how to write matchers for Peasy.

# In fact, It's realy easy peasy to write the matchers for your grammar rule yourself.

# see [easy peasy]( http://en.wiktionary.org/wiki/easy_peasy )

# These utilities below exists for people who want to use these file a independent module, and put the grammar rule in
# another separated file.

# gettext: get the being pased text

# If you use this file to contain the grammar rules, just directly use `text`

# and use `text[cursor]` to get current character, `text.slice(cursor, cursor+n)` to get substring of the text, if
# text is a string object.
def gettext(): return text

# If you use this file to contain the grammar rules, just directly use `cursor` or `cursor = n` or `cursor += 1` or `cursor--`
def cur(): return cursor
def setcur(pos):
  global cursor
  cursor = pos
  return cursor

# It's a pity that assign in python is a statement and can not occur in expression.

# So We can not write x = Additive(start) and op = Op(cursor) and y = Multiply(cursor) and op(x, y)

# As a workaround, we assign some Var beforehand, e.g. x, y, op = vars(3)
# and then we can write like this:

# x.set(Additive(start)) and op << Op(cursor) and y << Multiply(cursor) and op(x, y)
# we can also wrtie like below:

# x << Additive(start) and op << Op(cursor) and y << Multiply(cursor) and op.v(x.v, y.v)

# If you do not need them, you may remove any overload definitions below except left shift.

# And you can use var.v at every place and remove all of the overload definitions, and that will make program faster.

def vars(n): [Var() for i in range(n)]

class Var:
  def __init__(self, name=''):
    # name is unnecessary attribute. remove it if you like.
    self.name = name
    self.v = None

  # faked assignment, let we can write in rules like so: x << memo('Add')(start) and op << Op(cursor)

  def __lshift__(self, y): selv.v = y; y

  # had best reserve the overloading to __nonzero__. and then you can write like below:

  # class Rules

  #   def Add(self, start):

  #      x, op, y = vars(3)
  #      return x << memo('Add')(start) and op << Op(cursor) and y << Mul(cursor) and op.v(x.v, y.v) \

  #             or x\

  #             or Mul(start)
  def __nonzero__(self): return self.v

  def __repr__(self): self.name+':'+repr(self.v)

  # You can overload the attribute of Var on demand.

  # Or overload none of them.
  def __lt__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v<y
  def __le__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v<=y
  def __eq__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v==y
  def __ne__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v!=y
  def __gt__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v>y
  def __ge__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v>=y
  def __setattr__(self, attr, value):
    if attr=='set': self.v = value; return self
    return getattr(self.v, attr, value)
  def __getattr__(self, attr):
    return getattr(self.v, attr)
  def __call__(self, *args, **kwargs):
    args = [(arg.v if isinstance(arg, Var) else arg) for arg in args]
    kwargs = {k:(v.v if isinstance(v, Value) else v) for k, v in kwargs}
    return self.v(*args, **kwargs);
  def __getitem__(self, key):
    if isinstance(y, Var): y = y.y
    return self.v[key]
  def __add__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v+y
  def __sub__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v-y
  def __mul__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v*y
  def __floordiv__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v//y
  def __div__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v/y
  def __truediv__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v//y
  def __mod__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v%y
  def __pow__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v**y
  def __rshift__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v>>y
  def __and__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v&y
  def __xor__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v^y
  def __or__(self, y):
    if isinstance(y, Var): y = y.y
    return self.v|y
  def __radd__(self, y):
    if isinstance(y, Var): y = y.y
    return y+self.v
  def __rsub__(self, y):
    if isinstance(y, Var): y = y.y
    return y-self.v
  def __rmul__(self, y):
    if isinstance(y, Var): y = y.y
    return y*self.v
  def __rfloordiv__(self, y):
    if isinstance(y, Var): y = y.y
    return y//self.v
  def __rdiv__(self, y):
    if isinstance(y, Var): y = y.y
    return y/self.v
  def __rtruediv__(self, y):
    if isinstance(y, Var): y = y.y
    return y/self.v
  def __rmod__(self, y):
    if isinstance(y, Var): y = y.y
    return y&self.v
  def __rpow__(self, y):
    if isinstance(y, Var): y = y.y
    return y**self.v
  def __rlshift__(self, y):
    return y<<self.vr
  def __rshift__(self, y):
    if isinstance(y, Var): y = y.y
    return y>>self.v
  def __rand__(self, y):
    return y&self.v
  def __rxor__(self, y):
    if isinstance(y, Var): y = y.y
    return y^self.v
  def __ror__(self, y):
    return y|self.v;
  def __iadd__(self, y):
    self.v += y; return self
  def __isub__(self, y):
    self.v -= y; return self
  def __imul__(self, y):
    if isinstance(y, Var): y = y.y
    self.v *= y; return self
  def __ifloordiv__(self, y):
    if isinstance(y, Var): y = y.y
    self.v//=y; return self
  def __idiv__(self, y):
    if isinstance(y, Var): y = y.y
    self.v/=y; return self
  def __itruediv__(self, y):
    if isinstance(y, Var): y = y.y
    self.v/=y; return self
  def __imod__(self, y):
    if isinstance(y, Var): y = y.y
    self.v%=y; return self
  def __ipow__(self, y):
    if isinstance(y, Var): y = y.y
    self.v**=y; return self
  def __ilshift__(self, y):
    if isinstance(y, Var): y = y.y
    self.v<<=y; return self
  def __irshift__(self, y):
    if isinstance(y, Var): y = y.y
    self.v>>=y; return self
  def __iand__(self, y):
    if isinstance(y, Var): y = y.y
    self.v&=y; return self
  def __ixor__(self, y):
    if isinstance(y, Var): y = y.y
    self.v^=y; return self
  def __ior__(self, y):
    if isinstance(y, Var): y = y.y
    self.v|=y; return self

  def __iter__(self): return iter(self.v)
  def __neg__(self):  return -self.v>=y
  def __pos__(self): return +self.v
  def __abs__(self): return abs(self.v)
  def __invert__(self): return ~self.v


text:
var support = require( './support' )
  , sandbox = require( 'sandboxed-module' )
  , expect = support.expect
  , stream = require( 'stream' ).Stream
  , stub = support.stub
  , flickrStub = stub()
  , parsedJsonPipeStub = stub()
  , jsonStreamStub = stub().returns( parsedJsonPipeStub )
  , Panda = sandbox.require( '../lib/pandas', {
      requires: {
        './flickr': { request: flickrStub }
      , 'JSONStream': { parse: jsonStreamStub }
      }
    })

describe( 'Panda', function() {

  beforeEach( function() {
    flickrStub.reset()
    jsonStreamStub.reset()
    parsedJsonPipeStub.reset()
  })

  var apiKey = 'laksdjlksdafj'
    , panda  = new Panda( apiKey )

  it( 'throws an error if api_key not provided/falsey', function(){
    expect( Panda ).to.throw( /must provide a valid Flickr API key/i )
  })

  it( 'throws an error if api_key is not a string', function() {
    expect( function(){ new Panda( 3214 ) } )
      .to.throw( /must provide a valid Flickr API key/i )
  })

  it( 'stores the api key', function() {
    expect( panda.apiKey ).to.equal( apiKey )
  })

  describe( '#getList', function() {

    var flickrStream

    beforeEach( function() {
      flickrStream = panda.getList()
    })

    it( 'passes along the panda\'s api_key in an options object', function() {
      expect( flickrStub.args[0][1] ).to.have.ownProperty( 'api_key' )
    })

    it( 'requests a response for the flickr.panda.getList', function() {
      expect( flickrStub ).to.have.been.calledWith( 'flickr.panda.getList' )
    })

    it( 'parses out pandas', function() {
      expect( jsonStreamStub ).to.have.been
        .calledWith( [ 'pandas', true, true, '_content' ] )
    })

    it( 'returns the JSONStream', function() {
      expect( flickrStream ).to.equal( parsedJsonPipeStub )
    })

  })

  describe( '#getPhoto', function() {

    var photoStream

    beforeEach( function() {
      photoStream = panda.getPhotos( 'pan' )
    })

    it( 'passes along the panda\'s api_key in an options object', function() {
      expect( flickrStub.args[0][1] ).to.have.ownProperty( 'api_key' )
    })

    it( 'passes along the panda name to the flickr request', function() {
      expect( flickrStub.args[0][1] ).to.have.ownProperty( 'panda_name' )
    })

    it( 'requests a response for the flickr.panda.getPhoto', function() {
      expect( flickrStub ).to.have.been.calledWith( 'flickr.panda.getPhotos' )
    })

    it( 'creates a JSON stream that listens for photos > photo', function() {
      expect( jsonStreamStub ).to.have
        .been.calledWith([  'photos', 'photo', true ])
    })

    it( 'returns the JSON stream that listens for photos', function() {
      expect( photoStream ).to.equal( parsedJsonPipeStub )
    })

  })

})


text:
package edu.colorado.hopper.solver

import com.microsoft.z3.{AST, ArithExpr, BoolExpr, Context, Expr, IntExpr, Status}
import edu.colorado.hopper.state.{PureExpr, PureVal, PureVar}
import edu.colorado.walautil.Types.MMap

import scala.collection.mutable.HashMap

class Z3Solver extends ModelSolver[AST] {
  val ctx : Context = new Context
  val solver = {
    val solver = ctx.mkSolver
    val params = ctx.mkParams()
    params.add("timeout", 10000)
    solver.setParameters(params)
    solver
  }

  // We maintain a mapping from Z3 names to PureVars for producing useful models
  val names : MMap[String, PureVar] = new HashMap[String, PureVar]

  override def checkSAT : Boolean = interpretSolverOutput(solver.check)

  override def checkSATWithAssumptions(assumes : List[String]) : Boolean =
    interpretSolverOutput(solver.check(assumes.map(assume => ctx.mkBoolConst(assume)) : _*))

  override def push() : Unit = solver.push()
  override def pop() : Unit = solver.pop()

  override def getUNSATCore : String =  sys.error("Unimp")

  override def dispose() : Unit =  ctx.dispose()

  private def interpretSolverOutput(status : Status) : Boolean = status match {
    case Status.UNSATISFIABLE => false
    case Status.SATISFIABLE => true
    case Status.UNKNOWN =>
      // this usually happens because of timeouts
      throw new UnknownSMTResult("Z3 decidability or timeout issue--got Status.UNKNOWN")
  }

  override def mkAssert(a : AST) : Unit = solver.add(a.asInstanceOf[BoolExpr])

  override def mkNot(o : AST) : AST = ctx.mkNot(o.asInstanceOf[BoolExpr])
  override def mkEq(lhs : AST, rhs : AST) : AST = ctx.mkEq(lhs.asInstanceOf[Expr], rhs.asInstanceOf[Expr])
  override def mkNe(lhs : AST, rhs : AST) : AST = ctx.mkNot(ctx.mkEq(lhs.asInstanceOf[Expr], rhs.asInstanceOf[Expr]))
  override def mkGt(lhs : AST, rhs : AST) : AST = ctx.mkGt(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])
  override def mkLt(lhs : AST, rhs : AST) : AST = ctx.mkLt(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])
  override def mkGe(lhs : AST, rhs : AST) : AST = ctx.mkGe(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])
  override def mkLe(lhs : AST, rhs : AST) : AST = ctx.mkLe(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])

  override def mkAdd(lhs : AST, rhs : AST) : AST = ctx.mkAdd(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])
  override def mkSub(lhs : AST, rhs : AST) : AST = ctx.mkSub(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])
  override def mkMul(lhs : AST, rhs : AST) : AST = ctx.mkMul(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])
  override def mkDiv(lhs : AST, rhs : AST) : AST = ctx.mkDiv(lhs.asInstanceOf[ArithExpr], rhs.asInstanceOf[ArithExpr])
  override def mkRem(lhs : AST, rhs : AST) : AST = ctx.mkMod(lhs.asInstanceOf[IntExpr], rhs.asInstanceOf[IntExpr])
  override def mkImplies(lhs : AST, rhs : AST) : AST = ctx.mkImplies(lhs.asInstanceOf[BoolExpr], rhs.asInstanceOf[BoolExpr])
  override def mkAnd(lhs : AST, rhs : AST) : AST = ctx.mkAnd(lhs.asInstanceOf[BoolExpr], rhs.asInstanceOf[BoolExpr])
  override def mkOr(lhs : AST, rhs : AST) : AST = ctx.mkOr(lhs.asInstanceOf[BoolExpr], rhs.asInstanceOf[BoolExpr])
  override def mkXor(lhs : AST, rhs : AST) : AST = ctx.mkXor(lhs.asInstanceOf[BoolExpr], rhs.asInstanceOf[BoolExpr])

  override def mkIntVal(i : Int) : AST = ctx.mkInt(i)
  override def mkBoolVal(b : Boolean) : AST = ctx.mkBool(b)
  override def mkIntVar(s : String) : AST = ctx.mkIntConst(s)
  override def mkBoolVar(s : String) : AST = ctx.mkBoolConst(s)

  override def toAST(p: PureExpr) : AST = {
    p match {
      // Every time we create a name referencing a PureVar in our solver,
      // add it to a mapping so we can resolve names later.
      case p@PureVar(_) => names += (getSolverName(p) -> p)
      case _ => {}
    }
    super.toAST(p)
  }

  override def model: Option[Map[PureVar, PureVal]] = sys.error("Unimp")
}


text:
<?php

namespace MicrosoftAzure\Arm\Graph;

use MicrosoftAzure\Common\Internal\Http\HttpClient;
use MicrosoftAzure\Common\Internal\Resources;
use MicrosoftAzure\Common\Internal\Utilities;
use MicrosoftAzure\Common\Internal\Validate;

/**
 * ServicePrincipals for The Graph RBAC Management Client
 */
class ServicePrincipals
{
    /**
     * The service client object for the operations.
     *
     * @var GraphRbacManagementClient
     */
    private $_client;

    /**
     * Creates a new instance for ServicePrincipals.
     *
     * @param GraphRbacManagementClient, Service client for ServicePrincipals
     */
    public function __construct($client)
    {
        $this->_client = $client;
    }

    /**
     * Creates a service principal in the  directory.
     *
     * @param array $parameters Parameters to create a service principal.
     *

     * [
     *    'appId' => 'requiredAppId',
     *    'accountEnabled' => 'false'
     * ];
     *

     * @param array $customHeaders An array of custom headers ['key' => 'value'] that will be added to
     *  the HTTP request.
     *
     * @return array
     * When the resposne status is Created(201),
     *

     * [
     *    'objectId' => '',
     *    'objectType' => '',
     *    'displayName' => '',
     *    'appId' => '',
     *    'servicePrincipalNames' => ''
     * ];
     *

     */
    public function create(array $parameters, array $customHeaders = [])
    {
        $response = $this->createAsync($parameters, $customHeaders);

        if ($response->getBody()) {
            $contents = $response->getBody()->getContents();
            if ($contents) {
                return $this->_client->getDataSerializer()->deserialize($contents);
            }
        }

        return [];
    }

    /**
     * Creates a service principal in the  directory.
     *
     * @param array $parameters Parameters to create a service principal.
     *

     * [
     *    'appId' => 'requiredAppId',
     *    'accountEnabled' => 'false'
     * ];
     *

     * @param array $customHeaders An array of custom headers ['key' => 'value']
     * that will be added to the HTTP request.
     *
     * @return \GuzzleHttp\Psr7\Response
     */
    public function createAsync(array $parameters, array $customHeaders = [])
    {
        if ($parameters == null) {
            Validate::notNullOrEmpty($parameters, '$parameters');
        }
        if ($this->_client->getApiVersion() == null) {
            Validate::notNullOrEmpty($this->_client->getApiVersion(), '$this->_client->getApiVersion()');
        }
        if ($this->_client->getTenantID() == null) {
            Validate::notNullOrEmpty($this->_client->getTenantID(), '$this->_client->getTenantID()');
        }

        $path = '/{tenantID}/servicePrincipals';
        $statusCodes = [201];
        $method = 'POST';

        $path = strtr($path, ['{tenantID}' => $this->_client->getTenantID()]);
        $queryParams = ['api-version' => $this->_client->getApiVersion()];
        $headers = $customHeaders;
        if ($this->_client->getAcceptLanguage() != null) {
            $headers['accept-language'] = $this->_client->getAcceptLanguage();
        }
        if ($this->_client->getGenerateClientRequestId()) {
            $headers[Resources::X_MS_REQUEST_ID] = Utilities::getGuid();
        }

        $headers['Content-Type'] = 'application/json; charset=utf-8';
        $body = $this->_client->getDataSerializer()->serialize($parameters);

        $response = HttpClient::send(
            $method,
            $headers,
            $queryParams,
            [],
            $this->_client->getUrl($path),
            $statusCodes,
            $body,
            $this->_client->getFilters()
        );

        return $response;
    }

    /**
     * Gets list of service principals from the current tenant.
     *
     * @param array $filter The filter to apply on the operation.
     *

     * [
     *    'objectId' => '',
     *    'objectType' => '',
     *    'displayName' => '',
     *    'appId' => '',
     *    'servicePrincipalNames' => ''
     * ];
     *

     * @param array $customHeaders An array of custom headers ['key' => 'value'] that will be added to
     *  the HTTP request.
     *
     * @return array
     * When the resposne status is OK(200),
     *

     * [
     *    'value' => '',
     *    'odata.nextLink' => ''
     * ];
     *

     */
    public function listOperation(array $filter, array $customHeaders = [])
    {
        $response = $this->listOperationAsync($filter, $customHeaders);

        if ($response->getBody()) {
            $contents = $response->getBody()->getContents();
            if ($contents) {
                return $this->_client->getDataSerializer()->deserialize($contents);
            }
        }

        return [];
    }

    /**
     * Gets list of service principals from the current tenant.
     *
     * @param array $filter The filter to apply on the operation.
     *

     * [
     *    'objectId' => '',
     *    'objectType' => '',
     *    'displayName' => '',
     *    'appId' => '',
     *    'servicePrincipalNames' => ''
     * ];
     *

     * @param array $customHeaders An array of custom headers ['key' => 'value']
     * that will be added to the HTTP request.
     *
     * @return \GuzzleHttp\Psr7\Response
     */
    public function listOperationAsync(array $filter, array $customHeaders = [])
    {
        if ($this->_client->getApiVersion() == null) {
            Validate::notNullOrEmpty($this->_client->getApiVersion(), '$this->_client->getApiVersion()');
        }
        if ($this->_client->getTenantID() == null) {
            Validate::notNullOrEmpty($this->_client->getTenantID(), '$this->_client->getTenantID()');
        }

        $path = '/{tenantID}/servicePrincipals';
        $statusCodes = [200];
        $method = 'GET';

        $path = strtr($path, ['{tenantID}' => $this->_client->getTenantID()]);
        $queryParams = ['$filter' => $filter, 'api-version' => $this->_client->getApiVersion()];
        $headers = $customHeaders;
        if ($this->_client->getAcceptLanguage() != null) {
            $headers['accept-language'] = $this->_client->getAcceptLanguage();
        }
        if ($this->_client->getGenerateClientRequestId()) {
            $headers[Resources::X_MS_REQUEST_ID] = Utilities::getGuid();
        }

        $body = '';

        $response = HttpClient::send(
            $method,
            $headers,
            $queryParams,
            [],
            $this->_client->getUrl($path),
            $statusCodes,
            $body,
            $this->_client->getFilters()
        );

        return $response;
    }

    /**
     * Deletes service principal from the directory.
     *
     * @param string $objectId Object id to delete service principal information.
     * @param array $customHeaders An array of custom headers ['key' => 'value'] that will be added to
     *  the HTTP request.
     *
     * @return array
     * Empty array with resposne status NoContent(204).

     */
    public function delete($objectId, array $customHeaders = [])
    {
        $response = $this->deleteAsync($objectId, $customHeaders);

        if ($response->getBody()) {
            $contents = $response->getBody()->getContents();
            if ($contents) {
                return $this->_client->getDataSerializer()->deserialize($contents);
            }
        }

        return [];
    }

    /**
     * Deletes service principal from the directory.
     *
     * @param string $objectId Object id to delete service principal information.
     * @param array $customHeaders An array of custom headers ['key' => 'value']
     * that will be added to the HTTP request.
     *
     * @return \GuzzleHttp\Psr7\Response
     */
    public function deleteAsync($objectId, array $customHeaders = [])
    {
        if ($objectId == null) {
            Validate::notNullOrEmpty($objectId, '$objectId');
        }
        if ($this->_client->getApiVersion() == null) {
            Validate::notNullOrEmpty($this->_client->getApiVersion(), '$this->_client->getApiVersion()');
        }
        if ($this->_client->getTenantID() == null) {
            Validate::notNullOrEmpty($this->_client->getTenantID(), '$this->_client->getTenantID()');
        }

        $path = '/{tenantID}/servicePrincipals/{objectId}';
        $statusCodes = [204];
        $method = 'DELETE';

        $path = strtr($path, ['{tenantID}' => $this->_client->getTenantID()]);
        $queryParams = ['api-version' => $this->_client->getApiVersion()];
        $headers = $customHeaders;
        if ($this->_client->getAcceptLanguage() != null) {
            $headers['accept-language'] = $this->_client->getAcceptLanguage();
        }
        if ($this->_client->getGenerateClientRequestId()) {
            $headers[Resources::X_MS_REQUEST_ID] = Utilities::getGuid();
        }

        $body = '';

        $response = HttpClient::send(
            $method,
            $headers,
            $queryParams,
            [],
            $this->_client->getUrl($path),
            $statusCodes,
            $body,
            $this->_client->getFilters()
        );

        return $response;
    }

    /**
     * Gets service principal information from the directory.
     *
     * @param string $objectId Object id to get service principal information.
     * @param array $customHeaders An array of custom headers ['key' => 'value'] that will be added to
     *  the HTTP request.
     *
     * @return array
     * When the resposne status is OK(200),
     *

     * [
     *    'objectId' => '',
     *    'objectType' => '',
     *    'displayName' => '',
     *    'appId' => '',
     *    'servicePrincipalNames' => ''
     * ];
     *

     */
    public function get($objectId, array $customHeaders = [])
    {
        $response = $this->getAsync($objectId, $customHeaders);

        if ($response->getBody()) {
            $contents = $response->getBody()->getContents();
            if ($contents) {
                return $this->_client->getDataSerializer()->deserialize($contents);
            }
        }

        return [];
    }

    /**
     * Gets service principal information from the directory.
     *
     * @param string $objectId Object id to get service principal information.
     * @param array $customHeaders An array of custom headers ['key' => 'value']
     * that will be added to the HTTP request.
     *
     * @return \GuzzleHttp\Psr7\Response
     */
    public function getAsync($objectId, array $customHeaders = [])
    {
        if ($objectId == null) {
            Validate::notNullOrEmpty($objectId, '$objectId');
        }
        if ($this->_client->getApiVersion() == null) {
            Validate::notNullOrEmpty($this->_client->getApiVersion(), '$this->_client->getApiVersion()');
        }
        if ($this->_client->getTenantID() == null) {
            Validate::notNullOrEmpty($this->_client->getTenantID(), '$this->_client->getTenantID()');
        }

        $path = '/{tenantID}/servicePrincipals/{objectId}';
        $statusCodes = [200];
        $method = 'GET';

        $path = strtr($path, ['{tenantID}' => $this->_client->getTenantID()]);
        $queryParams = ['api-version' => $this->_client->getApiVersion()];
        $headers = $customHeaders;
        if ($this->_client->getAcceptLanguage() != null) {
            $headers['accept-language'] = $this->_client->getAcceptLanguage();
        }
        if ($this->_client->getGenerateClientRequestId()) {
            $headers[Resources::X_MS_REQUEST_ID] = Utilities::getGuid();
        }

        $body = '';

        $response = HttpClient::send(
            $method,
            $headers,
            $queryParams,
            [],
            $this->_client->getUrl($path),
            $statusCodes,
            $body,
            $this->_client->getFilters()
        );

        return $response;
    }

    /**
     * Gets list of service principals from the current tenant.
     *
     * @param string $nextLink Next link for list operation.
     * @param array $customHeaders An array of custom headers ['key' => 'value'] that will be added to
     *  the HTTP request.
     *
     * @return array
     * When the resposne status is OK(200),
     *

     * [
     *    'value' => '',
     *    'odata.nextLink' => ''
     * ];
     *

     */
    public function listNext($nextLink, array $customHeaders = [])
    {
        $response = $this->listNextAsync($nextLink, $customHeaders);

        if ($response->getBody()) {
            $contents = $response->getBody()->getContents();
            if ($contents) {
                return $this->_client->getDataSerializer()->deserialize($contents);
            }
        }

        return [];
    }

    /**
     * Gets list of service principals from the current tenant.
     *
     * @param string $nextLink Next link for list operation.
     * @param array $customHeaders An array of custom headers ['key' => 'value']
     * that will be added to the HTTP request.
     *
     * @return \GuzzleHttp\Psr7\Response
     */
    public function listNextAsync($nextLink, array $customHeaders = [])
    {
        if ($nextLink == null) {
            Validate::notNullOrEmpty($nextLink, '$nextLink');
        }
        if ($this->_client->getApiVersion() == null) {
            Validate::notNullOrEmpty($this->_client->getApiVersion(), '$this->_client->getApiVersion()');
        }
        if ($this->_client->getTenantID() == null) {
            Validate::notNullOrEmpty($this->_client->getTenantID(), '$this->_client->getTenantID()');
        }

        $path = '/{tenantID}/{nextLink}';
        $statusCodes = [200];
        $method = 'GET';

        $path = strtr($path, ['{tenantID}' => $this->_client->getTenantID()]);
        $queryParams = ['api-version' => $this->_client->getApiVersion()];
        $headers = $customHeaders;
        if ($this->_client->getAcceptLanguage() != null) {
            $headers['accept-language'] = $this->_client->getAcceptLanguage();
        }
        if ($this->_client->getGenerateClientRequestId()) {
            $headers[Resources::X_MS_REQUEST_ID] = Utilities::getGuid();
        }

        $body = '';

        $response = HttpClient::send(
            $method,
            $headers,
            $queryParams,
            [],
            $this->_client->getUrl($path),
            $statusCodes,
            $body,
            $this->_client->getFilters()
        );

        return $response;
    }
}


text:
using System;
using NDatabase.Api;
using NDatabase.Meta;
using NDatabase.Oid;
using NDatabase.Triggers;

namespace NDatabase.Core
{
    internal interface IObjectWriter : IDisposable
    {
        ClassInfoList AddClasses(ClassInfoList classInfoList);

        void UpdateClassInfo(ClassInfo classInfo, bool writeInTransaction);

        /// <param name="oid"> The Oid of the object to be inserted </param>
        /// <param name="nnoi"> The object meta representation The object to be inserted in the database </param>
        /// <param name="isNewObject"> To indicate if object is new </param>
        /// <returns> The position of the inserted object </returns>
        OID InsertNonNativeObject(OID oid, NonNativeObjectInfo nnoi, bool isNewObject);

        /// <summary>
        ///   Updates an object.
        /// </summary>
        /// <remarks>
        ///   Updates an object. Deletes the current object and creates a new at the end of the database file and updates
        ///                        OID object position.
        /// </remarks>
        /// <param name="nnoi"> The meta representation of the object to be updated </param>
        /// <param name="forceUpdate"> when true, no verification is done to check if update must be done. </param>
        /// <returns> The oid of the object, as a negative number </returns>
        OID UpdateNonNativeObjectInfo(NonNativeObjectInfo nnoi, bool forceUpdate);

        IIdManager GetIdManager();

        void Close();

        /// <summary>
        ///   Creates the header of the file
        /// </summary>
        /// <param name="creationDate"> The creation date </param>
        void CreateEmptyDatabaseHeader(long creationDate);

        OID Delete(ObjectInfoHeader header);

        /// <summary>
        ///   Updates the previous object position field of the object at objectPosition
        /// </summary>
        /// <param name="objectOID"> </param>
        /// <param name="previousObjectOID"> </param>
        /// <param name="writeInTransaction"> </param>
        void UpdatePreviousObjectFieldOfObjectInfo(OID objectOID, OID previousObjectOID, bool writeInTransaction);

        /// <summary>
        ///   Update next object oid field of the object at the specific position
        /// </summary>
        /// <param name="objectOID"> </param>
        /// <param name="nextObjectOID"> </param>
        /// <param name="writeInTransaction"> </param>
        void UpdateNextObjectFieldOfObjectInfo(OID objectOID, OID nextObjectOID, bool writeInTransaction);

        void AfterInit();

        void SetTriggerManager(IInternalTriggerManager triggerManager);

        /// <summary>
        ///   Mark a block as deleted
        /// </summary>
        /// <returns> The block size </returns>
        void MarkAsDeleted(long currentPosition, bool writeInTransaction);

        ClassInfo AddClass(ClassInfo newClassInfo, bool addDependentClasses);

        /// <summary>
        ///   Updates pointers of objects, Only changes uncommitted info pointers
        /// </summary>
        /// <param name="objectInfo"> The meta representation of the object being inserted </param>
        /// <param name="classInfo"> The class of the object being inserted </param>
        void ManageNewObjectPointers(NonNativeObjectInfo objectInfo, ClassInfo classInfo);

        /// <summary>
        ///   Store a meta representation of a native object(already as meta representation)in ODBFactory database.
        /// </summary>
        /// <remarks>
        ///   Store a meta representation of a native object(already as meta representation)in ODBFactory database. A Native object is an object that use native language type, String for example To detect if object must be updated or insert, we use the cache. To update an object, it must be first selected from the database. When an object is to be stored, if it exist in the cache, then it will be updated, else it will be inserted as a new object. If the object is null, the cache will be used to check if the meta representation is in the cache
        /// </remarks>
        /// <param name="noi"> The meta representation of an object </param>
        /// <returns> The object position @ </returns>
        long InternalStoreObject(NativeObjectInfo noi);

        /// <summary>
        ///   Insert the object in the index
        /// </summary>
        /// <param name="oid"> The object id </param>
        /// <param name="nnoi"> The object meta represenation </param>
        void ManageIndexesForInsert(OID oid, NonNativeObjectInfo nnoi);

        /// <summary>
        ///   Store a meta representation of an object(already as meta representation)in ODBFactory database.
        /// </summary>
        /// <remarks>
        ///   Store a meta representation of an object(already as meta representation)in ODBFactory database. To detect if object must be updated or insert, we use the cache. To update an object, it must be first selected from the database. When an object is to be stored, if it exist in the cache, then it will be updated, else it will be inserted as a new object. If the object is null, the cache will be used to check if the meta representation is in the cache
        /// </remarks>
        /// <param name="oid"> The oid of the object to be inserted/updates </param>
        /// <param name="nnoi"> The meta representation of an object </param>
        /// <returns> The object position </returns>
        OID StoreObject(OID oid, NonNativeObjectInfo nnoi);

        IFileSystemWriter FileSystemProcessor { get; }
    }
}


text:
package org.vaadin.example;

import com.vaadin.annotations.AutoGenerated;
import com.vaadin.annotations.DesignRoot;
import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.declarative.Design;

/**
 * !! DO NOT EDIT THIS FILE !!
 *
 * This class is generated by Vaadin Designer and will be overwritten.
 *
 * Please make a subclass with logic and additional interfaces as needed,
 * e.g class LoginView extends LoginDesign implements View { … }
 */
@DesignRoot
@AutoGenerated
@SuppressWarnings("serial")
public class ApplicationDesign extends HorizontalLayout {
    protected Button menuToggle;
    protected CssLayout menuItems;
    protected Button composeButton;
    protected Button inboxButton;
    protected Button draftsButton;
    protected Button sentButton;
    protected Button junkButton;
    protected Button trashButton;
    protected Button flaggedButton;
    protected VerticalLayout content;
    protected ComboBox sortCombo;
    protected Button deleteButton;
    protected Button replyButton;
    protected Button replyAllButton;
    protected Button forwardButton;
    protected VerticalLayout messageList;

    public ApplicationDesign() {
        Design.read(this);
    }
}


text:
About
-----
- Author: [Trent Richardson](http://trentrichardson.com)
- Original Source: [https://github.com/trentrichardson/jQuery-Timepicker-Addon](https://github.com/trentrichardson/jQuery-Timepicker-Addon)
- Documentation: [http://trentrichardson.com/examples/timepicker/](http://trentrichardson.com/examples/timepicker/)
- Twitter: [@practicalweb](http://twitter.com/practicalweb)
- Ported By: [Cigano Morrison Mendez](http://github.com/cigano)

Use
---
Simply invoke the `Install-Package` from [NuGet](http://nuget.org) to install with all dependencies resolved:

`Install-Package jQuery-Timepicker-Addon`


text:
describe('ScrollingWizard', function() {
  var options;
  options = {
    message: 'Hello World'
  };
  beforeEach(function() {
    loadFixtures('fragment.html');
    return this.$element = $('#fixtures');
  });
  describe('plugin behavior', function() {
    it('should be available on the jQuery object', function() {
      return expect($.fn.scrollingWizard).toBeDefined();
    });
    it('should be chainable', function() {
      return expect(this.$element.scrollingWizard()).toBe(this.$element);
    });
    it('should offers default values', function() {
      var plugin;
      plugin = new $.scrollingWizard(this.$element);
      return expect(plugin.defaults).toBeDefined();
    });
    return it('should overwrites the settings', function() {
      var plugin;
      plugin = new $.scrollingWizard(options);
      return expect(plugin.settings.message).toBe(options.message);
    });
  });
  return describe('plugin state', function() {
    beforeEach(function() {
      return this.plugin = new $.scrollingWizard();
    });
    it('should have a ready state', function() {
      return expect(this.plugin.getState()).toBe('ready');
    });
    return it('should be updatable', function() {
      this.plugin.setState('new state');
      return expect(this.plugin.getState()).toBe('new state');
    });
  });
});


text:
var asyncCallbacks = {
  _next_id: 0,
  _callbacks: {},
  key: '_callback',

  // Return a callback ID number which will be contained by the native message.
  setup: function(callback) {
    var id = ++this._next_id;
    this._callbacks[id] = callback;
    return id;
  },

  dispatch: function(m) {
    var id = m[this.key];
    var callback = this._callbacks[id];
    callback.call(null, m);
    delete this._callbacks[id];
  }
};

var appInfoEventCallbacks = {
  _next_id: 0,
  _callbacks: [],
  key: '_appInfoEventCallback',

  // Return a callback ID number which can be unregistered later.
  addCallback: function(callback) {
    if (!this._callbacks.length) {
      var result = sendSyncMessage({ cmd: 'RegisterAppInfoEvent' });
      if (result.error !== null && result.error !== undefined)
        throw new tizen.WebAPIException(result.error);
    }

    var id = ++this._next_id;
    this._callbacks.push({func: callback, id: id});
    return id;
  },

  removeCallback: function(id) {
    for (var i = 0, len = this._callbacks.length; i < len; i++) {
      if (id === this._callbacks[i].id)
        break;
    }
    if (i == len)
      throw new tizen.WebAPIException(tizen.WebAPIException.NOT_FOUND_ERR);

    this._callbacks.splice(i, 1);
    if (!this._callbacks.length) {
      var result = sendSyncMessage({ cmd: 'UnregisterAppInfoEvent' });
      if (result.error !== null && result.error !== undefined)
        throw new tizen.WebAPIException(result.error);
    }
  },

  dispatch: function(m) {
    var callbacks = this._callbacks.slice();
    for (var i = 0, len = callbacks.length; i < len; i++)
      callbacks[i].func.call(null, m);
  }
};

extension.setMessageListener(function(msg) {
  var m = JSON.parse(msg);
  if (typeof m[asyncCallbacks.key] === 'number') {
    asyncCallbacks.dispatch(m);
  } else {
    if (m[asyncCallbacks.key] === appInfoEventCallbacks.key)
      appInfoEventCallbacks.dispatch(m);
    else
      console.error('unexpected message received' + msg);
  }
});

// Post async message to extension with callbackId saved. The extension will return
// a message with the same callbackId to the callback set in setMessageListener.
function postMessage(msg, callbackId) {
  if (callbackId !== undefined && callbackId !== null) {
    msg[asyncCallbacks.key] = callbackId;
  }
  extension.postMessage(JSON.stringify(msg));
}

function sendSyncMessage(msg) {
  return JSON.parse(extension.internal.sendSyncMessage(JSON.stringify(msg)));
}

function defineProperty(object, key, value) {
  Object.defineProperty(object, key, {
    enumerable: true,
    writable: true,
    value: value
  });
}

function defineReadOnlyProperty(object, key, value) {
  Object.defineProperty(object, key, {
    enumerable: true,
    writable: false,
    value: value
  });
}

function defineNonNullProperty(object, key, value) {
  var property_value = value;
  Object.defineProperty(object, key, {
    enumerable: true,
    set: function(val) {
      if (val !== null && val !== undefined) {
        property_value = val;
      }
    },
    get: function() {
      return property_value;
    }
  });
}

// ApplicationControlData interface
tizen.ApplicationControlData = function(key, value) {
  if (!(this instanceof tizen.ApplicationControlData)) {
    throw new TypeError();
  }

  if (typeof key !== 'string' || !(value instanceof Array)) {
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  }

  // FIXME: tests assume you can push anything to value
  // so stringify data instead of validating it
  for (var i = 0; i < value.length; i++) {
    value[i] = String(value[i]);
  }

  defineNonNullProperty(this, 'key', key);
  defineNonNullProperty(this, 'value', value);
};

function toApplicationControlDataArray(data) {
  var array_objects = [];
  for (var i = 0; i < data.length; i++) {
    if (typeof data[i]['key'] != 'string' || !(data[i]['value'] instanceof Array)) {
      throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_UNKNOWN_ERR);
    }
    array_objects.push(new tizen.ApplicationControlData(data[i]['key'], data[i]['value']));
  }
  return array_objects;
}

// ApplicationControl interface
tizen.ApplicationControl = function(operation, uri, mime, category, data) {
  if (!(this instanceof tizen.ApplicationControl)) {
    throw new TypeError();
  }

  if (uri === undefined) {
    uri = null;
  }
  if (mime === undefined) {
    mime = null;
  }
  if (category === undefined) {
    category = null;
  }
  if (data === undefined || data === null) {
    data = [];
  }

  if (typeof operation !== 'string' ||
      uri !== null &&
      typeof uri !== 'string' ||
      mime !== null &&
      typeof mime !== 'string' ||
      category !== null &&
      typeof category !== 'string' ||
      !(data instanceof Array)) {
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  }

  if (data) {
    for (var i = 0; i < data.length; i++) {
      if (!(data[i] instanceof tizen.ApplicationControlData)) {
        throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
      }
    }
  }

  defineNonNullProperty(this, 'operation', operation);
  defineProperty(this, 'uri', uri);
  defineProperty(this, 'mime', mime);
  defineProperty(this, 'category', category);
  defineNonNullProperty(this, 'data', data);
};

// RequestedApplicationControl interface
function RequestedApplicationControl(appControl, callerAppId) {
  if (!(appControl instanceof tizen.ApplicationControl) ||
      typeof callerAppId !== 'string') {
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_UNKNOWN_ERR);
  }

  defineReadOnlyProperty(this, 'appControl', appControl);
  defineReadOnlyProperty(this, 'callerAppId', callerAppId);
}

RequestedApplicationControl.prototype.replyResult = function(data) {
  if (data === undefined || data === null) {
    data = [];
  }
  if (!(data instanceof Array))
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  for (var acd = 0; acd < data.length; acd++) {
    if (!(data[acd] instanceof tizen.ApplicationControlData)) {
      throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
    }
  }

  var msg = { cmd: 'ReplyResult', data: data };
  var result = sendSyncMessage(msg);
  if (result.error !== null && result.error !== undefined)
    throw new tizen.WebAPIException(result.error);
};

RequestedApplicationControl.prototype.replyFailure = function() {
  var msg = { cmd: 'ReplyFailure' };
  var result = sendSyncMessage(msg);
  if (result.error !== null && result.error !== undefined) {
    throw new tizen.WebAPIException(result.error);
  }
};

// Application interface
function Application(appInfo, contextId) {
  if (!(this instanceof Application))
    throw new TypeError;

  defineReadOnlyProperty(this, 'appInfo', appInfo);
  defineReadOnlyProperty(this, 'contextId', contextId);
}

Application.prototype.exit = function() {
  var result = sendSyncMessage({ cmd: 'ExitCurrentApp' });
  if (result.error !== null && result.error !== undefined) {
    throw new tizen.WebAPIException(result.error);
  }
};

Application.prototype.hide = function() {
  var result = sendSyncMessage({ cmd: 'HideCurrentApp' });
  if (result.error !== null && result.error !== undefined) {
    throw new tizen.WebAPIException(result.error);
  }
};

Application.prototype.getRequestedAppControl = function() {
  var msg = { cmd: 'GetRequestedAppControl' };
  var result = sendSyncMessage(msg);

  if (result.error !== null && result.error !== undefined) {
    throw new tizen.WebAPIException(result.error);
  }

  var data = result.data;
  if (!data.appControl || !data.callerId) {
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_UNKNOWN_ERR);
  }

  return new RequestedApplicationControl(
      new tizen.ApplicationControl(
          data.appControl.operation,
          data.appControl.uri,
          data.appControl.mime,
          data.appControl.category,
          toApplicationControlDataArray(data.appControl.data)), data.callerId);
};

// ApplicationContext interface.
function ApplicationContext(json) {
  defineReadOnlyProperty(this, 'id', json.id);
  defineReadOnlyProperty(this, 'appId', json.appId);
}

// ApplicationInformation interface.
function ApplicationInformation(json) {
  for (var field in json) {
    var val = json[field];
    if (field === 'installDate')
      val = new Date(val * 1000);
    defineReadOnlyProperty(this, field, val);
  }
}

// ApplicationMetaData interface.
function ApplicationMetaData(json) {
  defineReadOnlyProperty(this, 'key', json.key);
  defineReadOnlyProperty(this, 'value', json.value);
}

exports.getAppInfo = function(appId) {
  if (typeof appId !== 'string' && appId != undefined)
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var result = sendSyncMessage({ cmd: 'GetAppInfo', id: appId });
  if (result.error !== null && result.error !== undefined)
    throw new tizen.WebAPIException(result.error);
  return new ApplicationInformation(result.data);
};

exports.getAppsInfo = function(onsuccess, onerror) {
  if ((typeof onsuccess !== 'function') ||
      (onerror !== null && onerror !== undefined && typeof onerror !== 'function'))
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var callbackId = asyncCallbacks.setup(function(result) {
    if (result.error !== null && result.error !== undefined) {
      if (!onerror)
        return;
      return onerror(new tizen.WebAPIError(result.error));
    }

    var appsInfo = [];
    for (var i = 0, len = result.data.length; i < len; ++i)
      appsInfo.push(new ApplicationInformation(result.data[i]));
    return onsuccess(appsInfo);
  });

  var msg = { cmd: 'GetAppsInfo' };
  postMessage(msg, callbackId);
};

exports.getAppContext = function(contextId) {
  if (contextId && !/^\d+$/.test(contextId))
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var result = sendSyncMessage({ cmd: 'GetAppContext', id: contextId});
  if (result.error)
    throw new tizen.WebAPIException(result.error);

  return new ApplicationContext(result.data);
};

exports.getAppsContext = function(onsuccess, onerror) {
  if ((typeof onsuccess !== 'function') ||
      (onerror !== undefined && onerror !== null && typeof onerror !== 'function'))
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var callbackId = asyncCallbacks.setup(function(result) {
    if (result.error !== null && result.error !== undefined) {
      if (!onerror)
        return;
      return onerror(new tizen.WebAPIError(result.error));
    }

    var contexts = [];
    for (var i = 0, len = result.data.length; i < len; ++i) {
      contexts.push(new ApplicationContext(result.data[i]));
    }
    return onsuccess(contexts);
  });

  var msg = { cmd: 'GetAppsContext' };
  postMessage(msg, callbackId);
};

exports.getCurrentApplication = function() {
  var result = sendSyncMessage({ cmd: 'GetCurrentApp' });
  if (result.error)
    throw new tizen.WebAPIException(result.error);

  var appInfo = new ApplicationInformation(result.data.appInfo);
  return new Application(appInfo, result.data.appContext.id);
};

exports.kill = function(contextId, onsuccess, onerror) {
  if ((!/^\d+$/.test(contextId)) ||
      (onsuccess !== undefined && onsuccess !== null &&
       typeof onsuccess !== 'function') ||
      (onerror !== undefined && onerror !== null &&
       typeof onerror !== 'function'))
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var callbackId = asyncCallbacks.setup(function(result) {
    if (result.error != null) {
      if (!onerror)
        return;
      return onerror(new tizen.WebAPIError(result.code));
    }
    if (!onsuccess)
      return;
    return onsuccess();
  });

  var msg = { cmd: 'KillApp', id: contextId };
  postMessage(msg, callbackId);
};

exports.launch = function(appId, onsuccess, onerror) {
  if ((typeof appId !== 'string') ||
      (onsuccess && typeof onsuccess !== 'function') ||
      (onerror && typeof onerror !== 'function'))
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var callbackId = asyncCallbacks.setup(function(result) {
    if (result.error != null) {
      if (!onerror)
        return;
      return onerror(new tizen.WebAPIError(result.error));
    }
    return onsuccess();
  });

  var msg = { cmd: 'LaunchApp', id: appId };
  postMessage(msg, callbackId);
};

exports.launchAppControl =
    function(appControl, id, successCallback, errorCallback, replyCallback) {
  if (!(appControl instanceof tizen.ApplicationControl) ||
      id !== undefined && id !== null && typeof id !== 'string')
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  if (successCallback !== undefined && successCallback !== null &&
      typeof(successCallback) !== 'function' ||
      errorCallback !== undefined && errorCallback !== null &&
      typeof(errorCallback) !== 'function' ||
      replyCallback !== undefined && replyCallback !== null &&
      (typeof(replyCallback) !== 'object' ||
      typeof(replyCallback.onsuccess) !== 'function' ||
      typeof(replyCallback.onfailure) !== 'function')) {
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  }

  var callbackId = asyncCallbacks.setup(function(result) {
    if (result.error !== null && result.error !== undefined) {
      if (!errorCallback) {
        return;
      }
      return errorCallback(new tizen.WebAPIError(result.error));
    }
    if (successCallback) {
      return successCallback();
    }
  });

  var replyId = asyncCallbacks.setup(function(result) {
    if (replyCallback !== undefined && replyCallback !== null) {
      if (result.error !== null && result.error !== undefined) {
        replyCallback.onfailure();
      } else {
        replyCallback.onsuccess(toApplicationControlDataArray(result.data));
      }
    }
  });

  var msg = {
    cmd: 'LaunchAppControl',
    appControl: appControl,
    id: id,
    reply_callback: replyId  // extra callback for async reply
  };
  postMessage(msg, callbackId);
};

exports.findAppControl = function(appControl, successCallback, errorCallback) {
  if (!(appControl instanceof tizen.ApplicationControl) ||
      typeof(successCallback) !== 'function' ||
      errorCallback !== undefined && errorCallback !== null &&
      typeof(errorCallback) !== 'function') {
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  }

  var callbackId = asyncCallbacks.setup(function(result) {
    if (result.error !== null && result.error !== undefined) {
      if (!errorCallback) {
        return;
      }
      return errorCallback(new tizen.WebAPIError(result.error));
    }
    if (successCallback) {
      var array = [];
      for (var i = 0; i < result.data.length; i++) {
        array.push(new ApplicationInformation(result.data[i]));
      }
      return successCallback(array, appControl);
    }
  });

  var msg = { cmd: 'FindAppControl', appControl: appControl };
  postMessage(msg, callbackId);
};

exports.addAppInfoEventListener = function(eventCallback) {
  if (typeof eventCallback !== 'object' ||
      typeof eventCallback.oninstalled !== 'function' ||
      typeof eventCallback.onupdated !== 'function' ||
      typeof eventCallback.onuninstalled !== 'function')
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var watchId = appInfoEventCallbacks.addCallback(function(result) {
    if (result.installed) {
      result.installed.forEach(function(appInfo) {
        var appInfo = new ApplicationInformation(appInfo);
        eventCallback.oninstalled(appInfo);
      });
    }
    if (result.updated) {
      result.updated.forEach(function(appInfo) {
        var appInfo = new ApplicationInformation(appInfo);
        eventCallback.onupdated(appInfo);
      });
    }
    if (result.uninstalled) {
      result.uninstalled.forEach(function(appId) {
        eventCallback.onuninstalled(appId);
      });
    }
  });

  return watchId;
};

exports.removeAppInfoEventListener = function(watchId) {
  if (typeof watchId !== 'number')
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  appInfoEventCallbacks.removeCallback(watchId);
};

exports.getAppMetaData = function(appId) {
  if (typeof appId !== 'string' && appId != undefined)
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);

  var result = sendSyncMessage({ cmd: 'GetAppMetaData', id: appId });
  if (result.error !== null && result.error !== undefined)
    throw new tizen.WebAPIException(result.error);

  var data = [];
  for (var i = 0, len = result.data.length; i < len; ++i)
    data.push(new ApplicationMetaData(result.data[i]));
  return data;
};


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.7: http://docutils.sourceforge.net/" />
<title>The MPL Reference Manual: vector</title>
<link rel="stylesheet" href="../style.css" type="text/css" />

Prev Next | Back Along | Up Home | Full TOC
Front Page / Sequences / Classes / vector

vector

Description

<tt class="literal">vector</tt> is a variadic, random access, extensible sequence of types that
supports constant-time insertion and removal of elements at both ends, and
linear-time insertion and removal of elements in the middle. On compilers that
support the <tt class="literal">typeof</tt> extension, <tt class="literal">vector</tt> is the simplest and in many cases the
most efficient sequence.

Header

<colgroup>
<col width="26%" />
<col width="74%" />
</colgroup>

Sequence form
Header

Variadic
<tt class="literal">#include <boost/mpl/vector.hpp></tt>

Numbered
<tt class="literal">#include <boost/mpl/vector/vector</tt>n<tt class="literal">.hpp></tt>

Model of

Variadic Sequence

Random Access Sequence

Extensible Sequence

Back Extensible Sequence

Front Extensible Sequence

Expression semantics

In the following table, <tt class="literal">v</tt> is an instance of <tt class="literal">vector</tt>, <tt class="literal">pos</tt> and <tt class="literal">last</tt> are iterators
into <tt class="literal">v</tt>, <tt class="literal">r</tt> is a Forward Sequence, <tt class="literal">n</tt> is an Integral Constant, and <tt class="literal">x</tt> and
t1,t2,... tn are arbitrary types.

<colgroup>
<col width="40%" />
<col width="60%" />
</colgroup>

Expression
Semantics

vector<t1,t2,... tn>
vectorn<t1,t2,... tn>

<tt class="literal">vector</tt> of elements t1,t2,... tn; see
Variadic Sequence.

vector<t1,t2,... tn>::type
vectorn<t1,t2,... tn>::type

Identical to <tt class="literal">vector</tt>n<tt class="literal"><</tt>t1,t2,... tn<tt class="literal">></tt>;
see Variadic Sequence.

<tt class="literal">begin<v>::type</tt>
An iterator pointing to the beginning of <tt class="literal">v</tt>;
see Random Access Sequence.

<tt class="literal">end<v>::type</tt>
An iterator pointing to the end of <tt class="literal">v</tt>;
see Random Access Sequence.

<tt class="literal">size<v>::type</tt>
The size of <tt class="literal">v</tt>; see Random Access Sequence.

<tt class="literal">empty<v>::type</tt>
A boolean Integral Constant <tt class="literal">c</tt> such that
<tt class="literal">c::value == true</tt> if and only if the sequence is empty;
see Random Access Sequence.

<tt class="literal">front<v>::type</tt>
The first element in <tt class="literal">v</tt>; see
Random Access Sequence.

<tt class="literal">back<v>::type</tt>
The last element in <tt class="literal">v</tt>; see
Random Access Sequence.

<tt class="literal">at<v,n>::type</tt>
The <tt class="literal">n</tt>th element from the beginning of <tt class="literal">v</tt>; see
Random Access Sequence.

<tt class="literal">insert<v,pos,x>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
[<tt class="literal">begin<v>::type</tt>, <tt class="literal">pos</tt>), <tt class="literal">x</tt>,
[<tt class="literal">pos</tt>, <tt class="literal">end<v>::type</tt>); see Extensible Sequence.

<tt class="literal">insert_range<v,pos,r>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
[<tt class="literal">begin<v>::type</tt>, <tt class="literal">pos</tt>),
[<tt class="literal">begin<r>::type</tt>, <tt class="literal">end<r>::type</tt>)
[<tt class="literal">pos</tt>, <tt class="literal">end<v>::type</tt>); see Extensible Sequence.

<tt class="literal">erase<v,pos>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
[<tt class="literal">begin<v>::type</tt>, <tt class="literal">pos</tt>),
[<tt class="literal">next<pos>::type</tt>, <tt class="literal">end<v>::type</tt>); see
Extensible Sequence.

<tt class="literal">erase<v,pos,last>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
[<tt class="literal">begin<v>::type</tt>, <tt class="literal">pos</tt>),
[<tt class="literal">last</tt>, <tt class="literal">end<v>::type</tt>); see Extensible Sequence.

<tt class="literal">clear<v>::type</tt>
An empty <tt class="literal">vector</tt>; see Extensible Sequence.

<tt class="literal">push_back<v,x>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
[<tt class="literal">begin<v>::type</tt>, <tt class="literal">end<v>::type</tt>), <tt class="literal">x</tt>;
see Back Extensible Sequence.

<tt class="literal">pop_back<v>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
[<tt class="literal">begin<v>::type</tt>, <tt class="literal">prior< end<v>::type >::type</tt>);
see Back Extensible Sequence.

<tt class="literal">push_front<v,x>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
<tt class="literal">x</tt>, [<tt class="literal">begin<v>::type</tt>, <tt class="literal">end<v>::type</tt>); see Front Extensible Sequence.

<tt class="literal">pop_front<v>::type</tt>
A new <tt class="literal">vector</tt> of following elements:
[<tt class="literal">next< begin<v>::type >::type</tt>, <tt class="literal">end<v>::type</tt>);
see Front Extensible Sequence.

Example

typedef vector<float,double,long double> floats;
typedef push_back<floats,int>::type types;

BOOST_MPL_ASSERT(( is_same< at_c<types,3>::type, int > ));

See also

Sequences, Variadic Sequence, Random Access Sequence, Extensible Sequence, vector_c, list

Prev Next | Back Along | Up Home | Full TOC

Copyright ©  2001-2009 Aleksey Gurtovoy and David Abrahams

Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)