text:
{-# LANGUAGE PatternGuards, ExistentialQuantification, CPP #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Core.Execute (execute) where

import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import IRTS.Lang(FDesc(..), FType(..))

import Idris.Primitives(Prim(..), primitives)

import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.CaseTree

import Idris.Error

import Debug.Trace

import Util.DynamicLinker
import Util.System

import Control.Applicative hiding (Const)
import Control.Exception
import Control.Monad.Trans
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
import Control.Monad hiding (forM)
import Data.Maybe
import Data.Bits
import Data.Traversable (forM)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Data.Map as M

#ifdef IDRIS_FFI
import Foreign.LibFFI
import Foreign.C.String
import Foreign.Marshal.Alloc (free)
import Foreign.Ptr
#endif

import System.IO

#ifndef IDRIS_FFI
execute :: Term -> Idris Term
execute tm = fail "libffi not supported, rebuild Idris with -f FFI"
#else
-- else is rest of file
readMay :: (Read a) => String -> Maybe a
readMay s = case reads s of
              [(x, "")] -> Just x
              _         -> Nothing

data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show

data ExecState = ExecState { exec_dynamic_libs :: [DynamicLib] -- ^ Dynamic libs from idris monad
                           , binderNames :: [Name] -- ^ Used to uniquify binders when converting to TT
                           }

data ExecVal = EP NameType Name ExecVal
             | EV Int
             | EBind Name (Binder ExecVal) (ExecVal -> Exec ExecVal)
             | EApp ExecVal ExecVal
             | EType UExp
             | EUType Universe
             | EErased
             | EConstant Const
             | forall a. EPtr (Ptr a)
             | EThunk Context ExecEnv Term
             | EHandle Handle

instance Show ExecVal where
  show (EP _ n _)        = show n
  show (EV i)            = "!!V" ++ show i ++ "!!"
  show (EBind n b body)  = "EBind " ++ show b ++ " <<fn>>"
  show (EApp e1 e2)      = show e1 ++ " (" ++ show e2 ++ ")"
  show (EType _)         = "Type"
  show (EUType _)        = "UType"
  show EErased           = "[__]"
  show (EConstant c)     = show c
  show (EPtr p)          = "<<ptr " ++ show p ++ ">>"
  show (EThunk _ env tm) = "<<thunk " ++ show env ++ "||||" ++ show tm ++ ">>"
  show (EHandle h)       = "<<handle " ++ show h ++ ">>"

toTT :: ExecVal -> Exec Term
toTT (EP nt n ty) = (P nt n) <$> (toTT ty)
toTT (EV i) = return $ V i
toTT (EBind n b body) = do n' <- newN n
                           body' <- body $ EP Bound n' EErased
                           b' <- fixBinder b
                           Bind n' b' <$> toTT body'
    where fixBinder (Lam t)       = Lam     <$> toTT t
          fixBinder (Pi i t k)    = Pi i    <$> toTT t <*> toTT k
          fixBinder (Let t1 t2)   = Let     <$> toTT t1 <*> toTT t2
          fixBinder (NLet t1 t2)  = NLet    <$> toTT t1 <*> toTT t2
          fixBinder (Hole t)      = Hole    <$> toTT t
          fixBinder (GHole i ns t) = GHole i ns <$> toTT t
          fixBinder (Guess t1 t2) = Guess   <$> toTT t1 <*> toTT t2
          fixBinder (PVar t)      = PVar    <$> toTT t
          fixBinder (PVTy t)      = PVTy    <$> toTT t
          newN n = do (ExecState hs ns) <- lift get
                      let n' = uniqueName n ns
                      lift (put (ExecState hs (n':ns)))
                      return n'
toTT (EApp e1 e2) = do e1' <- toTT e1
                       e2' <- toTT e2
                       return $ App Complete e1' e2'
toTT (EType u) = return $ TType u
toTT (EUType u) = return $ UType u
toTT EErased = return Erased
toTT (EConstant c) = return (Constant c)
toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env
                               return $ normalise ctxt env' tm
  where toBinder (n, v) = do v' <- toTT v
                             return (n, Let Erased v')
toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution."
toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution."

unApplyV :: ExecVal -> (ExecVal, [ExecVal])
unApplyV tm = ua [] tm
    where ua args (EApp f a) = ua (a:args) f
          ua args t = (t, args)

mkEApp :: ExecVal -> [ExecVal] -> ExecVal
mkEApp f [] = f
mkEApp f (a:args) = mkEApp (EApp f a) args

initState :: Idris ExecState
initState = do ist <- getIState
               return $ ExecState (idris_dynamic_libs ist) []

type Exec = ExceptT Err (StateT ExecState IO)

runExec :: Exec a -> ExecState -> IO (Either Err a)
runExec ex st = fst <$> runStateT (runExceptT ex) st

getExecState :: Exec ExecState
getExecState = lift get

putExecState :: ExecState -> Exec ()
putExecState = lift . put

execFail :: Err -> Exec a
execFail = throwE

execIO :: IO a -> Exec a
execIO = lift . lift

execute :: Term -> Idris Term
execute tm = do est <- initState
                ctxt <- getContext
                res <- lift . lift . flip runExec est $
                         do res <- doExec [] ctxt tm
                            toTT res
                case res of
                  Left err -> ierror err
                  Right tm' -> return tm'

ioWrap :: ExecVal -> ExecVal
ioWrap tm = mkEApp (EP (DCon 0 2 False) (sUN "prim__IO") EErased) [EErased, tm]

ioUnit :: ExecVal
ioUnit = ioWrap (EP Ref unitCon EErased)

type ExecEnv = [(Name, ExecVal)]

doExec :: ExecEnv -> Context -> Term -> Exec ExecVal
doExec env ctxt p@(P Ref n ty) | Just v <- lookup n env = return v
doExec env ctxt p@(P Ref n ty) =
    do let val = lookupDef n ctxt
       case val of
         [Function _ tm] -> doExec env ctxt tm
         [TyDecl _ _] -> return (EP Ref n EErased) -- abstract def
         [Operator tp arity op] -> return (EP Ref n EErased) -- will be special-cased later
         [CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
             doExec env ctxt tm
         [CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] -> return (EP Ref n EErased)
         [] -> execFail . Msg $ "Could not find " ++ show n ++ " in definitions."
         other | length other > 1 -> execFail . Msg $ "Multiple definitions found for " ++ show n
               | otherwise        -> execFail . Msg . take 500 $ "got to " ++ show other ++ " lookup up " ++ show n
doExec env ctxt p@(P Bound n ty) =
  case lookup n env of
    Nothing -> execFail . Msg $ "not found"
    Just tm -> return tm
doExec env ctxt (P (DCon a b u) n _) = return (EP (DCon a b u) n EErased)
doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased)
doExec env ctxt v@(V i) | i < length env = return (snd (env !! i))
                        | otherwise      = execFail . Msg $ "env too small"
doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v
                                             doExec ((n, v'):env) ctxt body
doExec env ctxt (Bind n (NLet t v) body) = trace "NLet" $ undefined
doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt)
                                        return $
                                          EBind n b' (\arg -> doExec ((n, arg):env) ctxt body)
doExec env ctxt a@(App _ _ _) =
  do let (f, args) = unApply a
     f' <- doExec env ctxt f
     args' <- case f' of
                (EP _ d _) | d == delay ->
                  case args of
                    [t,a,tm] -> do t' <- doExec env ctxt t
                                   a' <- doExec env ctxt a
                                   return [t', a', EThunk ctxt env tm]
                    _ -> mapM (doExec env ctxt) args -- partial applications are fine to evaluate
                fun' -> do mapM (doExec env ctxt) args
     execApp env ctxt f' args'
doExec env ctxt (Constant c) = return (EConstant c)
doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in
                              doExec env ctxt ((x:xs) !! i)
doExec env ctxt Erased = return EErased
doExec env ctxt Impossible = fail "Tried to execute an impossible case"
doExec env ctxt (TType u) = return (EType u)
doExec env ctxt (UType u) = return (EUType u)

execApp :: ExecEnv -> Context -> ExecVal -> [ExecVal] -> Exec ExecVal
execApp env ctxt v [] = return v -- no args is just a constant! can result from function calls
execApp env ctxt (EP _ f _) (t:a:delayed:rest)
  | f == force
  , (_, [_, _, EThunk tmCtxt tmEnv tm]) <- unApplyV delayed =
    do tm' <- doExec tmEnv tmCtxt tm
       execApp env ctxt tm' rest
execApp env ctxt (EP _ fp _) (ty:action:rest)
  | fp == upio,
    (prim__IO, [_, v]) <- unApplyV action
       = execApp env ctxt v rest

execApp env ctxt (EP _ fp _) args@(_:_:v:k:rest)
  | fp == piobind,
    (prim__IO, [_, v']) <- unApplyV v =
    do res <- execApp env ctxt k [v']
       execApp env ctxt res rest
execApp env ctxt con@(EP _ fp _) args@(tp:v:rest)
  | fp == pioret = execApp env ctxt (mkEApp con [tp, v]) rest

-- Special cases arising from not having access to the C RTS in the interpreter
execApp env ctxt f@(EP _ fp _) args@(xs:_:_:_:args')
    | fp == mkfprim,
      (ty : fn : w : rest) <- reverse args' =
          execForeign env ctxt getArity ty fn rest (mkEApp f args)
  where getArity = case unEList xs of
                        Just as -> length as
                        _ -> 0

execApp env ctxt c@(EP (DCon _ arity _) n _) args =
    do let args' = take arity args
       let restArgs = drop arity args
       execApp env ctxt (mkEApp c args') restArgs

execApp env ctxt c@(EP (TCon _ arity) n _) args =
    do let args' = take arity args
       let restArgs = drop arity args
       execApp env ctxt (mkEApp c args') restArgs

execApp env ctxt f@(EP _ n _) args
    | Just (res, rest) <- getOp n args = do r <- res
                                            execApp env ctxt r rest
execApp env ctxt f@(EP _ n _) args =
    do let val = lookupDef n ctxt
       case val of
         [Function _ tm] -> fail "should already have been eval'd"
         [TyDecl nt ty] -> return $ mkEApp f args
         [Operator tp arity op] ->
             if length args >= arity
               then let args' = take arity args in
                    case getOp n args' of
                      Just (res, []) -> do r <- res
                                           execApp env ctxt r (drop arity args)
                      _ -> return (mkEApp f args)
               else return (mkEApp f args)
         [CaseOp _ _ _ _ _ (CaseDefs _ ([], STerm tm) _ _)] -> -- nullary fun
             do rhs <- doExec env ctxt tm
                execApp env ctxt rhs args
         [CaseOp _ _ _ _ _ (CaseDefs _ (ns, sc) _ _)] ->
             do res <- execCase env ctxt ns sc args
                return $ fromMaybe (mkEApp f args) res
         thing -> return $ mkEApp f args
execApp env ctxt bnd@(EBind n b body) (arg:args) = do ret <- body arg
                                                      let (f', as) = unApplyV ret
                                                      execApp env ctxt f' (as ++ args)
execApp env ctxt app@(EApp _ _) args2 | (f, args1) <- unApplyV app = execApp env ctxt f (args1 ++ args2)
execApp env ctxt f args = return (mkEApp f args)

execForeign env ctxt arity ty fn xs onfail
    | Just (FFun "putStr" [(_, str)] _) <- foreignFromTT arity ty fn xs
       = case str of
           EConstant (Str arg) -> do execIO (putStr arg)
                                     execApp env ctxt ioUnit (drop arity xs)
           _ -> execFail . Msg $
                  "The argument to putStr should be a constant string, but it was " ++
                  show str ++
                  ". Are all cases covered?"
    | Just (FFun "putchar" [(_, ch)] _) <- foreignFromTT arity ty fn xs
           = case ch of
               EConstant (Ch c) -> do execIO (putChar c)
                                      execApp env ctxt ioUnit (drop arity xs)
               EConstant (I i)  -> do execIO (putChar (toEnum i))
                                      execApp env ctxt ioUnit (drop arity xs)
               _ -> execFail . Msg $
                      "The argument to putchar should be a constant character, but it was " ++
                      show str ++
                      ". Are all cases covered?"
    | Just (FFun "idris_readStr" [_, (_, handle)] _) <- foreignFromTT arity ty fn xs
           = case handle of
               EHandle h -> do contents <- execIO $ hGetLine h
                               execApp env ctxt (EConstant (Str (contents ++ "\n"))) (drop arity xs)
               _ -> execFail . Msg $
                      "The argument to idris_readStr should be a handle, but it was " ++
                      show handle ++
                      ". Are all cases covered?"
    | Just (FFun "getchar" _ _) <- foreignFromTT arity ty fn xs
           = do -- The C API returns an Int which Idris library code
                -- converts; thus, we must make an int here.
                ch <- execIO $ fmap (ioWrap . EConstant . I . fromEnum) getChar
                execApp env ctxt ch xs
    | Just (FFun "idris_time" _ _) <- foreignFromTT arity ty fn xs
           = do execIO $ fmap (ioWrap . EConstant . I . round) getPOSIXTime
    | Just (FFun "fileOpen" [(_,fileStr), (_,modeStr)] _) <- foreignFromTT arity ty fn xs
           = case (fileStr, modeStr) of
               (EConstant (Str f), EConstant (Str mode)) ->
                 do f <- execIO $
                         catch (do let m = case mode of
                                             "r"  -> Right ReadMode
                                             "w"  -> Right WriteMode
                                             "a"  -> Right AppendMode
                                             "rw" -> Right ReadWriteMode
                                             "wr" -> Right ReadWriteMode
                                             "r+" -> Right ReadWriteMode
                                             _    -> Left ("Invalid mode for " ++ f ++ ": " ++ mode)
                                   case fmap (openFile f) m of
                                     Right h -> do h' <- h
                                                   hSetBinaryMode h' True
                                                   return $ Right (ioWrap (EHandle h'), drop arity xs)
                                     Left err -> return $ Left err)
                               (\e -> let _ = ( e::SomeException)
                                      in return $ Right (ioWrap (EPtr nullPtr), drop arity xs))
                    case f of
                      Left err -> execFail . Msg $ err
                      Right (res, rest) -> execApp env ctxt res rest
               _ -> execFail . Msg $
                      "The arguments to fileOpen should be constant strings, but they were " ++
                      show fileStr ++ " and " ++ show modeStr ++
                      ". Are all cases covered?"
    | Just (FFun "fileEOF" [(_,handle)] _) <- foreignFromTT arity ty fn xs
           = case handle of
               EHandle h -> do eofp <- execIO $ hIsEOF h
                               let res = ioWrap (EConstant (I $ if eofp then 1 else 0))
                               execApp env ctxt res (drop arity xs)
               _ -> execFail . Msg $
                      "The argument to fileEOF should be a file handle, but it was " ++
                      show handle ++
                      ". Are all cases covered?"
    | Just (FFun "fileError" [(_,handle)] _) <- foreignFromTT arity ty fn xs
           = case handle of
             -- errors handled differently in Haskell than in C, so if
             -- there's been an error we'll have had an exception already.
             -- Therefore, assume we're okay.
               EHandle h -> do let res = ioWrap (EConstant (I 0))
                               execApp env ctxt res (drop arity xs)
               _ -> execFail . Msg $
                      "The argument to fileError should be a file handle, but it was " ++
                      show handle ++
                      ". Are all cases covered?"
    | Just (FFun "fileClose" [(_,handle)] _) <- foreignFromTT arity ty fn xs
           = case handle of
               EHandle h -> do execIO $ hClose h
                               execApp env ctxt ioUnit (drop arity xs)
               _ -> execFail . Msg $
                      "The argument to fileClose should be a file handle, but it was " ++
                      show handle ++
                      ". Are all cases covered?"

    | Just (FFun "isNull" [(_, ptr)] _) <- foreignFromTT arity ty fn xs
           = case ptr of
               EPtr p -> let res = ioWrap . EConstant . I $
                                   if p == nullPtr then 1 else 0
                         in execApp env ctxt res (drop arity xs)
               -- Handles will be checked as null pointers sometimes - but if we got a
               -- real Handle, then it's valid, so just return 1.
               EHandle h -> let res = ioWrap . EConstant . I $ 0
                            in execApp env ctxt res (drop arity xs)
               -- A foreign-returned char* has to be tested for NULL sometimes
               EConstant (Str s) -> let res = ioWrap . EConstant . I $ 0
                                    in execApp env ctxt res (drop arity xs)
               _ -> execFail . Msg $
                      "The argument to isNull should be a pointer or file handle or string, but it was " ++
                      show ptr ++
                      ". Are all cases covered?"

-- Right now, there's no way to send command-line arguments to the executor,
-- so just return 0.
execForeign env ctxt arity ty fn xs onfail
    | Just (FFun "idris_numArgs" _ _) <- foreignFromTT arity ty fn xs
           = let res = ioWrap . EConstant . I $ 0
             in execApp env ctxt res (drop arity xs)

execForeign env ctxt arity ty fn xs onfail
   = case foreignFromTT arity ty fn xs of
        Just ffun@(FFun f argTs retT) | length xs >= arity ->
           do let (args', xs') = (take arity xs, -- foreign args
                                  drop arity xs) -- rest
              res <- call ffun (map snd argTs)
              case res of
                   Nothing -> fail $ "Could not call foreign function \"" ++ f ++
                                     "\" with args " ++ show (map snd argTs)
                   Just r -> return (mkEApp r xs')
        _ -> return onfail

splitArg tm | (_, [_,_,l,r]) <- unApplyV tm -- pair, two implicits
    = Just (toFDesc l, r)
splitArg _ = Nothing

toFDesc tm
   | (EP _ n _, []) <- unApplyV tm = FCon (deNS n)
   | (EP _ n _, as) <- unApplyV tm = FApp (deNS n) (map toFDesc as)
toFDesc _ = FUnknown

deNS (NS n _) = n
deNS n = n

prf = sUN "prim__readFile"
pwf = sUN "prim__writeFile"
prs = sUN "prim__readString"
pws = sUN "prim__writeString"
pbm = sUN "prim__believe_me"
pstdin = sUN "prim__stdin"
pstdout = sUN "prim__stdout"
mkfprim = sUN "mkForeignPrim"
pioret = sUN "prim_io_return"
piobind = sUN "prim_io_bind"
upio = sUN "unsafePerformPrimIO"
delay = sUN "Delay"
force = sUN "Force"

-- | Look up primitive operations in the global table and transform
-- them into ExecVal functions
getOp :: Name -> [ExecVal] -> Maybe (Exec ExecVal, [ExecVal])
getOp fn (_ : _ : x : xs) | fn == pbm = Just (return x, xs)
getOp fn (_ : EConstant (Str n) : xs)
    | fn == pws =
              Just (do execIO $ putStr n
                       return (EConstant (I 0)), xs)
getOp fn (_:xs)
    | fn == prs =
              Just (do line <- execIO getLine
                       return (EConstant (Str line)), xs)
getOp fn (_ : EP _ fn' _ : EConstant (Str n) : xs)
    | fn == pwf && fn' == pstdout =
              Just (do execIO $ putStr n
                       return (EConstant (I 0)), xs)
getOp fn (_ : EP _ fn' _ : xs)
    | fn == prf && fn' == pstdin =
              Just (do line <- execIO getLine
                       return (EConstant (Str line)), xs)
getOp fn (_ : EHandle h : EConstant (Str n) : xs)
    | fn == pwf =
              Just (do execIO $ hPutStr h n
                       return (EConstant (I 0)), xs)
getOp fn (_ : EHandle h : xs)
    | fn == prf =
              Just (do contents <- execIO $ hGetLine h
                       return (EConstant (Str (contents ++ "\n"))), xs)
getOp fn (_ : arg : xs)
    | fn == prf =
              Just $ (execFail (Msg "Can't use prim__readFile on a raw pointer in the executor."), xs)
getOp n args = do (arity, prim) <- getPrim n primitives
                  if (length args >= arity)
                     then do res <- applyPrim prim (take arity args)
                             Just (res, drop arity args)
                     else Nothing
    where getPrim :: Name -> [Prim] -> Maybe (Int, [ExecVal] -> Maybe ExecVal)
          getPrim n [] = Nothing
          getPrim n ((Prim pn _ arity def _ _) : prims)
             | n == pn   = Just (arity, execPrim def)
             | otherwise = getPrim n prims

          execPrim :: ([Const] -> Maybe Const) -> [ExecVal] -> Maybe ExecVal
          execPrim f args = EConstant <$> (mapM getConst args >>= f)

          getConst (EConstant c) = Just c
          getConst _             = Nothing

          applyPrim :: ([ExecVal] -> Maybe ExecVal) -> [ExecVal] -> Maybe (Exec ExecVal)
          applyPrim fn args = return <$> fn args

-- | Overall wrapper for case tree execution. If there are enough arguments, it takes them,
-- evaluates them, then begins the checks for matching cases.
execCase :: ExecEnv -> Context -> [Name] -> SC -> [ExecVal] -> Exec (Maybe ExecVal)
execCase env ctxt ns sc args =
    let arity = length ns in
    if arity <= length args
    then do let amap = zip ns args
--            trace ("Case " ++ show sc ++ "\n   in " ++ show amap ++"\n   in env " ++ show env ++ "\n\n" ) $ return ()
            caseRes <- execCase' env ctxt amap sc
            case caseRes of
              Just res -> Just <$> execApp (map (\(n, tm) -> (n, tm)) amap ++ env) ctxt res (drop arity args)
              Nothing -> return Nothing
    else return Nothing

-- | Take bindings and a case tree and examines them, executing the matching case if possible.
execCase' :: ExecEnv -> Context -> [(Name, ExecVal)] -> SC -> Exec (Maybe ExecVal)
execCase' env ctxt amap (UnmatchedCase _) = return Nothing
execCase' env ctxt amap (STerm tm) =
    Just <$> doExec (map (\(n, v) -> (n, v)) amap ++ env) ctxt tm
execCase' env ctxt amap (Case sh n alts) | Just tm <- lookup n amap =
       case chooseAlt tm alts of
         Just (newCase, newBindings) ->
             let amap' = newBindings ++ (filter (\(x,_) -> not (elem x (map fst newBindings))) amap) in
             execCase' env ctxt amap' newCase
         Nothing -> return Nothing
execCase' _ _ _ cse = fail $ "The impossible happened: tried to exec  " ++ show cse

chooseAlt :: ExecVal -> [CaseAlt] -> Maybe (SC, [(Name, ExecVal)])
chooseAlt tm (DefaultCase sc : alts) | ok tm = Just (sc, [])
                                     | otherwise = Nothing
  where -- Default cases should only work on applications of constructors or on constants
        ok (EApp f x) = ok f
        ok (EP Bound _ _) = False
        ok (EP Ref _ _) = False
        ok _ = True

chooseAlt (EConstant c) (ConstCase c' sc : alts) | c == c' = Just (sc, [])
chooseAlt tm (ConCase n i ns sc : alts) | ((EP _ cn _), args) <- unApplyV tm
                                        , cn == n = Just (sc, zip ns args)
                                        | otherwise = chooseAlt tm alts
chooseAlt tm (_:alts) = chooseAlt tm alts
chooseAlt _ [] = Nothing

data Foreign = FFun String [(FDesc, ExecVal)] FDesc deriving Show

toFType :: FDesc -> FType
toFType (FCon c)
    | c == sUN "C_Str" = FString
    | c == sUN "C_Float" = FArith ATFloat
    | c == sUN "C_Ptr" = FPtr
    | c == sUN "C_MPtr" = FManagedPtr
    | c == sUN "C_Unit" = FUnit
toFType (FApp c [_,ity])
    | c == sUN "C_IntT" = FArith (toAType ity)
  where toAType (FCon i)
          | i == sUN "C_IntChar" = ATInt ITChar
          | i == sUN "C_IntNative" = ATInt ITNative
          | i == sUN "C_IntBits8" = ATInt (ITFixed IT8)
          | i == sUN "C_IntBits16" = ATInt (ITFixed IT16)
          | i == sUN "C_IntBits32" = ATInt (ITFixed IT32)
          | i == sUN "C_IntBits64" = ATInt (ITFixed IT64)
        toAType t = error (show t ++ " not defined in toAType")

toFType (FApp c [_])
    | c == sUN "C_Any" = FAny
toFType t = error (show t ++ " not defined in toFType")

call :: Foreign -> [ExecVal] -> Exec (Maybe ExecVal)
call (FFun name argTypes retType) args =
    do fn <- findForeign name
       maybe (return Nothing)
             (\f -> Just . ioWrap <$> call' f args (toFType retType)) fn
    where call' :: ForeignFun -> [ExecVal] -> FType -> Exec ExecVal
          call' (Fun _ h) args (FArith (ATInt ITNative)) = do
            res <- execIO $ callFFI h retCInt (prepArgs args)
            return (EConstant (I (fromIntegral res)))
          call' (Fun _ h) args (FArith (ATInt (ITFixed IT8))) = do
            res <- execIO $ callFFI h retCChar (prepArgs args)
            return (EConstant (B8 (fromIntegral res)))
          call' (Fun _ h) args (FArith (ATInt (ITFixed IT16))) = do
            res <- execIO $ callFFI h retCWchar (prepArgs args)
            return (EConstant (B16 (fromIntegral res)))
          call' (Fun _ h) args (FArith (ATInt (ITFixed IT32))) = do
            res <- execIO $ callFFI h retCInt (prepArgs args)
            return (EConstant (B32 (fromIntegral res)))
          call' (Fun _ h) args (FArith (ATInt (ITFixed IT64))) = do
            res <- execIO $ callFFI h retCLong (prepArgs args)
            return (EConstant (B64 (fromIntegral res)))
          call' (Fun _ h) args (FArith ATFloat) = do
            res <- execIO $ callFFI h retCDouble (prepArgs args)
            return (EConstant (Fl (realToFrac res)))
          call' (Fun _ h) args (FArith (ATInt ITChar)) = do
            res <- execIO $ callFFI h retCChar (prepArgs args)
            return (EConstant (Ch (castCCharToChar res)))
          call' (Fun _ h) args FString = do res <- execIO $ callFFI h retCString (prepArgs args)
                                            if res == nullPtr
                                               then return (EPtr res)
                                               else do hStr <- execIO $ peekCString res
                                                       return (EConstant (Str hStr))

          call' (Fun _ h) args FPtr = EPtr <$> (execIO $ callFFI h (retPtr retVoid) (prepArgs args))
          call' (Fun _ h) args FUnit = do _ <- execIO $ callFFI h retVoid (prepArgs args)
                                          return $ EP Ref unitCon EErased
          call' _ _ _ = fail "the impossible happened in call' in Execute.hs"

          prepArgs = map prepArg
          prepArg (EConstant (I i)) = argCInt (fromIntegral i)
          prepArg (EConstant (B8 i)) = argCChar (fromIntegral i)
          prepArg (EConstant (B16 i)) = argCWchar (fromIntegral i)
          prepArg (EConstant (B32 i)) = argCInt (fromIntegral i)
          prepArg (EConstant (B64 i)) = argCLong (fromIntegral i)
          prepArg (EConstant (Fl f)) = argCDouble (realToFrac f)
          prepArg (EConstant (Ch c)) = argCChar (castCharToCChar c) -- FIXME - castCharToCChar only safe for first 256 chars
                                                                    -- Issue #1720 on the issue tracker.
                                                                    -- https://github.com/idris-lang/Idris-dev/issues/1720
          prepArg (EConstant (Str s)) = argString s
          prepArg (EPtr p) = argPtr p
          prepArg other = trace ("Could not use " ++ take 100 (show other) ++ " as FFI arg.") undefined

foreignFromTT :: Int -> ExecVal -> ExecVal -> [ExecVal] -> Maybe Foreign
foreignFromTT arity ty (EConstant (Str name)) args
    = do argFTyVals <- mapM splitArg (take arity args)
         return $ FFun name argFTyVals (toFDesc ty)
foreignFromTT arity ty fn args = trace ("failed to construct ffun from " ++ show (ty,fn,args)) Nothing

getFTy :: ExecVal -> Maybe FType
getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _))
  | fi == txt "FIntT" =
    case str intTy of
      "ITNative" -> Just (FArith (ATInt ITNative))
      "ITChar" -> Just (FArith (ATInt ITChar))
      "IT8" -> Just (FArith (ATInt (ITFixed IT8)))
      "IT16" -> Just (FArith (ATInt (ITFixed IT16)))
      "IT32" -> Just (FArith (ATInt (ITFixed IT32)))
      "IT64" -> Just (FArith (ATInt (ITFixed IT64)))
      _ -> Nothing
getFTy (EP _ (UN t) _) =
    case str t of
      "FFloat"  -> Just (FArith ATFloat)
      "FString" -> Just FString
      "FPtr"    -> Just FPtr
      "FUnit"   -> Just FUnit
      _         -> Nothing
getFTy _ = Nothing

unEList :: ExecVal -> Maybe [ExecVal]
unEList tm = case unApplyV tm of
               (nil, [_]) -> Just []
               (cons, ([_, x, xs])) ->
                   do rest <- unEList xs
                      return $ x:rest
               (f, args) -> Nothing

toConst :: Term -> Maybe Const
toConst (Constant c) = Just c
toConst _ = Nothing

mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f [] = return []
mapMaybeM f (x:xs) = do rest <- mapMaybeM f xs
                        maybe rest (:rest) <$> f x
findForeign :: String -> Exec (Maybe ForeignFun)
findForeign fn = do est <- getExecState
                    let libs = exec_dynamic_libs est
                    fns <- mapMaybeM getFn libs
                    case fns of
                      [f] -> return (Just f)
                      [] -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" not found"
                               return Nothing
                      fs -> do execIO . putStrLn $ "Symbol \"" ++ fn ++ "\" is ambiguous. Found " ++
                                                   show (length fs) ++ " occurrences."
                               return Nothing
    where getFn lib = execIO $ catchIO (tryLoadFn fn lib) (\_ -> return Nothing)

#endif


text:
/***** includes *****/
#include "lfds720_freelist_n_internal.h"

/****************************************************************************/
void lfds720_freelist_n_add_optional_elimination_array_to_improve_performance( struct lfds720_freelist_n_state *fs,
                                                                               void *elimination_array,
                                                                               size_t elimination_array_size_in_bytes )
{
  lfds720_pal_uint_t
    loop,
    subloop;

  LFDS720_PAL_ASSERT( fs != NULL );
  LFDS720_PAL_ASSERT( elimination_array != NULL );
  LFDS720_PAL_ASSERT( (lfds720_pal_uint_t) elimination_array % LFDS720_PAL_ATOMIC_ISOLATION_LENGTH_IN_BYTES == 0 );
  LFDS720_PAL_ASSERT( elimination_array_size_in_bytes >= LFDS720_PAL_ATOMIC_ISOLATION_LENGTH_IN_BYTES );

  fs->elimination_array = elimination_array;
  fs->elimination_array_number_of_lines = elimination_array_size_in_bytes / LFDS720_PAL_ATOMIC_ISOLATION_LENGTH_IN_BYTES;

  for( loop = 0 ; loop < fs->elimination_array_number_of_lines ; loop++ )
    for( subloop = 0 ; subloop < LFDS720_FREELIST_N_ELIMINATION_ARRAY_USED_LINE_LENGTH_IN_FREELIST_N_POINTER_ELEMENTS ; subloop++ )
      fs->elimination_array[loop][subloop] = NULL;

  LFDS720_MISC_BARRIER_STORE;

  lfds720_misc_force_store();

  return;
}

redpajama_set_name: RedPajamaGithub


text:
package org.jkiss.dbeaver.ext.postgresql.model;

import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.postgresql.PostgreUtils;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCStructureAssistant;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.impl.struct.AbstractObjectReference;
import org.jkiss.dbeaver.model.impl.struct.RelationalObjectType;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectFilter;
import org.jkiss.dbeaver.model.struct.DBSObjectReference;
import org.jkiss.dbeaver.model.struct.DBSObjectType;
import org.jkiss.utils.CommonUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * PostgreStructureAssistant
 */
public class PostgreStructureAssistant extends JDBCStructureAssistant
{
    private final PostgreDataSource dataSource;

    public PostgreStructureAssistant(PostgreDataSource dataSource)
    {
        this.dataSource = dataSource;
    }

    @Override
    protected JDBCDataSource getDataSource()
    {
        return dataSource;
    }

    @Override
    public DBSObjectType[] getSupportedObjectTypes()
    {
        return new DBSObjectType[] {
            RelationalObjectType.TYPE_TABLE,
            RelationalObjectType.TYPE_CONSTRAINT,
            RelationalObjectType.TYPE_PROCEDURE,
            RelationalObjectType.TYPE_TABLE_COLUMN,
            RelationalObjectType.TYPE_DATA_TYPE,
            };
    }

    @Override
    public DBSObjectType[] getHyperlinkObjectTypes()
    {
        return new DBSObjectType[] {
            RelationalObjectType.TYPE_TABLE,
            RelationalObjectType.TYPE_PROCEDURE
        };
    }

    @Override
    public DBSObjectType[] getAutoCompleteObjectTypes()
    {
        return new DBSObjectType[] {
            RelationalObjectType.TYPE_TABLE,
            RelationalObjectType.TYPE_PROCEDURE,
        };
    }

    @Override
    protected void findObjectsByMask(JDBCSession session, DBSObjectType objectType, DBSObject parentObject, String objectNameMask, boolean caseSensitive, boolean globalSearch, int maxResults, List<DBSObjectReference> references) throws DBException, SQLException
    {
        PostgreSchema ownerSchema = parentObject instanceof PostgreSchema ? (PostgreSchema) parentObject : null;
        final PostgreDataSource dataSource = (PostgreDataSource) session.getDataSource();
        PostgreDatabase database = parentObject instanceof PostgreObject ? ((PostgreObject) parentObject).getDatabase() : dataSource.getDefaultInstance();
        List<PostgreSchema> nsList = new ArrayList<>();
        if (ownerSchema != null) {
            nsList.add(0, ownerSchema);
        } else if (!globalSearch) {
            // Limit object search with search path
            for (String sn : database.getSearchPath()) {
                final PostgreSchema schema = database.getSchema(
                    session.getProgressMonitor(),
                    PostgreUtils.getRealSchemaName(database, sn));
                if (schema != null) {
                    nsList.add(schema);
                }
            }
            PostgreSchema pgCatalog = database.getCatalogSchema(session.getProgressMonitor());
            if (pgCatalog != null) {
                nsList.add(pgCatalog);
            }
        } else {
            // Limit object search with available schemas (use filters - #648)
            DBSObjectFilter schemaFilter = dataSource.getContainer().getObjectFilter(PostgreSchema.class, database, true);
            if (schemaFilter != null && schemaFilter.isEnabled()) {
                for (PostgreSchema schema : database.getSchemas(session.getProgressMonitor())) {
                    if (schemaFilter.matches(schema.getName())) {
                        nsList.add(schema);
                    }
                }
            }
        }

        if (objectType == RelationalObjectType.TYPE_TABLE) {
            findTablesByMask(session, nsList, objectNameMask, caseSensitive, maxResults, references);
        } else if (objectType == RelationalObjectType.TYPE_CONSTRAINT) {
            findConstraintsByMask(session, nsList, objectNameMask, caseSensitive, maxResults, references);
        } else if (objectType == RelationalObjectType.TYPE_PROCEDURE) {
            findProceduresByMask(session, nsList, objectNameMask, caseSensitive, maxResults, references);
        } else if (objectType == RelationalObjectType.TYPE_TABLE_COLUMN) {
            findTableColumnsByMask(session, nsList, objectNameMask, caseSensitive, maxResults, references);
        } else if (objectType == RelationalObjectType.TYPE_DATA_TYPE) {
            findDataTypesByMask(session, nsList, objectNameMask, caseSensitive, maxResults, references);
        }
    }

    private void findTablesByMask(JDBCSession session, @Nullable final List<PostgreSchema> schema, String tableNameMask, boolean caseSensitive, int maxResults, List<DBSObjectReference> objects)
        throws SQLException, DBException
    {
        DBRProgressMonitor monitor = session.getProgressMonitor();

        // Load tables
        try (JDBCPreparedStatement dbStat = session.prepareStatement(
            "SELECT x.oid,x.relname,x.relnamespace,x.relkind FROM pg_catalog.pg_class x " +
                "WHERE x.relkind in('r','v','m') AND x.relname " + (caseSensitive ? "LIKE" : "ILIKE") + " ? " +
                (CommonUtils.isEmpty(schema) ? "" : " AND x.relnamespace IN (" + SQLUtils.generateParamList(schema.size())+ ")") +
                " ORDER BY x.relname LIMIT " + maxResults)) {
            dbStat.setString(1, tableNameMask);
            if (!CommonUtils.isEmpty(schema)) {
                PostgreUtils.setArrayParameter(dbStat, 2, schema);
            }
            try (JDBCResultSet dbResult = dbStat.executeQuery()) {
                int tableNum = maxResults;
                while (dbResult.next() && tableNum-- > 0) {
                    if (monitor.isCanceled()) {
                        break;
                    }
                    final long schemaId = JDBCUtils.safeGetLong(dbResult, "relnamespace");
                    final long tableId = JDBCUtils.safeGetLong(dbResult, "oid");
                    final String tableName = JDBCUtils.safeGetString(dbResult, "relname");
                    final PostgreClass.RelKind tableType = PostgreClass.RelKind.valueOf(JDBCUtils.safeGetString(dbResult, "relkind"));
                    final PostgreSchema tableSchema = dataSource.getDefaultInstance().getSchema(session.getProgressMonitor(), schemaId);
                    if (tableSchema == null) {
                        log.debug("Can't resolve table '" + tableName + "' - owner schema " + schemaId + " not found");
                        continue;
                    }
                    objects.add(new AbstractObjectReference(tableName, tableSchema, null,
                        tableType == PostgreClass.RelKind.r ? PostgreTable.class :
                            (tableType == PostgreClass.RelKind.v ? PostgreView.class : PostgreMaterializedView.class),
                        RelationalObjectType.TYPE_TABLE) {
                        @Override
                        public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException {
                            PostgreTableBase table = tableSchema.getTable(monitor, tableId);
                            if (table == null) {
                                throw new DBException("Table '" + tableName + "' not found in schema '" + tableSchema.getName() + "'");
                            }
                            return table;
                        }
                    });
                }
            }
        }
    }

    private void findProceduresByMask(JDBCSession session, @Nullable final List<PostgreSchema> schema, String procNameMask, boolean caseSensitive, int maxResults, List<DBSObjectReference> objects)
        throws SQLException, DBException
    {
        DBRProgressMonitor monitor = session.getProgressMonitor();

        // Load procedures
        try (JDBCPreparedStatement dbStat = session.prepareStatement(
            "SELECT DISTINCT x.oid,x.proname,x.pronamespace FROM pg_catalog.pg_proc x " +
                "WHERE x.proname " + (caseSensitive ? "LIKE" : "ILIKE") + " ? " +
                "AND x.proname NOT LIKE '\\_%'" + // Exclude procedures starting with underscore
                (CommonUtils.isEmpty(schema) ? "" : " AND x.pronamespace IN (" + SQLUtils.generateParamList(schema.size())+ ")") +
                " ORDER BY x.proname LIMIT " + maxResults)) {
            dbStat.setString(1, procNameMask);
            if (!CommonUtils.isEmpty(schema)) {
                PostgreUtils.setArrayParameter(dbStat, 2, schema);
            }
            try (JDBCResultSet dbResult = dbStat.executeQuery()) {
                int tableNum = maxResults;
                while (dbResult.next() && tableNum-- > 0) {
                    if (monitor.isCanceled()) {
                        break;
                    }
                    final long schemaId = JDBCUtils.safeGetLong(dbResult, "pronamespace");
                    final String procName = JDBCUtils.safeGetString(dbResult, "proname");
                    final long procId = JDBCUtils.safeGetLong(dbResult, "oid");
                    final PostgreSchema procSchema = dataSource.getDefaultInstance().getSchema(session.getProgressMonitor(), schemaId);
                    if (procSchema == null) {
                        log.debug("Procedure's schema '" + schemaId + "' not found");
                        continue;
                    }
                    objects.add(new AbstractObjectReference(procName, procSchema, null, PostgreProcedure.class, RelationalObjectType.TYPE_PROCEDURE) {
                        @Override
                        public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException {
                            PostgreProcedure procedure = procSchema.getProcedure(monitor, procId);
                            if (procedure == null) {
                                throw new DBException("Procedure '" + procName + "' not found in schema '" + procSchema.getName() + "'");
                            }
                            return procedure;
                        }
                    });
                }
            }
        }
    }

    private void findConstraintsByMask(JDBCSession session, @Nullable final List<PostgreSchema> schema, String constrNameMask, boolean caseSensitive, int maxResults, List<DBSObjectReference> objects)
        throws SQLException, DBException
    {
        DBRProgressMonitor monitor = session.getProgressMonitor();

        // Load constraints
        try (JDBCPreparedStatement dbStat = session.prepareStatement(
            "SELECT x.oid,x.conname,x.connamespace FROM pg_catalog.pg_constraint x " +
                "WHERE x.conname " + (caseSensitive ? "LIKE" : "ILIKE") + " ? " +
                (CommonUtils.isEmpty(schema) ? "" : " AND x.connamespace IN (" + SQLUtils.generateParamList(schema.size())+ ")") +
                " ORDER BY x.conname LIMIT " + maxResults)) {
            dbStat.setString(1, constrNameMask);
            if (!CommonUtils.isEmpty(schema)) {
                PostgreUtils.setArrayParameter(dbStat, 2, schema);
            }
            try (JDBCResultSet dbResult = dbStat.executeQuery()) {
                int tableNum = maxResults;
                while (dbResult.next() && tableNum-- > 0) {
                    if (monitor.isCanceled()) {
                        break;
                    }
                    final long schemaId = JDBCUtils.safeGetLong(dbResult, "connamespace");
                    final long constrId = JDBCUtils.safeGetLong(dbResult, "oid");
                    final String constrName = JDBCUtils.safeGetString(dbResult, "conname");
                    final PostgreSchema constrSchema = dataSource.getDefaultInstance().getSchema(session.getProgressMonitor(), schemaId);
                    if (constrSchema == null) {
                        log.debug("Constraint's schema '" + schemaId + "' not found");
                        continue;
                    }
                    objects.add(new AbstractObjectReference(constrName, constrSchema, null, PostgreTableConstraintBase.class, RelationalObjectType.TYPE_CONSTRAINT) {
                        @Override
                        public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException {
                            final PostgreTableConstraintBase constraint = PostgreUtils.getObjectById(monitor, constrSchema.constraintCache, constrSchema, constrId);
                            if (constraint == null) {
                                throw new DBException("Constraint '" + constrName + "' not found in schema '" + constrSchema.getName() + "'");
                            }
                            return constraint;
                        }
                    });
                }
            }
        }
    }

    private void findTableColumnsByMask(JDBCSession session, @Nullable final List<PostgreSchema> schema, String columnNameMask, boolean caseSensitive, int maxResults, List<DBSObjectReference> objects)
        throws SQLException, DBException
    {
        DBRProgressMonitor monitor = session.getProgressMonitor();

        // Load constraints
        try (JDBCPreparedStatement dbStat = session.prepareStatement(
            "SELECT x.attname,x.attrelid,x.atttypid,c.relnamespace " +
                "FROM pg_catalog.pg_attribute x, pg_catalog.pg_class c\n" +
                "WHERE c.oid=x.attrelid AND x.attname " + (caseSensitive ? "LIKE" : "ILIKE") + " ? " +
                (CommonUtils.isEmpty(schema) ? "" : " AND c.relnamespace IN (" + SQLUtils.generateParamList(schema.size())+ ")") +
                " ORDER BY x.attname LIMIT " + maxResults)) {
            dbStat.setString(1, columnNameMask);
            if (!CommonUtils.isEmpty(schema)) {
                PostgreUtils.setArrayParameter(dbStat, 2, schema);
            }
            try (JDBCResultSet dbResult = dbStat.executeQuery()) {
                int tableNum = maxResults;
                while (dbResult.next() && tableNum-- > 0) {
                    if (monitor.isCanceled()) {
                        break;
                    }
                    final long schemaId = JDBCUtils.safeGetLong(dbResult, "relnamespace");
                    final long tableId = JDBCUtils.safeGetLong(dbResult, "attrelid");
                    final String attributeName = JDBCUtils.safeGetString(dbResult, "attname");
                    final PostgreSchema constrSchema = dataSource.getDefaultInstance().getSchema(session.getProgressMonitor(), schemaId);
                    if (constrSchema == null) {
                        log.debug("Attribute's schema '" + schemaId + "' not found");
                        continue;
                    }
                    objects.add(new AbstractObjectReference(attributeName, constrSchema, null, PostgreTableBase.class, RelationalObjectType.TYPE_TABLE_COLUMN) {
                        @Override
                        public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException {
                            final PostgreTableBase table = PostgreUtils.getObjectById(monitor, constrSchema.tableCache, constrSchema, tableId);
                            if (table == null) {
                                throw new DBException("Table '" + tableId + "' not found in schema '" + constrSchema.getName() + "'");
                            }
                            return table.getAttribute(monitor, attributeName);
                        }
                    });
                }
            }
        }
    }

    private void findDataTypesByMask(JDBCSession session, List<PostgreSchema> catalog, String objectNameMask, boolean caseSensitive, int maxResults, List<DBSObjectReference> references) {
        DBRProgressMonitor monitor = session.getProgressMonitor();

    }

}


text:
/**
* Support and FAQ: visit Atmel Support
*/

#ifndef _SAMD21_GCLK_INSTANCE_
#define _SAMD21_GCLK_INSTANCE_

/* ========== Register definition for GCLK peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_GCLK_CTRL              (0x40000C00U) /**< \brief (GCLK) Control */
#define REG_GCLK_STATUS            (0x40000C01U) /**< \brief (GCLK) Status */
#define REG_GCLK_CLKCTRL           (0x40000C02U) /**< \brief (GCLK) Generic Clock Control */
#define REG_GCLK_GENCTRL           (0x40000C04U) /**< \brief (GCLK) Generic Clock Generator Control */
#define REG_GCLK_GENDIV            (0x40000C08U) /**< \brief (GCLK) Generic Clock Generator Division */
#else
#define REG_GCLK_CTRL              (*(RwReg8 *)0x40000C00U) /**< \brief (GCLK) Control */
#define REG_GCLK_STATUS            (*(RoReg8 *)0x40000C01U) /**< \brief (GCLK) Status */
#define REG_GCLK_CLKCTRL           (*(RwReg16*)0x40000C02U) /**< \brief (GCLK) Generic Clock Control */
#define REG_GCLK_GENCTRL           (*(RwReg  *)0x40000C04U) /**< \brief (GCLK) Generic Clock Generator Control */
#define REG_GCLK_GENDIV            (*(RwReg  *)0x40000C08U) /**< \brief (GCLK) Generic Clock Generator Division */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */

/* ========== Instance parameters for GCLK peripheral ========== */
#define GCLK_GENDIV_BITS            16
#define GCLK_GEN_NUM                9        // Number of Generic Clock Generators
#define GCLK_GEN_NUM_MSB            8        // Number of Generic Clock Generators - 1
#define GCLK_GEN_SOURCE_NUM_MSB     8        // Number of Generic Clock Sources - 1
#define GCLK_NUM                    37       // Number of Generic Clock Users
#define GCLK_SOURCE_DFLL48M         7
#define GCLK_SOURCE_FDPLL           8
#define GCLK_SOURCE_GCLKGEN1        2
#define GCLK_SOURCE_GCLKIN          1
#define GCLK_SOURCE_NUM             9        // Number of Generic Clock Sources
#define GCLK_SOURCE_OSCULP32K       3
#define GCLK_SOURCE_OSC8M           6
#define GCLK_SOURCE_OSC32K          4
#define GCLK_SOURCE_XOSC            0
#define GCLK_SOURCE_XOSC32K         5

#endif /* _SAMD21_GCLK_INSTANCE_ */


text:
Forked from [Vault](https://github.com/hashicorp/vault/tree/master/shamir)

## How it works

We want to split a secret into parts.

Any two points on the cartesian plane define a line. Three points define a
parabola. Four points define a cubic curve, and so on. In general, `n` points
define an function of degree `(n - 1)`. If our secret was somehow an function of
degree `(n - 1)`, we could just compute `n` different points of that function
and give `n` different people one point each. In order to recover the secret,
then we'd need all the `n` points. If we wanted to, we could compute more than n
points, but even then still only `n` points out of our whole set of computed
points would be required to recover the function.

A concrete example: our secret is the function `y = 2x + 1`. This function is of
degree 1, so we need at least 2 points to define it. For example, let's set
`x = 1`, `x = 2` and `x = 3`. From this follows that `y = 3`, `y = 5` and
`y = 7`, respectively. Now, with the information that our secret is of degree 1,
we can use any 2 of the 3 points we computed to recover our original function.
For example, let's use the points `x = 1; y = 3` and `x = 2; y = 5`.
We know that first degree functions are lines, defined by their slope and their
intersection point with the y axis. We can easily compute the slope given our
two points: it's the change in `y` divided by the change in `x`:
`(5 - 3)/(2 - 1) = 2`. Now, knowing the slope we can compute the intersection
point with the `y` axis by "working our way back". We know that at `x = 1`,
`y` equals `3`, so naturally because the slope is `2`, at `x = 0`, `y` must be
`1`.

## Lagrange interpolation

The method we've used for this isn't very general: it only works for polynomials
of degree 1. Lagrange interpolation is a more general way that lets us obtain
the function of degree `(n - 1)` that passes through `n` arbitrary points.

Understanding how to perform Lagrange interpolation isn't really necessary to
understand Shamir's Secret Sharing: it's enough to know that there's only one
function of degree `(n - 1)` that passes through `n` given points and that
computing this function given the points is computationally efficient.

But for those interested, here's an explanation:

Let's say our points are `(x_0, y_0),...,(x_j, y_j),...,(x_(n-1), y_(n-1))`.
Then, the Lagrange polynomial `L(x)`, the polynomial we're looking for, is
defined as follows:

`L(x) = sum from j=0 to j=(n-1) of {y_j * l_j(x)}`

and `l_j(x) = product from m=0 to m=(n-1) except when m=j of {(x - x_m)/(x_j - x_m)}`

A concrete example, with 3 points:

```
x_0 = 1   y_0 = 1
x_1 = 2   y_1 = 4
x_2 = 3   y_2 = 9
```

Let's apply the formula:

```
L(x) =
        y_0 * l_0(x) +
        y_1 * l_1(x) +
        y_2 * l_2(x)
```

Substitute `y_j` for the actual value:

```
L(x) =
        1 * l_0(x) +
        4 * l_1(x) +
        9 * l_2(x)
```

Replace `l_j(x)`:

```
l_0(x) = (x - 2)/(1 - 2) * (x - 3)/(1 - 3) =  0.5x^2 - 2.5x + 3
l_1(x) = (x - 1)/(2 - 1) * (x - 3)/(2 - 3) = -   x^2 +   4x - 3
l_2(x) = (x - 1)/(3 - 1) * (x - 2)/(3 - 2) =  0.5x^2 - 1.5x + 1
```

```

L(x) =
        1 * ( 0.5x^2 - 2.5x + 3) +
        4 * (   -x^2 +   4x - 3) +
        9 * ( 0.5x^2 - 1.5x + 1)
```

```

L(x) =
        ( 0.5x^2 -  2.5x +  3) +
        (  -4x^2 +   16x - 12) +
        ( 4.5x^2 - 13.5x +  9)
     =       x^2 +    0x +  0
     = x^2
```

So the polynomial we were looking for is `y = x^2`.

## Splitting a secret

So we have the ability of splitting a function into parts, but in the context
of computing we generally want to split a number, not a function. For this,
let's define a function of degree `threshold`. `threshold` is the amount of
parts we want to require in order to recover the secret. Let's set the parameter
of degree zero to our secret `S` and make the rest of the parameters random:

`y = ax^(threshold) + bx^(threshold-1) + ... + zx^1 + S`

With `a, b, ...` random.

Then, we want to generate our parts. For this, we evaluate our function at as
many points as we want parts. For example, say our secret is 123, we want 5
parts and a threshold of 2. Because the threshold is 2, we're going to need a
polynomial of degree 2:

`y = ax^2 + bx + 123`

We randomly set `a = 7` and `b = 1`:

`y = 7x^2 + x + 123`

Because we want 5 parts, we need to compute 5 points:

```
x = 0 -> y = 123 # woops! This is the secret itself. Let's not use that one.
x = 1 -> y = 131
x = 2 -> y = 153
x = 3 -> y = 189
x = 4 -> y = 239
x = 5 -> y = 303
```

And that's it. Each of the computed points is one part of the secret.

## Combining a secret

Now that we have our parts, we have to define a way to recover them. Using
the example from the previous section, we only need any two points out of the
five we created to recover the secret, because we set the threshold to two.
So with any two of the five points we created, we can recover the original
polynomial, and because the secret is the free term in the polynomial, we can
recover the secret.

## Finite fields

In the previous examples we've only used integers, and this unfortunately has
a flaw. First of all, it's impossible to uniformly sample integers to get
random coefficients for our generated polynomial. Additionally, if we don't
operate in a finite field, information about the secret is leaked for every part
someone recovers.

For these reasons, Vault's implementation of Shamir's Secret Sharing uses finite
field arithmetic, specifically in GF(2^8), with 229 as the generator. GF(2^8)
has 256 elements, so using this we can only split one byte at a time. This is
not a problem, though, as we can just split each byte in our secret
independently. This implementation uses tables to speed up the execution of
finite field arithmetic.


text:
package io.jenkins.blueocean.service.embedded.rest;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

import edu.umd.cs.findbugs.annotations.NonNull;
import javax.servlet.ServletException;

import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.apache.commons.lang.StringUtils;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.Test;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.verb.DELETE;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.cloudbees.plugins.credentials.CredentialsProvider;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.model.Node;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.User;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import io.jenkins.blueocean.commons.ServiceException;
import io.jenkins.blueocean.rest.ApiHead;
import io.jenkins.blueocean.rest.factory.organization.AbstractOrganization;
import io.jenkins.blueocean.rest.hal.Link;
import io.jenkins.blueocean.rest.model.BluePipeline;
import io.jenkins.blueocean.rest.model.BluePipelineContainer;
import io.jenkins.blueocean.rest.model.BlueUser;
import io.jenkins.blueocean.rest.model.BlueUserContainer;
import io.jenkins.blueocean.rest.model.BlueUserPermission;
import jenkins.model.Jenkins;
import jenkins.model.ModifiableTopLevelItemGroup;

public class UserImplPermissionTest {
    private TestOrganization testOrganization;
    private User user;
    private Authentication authentication;
    private Jenkins jenkins;

    private MockedStatic<Jenkins> jenkinsMockedStatic;

    private MockedStatic<User> userMockedStatic;

    @Before
    public void setup() throws IOException {
        testOrganization = new TestOrganization("org", "orgDisplayName");

        user = mock(User.class);
        when(user.getId()).thenReturn("some_user");
        authentication = new Authentication() {
            public String getName() {
                return "some_user";
            }
            public GrantedAuthority[] getAuthorities() { return null; }
            public Object getCredentials() { return null; }
            public Object getDetails() { return null; }
            public Object getPrincipal() { return null; }
            public boolean isAuthenticated() { return false; }
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {}
        };

        jenkins = mock(Jenkins.class);
        when(jenkins.getACL()).thenReturn(new ACL() {
            public boolean hasPermission(Authentication a, Permission permission) {
                return false;
            }
        });

        jenkinsMockedStatic = Mockito.mockStatic(Jenkins.class);
        when(Jenkins.getAuthentication()).thenReturn(authentication);
        when(Jenkins.get()).thenReturn(jenkins);

        try {
            // After Jenkins 2.77 hasPermission is no longer in Node.class and is not final so we need to mock it
            // prior to it is called as being final and mocking it will fail for the same reason.
            // TODO remove after core base line is >= 2.77
            Node.class.getDeclaredMethod("hasPermission", Permission.class);
        } catch (NoSuchMethodException e) {
            when(jenkins.hasPermission(Mockito.any())).thenAnswer(new Answer<Boolean>() {
                public Boolean answer(InvocationOnMock invocation) {
                    Permission permission = invocation.getArgument(0);
                    Jenkins j = (Jenkins) invocation.getMock();
                    ACL acl = j.getACL();
                    try {
                        return acl.hasPermission(permission);
                    } catch (NullPointerException x) {
                        throw new AssumptionViolatedException("TODO cannot be made to work prior to Spring Security update", x);
                    }
                }
            });
        }

        userMockedStatic = Mockito.mockStatic(User.class);
        when(User.get("some_user", false, Collections.EMPTY_MAP)).thenReturn(user);
    }

    @After
    public void cleanup() {
        jenkinsMockedStatic.close();
        userMockedStatic.close();
    }
    /**
     * Tests that the permissions are checked against the organization base and not the Jenkins instance. In this case
     * Jenkins instance will always return false to permission request and the organization base true.
     */
    @Test
    public void useTestAgainstOrgBaseOnFolder() {
        try { // https://github.com/powermock/powermock/issues/428
        UserImpl userImpl = new UserImpl(testOrganization, user, testOrganization);
        checkPermissions(userImpl.getPermission(), false, true);
        } catch (AssumptionViolatedException x) {
            System.err.println(x);
        }
    }

    /**
     * Tests against jenkins
     */
    @Test
    public void useTestAgainstJenkinsRoot() {
        try { // https://github.com/powermock/powermock/issues/428
        OrganizationImpl baseOrg = new OrganizationImpl("jenkins", jenkins);
        UserImpl userImpl = new UserImpl(baseOrg, user, baseOrg);
        checkPermissions(userImpl.getPermission(), false, false);

        when(jenkins.getACL()).thenReturn(new ACL() {
            public boolean hasPermission(Authentication a, Permission permission) {
                return true;
            }
        });

        checkPermissions(userImpl.getPermission(), true, true);
        } catch (AssumptionViolatedException x) {
            System.err.println(x);
        }
    }

    private void checkPermissions(BlueUserPermission permission, boolean shouldBeAdmin, boolean shouldHaveOtherPermissions) {

        assertEquals("User permission does not match", permission.isAdministration(), shouldBeAdmin);

        Map<String, Boolean> permissions = permission.getPipelinePermission();
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(BluePipeline.CREATE_PERMISSION));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(BluePipeline.READ_PERMISSION));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(BluePipeline.START_PERMISSION));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(BluePipeline.STOP_PERMISSION));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(BluePipeline.CONFIGURE_PERMISSION));

        permissions = permission.getCredentialPermission();
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(CredentialsProvider.CREATE.name.toLowerCase()));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(CredentialsProvider.VIEW.name.toLowerCase()));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(CredentialsProvider.DELETE.name.toLowerCase()));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(CredentialsProvider.UPDATE.name.toLowerCase()));
        assertEquals("User permission does not match", shouldHaveOtherPermissions, permissions.get(StringUtils.uncapitalize(CredentialsProvider.MANAGE_DOMAINS.name)));
    }

    public static class TestOrganization extends AbstractOrganization implements ModifiableTopLevelItemGroup, AccessControlled {
        private final String name;
        private final String displayName;

        private final UserContainerImpl users = new UserContainerImpl(this, this);

        public TestOrganization(@NonNull String name, @CheckForNull String displayName) {
            this.name = name;
            this.displayName = displayName != null ? displayName : name;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getDisplayName() {
            return displayName;
        }

        @NonNull
        @Override
        public ModifiableTopLevelItemGroup getGroup() {
            return this;
        }

        @Override
        public BluePipelineContainer getPipelines() {
            return new PipelineContainerImpl(this, this, this);
        }

        @WebMethod(name = "")
        @DELETE
        public void delete() {
            throw new ServiceException.NotImplementedException("Not implemented yet");
        }

        @Override
        public BlueUserContainer getUsers() {
            return users;
        }

        @Override
        public BlueUser getUser() {
            User user = User.current();
            if (user == null) {
                throw new ServiceException.NotFoundException("No authenticated user found");
            }
            return new UserImpl(this, user, new UserContainerImpl(this, this));
        }

        @Override
        public Link getLink() {
            return ApiHead.INSTANCE().getLink().rel("organizations/" + getName());
        }

        @Override
        public TopLevelItem doCreateItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
            return null;
        }

        @Override
        public String getFullName() {
            return name;
        }

        @Override
        public String getFullDisplayName() {
            return name;
        }

        @Override
        public Collection<TopLevelItem> getItems() {
            return null;
        }

        @Override
        public String getUrl() {
            return null;
        }

        @Override
        public String getUrlChildPrefix() {
            return null;
        }

        @Override
        public TopLevelItem getItem(String name) throws AccessDeniedException {
            return null;
        }

        @Override
        public File getRootDirFor(TopLevelItem child) {
            return null;
        }

        @Override
        public void onRenamed(TopLevelItem item, String oldName, String newName) throws IOException {
        }

        @Override
        public void onDeleted(TopLevelItem item) throws IOException {
        }

        @Override
        public File getRootDir() {
            return null;
        }

        @Override
        public void save() throws IOException {
        }

        @Override
        public <T extends TopLevelItem> T copy(T src, String name) throws IOException {
            return null;
        }

        @Override
        public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
            return null;
        }

        @Override
        public TopLevelItem createProject(TopLevelItemDescriptor type, String name, boolean notify) throws IOException {
            return null;
        }

        @Override
        public ACL getACL() {
            return null;
        }

        @Override
        public void checkPermission(Permission permission) throws AccessDeniedException {
        }

        @Override
        public boolean hasPermission(Permission permission) {
            return true;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright (c) 2012 Ngewi Fet <ngewif@gmail.com>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    android:divider="?android:attr/dividerHorizontal"
    android:showDividers="middle">

    <!-- placeholder, allows the divider to be displayed -->
    <View android:layout_width="match_parent"
        android:layout_height="0dp" />

    <LinearLayout style="?android:attr/buttonBarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button android:id="@+id/btn_cancel"
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:drawableLeft="@drawable/navigation_cancel_holo_light"
            android:text="@string/btn_cancel" />

        <Button android:id="@+id/btn_save"
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:drawableLeft="@drawable/navigation_accept_holo_light"
            android:text="@string/btn_save" />
    </LinearLayout>
</LinearLayout>


text:
package bsw

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"
)

const censysURL = "https://www.censys.io/api/v1"

type censysSearchResponse struct {
	Status  string `json:"status"`
	Results []struct {
		IP string `json:"ip"`
	} `json:"results"`
	Metadata struct {
		Pages int `json:"pages"`
	} `json:"metadata"`
}

type censysViewResponse struct {
	Num443 struct {
		HTTPS struct {
			TLS struct {
				Certificate struct {
					Parsed struct {
						Extensions struct {
							SubjectAltName struct {
								DNSNames []string `json:"dns_names"`
							} `json:"subject_alt_name"`
						} `json:"extensions"`
						Subject struct {
							CommonName []string `json:"common_name"`
						} `json:"subject"`
					} `json:"parsed"`
				} `json:"certificate"`
			} `json:"tls"`
		} `json:"https"`
	} `json:"443"`
}

// CensysDomain search censys.io for a particular domain.
// After a list of IP addresses are found to be matching the domain,
// each ip in the list is looked up using the 'view' search.
// This TLS certificates for each IP, hostnames are gathers from these
// TLS certificates.
func CensysDomain(domain, auth string) *Tsk {
	t := newTsk("censys.io Domain")
	p := 1
	ips, pages, err := censysSearch(domain, auth, p)
	if err != nil {
		t.SetErr(err)
		return t
	}
	p++
	for p <= pages {
		i, _, err := censysSearch(domain, auth, p)
		if err != nil {
			t.SetErr(err)
			return t
		}
		p++
		ips = append(ips, i...)
	}
	for _, ip := range ips {
		names, err := censysView(ip, auth)
		if err != nil {
			t.SetErr(err)
			return t
		}
		for _, n := range removeDuplicates(names) {
			if ok, err := regexp.Match(DomainRegex, []byte(n)); !ok || err != nil {
				continue
			}
			if strings.Contains(n, domain) && n != domain {
				t.AddResult(ip, n)
			}
		}
	}
	return t
}

// CensysIP search an ip using censys.io's ipv4 view.
// Hostnames are extracted from previously gathered TLS certificates.
func CensysIP(ip, auth string) *Tsk {
	t := newTsk("censys.io IP search")
	names, err := censysView(ip, auth)
	if err != nil {
		t.SetErr(err)
		return t
	}
	for _, n := range removeDuplicates(names) {
		if ok, err := regexp.Match(DomainRegex, []byte(n)); ok && err == nil {
			t.AddResult(ip, n)
		}
	}
	return t
}

func censysSearch(domain, auth string, page int) ([]string, int, error) {
	buf := bytes.NewBuffer([]byte(fmt.Sprintf("{\"query\": \"%s\", \"page\": %d}", domain, page)))
	req, err := http.NewRequest("POST", fmt.Sprintf("%s/search/ipv4", censysURL), buf)
	ips := []string{}
	if err != nil {
		return ips, 0, err
	}
	parts := strings.Split(auth, ":")
	if len(parts) != 2 {
		return ips, 0, errors.New("Invalid auth string for censys.io")
	}
	req.SetBasicAuth(parts[0], parts[1])
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return ips, 0, err
	}
	if resp.StatusCode != 200 {
		return ips, 0, errors.New("Request returned non 200 status code")
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return ips, 0, err
	}
	m := &censysSearchResponse{}
	if err = json.Unmarshal(body, &m); err != nil {
		return ips, 0, err
	}
	for _, r := range m.Results {
		ips = append(ips, r.IP)
	}
	return ips, m.Metadata.Pages, nil
}

func censysView(ip, auth string) ([]string, error) {
	names := []string{}
	client := &http.Client{}
	req, err := http.NewRequest("GET", fmt.Sprintf("%s/view/ipv4/%s", censysURL, ip), nil)
	if err != nil {
		return names, err
	}
	parts := strings.Split(auth, ":")
	if len(parts) != 2 {
		return names, errors.New("Invalid auth string for censys.io")
	}
	req.SetBasicAuth(parts[0], parts[1])
	resp, err := client.Do(req)
	if err != nil {
		return names, err
	}
	if resp.StatusCode != 200 {
		return names, errors.New("Request returned non 200 status code")
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return names, err
	}
	m := &censysViewResponse{}
	if err = json.Unmarshal(body, &m); err != nil {
		return names, err
	}
	names = append(names, m.Num443.HTTPS.TLS.Certificate.Parsed.Extensions.SubjectAltName.DNSNames...)
	names = append(names, m.Num443.HTTPS.TLS.Certificate.Parsed.Subject.CommonName...)
	return names, nil
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: The Date.prototype property "setMonth" has { DontEnum } attributes
es5id: 15.9.5.38_A1_T2
description: Checking absence of DontDelete attribute
includes: [$FAIL.js]
---*/

if (delete Date.prototype.setMonth  === false) {
  $ERROR('#1: The Date.prototype.setMonth property has not the attributes DontDelete');
}

if (Date.prototype.hasOwnProperty('setMonth')) {
  $FAIL('#2: The Date.prototype.setMonth property has not the attributes DontDelete');
}


text:
'use strict'

const joi = require('joi')

const envVarsSchema = joi.object({
  NODE_ENV: joi.string()
    .allow(['development', 'production', 'test', 'provision'])
    .required()
}).unknown()
  .required()

const { error, value: envVars } = joi.validate(process.env, envVarsSchema)
if (error) {
  throw new Error(`Config validation error: ${error.message}`)
}

const config = {
  env: envVars.NODE_ENV,
  firebase_key_path: '../firebase/puzzle-c6f1c-firebase-adminsdk-sf2m5-d5e7f7c434.json',
  base_domain: 'http://ec2-13-113-12-108.ap-northeast-1.compute.amazonaws.com:3000',
  confirm_uri: '/users/user/verify',
  mail_id: envVars.MAIL_ID,
  mail_pass: envVars.MAIL_PASS,
  mail_retry: 3,
  mail_smtp_domain: 'smtp.gmail.com',
  mail_smtp_port: 587
}

module.exports = config


text:
[![Logbook](https://github.com/zalando/logbook/raw/master/docs/logbook.jpg)](https://github.com/zalando/logbook#credits-and-references)

[![Javadoc](https://www.javadoc.io/badge/org.zalando/riptide-logbook.svg)](http://www.javadoc.io/doc/org.zalando/riptide-logbook)
[![Maven Central](https://img.shields.io/maven-central/v/org.zalando/riptide-logbook.svg)](https://maven-badges.herokuapp.com/maven-central/org.zalando/riptide-logbook)

*Riptide: Logbook* adds [Logbook](https://github.com/zalando/logbook) support to Riptide.

## Example

```java
Http.builder()
    .plugin(new LogbookPlugin(logbook))
    .build();
```

## Features

- Logbook (request and response logging) support

## Dependencies

- Java 8
- Riptide: Core

## Installation

Add the following dependency to your project:

```xml
<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>riptide-logbook</artifactId>
    <version>${riptide.version}</version>
</dependency>
```

## Configuration

Configuration of Logbook is documented at [zalando/logbook](https://github.com/zalando/logbook#usage).

If configuring it manually is not desired you're encouraged to make use of the
[Logbook-](https://github.com/zalando/logbook#spring-boot-starter) and
[Riptide Spring Boot Auto Configuration](../riptide-spring-boot-autoconfigure)

The default configuration will produce log message like the following:

```http
Incoming Request: 2d66e4bc-9a0d-11e5-a84c-1f39510f0d6b
GET http://example.org/test HTTP/1.1
Accept: application/json
Host: localhost
Content-Type: text/plain

Hello world!
```

```http
Outgoing Response: 2d66e4bc-9a0d-11e5-a84c-1f39510f0d6b
Duration: 25 ms
HTTP/1.1 200
Content-Type: application/json

{"value":"Hello world!"}
```

## Getting Help

If you have questions, concerns, bug reports, etc., please file an issue in this repository's [Issue Tracker](../../../../issues).

## Getting Involved/Contributing

To contribute, simply make a pull request and add a brief description (1-2 sentences) of your addition or change. For
more details, check the [contribution guidelines](../.github/CONTRIBUTING.md).


text:
import React, { PropTypes } from 'react'
import Component from 'react-pure-render/component'
import Dialog from 'material-ui/lib/dialog'
import FlatButton from 'material-ui/lib/flat-button'
import { connect } from 'react-redux'
import { ActionCreators } from 'app/actions'

const { clearServerError, clearNetworkError } = ActionCreators

export class CriticalErrorAlert extends Component {
    render () {
        const {
            serverError,
            networkError,
            clearServerError,
            clearNetworkError,
        } = this.props

        const open = serverError || networkError

        let closeAction
        if (open) {
            closeAction = serverError ? clearServerError : clearNetworkError
        }

        let message
        if (serverError) {
            message = `A problem occurred on the server.
                       Please try again later.`
        } else if (networkError) {
            message = `Cannot connect to internet.
                       Please ensure you're connected and try again.`
        }

        const closeButton = (
            <FlatButton
             key="close-button"
             label="Close"
             primary={true}
             onTouchTap={closeAction} />
        )

        // TODO: no need to wrap `closeAction` in array
        // after upgrading to `material-ui` v0.14.x

        return (
            <Dialog
             title="Oops!"
             actions={[closeButton]}
             open={open}
             onRequestClose={closeAction}>

              {message}

            </Dialog>
        )
    }
}

CriticalErrorAlert.propTypes = {
    serverError: PropTypes.bool.isRequired,
    networkError: PropTypes.bool.isRequired,
    clearServerError: PropTypes.func.isRequired,
    clearNetworkError: PropTypes.func.isRequired,
}

const mapStateToProps = ({ serverError, networkError }) =>
    ({ serverError, networkError })

export default connect(mapStateToProps, {
    clearServerError, clearNetworkError
})(CriticalErrorAlert)


text:
"""

Python Interchangeable Virtual Instrument Library

Copyright (c) 2012-2016 Alex Forencich

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

"""

import serial
import time
import re

def parse_visa_resource_string(resource_string):
    # valid resource strings:
    # ASRL1::INSTR
    # ASRL::COM1::INSTR
    # ASRL::COM1,9600::INSTR
    # ASRL::COM1,9600,8n1::INSTR
    # ASRL::/dev/ttyUSB0::INSTR
    # ASRL::/dev/ttyUSB0,9600::INSTR
    # ASRL::/dev/ttyUSB0,9600,8n1::INSTR
    m = re.match('^(?P<prefix>(?P<type>ASRL)\d*)(::(?P<arg1>[^\s:]+))?(::(?P<suffix>INSTR))$',
            resource_string, re.I)

    if m is not None:
        return dict(
                type = m.group('type').upper(),
                prefix = m.group('prefix'),
                arg1 = m.group('arg1'),
                suffix = m.group('suffix'),
        )

class SerialInstrument:
    "Serial instrument interface client"
    def __init__(self, port = None, baudrate=9600, bytesize=8, paritymode=0, stopbits=1, timeout=None,
                xonxoff=False, rtscts=False, dsrdtr=False):

        if port.upper().startswith("ASRL") and '::' in port:
            res = parse_visa_resource_string(port)

            if res is None:
                raise IOError("Invalid resource string")

            index = res['prefix'][4:]
            if len(index) > 0:
                port = int(index)
            else:
                # port[,baud[,nps]]
                # n = data bits (5,6,7,8)
                # p = parity (n,o,e,m,s)
                # s = stop bits (1,1.5,2)
                t = res['arg1'].split(',')
                port = t[0]
                if len(t) > 1:
                    baudrate = int(t[1])

        self.serial = serial.Serial(port)

        self.term_char = '\n'

        self.port = port

        self.baudrate = baudrate
        self.bytesize = bytesize
        self.paritymode = paritymode
        self.stopbits = stopbits
        self.timeout = timeout
        self.xonxoff = xonxoff
        self.rtscts = rtscts
        self.dsrdtr = dsrdtr

        self.wait_dsr = False
        self.message_delay = 0

        self.update_settings()

    def update_settings(self):

        self.serial.baudrate = self.baudrate

        if self.bytesize == 5:
            self.serial.bytesize = serial.FIVEBITS
        elif self.bytesize == 6:
            self.serial.bytesize = serial.SIXBITS
        elif self.bytesize == 7:
            self.serial.bytesize = serial.SEVENBITS
        else:
            self.serial.bytesize = serial.EIGHTBITS

        if self.paritymode == 1:
            self.serial.paritymode = serial.PARITY_ODD
        elif self.paritymode == 2:
            self.serial.paritymode = serial.PARITY_EVEN
        elif self.paritymode == 3:
            self.serial.paritymode = serial.PARITY_MARK
        elif self.paritymode == 4:
            self.serial.paritymode = serial.PARITY_SPACE
        else:
            self.serial.paritymode = serial.PARITY_NONE

        if self.stopbits == 1.5:
            self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
        elif self.stopbits == 2:
            self.serial.stopbits = serial.STOPBITS_TWO
        else:
            self.serial.stopbits = serial.STOPBITS_ONE

        self.serial.timeout = self.timeout
        self.serial.xonxoff = self.xonxoff
        self.serial.rtscts = self.rtscts
        self.serial.dsrdtr = self.dsrdtr

        if self.dsrdtr:
            self.wait_dsr = True
            self.message_delay = 0.1

    def write_raw(self, data):
        "Write binary data to instrument"

        if self.term_char is not None:
            data += str(self.term_char).encode('utf-8')[0:1]

        self.serial.write(data)

        if self.message_delay > 0:
            time.sleep(self.message_delay)

        if self.wait_dsr:
            while not self.serial.getDSR():
                time.sleep(0.01)

    def read_raw(self, num=-1):
        "Read binary data from instrument"

        data = b''
        term_char = str(self.term_char).encode('utf-8')[0:1]

        while True:
            c = self.serial.read(1)
            data += c
            num -= 1
            if c == term_char:
                break
            if num == 0:
                break

        return data

    def ask_raw(self, data, num=-1):
        "Write then read binary data"
        self.write_raw(data)
        return self.read_raw(num)

    def write(self, message, encoding = 'utf-8'):
        "Write string to instrument"
        if type(message) is tuple or type(message) is list:
            # recursive call for a list of commands
            for message_i in message:
                self.write(message_i, encoding)
            return

        self.write_raw(str(message).encode(encoding))

    def read(self, num=-1, encoding = 'utf-8'):
        "Read string from instrument"
        return self.read_raw(num).decode(encoding).rstrip('\r\n')

    def ask(self, message, num=-1, encoding = 'utf-8'):
        "Write then read string"
        if type(message) is tuple or type(message) is list:
            # recursive call for a list of commands
            val = list()
            for message_i in message:
                val.append(self.ask(message_i, num, encoding))
            return val

        self.write(message, encoding)
        return self.read(num, encoding)

    def read_stb(self):
        "Read status byte"
        raise NotImplementedError()

    def trigger(self):
        "Send trigger command"
        self.write("*TRG")

    def clear(self):
        "Send clear command"
        self.write("*CLS")

    def remote(self):
        "Send remote command"
        raise NotImplementedError()

    def local(self):
        "Send local command"
        raise NotImplementedError()

    def lock(self):
        "Send lock command"
        raise NotImplementedError()

    def unlock(self):
        "Send unlock command"
        raise NotImplementedError()