text:
package com.squareup.spoon;

import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.ddmlib.testrunner.TestIdentifier;
import java.util.HashMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.squareup.spoon.SpoonLogger.logDebug;
import static com.squareup.spoon.SpoonLogger.logError;

/** Marshals an {@link ITestRunListener}'s output to a {@link DeviceResult.Builder}. */
final class SpoonTestRunListener implements ITestRunListener {
  private final DeviceResult.Builder result;
  private final Map<TestIdentifier, DeviceTestResult.Builder> methodResults = new HashMap<>();
  private final boolean debug;

  SpoonTestRunListener(DeviceResult.Builder result, boolean debug) {
    checkNotNull(result);
    this.result = result;
    this.debug = debug;
  }

  @Override public void testRunStarted(String runName, int testCount) {
    logDebug(debug, "testCount=%d runName=%s", testCount, runName);
    result.startTests();
  }

  @Override public void testStarted(TestIdentifier test) {
    logDebug(debug, "test=%s", test);
    DeviceTestResult.Builder methodResult = new DeviceTestResult.Builder().startTest();
    methodResults.put(test, methodResult);
  }

  @Override public void testFailed(TestIdentifier test, String trace) {
    logDebug(debug, "test=%s", test);
    DeviceTestResult.Builder methodResult = methodResults.get(test);
    if (methodResult == null) {
      logError("unknown test=%s", test);
      methodResult = new DeviceTestResult.Builder();
      methodResults.put(test, methodResult);
    }
    logDebug(debug, "failed %s", trace);
    methodResult.markTestAsFailed(trace);
  }

  @Override public void testAssumptionFailure(TestIdentifier test, String trace) {
    // TODO Add assumption failures to the report.
    logDebug(debug, "test=%s", test);
    logDebug(debug, "assumption failure %s", trace);
  }

  @Override public void testIgnored(TestIdentifier test) {
    // TODO Add ignored tests to the report.
    logDebug(debug, "ignored test %s", test);
  }

  @Override public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
    logDebug(debug, "test=%s", test);
    DeviceTestResult.Builder methodResult = methodResults.get(test);
    if (methodResult == null) {
      logError("unknown test=%s", test);
      methodResult = new DeviceTestResult.Builder().startTest();
      methodResults.put(test, methodResult);
    }
    DeviceTestResult.Builder methodResultBuilder = methodResult.endTest();
    result.addTestResultBuilder(DeviceTest.from(test), methodResultBuilder);
  }

  @Override public void testRunFailed(String errorMessage) {
    logDebug(debug, "errorMessage=%s", errorMessage);
    result.addException(errorMessage);
  }

  @Override public void testRunStopped(long elapsedTime) {
    logDebug(debug, "elapsedTime=%d", elapsedTime);
  }

  @Override public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {
    logDebug(debug, "elapsedTime=%d", elapsedTime);
    result.endTests();
  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.inspector.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.inspector.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AgentFilterMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AgentFilterMarshaller {

    private static final MarshallingInfo<List> AGENTHEALTHS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("agentHealths").build();
    private static final MarshallingInfo<List> AGENTHEALTHCODES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("agentHealthCodes").build();

    private static final AgentFilterMarshaller instance = new AgentFilterMarshaller();

    public static AgentFilterMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AgentFilter agentFilter, ProtocolMarshaller protocolMarshaller) {

        if (agentFilter == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(agentFilter.getAgentHealths(), AGENTHEALTHS_BINDING);
            protocolMarshaller.marshall(agentFilter.getAgentHealthCodes(), AGENTHEALTHCODES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
{-
(c) The AQUA Project, Glasgow University, 1993-1998

\section[SimplMonad]{The simplifier Monad}
-}

{-# LANGUAGE CPP #-}

module SimplEnv (
        InId, InBind, InExpr, InAlt, InArg, InType, InBndr, InVar,
        OutId, OutTyVar, OutBind, OutExpr, OutAlt, OutArg, OutType, OutBndr, OutVar,
        InCoercion, OutCoercion,

        -- The simplifier mode
        setMode, getMode, updMode,

        -- Environments
        SimplEnv(..), StaticEnv, pprSimplEnv,   -- Temp not abstract
        mkSimplEnv, extendIdSubst, SimplEnv.extendTvSubst, SimplEnv.extendCvSubst,
        zapSubstEnv, setSubstEnv,
        getInScope, setInScope, setInScopeSet, modifyInScope, addNewInScopeIds,
        getSimplRules,

        SimplSR(..), mkContEx, substId, lookupRecBndr, refineFromInScope,

        simplNonRecBndr, simplRecBndrs,
        simplBinder, simplBinders,
        substTy, substTyVar, getTvSubst,
        getCvSubst, substCo, substCoVar,

        -- Floats
        Floats, emptyFloats, isEmptyFloats, addNonRec, addFloats, extendFloats,
        wrapFloats, setFloats, zapFloats, addRecFloats, mapFloats,
        doFloatFromRhs, getFloatBinds
    ) where

#include "HsVersions.h"

import SimplMonad
import CoreMonad        ( SimplifierMode(..) )
import CoreSyn
import CoreUtils
import Var
import VarEnv
import VarSet
import OrdList
import Id
import MkCore                   ( mkWildValBinder )
import TysWiredIn
import qualified Type
import Type hiding              ( substTy, substTyVarBndr, substTyVar )
import qualified Coercion
import Coercion hiding          ( substCo, substTy, substCoVar, substCoVarBndr, substTyVarBndr )
import BasicTypes
import MonadUtils
import Outputable
import FastString
import Util

import Data.List

{-
************************************************************************
*                                                                      *
\subsection[Simplify-types]{Type declarations}
*                                                                      *
************************************************************************
-}

type InBndr     = CoreBndr
type InVar      = Var                   -- Not yet cloned
type InId       = Id                    -- Not yet cloned
type InType     = Type                  -- Ditto
type InBind     = CoreBind
type InExpr     = CoreExpr
type InAlt      = CoreAlt
type InArg      = CoreArg
type InCoercion = Coercion

type OutBndr     = CoreBndr
type OutVar      = Var                  -- Cloned
type OutId       = Id                   -- Cloned
type OutTyVar    = TyVar                -- Cloned
type OutType     = Type                 -- Cloned
type OutCoercion = Coercion
type OutBind     = CoreBind
type OutExpr     = CoreExpr
type OutAlt      = CoreAlt
type OutArg      = CoreArg

{-
************************************************************************
*                                                                      *
\subsubsection{The @SimplEnv@ type}
*                                                                      *
************************************************************************
-}

data SimplEnv
  = SimplEnv {
     ----------- Static part of the environment -----------
     -- Static in the sense of lexically scoped,
     -- wrt the original expression

        seMode      :: SimplifierMode,

        -- The current substitution
        seTvSubst   :: TvSubstEnv,      -- InTyVar |--> OutType
        seCvSubst   :: CvSubstEnv,      -- InCoVar |--> OutCoercion
        seIdSubst   :: SimplIdSubst,    -- InId    |--> OutExpr

     ----------- Dynamic part of the environment -----------
     -- Dynamic in the sense of describing the setup where
     -- the expression finally ends up

        -- The current set of in-scope variables
        -- They are all OutVars, and all bound in this module
        seInScope   :: InScopeSet,      -- OutVars only
                -- Includes all variables bound by seFloats
        seFloats    :: Floats
                -- See Note [Simplifier floats]
    }

type StaticEnv = SimplEnv       -- Just the static part is relevant

pprSimplEnv :: SimplEnv -> SDoc
-- Used for debugging; selective
pprSimplEnv env
  = vcat [ptext (sLit "TvSubst:") <+> ppr (seTvSubst env),
          ptext (sLit "IdSubst:") <+> ppr (seIdSubst env),
          ptext (sLit "InScope:") <+> vcat (map ppr_one in_scope_vars)
    ]
  where
   in_scope_vars = varEnvElts (getInScopeVars (seInScope env))
   ppr_one v | isId v = ppr v <+> ppr (idUnfolding v)
             | otherwise = ppr v

type SimplIdSubst = IdEnv SimplSR       -- IdId |--> OutExpr
        -- See Note [Extending the Subst] in CoreSubst

data SimplSR
  = DoneEx OutExpr              -- Completed term
  | DoneId OutId                -- Completed term variable
  | ContEx TvSubstEnv           -- A suspended substitution
           CvSubstEnv
           SimplIdSubst
           InExpr

instance Outputable SimplSR where
  ppr (DoneEx e) = ptext (sLit "DoneEx") <+> ppr e
  ppr (DoneId v) = ptext (sLit "DoneId") <+> ppr v
  ppr (ContEx _tv _cv _id e) = vcat [ptext (sLit "ContEx") <+> ppr e {-,
                                ppr (filter_env tv), ppr (filter_env id) -}]
        -- where
        -- fvs = exprFreeVars e
        -- filter_env env = filterVarEnv_Directly keep env
        -- keep uniq _ = uniq `elemUFM_Directly` fvs

{-
Note [SimplEnv invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~~
seInScope:
        The in-scope part of Subst includes *all* in-scope TyVars and Ids
        The elements of the set may have better IdInfo than the
        occurrences of in-scope Ids, and (more important) they will
        have a correctly-substituted type.  So we use a lookup in this
        set to replace occurrences

        The Ids in the InScopeSet are replete with their Rules,
        and as we gather info about the unfolding of an Id, we replace
        it in the in-scope set.

        The in-scope set is actually a mapping OutVar -> OutVar, and
        in case expressions we sometimes bind

seIdSubst:
        The substitution is *apply-once* only, because InIds and OutIds
        can overlap.
        For example, we generally omit mappings
                a77 -> a77
        from the substitution, when we decide not to clone a77, but it's quite
        legitimate to put the mapping in the substitution anyway.

        Furthermore, consider
                let x = case k of I# x77 -> ... in
                let y = case k of I# x77 -> ... in ...
        and suppose the body is strict in both x and y.  Then the simplifier
        will pull the first (case k) to the top; so the second (case k) will
        cancel out, mapping x77 to, well, x77!  But one is an in-Id and the
        other is an out-Id.

        Of course, the substitution *must* applied! Things in its domain
        simply aren't necessarily bound in the result.

* substId adds a binding (DoneId new_id) to the substitution if
        the Id's unique has changed

  Note, though that the substitution isn't necessarily extended
  if the type of the Id changes.  Why not?  Because of the next point:

* We *always, always* finish by looking up in the in-scope set
  any variable that doesn't get a DoneEx or DoneVar hit in the substitution.
  Reason: so that we never finish up with a "old" Id in the result.
  An old Id might point to an old unfolding and so on... which gives a space
  leak.

  [The DoneEx and DoneVar hits map to "new" stuff.]

* It follows that substExpr must not do a no-op if the substitution is empty.
  substType is free to do so, however.

* When we come to a let-binding (say) we generate new IdInfo, including an
  unfolding, attach it to the binder, and add this newly adorned binder to
  the in-scope set.  So all subsequent occurrences of the binder will get
  mapped to the full-adorned binder, which is also the one put in the
  binding site.

* The in-scope "set" usually maps x->x; we use it simply for its domain.
  But sometimes we have two in-scope Ids that are synomyms, and should
  map to the same target:  x->x, y->x.  Notably:
        case y of x { ... }
  That's why the "set" is actually a VarEnv Var
-}

mkSimplEnv :: SimplifierMode -> SimplEnv
mkSimplEnv mode
  = SimplEnv { seMode = mode
             , seInScope = init_in_scope
             , seFloats = emptyFloats
             , seTvSubst = emptyVarEnv
             , seCvSubst = emptyVarEnv
             , seIdSubst = emptyVarEnv }
        -- The top level "enclosing CC" is "SUBSUMED".

init_in_scope :: InScopeSet
init_in_scope = mkInScopeSet (unitVarSet (mkWildValBinder unitTy))
              -- See Note [WildCard binders]

{-
Note [WildCard binders]
~~~~~~~~~~~~~~~~~~~~~~~
The program to be simplified may have wild binders
    case e of wild { p -> ... }
We want to *rename* them away, so that there are no
occurrences of 'wild-id' (with wildCardKey).  The easy
way to do that is to start of with a representative
Id in the in-scope set

There can be be *occurrences* of wild-id.  For example,
MkCore.mkCoreApp transforms
   e (a /# b)   -->   case (a /# b) of wild { DEFAULT -> e wild }
This is ok provided 'wild' isn't free in 'e', and that's the delicate
thing. Generally, you want to run the simplifier to get rid of the
wild-ids before doing much else.

It's a very dark corner of GHC.  Maybe it should be cleaned up.
-}

getMode :: SimplEnv -> SimplifierMode
getMode env = seMode env

setMode :: SimplifierMode -> SimplEnv -> SimplEnv
setMode mode env = env { seMode = mode }

updMode :: (SimplifierMode -> SimplifierMode) -> SimplEnv -> SimplEnv
updMode upd env = env { seMode = upd (seMode env) }

---------------------
extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
  = ASSERT2( isId var && not (isCoVar var), ppr var )
    env {seIdSubst = extendVarEnv subst var res}

extendTvSubst :: SimplEnv -> TyVar -> Type -> SimplEnv
extendTvSubst env@(SimplEnv {seTvSubst = subst}) var res
  = env {seTvSubst = extendVarEnv subst var res}

extendCvSubst :: SimplEnv -> CoVar -> Coercion -> SimplEnv
extendCvSubst env@(SimplEnv {seCvSubst = subst}) var res
  = env {seCvSubst = extendVarEnv subst var res}

---------------------
getInScope :: SimplEnv -> InScopeSet
getInScope env = seInScope env

setInScopeSet :: SimplEnv -> InScopeSet -> SimplEnv
setInScopeSet env in_scope = env {seInScope = in_scope}

setInScope :: SimplEnv -> SimplEnv -> SimplEnv
-- Set the in-scope set, and *zap* the floats
setInScope env env_with_scope
  = env { seInScope = seInScope env_with_scope,
          seFloats = emptyFloats }

setFloats :: SimplEnv -> SimplEnv -> SimplEnv
-- Set the in-scope set *and* the floats
setFloats env env_with_floats
  = env { seInScope = seInScope env_with_floats,
          seFloats  = seFloats  env_with_floats }

addNewInScopeIds :: SimplEnv -> [CoreBndr] -> SimplEnv
        -- The new Ids are guaranteed to be freshly allocated
addNewInScopeIds env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst }) vs
  = env { seInScope = in_scope `extendInScopeSetList` vs,
          seIdSubst = id_subst `delVarEnvList` vs }
        -- Why delete?  Consider
        --      let x = a*b in (x, \x -> x+3)
        -- We add [x |-> a*b] to the substitution, but we must
        -- _delete_ it from the substitution when going inside
        -- the (\x -> ...)!

modifyInScope :: SimplEnv -> CoreBndr -> SimplEnv
-- The variable should already be in scope, but
-- replace the existing version with this new one
-- which has more information
modifyInScope env@(SimplEnv {seInScope = in_scope}) v
  = env {seInScope = extendInScopeSet in_scope v}

---------------------
zapSubstEnv :: SimplEnv -> SimplEnv
zapSubstEnv env = env {seTvSubst = emptyVarEnv, seCvSubst = emptyVarEnv, seIdSubst = emptyVarEnv}

setSubstEnv :: SimplEnv -> TvSubstEnv -> CvSubstEnv -> SimplIdSubst -> SimplEnv
setSubstEnv env tvs cvs ids = env { seTvSubst = tvs, seCvSubst = cvs, seIdSubst = ids }

mkContEx :: SimplEnv -> InExpr -> SimplSR
mkContEx (SimplEnv { seTvSubst = tvs, seCvSubst = cvs, seIdSubst = ids }) e = ContEx tvs cvs ids e

{-
************************************************************************
*                                                                      *
\subsection{Floats}
*                                                                      *
************************************************************************

Note [Simplifier floats]
~~~~~~~~~~~~~~~~~~~~~~~~~
The Floats is a bunch of bindings, classified by a FloatFlag.

* All of them satisfy the let/app invariant

Examples

  NonRec x (y:ys)       FltLifted
  Rec [(x,rhs)]         FltLifted

  NonRec x* (p:q)       FltOKSpec   -- RHS is WHNF.  Question: why not FltLifted?
  NonRec x# (y +# 3)    FltOkSpec   -- Unboxed, but ok-for-spec'n

  NonRec x* (f y)       FltCareful  -- Strict binding; might fail or diverge

Can't happen:
  NonRec x# (a /# b)    -- Might fail; does not satisfy let/app
  NonRec x# (f y)       -- Might diverge; does not satisfy let/app
-}

data Floats = Floats (OrdList OutBind) FloatFlag
        -- See Note [Simplifier floats]

data FloatFlag
  = FltLifted   -- All bindings are lifted and lazy
                --  Hence ok to float to top level, or recursive

  | FltOkSpec   -- All bindings are FltLifted *or*
                --      strict (perhaps because unlifted,
                --      perhaps because of a strict binder),
                --        *and* ok-for-speculation
                --  Hence ok to float out of the RHS
                --  of a lazy non-recursive let binding
                --  (but not to top level, or into a rec group)

  | FltCareful  -- At least one binding is strict (or unlifted)
                --      and not guaranteed cheap
                --      Do not float these bindings out of a lazy let

instance Outputable Floats where
  ppr (Floats binds ff) = ppr ff $$ ppr (fromOL binds)

instance Outputable FloatFlag where
  ppr FltLifted = ptext (sLit "FltLifted")
  ppr FltOkSpec = ptext (sLit "FltOkSpec")
  ppr FltCareful = ptext (sLit "FltCareful")

andFF :: FloatFlag -> FloatFlag -> FloatFlag
andFF FltCareful _          = FltCareful
andFF FltOkSpec  FltCareful = FltCareful
andFF FltOkSpec  _          = FltOkSpec
andFF FltLifted  flt        = flt

doFloatFromRhs :: TopLevelFlag -> RecFlag -> Bool -> OutExpr -> SimplEnv -> Bool
-- If you change this function look also at FloatIn.noFloatFromRhs
doFloatFromRhs lvl rec str rhs (SimplEnv {seFloats = Floats fs ff})
  =  not (isNilOL fs) && want_to_float && can_float
  where
     want_to_float = isTopLevel lvl || exprIsCheap rhs || exprIsExpandable rhs
                     -- See Note [Float when cheap or expandable]
     can_float = case ff of
                   FltLifted  -> True
                   FltOkSpec  -> isNotTopLevel lvl && isNonRec rec
                   FltCareful -> isNotTopLevel lvl && isNonRec rec && str

{-
Note [Float when cheap or expandable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We want to float a let from a let if the residual RHS is
   a) cheap, such as (\x. blah)
   b) expandable, such as (f b) if f is CONLIKE
But there are
  - cheap things that are not expandable (eg \x. expensive)
  - expandable things that are not cheap (eg (f b) where b is CONLIKE)
so we must take the 'or' of the two.
-}

emptyFloats :: Floats
emptyFloats = Floats nilOL FltLifted

unitFloat :: OutBind -> Floats
-- This key function constructs a singleton float with the right form
unitFloat bind = Floats (unitOL bind) (flag bind)
  where
    flag (Rec {})                = FltLifted
    flag (NonRec bndr rhs)
      | not (isStrictId bndr)    = FltLifted
      | exprOkForSpeculation rhs = FltOkSpec  -- Unlifted, and lifted but ok-for-spec (eg HNF)
      | otherwise                = ASSERT2( not (isUnLiftedType (idType bndr)), ppr bndr )
                                   FltCareful
      -- Unlifted binders can only be let-bound if exprOkForSpeculation holds

addNonRec :: SimplEnv -> OutId -> OutExpr -> SimplEnv
-- Add a non-recursive binding and extend the in-scope set
-- The latter is important; the binder may already be in the
-- in-scope set (although it might also have been created with newId)
-- but it may now have more IdInfo
addNonRec env id rhs
  = id `seq`   -- This seq forces the Id, and hence its IdInfo,
               -- and hence any inner substitutions
    env { seFloats = seFloats env `addFlts` unitFloat (NonRec id rhs),
          seInScope = extendInScopeSet (seInScope env) id }

extendFloats :: SimplEnv -> OutBind -> SimplEnv
-- Add these bindings to the floats, and extend the in-scope env too
extendFloats env bind
  = env { seFloats  = seFloats env `addFlts` unitFloat bind,
          seInScope = extendInScopeSetList (seInScope env) bndrs }
  where
    bndrs = bindersOf bind

addFloats :: SimplEnv -> SimplEnv -> SimplEnv
-- Add the floats for env2 to env1;
-- *plus* the in-scope set for env2, which is bigger
-- than that for env1
addFloats env1 env2
  = env1 {seFloats = seFloats env1 `addFlts` seFloats env2,
          seInScope = seInScope env2 }

addFlts :: Floats -> Floats -> Floats
addFlts (Floats bs1 l1) (Floats bs2 l2)
  = Floats (bs1 `appOL` bs2) (l1 `andFF` l2)

zapFloats :: SimplEnv -> SimplEnv
zapFloats env = env { seFloats = emptyFloats }

addRecFloats :: SimplEnv -> SimplEnv -> SimplEnv
-- Flattens the floats from env2 into a single Rec group,
-- prepends the floats from env1, and puts the result back in env2
-- This is all very specific to the way recursive bindings are
-- handled; see Simplify.simplRecBind
addRecFloats env1 env2@(SimplEnv {seFloats = Floats bs ff})
  = ASSERT2( case ff of { FltLifted -> True; _ -> False }, ppr (fromOL bs) )
    env2 {seFloats = seFloats env1 `addFlts` unitFloat (Rec (flattenBinds (fromOL bs)))}

wrapFloats :: SimplEnv -> OutExpr -> OutExpr
-- Wrap the floats around the expression; they should all
-- satisfy the let/app invariant, so mkLets should do the job just fine
wrapFloats (SimplEnv {seFloats = Floats bs _}) body
  = foldrOL Let body bs

getFloatBinds :: SimplEnv -> [CoreBind]
getFloatBinds (SimplEnv {seFloats = Floats bs _})
  = fromOL bs

isEmptyFloats :: SimplEnv -> Bool
isEmptyFloats (SimplEnv {seFloats = Floats bs _})
  = isNilOL bs

mapFloats :: SimplEnv -> ((Id,CoreExpr) -> (Id,CoreExpr)) -> SimplEnv
mapFloats env@SimplEnv { seFloats = Floats fs ff } fun
   = env { seFloats = Floats (mapOL app fs) ff }
   where
    app (NonRec b e) = case fun (b,e) of (b',e') -> NonRec b' e'
    app (Rec bs)     = Rec (map fun bs)

{-
************************************************************************
*                                                                      *
                Substitution of Vars
*                                                                      *
************************************************************************

Note [Global Ids in the substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We look up even a global (eg imported) Id in the substitution. Consider
   case X.g_34 of b { (a,b) ->  ... case X.g_34 of { (p,q) -> ...} ... }
The binder-swap in the occurrence analyser will add a binding
for a LocalId version of g (with the same unique though):
   case X.g_34 of b { (a,b) ->  let g_34 = b in
                                ... case X.g_34 of { (p,q) -> ...} ... }
So we want to look up the inner X.g_34 in the substitution, where we'll
find that it has been substituted by b.  (Or conceivably cloned.)
-}

substId :: SimplEnv -> InId -> SimplSR
-- Returns DoneEx only on a non-Var expression
substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
  = case lookupVarEnv ids v of  -- Note [Global Ids in the substitution]
        Nothing               -> DoneId (refineFromInScope in_scope v)
        Just (DoneId v)       -> DoneId (refineFromInScope in_scope v)
        Just (DoneEx (Var v)) -> DoneId (refineFromInScope in_scope v)
        Just res              -> res    -- DoneEx non-var, or ContEx

        -- Get the most up-to-date thing from the in-scope set
        -- Even though it isn't in the substitution, it may be in
        -- the in-scope set with better IdInfo
refineFromInScope :: InScopeSet -> Var -> Var
refineFromInScope in_scope v
  | isLocalId v = case lookupInScope in_scope v of
                  Just v' -> v'
                  Nothing -> WARN( True, ppr v ) v  -- This is an error!
  | otherwise = v

lookupRecBndr :: SimplEnv -> InId -> OutId
-- Look up an Id which has been put into the envt by simplRecBndrs,
-- but where we have not yet done its RHS
lookupRecBndr (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
  = case lookupVarEnv ids v of
        Just (DoneId v) -> v
        Just _ -> pprPanic "lookupRecBndr" (ppr v)
        Nothing -> refineFromInScope in_scope v

{-
************************************************************************
*                                                                      *
\section{Substituting an Id binder}
*                                                                      *
************************************************************************

These functions are in the monad only so that they can be made strict via seq.
-}

simplBinders :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
simplBinders  env bndrs = mapAccumLM simplBinder  env bndrs

-------------
simplBinder :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
-- Used for lambda and case-bound variables
-- Clone Id if necessary, substitute type
-- Return with IdInfo already substituted, but (fragile) occurrence info zapped
-- The substitution is extended only if the variable is cloned, because
-- we *don't* need to use it to track occurrence info.
simplBinder env bndr
  | isTyVar bndr  = do  { let (env', tv) = substTyVarBndr env bndr
                        ; seqTyVar tv `seq` return (env', tv) }
  | otherwise     = do  { let (env', id) = substIdBndr env bndr
                        ; seqId id `seq` return (env', id) }

---------------
simplNonRecBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
-- A non-recursive let binder
simplNonRecBndr env id
  = do  { let (env1, id1) = substIdBndr env id
        ; seqId id1 `seq` return (env1, id1) }

---------------
simplRecBndrs :: SimplEnv -> [InBndr] -> SimplM SimplEnv
-- Recursive let binders
simplRecBndrs env@(SimplEnv {}) ids
  = do  { let (env1, ids1) = mapAccumL substIdBndr env ids
        ; seqIds ids1 `seq` return env1 }

---------------
substIdBndr :: SimplEnv -> InBndr -> (SimplEnv, OutBndr)
-- Might be a coercion variable
substIdBndr env bndr
  | isCoVar bndr  = substCoVarBndr env bndr
  | otherwise     = substNonCoVarIdBndr env bndr

---------------
substNonCoVarIdBndr
   :: SimplEnv
   -> InBndr    -- Env and binder to transform
   -> (SimplEnv, OutBndr)
-- Clone Id if necessary, substitute its type
-- Return an Id with its
--      * Type substituted
--      * UnfoldingInfo, Rules, WorkerInfo zapped
--      * Fragile OccInfo (only) zapped: Note [Robust OccInfo]
--      * Robust info, retained especially arity and demand info,
--         so that they are available to occurrences that occur in an
--         earlier binding of a letrec
--
-- For the robust info, see Note [Arity robustness]
--
-- Augment the substitution  if the unique changed
-- Extend the in-scope set with the new Id
--
-- Similar to CoreSubst.substIdBndr, except that
--      the type of id_subst differs
--      all fragile info is zapped
substNonCoVarIdBndr env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst })
                    old_id
  = ASSERT2( not (isCoVar old_id), ppr old_id )
    (env { seInScope = in_scope `extendInScopeSet` new_id,
           seIdSubst = new_subst }, new_id)
  where
    id1    = uniqAway in_scope old_id
    id2    = substIdType env id1
    new_id = zapFragileIdInfo id2       -- Zaps rules, worker-info, unfolding
                                        -- and fragile OccInfo

        -- Extend the substitution if the unique has changed,
        -- or there's some useful occurrence information
        -- See the notes with substTyVarBndr for the delSubstEnv
    new_subst | new_id /= old_id
              = extendVarEnv id_subst old_id (DoneId new_id)
              | otherwise
              = delVarEnv id_subst old_id

------------------------------------
seqTyVar :: TyVar -> ()
seqTyVar b = b `seq` ()

seqId :: Id -> ()
seqId id = seqType (idType id)  `seq`
           idInfo id            `seq`
           ()

seqIds :: [Id] -> ()
seqIds []       = ()
seqIds (id:ids) = seqId id `seq` seqIds ids

{-
Note [Arity robustness]
~~~~~~~~~~~~~~~~~~~~~~~
We *do* transfer the arity from from the in_id of a let binding to the
out_id.  This is important, so that the arity of an Id is visible in
its own RHS.  For example:
        f = \x. ....g (\y. f y)....
We can eta-reduce the arg to g, because f is a value.  But that
needs to be visible.

This interacts with the 'state hack' too:
        f :: Bool -> IO Int
        f = \x. case x of
                  True  -> f y
                  False -> \s -> ...
Can we eta-expand f?  Only if we see that f has arity 1, and then we
take advantage of the 'state hack' on the result of
(f y) :: State# -> (State#, Int) to expand the arity one more.

There is a disadvantage though.  Making the arity visible in the RHS
allows us to eta-reduce
        f = \x -> f x
to
        f = f
which technically is not sound.   This is very much a corner case, so
I'm not worried about it.  Another idea is to ensure that f's arity
never decreases; its arity started as 1, and we should never eta-reduce
below that.

Note [Robust OccInfo]
~~~~~~~~~~~~~~~~~~~~~
It's important that we *do* retain the loop-breaker OccInfo, because
that's what stops the Id getting inlined infinitely, in the body of
the letrec.
-}

{-
************************************************************************
*                                                                      *
                Impedence matching to type substitution
*                                                                      *
************************************************************************
-}

getTvSubst :: SimplEnv -> TvSubst
getTvSubst (SimplEnv { seInScope = in_scope, seTvSubst = tv_env })
  = mkTvSubst in_scope tv_env

getCvSubst :: SimplEnv -> CvSubst
getCvSubst (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seCvSubst = cv_env })
  = CvSubst in_scope tv_env cv_env

substTy :: SimplEnv -> Type -> Type
substTy env ty = Type.substTy (getTvSubst env) ty

substTyVar :: SimplEnv -> TyVar -> Type
substTyVar env tv = Type.substTyVar (getTvSubst env) tv

substTyVarBndr :: SimplEnv -> TyVar -> (SimplEnv, TyVar)
substTyVarBndr env tv
  = case Type.substTyVarBndr (getTvSubst env) tv of
        (TvSubst in_scope' tv_env', tv')
           -> (env { seInScope = in_scope', seTvSubst = tv_env' }, tv')

substCoVar :: SimplEnv -> CoVar -> Coercion
substCoVar env tv = Coercion.substCoVar (getCvSubst env) tv

substCoVarBndr :: SimplEnv -> CoVar -> (SimplEnv, CoVar)
substCoVarBndr env cv
  = case Coercion.substCoVarBndr (getCvSubst env) cv of
        (CvSubst in_scope' tv_env' cv_env', cv')
           -> (env { seInScope = in_scope', seTvSubst = tv_env', seCvSubst = cv_env' }, cv')

substCo :: SimplEnv -> Coercion -> Coercion
substCo env co = Coercion.substCo (getCvSubst env) co

------------------
substIdType :: SimplEnv -> Id -> Id
substIdType (SimplEnv { seInScope = in_scope,  seTvSubst = tv_env }) id
  | isEmptyVarEnv tv_env || isEmptyVarSet (tyVarsOfType old_ty) = id
  | otherwise = Id.setIdType id (Type.substTy (TvSubst in_scope tv_env) old_ty)
                -- The tyVarsOfType is cheaper than it looks
                -- because we cache the free tyvars of the type
                -- in a Note in the id's type itself
  where
    old_ty = idType id


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>just-box</title>


text:
"""
airPy is a flight controller based on pyboard and written in micropython.

The MIT License (MIT)
Copyright (c) 2016 Fabrizio Scimia, fabrizio.scimia@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

class ConfigFileGenerator:

    @classmethod
    def get_default_config_file(self):
        return {
            "num_motors": 4,
            "attitude": {
                'max_increment': 50,
                'max_gyro_increment': 50,
                'max_pitch': 45,
                'max_roll': 45,
                'max_yaw': 180,
                'stab_Kp': 1,
                'stab_Kd': 0,
                'stab_Ki': 0,
                'gyro_Kp': 1,
                'gyro_Kd': 0,
                'gyro_Ki': 0,
                'pitch_offset': -0.1,
                'roll_offset': -0.75,
                'pitch_rate_offset': 0.2,
                'roll_rate_offset': 1.75
            },
            "rcRadio": {
                'type': 'sbus',
                'calibrationStatus': False,
                "num_channels": 4,
                'channels_default_center': [1024, 1024, 1024, 1024],
                'channels_default_min': [0, 0, 0, 0],
                'channels_default_max': [2047, 2047, 2047, 2047]
            },
            "esc": {
                "esc_pwm_min_cmd": 1000,
                "esc_pwm_center": 1500,
                "esc_pwm_min": 1150,
                "esc_pwm_max": 2000,
                "quadcopter": {
                  "pins": ["X1", "X2", "X3", "X4"],
                  "timers": [5, 5, 5, 5],
                  "channels": [1, 2, 3, 4]
                }
            }
        }


text:
// Copyright (c) 2015 Ionel Gog <ionel.gog@cl.cam.ac.uk>

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
 * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
 * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 */

#define DYNAMICEDATA 1

#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/time.h>

#include "graphchi_basic_includes.hpp"
#include "api/dynamicdata/chivector.hpp"
#include "util/toplist.hpp"

using namespace graphchi;
using namespace std;

typedef {{VERTEX_DATA_TYPE}} VertexDataType;
typedef chivector<{{EDGE_DATA_TYPE}}> EdgeDataType;

struct {{CLASS_NAME}} : public GraphChiProgram<VertexDataType, EdgeDataType> {
  void before_iteration(int iteration, graphchi_context &ginfo) {
  }

  void after_iteration(int iteration, graphchi_context &ginfo) {
  }

  void before_exec_interval(vid_t window_st, vid_t window_en,
                            graphchi_context &ginfo) {
  }

  void update(graphchi_vertex<VertexDataType, EdgeDataType> &v,
              graphchi_context &ginfo) {
    if (ginfo.iteration == 0) {
      VertexDataType ver_val = v.get_data();
      // On the first iteration add the values to the edges.
      {{EDGE_DATA_TYPE}} n_out_edges = v.num_outedges();
      for (int i = 0; i < v.num_outedges(); i++) {
        EdgeDataType* out_edge_vector = v.outedge(i)->get_vector();
        {{ADD_NUM_OUT_EDGES}}
        out_edge_vector->add(ver_val);
      }
    } else {
      VertexDataType ver_val = {{INIT_VER_VAL}};
      {{EDGE_DATA_TYPE}} e_cost = 0;
      {{EDGE_DATA_TYPE}} in_edge_val = 0;
      for (int i = 0; i < v.num_inedges(); i++) {
        EdgeDataType* in_edge_vector = v.inedge(i)->get_vector();
        {{PRE_GROUP_VERTEX_VAL}}
        {{GROUP_VERTEX_VAL}}
      }
      {{POST_GROUP_VERTEX_VAL}}

      for (int i = 0; i < v.num_outedges(); i++) {
        EdgeDataType* out_edge_vector = v.outedge(i)->get_vector();
        if (out_edge_vector->size() == 1) {
          out_edge_vector->set(0, ver_val);
        } else {
          // This doesn't support dynamic values for the edges.
          out_edge_vector->set(1, ver_val);
        }
      }
      v.set_data(ver_val);
    }
  }
};

class OutputVertexCallback : public VCallback<VertexDataType> {
public:
  OutputVertexCallback(): VCallback<VertexDataType>(),
                          outfile("/tmp{{EDGES_PATH}}output") {
  }

  ~OutputVertexCallback() {
    outfile.close();
  }

  ofstream outfile;

  virtual void callback(vid_t vertex_id, VertexDataType &value) {
    outfile << vertex_id << " " << value << endl;
  }
};

int main(int argc, const char** argv) {
  graphchi_init(argc, argv);
  metrics met("{{CLASS_NAME}}");
  int niters = get_option_int("niters", {{N_ITERS}});
  string filetype = get_option_string("filetype", "multivalueedgelist");
  bool scheduler = false;
  timeval start_proc;
  gettimeofday(&start_proc, NULL);
  int num_shards = convert_if_notexists<{{EDGE_DATA_TYPE}}>(
      "/tmp{{EDGES_PATH}}input", get_option_string("nshards", "auto"));
  graphchi_engine<VertexDataType, EdgeDataType> engine(
      "/tmp{{EDGES_PATH}}input", num_shards, scheduler, met);
  timeval end_proc;
  gettimeofday(&end_proc, NULL);
  engine.set_modifies_inedges(false);
  {{CLASS_NAME}} program;
  engine.run(program, niters);
  timeval end_run;
  gettimeofday(&end_run, NULL);
  long loading_data = end_proc.tv_sec - start_proc.tv_sec;
  long run_time = end_run.tv_sec - end_proc.tv_sec;
  cout << "LOADING DATA: " << loading_data << endl;
  cout << "RUN TIME: " << run_time << endl;
  //  OutputVertexCallback output_callback;
  //  foreach_vertices<VertexDataType>("/tmp{{EDGES_PATH}}input", 0,
  //                                   engine.num_vertices(), output_callback);
  metrics_report(met);
  return 0;
}


text:
#ifndef SSP_H
#define SSP_H

/*
 * SSP initialisation flags
 */
#define SSP_NO_IRQ	0x1		/* don't register an irq handler in SSP driver */

struct ssp_state {
	u32	cr0;
	u32 cr1;
	u32 to;
	u32 psp;
};

struct ssp_dev {
	u32 port;
	u32 mode;
	u32 flags;
	u32 psp_flags;
	u32 speed;
	int irq;
};

int ssp_write_word(struct ssp_dev *dev, u32 data);
int ssp_read_word(struct ssp_dev *dev, u32 *data);
int ssp_flush(struct ssp_dev *dev);
void ssp_enable(struct ssp_dev *dev);
void ssp_disable(struct ssp_dev *dev);
void ssp_save_state(struct ssp_dev *dev, struct ssp_state *ssp);
void ssp_restore_state(struct ssp_dev *dev, struct ssp_state *ssp);
int ssp_init(struct ssp_dev *dev, u32 port, u32 init_flags);
int ssp_config(struct ssp_dev *dev, u32 mode, u32 flags, u32 psp_flags, u32 speed);
void ssp_exit(struct ssp_dev *dev);

#endif


text:
package drds

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// InstanceDb is a nested struct in drds response
type InstanceDb struct {
	InstanceName string    `json:"InstanceName" xml:"InstanceName"`
	HotDbList    HotDbList `json:"HotDbList" xml:"HotDbList"`
}


text:
package com.outbrain.ob1k.server.jetty.build;

import com.outbrain.ob1k.server.Server;
import com.outbrain.ob1k.server.jetty.JettyServer;
import com.outbrain.ob1k.server.jetty.SslContext;
import com.outbrain.swinfra.metrics.api.MetricFactory;

/**
 * Created by aronen on 9/8/14.
 *
 * a builder for a jetty based embedded server.
 */
public class ServerBuilder {

  protected String contextPath;
  protected int port;
  protected Integer securePort;
  protected SslContextBuilder sslContext;
  protected int maxThreads = 200;
  protected boolean accessLogEnabled = false;
  protected boolean compressionEnabled = true;
  protected Long httpConnectorIdleTimeout = null;
  protected String staticRootResourcesBase = null;
  protected Long requestTimeoutMillis;
  protected MetricFactory metricFactory;
  protected String applicationName;
  protected String logDirectory;
  private Integer setMaxFormSize;
  private int accessLogsRetainDays;
  private Class<?> appServerClass;

  public ServerBuilder configurationPorts(final int httpPort, final Integer securePort) {
    this.port = httpPort;
    this.securePort = securePort;

    return this;
  }

  public ServerBuilder setPort(final int port) {
    this.port = port;
    return this;
  }

  public ServerBuilder setSecurePort(final int securePort) {
    this.securePort = securePort;
    return this;
  }

  public ServerBuilder setContextPath(final String contextPath) {
    this.contextPath = contextPath;
    return this;
  }

  public ServerBuilder setMaxThreads(final int maxThreads) {
    this.maxThreads = maxThreads;
    return this;
  }

  /**
   * Sets the request hard timeout in milliseconds. Disabled by default.
   * When this is set, each request that takes longer than this timeout will get interrupted.
   *
   * @param requestTimeoutMillis request timeout in milliseconds
   */
  public ServerBuilder setRequestTimeout(final long requestTimeoutMillis) {
    this.requestTimeoutMillis = requestTimeoutMillis;
    return this;
  }

  public ServerBuilder enableAccessLog() {
    return enableAccessLog(30);
  }

  public ServerBuilder enableAccessLog(final int accessLogsRetainDays) {
    this.accessLogEnabled = true;
    this.accessLogsRetainDays = accessLogsRetainDays;
    return this;
  }

  public SslContextBuilder configureSsl(final String keyStorePath, final String keyStorePassword, final String keyManagerPassword) {
    this.sslContext = new SslContextBuilder()
        .keyStorePath(keyStorePath)
        .keyStorePassword(keyStorePassword)
        .keyManagerPassword(keyManagerPassword);
    return sslContext;
  }

  public ServerBuilder setMetricFactory(final MetricFactory metricFactory) {
    this.metricFactory = metricFactory;

    return this;
  }

  public ServerBuilder setApplicationName(final String applicationName) {
    this.applicationName = applicationName;

    return this;
  }

  public ServerBuilder setLogDirectory(final String logDirectory) {
    this.logDirectory = logDirectory;
    return this;
  }

  public ServerBuilder setMaxFormSize(final int size) {
    this.setMaxFormSize = size;
    return this;
  }

  public ServerBuilder setCompressionEnabled(final boolean enableCompression) {
    this.compressionEnabled = enableCompression;
    return this;
  }

  public ServerBuilder setAppServerClass(final Class<?> cls) {
    this.appServerClass = cls;
    return this;
  }

  public ServerBuilder setStaticRootResourceBase(final String staticResourceBase) {
    this.staticRootResourcesBase = staticResourceBase;
    return this;
  }

  public ServerBuilder setHttpConnectorIdleTimeout(final long timeout) {
    this.httpConnectorIdleTimeout = timeout;
    return this;
  }

  public Server build() {
    final String accessLogsDirectory = accessLogEnabled ? logDirectory : null;
    return new JettyServer(applicationName, port, sslContext, contextPath, maxThreads, httpConnectorIdleTimeout,
        requestTimeoutMillis, setMaxFormSize, accessLogsDirectory, accessLogsRetainDays, compressionEnabled,
        staticRootResourcesBase,appServerClass, metricFactory);
  }

  /**
   * Used to configure SSL connectors
   *
   * @author Eran Harel
   */
  public class SslContextBuilder implements SslContext {
    private String keyStorePath;
    private String keyStorePassword;
    private String keyManagerPassword;

    public SslContextBuilder keyStorePath(final String keyStorePath) {
      this.keyStorePath = keyStorePath;
      return this;
    }

    public SslContextBuilder keyStorePassword(final String keyStorePassword) {
      this.keyStorePassword = keyStorePassword;
      return this;
    }

    public SslContextBuilder keyManagerPassword(final String keyManagerPassword) {
      this.keyManagerPassword = keyManagerPassword;
      return this;
    }

    public ServerBuilder enableSsl() {
      return ServerBuilder.this;
    }

    @Override
    public int getSecurePort() {
      return securePort == null ? 0 : securePort;
    }

    public String getKeyManagerPassword() {
      return keyManagerPassword;
    }

    public String getKeyStorePassword() {
      return keyStorePassword;
    }

    public String getKeyStorePath() {
      return keyStorePath;
    }
  }

}


text:
/*eslint-env node*/
/*eslint no-console:[0]*/
/*global console*/
"use strict";

var Path = require("path");
var System = require("../system");
var Location = require("../location");

var failures = 0;

var test = {
    comment: function (message) {
        console.log(message);
    },
    assert: function (ok, message) {
        if (ok) {
            console.log("ok - " + message);
        } else {
            console.log("not ok - " + message);
            failures++;
        }
    }
};

[
    "case-sensitive",
    "comments",
    "cyclic",
    "determinism",
    "dev-dependencies",
    "exact-exports",
    "hasOwnProperty",
    "main-name",
    "main",
    "method",
    "missing",
    "module-exports",
    "monkeys",
    "nested",
    "redirects",
    "redirect-extension",
    "relative",
    "transitive",
    "translator",
    "translator-package",
    "analyzer",
    "analyzer-package",
    "introduction"
].reduce(function (prev, name) {
    return prev.then(function () {
        console.log("# " + name);
        var location = Location.fromDirectory(Path.join(__dirname, name));
        return System.load(location, {
            modules: {
                test: { exports: test }
            }
        }).then(function (system) {
            return system.import("./program");
        }).catch(function (error) {
            console.log("not ok - test terminated with error");
            console.log(error.stack);
        });
    });
}, Promise.resolve()).then(function () {
    process.exit(Math.min(failures, 255));
});


text:
package ru.stqa.pft.addressbook.appmanager;

import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 * Created by agroshev on 15.06.2016.
 */
public class NavigationHelper extends HelperBase {

    public NavigationHelper(FirefoxDriver wd) {
        super(wd);
    }

    public void gotoGroupPage() {
        click(By.linkText("groups"));
    }
}


text:
layout: page
title: Miscellaneous
navlevel: header
navtitle: Misc
position: 99
navlevel: header
---

You can view my [CTF Writeups](https://github.com/Auxy233/writeups) in Github.


text:
<?php

namespace Dunglas\ApiBundle\JsonLd;

use Dunglas\ApiBundle\Api\ResourceCollectionInterface;
use Dunglas\ApiBundle\Api\ResourceInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\RouterInterface;

/**
 * JSON-LD Context Builder.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class ContextBuilder
{
    const HYDRA_NS = 'http://www.w3.org/ns/hydra/core#';
    const RDF_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
    const RDFS_NS = 'http://www.w3.org/2000/01/rdf-schema#';
    const XML_NS = 'http://www.w3.org/2001/XMLSchema#';
    const OWL_NS = 'http://www.w3.org/2002/07/owl#';

    /**
     * @var RouterInterface
     */
    private $router;
    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;
    /**
     * @var ResourceCollectionInterface
     */
    private $resourceCollection;

    public function __construct(
        RouterInterface $router,
        EventDispatcherInterface $eventDispatcher,
        ResourceCollectionInterface $resourceCollection
    ) {
        $this->router = $router;
        $this->eventDispatcher = $eventDispatcher;
        $this->resourceCollection = $resourceCollection;
    }

    /**
     * Builds the JSON-LD context for the entrypoint.
     *
     * @return array
     */
    public function getEntrypointContext()
    {
        $context = $this->getBaseContext();

        foreach ($this->resourceCollection as $resource) {
            $resourceName = lcfirst($resource->getShortName());

            $context[$resourceName] = [
                '@id' => 'Entrypoint/'.$resourceName,
                '@type' => '@id',
            ];
        }

        return $context;
    }

    /**
     * @param ResourceInterface $resource
     * @param array             $normalizationContext
     *
     * @return array|string
     */
    public function getResourceContext(ResourceInterface $resource, array $normalizationContext)
    {
        if (isset($normalizationContext['json_ld_context_embedded'])) {
            return $this->getContext($resource);
        }

        return $this->getContextUri($resource);
    }

    /**
     * Builds the JSON-LD context for the given resource.
     *
     * @param ResourceInterface|null $resource
     *
     * @return array
     */
    public function getContext(ResourceInterface $resource = null)
    {
        $context = $this->getBaseContext();
        $event = new Event\ContextBuilderEvent($context, $resource);
        $this->eventDispatcher->dispatch(Event\Events::CONTEXT_BUILDER, $event);

        return $event->getContext();
    }

    /**
     * Gets the context URI for the given resource.
     *
     * @param ResourceInterface $resource
     *
     * @return string
     */
    public function getContextUri(ResourceInterface $resource)
    {
        return $this->router->generate('api_json_ld_context', ['shortName' => $resource->getShortName()]);
    }

    /**
     * Gets the base context.
     *
     * @return array
     */
    private function getBaseContext()
    {
        return [
            '@vocab' => $this->router->generate('api_hydra_vocab', [], RouterInterface::ABSOLUTE_URL).'#',
            'hydra' => self::HYDRA_NS,
        ];
    }
}


text:
app.controller('MainCtrl', ['$rootScope', '$scope', '$http', function ($rootScope, $scope, $http) {

  $scope.sidebarInfo = {};

  $scope.selectedConnectServer;
  $scope.passwordPromptValue;
  $scope.passPromptSubmitted;
  $scope.activeTab;
  $scope.multiExecMode = false;

  $scope.connectedServer = [];
  $scope.webSockets = [];

  $scope.resize = function () {
    setTimeout(() => {
      var colsAndRows = $scope.getColsAndRows();
      $scope.webSockets.forEach(x => {
        x.send('^_^' + colsAndRows.rows + '|' + colsAndRows.cols);
        x.server.term.resize(colsAndRows.cols, colsAndRows.rows);
      });
    }, 301);
  }

  $(document).ready(function () {
    $(window).resize(function () {
      $scope.resize();
    });
  })

  $scope.init = function (server) {
    if ($rootScope.isLogin) {
      $rootScope.UserInfo.servers = $rootScope.UserInfo.servers || [];
      var groups = $rootScope.UserInfo.servers.map(x => x.group);
      if (groups.length === 0) {
        groups.push('Default');
      } else {
        groups = _.uniq(groups);
      }
      $scope.groups = groups;
    }
    $scope.isEditServer = !!server;
    if (server) {
      $scope.connectToServerInfo = _.cloneDeep(server);
    } else {
      $scope.connectToServerInfo = {
        displayName: '',
        ip: '',
        port: null,
        user: '',
        password: '',
        saveToCloud: true,
        rememberPass: false,
        group: $scope.groups ? $scope.groups[0] : ''
      };
    }
    $scope.connectToServerSubmitted = false;
  }

  $scope.init();

  $scope.buildSidebar = function () {
    $http.get('/api/user')
      .then(function (res) {
        $rootScope.isLogin = true;
        $rootScope.UserInfo = res.data;
        var servers = $rootScope.UserInfo.servers || [];
        $scope.sidebarInfo = _.groupBy(servers, 'group');
        if (_.isEmpty($scope.sidebarInfo)) {
          $scope.sidebarInfo = {
            'Default': []
          }
        }
      }, function (errRes) {
        $rootScope.isLogin = false;
        $rootScope.UserInfo = null;
      });
  }
  $scope.buildSidebar();

  $scope.toggleSidebar = function () {
    $('body').toggleClass('mini-sidebar');
    $scope.resize();
  }

  $scope.$on('UserCtrlChange', function (event, msg) {
    $rootScope.isLogin = !!msg.isLogin;
    if ($rootScope.isLogin) {
      $scope.buildSidebar();
    }
  });

  $scope.showConnectToServerModal = function () {
    $scope.init();
    $scope.showConnectServerModal();
  }

  $scope.connectToServer = function () {
    $scope.connectToServerSubmitted = true;
    if ($scope.connectServerForm.$invalid) return;
    var data = _.cloneDeep($scope.connectToServerInfo);
    if (data.group === '__new_group__') {
      data.group = data.newGroup;
      delete data.newGroup;
    }
    data.port = data.port || 22;
    data._id = data._id || (data.user + '@' + data.ip + (data.port === 22 ? '' : ':' + data.port));
    if (data.saveToCloud) {
      var pass = data.password;
      if (!data.rememberPass) {
        data.password = '';
      }
      $http.put('/api/user/servers', data)
        .then(function (resData) {
          $scope.buildSidebar();
          if (!$scope.isEditServer) {
            data.password = pass;
            $scope.addConnectedServer(data);
          }
          $scope.hideConnectServerModal();
        }, function (errData) {
          $scope.hideConnectServerModal();
        });
    } else {
      $scope.addConnectedServer(data);
      $scope.hideConnectServerModal();
    }
  }

  $scope.showConnectServerModal = function () {
    $("#connect_server_modal").modal({ backdrop: 'static' }).modal('show');
  }

  $scope.hideConnectServerModal = function () {
    $("#connect_server_modal").modal('hide');
  }

  $scope.toggleServerList = function (id) {
    $('#' + id).slideToggle();
    $('#parent_' + id).toggleClass('expaned');
  }

  $scope.connectServer = function (server) {
    $scope.selectedConnectServer = server;
    if (!server.password) {
      $scope.showPasswordPrompt();
    } else {
      $scope.addConnectedServer(server);
    }
  }

  $scope.editServer = function (server) {
    $scope.init(server);
    $scope.showConnectServerModal();
  }

  $scope.deleteServer = function () {
    if (!$scope.connectToServerInfo._id) return;
    $http.delete('/api/user/servers/' + $scope.connectToServerInfo._id)
      .then(function (resData) {
        toastr.success("Deleted");
        $scope.buildSidebar();
        $scope.hideConnectServerModal();
      }, function (errRes) {
        toastr.error("Delete server failed. Please try again.");
        console.log(errRes.data);
      });
  }

  $scope.showPasswordPrompt = function () {
    $scope.passPromptSubmitted = false;
    $scope.passwordPromptValue = '';
    $("#server_password_modal").modal({ backdrop: 'static' }).modal('show');
    $("form[name='serverPasswordInputForm'] input[name=password]").focus();
  }

  $scope.hidePasswordPrompt = function () {
    $("#server_password_modal").modal('hide');
  }

  $scope.submitPasswodPrompt = function () {
    $scope.passPromptSubmitted = true;
    if ($scope.serverPasswordInputForm.$invalid) return;
    $scope.addConnectedServer($scope.selectedConnectServer, $scope.passwordPromptValue);
    $scope.hidePasswordPrompt();
  }

  $scope.getColsAndRows = function () {
    var cols = 80;
    var rows = 20;
    var contentElement = document.getElementById('content_panel');
    if (contentElement) {
      if ($scope.multiExecMode) {
        cols = Math.floor((contentElement.offsetWidth - 37) / 2 / 9);
        if ($scope.connectedServer.length > 1 && $scope.connectedServer.length < 5) {
          rows = Math.floor((contentElement.offsetHeight - 85) / 2 / 21);
        } else {
          rows = Math.floor((contentElement.offsetHeight - 85) / 3 / 21);
        }
      } else {
        cols = Math.floor((contentElement.offsetWidth - 37) / 9);
        rows = Math.floor((contentElement.offsetHeight - 60) / 21);
      }
    }
    if (rows < 15) rows = 15;
    var data = {
      cols: cols,
      rows: rows
    };
    return data;
  }

  $scope.addConnectedServer = function (server, password) {
    var notClosed = _.countBy($scope.connectedServer, function (x) {
      return !!x._closed;
    });
    if (notClosed > 10) {
      toastr.error('Up to 10 servers can be connected');
      return;
    }
    var server = _.cloneDeep(server);
    server._id = server._id + '_' + new Date().valueOf();
    $scope.connectedServer.push(server);
    $scope.activeTab = server._id;

    var colsAndRows = $scope.getColsAndRows();

    var wsUrl = 'ws://' + location.host + '?rows=' + colsAndRows.rows + '&cols=' + colsAndRows.cols;
    wsUrl += '&user=' + server.user;
    wsUrl += '&password=' + (server.password || password);
    wsUrl += '&host=' + server.ip;
    wsUrl += '&port=' + server.port;
    wsUrl += '&t=' + new Date().valueOf();

    let ws = new WebSocket(wsUrl);
    ws._id = new Date().valueOf() + '' + server._id;
    server._wsid = ws._id;
    ws.server = server;
    ws.onopen = function () {
      var selfWs = this;
      var term = new Terminal({
        cols: colsAndRows.cols,
        rows: colsAndRows.rows,
        useStyle: true,
        convertEol: true,
        screenKeys: true,
        cursorBlink: false,
        visualBell: true,
        colors: Terminal.xtermColors
      });
      server.term = term;

      term.on('key', function (key, ev) {
        if (!$scope.multiExecMode) return;
        var self = this;
        $scope.webSockets.forEach(function (x) {
          if (!x.server.disableMultiExec && x.server._wsid !== selfWs._id) {
            x.send(key);
          }
        });
      });

      // term.on('paste', function (data, ev) {
      //   term.write(data);
      // });

      term.attach(ws);
      setTimeout(() => {
        var element = document.getElementById('term_' + server._id);
        if (element) {
          term.open(element, { focus: true });
        }
      }, 500);
    };
    ws.onclose = function (e) {
      var self = this;
      _.remove($scope.webSockets, function (x) {
        return x._id === self._id;
      });
      $scope.delConnectedServer(self.server._id);
      console.log("Disconnected. Current sockets nums: ", $scope.webSockets.length);
    };
    $scope.webSockets.push(ws);
  }

  $scope.delConnectedServer = function (id) {
    $scope.connectedServer.forEach(function (x) {
      if (x._id === id) {
        x._closed = true;
      }
    });
    var notClosed = _.filter($scope.connectedServer, function (x) {
      return !x._closed;
    });
    if (notClosed.length === 0) {
      $scope.connectedServer = [];
      $scope.multiExecMode = false;
    } else if ($scope.activeTab === id) {
      $scope.activeTab = notClosed[0] ? notClosed[0]._id : '';
    }
    $scope.$apply();
  }

  $scope.setActiveTab = function (item) {
    $scope.activeTab = item._id;
  }

  $scope.closeTab = function (evt, item) {
    evt.stopPropagation();
    var ws = _.find($scope.webSockets, function (x) {
      return x._id === item._wsid;
    });
    ws.close();
  }

  $scope.multiExec = function () {
    if ($scope.connectedServer.length < 2) return;
    $scope.multiExecMode = !$scope.multiExecMode;
    $scope.connectedServer.forEach(function (x) {
      x.disableMultiExec = false;
    });
    $scope.resize();
  }

  $scope.signOut = function () {
    $http.get('/api/user/logout')
      .then(function (data) {
        location.href = '/';
      }, function (errData) {
        toastr.error('Sign out failed. Please try again.')
      });
  }
}]);


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 321919 $ -->

<refentry xml:id="mysqlnduhpreparedstatement.prepare" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>MysqlndUhPreparedStatement::prepare</refname>
  <refpurpose>Prepare an SQL statement for execution</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>bool</type><methodname>MysqlndUhPreparedStatement::prepare</methodname>
   <methodparam><type>mysqlnd_prepared_statement</type><parameter>statement</parameter></methodparam>
   <methodparam><type>string</type><parameter>query</parameter></methodparam>
  </methodsynopsis>
  <para>
    Prepare an SQL statement for execution.
  </para>
</refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <variablelist>
   <varlistentry>
    <term><parameter>statement</parameter></term>
    <listitem>
     <para>
      Mysqlnd prepared statement handle. Do not modify!
      Resource of type <literal>Mysqlnd Prepared Statement (internal only - you must not modify it!)</literal>.
     </para>
    </listitem>
   </varlistentry>
   <varlistentry>
    <term><parameter>query</parameter></term>
    <listitem>
     <para>
      The query to be prepared.
     </para>
    </listitem>
   </varlistentry>
  </variablelist>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns &true; on success.
   Otherwise, returns &false;
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>MysqlndUhPreparedStatement::prepare</function> example</title>
        <programlisting role="php">
<![CDATA[
<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $query = "SELECT 'No more you-know-what-I-mean for lunch, please' AS _msg FROM DUAL";
  $ret = parent::prepare($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'Labskaus' AS _msg FROM DUAL");
$stmt->execute();
$msg = NULL;
$stmt->bind_result($msg);
$stmt->fetch();
var_dump($msg);
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
stmt_proxy::prepare(array (
  0 => NULL,
  1 => 'SELECT \'Labskaus\' AS _msg FROM DUAL',
))
stmt_proxy::prepare returns true
bool(true)
string(46) "No more you-know-what-I-mean for lunch, please"
]]>
    </screen>
   </example>
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member>
     <function>mysqlnd_uh_set_statement_proxy</function>
    </member>
    <member>
     <function>mysqli_stmt_prepare</function>
    </member>
    <member>
     <function>mysqli_prepare</function>
    </member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
using System;
using System.Diagnostics;
using System.Collections;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace qf4net
{
	/// <summary>
	/// The base class for all hierarchical state machines
	/// </summary>
	[Serializable]
	public abstract class QHsm : LoggingUserBase, IQHsm
	{
		private static QState s_TopState;

		/// <summary>
		/// Added for symmetry reasons, so that all deriving classes can add their own static
		/// <see cref="TransitionChainStore"/> variable using the new key word.
		/// </summary>
		protected static TransitionChainStore s_TransitionChainStore = null;

		private MethodInfo m_MyStateMethod;
		private MethodInfo m_MySourceStateMethod;

		static QHsm()
		{
			s_TopState = new QState(Top);
		}

		/// <summary>
		/// Constructor for the Quantum Hierarchical State Machine.
		/// </summary>
		public QHsm()
		{
			m_MyStateMethod = s_TopState.Method;
		}

		/// <summary>
		/// Getter for an optional <see cref="TransitionChainStore"/> that can hold cached
		/// <see cref="TransitionChain"/> objects that are used to optimize static transitions.
		/// </summary>
		protected virtual TransitionChainStore TransChainStore
		{
			get { return null; }
		}

		/// <summary>
		/// Is called inside of the function Init to give the deriving class a chance to
		/// initialize the state machine.
		/// </summary>
		protected abstract void InitializeStateMachine();

		/// <summary>
		/// Must only be called once by the client of the state machine to initialize the machine.
		/// </summary>
		public void Init()
		{
			Debug.Assert(m_MyStateMethod == s_TopState.Method); // HSM not executed yet
			MethodInfo stateMethod = m_MyStateMethod; // save m_StateHandler in a temporary

			this.InitializeStateMachine(); // We call into the deriving class
			// initial transition must go *one* level deep
			Debug.Assert(GetSuperStateMethod(m_MyStateMethod) == stateMethod);

			stateMethod = m_MyStateMethod; // Note: We only use the temporary
			// variable stateMethod so that we can use Assert statements to ensure
			// that each transition is only one level deep.
			Trigger(stateMethod, QSignals.Entry);
			while(Trigger(stateMethod, QSignals.Init) == null) // init handled?
			{
				Debug.Assert(GetSuperStateMethod(m_MyStateMethod) == stateMethod);
				stateMethod = m_MyStateMethod;

				Trigger(stateMethod, QSignals.Entry);
			}
		}

		/// <summary>
		/// Determines whether the state machine is in the state specified by <see paramref="inquiredState"/>.
		/// </summary>
		/// <param name="inquiredState">The state to check for.</param>
		/// <returns>
		/// <see langword="true"/> if the state machine is in the specified state;
		/// <see langword="false"/> otherwise.
		/// </returns>
		/// <remarks>
		/// If the currently active state of a hierarchical state machine is s then it is in the
		/// state s AND all its parent states.
		/// </remarks>
		public bool IsInState(QState inquiredState)
		{
			MethodInfo stateMethod;
			for(stateMethod = m_MyStateMethod;
				stateMethod != null;
				stateMethod = GetSuperStateMethod(stateMethod))
			{
				if (stateMethod == inquiredState.Method) // do the states match?
				{
					return true;
				}
			}
			return false; // no match found
		}

		/// <summary>
		/// Returns the name of the (deepest) state that the state machine is currently in.
		/// </summary>
		public string CurrentStateName
		{
			get { return m_MyStateMethod.Name; }
		}

		protected MethodInfo CurrentStateMethod
		{
			get
			{
				return m_MyStateMethod;
			}
			set
			{
				m_MyStateMethod = value;
			}
		}

		protected void ComplainIfUnhandled (MethodInfo stateMethod, IQEvent qEvent)
		{
			switch (qEvent.QSignal)
			{
				case QSignals.Init:
				case QSignals.Entry:
				case QSignals.Exit:
				case QSignals.Empty:
					break;
				default:
					DoUnhandledTransition (this, stateMethod, qEvent);
					break;
			}
		}

        /// <summary>
        /// Dispatches the specified event to this state machine
        /// </summary>
        /// <param name="qEvent">The <see cref="IQEvent"/> to dispatch.</param>
        private void Dispatch_Internal(IQEvent qEvent)
        {
            // We let the event bubble up the chain until it is handled by a state handler
            m_MySourceStateMethod = m_MyStateMethod;
            while(m_MySourceStateMethod != null)
            {
                // check for TopState - aka Unhandled event
                if (m_MySourceStateMethod == TopState.Method)
                {
                    ComplainIfUnhandled (m_MyStateMethod, qEvent);
                }

                QState state = (QState)m_MySourceStateMethod.Invoke(this, new object[] { qEvent } );
                if (state != null)
                {
                    m_MySourceStateMethod = state.Method;
                }
                else
                {
                    m_MySourceStateMethod = null;
                }
            }
        }

		/// <summary>
		/// Dispatches the specified event to this state machine
		/// </summary>
		/// <param name="qEvent">The <see cref="IQEvent"/> to dispatch.</param>
		public void Dispatch(IQEvent qEvent)
		{
            qEvent.ApplyActivityId ();
            try
            {
                Dispatch_Internal (qEvent);
            }
            finally
            {
                qEvent.ClearActivityId ();
            }
		}

		#region DispatchExceptionEvent
		/// <summary>
		/// This event is called when an exception is thrown while
		/// a Trigger is firing. It is meant to indicate a failure
		/// in the handling of an event in the specified state method.
		///
		/// This failure can then be used to transition to a failure state.
		/// </summary>
		public event DispatchExceptionHandler DispatchException;

		/// <summary>
		/// Internal DispatchException handler. Return false to prevent the exception
		/// from being passed out as a DispatchException event.
		/// </summary>
		protected virtual bool OnDispatchException (IQHsm hsm, Exception ex, MethodInfo stateMethod, IQEvent ev)
		{
			return true;
		}

        protected void RaiseDispatchException (DispatchExceptionHandler handler, IQHsm hsm, Exception ex, MethodInfo stateMethod, IQEvent ev)
        {
            if (handler != null)
            {
                handler (ex, hsm, stateMethod, ev);
            }
        }

		/// <summary>
		/// DispatchException (see def on IQHsm)
		/// </summary>
		protected virtual void DoDispatchException (IQHsm hsm, Exception ex, MethodInfo stateMethod, IQEvent ev)
		{
            if (OnDispatchException (hsm, ex, stateMethod, ev))
            {
                RaiseDispatchException (DispatchException, hsm, ex, stateMethod, ev);
            }
		}
		#endregion

		#region UnhandledTransition
		public event DispatchUnhandledTransitionHandler UnhandledTransition;

		protected virtual bool OnUnhandledTransition (IQHsm hsm, MethodInfo stateMethod, IQEvent qEvent)
		{
			return true;
		}

        protected void RaiseUnhandledTransition (DispatchUnhandledTransitionHandler handler, IQHsm hsm, MethodInfo stateMethod, IQEvent qEvent)
        {
            if (handler != null)
            {
                handler (hsm, stateMethod, qEvent);
            }
        }

		protected void DoUnhandledTransition (IQHsm hsm, MethodInfo stateMethod, IQEvent qEvent)
		{
			if (OnUnhandledTransition (hsm, stateMethod, qEvent))
			{
                RaiseUnhandledTransition (UnhandledTransition, hsm, stateMethod, qEvent);
			}
		}
		#endregion

		/// <summary>
		/// Dispatch
		/// </summary>
        public bool DispatchWithExceptionTrap (IQEvent qEvent, bool ReraiseOnException)
        {
            bool ok;

            qEvent.ApplyActivityId ();
            try
            {
                try
                {
                    Dispatch_Internal (qEvent);
                    ok = true;
                }
                catch (Exception ex)
                {
                    ok = false;
                    DoDispatchException (this, ex, this.m_MySourceStateMethod, qEvent);
                    if (ReraiseOnException)
                    {
                        throw;
                    }
                }
            }
            finally
            {
                qEvent.ClearActivityId ();
            }

            return ok;
        }

		/// <summary>
		/// Same as the method <see cref="Dispatch"/> but guarantees that the method can
		/// be executed by only one thread at a time.
		/// </summary>
		/// <param name="qEvent">The <see cref="IQEvent"/> to dispatch.</param>
		[MethodImpl(MethodImplOptions.Synchronized)]
		public void DispatchSynchronized(IQEvent qEvent)
		{
			Dispatch(qEvent);
		}

		/// <summary>
		/// The handler for the top state that is shared by all instances of a QHSM.
		/// </summary>
		/// <param name="qEvent"></param>
		/// <returns></returns>
		private static QState Top(IQEvent qEvent)
		{
			return null;
		}

		/// <summary>
		/// The top state of each <see cref="QHsm"/>
		/// </summary>
		protected QState TopState
		{
			get { return s_TopState; }
		}

		#region Helper functions for the predefined signals

		private MethodInfo Trigger(MethodInfo stateMethod, string qSignal)
		{
			QState state = (QState)stateMethod.Invoke(this, new object[] { new QEvent (qSignal) } );
			if (state == null)
			{
				return null;
			}
			else
			{
				return state.Method;
			}
		}

		/// <summary>
		/// Sends the specified signal to the specified state and (optionally) records the transition
		/// </summary>
		/// <param name="receiverStateMethod">The <see cref="MethodInfo"/> that represents the state method
		/// to which to send the signal.</param>
		/// <param name="qSignal">The <see cref="QSignals"/> to send.</param>
		/// <param name="recorder">An instance of <see cref="TransitionChainRecorder"/> if the transition
		/// is to be recorded; <see langword="null"/> otherwise.</param>
		/// <returns>The <see cref="QState"/> returned by the state that recieved the signal.</returns>
		/// <remarks>
		/// Even if a recorder is specified, the transition will only be recorded if the state
		/// <see paramref="receiverStateMethod"/> actually handled it.
		/// This function is used to record the transition chain for a static transition that is executed
		/// the first time.
		/// </remarks>
		private MethodInfo Trigger(MethodInfo receiverStateMethod, string qSignal, TransitionChainRecorder recorder)
		{
			MethodInfo stateMethod = Trigger(receiverStateMethod, qSignal);
			if ((stateMethod == null) && (recorder != null))
			{
				// The receiverState handled the event
				recorder.Record(receiverStateMethod, qSignal);
			}
			return stateMethod;
		}

		///<summary>
		/// Retrieves the super state (parent state) of the specified
		/// state by sending it the empty signal.
		///</summary>
		private MethodInfo GetSuperStateMethod(MethodInfo stateMethod)
		{
			QState superState = (QState)stateMethod.Invoke(this, new object[] { new QEvent (QSignals.Empty) } );
			if (superState != null)
			{
				return superState.Method;
			}
			else
			{
				return null;
			}
		}

		#endregion

		/// <summary>
		/// Represents the macro Q_INIT in Miro Samek's implementation
		/// </summary>
		protected void InitializeState(QState state)
		{
			m_MyStateMethod = state.Method;
		}

		/// <summary>
		/// Performs a dynamic transition; i.e., the transition path is determined on the fly and not recorded.
		/// </summary>
		/// <param name="targetState">The <see cref="QState"/> to transition to.</param>
		protected void TransitionTo(QState targetState)
		{
			Debug.Assert(targetState != s_TopState); // can't target 'top' state
			ExitUpToSourceState();
			// This is a dynamic transition. We pass in null instead of a recorder
			TransitionFromSourceToTarget(targetState.Method, null);
		}

		/// <summary>
		/// Performs the transition from the current state to the specified target state.
		/// </summary>
		/// <param name="targetState">The <see cref="QState"/> to transition to.</param>
		/// <param name="transitionChain">A <see cref="TransitionChain"/> used to hold the transition chain that
		/// needs to be executed to perform the transition to the target state.</param>
		/// <remarks>
		/// The very first time that a given static transition is executed, the <see paramref="transitionChain"/>
		/// reference will point to <see langword="null"/>. In this case a new <see cref="TransitionChain"/>
		/// instance is created. As the complete transition is performed the individual transition steps are
		/// recorded in the new <see cref="TransitionChain"/> instance. At the end of the call the new
		/// (and now filled) <see cref="TransitionChain"/> is handed back to the caller.
		/// If the same transition needs to be performed later again, the caller needs to pass
		/// in the filled <see cref="TransitionChain"/> instance. The recorded transition path will then be
		/// played back very efficiently.
		/// </remarks>
		protected void TransitionTo(QState targetState, ref TransitionChain transitionChain)
		{
			Debug.Assert(targetState != s_TopState); // can't target 'top' state
			ExitUpToSourceState();

			if (transitionChain == null) // for efficiency the first check is not thread-safe
			{
				// We implement the double-checked locking pattern
				TransitionToSynchronized(targetState, ref transitionChain);
			}
			else
			{
				// We just need to 'replay' the transition chain that is stored in the transitions chain.
				ExecuteTransitionChain(transitionChain);
			}
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		private void TransitionToSynchronized(QState targetState, ref TransitionChain transitionChain)
		{
			if (transitionChain != null)
			{
				// We encountered a race condition. The first (non-synchronized) check indicated that the transition chain
				// is null. However, a second threat beat us in getting into this synchronized method and populated
				// the transition chain in the meantime. We can execute the regular method again now.
				TransitionTo(targetState, ref transitionChain);
			}
			else
			{
				// The transition chain is not initialized yet, we need to dynamically retrieve
				// the required transition steps and record them so that we can subsequently simply
				// play them back.
				TransitionChainRecorder recorder = new TransitionChainRecorder();
				TransitionFromSourceToTarget(targetState.Method, recorder);
				// We pass the recorded transition steps back to the caller:
				transitionChain = recorder.GetRecordedTransitionChain();
			}
		}

		/// <summary>
		/// Performs a static transition from the current state to the specified target state. The
		/// <see cref="TransitionChain"/> that specifies the steps required for the static transition
		/// is specified by the provided index into the <see cref="TransitionChainStore"/>. Note that this
		/// method can only be used if the class that implements the <see cref="QHsm"/> provides a class
		/// specific <see cref="TransitionChainStore"/> via the virtual getter <see cref="TransChainStore"/>.
		/// </summary>
		/// <param name="targetState">The <see cref="QState"/> to transition to.</param>
		/// <param name="chainIndex">The index into <see cref="TransitionChainStore"/> pointing to the
		/// <see cref="TransitionChain"/> that is used to hold the individual transition steps that are
		/// required to perform the transition.</param>
		/// <remarks>
		/// In order to use the method the calling class must retrieve the chain index during its static
		/// construction phase by calling the method <see cref="TransitionChainStore.GetOpenSlot()"/> on
		/// its static <see cref="TransitionChainStore"/>.
		/// </remarks>
		protected void TransitionTo(QState targetState, int chainIndex)
		{
			// This method can only be used if a TransitionChainStore has been created for the QHsm
			Debug.Assert(this.TransChainStore != null);
			TransitionTo(targetState, ref this.TransChainStore.TransitionChains[chainIndex]);
		}

		private void ExitUpToSourceState()
		{
			for(MethodInfo stateMethod = m_MyStateMethod; stateMethod != m_MySourceStateMethod; )
			{
				Debug.Assert(stateMethod != null);
				MethodInfo stateMethodToHandleExit = Trigger(stateMethod, QSignals.Exit);
				if (stateMethodToHandleExit != null)
				{
					// state did not handle the Exit signal itself
					stateMethod = stateMethodToHandleExit;
				}
				else
				{
					// state handled the Exit signal. We need to elicit
					// the superstate explicitly.
					stateMethod = GetSuperStateMethod(stateMethod);
				}
			}
		}

		/// <summary>
		/// Handles the transition from the source state to the target state without the help of a previously
		/// recorded transition chain.
		/// </summary>
		/// <param name="targetStateMethod">The <see cref="MethodInfo"/> representing the state method to transition to.</param>
		/// <param name="recorder">An instance of <see cref="TransitionChainRecorder"/> or <see langword="null"/></param>
		/// <remarks>
		/// Passing in <see langword="null"/> as the recorder means that we deal with a dynamic transition.
		/// If an actual instance of <see cref="TransitionChainRecorder"/> is passed in then we deal with a static
		/// transition that was not recorded yet. In this case the function will record the transition steps
		/// as they are determined.
		/// </remarks>
		private void TransitionFromSourceToTarget(MethodInfo targetStateMethod, TransitionChainRecorder recorder)
		{
			ArrayList statesTargetToLCA;
			int indexFirstStateToEnter;
			ExitUpToLCA(targetStateMethod, out statesTargetToLCA, out indexFirstStateToEnter, recorder);
			TransitionDownToTargetState(targetStateMethod, statesTargetToLCA, indexFirstStateToEnter, recorder);
		}

		/// <summary>
		/// Determines the transition chain between the target state and the LCA (Least Common Ancestor)
		/// and exits up to LCA while doing so.
		/// </summary>
		/// <param name="targetStateMethod">The target state method of the transition.</param>
		/// <param name="statesTargetToLCA">An <see cref="ArrayList"/> that holds (in reverse order) the states
		/// that need to be entered on the way down to the target state.
		/// Note: The index of the first state that needs to be entered is returned in
		/// <see paramref="indexFirstStateToEnter"/>.</param>
		/// <param name="indexFirstStateToEnter">Returns the index in the array <see cparamref="statesTargetToLCA"/>
		/// that specifies the first state that needs to be entered on the way down to the target state.</param>
		/// <param name="recorder">An instance of <see cref="TransitionChainRecorder"/> if the transition chain
		/// should be recorded; <see langword="null"/> otherwise.</param>
		private void ExitUpToLCA(
			MethodInfo targetStateMethod,
			out ArrayList statesTargetToLCA,
			out int indexFirstStateToEnter,
			TransitionChainRecorder recorder)
		{
			statesTargetToLCA = new ArrayList();
			statesTargetToLCA.Add(targetStateMethod);
			indexFirstStateToEnter = 0;

			// (a) check my source state == target state (transition to self)
			if(m_MySourceStateMethod == targetStateMethod)
			{
				Trigger(m_MySourceStateMethod, QSignals.Exit, recorder);
				return;
			}

			// (b) check my source state == super state of the target state
			MethodInfo targetSuperStateMethod = GetSuperStateMethod(targetStateMethod);
			//Debug.WriteLine(targetSuperStateMethod.Name);
			if(m_MySourceStateMethod == targetSuperStateMethod)
			{
				return;
			}

			// (c) check super state of my source state == super state of target state
			// (most common)
			MethodInfo sourceSuperStateMethod = GetSuperStateMethod(m_MySourceStateMethod);
			if(sourceSuperStateMethod == targetSuperStateMethod)
			{
				Trigger(m_MySourceStateMethod, QSignals.Exit, recorder);
				return;
			}

			// (d) check super state of my source state == target
			if (sourceSuperStateMethod == targetStateMethod)
			{
				Trigger(m_MySourceStateMethod, QSignals.Exit, recorder);
				indexFirstStateToEnter = -1; // we don't enter the LCA
				return;
			}

			// (e) check rest of my source = super state of super state ... of target state hierarchy
			statesTargetToLCA.Add(targetSuperStateMethod);
			indexFirstStateToEnter++;
			for (MethodInfo stateMethod = GetSuperStateMethod(targetSuperStateMethod);
				stateMethod != null; stateMethod = GetSuperStateMethod(stateMethod))
			{
				if (m_MySourceStateMethod == stateMethod)
				{
					return;
				}

				statesTargetToLCA.Add(stateMethod);
				indexFirstStateToEnter++;
			}

			// For both remaining cases we need to exit the source state
			Trigger(m_MySourceStateMethod, QSignals.Exit, recorder);

			// (f) check rest of super state of my source state ==
			//     super state of super state of ... target state
			// The array list is currently filled with all the states
			// from the target state up to the top state
			for (int stateIndex = indexFirstStateToEnter; stateIndex >= 0; stateIndex--)
			{
				if (sourceSuperStateMethod == (MethodInfo)statesTargetToLCA[stateIndex])
				{
					indexFirstStateToEnter = stateIndex - 1;
					// Note that we do not include the LCA state itself;
					// i.e., we do not enter the LCA
					return;
				}
			}

			// (g) check each super state of super state ... of my source state ==
			//     super state of super state of ... target state
			for (MethodInfo stateMethod = sourceSuperStateMethod;
				stateMethod != null; stateMethod = GetSuperStateMethod(stateMethod))
			{
				for (int stateIndex = indexFirstStateToEnter; stateIndex >= 0; stateIndex--)
				{
					if (stateMethod == (MethodInfo)statesTargetToLCA[stateIndex])
					{
						indexFirstStateToEnter = stateIndex - 1;
						// Note that we do not include the LCA state itself;
						// i.e., we do not enter the LCA
						return;
					}
				}
				Trigger(stateMethod, QSignals.Exit, recorder);
			}

			// We should never get here
			throw new ApplicationException("Mal formed Hierarchical State Machine");
		}

		private void TransitionDownToTargetState(
			MethodInfo targetStateMethod,
			ArrayList statesTargetToLCA,
			int indexFirstStateToEnter,
			TransitionChainRecorder recorder)
		{
			// we enter the states in the passed in array in reverse order
			for (int stateIndex = indexFirstStateToEnter; stateIndex >= 0; stateIndex--)
			{
				Trigger((MethodInfo)statesTargetToLCA[stateIndex], QSignals.Entry, recorder);
			}

			m_MyStateMethod = targetStateMethod;

			// At last we are ready to initialize the target state.
			// If the specified target state handles init then the effective
			// target state is deeper than the target state specified in
			// the transition.
			while (Trigger(targetStateMethod, QSignals.Init, recorder) == null)
			{
				// Initial transition must be one level deep
				Debug.Assert(targetStateMethod == GetSuperStateMethod(m_MyStateMethod));
				targetStateMethod = m_MyStateMethod;
				Trigger(targetStateMethod, QSignals.Entry, recorder);
			}

			if (recorder != null)
			{
				// We always make sure that the last entry in the recorder represents the entry to the target state.
				EnsureLastTransistionStepIsEntryIntoTargetState(targetStateMethod, recorder);
				Debug.Assert(recorder.GetRecordedTransitionChain().Length > 0);
			}
		}

		private void EnsureLastTransistionStepIsEntryIntoTargetState(
			MethodInfo targetStateMethod,
			TransitionChainRecorder recorder)
		{
			if (recorder.GetRecordedTransitionChain().Length == 0)
			{
				// Nothing recorded so far
				RecordEntryIntoTargetState(targetStateMethod, recorder);
				return;
			}
			else
			{
				// We need to test whether the last recorded transition step is the entry into the target state
				TransitionChain transitionChain = recorder.GetRecordedTransitionChain();
				TransitionStep lastTransitionStep = transitionChain[transitionChain.Length - 1];
				if (lastTransitionStep.StateMethod != targetStateMethod ||
					lastTransitionStep.QSignal != QSignals.Entry)
				{
					RecordEntryIntoTargetState(targetStateMethod, recorder);
					return;
				}
			}
		}

		private void RecordEntryIntoTargetState(
			MethodInfo targetStateMethod,
			TransitionChainRecorder recorder)
		{
			recorder.Record(targetStateMethod, QSignals.Entry);
		}

		private void ExecuteTransitionChain(TransitionChain transitionChain)
		{
			// There must always be at least one transition step in the provided transition chain
			Debug.Assert(transitionChain.Length > 0);

			TransitionStep transitionStep = transitionChain[0]; // to shut up the compiler;
			// without it we would get the following error on the line
			//       m_MyStateMethod = transitionStep.StateMethod;
			// at the end of this method: Use of possibly unassigned field 'State'
			for(int i = 0; i < transitionChain.Length; i++)
			{
				transitionStep = transitionChain[i];
				Trigger(transitionStep.StateMethod, transitionStep.QSignal);
			}
			m_MyStateMethod = transitionStep.StateMethod;
		}

		#region Helper classes for the handling of static transitions

		#region TransitionChainRecorder

		/// <summary>
		/// This class is used to record the individual transition steps that are required to transition from
		/// a given state to a target state.
		/// </summary>
		private class TransitionChainRecorder
		{
			private ArrayList m_TransitionSteps = new ArrayList();

			internal void Record(MethodInfo stateMethod, string qSignal)
			{
				m_TransitionSteps.Add(new TransitionStep(stateMethod, qSignal));
			}

			/// <summary>
			/// Returns the recorded transition steps in form of a <see cref="TransitionChain"/> instance.
			/// </summary>
			/// <returns></returns>
			internal TransitionChain GetRecordedTransitionChain()
			{
				// We turn the ArrayList into a strongly typed array
				return new TransitionChain(m_TransitionSteps);
			}
		}

		#endregion

		#region TransitionChain & TransitionStep

		/// <summary>
		/// Class that wraps the handling of recorded transition steps.
		/// </summary>
		protected class TransitionChain
		{
			private MethodInfo[] m_StateMethodChain;
			//  holds the transitions that need to be performed from the LCA down to the target state

			private BitArray m_ActionBits;
			// holds the actions that need to be performed on each transition in two bits:
			// 0x1: Init; 0x2: Entry, 0x3: Exit

			internal TransitionChain(ArrayList transitionSteps)
			{
				m_StateMethodChain = new MethodInfo[transitionSteps.Count];
				m_ActionBits = new BitArray(transitionSteps.Count * 2);

				for(int i = 0; i<transitionSteps.Count; i++)
				{
					TransitionStep transitionStep = (TransitionStep)transitionSteps[i];

					m_StateMethodChain[i] = transitionStep.StateMethod;
					int bitPos = i * 2;
					switch (transitionStep.QSignal)
					{
						case QSignals.Empty:   m_ActionBits[bitPos] = false; m_ActionBits[++bitPos] = false; break;
						case QSignals.Init:    m_ActionBits[bitPos] = false; m_ActionBits[++bitPos] = true;  break;
						case QSignals.Entry:   m_ActionBits[bitPos] = true;  m_ActionBits[++bitPos] = false; break;
						case QSignals.Exit:    m_ActionBits[bitPos] = true;  m_ActionBits[++bitPos] = true;  break;
					}
				}
			}

			internal int Length { get { return m_StateMethodChain.Length; } }

			internal TransitionStep this[int index]
			{
				get
				{
					TransitionStep transitionStep = new TransitionStep();
					transitionStep.StateMethod = m_StateMethodChain[index];

					int bitPos = index * 2;
					if (m_ActionBits[bitPos])
					{
						if (m_ActionBits[bitPos + 1])
						{
							transitionStep.QSignal = QSignals.Exit;
						}
						else
						{
							transitionStep.QSignal = QSignals.Entry;
						}
					}
					else
					{
						if (m_ActionBits[bitPos + 1])
						{
							transitionStep.QSignal = QSignals.Init;
						}
						else
						{
							transitionStep.QSignal = QSignals.Empty;
						}
					}
					return transitionStep;
				}
			}
		}

		internal struct TransitionStep
		{
			internal MethodInfo StateMethod;
			internal string QSignal;

			internal TransitionStep(MethodInfo stateMethod, string qSignal)
			{
				StateMethod = stateMethod;
				QSignal = qSignal;
			}
		}

		#endregion

		#region TransitionChainStore

		/// <summary>
		/// Class that handles storage and access to the various <see cref="TransitionChain"/> instances
		/// that are required for all the static transitions in use by a given hierarchical state machine.
		/// </summary>
		protected class TransitionChainStore
		{
			private const int c_DefaultCapacity = 16;

			private TransitionChain[] m_Items;
			private int m_Size;

			/// <summary>
			/// Constructs a <see cref="TransitionChainStore"/>. The internal array for holding
			/// <see cref="TransitionChain"/> instances is configured to have room for the static
			/// transitions in the base class (if any).
			/// </summary>
			/// <param name="callingClass">The class that called called the constructor.</param>
			public TransitionChainStore(Type callingClass)
			{
				Debug.Assert(IsDerivedFromQHsm(callingClass));

				Type baseType = callingClass.BaseType;
				int slotsRequiredByBaseQHsm;
				if (baseType == typeof(QHsm))
				{
					slotsRequiredByBaseQHsm = 0;
				}
				else
				{
					slotsRequiredByBaseQHsm = RetrieveStoreSizeOfBaseClass(baseType);
				}

				InitializeStore(slotsRequiredByBaseQHsm);
			}

			private bool IsDerivedFromQHsm(Type type)
			{
				Type baseType = type.BaseType;
				while ((baseType != null))
				{
					if (baseType == typeof(QHsm))
					{
						return true;
					}
					baseType = baseType.BaseType;
				}

				// None of the base classes is QHsm
				return false;
			}

			private int RetrieveStoreSizeOfBaseClass(Type baseType)
			{
				BindingFlags bindingFlags =
					BindingFlags.DeclaredOnly |
					BindingFlags.NonPublic |
					BindingFlags.Static |
					BindingFlags.GetField;

				TransitionChainStore store = (TransitionChainStore) baseType.InvokeMember(
					"s_TransitionChainStore",
					bindingFlags, null, null, null);
				return store.Size;
			}

			private void InitializeStore(int slotsRequiredByBaseQHsm)
			{
				if (slotsRequiredByBaseQHsm == 0)
				{
					m_Items = new TransitionChain[c_DefaultCapacity];
				}
				else
				{
					m_Items = new TransitionChain[2 * slotsRequiredByBaseQHsm];
				}

				m_Size = slotsRequiredByBaseQHsm;
			}

			/// <summary>
			/// Creates a new slot for a <see cref="TransitionChain"/> and returns its index
			/// </summary>
			/// <returns>The index of the new slot.</returns>
			public int GetOpenSlot()
			{
				if (m_Size >= m_Items.Length)
				{
					// We no longer have room in the items array to hold a new slot
					IncreaseCapacity();
				}
				return m_Size++;
			}

			/// <summary>
			/// Reallocates the internal array <see cref="m_Items"/> to an array twice the previous capacity.
			/// </summary>
			private void IncreaseCapacity()
			{
				int newCapacity;
				if (m_Items.Length == 0)
				{
					newCapacity = c_DefaultCapacity;
				}
				else
				{
					newCapacity	= m_Items.Length * 2;
				}
				TransitionChain[] newItems = new TransitionChain[newCapacity];
				Array.Copy(m_Items, 0, newItems, 0, m_Items.Length);
				m_Items = newItems;
			}

			/// <summary>
			/// Should be called once all required slots have been established in order to minimize the memory
			/// footprint of the store.
			/// </summary>
			public void ShrinkToActualSize()
			{
				TransitionChain[] newItems = new TransitionChain[m_Size];
				Array.Copy(m_Items, 0, newItems, 0, m_Size);
				m_Items = newItems;
			}

			/// <summary>
			/// Provides access to the array that holds the persisted <see cref="TransitionChain"/> objects.
			/// </summary>
			public TransitionChain[] TransitionChains
			{
				get { return m_Items; }
			}

			/// <summary>
			/// The size of the <see cref="TransitionChainStore"/>; i.e., the actual number of used slots.
			/// </summary>
			internal int Size
			{
				get { return m_Size; }
			}
		}

		#endregion

		#endregion
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Erysiphe lycii Lasch, 1846

### Remarks
null


text:
const concat = require('gulp-concat');
const contains = require('gulp-contains');
const del = require('del');
const eslint = require('gulp-eslint');
const expose = require('gulp-expose');
const gulp = require('gulp');
const rename = require("gulp-rename");

// Regex that looks for a populated client ID in the code. This is used to
// catch cases where the client ID is accidentally committed in a sample.
const CLIENT_ID_REGEX = /CLIENT_ID\s*=\s*'[^.']/;

// String which if it appears in the source code bypasses the client ID check.
// This is to allow samples that use a publicly-available demo client ID to
// not trigger the error.
const CLIENT_ID_BYPASS = '@credentialsOK';

gulp.task('clean', async function() {
  return del([
    'dist/*'
  ]);
});

gulp.task('dist', gulp.series('clean', async function(){
  return gulp.src('src/*.js')
      .pipe(concat('OAuth2.gs'))
      .pipe(expose('this', 'OAuth2'))
      .pipe(gulp.dest('dist'));
}));

gulp.task('lint', () => {
  return gulp.src(['src/*.js', 'samples/*.gs', 'test/**/*.js', '!node_modules/**'])
      .pipe(eslint())
      .pipe(eslint.format())
      .pipe(eslint.failAfterError())
      .pipe(contains({
        search: CLIENT_ID_REGEX,
        onFound: (string, file, cb) => {
          if (file.contents.toString().includes(CLIENT_ID_BYPASS)) {
            return false;
          }
          return cb(`Client ID found in file: "${file.relative}"`);
        }
      }));
});

gulp.task('fix', () => {
    return gulp.src(['src/*.js', 'samples/*.gs', 'test/**/*.js', '!node_modules/**'])
      .pipe(eslint({fix: true}))
      .pipe(eslint.format())
      .pipe(gulp.dest(file => file.base))
});