text:
{-# language Rank2Types #-}
{-# language ScopedTypeVariables #-}
{-# language DataKinds #-}
{-# language TypeOperators #-}
{-# language TypeFamilies #-}
{-# language FlexibleInstances #-}
{-# language FlexibleContexts #-}
{-# language MultiParamTypeClasses #-}
{-# language PolyKinds #-}
{-# language GADTs #-}
{-# language ConstraintKinds #-}
{-# language GeneralizedNewtypeDeriving #-}

module Feldspar.Software.Verify.Primitive where

import Feldspar.Sugar
import Feldspar.Representation
import Feldspar.Software.Primitive
import Feldspar.Software.Expression
import Feldspar.Software.Representation hiding (Nil)
import Feldspar.Software.Verify.Command
import Feldspar.Verify.Arithmetic

import Feldspar.Verify.Monad (Verify)
import qualified Feldspar.Verify.FirstOrder as FO
import qualified Feldspar.Verify.Monad as V
import qualified Feldspar.Verify.SMT as SMT
import qualified Feldspar.Verify.Abstract as A

import Data.Struct
import qualified Data.Map.Strict as Map

import qualified Control.Monad.RWS.Strict as S

import qualified SimpleSMT as SMT hiding (not, declareFun)

import qualified Language.Embedded.Expression as Imp
import qualified Language.Embedded.Imperative.CMD as Imp

import qualified Data.Bits as Bits
import qualified Data.Complex as Complex
import Data.Constraint hiding (Sub)
import Data.Int
import Data.Word
import Data.Typeable

import Language.Syntactic

import GHC.Stack

--------------------------------------------------------------------------------
-- *
--------------------------------------------------------------------------------

newtype Symbolic a = Symbolic { unSymbolic :: Rat }
  deriving (Eq, Ord, Show, V.TypedSExpr, V.SMTOrd)

instance V.Fresh (Symbolic a)
  where
    fresh = V.freshSExpr

symbCast :: Symbolic a -> Symbolic b
symbCast = Symbolic . unSymbolic

symbFun :: SymbParam a => String -> [Symbolic a] -> Symbolic a
symbFun name (args :: [Symbolic a]) = V.fromSMT $
  SMT.fun (symbType (undefined :: a) ++ "-" ++ name) (map V.toSMT args)

fromComplexConstant :: (RealFrac a, SymbParam b) => Complex.Complex a -> Symbolic b
fromComplexConstant c = symbFun "complex" [real, imag]
  where
    real = Symbolic $ fromRational $ toRational $ Complex.realPart c
    imag = Symbolic $ fromRational $ toRational $ Complex.imagPart c

--------------------------------------------------------------------------------

data SymbFloat
data SymbDouble
data SymbComplexFloat
data SymbComplexDouble

class SymbParam a
  where
    symbType :: a -> String

instance SymbParam SymbFloat  where symbType _ = "float"
instance SymbParam SymbDouble where symbType _ = "double"
instance SymbParam SymbComplexFloat  where symbType _ = "cfloat"
instance SymbParam SymbComplexDouble where symbType _ = "cdouble"

instance SymbParam a => Num (Symbolic a)
  where
    fromInteger = Symbolic . fromInteger
    x + y  = symbFun "+" [x, y]
    x - y  = symbFun "-" [x, y]
    x * y  = symbFun "*" [x, y]
    abs    = smtAbs
    signum = smtSignum

instance SymbParam a => Fractional (Symbolic a) where
  fromRational = Symbolic . fromRational
  x / y = symbFun "/" [x, y]

instance SymbParam a => Floating (Symbolic a) where
  pi      = fromRational (toRational pi)
  exp x   = symbFun "exp" [x]
  log x   = symbFun "log" [x]
  sqrt x  = symbFun "sqrt" [x]
  x ** y  = symbFun "pow" [x, y]
  sin x   = symbFun "sin" [x]
  cos x   = symbFun "cos" [x]
  tan x   = symbFun "tan" [x]
  asin x  = symbFun "asin" [x]
  acos x  = symbFun "acos" [x]
  atan x  = symbFun "atan" [x]
  sinh x  = symbFun "sinh" [x]
  cosh x  = symbFun "cosh" [x]
  tanh x  = symbFun "tanh" [x]
  asinh x = symbFun "asinh" [x]
  acosh x = symbFun "acosh" [x]
  atanh x = symbFun "atanh" [x]

--------------------------------------------------------------------------------

class Floating a => Complex a
  where
    type RealPart a
    complex   :: RealPart a -> RealPart a -> a
    polar     :: RealPart a -> RealPart a -> a
    real      :: a -> RealPart a
    imag      :: a -> RealPart a
    magnitude :: a -> RealPart a
    phase     :: a -> RealPart a
    conjugate :: a -> a

instance Complex (V.SMTExpr Prim (Complex.Complex Float))
  where
    type RealPart (V.SMTExpr Prim (Complex.Complex Float)) = V.SMTExpr Prim Float
    complex   (Float x) (Float y) = ComplexFloat (complex x y)
    polar     (Float x) (Float y) = ComplexFloat (polar x y)
    real      (ComplexFloat x)    = Float (real x)
    imag      (ComplexFloat x)    = Float (imag x)
    magnitude (ComplexFloat x)    = Float (magnitude x)
    phase     (ComplexFloat x)    = Float (phase x)
    conjugate (ComplexFloat x)    = ComplexFloat (conjugate x)

instance Complex (V.SMTExpr Prim (Complex.Complex Double))
  where
    type RealPart (V.SMTExpr Prim (Complex.Complex Double)) = V.SMTExpr Prim Double
    complex   (Double x) (Double y) = ComplexDouble (complex x y)
    polar     (Double x) (Double y) = ComplexDouble (polar x y)
    real      (ComplexDouble x)     = Double (real x)
    imag      (ComplexDouble x)     = Double (imag x)
    magnitude (ComplexDouble x)     = Double (magnitude x)
    phase     (ComplexDouble x)     = Double (phase x)
    conjugate (ComplexDouble x)     = ComplexDouble (conjugate x)

witnessComplex :: (SoftwarePrimType a, SoftwarePrimType (Complex.Complex a)) =>
  Prim (Complex.Complex a) ->
  Dict ( Floating (V.SMTExpr Prim a)
       , Complex  (V.SMTExpr Prim (Complex.Complex a))
       , RealPart (V.SMTExpr Prim (Complex.Complex a)) ~ V.SMTExpr Prim a)
witnessComplex (_ :: Prim (Complex.Complex a)) =
  case softwareRep :: SoftwarePrimTypeRep (Complex.Complex a) of
    ComplexFloatST  -> Dict
    ComplexDoubleST -> Dict

witnessFractional :: (SoftwarePrimType a, Fractional a) =>
  Prim a ->
  Dict (Floating (V.SMTExpr Prim a))
witnessFractional (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
    FloatST         -> Dict
    DoubleST        -> Dict
    ComplexFloatST  -> Dict
    ComplexDoubleST -> Dict

witnessIntegral :: (SoftwarePrimType a, Integral a) =>
  Prim a ->
  Dict (Integral (V.SMTExpr Prim a), Bits (V.SMTExpr Prim a))
witnessIntegral (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
  Int8ST   -> Dict
  Int16ST  -> Dict
  Int32ST  -> Dict
  Int64ST  -> Dict
  Word8ST  -> Dict
  Word16ST -> Dict
  Word32ST -> Dict
  Word64ST -> Dict

witnessBits :: (SoftwarePrimType a, Bits.Bits a) =>
  Prim a ->
  Dict ( Num a
       , Integral (V.SMTExpr Prim a)
       , Bits (V.SMTExpr Prim a))
witnessBits (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
  Int8ST   -> Dict
  Int16ST  -> Dict
  Int32ST  -> Dict
  Int64ST  -> Dict
  Word8ST  -> Dict
  Word16ST -> Dict
  Word32ST -> Dict
  Word64ST -> Dict

--------------------------------------------------------------------------------

toRat :: (SoftwarePrimType a, Fractional a) => V.SMTExpr Prim a -> Rat
toRat (x :: V.SMTExpr Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
  FloatST         -> let Float         (Symbolic y) = x in y
  DoubleST        -> let Double        (Symbolic y) = x in y
  ComplexFloatST  -> let ComplexFloat  (Symbolic y) = x in y
  ComplexDoubleST -> let ComplexDouble (Symbolic y) = x in y

fromRat :: forall a. (SoftwarePrimType a, Num a) => Rat -> V.SMTExpr Prim a
fromRat x = case softwareRep :: SoftwarePrimTypeRep a of Int8ST -> Int8 (f2i x)
  where
    f2i :: forall s w. (Sign s, Width w) => Rat -> BV s w
    f2i (Rat x) = BV $ SMT.List [SMT.fam "int2bv" [width (undefined :: w)], SMT.fun "to_int" [x]]

i2n :: forall a b.
  ( V.SMTEval Prim a, SoftwarePrimType a, Integral a
  , V.SMTEval Prim b, SoftwarePrimType b, Num b) =>
  V.SMTExpr Prim a ->
  V.SMTExpr Prim b
i2n x = toBV x $ case softwareRep :: SoftwarePrimTypeRep b of
  Int8ST   -> Int8   . i2i
  Int16ST  -> Int16  . i2i
  Int32ST  -> Int32  . i2i
  Int64ST  -> Int64  . i2i
  Word8ST  -> Word8  . i2i
  Word16ST -> Word16 . i2i
  Word32ST -> Word32 . i2i
  Word64ST -> Word64 . i2i
  FloatST  -> Float  . Symbolic . i2f
  DoubleST -> Double . Symbolic . i2f
  ComplexFloatST  -> ComplexFloat  . Symbolic . i2f
  ComplexDoubleST -> ComplexDouble . Symbolic . i2f
  where
    toBV :: forall a b. (V.SMTEval Prim a, SoftwarePrimType a, Integral a) =>
      V.SMTExpr Prim a -> (forall s w. (Sign s, Width w) => BV s w -> b) -> b
    toBV (x :: V.SMTExpr Prim a) k = case softwareRep :: SoftwarePrimTypeRep a of
      Int8ST   -> let Int8   y = x in k y
      Int16ST  -> let Int16  y = x in k y
      Int32ST  -> let Int32  y = x in k y
      Int64ST  -> let Int64  y = x in k y
      Word8ST  -> let Word8  y = x in k y
      Word16ST -> let Word16 y = x in k y
      Word32ST -> let Word32 y = x in k y
      Word64ST -> let Word64 y = x in k y

    i2f :: (Sign s, Width w) => BV s w -> Rat
    i2f (BV x) = Rat (SMT.fun "to_real" [SMT.fun "bv2int" [x]])

    i2i :: forall s1 w1 s2 w2. (Sign s1, Width w1, Sign s2, Width w2) => BV s1 w1 -> BV s2 w2
    i2i x = case compare m n of
      LT | isSigned x -> V.fromSMT (SMT.signExtend (n-m) (V.toSMT x))
         | otherwise  -> V.fromSMT (SMT.zeroExtend (n-m) (V.toSMT x))
      EQ -> V.fromSMT (V.toSMT x)
      GT -> V.fromSMT (SMT.extract (V.toSMT x) (n-1) 0)
      where
        m = width (undefined :: w1)
        n = width (undefined :: w2)

--------------------------------------------------------------------------------

class SymbParam a => SymbComplex a
  where
    type SymbRealPart a

instance SymbComplex SymbComplexFloat
  where
    type SymbRealPart SymbComplexFloat  = SymbFloat

instance SymbComplex SymbComplexDouble
  where
    type SymbRealPart SymbComplexDouble = SymbDouble

instance SymbComplex a => Complex (Symbolic a)
  where
    type RealPart (Symbolic a) = Symbolic (SymbRealPart a)
    complex x y = symbFun "complex" [symbCast x, symbCast y]
    polar x y   = symbFun "polar" [symbCast x, symbCast y]
    real x      = symbCast (symbFun "real" [x])
    imag x      = symbCast (symbFun "imag" [x])
    magnitude x = symbCast (symbFun "magnitude" [x])
    phase x     = symbCast (symbFun "phase" [x])
    conjugate x = symbFun "conjugate" [x]

--------------------------------------------------------------------------------

declareSymbFun :: SymbParam a => String -> a ->
  [SMT.SExpr] -> SMT.SExpr -> SMT.SMT ()
declareSymbFun name (_ :: a) args res =
  S.void $ SMT.declareFun (symbType (undefined :: a) ++ "-" ++ name) args res

declareSymbArith :: SymbParam a => a -> SMT.SMT ()
declareSymbArith x = do
  declareSymbFun "+" x     [SMT.tReal, SMT.tReal] SMT.tReal
  declareSymbFun "-" x     [SMT.tReal, SMT.tReal] SMT.tReal
  declareSymbFun "*" x     [SMT.tReal, SMT.tReal] SMT.tReal
  declareSymbFun "/" x     [SMT.tReal, SMT.tReal] SMT.tReal
  declareSymbFun "exp" x   [SMT.tReal] SMT.tReal
  declareSymbFun "log" x   [SMT.tReal] SMT.tReal
  declareSymbFun "sqrt" x  [SMT.tReal] SMT.tReal
  declareSymbFun "pow" x   [SMT.tReal, SMT.tReal] SMT.tReal
  declareSymbFun "sin" x   [SMT.tReal] SMT.tReal
  declareSymbFun "cos" x   [SMT.tReal] SMT.tReal
  declareSymbFun "tan" x   [SMT.tReal] SMT.tReal
  declareSymbFun "asin" x  [SMT.tReal] SMT.tReal
  declareSymbFun "acos" x  [SMT.tReal] SMT.tReal
  declareSymbFun "atan" x  [SMT.tReal] SMT.tReal
  declareSymbFun "sinh" x  [SMT.tReal] SMT.tReal
  declareSymbFun "cosh" x  [SMT.tReal] SMT.tReal
  declareSymbFun "tanh" x  [SMT.tReal] SMT.tReal
  declareSymbFun "asinh" x [SMT.tReal] SMT.tReal
  declareSymbFun "acosh" x [SMT.tReal] SMT.tReal
  declareSymbFun "atanh" x [SMT.tReal] SMT.tReal

declareSymbComplex :: SymbParam a => a -> SMT.SMT ()
declareSymbComplex x = do
  declareSymbArith x
  declareSymbFun "complex" x   [SMT.tReal, SMT.tReal] SMT.tReal
  declareSymbFun "polar" x     [SMT.tReal, SMT.tReal] SMT.tReal
  declareSymbFun "real" x      [SMT.tReal] SMT.tReal
  declareSymbFun "imag" x      [SMT.tReal] SMT.tReal
  declareSymbFun "magnitude" x [SMT.tReal] SMT.tReal
  declareSymbFun "phase" x     [SMT.tReal] SMT.tReal
  declareSymbFun "conjugate" x [SMT.tReal] SMT.tReal

declareFeldsparGlobals :: SMT.SMT ()
declareFeldsparGlobals = do
  declareSymbArith   (undefined :: SymbFloat)
  declareSymbArith   (undefined :: SymbDouble)
  declareSymbComplex (undefined :: SymbComplexFloat)
  declareSymbComplex (undefined :: SymbComplexDouble)
  SMT.declareFun "skolem-int8"   [] (SMT.tBits 8)
  SMT.declareFun "skolem-int16"  [] (SMT.tBits 16)
  SMT.declareFun "skolem-int32"  [] (SMT.tBits 32)
  SMT.declareFun "skolem-int64"  [] (SMT.tBits 64)
  SMT.declareFun "skolem-word8"  [] (SMT.tBits 8)
  SMT.declareFun "skolem-word16" [] (SMT.tBits 16)
  SMT.declareFun "skolem-word32" [] (SMT.tBits 32)
  SMT.declareFun "skolem-word64" [] (SMT.tBits 64)
  return ()

instance FO.Substitute Prim
  where
    type SubstPred Prim = SoftwarePrimType
    subst sub (Prim exp) = Prim (everywhereUp f exp)
      where
        f :: ASTF SoftwarePrimDomain a -> ASTF SoftwarePrimDomain a
        f (Sym (FreeVar x :&: ty)) = case FO.lookupSubst sub (Imp.ValComp x) of
          Imp.ValComp y -> Sym (FreeVar y :&: ty)
          Imp.ValRun  z -> Sym (Lit z :&: ty)
        f (Sym (ArrIx iarr :&: ty) :$ i) = Sym (ArrIx iarr' :&: ty) :$ i
          where iarr' = FO.lookupSubst sub iarr
        f x = x

instance FO.TypeablePred SoftwarePrimType
  where
    witnessTypeable Dict = Dict

--------------------------------------------------------------------------------

instance V.SMTEval Prim Bool where
  fromConstant = Bool . SMT.bool
  witnessOrd _ = Dict

instance V.SMTEval Prim Int8 where
  fromConstant = Int8 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-int8" [])

instance V.SMTEval Prim Int16 where
  fromConstant = Int16 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-int16" [])

instance V.SMTEval Prim Int32 where
  fromConstant = Int32 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-int32" [])

instance V.SMTEval Prim Int64 where
  fromConstant = Int64 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-int64" [])

instance V.SMTEval Prim Word8 where
  fromConstant = Word8 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-word8" [])

instance V.SMTEval Prim Word16 where
  fromConstant = Word16 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-word16" [])

instance V.SMTEval Prim Word32 where
  fromConstant = Word32 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-word32" [])

instance V.SMTEval Prim Word64 where
  fromConstant = Word64 . fromIntegral
  witnessNum _ = Dict
  witnessOrd _ = Dict
  skolemIndex  = V.fromSMT (SMT.fun "skolem-word64" [])

instance V.SMTEval Prim Float where
  fromConstant = Float . fromRational . toRational
  witnessOrd _ = Dict
  witnessNum _ = Dict

instance V.SMTEval Prim Double where
  fromConstant = Double . fromRational . toRational
  witnessOrd _ = Dict
  witnessNum _ = Dict

instance V.SMTEval Prim (Complex.Complex Float) where
  fromConstant = ComplexFloat . fromComplexConstant
  witnessNum _ = Dict

instance V.SMTEval Prim (Complex.Complex Double) where
  fromConstant = ComplexDouble . fromComplexConstant
  witnessNum _ = Dict

--------------------------------------------------------------------------------

instance V.SMTEval1 Prim where
  type Pred Prim = SoftwarePrimType
  newtype SMTExpr Prim Bool   = Bool SMT.SExpr
    deriving (Typeable)
  newtype SMTExpr Prim Float  = Float  (Symbolic SymbFloat)
    deriving (Typeable, Num, Fractional, Floating, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Double = Double (Symbolic SymbDouble)
    deriving (Typeable, Num, Fractional, Floating, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim (Complex.Complex Float) =
      ComplexFloat (Symbolic SymbComplexFloat)
    deriving (Typeable, Num, Fractional, Floating, V.TypedSExpr)
  newtype SMTExpr Prim (Complex.Complex Double) =
      ComplexDouble (Symbolic SymbComplexDouble)
    deriving (Typeable, Num, Fractional, Floating, V.TypedSExpr)
  newtype SMTExpr Prim Int8   = Int8   (BV Signed W8)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Int16  = Int16  (BV Signed W16)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Int32  = Int32  (BV Signed W32)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Int64  = Int64  (BV Signed W64)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Word8  = Word8  (BV Unsigned W8)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Word16 = Word16 (BV Unsigned W16)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Word32 = Word32 (BV Unsigned W32)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
  newtype SMTExpr Prim Word64 = Word64 (BV Unsigned W64)
    deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)

  eval (Prim exp :: Prim a) =
    simpleMatch (\(exp :&: ty) -> case softwarePrimWitType ty of
      Dict -> case V.witnessPred (undefined :: Prim a) of
        Dict -> verifyPrim exp) exp

  witnessPred (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
    BoolST   -> Dict
    Int8ST   -> Dict
    Int16ST  -> Dict
    Int32ST  -> Dict
    Int64ST  -> Dict
    Word8ST  -> Dict
    Word16ST -> Dict
    Word32ST -> Dict
    Word64ST -> Dict
    FloatST  -> Dict
    DoubleST -> Dict
    ComplexFloatST  -> Dict
    ComplexDoubleST -> Dict

instance V.SMTOrd (V.SMTExpr Prim Bool) where
  Bool x .<.  Bool y = SMT.not x SMT..&&. y
  Bool x .>.  Bool y = x SMT..&&. SMT.not y
  Bool x .<=. Bool y = SMT.not x SMT..||. y
  Bool x .>=. Bool y = x SMT..||. SMT.not y

instance V.TypedSExpr (V.SMTExpr Prim Bool) where
  smtType _ = SMT.tBool
  toSMT (Bool x) = x
  fromSMT x = Bool x

--------------------------------------------------------------------------------

verifyPrim :: forall a .
  (SoftwarePrimType (DenResult a), V.SMTEval Prim (DenResult a), HasCallStack) =>
  SoftwarePrim a ->
  Args (AST SoftwarePrimDomain) a ->
  V.Verify (V.SMTExpr Prim (DenResult a))
verifyPrim (FreeVar x) _ = peekValue x
verifyPrim (Lit x) _     = return (V.fromConstant x)
verifyPrim Add (x :* y :* Nil)
  | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
    S.liftM2 (+) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Sub (x :* y :* Nil)
  | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
    S.liftM2 (-) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Mul (x :* y :* Nil)
  | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
    S.liftM2 (*) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Neg (x :* Nil)
  | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
    fmap negate (V.eval (Prim x))
verifyPrim Abs (x :* Nil)
  | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
    fmap abs (V.eval (Prim x))
verifyPrim Sign (x :* Nil)
  | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
    fmap signum (V.eval (Prim x))
verifyPrim Div (x :* y :* Nil)
  | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
    S.liftM2 div (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Mod (x :* y :* Nil)
  | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
    S.liftM2 mod (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Quot (x :* y :* Nil)
  | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
    S.liftM2 quot (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Rem (x :* y :* Nil)
  | Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
    S.liftM2 rem (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim FDiv (x :* y :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    S.liftM2 (/) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Pi Nil
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    return pi
verifyPrim Exp (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap exp (V.eval (Prim x))
verifyPrim Log (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap log (V.eval (Prim x))
verifyPrim Sqrt (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap sqrt (V.eval (Prim x))
verifyPrim Pow (x :* y :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    S.liftM2 (**) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Sin (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap sin (V.eval (Prim x))
verifyPrim Cos (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap cos (V.eval (Prim x))
verifyPrim Tan (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap tan (V.eval (Prim x))
verifyPrim Asin (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap asin (V.eval (Prim x))
verifyPrim Acos (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap acos (V.eval (Prim x))
verifyPrim Atan (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap atan (V.eval (Prim x))
verifyPrim Sinh (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap sinh (V.eval (Prim x))
verifyPrim Cosh (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap cosh (V.eval (Prim x))
verifyPrim Tanh (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap tanh (V.eval (Prim x))
verifyPrim Asinh (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap asinh (V.eval (Prim x))
verifyPrim Acosh (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap acosh (V.eval (Prim x))
verifyPrim Atanh (x :* Nil)
  | Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
    fmap atanh (V.eval (Prim x))
verifyPrim Complex (x :* y :* Nil)
  | Dict <- witnessComplex (undefined :: Prim (DenResult a)) =
    S.liftM2 complex (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Polar (x :* y :* Nil)
  | Dict <- witnessComplex (undefined :: Prim (DenResult a)) =
    S.liftM2 polar (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Real ((x :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- witnessComplex (undefined :: Prim b) =
    fmap real (V.eval (Prim x))
verifyPrim Imag ((x :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- witnessComplex (undefined :: Prim b) =
    fmap imag (V.eval (Prim x))
verifyPrim Magnitude ((x :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- witnessComplex (undefined :: Prim b) =
    fmap magnitude (V.eval (Prim x))
verifyPrim Phase ((x :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- witnessComplex (undefined :: Prim b) =
    fmap phase (V.eval (Prim x))
verifyPrim Conjugate ((x :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- witnessComplex (undefined :: Prim b) =
    fmap conjugate (V.eval (Prim x))
verifyPrim I2N ((x :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- V.witnessNum (undefined :: Prim b) = do
    fmap i2n (V.eval (Prim x))
verifyPrim I2B ((x :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- V.witnessNum (undefined :: Prim b) = do
    x <- V.eval (Prim x)
    return (V.fromSMT (SMT.not (x V..==. 0)))
verifyPrim B2I (x :* Nil)
  | Dict <- V.witnessNum (undefined :: Prim (DenResult a)) = do
    x <- V.eval (Prim x)
    return (V.smtIte (V.toSMT x) 1 0)
verifyPrim Round ((x :: ASTF SoftwarePrimDomain b) :* Nil) = do
  x <- V.eval (Prim x)
  return (fromRat (toRat x))
verifyPrim Not (x :* Nil) =
  fmap (V.fromSMT . SMT.not . V.toSMT) (V.eval (Prim x))
verifyPrim And (x :* y :* Nil) = do
  x <- V.eval (Prim x)
  y <- V.eval (Prim y)
  return (V.fromSMT (V.toSMT x SMT..&&. V.toSMT y))
verifyPrim Or (x :* y :* Nil) = do
  x <- V.eval (Prim x)
  y <- V.eval (Prim y)
  return (V.fromSMT (V.toSMT x SMT..||. V.toSMT y))
verifyPrim Eq ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b) =
    fmap V.fromSMT (S.liftM2 (V..==.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Neq ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b) =
    fmap V.fromSMT (S.liftM2 (./=.) (V.eval (Prim x)) (V.eval (Prim y)))
  where
    x ./=. y = SMT.not (x V..==. y)
verifyPrim Lt ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- V.witnessOrd  (undefined :: Prim b) =
    fmap V.fromSMT (S.liftM2 (V..<.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Gt ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- V.witnessOrd  (undefined :: Prim b) =
    fmap V.fromSMT (S.liftM2 (V..>.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Lte ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- V.witnessOrd  (undefined :: Prim b) =
    fmap V.fromSMT (S.liftM2 (V..<=.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Gte ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
  | Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- V.witnessOrd  (undefined :: Prim b) =
    fmap V.fromSMT (S.liftM2 (V..>=.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim BitAnd (x :* y :* Nil)
  | Dict <- witnessBits (undefined :: Prim (DenResult a)) =
    S.liftM2 (.&.) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim BitOr (x :* y :* Nil)
  | Dict <- witnessBits (undefined :: Prim (DenResult a)) =
    S.liftM2 (.|.) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim BitXor (x :* y :* Nil)
  | Dict <- witnessBits (undefined :: Prim (DenResult a)) =
    S.liftM2 xor (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim BitCompl (x :* Nil)
  | Dict <- witnessBits (undefined :: Prim (DenResult a)) =
    fmap complement (V.eval (Prim x))
verifyPrim ShiftL (x :* (y :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- witnessBits (undefined :: Prim (DenResult a)),
    Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- witnessIntegral (undefined :: Prim b) = do
    -- todo: should check for undefined behaviour
    x <- V.eval (Prim x)
    y <- V.eval (Prim y)
    return (shiftL x (i2n y))
verifyPrim ShiftR (x :* (y :: ASTF SoftwarePrimDomain b) :* Nil)
  | Dict <- witnessBits (undefined :: Prim (DenResult a)),
    Dict <- V.witnessPred (undefined :: Prim b),
    Dict <- witnessIntegral (undefined :: Prim b) = do
    -- todo: should check for undefined behaviour
    x <- V.eval (Prim x)
    y <- V.eval (Prim y)
    return (shiftR x (i2n y))
verifyPrim (ArrIx (Imp.IArrComp name :: Imp.IArr Index b)) (i :* Nil) = do
  i <- V.eval (Prim i)
  readArray name i
verifyPrim Cond (cond :* x :* y :* Nil) =
  S.liftM3 V.smtIte
    (fmap V.toSMT (V.eval (Prim cond)))
    (V.eval (Prim x))
    (V.eval (Prim y))
verifyPrim exp _ = error ("Unimplemented: " ++ show exp)

--------------------------------------------------------------------------------


text:
using namespace std;

constexpr int n = 10;
atomic_int number;
atomic_int next_number;
atomic_int turn_number[n];
int thread_nums;
mutex coutMutex;

ostringstream data;

void func() {
    int i = thread_nums++;  //Intentional post-increment

    coutMutex.lock();
    cout << "Thread " << i << " reporting in." << endl;
    coutMutex.unlock();

    this_thread::sleep_for(chrono::milliseconds(rand() % 500 + 500));

    for (auto i = 0; i < 1000; i++) {
        //Take a ticket
        turn_number[i] = number.fetch_add(1);

        coutMutex.lock();
        cout << "t" << i << "\tturn: " << turn_number[i] << endl;
        coutMutex.unlock();

        this_thread::sleep_for(chrono::milliseconds(rand() % 500 + 500));

        while (turn_number[i] != next_number) {
            continue;
        }

        coutMutex.lock();
        cout << "t" << i << "\t+CS" << endl;
        coutMutex.unlock();

        //critical section
        data << " data_t" << i;

        //exit protocol
        next_number += 1;

        coutMutex.lock();
        cout << data.str() << endl;
        cout << "t" << i << "\tnext = " << next_number << endl;
        coutMutex.unlock();
    }
}

int main(int argc, char *argv[]) {
    srand(static_cast<unsigned int>(time(NULL)));

    data = ostringstream();

    thread_nums = 0;
    number = 1;
    next_number = 1;

    for (int i = 0; i < n; i++) {
        turn_number[i] = 0;
    }

    thread t1 = thread(func);
    thread t2 = thread(func);

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

    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
#import <IDEGit/GitOperation.h>

@interface GitFetchRemoteOriginOperation : GitOperation
{
}

- (void)parseData;
- (id)initWithRequest:(id)arg1;

@end


text:
Follow the guidelines below for building **Electron itself**, for the purposes of creating custom Electron binaries. For bundling and distributing your app code with the prebuilt Electron binaries, see the [application distribution][application-distribution] guide.

[application-distribution]: ../tutorial/application-distribution.md

## Platform prerequisites

Check the build prerequisites for your platform before proceeding

* [macOS](build-instructions-macos.md#prerequisites)
* [Linux](build-instructions-linux.md#prerequisites)
* [Windows](build-instructions-windows.md#prerequisites)

## Build Tools

[Electron's Build Tools](https://github.com/electron/build-tools) automate much of the setup for compiling Electron from source with different configurations and build targets. If you wish to set up the environment manually, the instructions are listed below.

## GN prerequisites

You'll need to install [`depot_tools`][depot-tools], the toolset
used for fetching Chromium and its dependencies.

Also, on Windows, you'll need to set the environment variable
`DEPOT_TOOLS_WIN_TOOLCHAIN=0`. To do so, open `Control Panel` → `System and
Security` → `System` → `Advanced system settings` and add a system variable
`DEPOT_TOOLS_WIN_TOOLCHAIN` with value `0`.  This tells `depot_tools` to use
your locally installed version of Visual Studio (by default, `depot_tools` will
try to download a Google-internal version that only Googlers have access to).

[depot-tools]: https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up

### Setting up the git cache

If you plan on checking out Electron more than once (for example, to have
multiple parallel directories checked out to different branches), using the git
cache will speed up subsequent calls to `gclient`. To do this, set a
`GIT_CACHE_PATH` environment variable:

```sh
$ export GIT_CACHE_PATH="${HOME}/.git_cache"
$ mkdir -p "${GIT_CACHE_PATH}"
# This will use about 16G.
```

## Getting the code

```sh
$ mkdir electron && cd electron
$ gclient config --name "src/electron" --unmanaged https://github.com/electron/electron
$ gclient sync --with_branch_heads --with_tags
# This will take a while, go get a coffee.
```

> Instead of `https://github.com/electron/electron`, you can use your own fork
> here (something like `https://github.com/<username>/electron`).

### A note on pulling/pushing

If you intend to `git pull` or `git push` from the official `electron`
repository in the future, you now need to update the respective folder's
origin URLs.

```sh
$ cd src/electron
$ git remote remove origin
$ git remote add origin https://github.com/electron/electron
$ git checkout master
$ git branch --set-upstream-to=origin/master
$ cd -
```

:memo: `gclient` works by checking a file called `DEPS` inside the
`src/electron` folder for dependencies (like Chromium or Node.js).
Running `gclient sync -f` ensures that all dependencies required
to build Electron match that file.

So, in order to pull, you'd run the following commands:

```sh
$ cd src/electron
$ git pull
$ gclient sync -f
```

## Building

```sh
$ cd src
$ export CHROMIUM_BUILDTOOLS_PATH=`pwd`/buildtools
$ gn gen out/Testing --args="import(\"//electron/build/args/testing.gn\") $GN_EXTRA_ARGS"
```

Or on Windows (without the optional argument):

```sh
$ cd src
$ set CHROMIUM_BUILDTOOLS_PATH=%cd%\buildtools
$ gn gen out/Testing --args="import(\"//electron/build/args/testing.gn\")"
```

This will generate a build directory `out/Testing` under `src/` with
the testing build configuration. You can replace `Testing` with another name,
but it should be a subdirectory of `out`.
Also you shouldn't have to run `gn gen` again—if you want to change the
build arguments, you can run `gn args out/Testing` to bring up an editor.

To see the list of available build configuration options, run `gn args
out/Testing --list`.

**For generating Testing build config of
Electron:**

```sh
$ gn gen out/Testing --args="import(\"//electron/build/args/testing.gn\") $GN_EXTRA_ARGS"
```

**For generating Release (aka "non-component" or "static") build config of
Electron:**

```sh
$ gn gen out/Release --args="import(\"//electron/build/args/release.gn\") $GN_EXTRA_ARGS"
```

**To build, run `ninja` with the `electron` target:**
Nota Bene: This will also take a while and probably heat up your lap.

For the testing configuration:

```sh
$ ninja -C out/Testing electron
```

For the release configuration:

```sh
$ ninja -C out/Release electron
```

This will build all of what was previously 'libchromiumcontent' (i.e. the
`content/` directory of `chromium` and its dependencies, incl. WebKit and V8),
so it will take a while.

The built executable will be under `./out/Testing`:

```sh
$ ./out/Testing/Electron.app/Contents/MacOS/Electron
# or, on Windows
$ ./out/Testing/electron.exe
# or, on Linux
$ ./out/Testing/electron
```

### Packaging

On linux, first strip the debugging and symbol information:

```sh
electron/script/strip-binaries.py -d out/Release
```

To package the electron build as a distributable zip file:

```sh
ninja -C out/Release electron:electron_dist_zip
```

### Cross-compiling

To compile for a platform that isn't the same as the one you're building on,
set the `target_cpu` and `target_os` GN arguments. For example, to compile an
x86 target from an x64 host, specify `target_cpu = "x86"` in `gn args`.

```sh
$ gn gen out/Testing-x86 --args='... target_cpu = "x86"'
```

Not all combinations of source and target CPU/OS are supported by Chromium.

| Host        | Target        | Status               |
|-------------|---------------|----------------------|
| Windows x64 | Windows arm64 | Experimental         |
| Windows x64 | Windows x86   | Automatically tested |
| Linux x64   | Linux x86     | Automatically tested |

If you test other combinations and find them to work, please update this document :)

See the GN reference for allowable values of [`target_os`][target_os values]
and [`target_cpu`][target_cpu values].

[target_os values]: https://gn.googlesource.com/gn/+/master/docs/reference.md#built_in-predefined-variables-target_os_the-desired-operating-system-for-the-build-possible-values
[target_cpu values]: https://gn.googlesource.com/gn/+/master/docs/reference.md#built_in-predefined-variables-target_cpu_the-desired-cpu-architecture-for-the-build-possible-values

#### Windows on Arm (experimental)

To cross-compile for Windows on Arm, [follow Chromium's guide](https://chromium.googlesource.com/chromium/src/+/refs/heads/master/docs/windows_build_instructions.md#Visual-Studio) to get the necessary dependencies, SDK and libraries, then build with `ELECTRON_BUILDING_WOA=1` in your environment before running `gclient sync`.

```bat
set ELECTRON_BUILDING_WOA=1
gclient sync -f --with_branch_heads --with_tags
```

Or (if using PowerShell):

```powershell
$env:ELECTRON_BUILDING_WOA=1
gclient sync -f --with_branch_heads --with_tags
```

Next, run `gn gen` as above with `target_cpu="arm64"`.

## Tests

To run the tests, you'll first need to build the test modules against the
same version of Node.js that was built as part of the build process. To
generate build headers for the modules to compile against, run the following
under `src/` directory.

```sh
$ ninja -C out/Testing third_party/electron_node:headers
```

You can now [run the tests](testing.md#unit-tests).

If you're debugging something, it can be helpful to pass some extra flags to
the Electron binary:

```sh
$ npm run test -- \
  --enable-logging -g 'BrowserWindow module'
```

## Sharing the git cache between multiple machines

It is possible to share the gclient git cache with other machines by exporting it as
SMB share on linux, but only one process/machine can be using the cache at a
time. The locks created by git-cache script will try to prevent this, but it may
not work perfectly in a network.

On Windows, SMBv2 has a directory cache that will cause problems with the git
cache script, so it is necessary to disable it by setting the registry key

```sh
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Lanmanworkstation\Parameters\DirectoryCacheLifetime
```

to 0. More information: https://stackoverflow.com/a/9935126

This can be set quickly in powershell (ran as administrator):

```powershell
New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\Lanmanworkstation\Parameters" -Name DirectoryCacheLifetime -Value 0 -PropertyType DWORD -Force
```

## Troubleshooting

### gclient sync complains about rebase

If `gclient sync` is interrupted the git tree may be left in a bad state, leading to a cryptic message when running `gclient sync` in the future:

```plaintext
2> Conflict while rebasing this branch.
2> Fix the conflict and run gclient again.
2> See man git-rebase for details.
```

If there are no git conflicts or rebases in `src/electron`, you may need to abort a `git am` in `src`:

```sh
$ cd ../
$ git am --abort
$ cd electron
$ gclient sync -f
```

### I'm being asked for a username/password for chromium-internal.googlesource.com

If you see a prompt for `Username for 'https://chrome-internal.googlesource.com':` when running `gclient sync` on Windows, it's probably because the `DEPOT_TOOLS_WIN_TOOLCHAIN` environment variable is not set to 0. Open `Control Panel` → `System and Security` → `System` → `Advanced system settings` and add a system variable
`DEPOT_TOOLS_WIN_TOOLCHAIN` with value `0`.  This tells `depot_tools` to use
your locally installed version of Visual Studio (by default, `depot_tools` will
try to download a Google-internal version that only Googlers have access to).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mozu.Api.Clients.Commerce.Fulfillment
{
	/// <summary>
	///
	/// </summary>
    public partial class ShipmentDataClient
    {

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <returns></returns>
		public static MozuClient<Dictionary<string, object>> GetShipmentDataClient(int shipmentNumber)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.GetShipmentDataUrl(shipmentNumber);
			const string verb = "GET";
			var mozuClient = new MozuClient<Dictionary<string, object>>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <param name="data"></param>
		/// <returns></returns>
		public static MozuClient<Dictionary<string, object>> ReplaceShipmentDataClient(int shipmentNumber, Dictionary<string, object> data)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.ReplaceShipmentDataUrl(shipmentNumber);
			const string verb = "PUT";
			var mozuClient = new MozuClient<Dictionary<string, object>>()
									.WithVerb(verb).WithResourceUrl(url)
									.WithBody(data);
			;
			return mozuClient;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <returns></returns>
		public static MozuClient<System.IO.Stream> DeleteShipmentDataClient(int shipmentNumber)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.DeleteShipmentDataUrl(shipmentNumber);
			const string verb = "DELETE";
			var mozuClient = new MozuClient<System.IO.Stream>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public static MozuClient<System.IO.Stream> DeleteShipmentDataByKeyClient(int shipmentNumber, string key)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.DeleteShipmentDataByKeyUrl(shipmentNumber, key);
			const string verb = "DELETE";
			var mozuClient = new MozuClient<System.IO.Stream>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <param name="lineId"></param>
		/// <returns></returns>
		public static MozuClient<Dictionary<string, object>> GetShipmentItemDataClient(int shipmentNumber, int lineId)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.GetShipmentItemDataUrl(shipmentNumber, lineId);
			const string verb = "GET";
			var mozuClient = new MozuClient<Dictionary<string, object>>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <param name="lineId"></param>
		/// <param name="data"></param>
		/// <returns></returns>
		public static MozuClient<Dictionary<string, object>> ReplaceShipmentItemDataClient(int shipmentNumber, int lineId, Dictionary<string, object> data)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.ReplaceShipmentItemDataUrl(shipmentNumber, lineId);
			const string verb = "PUT";
			var mozuClient = new MozuClient<Dictionary<string, object>>()
									.WithVerb(verb).WithResourceUrl(url)
									.WithBody(data);
			;
			return mozuClient;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <param name="lineId"></param>
		/// <returns></returns>
		public static MozuClient<System.IO.Stream> DeleteShipmentItemDataClient(int shipmentNumber, int lineId)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.DeleteShipmentItemDataUrl(shipmentNumber, lineId);
			const string verb = "DELETE";
			var mozuClient = new MozuClient<System.IO.Stream>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

		/// <summary>
		///
		/// </summary>
		/// <param name="shipmentNumber"></param>
		/// <param name="lineId"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public static MozuClient<System.IO.Stream> DeleteShipmentItemDataByKeyClient(int shipmentNumber,int lineId, string key)
		{
			var url = Mozu.Api.Urls.Commerce.Fulfillment.ShipmentDataUrl.DeleteShipmentItemDataByKeyUrl(shipmentNumber, lineId, key);
			const string verb = "DELETE";
			var mozuClient = new MozuClient<System.IO.Stream>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}
	}
}


text:
package org.jcodec.codecs.vpx.vp8.data;

import java.util.EnumSet;

import org.jcodec.codecs.vpx.vp8.enums.InitFlags;

/**
 * This class is part of JCodec ( www.jcodec.org ) This software is distributed
 * under FreeBSD License.
 *
 * The class is a direct java port of libvpx's
 * (https://github.com/webmproject/libvpx) relevant VP8 code with significant
 * java oriented refactoring.
 *
 * @author The JCodec project
 *
 */
public class CodecPriv {
    public EnumSet<InitFlags> init_flags = EnumSet.noneOf(InitFlags.class);

    public EncData enc=new EncData();
    public CodecAlgPRiv priv;
}


text:
<!doctype html>

    <title>Code coverage report for lib/authc/BasicApiAuthenticator.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / lib/authc/ BasicApiAuthenticator.js

        90.91%
        Statements
        20/22

        76.92%
        Branches
        10/13

        100%
        Functions
        3/3

        90.91%
        Lines
        20/22

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

1×
1×

1×
2×

2×

2×
2×
2×

2×

1×
2×

2×
2×
1×

1×

1×

1×
1×

1×

1×

'use strict';

var ApiAuthRequestError = require('../error/ApiAuthRequestError');
var AuthenticationResult = require('../resource/AuthenticationResult');

function BasicApiAuthenticator(application,authHeaderValue, ttl){
  var parts = new Buffer(authHeaderValue.replace(/Basic /i,''),'base64').toString('utf8').split(':');

  Iif(parts.length !== 2){
    return new ApiAuthRequestError({userMessage: 'Invalid Authorization value', statusCode: 400});
  }

  this.application = application;
  this.id = parts[0];
  this.secret = parts[1];

  this.ttl = ttl || 3600;
}

BasicApiAuthenticator.prototype.authenticate = function authenticate(callback) {
  var self = this;

  self.application.getApiKey(self.id,function(err,apiKey){
    if(err){
      callback(err.status===404 ? new ApiAuthRequestError({userMessage: 'Invalid Client Credentials', error: 'invalid_client',  statusCode: 401}) : err);
    }else{
      Eif(
        (apiKey.secret===self.secret) &&
        (apiKey.status==='ENABLED') &&
        (apiKey.account.status==='ENABLED')
      ){
        var authenticationResult = new AuthenticationResult(apiKey,self.application.dataStore);

        authenticationResult.application = self.application;
        authenticationResult.ttl = self.ttl;

        callback(null,authenticationResult);
      }else{
        callback(new ApiAuthRequestError({userMessage: 'Invalid Client Credentials', error: 'invalid_client',  statusCode: 401}));
      }
    }
  });
};

module.exports = BasicApiAuthenticator;

  Code coverage
  generated by istanbul at Thu Mar 24 2016 15:28:42 GMT-0700 (PDT)


text:
import unittest
from quepy.expression import Expression
from quepy.dsl import HasKeyword, FixedRelation, FixedType, \
    FixedDataRelation

class TestDSL(unittest.TestCase):
    def test_fixed_relation(self):

        class MyFixedRelation(FixedRelation):
            relation = u"uranium:blowtorch"

        empty = Expression()
        fixedinstance = MyFixedRelation(empty)

        head = fixedinstance.get_head()
        relations = [x[0] for x in fixedinstance.iter_edges(head)]

        self.assertIn(u"uranium:blowtorch", relations)

    def test_fixed_type(self):

        class MyFixedType(FixedType):
            fixedtype = u"uranium:blowtorch"
            fixedtyperelation = u"rdf:type"

        fixedinstance = MyFixedType()

        head = fixedinstance.get_head()
        edges = list(fixedinstance.iter_edges(head))

        self.assertEqual(len(edges), 1)
        self.assertIsInstance(edges[0][0], unicode)
        self.assertEqual(edges[0][0], u"rdf:type")
        self.assertIsInstance(edges[0][1], unicode)
        self.assertEqual(edges[0][1], u"uranium:blowtorch")

    def test_fixed_data_relation(self):

        class MyFixedDataRelation(FixedDataRelation):
            relation = u"uranium:blowtorch"

        fixedinstance = MyFixedDataRelation(u"soplete")
        head = fixedinstance.get_head()
        edges = list(fixedinstance.iter_edges(head))

        self.assertEqual(len(edges), 1)
        self.assertIsInstance(edges[0][0], unicode)
        self.assertEqual(edges[0][0], u"uranium:blowtorch")
        self.assertIsInstance(edges[0][1], unicode)
        self.assertEqual(edges[0][1], u"soplete")

    def test_has_keyword(self):

        HasKeyword.relation = u"uranium:keyword"
        keywordinstance = HasKeyword(u"soplete")

        head = keywordinstance.get_head()
        edges = list(keywordinstance.iter_edges(head))
        self.assertEqual(len(edges), 1)
        self.assertIsInstance(edges[0][0], unicode)
        self.assertEqual(edges[0][0], u"uranium:keyword")
        self.assertIsInstance(edges[0][1], unicode)
        self.assertEqual(edges[0][1], u'soplete')

        # With language
        HasKeyword.language = "en"
        keywordinstance = HasKeyword("soplete")

        head = keywordinstance.get_head()
        edges = list(keywordinstance.iter_edges(head))
        self.assertEqual(len(edges), 1)
        self.assertIsInstance(edges[0][1], unicode)
        self.assertEqual(edges[0][1], u'"soplete"@en')

        # With sanitize
        HasKeyword.sanitize = staticmethod(lambda x: x.upper())
        keywordinstance = HasKeyword(u"soplete")

        head = keywordinstance.get_head()
        edges = list(keywordinstance.iter_edges(head))
        self.assertEqual(len(edges), 1)
        self.assertIsInstance(edges[0][1], unicode)
        self.assertEqual(edges[0][1], u'"SOPLETE"@en')

if __name__ == "__main__":
    unittest.main()


text:
/*
Modified Fibonacci golden nuggets
Problem 140

Consider the infinite polynomial series AG(x) = xG1 + x2G2 + x3G3 + ..., where Gk is the kth term of the second order recurrence relation Gk = Gk1 + Gk2, G1 = 1 and G2 = 4; that is, 1, 4, 5, 9, 14, 23, ... .
For this problem we shall be concerned with values of x for which AG(x) is a positive integer.
The corresponding values of x for the first five natural numbers are shown below.
We shall call AG(x) a golden nugget if x is rational, because they become increasingly rarer; for example, the 20th golden nugget is 211345365.
Find the sum of the first thirty golden nuggets.
*/


text:
#region S# License

#endregion S# License
namespace StockSharp.Community
{
	using System;
	using System.Linq;

	using Ecng.Common;

	using StockSharp.Localization;

	/// <summary>
	/// The client for access to the StockSharp authentication service.
	/// </summary>
	public class AuthenticationClient : BaseServiceClient<IAuthenticationService>
	{
		static AuthenticationClient()
		{
			_instance = new Lazy<AuthenticationClient>(() => new AuthenticationClient());
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AuthenticationClient"/>.
		/// </summary>
		public AuthenticationClient()
			: this(new Uri("http://stocksharp.com/services/authenticationservice.svc"))
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AuthenticationClient"/>.
		/// </summary>
		/// <param name="address">Service address.</param>
		public AuthenticationClient(Uri address)
			: base(address, "authentication")
		{
			Credentials = new ServerCredentials();
		}

		private static readonly Lazy<AuthenticationClient> _instance;

		/// <summary>
		/// The common authorization client for the whole application.
		/// </summary>
		public static AuthenticationClient Instance => _instance.Value;

		/// <summary>
		/// Information about the login and password for access to the StockSharp.
		/// </summary>
		public ServerCredentials Credentials { get; }

		/// <summary>
		/// Has the client successfully authenticated.
		/// </summary>
		public bool IsLoggedIn { get; private set; }

		private Guid _sessionId;

		/// <summary>
		/// Session ID.
		/// </summary>
		public Guid SessionId
		{
			get
			{
				if (!IsLoggedIn)
					Login();

				return _sessionId;
			}
		}

		/// <summary>
		/// To log in.
		/// </summary>
		public void Login()
		{
			Login(Credentials.Login, Credentials.Password.To<string>());
		}

		/// <summary>
		/// To log in.
		/// </summary>
		/// <param name="login">Login.</param>
		/// <param name="password">Password.</param>
		public void Login(string login, string password)
		{
			if (login.IsEmpty())
				throw new ArgumentNullException(nameof(login));

			if (password.IsEmpty())
				throw new ArgumentNullException(nameof(password));

			var sessionId = Invoke(f => f.Login(login, password));

			if (sessionId == Guid.Empty)
				throw new InvalidOperationException(LocalizedStrings.UnknownServerError);

			var bytes = sessionId.ToByteArray();
			if (bytes.Take(14).All(b => b == 0))
				((ErrorCodes)bytes[15]).ThrowIfError();

			_sessionId = sessionId;
			IsLoggedIn = true;
		}

		/// <summary>
		/// Logout.
		/// </summary>
		public void Logout()
		{
			Invoke(f => f.Logout(SessionId));
			IsLoggedIn = false;
		}

		/// <summary>
		/// Get a user id.
		/// </summary>
		/// <param name="sessionId">Session ID.</param>
		/// <returns>User id.</returns>
		public long GetId(Guid sessionId)
		{
			return Invoke(f => f.GetId(sessionId));
		}

		/// <summary>
		/// Release resources.
		/// </summary>
		protected override void DisposeManaged()
		{
			if (IsLoggedIn)
				Logout();

			base.DisposeManaged();
		}
	}
}


text:
.. _poissonized_plancherel_measure:

Poissonized Plancherel measure
******************************

The poissonized Plancherel measure is a measure on partitions :math:`\lambda=(\lambda_1 \geq \lambda_2 \geq \cdots \geq 0)\in \mathbb{N}^{\mathbb{N}^*}`.
Samples from this measure can be obtained in the following way

- Sample :math:`N \sim \mathcal{P}(\theta)`
- Sample a uniform permutation :math:`\sigma\in \mathfrak{S}_N`
- Compute the sorting tableau :math:`P` associated to the RSK (`Robinson-Schensted-Knuth correspondence <https://en.wikipedia.org/wiki/Robinson%E2%80%93Schensted%E2%80%93Knuth_correspondence>`_) applied to :math:`\sigma`
- Consider only the shape :math:`\lambda` of :math:`P`.

Finally, the point process formed by :math:`\{\lambda_i - i + \frac12\}_{i\geq 1}` is a DPP on :math:`\mathbb{Z}+\frac12`.

.. :ref:`Fig. <poissonized_plancherel_plot>`

.. _poissonized_plancherel_plot:

.. plot:: plots/ex_plot_poissonized_plancherel.py

    Poissonized Plancherel measure

.. seealso::

    - :py:class:`~dppy.exotic_dpps.PoissonizedPlancherel`
    - :cite:`Bor09` Section 6


text:
#ifndef BOOST_FLYWEIGHT_DETAIL_HANDLE_FACTORY_ADAPTOR_HPP
#define BOOST_FLYWEIGHT_DETAIL_HANDLE_FACTORY_ADAPTOR_HPP

#if defined(_MSC_VER)&&(_MSC_VER>=1200)
#pragma once
#endif

/* Given a Factory and a Handle type constructible from and implicitly
 * convertible to Factory::handle_type, handle_factory_adaptor
 * adapts Factory to present Handle as the associated handle_type.
 */

namespace boost{

namespace flyweights{

namespace detail{

template<typename Factory,typename Handle,typename Entry>
struct handle_factory_adaptor:Factory
{
public:
  typedef Handle handle_type;

  handle_type insert(const Entry& x)
  {
    return static_cast<handle_type>(base().insert(x));
  }

private:
  Factory& base(){return *this;}
};

} /* namespace flyweights::detail */

} /* namespace flyweights */

} /* namespace boost */

#endif


text:
package org.sakaiproject.gradebookng.tool.actions;

import com.fasterxml.jackson.databind.JsonNode;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.Model;

import org.sakaiproject.gradebookng.tool.model.GbModalWindow;
import org.sakaiproject.gradebookng.tool.pages.GradebookPage;
import org.sakaiproject.gradebookng.tool.panels.RubricGradePanel;

public class ViewRubricGradeAction extends InjectableAction implements Serializable {

    @Override
    public ActionResponse handleEvent(final JsonNode params, final AjaxRequestTarget target) {
        final String assignmentId = params.get("assignmentId").asText();
        final String studentUuid = params.get("studentId").asText();

        final Map<String, Object> model = new HashMap<>();
        model.put("assignmentId", Long.valueOf(assignmentId));
        model.put("studentUuid", studentUuid);

        final GradebookPage gradebookPage = (GradebookPage) target.getPage();
        final GbModalWindow window = gradebookPage.getRubricGradeWindow();

        window.setAssignmentToReturnFocusTo(assignmentId);
        window.setStudentToReturnFocusTo(studentUuid);
        window.setContent(new RubricGradePanel(window.getContentId(), Model.ofMap(model), window));
        window.show(target);

        return new EmptyOkResponse();
    }
}


text:
using System.Collections.Generic;
using Shouldly.Tests.TestHelpers;

namespace Shouldly.Tests.Dictionaries.ShouldNotContainKey
{
    public class ClassScenario : ShouldlyShouldTestScenario
    {
        readonly Dictionary<MyThing, MyThing> _dictionary = new Dictionary<MyThing, MyThing>
        {
            {ThingKey, new MyThing()}
        };

        private static readonly MyThing ThingKey = new MyThing();

        protected override void ShouldThrowAWobbly()
        {
            _dictionary.ShouldNotContainKey(ThingKey);
        }

        protected override string ChuckedAWobblyErrorMessage
        {
            get { return "Dictionary \"_dictionary\" should not contain key \"Shouldly.Tests.TestHelpers.MyThing\" but does"; }
        }

        protected override void ShouldPass()
        {
            _dictionary.ShouldNotContainKey(new MyThing());
        }
    }
}


text:
package com.infrarch.engine.command;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.servlet.http.HttpServletRequest;

import com.infrarch.engine.AbstractCommand;
import com.infrarch.engine.Command;
import com.infrarch.engine.CommandManager;
import com.infrarch.engine.Engine;
import com.infrarch.engine.EngineUtils;
import com.infrarch.engine.Worker;
import com.infrarch.engine.constants.Cmd;
import com.infrarch.engine.constants.Field;
import com.infrarch.engine.constants.Response;

/**
 * {@code Cmd.SERVER_INFO}, {@code Cmd.SETTINGS_GET}, {@code Cmd.SETTINGS_SET},
 * {@code Cmd.LIST_SETTINGS}.
 *
 * @author Assen Antov
 * @version 1.0, 07/2016
 */
public class Settings extends AbstractCommand {

	// attribute names
	public static final String SERVER_IP = "serverIP";
	public static final String SERVER_HOST_NAME = "serverHostName";
	public static final String LOCAL_DATE_AND_TIME = "localDateAndTime";
	public static final String DISK_SPACE_FREE = "diskSpaceFree";
	public static final String DISK_SPACE_TAKEN = "diskSpaceTaken";
	public static final String WEB_SERVER_VERSION = "webServerVersion";
	public static final String JAVA_VERSION = "JavaVersion";
	public static final String SERVER_APPLICATION_ROOT = "serverApplicationRoot";
	public static final String DOCUMENT_ROOT = "documentRoot";
	public static final String CONFIG_ROOT = "configurationRoot";
	public static final String VERSION = "version";
	public static final String COMMANDS = "supportedCommands";

	private static final Settings instance = new Settings();

	private String hostName = null, serverIP = null;

	private Settings() {
	    try {
			InetAddress inetAddress = InetAddress.getLocalHost();
			hostName = inetAddress.getHostName();
	        serverIP = inetAddress.getHostAddress();
	    } catch (UnknownHostException e) {}
	}

	public static Command getInstance() {
		return instance;
	}

	@Override
	public String[] getSupportedCommands() {
		return new String[] { Cmd.SERVER_INFO, Cmd.SETTINGS_GET, Cmd.SETTINGS_SET, Cmd.LIST_SETTINGS };
	}

	@Override
	public void execute(HttpServletRequest request, JsonObject params, JsonObjectBuilder builder) throws Throwable {

		// Cmd.SERVER_INFO
		String cmdStr = params.getString(Cmd.Q_COMMAND);
		if (Cmd.SERVER_INFO.equalsIgnoreCase(cmdStr)) {

			JsonArrayBuilder cmds = Json.createArrayBuilder();
			String[] cmdStrings = CommandManager.getInstance().getSupportedCommands();
			for (String c: cmdStrings) cmds.add(c);

			builder
				.add(VERSION, Engine.VERSION)
				.add(COMMANDS, cmds)
				.add(DOCUMENT_ROOT, Worker.getDocRoot().getAbsolutePath())
				.add(CONFIG_ROOT, Worker.getConfigRoot().getAbsolutePath())
				.add(SERVER_APPLICATION_ROOT, request.getServletContext().getRealPath(""))
				.add(JAVA_VERSION, System.getProperty("java.version") + ", " + System.getProperty("java.vendor"))
				.add(WEB_SERVER_VERSION, request.getServletContext().getServerInfo())
				.add(DISK_SPACE_TAKEN, Worker.getSizeOnDisk())
				.add(DISK_SPACE_FREE, Worker.getDocRoot().getUsableSpace())
				.add(LOCAL_DATE_AND_TIME, EngineUtils.formatDate(new Date()));

			if (hostName != null && serverIP != null) builder.add(SERVER_HOST_NAME, hostName).add(SERVER_IP, serverIP);
		}

		// Cmd.LIST_SETTINGS
		else if (Cmd.LIST_SETTINGS.equalsIgnoreCase(cmdStr)) {
			String[] keys = Worker.getConfigKeys();
			for (String key: keys) {
				builder.add(key, Worker.getConfigProperty(key));
			}
		}

		// Cmd.SETTINGS_GET
		else if (Cmd.SETTINGS_GET.equalsIgnoreCase(cmdStr)) {

			// get the property name
			String property;
			try {
				property = params.getString(Cmd.Q_PROPERTY);
			} catch (NullPointerException e) {
				EngineUtils.putStatus(builder, Response.CODE_MISSING_PARAMETER);
				return;
			}
			if ("".equals(property)) {
				EngineUtils.putStatus(builder, Response.CODE_MISSING_PARAMETER);
				return;
			}
			property = EngineUtils.urlDecode(property);

			// get the property value
			String value = Worker.getConfigProperty(property);
			builder
				.add(Field.PROPERTY, property)
				.add(Field.VALUE, value);
		}

		// Cmd.SETTINGS_SET
		else if (Cmd.SETTINGS_SET.equalsIgnoreCase(cmdStr)) {

			// get the property name
			String property;
			try {
				property = params.getString(Cmd.Q_PROPERTY);
			} catch (NullPointerException e) {
				EngineUtils.putStatus(builder, Response.CODE_MISSING_PARAMETER);
				return;
			}
			if ("".equals(property)) {
				EngineUtils.putStatus(builder, Response.CODE_MISSING_PARAMETER);
				return;
			}
			property = EngineUtils.urlDecode(property);

			// get the property value
			String value;
			try {
				value = params.getString(Cmd.Q_VALUE);
			} catch (NullPointerException e) {
				EngineUtils.putStatus(builder, Response.CODE_MISSING_PARAMETER);
				return;
			}
			if ("".equals(value)) {
				EngineUtils.putStatus(builder, Response.CODE_MISSING_PARAMETER);
				return;
			}
			value = EngineUtils.urlDecode(value);

			// set the property value
			Worker.setConfigProperty(property, value);
		}

		else {
			EngineUtils.putStatus(builder, Response.CODE_UNRECOGNIZED_COMMAND);
			return;
		}

		EngineUtils.putStatus(builder, Response.CODE_OK);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="folder" namespace="/folder" extends="default">
    </package>
</struts>


text: DROP TABLE crates_categories;


text:
namespace MediaBrowser.Channels.TouTv
{
    internal class VideoUrl
    {
        public string Url { get; set; }
    }
}


text:
BOOST_PYTHON_MODULE(py_simulation)
{
    docstring_options local_docstring_options(true, true, false);

    exportSimulationService();
}


text:
Break a URL down into it's components and insert into a Logstash event

Version 0.2

# Can be used like this

	logstash -f example.conf --pluginpath .

# Where the configuration file could contain this:

	filter {
		url {
			source => "source_url_field_name"
			target => "target_field_name"
		}
	}

# Testing the plugin

	logstash rspec spec/filters/url.rb


text:
/*
File: XWindow.cpp
Sample: XWindow
Author: Jonathan Beverly
Description: Opens a single blank window using the XPlatformer framework.

Notes:
The XWindow sample makes use of the XInfo controller class.  The purpose of XInfo is to act as a controller
for handling a single xwindow.  It controls opening/closing/graphics and other aspects.  It removes a large
portion of the busy work associated with XLib functions and as a wrapper.

The sample provided below is designed to show how to perform a series of basic tasks using the XGameLib library.

The following code is based on demo code provided in the CS349 course. The code has been altered to fit the XGameLib approach.
*/

/// Standard Libraries
#include <list>
#include <cstdlib>
#include <iostream>
#include <unistd.h>

/// XLib Libraries
#include <X11/Xlib.h>
#include <X11/Xutil.h>

/// Project Libraries
#include "XInfo.h"

/*
* Start executing here.
*	First initialize xinfo (XWindows manager).
*	Next open window and prepare for commands.
*	Use xinfo to close window.
*/
int main(int argc, char* argv[])
{
	// initializes and creates new instance of xinfo window manager
	// xinfo manages xwindow related tasks (graphics/window management)
	XInfo* xinfo = new XInfo();
	xinfo->initialize(argc, argv);

	// opens the window that is controlled by xinfo
	xinfo->openw();

	// let server get set up before sending drawing commands
	sleep(2);

	// wait for user input to quit (using simple console command)
	std::cout << "press ENTER to exit";
	std::cin.get();

	// closes the window controlled by XInfo
	xinfo->close();
}


text:
package com.rabbitframework.dbase.dataaccess.datasource;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitframework.commons.utils.StringUtils;
import com.rabbitframework.dbase.dataaccess.DataSourceBean;
import com.rabbitframework.dbase.dataaccess.dialect.Dialect;
import com.rabbitframework.dbase.mapping.MappedStatement;
import com.rabbitframework.dbase.mapping.SqlCommendType;

/**
 * 主从数据源配置,所有写操作使用master,读操作使用slave 允许有多master/salve,使用
 * {@link RandomDataSourceFactory}随机获取{@link DataSourceFactory}
 * 在多master/salve数据源情况下,主要通过key来区分,key中只要包含有master/salve字符,程序将自动匹配
 * 当不匹配master/savle时,将默认同时都可以使用二者
 */
public class MasterSlaveDataSourceFactory implements DataSourceFactory {
	private static final Logger logger = LoggerFactory.getLogger(MasterSlaveDataSourceFactory.class);
	private final static String MASTER = "master";
	private final static String SLAVE = "slave";
	private DataSourceFactory masters = new RandomDataSourceFactory();
	private DataSourceFactory slaves = new RandomDataSourceFactory();

	@Override
	public void addDataSource(String key, DataSourceBean dataSourceBean) {
		if (StringUtils.isEmpty(key) || dataSourceBean == null) {
			throw new NullPointerException("DataSource add fail: key=" + key + ",DataDataSource=" + dataSourceBean);
		}
		String name = key.toLowerCase();
		if (name.contains(MASTER)) {
			masters.addDataSource(key, dataSourceBean);
		} else if (name.contains(SLAVE)) {
			slaves.addDataSource(key, dataSourceBean);
		} else {
			int index = name.lastIndexOf(MASTER);
			int index1 = name.lastIndexOf(SLAVE);
			if (index == -1 && index1 == -1) {
				slaves.addDataSource(key, dataSourceBean);
				masters.addDataSource(key, dataSourceBean);
			}
		}
	}

	@Override
	public DataSource getDataSource(MappedStatement mappedStatement) {
		SqlCommendType sqlCommendType = mappedStatement.getSqlCommendType();
		if (sqlCommendType == SqlCommendType.SELECT) {
			logger.debug("into slaves");
			return slaves.getDataSource(mappedStatement);
		} else {
			logger.debug("into master");
			return masters.getDataSource(mappedStatement);
		}
	}

	@Override
	public Dialect getDialect(MappedStatement mappedStatement) {
		SqlCommendType sqlCommendType = mappedStatement.getSqlCommendType();
		if (sqlCommendType == SqlCommendType.SELECT) {
			return slaves.getDialect(mappedStatement);
		} else {
			return masters.getDialect(mappedStatement);
		}
	}

}


text:
[![travis][travis]][travis-url]
[![test][test]][test-url]
[![prod][prod]][prod-url]
![nonprofit][nonprofit]

![logo][logo]

> Platform where college students can get development experience by working with nonprofits.

## Getting Started

:wave: Want to contribute to this project? Follow these steps to get started:

- **:computer: Environment Setup**: First, you're going to want to make sure your development environment is properly set up. Go ahead and read through our [development environment setup](docs/DEVELOPER.md) guide.

- **:pencil2: Contribute**: Once you're set up, you're ready to become a contributor. Make sure you read our [contributing guidelines](docs/CONTRIBUTING.md) before you start working on a story so that you can learn our workflows.

- **:european_castle: Project Architecture**: We've put together an [architecture guide](docs/ARCHITECTURE.md) to serve as a reference and help reduce the time it takes to familiarize yourself with this project's architecture and codebase.

- **:raising_hand: Questions & Problems**: If you're stuck on something, don't be afraid to ask around in [Slack](http://join-our-slack.code4socialgood.org/)! You can also check out the [docs](docs/), where there is a lot of helpful information including a list of [common problems](docs/PROBLEMS.md).

## Additional Information

Below is a cheatsheet for the scripts that can be found in `package.json`:

```bash
$ yarn                              # Install dependencies (npm install)
$ yarn start                        # Start all docker containers and app on port 3000 and on port 3001 via https w/ watch mode (npm start)
$ yarn stop                         # Stop all docker containers (npm stop)
$ yarn restart                      # Restart all docker containers and app (npm restart)
$ yarn test                         # Run linter, test build, and tests (npm test)
$ yarn e2e                          # Run end-to-end tests (npm run e2e)
$ yarn lint                         # Run linter (npm run lint)
$ yarn db <start/stop>              # Start/stop docker container with seeded MongoDB (npm run db -- <start/stop>)
$ yarn email <start/stop>           # Start/stop docker container with MailHog (npm run email -- <start/stop>)
$ yarn build                        # Generate distribution (npm run build)
```

*Although yarn is recommended, you may also use npm natively. The corresponding npm commands are in parenthesis above.*

[travis]: https://travis-ci.org/CodeForSocialGood/calltocode.org.svg
[travis-url]: https://travis-ci.org/CodeForSocialGood/calltocode.org

[test]: https://img.shields.io/badge/test-test.calltocode.org-orange.svg
[test-url]: https://test.calltocode.org

[prod]: https://img.shields.io/badge/prod-calltocode.org-orange.svg
[prod-url]: https://calltocode.org

[nonprofit]: https://img.shields.io/badge/project-nonprofit-ff69b4.svg

[logo]: /docs/media/logo.png


text:
[org.apache.struts.taglib.logic](../../../../../org/apache/struts/taglib/logic/package-summary.html.md)
|------------------------------------------------------------------------------------------------|
| Classes
  [CompareTagBase](CompareTagBase.html.md "class in org.apache.struts.taglib.logic")
  [ConditionalTagBase](ConditionalTagBase.html.md "class in org.apache.struts.taglib.logic")
  [EmptyTag](EmptyTag.html.md "class in org.apache.struts.taglib.logic")
  [EqualTag](EqualTag.html.md "class in org.apache.struts.taglib.logic")
  [ForwardTag](ForwardTag.html.md "class in org.apache.struts.taglib.logic")
  [GreaterEqualTag](GreaterEqualTag.html.md "class in org.apache.struts.taglib.logic")
  [GreaterThanTag](GreaterThanTag.html.md "class in org.apache.struts.taglib.logic")
  [IterateTag](IterateTag.html.md "class in org.apache.struts.taglib.logic")
  [IterateTei](IterateTei.html.md "class in org.apache.struts.taglib.logic")
  [LessEqualTag](LessEqualTag.html.md "class in org.apache.struts.taglib.logic")
  [LessThanTag](LessThanTag.html.md "class in org.apache.struts.taglib.logic")
  [MatchTag](MatchTag.html.md "class in org.apache.struts.taglib.logic")
  [MessagesNotPresentTag](MessagesNotPresentTag.html.md "class in org.apache.struts.taglib.logic")
  [MessagesPresentTag](MessagesPresentTag.html.md "class in org.apache.struts.taglib.logic")
  [NotEmptyTag](NotEmptyTag.html.md "class in org.apache.struts.taglib.logic")
  [NotEqualTag](NotEqualTag.html.md "class in org.apache.struts.taglib.logic")
  [NotMatchTag](NotMatchTag.html.md "class in org.apache.struts.taglib.logic")
  [NotPresentTag](NotPresentTag.html.md "class in org.apache.struts.taglib.logic")
  [PresentTag](PresentTag.html.md "class in org.apache.struts.taglib.logic")
  [RedirectTag](RedirectTag.html.md "class in org.apache.struts.taglib.logic")                      |


text:
class AggregationClient
  include Configurable

  self.config_file = "aggregation_api"
  self.api_prefix = "aggregation_api"

  configure :host
  configure :user_id, key: :user, type: :integer
  configure :application_id, key: :application, type: :integer

  attr_reader :connection

  def initialize(adapter = Faraday.default_adapter)
    @connection = connect!(adapter)
  end

  def connect!(adapter)
    Faraday.new host do |faraday|
      faraday.response :json, content_type: /\bjson$/
      faraday.use :http_cache, store: Rails.cache, logger: Rails.logger
      faraday.adapter(*adapter)
    end
  end

  def generate_token
    Doorkeeper::AccessToken.create! do |ac|
      ac.resource_owner_id = user_id
      ac.application_id = application_id
      ac.expires_in = 1.day
      ac.scopes = "medium project public"
    end
  end

  def body(project, medium)
    {
      project_id: project.id,
      medium_href: medium.location,
      metadata: medium.metadata,
      token: generate_token.token
    }
  end

  def aggregate(project, medium)
    connection.post('/') do |req|
      req.headers["Accept"] = "application/json"
      req.headers["Content-Type"] = "application/json"
      req.body = body(project, medium).to_json
    end
  end
end


text:
namespace XMVVM.ExpressApp.Demos.Module.Web
{
    partial class XafMVVMAspNetModule
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            //
            // XafMVVMAspNetModule
            //
            this.RequiredModuleTypes.Add(typeof(XafMVVMModule));
            this.RequiredModuleTypes.Add(typeof(DevExpress.ExpressApp.Web.SystemModule.SystemAspNetModule));

        }

        #endregion
    }
}


text:
use std::any::{self, Any};
use std::ops::Deref;

use neon_runtime::raw;
use neon_runtime::external;

use crate::context::{Context, FinalizeContext};
use crate::context::internal::Env;
use crate::handle::{Managed, Handle};
use crate::types::internal::ValueInternal;
use crate::types::Value;

type BoxAny = Box<dyn Any + Send + 'static>;

/// A smart pointer for Rust data managed by the JavaScript engine.
///
/// The type `JsBox<T>` provides shared ownership of a value of type `T`,
/// allocated in the heap. The data is owned by the JavaScript engine and the
/// lifetime is managed by the JavaScript garbage collector.
///
/// Shared references in Rust disallow mutation by default, and `JsBox` is no
/// exception: you cannot generally obtain a mutable reference to something
/// inside a `JsBox`. If you need to mutate through a `JsBox`, use
/// [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html),
/// [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html),
/// or one of the other types that provide
/// [interior mutability](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html).
///
/// Values contained by a `JsBox` must implement the `Finalize` trait. `Finalize::finalize`
/// will execute with the value in a `JsBox` immediately before the `JsBox` is garbage
/// collected. If no additional finalization is necessary, an emply implementation may
/// be provided.
///
///
/// ## `Deref` behavior
///
/// `JsBox<T>` automatically dereferences to `T` (via the `Deref` trait), so
/// you can call `T`'s method on a value of type `JsBox<T>`.
///
/// ```rust
/// # use neon::prelude::*;
/// # fn my_neon_function(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let vec: Handle<JsBox<Vec<_>>> = cx.boxed(vec![1, 2, 3]);
///
/// println!("Length: {}", vec.len());
/// # Ok(cx.undefined())
/// # }
/// ```
///
/// ## Examples
///
/// Passing some immutable data between Rust and JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::path::{Path, PathBuf};
/// fn create_path(mut cx: FunctionContext) -> JsResult<JsBox<PathBuf>> {
///     let path = cx.argument::<JsString>(0)?.value(&mut cx);
///     let path = Path::new(&path).to_path_buf();
///
///     Ok(cx.boxed(path))
/// }
///
/// fn print_path(mut cx: FunctionContext) -> JsResult<JsUndefined> {
///     let path = cx.argument::<JsBox<PathBuf>>(0)?;
///
///     println!("{}", path.display());
///
///     Ok(cx.undefined())
/// }
/// ```
///
/// Passing a user defined struct wrapped in a `RefCell` for mutability. This
/// pattern is useful for creating classes in JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::cell::RefCell;
///
/// type BoxedPerson = JsBox<RefCell<Person>>;
///
/// struct Person {
///      name: String,
/// }
///
/// impl Finalize for Person {}
///
/// impl Person {
///     pub fn new(name: String) -> Self {
///         Person { name }
///     }
///
///     pub fn set_name(&mut self, name: String) {
///         self.name = name;
///     }
///
///     pub fn greet(&self) -> String {
///         format!("Hello, {}!", self.name)
///     }
/// }
///
/// fn person_new(mut cx: FunctionContext) -> JsResult<BoxedPerson> {
///     let name = cx.argument::<JsString>(0)?.value(&mut cx);
///     let person = RefCell::new(Person::new(name));
///
///     Ok(cx.boxed(person))
/// }
///
/// fn person_set_name(mut cx: FunctionContext) -> JsResult<JsUndefined> {
///     let person = cx.argument::<BoxedPerson>(0)?;
///     let mut person = person.borrow_mut();
///     let name = cx.argument::<JsString>(1)?.value(&mut cx);
///
///     person.set_name(name);
///
///     Ok(cx.undefined())
/// }
///
/// fn person_greet(mut cx: FunctionContext) -> JsResult<JsString> {
///     let person = cx.argument::<BoxedPerson>(0)?;
///     let person = person.borrow();
///     let greeting = person.greet();
///
///     Ok(cx.string(greeting))
/// }
pub struct JsBox<T: Send + 'static> {
    local: raw::Local,
    // Cached raw pointer to the data contained in the `JsBox`. This value is
    // required to implement `Deref` for `JsBox`. Unlike most `Js` types, `JsBox`
    // is not a transparent wrapper around a `napi_value` and cannot implement `This`.
    //
    // Safety: `JsBox` cannot verify the lifetime. Store a raw pointer to force
    // uses to be marked unsafe. In practice, it can be treated as `'static` but
    // should only be exposed as part of a `Handle` tied to a `Context` lifetime.
    // Safety: The value must not move on the heap; we must never give a mutable
    // reference to the data until the `JsBox` is no longer accessible.
    raw_data: *const T,
}

// Attempt to use a `napi_value` as a `napi_external` to unwrap a `BoxAny>
/// Safety: `local` must be a `napi_value` that is valid for the lifetime `'a`.
unsafe fn maybe_external_deref<'a>(env: Env, local: raw::Local) -> Option<&'a BoxAny> {
    external::deref::<BoxAny>(env.to_raw(), local)
        .map(|v| &*v)
}

// Custom `Clone` implementation since `T` might not be `Clone`
impl<T: Send + 'static> Clone for JsBox<T> {
    fn clone(&self) -> Self {
        JsBox {
            local: self.local,
            raw_data: self.raw_data,
        }
    }
}

impl<T: Send + 'static> Copy for JsBox<T> {}

impl<T: Send + 'static> Value for JsBox<T> { }

impl<T: Send + 'static> Managed for JsBox<T> {
    fn to_raw(self) -> raw::Local {
        self.local
    }

    fn from_raw(env: Env, local: raw::Local) -> Self {
        let raw_data = unsafe { maybe_external_deref(env, local) }
            .expect("Failed to unwrap napi_external as Box<Any>")
            .downcast_ref()
            .expect("Failed to downcast Any");

        Self {
            local,
            raw_data,
        }
    }
}

impl<T: Send + 'static> ValueInternal for JsBox<T> {
    fn name() -> String {
        any::type_name::<Self>().to_string()
    }

    fn is_typeof<Other: Value>(env: Env, other: Other) -> bool {
        let data = unsafe { maybe_external_deref(env, other.to_raw()) };

        data.map(|v| v.is::<T>()).unwrap_or(false)
    }

    fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> {
        let local = other.to_raw();
        let data = unsafe { maybe_external_deref(env, local) };

        // Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>`
        data.and_then(|v| v.downcast_ref())
            .map(|raw_data| Self {
                local,
                raw_data,
            })
    }
}

/// Values contained by a `JsBox` must be `Finalize + Send + 'static`
///
/// ### `Finalize`
///
/// The `neon::prelude::Finalize` trait provides a `finalize` method that will be called
/// immediately before the `JsBox` is garbage collected.
///
/// ### `Send`
///
/// `JsBox` may be moved across threads. It is important to guarantee that the
/// contents is also safe to move across threads.
///
/// ### `'static'
///
/// The lifetime of a `JsBox` is managed by the JavaScript garbage collector. Since Rust
/// is unable to verify the lifetime of the contents, references must be valid for the
/// entire duration of the program. This does not mean that the `JsBox` will be valid
/// until the application terminates, only that its lifetime is indefinite.
impl<T: Finalize + Send + 'static> JsBox<T> {
    /// Constructs a new `JsBox` containing `value`.
    pub fn new<'a, C>(cx: &mut C, value: T) -> Handle<'a, JsBox<T>>
    where
        C: Context<'a>,
        T: Send + 'static,
    {
        // This function will execute immediately before the `JsBox` is garbage collected.
        // It unwraps the `napi_external`, downcasts the `BoxAny` and moves the type
        // out of the `Box`. Lastly, it calls the trait method `Finalize::fianlize` of the
        // contained value `T`.
        fn finalizer<U: Finalize + 'static>(env: raw::Env, data: BoxAny) {
            let data = *data.downcast::<U>().unwrap();
            let env = unsafe { std::mem::transmute(env) };

            FinalizeContext::with(
                env,
                move |mut cx| data.finalize(&mut cx),
            );
        }

        let v = Box::new(value) as BoxAny;
        // Since this value was just constructed, we know it is `T`
        let raw_data = &*v as *const dyn Any as *const T;
        let local = unsafe {
            external::create(cx.env().to_raw(), v, finalizer::<T>)
        };

        Handle::new_internal(Self {
            local,
            raw_data,
        })
    }
}

impl<'a, T: Send + 'static> Deref for JsBox<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        // Safety: This depends on a `Handle<'a, JsBox<T>>` wrapper to provide
        // a proper lifetime.
        unsafe { &*self.raw_data }
    }
}

/// Finalize is executed on the main JavaScript thread and executed immediately
/// before garbage collection.
/// Values contained by a `JsBox` must implement `Finalize`.
///
/// ## Examples
///
/// `Finalize` provides a default implementation that does not perform any finalization.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {}
/// ```
///
/// A `finalize` method may be specified for performing clean-up operations before dropping
/// the contained value.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {
///     fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
///         let global = cx.global();
///         let emit = global
///             .get(cx, "emit")
///             .unwrap()
///             .downcast::<JsFunction, _>(cx)
///             .unwrap();
///
///         let args = vec![
///             cx.string("gc_point").upcast::<JsValue>(),
///             cx.number(self.0).upcast(),
///             cx.number(self.1).upcast(),
///         ];
///
///         emit.call(cx, global, args).unwrap();
///     }
/// }
/// ```
pub trait Finalize: Sized {
    fn finalize<'a, C: Context<'a>>(self, _: &mut C) {}
}

// Primitives

impl Finalize for bool {}
impl Finalize for char {}
impl Finalize for i8 {}
impl Finalize for i16 {}
impl Finalize for i32 {}
impl Finalize for i64 {}
impl Finalize for isize {}
impl Finalize for u8 {}
impl Finalize for u16 {}
impl Finalize for u32 {}
impl Finalize for u64 {}
impl Finalize for usize {}
impl Finalize for f32 {}
impl Finalize for f64 {}

// Common types

impl Finalize for String {}
impl Finalize for std::path::PathBuf {}

// Tuples

macro_rules! finalize_tuple_impls {
    ($( $name:ident )+) => {
        impl<$($name: Finalize),+> Finalize for ($($name,)+) {
            fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
                #![allow(non_snake_case)]
                let ($($name,)+) = self;
                ($($name.finalize(cx),)+);
            }
        }
    };
}

impl Finalize for () {}
finalize_tuple_impls! { T0 }
finalize_tuple_impls! { T0 T1 }
finalize_tuple_impls! { T0 T1 T2 }
finalize_tuple_impls! { T0 T1 T2 T3 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 T7 }

// Collections

impl<T: Finalize> Finalize for Vec<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        for item in self {
            item.finalize(cx);
        }
    }
}

// Smart Pointers

impl<T: Finalize> Finalize for std::boxed::Box<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        (*self).finalize(cx);
    }
}

impl<T: Finalize> Finalize for std::rc::Rc<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        if let Ok(v) = std::rc::Rc::try_unwrap(self) {
            v.finalize(cx);
        }
    }
}

impl<T: Finalize> Finalize for std::sync::Arc<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        if let Ok(v) = std::sync::Arc::try_unwrap(self) {
            v.finalize(cx);
        }
    }
}

impl<T: Finalize> Finalize for std::sync::Mutex<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        if let Ok(v) = self.into_inner() {
            v.finalize(cx);
        }
    }
}

impl<T: Finalize> Finalize for std::sync::RwLock<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        if let Ok(v) = self.into_inner() {
            v.finalize(cx);
        }
    }
}

impl<T: Finalize> Finalize for std::cell::Cell<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        self.into_inner().finalize(cx);
    }
}

impl<T: Finalize> Finalize for std::cell::RefCell<T> {
    fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
        self.into_inner().finalize(cx);
    }
}


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

import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.elasticsearch.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * ElasticsearchClusterConfigStatusMarshaller
 */
public class ElasticsearchClusterConfigStatusJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a JSONWriter
     */
    public void marshall(
            ElasticsearchClusterConfigStatus elasticsearchClusterConfigStatus,
            JSONWriter jsonWriter) {
        if (elasticsearchClusterConfigStatus == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonWriter.object();

            if (elasticsearchClusterConfigStatus.getOptions() != null) {
                jsonWriter.key("Options");
                ElasticsearchClusterConfigJsonMarshaller.getInstance()
                        .marshall(
                                elasticsearchClusterConfigStatus.getOptions(),
                                jsonWriter);
            }

            if (elasticsearchClusterConfigStatus.getStatus() != null) {
                jsonWriter.key("Status");
                OptionStatusJsonMarshaller.getInstance().marshall(
                        elasticsearchClusterConfigStatus.getStatus(),
                        jsonWriter);
            }

            jsonWriter.endObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static ElasticsearchClusterConfigStatusJsonMarshaller instance;

    public static ElasticsearchClusterConfigStatusJsonMarshaller getInstance() {
        if (instance == null)
            instance = new ElasticsearchClusterConfigStatusJsonMarshaller();
        return instance;
    }

}


text:
package i2am.Common;

import java.sql.*;

public class DbAdapter {
    private String host;
    private String databaseName;
    private String userID;
    private String password;
    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;

    private static final String GETTARGETQUERY = "SELECT F_TARGET FROM tbl_intelligent_engine WHERE F_SRC = (SELECT F_SRC FROM tbl_plan WHERE IDX = (SELECT F_PLAN FROM tbl_topology WHERE TOPOLOGY_NAME = ?))";
    private static final String GETTARGETINDEXQUERY = "SELECT COLUMN_INDEX FROM tbl_src_csv_schema WHERE IDX = ?";

    public DbAdapter(){
        host = "jdbc:mariadb://114.70.235.43:3306/";
        databaseName = "i2am";
        userID = "plan-manager";
        password = "dke214";
    }

    public void connect() throws SQLException {
        connection = DriverManager.getConnection(host + databaseName, userID, password);
    }

    public String getTarget(String topologyName) throws SQLException {
        preparedStatement = connection.prepareStatement(GETTARGETQUERY);
        preparedStatement.setString(1, topologyName);
        resultSet = preparedStatement.executeQuery();
        String targetName = resultSet.getString("F_TARGET");
        preparedStatement.close();
        resultSet.close();
        return targetName;
    }

    public int getTargetIndex(String targetName) throws SQLException {
        preparedStatement = connection.prepareStatement(GETTARGETINDEXQUERY);
        preparedStatement.setString(1, targetName);
        resultSet = preparedStatement.executeQuery();
        int targetIndex = resultSet.getInt("COLUMN_INDEX");
        preparedStatement.close();
        resultSet.close();
        return targetIndex-1; // MariDB's target index start from 1
    }
}


text:
Initiative

            =

            +

            +

                    <input type="number" ng-model="controller.model.initiativeBonus"/>

            Total

            DEX

            Alert (feat)

            Misc


text:
package undeclared

func errorParam() {
	var err error
	undefinedErrorParam(err) // want "(undeclared name|undefined): undefinedErrorParam"
}


text:
package com.jalotsav.aalayam.common;

import com.jalotsav.aalayam.Login_Email;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class UserSessionManager {

	// Shared Preferences reference
    SharedPreferences pref;

    // Editor reference for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static String PREFER_NAME;

    // All Shared Preferences Keys
    // Is User Login or not (make variable public to access from outside)
    private static final String IS_USER_LOGIN = "IsUserLoggedIn";

    // Dr_Id
    public static final String KEY_DR_ID = "dr_id";

    // Doctor Email
    public static final String KEY_EMAIL = "email";

    // Selected Position of Doctor NavigationDrawer
    public static final String KEY_SLCTD_POSTN_DCTR_NAVDRWR = "slctd_postn_dctr_navdrwr";

    // Doctor Email
    public static final String KEY_ISHOME_DCTR_NAVDRWR = "is_home_dctr_navdrwr";

    // Constructor
    public UserSessionManager(Context context){

    	this._context = context;
        PREFER_NAME = _context.getPackageName() + "_shrdprfrnc";
        pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
        editor = pref.edit();
        editor.apply();
    }

    // Create login session
    // Store DrId to SharedPreferences
    public void setDrId(int dr_id){

        editor.putInt(KEY_DR_ID, dr_id);
        editor.commit();
    }

    // Store Doctor Email to SharedPreferences
    public void setEmail(String email){

        editor.putString(KEY_EMAIL, email);
        editor.commit();
    }

	// Store Login Status to SharedPreferences
	public void setLoginStatusTrue(){

    	// Storing login value as TRUE
        editor.putBoolean(IS_USER_LOGIN, true);
	    editor.commit();
	}

	// Store Selected Position of Doctor NavigationDrawer to SharedPreferences
	public void setSlctdPostnDctrNavdrwr(int slctd_postn_dctr_navdrwr){

	    editor.putInt(KEY_SLCTD_POSTN_DCTR_NAVDRWR, slctd_postn_dctr_navdrwr);
	    editor.commit();
	}

    // Store Is Home status of Doctor NavigationDrawer to SharedPreferences
    public void setIsHomeDctrNavdrwr(boolean is_home_dctr_navdrwr){

        editor.putBoolean(KEY_ISHOME_DCTR_NAVDRWR, is_home_dctr_navdrwr);
        editor.commit();
    }

    /**
     * Check login method will check user login status
     * If false it will redirect user to login page
     * Else do anything
     * */
    public boolean checkLogin(){
        // Check login status
        if(!this.isUserLoggedIn()){

            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, Login_Email.class);
            /*
            // Closing all the Activities from stack
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            */
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            _context.startActivity(i);

            return false;
        }
        return true;
    }

    public int getDrId(){

    	int dr_id = pref.getInt(KEY_DR_ID, 0);
    	return dr_id;
    }

    public String getEmail(){

    	String email = pref.getString(KEY_EMAIL, "");
    	return email;
    }

    public int getSlctdPostnDctrNavdrwr(){

    	int slctd_postn_dctr_navdrwr = pref.getInt(KEY_SLCTD_POSTN_DCTR_NAVDRWR, 1);
    	return slctd_postn_dctr_navdrwr;
    }

    public boolean getIsHomeDctrNavdrwr(){

        boolean ishome_dctr_navdrwr = pref.getBoolean(KEY_ISHOME_DCTR_NAVDRWR, true);
        return ishome_dctr_navdrwr;
    }

    /**
     * Clear session details
     * */
    public void logoutUser(){

        // Clearing all user data from Shared Preferences
        editor.clear();
        editor.commit();

        // After logout redirect user to Login Activity
        Intent i = new Intent(_context, Login_Email.class);

        /*// Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);*/

        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }

    // Check for login
    public boolean isUserLoggedIn(){
        return pref.getBoolean(IS_USER_LOGIN, false);
    }
}


text:
Spellbook.Classes.QuantityInput
===============================

Markup
------

```haml
%h1
  %span.js-quantityInput-target $29
  %b Per Month

%form(action="")
  %fieldset.js-quantityInput-field
    %a.js-quantityInput-decrease(href="#") Decrease
    %input.js-quantityInput(type="text" value="1")
    %a.js-quantityInput-increase(href="#") Increase
```

JavaScript (CoffeeScript)
-------------------------

```coffeescript
new Spellbook.Classes.QuantityInput()
```


text:
<?php defined('C5_EXECUTE') or die("Access Denied."); ?>

<?php $this->inc('form.php');


text:
package labapi;

import lombok.EqualsAndHashCode;

import java.util.HashMap;
import java.util.Map;

@EqualsAndHashCode
public class UserQueryParameters {

    public static final String USER_TYPE = "usertype";
    public static final String MFA = "mfa";
    public static final String PROTECTION_POLICEY = "protectionpolicy";
    public static final String HOME_DOMAIN = "homedomain";
    public static final String HOME_UPN = "homeupn";
    public static final String B2C_PROVIDER = "b2cprovider";
    public static final String FEDERATION_PROVIDER = "federationprovider";
    public static final String AZURE_ENVIRONMENT = "azureenvironment";
    public static final String HOME_AZURE_ENVIRONMENT = "guesthomeazureenvironment";
    public static final String GUEST_HOME_DIN = "guesthomedin";
    public static final String SIGN_IN_AUDIENCE = "signInAudience";

    public Map<String, String> parameters = new HashMap<>();
}


text:
package com.castle.integration.dubbo.serialize.kryo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.serialize.ObjectInput;
import com.alibaba.dubbo.common.serialize.ObjectOutput;
import com.castle.integration.dubbo.serialize.OptimizedSerialization;

/**
 *
 * @author lishen
 */
public class KryoSerialization implements OptimizedSerialization {

    public byte getContentTypeId() {
        return 8;
    }

    public String getContentType() {
        return "x-application/kryo";
    }

    public ObjectOutput serialize(URL url, OutputStream out) throws IOException {
        return new KryoObjectOutput(out);
    }

    public ObjectInput deserialize(URL url, InputStream is) throws IOException {
        return new KryoObjectInput(is);
    }
}


text:
//apply css; currently done on loadHTMLString
/*document.getElementsByTagName('head')[0].innerHTML += '<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\">';*/

//urls with different image size
var sizes = /(.*) 300w, (.*) 600w, (.*) 1000w, (.*) 2000w/ ;
var k, imgs = document.getElementsByTagName('img');
prepareImages();

window.onresize = function() {prepareImages()};

//replace img source with url from srcset
function prepareImages() {
    for (var img, i = 0; img = imgs[i]; i++) {
        var width = img.clientWidth;
        if (width <= 300) {
            k = 1;
        } else if (width <= 600) {
            k = 2;
        } else if (width <= 1000) {
            k = 3;
        } else {
            k = 4;
        }
        img.src = sizes.exec(img.srcset)[k];
        img.srcset = ""
    }
}