text:
{-# LANGUAGE GADTs, DeriveDataTypeable, BangPatterns, ImplicitParams, MagicHash #-}
module Types
  ( Exp(..)
  , ExpC(..)
  , Word64
  , MWord64
  , nothing64
  , fromMWord64
  , isNothing64
  , eval
  , isConstExpr
  , isConstExprC
  , progSize
  , expSize
  , expCSize
  , zero, one, mainArg, fold1Arg, fold2Arg, if0, fold_, not_, shl1, shr1, shr4, shr16, and_ , or_ , xor_, plus
  )
  where

import Data.Word
import Data.Bits
import Data.Data (Data)
import Data.Typeable (Typeable)
import Data.Maybe
import Control.Applicative
import Control.Monad
import RandomBV

-- Expression that caches result of evaluation on the first bitvector that we would test on
seed = head bvs

-- Packed "Maybe Word64"
newtype MWord64 = MWord64 Word64
  deriving (Show, Data, Typeable)

specialNothingValue = 0x1223071404BCBC05

just64 :: Word64 -> MWord64
just64 !x = MWord64 x

nothing64 :: MWord64
nothing64 = MWord64 specialNothingValue

isNothing64 :: MWord64 -> Bool
isNothing64 (MWord64 x) = x == specialNothingValue

unsafeValue64 :: MWord64 -> Word64
unsafeValue64 (MWord64 x) = x

fromMWord64 :: Word64 -> MWord64 -> Word64
fromMWord64 def x = if isNothing64 x then def else unsafeValue64 x

-- We use this function only when it's cheaper to apply f than to check b :)
map64 :: (Word64 -> Word64) -> MWord64 -> MWord64
map64 f x = if isNothing64 x then nothing64 else just64 (f (unsafeValue64 x))

zip64 :: (Word64 -> Word64 -> Word64) -> MWord64 -> MWord64 -> MWord64
zip64 f x y = if isNothing64 x || isNothing64 y
              then nothing64
              else just64 (f (unsafeValue64 x) (unsafeValue64 y))

data ExpC = ExpC {cached :: {-# UNPACK #-} !MWord64, expr :: Exp} deriving (Show, Data, Typeable)
instance Eq ExpC where
  (ExpC _ a) == (ExpC _ b) = a == b
instance Ord ExpC where
  compare (ExpC _ a) (ExpC _ b) = compare a b

data Exp =
    Zero
  | One
  | MainArg
  | Fold1Arg
  | Fold2Arg
  | If { ifCond :: ExpC, ifTrue :: ExpC, ifFalse :: ExpC }
  | Fold { foldArg :: ExpC, foldSeed :: ExpC, foldBody :: ExpC }
  | Not ExpC
  | Shl1 ExpC
  | Shr1 ExpC
  | Shr4 ExpC
  | Shr16 ExpC
  | And ExpC ExpC
  | Or ExpC ExpC
  | Xor ExpC ExpC
  | Plus ExpC ExpC
  deriving (Eq, Ord, Show, Data, Typeable)

isConstExprC (ExpC _ e) = isConstExpr e

isConstExpr Zero = True
isConstExpr One = True
isConstExpr MainArg = False
isConstExpr Fold1Arg = False
isConstExpr Fold2Arg = False
isConstExpr (If a b c) = isConstExprC a && isConstExprC b && isConstExprC c
isConstExpr (Fold a b c) = isConstExprC a && isConstExprC b && isConstExprC c
isConstExpr (Not a) = isConstExprC a
isConstExpr (Shl1 a) = isConstExprC a
isConstExpr (Shr1 a) = isConstExprC a
isConstExpr (Shr4 a) = isConstExprC a
isConstExpr (Shr16 a) = isConstExprC a
isConstExpr (And a b) = isConstExprC a && isConstExprC b
isConstExpr (Or a b) = isConstExprC a && isConstExprC b
isConstExpr (Xor a b) = isConstExprC a && isConstExprC b
isConstExpr (Plus a b) = isConstExprC a && isConstExprC b

eval :: Word64 -> Word64 -> Word64 -> ExpC -> Word64
eval main fold1 fold2 e =
  case expr e of
    Zero -> 0
    One -> 1
    MainArg -> main
    Fold1Arg -> fold1
    Fold2Arg -> fold2
    If c t f -> if eval main fold1 fold2 c == 0
                then eval main fold1 fold2 t
                else eval main fold1 fold2 f
    Not e -> complement (eval main fold1 fold2 e)
    Shl1 e -> shiftL (eval main fold1 fold2 e) 1
    Shr1 e -> shiftR (eval main fold1 fold2 e) 1
    Shr4 e -> shiftR (eval main fold1 fold2 e) 4
    Shr16 e -> shiftR (eval main fold1 fold2 e) 16
    And e1 e2 -> eval main fold1 fold2 e1 .&. eval main fold1 fold2 e2
    Or e1 e2 -> eval main fold1 fold2 e1 .|. eval main fold1 fold2 e2
    Xor e1 e2 -> xor (eval main fold1 fold2 e1) (eval main fold1 fold2 e2)
    Plus e1 e2 -> eval main fold1 fold2 e1 + eval main fold1 fold2 e2
    Fold arg seed body -> foldImpl (eval main) (eval main fold1 fold2 arg) (eval main fold1 fold2 seed) body

foldImpl
  :: (Word64 -> Word64 -> ExpC -> Word64)
    -- ^ function to use for evaluation of fold body. We it may be plain
    -- 'eval', or its cached version. The arguments are fold1Arg, fold2Arg,
    -- and body.
  -> Word64 -- ^ fold1Arg
  -> Word64 -- ^ fold2Arg
  -> ExpC   -- ^ body
  -> Word64
foldImpl eval !x !seed body = op x0 (op x1 (op x2 (op x3 (op x4 (op x5 (op x6 (op x7 seed)))))))
  where
    op !a !b = eval a b body
    {-# INLINE op #-}
    -- x7 is least significant, x0 most significant
    (!x7', !x7) = x `divMod` 256
    (!x6', !x6) = x7' `divMod` 256
    (!x5', !x5) = x6' `divMod` 256
    (!x4', !x4) = x5' `divMod` 256
    (!x3', !x3) = x4' `divMod` 256
    (!x2', !x2) = x3' `divMod` 256
    (!x1', !x1) = x2' `divMod` 256
    (!x0', !x0) = x1' `divMod` 256

evalOnSeed :: MWord64 -> MWord64 -> Exp -> MWord64
evalOnSeed !fold1 !fold2 e = {-# SCC "evalOnSeed" #-}
  case e of
    Zero -> just64 0
    One -> just64 1
    MainArg -> just64 seed
    Fold1Arg -> fold1
    Fold2Arg -> fold2
    If a b c ->
      case ev fold1 fold2 a of {
        x | isNothing64 x -> nothing64
          | unsafeValue64 x == 0 -> ev fold1 fold2 b
          | otherwise            -> ev fold1 fold2 c
      }

    Fold a b c ->
      let
        evalFn :: Word64 -> Word64 -> ExpC -> Word64
        evalFn !f1Arg !f2Arg body = case ev (just64 f1Arg) (just64 f2Arg) body of {
          x | isNothing64 x -> error $ "Failed evaluation within fold: (f1,f2,body) = " ++ show (f1Arg, f2Arg, body)
            | otherwise -> unsafeValue64 x
        }
      in case (ev fold1 fold2 a, ev fold1 fold2 b) of {
           (x, y) | isNothing64 x || isNothing64 y -> nothing64
                  | otherwise                      -> just64 $ foldImpl evalFn (unsafeValue64 x) (unsafeValue64 y) c
         }
    Not a   -> map64 complement (ev fold1 fold2 a)
    Shl1 a  -> map64 (\x -> x `shiftL` 1) (ev fold1 fold2 a)
    Shr1 a  -> map64 (\x -> x `shiftR` 1) (ev fold1 fold2 a)
    Shr4 a  -> map64 (\x -> x `shiftR` 4) (ev fold1 fold2 a)
    Shr16 a -> map64 (\x -> x `shiftR` 16) (ev fold1 fold2 a)
    And a b -> zip64 (.&.) (ev fold1 fold2 a) (ev fold1 fold2 b)
    Or a b ->  zip64 (.|.) (ev fold1 fold2 a) (ev fold1 fold2 b)
    Xor a b -> zip64 (xor) (ev fold1 fold2 a) (ev fold1 fold2 b)
    Plus a b -> zip64 (+) (ev fold1 fold2 a) (ev fold1 fold2 b)
  where
    ev :: MWord64 -> MWord64 -> ExpC -> MWord64
    ev !fold1 !fold2 x = {-# SCC "ev" #-} case cached x of {
        c | not (isNothing64 c) -> c
        -- if x's value was unknown but fold args are now in scope, re-evaluate
        -- the tree
          | otherwise -> case (fold1, fold2) of {
              (a, b) | isNothing64 a || isNothing64 b -> nothing64
                     | otherwise -> {-# SCC "reevaluate" #-} evalOnSeed fold1 fold2 (expr x)
            }
      }

cache e = ExpC (evalOnSeed nothing64 nothing64 e) e
zero = ExpC (just64 0) Zero
one  = ExpC (just64 1) One
mainArg = ExpC (just64 seed) MainArg
fold1Arg = ExpC nothing64 Fold1Arg
fold2Arg = ExpC nothing64 Fold2Arg
if0 a b c = cache (If a b c)
fold_ a b c = cache (Fold a b c)
not_ a   = cache (Not a)
shl1 a  = cache (Shl1 a)
shr1 a  = cache (Shr1 a)
shr4 a  = cache (Shr4 a)
shr16 a = cache (Shr16 a)
and_ a b = cache (And a b)
or_ a b = cache (Or a b)
xor_ a b = cache (Xor a b)
plus a b = cache (Plus a b)

progSize :: Exp -> Int
progSize e = expSize e + 1

expCSize ec = expSize (expr ec)

expSize :: Exp -> Int
expSize Zero = 1
expSize One = 1
expSize MainArg = 1
expSize Fold1Arg = 1
expSize Fold2Arg = 1
expSize (If a b c) = 1 + expCSize a + expCSize b + expCSize c
expSize (Fold a b c) = 2 + expCSize a + expCSize b + expCSize c
expSize (Not a) = 1 + expCSize a
expSize (Shl1 a) = 1 + expCSize a
expSize (Shr1 a) = 1 + expCSize a
expSize (Shr4 a) = 1 + expCSize a
expSize (Shr16 a) = 1 + expCSize a
expSize (And a b) = 1 + expCSize a + expCSize b
expSize (Or a b) = 1 + expCSize a + expCSize b
expSize (Xor a b) = 1 + expCSize a + expCSize b
expSize (Plus a b) = 1 + expCSize a + expCSize b


text:
unset http_proxy

FORMAT="\n%{url_effective}, %{response_code}\n\n"
ADDRESS=127.0.0.1

# [LearningSwitch] ---- (Network01) ---- [Slicer] ----  (Network00)
#                                     |
# [LearningSwitch] ---- (Network02) --|

# create NetworkComponent , Aggregator , and other Component
# curl http://$ADDRESS:10080/systemmanager/component_managers | python -mjson.tool
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/network00 -X PUT -d '{"type": "Network", "id": "network00", "cm_id": "romgr1"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/network01 -X PUT -d '{"type": "Network", "id": "network01", "cm_id": "romgr1"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/network02 -X PUT -d '{"type": "Network", "id": "network02", "cm_id": "romgr1"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/lsw01 -X PUT -d '{"type": "LearningSwitch", "id": "lsw01", "cm_id": "romgr1"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/lsw02 -X PUT -d '{"type": "LearningSwitch", "id": "lsw02", "cm_id": "romgr1"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/slicer -X PUT -d '{"type": "Slicer", "id": "slicer", "cm_id": "romgr1"}'
curl http://$ADDRESS:10080/systemmanager/components | python -mjson.tool

sleep 1

# connect Components
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/slicer_nw00 -X PUT -d '{"id": "slicer_nw00", "type": "LogicAndNetwork", "connection_type": "original", "logic_id": "slicer", "network_id":"network00"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/slicer_nw01 -X PUT -d '{"id": "slicer_nw01", "type": "LogicAndNetwork", "connection_type": "sliver", "logic_id": "slicer", "network_id":"network01"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/slicer_nw02 -X PUT -d '{"id": "slicer_nw02", "type": "LogicAndNetwork", "connection_type": "sliver", "logic_id": "slicer", "network_id":"network02"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/lsw_nw01 -X PUT -d '{"id": "lsw_nw01", "type": "LogicAndNetwork", "connection_type": "sliver", "logic_id": "lsw01", "network_id":"network01"}'
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/lsw_nw02 -X PUT -d '{"id": "lsw_nw02", "type": "LogicAndNetwork", "connection_type": "sliver", "logic_id": "lsw02", "network_id":"network02"}'
curl http://$ADDRESS:10080/systemmanager/connections | python -mjson.tool

sleep 1

# make Topology
#                                                  [port0023]
#   [port0011](node001)[port0012] -----  [port0021](node002)[port0022] ----  [port0031](node003)[port0032]
#             [port0013]                           [port0024]                          [port0033]
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001 -X PUT -d '{"node_id": "node001", "type": "Node", "version": "0", "ports": {}, "attributes": {"oper_status":"UP", "physical_id":"001", "vendor":"VENDOR_A"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002 -X PUT -d '{"node_id": "node002", "type": "Node", "version": "0", "ports": {}, "attributes": {"oper_status":"UP", "physical_id":"002", "vendor":"VENDOR_A"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003 -X PUT -d '{"node_id": "node003", "type": "Node", "version": "0", "ports": {}, "attributes": {"oper_status":"UP", "physical_id":"003", "vendor":"VENDOR_A"}}'
sleep 1
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports/port0011 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node001", "port_id": "port0011", "out_link": null, "in_link": null, "attributes": {"physical_id":"0011@001"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports/port0012 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node001", "port_id": "port0012", "out_link": null, "in_link": null, "attributes": {"physical_id":"0012@001"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports/port0013 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node001", "port_id": "port0013", "out_link": null, "in_link": null, "attributes": {"physical_id":"0013@001"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0021 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node002", "port_id": "port0021", "out_link": null, "in_link": null, "attributes": {"physical_id":"0021@002"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0022 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node002", "port_id": "port0022", "out_link": null, "in_link": null, "attributes": {"physical_id":"0022@002"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0023 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node002", "port_id": "port0023", "out_link": null, "in_link": null, "attributes": {"physical_id":"0023@002"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0024 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node002", "port_id": "port0024", "out_link": null, "in_link": null, "attributes": {"physical_id":"0024@002"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports/port0031 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node003", "port_id": "port0031", "out_link": null, "in_link": null, "attributes": {"physical_id":"0031@003"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports/port0032 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node003", "port_id": "port0032", "out_link": null, "in_link": null, "attributes": {"physical_id":"0032@003"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports/port0033 -X PUT -d '{"type": "Port", "version": "0", "node_id": "node003", "port_id": "port0033", "out_link": null, "in_link": null, "attributes": {"physical_id":"0033@003"}}'

sleep 1

curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0012 -X PUT -d '{"type": "Link", "version": "0", "link_id": "link0012", "src_node": "node001", "src_port": "port0012", "dst_node": "node002", "dst_port": "port0021", "attributes": {"attr0021":"value0021"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0021 -X PUT -d '{"type": "Link", "version": "0", "link_id": "link0021", "src_node": "node002", "src_port": "port0021", "dst_node": "node001", "dst_port": "port0012", "attributes": {"attr0012":"value0012"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0023 -X PUT -d '{"type": "Link", "version": "0", "link_id": "link0023", "src_node": "node002", "src_port": "port0022", "dst_node": "node003", "dst_port": "port0031", "attributes": {"attr0031":"value0031"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0032 -X PUT -d '{"type": "Link", "version": "0", "link_id": "link0032", "src_node": "node003", "src_port": "port0031", "dst_node": "node002", "dst_port": "port0022", "attributes": {"attr0022":"value0022"}}'

sleep 1

echo "------ original network -------"
curl http://$ADDRESS:10080/systemmanager/components/network00/topology -X GET | python -mjson.tool
sleep 1
echo "------ sliver network1 -------"
curl http://$ADDRESS:10080/systemmanager/components/network01/topology -X GET | python -mjson.tool
echo "------ sliver network2 -------"
curl http://$ADDRESS:10080/systemmanager/components/network02/topology -X GET | python -mjson.tool

echo "------ create slicer conditions -------"
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/40/conditions/sliceconditon1 -X PUT -d '{"id":"sliceconditon1", "type":"BasicSliceCondition", "connection":"slicer_nw01", "in_node":"node001","in_port":"port0011"}'
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/40/conditions/sliceconditon2 -X PUT -d '{"id":"sliceconditon2", "type":"BasicSliceCondition", "connection":"slicer_nw01", "in_node":"node003","in_port":"port0032"}'
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/50 -X PUT -d '[{"id":"sliceconditon3", "type":"BasicSliceCondition", "connection":"slicer_nw02", "in_node":"node001","in_port":"port0013"}, {"id":"sliceconditon4", "type":"BasicSliceCondition", "connection":"slicer_nw02", "in_node":"node003","in_port":"port0033"}]'

sleep 2

echo "------ get slicer conditions -------"
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/10 -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/20 -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/conditions/sliceconditon1 -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/conditions/sliceconditon2 -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/connections/slicer_nw01 -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/slicer/settings/slice_condition_table/connections/slicer_nw02 -X GET

sleep 1

# packet
echo "------ POST InPacket -------"
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/in -X POST -d '{"type":"OFPInPacket", "node":"node001", "port":"port0011" , "header":{"type":"OFPFlowMatch", "in_node":"node001", "in_port":"port0011", "eth_src":"00:11:22:33:44:55", "eth_dst":"66:77:88:99:00:11"}, "data":"ABCDEFGHIJKLMN", "attributes": {"test_attr":"test_attr_value"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/in -X POST -d '{"type":"OFPInPacket", "node":"node003", "port":"port0032" , "header":{"type":"OFPFlowMatch", "in_node":"node003", "in_port":"port0032", "eth_src":"66:77:88:99:00:11", "eth_dst":"00:11:22:33:44:55"}, "data":"ABCDEFGHIJKLMN", "attributes": {"test_attr":"test_attr_value"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/in -X POST -d '{"type":"OFPInPacket", "node":"node001", "port":"port0011" , "header":{"type":"OFPFlowMatch", "in_node":"node001", "in_port":"port0011", "eth_src":"00:11:22:33:44:55", "eth_dst":"66:77:88:99:00:11"}, "data":"ABCDEFGHIJKLMN", "attributes": {"test_attr":"test_attr_value"}}'

curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/in -X POST -d '{"type":"OFPInPacket", "node":"node001", "port":"port0013" , "header":{"type":"OFPFlowMatch", "in_node":"node001", "in_port":"port0013", "eth_src":"ff:11:22:33:44:55", "eth_dst":"ee:cc:88:99:00:11"}, "data":"12345678abcdefg", "attributes": {"test_attr2":"test_attr_value2"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/in -X POST -d '{"type":"OFPInPacket", "node":"node003", "port":"port0033" , "header":{"type":"OFPFlowMatch", "in_node":"node003", "in_port":"port0033", "eth_src":"ee:cc:88:99:00:11", "eth_dst":"ff:11:22:33:44:55"}, "data":"12345678abcdefg", "attributes": {"test_attr2":"test_attr_value2"}}'
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/in -X POST -d '{"type":"OFPInPacket", "node":"node001", "port":"port0013" , "header":{"type":"OFPFlowMatch", "in_node":"node001", "in_port":"port0013", "eth_src":"ff:11:22:33:44:55", "eth_dst":"ee:cc:88:99:00:11"}, "data":"12345678abcdefg", "attributes": {"test_attr2":"test_attr_value2"}}'

sleep 1

echo "------ Get In/OutPacket(network00) -------"
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets -X GET
echo "------ Get In/OutPacket(network01) -------"
curl -w "$FORMAT" http://$ADDRESS:10080/network01/packets -X GET
echo "------ Get In/OutPacket(network02) -------"
curl -w "$FORMAT" http://$ADDRESS:10080/network02/packets -X GET

echo "---------------- flow (network00)-------------------"
curl http://$ADDRESS:10080/systemmanager/components/network00/flows -X GET | python -mjson.tool
echo "---------------- flow (network01)-------------------"
curl http://$ADDRESS:10080/systemmanager/components/network01/flows -X GET | python -mjson.tool
echo "---------------- flow (network02)-------------------"
curl http://$ADDRESS:10080/systemmanager/components/network02/flows -X GET | python -mjson.tool

sleep 1

echo ""
echo "*************************************************"
echo "***************[ Result ]************************"
echo "*************************************************"
echo ""

sleep 2
echo "/////////////////////////////////////////////////"
echo "//////////////// search Node ////////////////////"
echo "/////////////////////////////////////////////////"
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes?'attributes="physical_id=001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes?'attributes="physical_id=002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes?'attributes="physical_id=003"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes?'attributes="physical_id=001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes?'attributes="physical_id=002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes?'attributes="physical_id=003"' -X GET

sleep 2
echo "/////////////////////////////////////////////////"
echo "//////////////// search Port ////////////////////"
echo "/////////////////////////////////////////////////"
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports?'attributes="physical_id=0011@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports?'attributes="physical_id=0012@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports?'attributes="physical_id=0013@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports?'attributes="physical_id=0021@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports?'attributes="physical_id=0022@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports?'attributes="physical_id=0023@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports?'attributes="physical_id=0031@003"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports?'attributes="physical_id=0032@003"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports?'attributes="physical_id=0033@003"' -X GET

curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node001/ports?'attributes="physical_id=0011@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node001/ports?'attributes="physical_id=0012@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node001/ports?'attributes="physical_id=0013@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node002/ports?'attributes="physical_id=0021@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node002/ports?'attributes="physical_id=0022@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node002/ports?'attributes="physical_id=0023@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node003/ports?'attributes="physical_id=0031@003"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node003/ports?'attributes="physical_id=0032@003"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/nodes/node003/ports?'attributes="physical_id=0033@003"' -X GET

curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node001/ports?'attributes="physical_id=0011@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node001/ports?'attributes="physical_id=0012@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node001/ports?'attributes="physical_id=0013@001"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node002/ports?'attributes="physical_id=0021@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node002/ports?'attributes="physical_id=0022@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node002/ports?'attributes="physical_id=0023@002"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node003/ports?'attributes="physical_id=0031@003"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node003/ports?'attributes="physical_id=0032@003"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/nodes/node003/ports?'attributes="physical_id=0033@003"' -X GET

sleep 2
echo "/////////////////////////////////////////////////"
echo "//////////////// search Link ////////////////////"
echo "/////////////////////////////////////////////////"
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links?'attributes="attr0021=value0021"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links?'attributes="attr0012=value0012"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links?'attributes="attr0031=value0031"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links?'attributes="attr0022=value0022"' -X GET

curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/links?'attributes="attr0021=value0021"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/links?'attributes="attr0012=value0012"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/links?'attributes="attr0031=value0031"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/topology/links?'attributes="attr0022=value0022"' -X GET

curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/links?'attributes="attr0021=value0021"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/links?'attributes="attr0012=value0012"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/links?'attributes="attr0031=value0031"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/topology/links?'attributes="attr0022=value0022"' -X GET

sleep 2
echo "/////////////////////////////////////////////////"
echo "//////////////// search OutPacket ///////////////"
echo "/////////////////////////////////////////////////"
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out?'attributes="test_attr=test_attr_value"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out?'attributes="test_attr2=test_attr_value2"' -X GET

sleep 2
echo "/////////////////////////////////////////////////"
echo "//////////////// search Flow ////////////////////"
echo "/////////////////////////////////////////////////"
curl -w "$FORMAT" http://$ADDRESS:10080/network00/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node001,in_port=port0011"&actions="type=FlowActionOutput,edge_node=node003,output=port0032"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node001,in_port=port0013"&actions="type=FlowActionOutput,edge_node=node003,output=port0033"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node003,in_port=port0032"&actions="type=FlowActionOutput,edge_node=node001,output=port0011"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network00/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node003,in_port=port0033"&actions="type=FlowActionOutput,edge_node=node001,output=port0013"' -X GET

curl -w "$FORMAT" http://$ADDRESS:10080/network01/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node001,in_port=port0011"&actions="type=FlowActionOutput,edge_node=node003,output=port0032"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network01/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node003,in_port=port0032"&actions="type=FlowActionOutput,edge_node=node001,output=port0011"' -X GET

curl -w "$FORMAT" http://$ADDRESS:10080/network02/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node001,in_port=port0013"&actions="type=FlowActionOutput,edge_node=node003,output=port0033"' -X GET
curl -w "$FORMAT" http://$ADDRESS:10080/network02/flows?'type=OFPFlow&match="type=OFPFlowMatch,in_node=node003,in_port=port0033"&actions="type=FlowActionOutput,edge_node=node001,output=port0013"' -X GET

echo ""
echo "***********************************************"
echo "***************[ Delete ]**********************"
echo "***********************************************"
echo ""
sleep 2

echo ""
echo "////////////////////////////////////////////////////"
echo "////////// Delete Outpacket to original  ///////////"
echo "////////////////////////////////////////////////////"
sleep 2
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out/0000000000 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out/0000000001 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out/0000000002 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out/0000000003 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out/0000000004 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/packets/out/0000000005 -X DELETE

echo ""
echo "////////////////////////////////////////////////////"
echo "////////// Delete Topology to original  ///////////"
echo "////////////////////////////////////////////////////"
sleep 2
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0012 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0021 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0023 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/links/link0032 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/physical_ports/0011@001 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports/port0012 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001/ports/port0013 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0021 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0022 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0023 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002/ports/port0024 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports/port0031 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports/port0032 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node003/ports/port0033 -X DELETE
sleep 1
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node001 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/nodes/node002 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/network00/topology/physical_nodes/003 -X DELETE
sleep 1

echo "------ Check network00's Topology -------"
curl http://$ADDRESS:10080/systemmanager/components/network00/topology -X GET | python -mjson.tool
echo "------ Check network01's Topology -------"
curl http://$ADDRESS:10080/systemmanager/components/network01/topology -X GET | python -mjson.tool
echo "------ Check network02's Topology -------"
curl http://$ADDRESS:10080/systemmanager/components/network02/topology -X GET | python -mjson.tool

sleep 1
echo ""
echo "/////////////////////////////////////////"
echo "////////// Delete Connections ///////////"
echo "/////////////////////////////////////////"
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/slicer_nw00 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/slicer_nw01 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/slicer_nw02 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/lsw_nw01 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/connections/lsw_nw02 -X DELETE

sleep 3
echo ""
echo "/////////////////////////////////////////"
echo "////////// Delete Components  ///////////"
echo "/////////////////////////////////////////"
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/network00 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/network01 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/network02 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/lsw01 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/lsw02 -X DELETE
curl -w "$FORMAT" http://$ADDRESS:10080/systemmanager/components/slicer -X DELETE

echo "------ Check Components -------"
curl http://$ADDRESS:10080/systemmanager/components -X GET | python -mjson.tool

echo "------ Check Connections -------"
curl http://$ADDRESS:10080/systemmanager/connections -X GET | python -mjson.tool

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Nunez Solutions Seminar
date: 2016-05-24
author: Maria Gamble
tags: weekly links, java
status: published
summary: Duis nec fermentum velit, imperdiet aliquam nunc. Vestibulum.
banner: images/banner/people.jpg
booking:
  startDate: 09/27/2019
  endDate: 09/28/2019
  ctyhocn: DACFLHX
  groupCode: NSS
published: true
---
Suspendisse consectetur, risus id dictum elementum, nisl sem facilisis risus, efficitur aliquam orci tellus at ex. Donec sit amet rhoncus lorem. Mauris tincidunt odio et leo posuere, non luctus nunc euismod. Duis sed laoreet diam, nec sodales urna. Vivamus hendrerit libero metus, vitae porta est blandit non. Sed velit quam, iaculis ac commodo id, lobortis ut justo. Curabitur egestas blandit quam, at congue nunc iaculis sit amet. Quisque a tellus purus. Fusce blandit at nulla ac tempor. Donec consequat lectus sit amet est pretium semper. Nunc placerat rhoncus sem, at fringilla augue dignissim eu. In ac purus in lorem mollis vehicula quis a ligula.

1 Nunc et nunc id nisl euismod rhoncus vel volutpat sem
1 Sed imperdiet orci vitae erat semper, at mollis tellus elementum
1 Phasellus in turpis vitae ante dapibus suscipit a vel diam
1 Vestibulum quis metus at nisl egestas ornare
1 Fusce ut ligula convallis, condimentum lacus ut, placerat lorem
1 Donec quis est mollis, ornare eros ac, molestie erat.

Etiam libero elit, vulputate sit amet consequat non, accumsan sed quam. Maecenas porttitor finibus arcu volutpat luctus. Donec consectetur lacinia eros, in malesuada lorem bibendum ac. Integer et nisi lacinia, interdum mauris quis, imperdiet turpis. Cras vel diam nulla. Ut feugiat vel quam id rhoncus. Sed consectetur commodo sem, non viverra magna. Duis tempor vestibulum libero dapibus varius. In hac habitasse platea dictumst. Donec condimentum elit eget pellentesque bibendum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec commodo volutpat metus, sed consectetur risus porta eget. Nulla nisi erat, dignissim vel blandit sed, dapibus viverra ligula. Proin dignissim nisi ornare, laoreet dui et, fermentum nisl. Maecenas et turpis sit amet nisi ultricies cursus ut lacinia sem. Aliquam finibus maximus ante, sit amet consequat ex eleifend a.


text:
"""
An MQTT node that runs a camera scheduler for one or more foscams.
The camera scheduler takes care of managing the use of the cameras
"""
__author__ = "Daniel Casner <www.danielcasner.org>"

import sys, os, json
import camscheduler
import paho.mqtt.client as mqtt

class CamqttServer(mqtt.Client):
    "ISA MQTT client, HAS several cam schedulers"

    REQUEST_SUFFIX = "_request"

    def on_snapshot(self, snapshot, preset, final, userdata):
        self.publish(userdata, json.dumps({'preset': preset, 'final': final}).encode() + b'\0' + snapshot)

    def on_connect(self, userdata, flags, rc):
        "Subscribe to topics on connect in case of disconnection"
        for camName in self.schedulers.keys():
            self.subscribe(name + self.REQUEST_SUFFIX, qos=2)

    def on_message(self, userdata, msg):
        if not msg.topic.endswith(self.REQUEST_SUFFIX):
            sys.stderr.write("Received unexpected topic: \"{}\"{}".format(msg.topic, os.linesep))
        else:
            camera = msg.topic[:-len(self.REQUEST_SUFFIX)]
            if not camera in self.schedulers:
                sys.stderr.write("Received request for camera \"{}\" but we only have{linesep}\t{}{linesep}".format(camera, repr(self.schedulers.keys(), linesep=os.linesep)))
            else:
                try:
                    command, args = json.loads(msg.payload)
                    args.update({'callback': self.on_snapshot, 'userdata': cammera})
                    if command == 'snapshot':
                        self.schedulers[camera].snapshot(**args)
                    elif command == 'internal':
                        self.schedulers[camera].interval(**args)
                    else:
                        raise ValueError("Invalid scheduler command: " + command)
                except Exception as e:
                    sys.stderr.write(str(e))

    def __init__(self, clientID, broker, cameras):
        """Initalize camera server
        @param clientID The MQTT client ID for the server
        @param The host name / IP address of the broker
        @param cameras A dictionary of named foscam instances. The names of the cameras be used as base names for MQTT
        topics for requesting and receiving images. The server will subscribe to a topic <NAME>_request for each camera
        to receive snapshot requests. Snapshots will be published as <NAME>_snapshot
        """
        mqtt.Client.__init__(self, clientID, True)
        self.schedulers = {name: camscheduler.FoscamScheduler(camera) for name, camera in cameras.items()}
        self.connect(broker)

class CamqttClient(mqtt.Client):
    "ISA MQTT client for requesting scheduled snapshots"

    def on_connect(self, userdata, flags, rc):


text:
/*
 * A program that predicts structures composed of probable base pairs and single-stranded nucleotides.
 *
 * (c) 2009 Mathews Lab, University of Rochester Medical Center.
 * Written by Jessica S. Reuter.
 */

#ifndef MAX_ACCURACY_H
#define MAX_ACCURACY_H

#include "../RNA_class/RNA.h"
#include "../src/ErrorChecker.h"
#include "../src/ParseCommandLine.h"

class MaxExpect {
 public:
	// Public constructor and methods.

	/*
	 * Name:        Constructor.
	 * Description: Initializes all private variables.
	 */
	MaxExpect();

	/*
	 * Name:        parse
	 * Description: Parses command line arguments to determine what options are required for a particular calculation.
	 * Arguments:
	 *     1.   The number of command line arguments.
	 *     2.   The command line arguments themselves.
	 * Returns:
	 *     True if parsing completed without errors, false if not.
	 */
	bool parse( int argc, char** argv );

	/*
	 * Name:        run
	 * Description: Run calculations.
	 */
	void run();

 private:
	// Private variables.

	// Description of the calculation type.
	string calcType;

	// Input and output file names.
	string input;            // The input plot data file.
	string ctFile;           // The output ct file.

	// The weight given to base pairs.
	double gamma;

	// Flag signifying if calculation handles RNA (true) or DNA (false).
	bool isRNA;

	// Boolean flag signifying if input is a sequence file (true) or not (false).
	bool isSequence;

	// The maximum number of structures to generate.
	int maxStructures;

	// The maximum percent energy difference.
	double percent;

	// The window size for calculation.
	int windowSize;
};

#endif /* MAX_ACCURACY_H */


text:
const ObservableProto = {
  onValue,
  onEnd,
  take: function(count) {
    return take(count, this);
  }
};

Observable.prototype = ObservableProto;


text:
const util = require('util');
const events = require('events');
const net = require('net');
const robot = require('robotjs');
const Composer = require('stream-pkg');

const listenPort = 6231;
var count = 0;
var screensize = robot.getScreenSize();
var composer = new Composer();

const client = net.connect({
    port: listenPort,
    host: '192.168.1.101'
}, function() {
    console.log("client connect.");
    client.setNoDelay();
    sendMousePosition();
});

function sendMousePosition() {
    count++;
    if (count == 50) {
        count = 0;
        client.write(composer.compose(JSON.stringify({
            type: 'click'
        })));
    } else {
        var mousePos = robot.getMousePos();
        var mousePosPercent = {
            x: ((mousePos.x / screensize.width) * 100).toFixed(2),
            y: ((mousePos.y / screensize.height) * 100).toFixed(2)
        }
        client.write(composer.compose(JSON.stringify({
            type: 'move',
            pos: mousePosPercent
        })));
    }

    setTimeout(function() {
        sendMousePosition();
    }, 100)
}


text:
package wallet

import (
	"path/filepath"
	"testing"
	"time"

	"github.com/NebulousLabs/Sia/build"
	"github.com/NebulousLabs/Sia/crypto"
	"github.com/NebulousLabs/Sia/modules"
	"github.com/NebulousLabs/Sia/modules/consensus"
	"github.com/NebulousLabs/Sia/modules/gateway"
	"github.com/NebulousLabs/Sia/modules/miner"
	"github.com/NebulousLabs/Sia/modules/transactionpool"
	"github.com/NebulousLabs/Sia/types"
	"github.com/NebulousLabs/fastrand"
)

// A Wallet tester contains a ConsensusTester and has a bunch of helpful
// functions for facilitating wallet integration testing.
type walletTester struct {
	cs      modules.ConsensusSet
	gateway modules.Gateway
	tpool   modules.TransactionPool
	miner   modules.TestMiner
	wallet  *Wallet

	walletMasterKey crypto.TwofishKey

	persistDir string
}

// createWalletTester takes a testing.T and creates a WalletTester.
func createWalletTester(name string, deps modules.Dependencies) (*walletTester, error) {
	// Create the modules
	testdir := build.TempDir(modules.WalletDir, name)
	g, err := gateway.New("localhost:0", false, filepath.Join(testdir, modules.GatewayDir))
	if err != nil {
		return nil, err
	}
	cs, err := consensus.New(g, false, filepath.Join(testdir, modules.ConsensusDir))
	if err != nil {
		return nil, err
	}
	tp, err := transactionpool.New(cs, g, filepath.Join(testdir, modules.TransactionPoolDir))
	if err != nil {
		return nil, err
	}
	w, err := NewCustomWallet(cs, tp, filepath.Join(testdir, modules.WalletDir), deps)
	if err != nil {
		return nil, err
	}
	var masterKey crypto.TwofishKey
	fastrand.Read(masterKey[:])
	_, err = w.Encrypt(masterKey)
	if err != nil {
		return nil, err
	}
	err = w.Unlock(masterKey)
	if err != nil {
		return nil, err
	}
	m, err := miner.New(cs, tp, w, filepath.Join(testdir, modules.WalletDir))
	if err != nil {
		return nil, err
	}

	// Assemble all components into a wallet tester.
	wt := &walletTester{
		cs:      cs,
		gateway: g,
		tpool:   tp,
		miner:   m,
		wallet:  w,

		walletMasterKey: masterKey,

		persistDir: testdir,
	}

	// Mine blocks until there is money in the wallet.
	for i := types.BlockHeight(0); i <= types.MaturityDelay; i++ {
		b, _ := wt.miner.FindBlock()
		err := wt.cs.AcceptBlock(b)
		if err != nil {
			return nil, err
		}
	}
	return wt, nil
}

// createBlankWalletTester creates a wallet tester that has not mined any
// blocks or encrypted the wallet.
func createBlankWalletTester(name string) (*walletTester, error) {
	// Create the modules
	testdir := build.TempDir(modules.WalletDir, name)
	g, err := gateway.New("localhost:0", false, filepath.Join(testdir, modules.GatewayDir))
	if err != nil {
		return nil, err
	}
	cs, err := consensus.New(g, false, filepath.Join(testdir, modules.ConsensusDir))
	if err != nil {
		return nil, err
	}
	tp, err := transactionpool.New(cs, g, filepath.Join(testdir, modules.TransactionPoolDir))
	if err != nil {
		return nil, err
	}
	w, err := New(cs, tp, filepath.Join(testdir, modules.WalletDir))
	if err != nil {
		return nil, err
	}
	m, err := miner.New(cs, tp, w, filepath.Join(testdir, modules.MinerDir))
	if err != nil {
		return nil, err
	}

	// Assemble all components into a wallet tester.
	wt := &walletTester{
		gateway: g,
		cs:      cs,
		tpool:   tp,
		miner:   m,
		wallet:  w,

		persistDir: testdir,
	}
	return wt, nil
}

// closeWt closes all of the modules in the wallet tester.
func (wt *walletTester) closeWt() error {
	errs := []error{
		wt.gateway.Close(),
		wt.cs.Close(),
		wt.tpool.Close(),
		wt.miner.Close(),
		wt.wallet.Close(),
	}
	return build.JoinErrors(errs, "; ")
}

// TestNilInputs tries starting the wallet using nil inputs.
func TestNilInputs(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	testdir := build.TempDir(modules.WalletDir, t.Name())
	g, err := gateway.New("localhost:0", false, filepath.Join(testdir, modules.GatewayDir))
	if err != nil {
		t.Fatal(err)
	}
	cs, err := consensus.New(g, false, filepath.Join(testdir, modules.ConsensusDir))
	if err != nil {
		t.Fatal(err)
	}
	tp, err := transactionpool.New(cs, g, filepath.Join(testdir, modules.TransactionPoolDir))
	if err != nil {
		t.Fatal(err)
	}

	wdir := filepath.Join(testdir, modules.WalletDir)
	_, err = New(cs, nil, wdir)
	if err != errNilTpool {
		t.Error(err)
	}
	_, err = New(nil, tp, wdir)
	if err != errNilConsensusSet {
		t.Error(err)
	}
	_, err = New(nil, nil, wdir)
	if err != errNilConsensusSet {
		t.Error(err)
	}
}

// TestAllAddresses checks that AllAddresses returns all of the wallet's
// addresses in sorted order.
func TestAllAddresses(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}
	wt, err := createBlankWalletTester(t.Name())
	if err != nil {
		t.Fatal(err)
	}
	defer wt.closeWt()

	wt.wallet.keys[types.UnlockHash{1}] = spendableKey{}
	wt.wallet.keys[types.UnlockHash{5}] = spendableKey{}
	wt.wallet.keys[types.UnlockHash{0}] = spendableKey{}
	wt.wallet.keys[types.UnlockHash{2}] = spendableKey{}
	wt.wallet.keys[types.UnlockHash{4}] = spendableKey{}
	wt.wallet.keys[types.UnlockHash{3}] = spendableKey{}
	addrs, err := wt.wallet.AllAddresses()
	if err != nil {
		t.Fatal(err)
	}
	for i := range addrs {
		if addrs[i][0] != byte(i) {
			t.Error("address sorting failed:", i, addrs[i][0])
		}
	}
}

// TestCloseWallet tries to close the wallet.
func TestCloseWallet(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}
	testdir := build.TempDir(modules.WalletDir, t.Name())
	g, err := gateway.New("localhost:0", false, filepath.Join(testdir, modules.GatewayDir))
	if err != nil {
		t.Fatal(err)
	}
	cs, err := consensus.New(g, false, filepath.Join(testdir, modules.ConsensusDir))
	if err != nil {
		t.Fatal(err)
	}
	tp, err := transactionpool.New(cs, g, filepath.Join(testdir, modules.TransactionPoolDir))
	if err != nil {
		t.Fatal(err)
	}
	wdir := filepath.Join(testdir, modules.WalletDir)
	w, err := New(cs, tp, wdir)
	if err != nil {
		t.Fatal(err)
	}
	if err := w.Close(); err != nil {
		t.Fatal(err)
	}
}

// TestRescanning verifies that calling Rescanning during a scan operation
// returns true, and false otherwise.
func TestRescanning(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	wt, err := createWalletTester(t.Name(), modules.ProdDependencies)
	if err != nil {
		t.Fatal(err)
	}
	defer wt.closeWt()

	// A fresh wallet should not be rescanning.
	rescanning, err := wt.wallet.Rescanning()
	if err != nil {
		t.Fatal(err)
	}
	if rescanning {
		t.Fatal("fresh wallet should not report that a scan is underway")
	}

	// lock the wallet
	wt.wallet.Lock()

	// spawn an unlock goroutine
	errChan := make(chan error)
	go func() {
		// acquire the write lock so that Unlock acquires the trymutex, but
		// cannot proceed further
		wt.wallet.mu.Lock()
		errChan <- wt.wallet.Unlock(wt.walletMasterKey)
	}()

	// wait for goroutine to start, after which Rescanning should return true
	time.Sleep(time.Millisecond * 10)
	rescanning, err = wt.wallet.Rescanning()
	if err != nil {
		t.Fatal(err)
	}
	if !rescanning {
		t.Fatal("wallet should report that a scan is underway")
	}

	// release the mutex and allow the call to complete
	wt.wallet.mu.Unlock()
	if err := <-errChan; err != nil {
		t.Fatal("unlock failed:", err)
	}

	// Rescanning should now return false again
	rescanning, err = wt.wallet.Rescanning()
	if err != nil {
		t.Fatal(err)
	}
	if rescanning {
		t.Fatal("wallet should not report that a scan is underway")
	}
}

// TestFutureAddressGeneration checks if the right amount of future addresses
// is generated after calling NextAddress() or locking + unlocking the wallet.
func TestLookaheadGeneration(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	wt, err := createWalletTester(t.Name(), modules.ProdDependencies)
	if err != nil {
		t.Fatal(err)
	}
	defer wt.closeWt()

	// Check if number of future keys is correct
	wt.wallet.mu.RLock()
	progress, err := dbGetPrimarySeedProgress(wt.wallet.dbTx)
	wt.wallet.mu.RUnlock()
	if err != nil {
		t.Fatal("Couldn't fetch primary seed from db")
	}

	actualKeys := uint64(len(wt.wallet.lookahead))
	expectedKeys := maxLookahead(progress)
	if actualKeys != expectedKeys {
		t.Errorf("expected len(lookahead) == %d but was %d", actualKeys, expectedKeys)
	}

	// Generate some more keys
	for i := 0; i < 100; i++ {
		wt.wallet.NextAddress()
	}

	// Lock and unlock
	wt.wallet.Lock()
	wt.wallet.Unlock(wt.walletMasterKey)

	wt.wallet.mu.RLock()
	progress, err = dbGetPrimarySeedProgress(wt.wallet.dbTx)
	wt.wallet.mu.RUnlock()
	if err != nil {
		t.Fatal("Couldn't fetch primary seed from db")
	}

	actualKeys = uint64(len(wt.wallet.lookahead))
	expectedKeys = maxLookahead(progress)
	if actualKeys != expectedKeys {
		t.Errorf("expected len(lookahead) == %d but was %d", actualKeys, expectedKeys)
	}

	wt.wallet.mu.RLock()
	defer wt.wallet.mu.RUnlock()
	for i := range wt.wallet.keys {
		_, exists := wt.wallet.lookahead[i]
		if exists {
			t.Fatal("wallet keys contained a key which is also present in lookahead")
		}
	}
}

// TestAdvanceLookaheadNoRescan tests if a transaction to multiple lookahead addresses
// is handled correctly without forcing a wallet rescan.
func TestAdvanceLookaheadNoRescan(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	wt, err := createWalletTester(t.Name(), modules.ProdDependencies)
	if err != nil {
		t.Fatal(err)
	}
	defer wt.closeWt()

	builder, err := wt.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
	payout := types.ZeroCurrency

	// Get the current progress
	wt.wallet.mu.RLock()
	progress, err := dbGetPrimarySeedProgress(wt.wallet.dbTx)
	wt.wallet.mu.RUnlock()
	if err != nil {
		t.Fatal("Couldn't fetch primary seed from db")
	}

	// choose 10 keys in the lookahead and remember them
	var receivingAddresses []types.UnlockHash
	for _, sk := range generateKeys(wt.wallet.primarySeed, progress, 10) {
		sco := types.SiacoinOutput{
			UnlockHash: sk.UnlockConditions.UnlockHash(),
			Value:      types.NewCurrency64(1e3),
		}

		builder.AddSiacoinOutput(sco)
		payout = payout.Add(sco.Value)
		receivingAddresses = append(receivingAddresses, sk.UnlockConditions.UnlockHash())
	}

	err = builder.FundSiacoins(payout)
	if err != nil {
		t.Fatal(err)
	}

	tSet, err := builder.Sign(true)
	if err != nil {
		t.Fatal(err)
	}

	err = wt.tpool.AcceptTransactionSet(tSet)
	if err != nil {
		t.Fatal(err)
	}

	_, err = wt.miner.AddBlock()
	if err != nil {
		t.Fatal(err)
	}

	// Check if the receiving addresses were moved from future keys to keys
	wt.wallet.mu.RLock()
	defer wt.wallet.mu.RUnlock()
	for _, uh := range receivingAddresses {
		_, exists := wt.wallet.lookahead[uh]
		if exists {
			t.Fatal("UnlockHash still exists in wallet lookahead")
		}

		_, exists = wt.wallet.keys[uh]
		if !exists {
			t.Fatal("UnlockHash not in map of spendable keys")
		}
	}
}

// TestAdvanceLookaheadNoRescan tests if a transaction to multiple lookahead addresses
// is handled correctly forcing a wallet rescan.
func TestAdvanceLookaheadForceRescan(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	wt, err := createWalletTester(t.Name(), modules.ProdDependencies)
	if err != nil {
		t.Fatal(err)
	}
	defer wt.closeWt()

	// Mine blocks without payouts so that the balance stabilizes
	for i := types.BlockHeight(0); i < types.MaturityDelay; i++ {
		wt.addBlockNoPayout()
	}

	// Get the current progress and balance
	wt.wallet.mu.RLock()
	progress, err := dbGetPrimarySeedProgress(wt.wallet.dbTx)
	wt.wallet.mu.RUnlock()
	if err != nil {
		t.Fatal("Couldn't fetch primary seed from db")
	}
	startBal, _, _, err := wt.wallet.ConfirmedBalance()
	if err != nil {
		t.Fatal(err)
	}

	// Send coins to an address with a high seed index, just outside the
	// lookahead range. It will not be initially detected, but later the
	// rescan should find it.
	highIndex := progress + uint64(len(wt.wallet.lookahead)) + 5
	farAddr := generateSpendableKey(wt.wallet.primarySeed, highIndex).UnlockConditions.UnlockHash()
	farPayout := types.SiacoinPrecision.Mul64(8888)

	builder, err := wt.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
	builder.AddSiacoinOutput(types.SiacoinOutput{
		UnlockHash: farAddr,
		Value:      farPayout,
	})
	err = builder.FundSiacoins(farPayout)
	if err != nil {
		t.Fatal(err)
	}

	txnSet, err := builder.Sign(true)
	if err != nil {
		t.Fatal(err)
	}

	err = wt.tpool.AcceptTransactionSet(txnSet)
	if err != nil {
		t.Fatal(err)
	}
	wt.addBlockNoPayout()
	newBal, _, _, err := wt.wallet.ConfirmedBalance()
	if err != nil {
		t.Fatal(err)
	}
	if !startBal.Sub(newBal).Equals(farPayout) {
		t.Fatal("wallet should not recognize coins sent to very high seed index")
	}

	builder, err = wt.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
	var payout types.Currency

	// choose 10 keys in the lookahead and remember them
	var receivingAddresses []types.UnlockHash
	for uh, index := range wt.wallet.lookahead {
		// Only choose keys that force a rescan
		if index < progress+lookaheadRescanThreshold {
			continue
		}
		sco := types.SiacoinOutput{
			UnlockHash: uh,
			Value:      types.SiacoinPrecision.Mul64(1000),
		}
		builder.AddSiacoinOutput(sco)
		payout = payout.Add(sco.Value)
		receivingAddresses = append(receivingAddresses, uh)

		if len(receivingAddresses) >= 10 {
			break
		}
	}

	err = builder.FundSiacoins(payout)
	if err != nil {
		t.Fatal(err)
	}

	txnSet, err = builder.Sign(true)
	if err != nil {
		t.Fatal(err)
	}

	err = wt.tpool.AcceptTransactionSet(txnSet)
	if err != nil {
		t.Fatal(err)
	}
	wt.addBlockNoPayout()

	// Allow the wallet rescan to finish
	time.Sleep(time.Second * 2)

	// Check that high seed index txn was discovered in the rescan
	rescanBal, _, _, err := wt.wallet.ConfirmedBalance()
	if err != nil {
		t.Fatal(err)
	}
	if !rescanBal.Equals(startBal) {
		t.Fatal("wallet did not discover txn after rescan")
	}

	// Check if the receiving addresses were moved from future keys to keys
	wt.wallet.mu.RLock()
	defer wt.wallet.mu.RUnlock()
	for _, uh := range receivingAddresses {
		_, exists := wt.wallet.lookahead[uh]
		if exists {
			t.Fatal("UnlockHash still exists in wallet lookahead")
		}

		_, exists = wt.wallet.keys[uh]
		if !exists {
			t.Fatal("UnlockHash not in map of spendable keys")
		}
	}
}

// TestDistantWallets tests if two wallets that use the same seed stay
// synchronized.
func TestDistantWallets(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	wt, err := createWalletTester(t.Name(), modules.ProdDependencies)
	if err != nil {
		t.Fatal(err)
	}
	defer wt.closeWt()

	// Create another wallet with the same seed.
	w2, err := New(wt.cs, wt.tpool, build.TempDir(modules.WalletDir, t.Name()+"2", modules.WalletDir))
	if err != nil {
		t.Fatal(err)
	}
	err = w2.InitFromSeed(crypto.TwofishKey{}, wt.wallet.primarySeed)
	if err != nil {
		t.Fatal(err)
	}
	err = w2.Unlock(crypto.TwofishKey(crypto.HashObject(wt.wallet.primarySeed)))
	if err != nil {
		t.Fatal(err)
	}

	// Use the first wallet.
	for i := uint64(0); i < lookaheadBuffer/2; i++ {
		_, err = wt.wallet.SendSiacoins(types.SiacoinPrecision, types.UnlockHash{})
		if err != nil {
			t.Fatal(err)
		}
		wt.addBlockNoPayout()
	}

	// The second wallet's balance should update accordingly.
	w1bal, _, _, err := wt.wallet.ConfirmedBalance()
	if err != nil {
		t.Fatal(err)
	}
	w2bal, _, _, err := w2.ConfirmedBalance()
	if err != nil {
		t.Fatal(err)
	}

	if !w1bal.Equals(w2bal) {
		t.Fatal("balances do not match:", w1bal, w2bal)
	}

	// Send coins to an address with a very high seed index, outside the
	// lookahead range. w2 should not detect it.
	tbuilder, err := wt.wallet.StartTransaction()
	if err != nil {
		t.Fatal(err)
	}
	farAddr := generateSpendableKey(wt.wallet.primarySeed, lookaheadBuffer*10).UnlockConditions.UnlockHash()
	value := types.SiacoinPrecision.Mul64(1e3)
	tbuilder.AddSiacoinOutput(types.SiacoinOutput{
		UnlockHash: farAddr,
		Value:      value,
	})
	err = tbuilder.FundSiacoins(value)
	if err != nil {
		t.Fatal(err)
	}
	txnSet, err := tbuilder.Sign(true)
	if err != nil {
		t.Fatal(err)
	}
	err = wt.tpool.AcceptTransactionSet(txnSet)
	if err != nil {
		t.Fatal(err)
	}
	wt.addBlockNoPayout()

	if newBal, _, _, err := w2.ConfirmedBalance(); !newBal.Equals(w2bal.Sub(value)) {
		if err != nil {
			t.Fatal(err)
		}
		t.Fatal("wallet should not recognize coins sent to very high seed index")
	}
}


text:
<?php if ( !defined('ABS_PATH') ) exit('ABS_PATH is not loaded. Direct access is not allowed.');

    /**
     * Model database for AlertsStats table
     *
     * @package Osclass
     * @subpackage Model
     * @since 3.1
     */
    class AlertsStats extends DAO
    {
        /**
         * It references to self object: AlertsStats.
         * It is used as a singleton
         *
         * @access private
         * @since 3.1
         * @var AlertsStats
         */
        private static $instance;

        /**
         * It creates a new AlertsStats object class ir if it has been created
         * before, it return the previous object
         *
         * @access public
         * @since 3.1
         * @return AlertsStats
         */
        public static function newInstance()
        {
            if( !self::$instance instanceof self ) {
                self::$instance = new self;
            }
            return self::$instance;
        }

        /**
         * Set data related to t_alerts_sent table
         */
        public function __construct()
        {
            parent::__construct();
            $this->setTableName('t_alerts_sent');
            $this->setPrimaryKey('d_date');
            $this->setFields( array('d_date', 'i_num_alerts_sent') );
        }

        /**
         * Increase the stat column given column name and item id
         *
         * @access public
         * @since 3.1
         * @param string $date
         * @return bool
         */
        function increase($date)
        {
            // check the date it's ok
            if( !preg_match('|^[0-9]{4}-[0-9]{2}-[0-9]{2}$|', $date) ) {
                return false;
            }

            // first we try to insert
            if( $this->insert(array('d_date' => $date, 'i_num_alerts_sent' => '1')) ) {
                return true;
            }

            // duplicate key?
            if( $this->getErrorLevel() != 1062 ) {
                return false;
            }

            $sql = sprintf("UPDATE %s SET i_num_alerts_sent = i_num_alerts_sent + 1 WHERE d_date = '%s'", $this->getTableName(), $date);
            $this->dao->query($sql);

            return true;
        }
    }

    /* file end: ./oc-includes/osclass/model/AlertsStats.php */
?>


text:
import { OHIF } from 'meteor/ohif:core';

Meteor.startup(function() {
    cornerstoneTools.loadHandlerManager.setStartLoadHandler(startLoadingHandler);
    cornerstoneTools.loadHandlerManager.setEndLoadHandler(doneLoadingHandler);
    cornerstoneTools.loadHandlerManager.setErrorLoadingHandler(errorLoadingHandler);
});

var loadHandlerTimeout;

startLoadingHandler = function(element) {
    clearTimeout(loadHandlerTimeout);
    loadHandlerTimeout = setTimeout(function() {
        var elem = $(element);
        elem.siblings('.imageViewerErrorLoadingIndicator').css('display', 'none');
        elem.find('canvas').not('.magnifyTool').addClass("faded");
        elem.siblings('.imageViewerLoadingIndicator').css('display', 'block');
    }, OHIF.viewer.loadIndicatorDelay);
};

doneLoadingHandler = function(element) {
    clearTimeout(loadHandlerTimeout);
    var elem = $(element);
    elem.siblings('.imageViewerErrorLoadingIndicator').css('display', 'none');
    elem.find('canvas').not('.magnifyTool').removeClass("faded");
    elem.siblings('.imageViewerLoadingIndicator').css('display', 'none');
};

errorLoadingHandler = function(element, imageId, error, source) {
    clearTimeout(loadHandlerTimeout);
    var elem = $(element);

    // Could probably chain all of these, but this is more readable
    elem.find('canvas').not('.magnifyTool').removeClass("faded");
    elem.siblings('.imageViewerLoadingIndicator').css('display', 'none');

    // Don't display errors from the stackPrefetch tool
    if (source === "stackPrefetch") {
        return;
    }

    var errorLoadingIndicator = elem.siblings('.imageViewerErrorLoadingIndicator');
    errorLoadingIndicator.css('display', 'block');

    var cleanedImageId = imageId;

    // This is just used to expand upon some error messages that are sent
    // when things fail. An example is a network error throwing the error
    // which is only described as "network".
    var errorDetails = {
        network: "A network error has occurred"
        // We need to expand this further when we see more obscure error messages
    };

    if (errorDetails.hasOwnProperty(error)) {
        error = errorDetails[error];
    }

    errorLoadingIndicator.find('.description').text("An error has occurred while loading image: " + cleanedImageId);
    if (error) {
        errorLoadingIndicator.find('.details').text("Details: " + error);
    }
};

Template.loadingIndicator.helpers({
    'percentComplete'() {
        var percentComplete = Session.get('CornerstoneLoadProgress' + this.viewportIndex);
        if (percentComplete && percentComplete !== 100) {
            return percentComplete + '%';
        }
    }
});


text:
layout: post
title: ! 'Code Kata: Kata Two'
date: 2013-08-27 22:04:43.000000000 +02:00
categories:
- .NET
tags:
- C#
- CodeKatas
status: publish
type: post
published: true
meta:
  _edit_last: '1'
author:
  login: admin
  email: pvlerick@gmail.com
  display_name: Philippe
  first_name: Philippe
  last_name: Vlérick
excerpt: !ruby/object:Hpricot::Doc
  options: {}
---

I haven't been coding much at work recently, so I decided that I need to sharpen the saw a bit and exercise.

I decided to start with some Code Kata. The first one is somewhat an academical problem: implement binary search in five different ways.

Here is my first solution, the iterative way:

        //Classic iterative method
        public int Chop1(int element, IEnumerable<int> collection)
        {
            //Empty collection -> not found
            if (collection.Count() == 0) return -1;

            var lower = 0;
            var upper = collection.Count() - 1;
            int index, candidate;

            while (lower != upper)
            {
                index = lower + ((upper - lower) / 2);
                candidate = collection.ElementAt(index);

                if (candidate == element)
                {
                    return index;
                }
                else if (candidate < element)
                {
                    lower = index + 1;
                }
                else //if (candidate > element)
                {
                    upper = index;
                }
            }

            return (collection.ElementAt(upper) == element) ? upper : -1;
        }

I was actually scared at the time it took me. This is the kind of problem you are expected to solve in 5 minutes flat at university, but the lack of programming puzzles lately soften my brain. On the bright side, I challenged myself to get it right without compiling before being absolutely sure that the code would pass the tests, which it did. This involved some scratching paper to test the different corner cases, but I felt good when the green light of passing tests appeared.

Here is my second solution, recursive and passing slices of the original array:

        //Recursively passing smaller slices of the initial array
        public int Chop2(int element, IEnumerable<int> collection)
        {
            //Empty collection -> not found
            if (collection.Count() == 0) return -1;

            var index = collection.Count() / 2;
            var candidate = collection.ElementAt(index);

            if (candidate == element)
            {
                return index;
            }
            else if (candidate < element)
            {
                var offset = index + 1;
                var position = Chop2(element, collection.Skip(index + 1));
                return position > -1 ? offset + position : -1;
            }
            else //if (candidate > element)
            {
                return Chop2(element, collection.Take(index));
            }
        }

After finishing this one, I started thinking about it and found it very funny that this came more naturally than a recursive function using boundaries inside the array. I tend to use LINQ a lot when I code in C#, and I guess this is where it shows. The good news is that this led me to the third possible solution, which would have been second if I was just out of university.

Third solution, recursive and passing arrays boundaries:

        //Classic recursive method, passing boundaries around
        public int Chop3(int element, IEnumerable<int> collection)
        {
            //Empty collection -> not found
            if (collection.Count() == 0) return -1;

            return SubChop3(element, collection, 0, collection.Count() - 1);
        }
        //...and its sub method required for passing boundaries around
        private int SubChop3(int element, IEnumerable<int> collection, int lower, int upper)
        {
            //End case: lower == upper
            if (lower == upper)
            {
                if (collection.ElementAt(lower) == element) return lower;
                else return -1;
            }

            var index = lower + ((upper - lower) / 2);
            var candidate = collection.ElementAt(index);

            if (candidate == element)
            {
                return index;
            }
            else if (candidate < element)
            {
                return SubChop3(element, collection, index + 1, upper);
            }
            else //if (candidate > element)
            {
                return SubChop3(element, collection, lower, index);
            }
        }

Nothing too fancy here.

I don't have a 4 and 5 yet, but I already have one idea that is very challenging: continuation passing style. I was also tempted to implement one version using TPL, but it wouldn't be very different from the recursive methods, so I am not sure… Maybe using a custom partitioner?


text:
module.exports = function(grunt) {

    var path = require('path');

    // load the package JSON file
    var pkg = grunt.file.readJSON('package.json');

    // get the project paths
    var sourceDir = 'src/',
        projectDir = sourceDir + pkg.name + '/';

    // get the release paths
    var releaseDir = 'release/',
        releaseFilesDir = releaseDir + 'files/';

    // load information about the assembly
    var assembly = grunt.file.readJSON(projectDir + 'Properties/AssemblyInfo.json');

    // get the version of the package
    var version = assembly.informationalVersion ? assembly.informationalVersion : assembly.version;

    grunt.initConfig({
        pkg: pkg,
        clean: {
            files: [
                releaseFilesDir + '**/*.*'
            ]
        },
        copy: {
            bacon: {
                files: [
                    {
                        expand: true,
                        cwd: projectDir + 'obj/Release/',
                        src: [
                            pkg.name + '.dll',
                            pkg.name + '.xml'
                        ],
                        dest: releaseFilesDir + 'bin/'
                    },
                    {
                        expand: true,
                        cwd: projectDir + 'Web/UI/',
                        src: ['**'],
                        dest: releaseFilesDir
                    }
                ]
            }
        },
        zip: {
            release: {
                cwd: releaseFilesDir,
                src: [
                    releaseFilesDir + '**/*.*'
                ],
                dest: releaseDir + 'zip/' + pkg.name + '.v' + version + '.zip'
            }
        },
        umbracoPackage: {
            dist: {
                src: releaseFilesDir,
                dest: releaseDir + 'umbraco/',
                options: {
                    name: pkg.name,
                    version: version,
                    url: pkg.url,
                    license: pkg.license.name,
                    licenseUrl: pkg.license.url,
                    author: pkg.author.name,
                    authorUrl: pkg.author.url,
                    readme: pkg.readme,
                    outputName: pkg.name + '.v' + version + '.zip'
                }
            }
        },
        nugetpack: {
            dist: {
                src: projectDir + pkg.name + '.csproj',
                dest: releaseDir + 'nuget/',
                options: {
                    properties: 'Platform=AnyCPU;Configuration=Release'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-umbraco-package');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-nuget');
    grunt.loadNpmTasks('grunt-zip');

    grunt.registerTask('dev', ['copy', 'zip', 'umbracoPackage', 'nugetpack']);

    grunt.registerTask('default', ['dev']);

};


text:
require 'helper'

module CouplerUnitTests
  class TestBase < Coupler::Test::UnitTest
    test "subclasses sinatra base" do
      assert_equal Sinatra::Base, Coupler::Base.superclass
    end
  end
end


text:
package log_test

import (
	"os"
	"time"

	"github.com/bitrise-io/bitrise/log"
)

func referenceTime() time.Time {
	return time.Date(2022, 1, 1, 1, 1, 1, 0, time.UTC)
}

func ExampleLogger() {
	var logger log.Logger

	logger = log.NewLogger(log.LoggerOpts{
		LoggerType:      log.ConsoleLogger,
		Producer:        log.BitriseCLI,
		DebugLogEnabled: true,
		Writer:          os.Stdout,
		TimeProvider:    referenceTime,
	})
	logger.Errorf("This is an %s", "error")

	logger = log.NewLogger(log.LoggerOpts{
		LoggerType:      log.JSONLogger,
		Producer:        log.BitriseCLI,
		DebugLogEnabled: true,
		Writer:          os.Stdout,
		TimeProvider:    referenceTime,
	})
	logger.Debug("This is a debug message")

	log.InitGlobalLogger(log.LoggerOpts{
		LoggerType:      log.JSONLogger,
		Producer:        log.BitriseCLI,
		DebugLogEnabled: true,
		Writer:          os.Stdout,
		TimeProvider:    referenceTime,
	})
	log.Info("This is an info message")
}


text:
namespace System.Net.Sockets.Tests
{
    internal static class TestPortBases
    {
        private const int Base = 8000;

        public const int AcceptAsync = Base;
        public const int AgnosticListener = Base + 10;
        public const int ConnectAsync = Base + 20;
        public const int ConnectEx = Base + 30;
        public const int Disconnect = Base + 40;
        public const int DisconnectAsync = Base + 50;
        public const int ReceiveMessageFrom = Base + 60;
        public const int DnsEndPoint = Base + 80;
        public const int ReceiveMessageFromAsync = Base + 90;
        public const int SendPacketsAsync = Base + 100;
        public const int Timeout = Base + 110;
        public const int DualMode = Base + 200;
        public const int UDPClient = Base + 500;
    }
}


text:
Templates & Placeholders
########################

In this tutorial we'll introduce Placeholders, and we're also going to show how
you can make your own HTML templates CMS-ready.

Templates
#########

You can use HTML templates to customise the look of your website, define
Placeholders to mark sections for managed content and use special tags to
generate menus and more.

You can define multiple templates, with different layouts or built-in
components, and choose them for each page as required. A page's template
can be switched for another at any time.

You'll find the site's templates in ``mysite/templates``. If you didn't change
the automatically-created home page's template, it's ``feature.html``.

Placeholders
############

Placeholders are an easy way to define sections in an HTML template that will
be filled with content from the database when the page is rendered. This
content is edited using django CMS's frontend editing mechanism, using Django
template tags.

You can see them in ``feature.html``: ``{% placeholder "feature" %}`` and ``{%
placeholder "content" %}``.

You'll also see ``{% load cms_tags %}`` in that file - ``cms_tags`` is the
required template tag library.

If you're not already familiar with Django template tags, you can find out more
in the `Django documentation
<https://docs.djangoproject.com/en/dev/topics/templates/>`_.

Try removing a placeholder from the template, or adding a new one in the
template's HTML structure.

Static Placeholders
*******************

The content of the placeholders we've encountered so far is different for
every page. Sometimes though you'll want to have a section on your website
which should be the same on every single page, such as a footer block.

You *could* hard-code your footer into the template, but it would be nicer to be
able to manage it through the CMS. This is what **static placeholders** are for.

Static placeholders are an easy way to display the same content on multiple
locations on your website. Static placeholders act almost like normal
placeholders, except for the fact that once a static placeholder is created and
you added content to it, it will be saved globally. Even when you remove the
static placeholders from a template, you can reuse them later.

So let's add a footer to all our pages. Since we want our footer on every
single page, we should add it to our base template
(``mysite/templates/base.html``). Place it at the bottom of the HTML body:

.. code-block:: html+django

    <footer>
      {% static_placeholder 'footer' %}
    </footer>

Save the template and return to your browser. Change to ``Draft`` and then
``Structure`` mode and add some content to it.

After you've saved it, you'll see that it appears on your site's other pages
too.

Rendering Menus
---------------

In order to render the CMS's menu in your template you can use the :doc:`show_menu </reference/navigation>` tag.

The example we use in ``mysite/templates/base.html``  is:

.. code-block:: html+django

    <ul class="nav navbar-nav">
        {% show_menu 0 1 100 100 "menu.html" %}
    </ul>

Any template that uses ``show_menu`` must load the CMS's ``menu_tags`` library
first:

.. code-block:: html+django

    {% load menu_tags %}

If you chose "bootstrap" while setting up with djangocms-installer, the menu
will already be there and ``templates/menu.html`` will already contain a
version that uses bootstrap compatible markup.

Next we'll look at django CMS plugins.


text:
"""Policy Engine For Glance"""

import json
import os.path

from oslo.config import cfg

from glance.common import exception
import glance.domain.proxy
import glance.openstack.common.log as logging
from glance.openstack.common import policy

LOG = logging.getLogger(__name__)

policy_opts = [
    cfg.StrOpt('policy_file', default='policy.json',
               help=_('The location of the policy file.')),
    cfg.StrOpt('policy_default_rule', default='default',
               help=_('The default policy to use.')),
]

CONF = cfg.CONF
CONF.register_opts(policy_opts)

DEFAULT_RULES = {
    'context_is_admin': policy.RoleCheck('role', 'admin'),
    'default': policy.TrueCheck(),
    'manage_image_cache': policy.RoleCheck('role', 'admin'),
}

class Enforcer(object):
    """Responsible for loading and enforcing rules"""

    def __init__(self):
        self.default_rule = CONF.policy_default_rule
        self.policy_path = self._find_policy_file()
        self.policy_file_mtime = None
        self.policy_file_contents = None
        self.load_rules()

    def set_rules(self, rules):
        """Create a new Rules object based on the provided dict of rules"""
        rules_obj = policy.Rules(rules, self.default_rule)
        policy.set_rules(rules_obj)

    def add_rules(self, rules):
        """Add new rules to the Rules object"""
        if policy._rules:
            rules_obj = policy.Rules(rules)
            policy._rules.update(rules_obj)
        else:
            self.set_rules(rules)

    def load_rules(self):
        """Set the rules found in the json file on disk"""
        if self.policy_path:
            rules = self._read_policy_file()
            rule_type = ""
        else:
            rules = DEFAULT_RULES
            rule_type = "default "

        text_rules = dict((k, str(v)) for k, v in rules.items())
        msg = (_('Loaded %(rule_type)spolicy rules: %(text_rules)s') %
               {'rule_type': rule_type, 'text_rules': text_rules})
        LOG.debug(msg)

        self.set_rules(rules)

    @staticmethod
    def _find_policy_file():
        """Locate the policy json data file"""
        policy_file = CONF.find_file(CONF.policy_file)
        if policy_file:
            return policy_file
        else:
            LOG.warn(_('Unable to find policy file'))
            return None

    def _read_policy_file(self):
        """Read contents of the policy file

        This re-caches policy data if the file has been changed.
        """
        mtime = os.path.getmtime(self.policy_path)
        if not self.policy_file_contents or mtime != self.policy_file_mtime:
            LOG.debug(_("Loading policy from %s") % self.policy_path)
            with open(self.policy_path) as fap:
                raw_contents = fap.read()
                rules_dict = json.loads(raw_contents)
                self.policy_file_contents = dict(
                    (k, policy.parse_rule(v))
                    for k, v in rules_dict.items())
            self.policy_file_mtime = mtime
        return self.policy_file_contents

    def _check(self, context, rule, target, *args, **kwargs):
        """Verifies that the action is valid on the target in this context.

           :param context: Glance request context
           :param rule: String representing the action to be checked
           :param object: Dictionary representing the object of the action.
           :raises: `glance.common.exception.Forbidden`
           :returns: A non-False value if access is allowed.
        """
        credentials = {
            'roles': context.roles,
            'user': context.user,
            'tenant': context.tenant,
        }

        return policy.check(rule, target, credentials, *args, **kwargs)

    def enforce(self, context, action, target):
        """Verifies that the action is valid on the target in this context.

           :param context: Glance request context
           :param action: String representing the action to be checked
           :param object: Dictionary representing the object of the action.
           :raises: `glance.common.exception.Forbidden`
           :returns: A non-False value if access is allowed.
        """
        return self._check(context, action, target,
                           exception.Forbidden, action=action)

    def check(self, context, action, target):
        """Verifies that the action is valid on the target in this context.

           :param context: Glance request context
           :param action: String representing the action to be checked
           :param object: Dictionary representing the object of the action.
           :returns: A non-False value if access is allowed.
        """
        return self._check(context, action, target)

    def check_is_admin(self, context):
        """Check if the given context is associated with an admin role,
           as defined via the 'context_is_admin' RBAC rule.

           :param context: Glance request context
           :returns: A non-False value if context role is admin.
        """
        target = context.to_dict()
        return self.check(context, 'context_is_admin', target)

class ImageRepoProxy(glance.domain.proxy.Repo):

    def __init__(self, image_repo, context, policy):
        self.context = context
        self.policy = policy
        self.image_repo = image_repo
        proxy_kwargs = {'context': self.context, 'policy': self.policy}
        super(ImageRepoProxy, self).__init__(image_repo,
                                             item_proxy_class=ImageProxy,
                                             item_proxy_kwargs=proxy_kwargs)

    def get(self, image_id):
        self.policy.enforce(self.context, 'get_image', {})
        return super(ImageRepoProxy, self).get(image_id)

    def list(self, *args, **kwargs):
        self.policy.enforce(self.context, 'get_images', {})
        return super(ImageRepoProxy, self).list(*args, **kwargs)

    def save(self, image):
        self.policy.enforce(self.context, 'modify_image', {})
        return super(ImageRepoProxy, self).save(image)

    def add(self, image):
        self.policy.enforce(self.context, 'add_image', {})
        return super(ImageRepoProxy, self).add(image)

class ImageProxy(glance.domain.proxy.Image):

    def __init__(self, image, context, policy):
        self.image = image
        self.context = context
        self.policy = policy
        super(ImageProxy, self).__init__(image)

    @property
    def visibility(self):
        return self.image.visibility

    @visibility.setter
    def visibility(self, value):
        if value == 'public':
            self.policy.enforce(self.context, 'publicize_image', {})
        self.image.visibility = value

    @property
    def locations(self):
        return ImageLocationsProxy(self.image.locations,
                                   self.context, self.policy)

    @locations.setter
    def locations(self, value):
        if not isinstance(value, (list, ImageLocationsProxy)):
            raise exception.Invalid(_('Invalid locations: %s') % value)
        self.policy.enforce(self.context, 'set_image_location', {})
        new_locations = list(value)
        if (set([loc['url'] for loc in self.image.locations]) -
                set([loc['url'] for loc in new_locations])):
            self.policy.enforce(self.context, 'delete_image_location', {})
        self.image.locations = new_locations

    def delete(self):
        self.policy.enforce(self.context, 'delete_image', {})
        return self.image.delete()

    def get_data(self, *args, **kwargs):
        self.policy.enforce(self.context, 'download_image', {})
        return self.image.get_data(*args, **kwargs)

    def get_member_repo(self, **kwargs):
        member_repo = self.image.get_member_repo(**kwargs)
        return ImageMemberRepoProxy(member_repo, self.context, self.policy)

class ImageFactoryProxy(glance.domain.proxy.ImageFactory):

    def __init__(self, image_factory, context, policy):
        self.image_factory = image_factory
        self.context = context
        self.policy = policy
        proxy_kwargs = {'context': self.context, 'policy': self.policy}
        super(ImageFactoryProxy, self).__init__(image_factory,
                                                proxy_class=ImageProxy,
                                                proxy_kwargs=proxy_kwargs)

    def new_image(self, **kwargs):
        if kwargs.get('visibility') == 'public':
            self.policy.enforce(self.context, 'publicize_image', {})
        return super(ImageFactoryProxy, self).new_image(**kwargs)

class ImageMemberFactoryProxy(glance.domain.proxy.ImageMembershipFactory):

    def __init__(self, member_factory, context, policy):
        super(ImageMemberFactoryProxy, self).__init__(
            member_factory,
            image_proxy_class=ImageProxy,
            image_proxy_kwargs={'context': context, 'policy': policy})

class ImageMemberRepoProxy(glance.domain.proxy.Repo):

    def __init__(self, member_repo, context, policy):
        self.member_repo = member_repo
        self.context = context
        self.policy = policy

    def add(self, member):
        self.policy.enforce(self.context, 'add_member', {})
        return self.member_repo.add(member)

    def get(self, member_id):
        self.policy.enforce(self.context, 'get_member', {})
        return self.member_repo.get(member_id)

    def save(self, member):
        self.policy.enforce(self.context, 'modify_member', {})
        return self.member_repo.save(member)

    def list(self, *args, **kwargs):
        self.policy.enforce(self.context, 'get_members', {})
        return self.member_repo.list(*args, **kwargs)

    def remove(self, member):
        self.policy.enforce(self.context, 'delete_member', {})
        return self.member_repo.remove(member)

class ImageLocationsProxy(object):

    __hash__ = None

    def __init__(self, locations, context, policy):
        self.locations = locations
        self.context = context
        self.policy = policy

    def __contains__(self, uri):
        return uri in self.locations

    def __len__(self):
        return len(self.locations)

    def __cast(self, other):
        if isinstance(other, ImageLocationsProxy):
            return other.locations
        else:
            return other

    def __cmp__(self, other):
        return cmp(self.locations, self.__cast(other))

    def __iter__(self):
        return iter(self.locations)

    def _get_checker(action, func_name):
        def _checker(self, *args, **kwargs):
            self.policy.enforce(self.context, action, {})
            assert hasattr(self.locations, func_name)
            method = getattr(self.locations, func_name)
            return method(*args, **kwargs)
        return _checker

    count = _get_checker('get_image_location', 'count')
    index = _get_checker('get_image_location', 'index')
    __getitem__ = _get_checker('get_image_location', '__getitem__')
    __contains__ = _get_checker('get_image_location', '__contains__')
    __len__ = _get_checker('get_image_location', '__len__')
    __cast = _get_checker('get_image_location', '__cast')
    __cmp__ = _get_checker('get_image_location', '__cmp__')
    __iter__ = _get_checker('get_image_location', '__iter__')

    append = _get_checker('set_image_location', 'append')
    extend = _get_checker('set_image_location', 'extend')
    insert = _get_checker('set_image_location', 'insert')
    reverse = _get_checker('set_image_location', 'reverse')
    __iadd__ = _get_checker('set_image_location', '__iadd__')
    __setitem__ = _get_checker('set_image_location', '__setitem__')

    pop = _get_checker('delete_image_location', 'pop')
    remove = _get_checker('delete_image_location', 'remove')
    __delitem__ = _get_checker('delete_image_location', '__delitem__')
    __delslice__ = _get_checker('delete_image_location', '__delslice__')

    del _get_checker


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Verh. Deutsch. Bot. Gessellsch. 177 (1859)

#### Original name
Puccinia veratri Niessl

### Remarks
null


text:
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
'''
from ambari_agent import main
main.MEMORY_LEAK_DEBUG_FILEPATH = "/tmp/memory_leak_debug.out"
import os
import logging
from unittest import TestCase
from mock.mock import Mock, MagicMock, patch

from resource_management.libraries.functions import mounted_dirs_helper
from resource_management.core.logger import Logger
from resource_management.core.exceptions import Fail
from resource_management import Directory
from resource_management.libraries.script.script import Script

class StubParams(object):
  """
  Dummy class to fake params where params.x performs a get on params.dict["x"]
  """
  def __init__(self):
    self.dict = {}

  def __getattr__(self, name):
    return self.dict[name]

  def __repr__(self):
    name = self.__class__.__name__
    mocks = set(dir(self))
    mocks = [x for x in mocks if not str(x).startswith("__")]   # Exclude private methods
    return "<StubParams: {0}; mocks: {1}>".format(name, str(mocks))

def fake_create_dir(directory):
  """
  Fake function used as function pointer.
  """
  print "Fake function to create directory {0}".format(directory)

@patch.object(Script, "get_config", new=MagicMock(return_value={'configurations':{'cluster-env': {'ignore_bad_mounts': False, 'manage_dirs_on_root': True, 'one_dir_per_partition': False}}}))
class TestDatanodeHelper(TestCase):
  """
  Test the functionality of the dfs_datanode_helper.py
  """
  logger = logging.getLogger('TestDatanodeHelper')

  grid0 = "/grid/0/data"
  grid1 = "/grid/1/data"
  grid2 = "/grid/2/data"

  params = StubParams()
  params.data_dir_mount_file = "/var/lib/ambari-agent/data/datanode/dfs_data_dir_mount.hist"
  params.dfs_data_dir = "{0},{1},{2}".format(grid0, grid1, grid2)
  params.hdfs_user = "hdfs_test"
  params.user_group = "hadoop_test"

  @patch("resource_management.libraries.functions.mounted_dirs_helper.Directory")
  @patch.object(Logger, "warning")
  @patch.object(Logger, "info")
  @patch.object(Logger, "error")
  def test_normalized(self, log_error, log_info, warning_info, dir_mock):
    """
    Test that the data dirs are normalized by removing leading and trailing whitespace, and case sensitive.
    """
    params = StubParams()
    params.data_dir_mount_file = "/var/lib/ambari-agent/data/datanode/dfs_data_dir_mount.hist"
    params.dfs_data_dir = "/grid/0/data  ,  /grid/1/data  ,/GRID/2/Data/"

    # Function under test
    mounted_dirs_helper.handle_mounted_dirs(fake_create_dir, params.dfs_data_dir, params.data_dir_mount_file, update_cache=False)

    for (name, args, kwargs) in log_info.mock_calls:
      print args[0]
    for (name, args, kwargs) in log_error.mock_calls:
      print args[0]

    log_info.assert_any_call("Forcefully ensuring existence and permissions of the directory: /grid/0/data")
    log_info.assert_any_call("Forcefully ensuring existence and permissions of the directory: /grid/1/data")
    log_info.assert_any_call("Forcefully ensuring existence and permissions of the directory: /GRID/2/Data/")

    self.assertEquals(0, log_error.call_count)

  @patch("resource_management.libraries.functions.mounted_dirs_helper.Directory")
  @patch.object(Logger, "info")
  @patch.object(Logger, "warning")
  @patch.object(Logger, "error")
  @patch.object(mounted_dirs_helper, "get_dir_to_mount_from_file")
  @patch.object(mounted_dirs_helper, "get_mount_point_for_dir")
  @patch.object(os.path, "isdir")
  @patch.object(os.path, "exists")
  def test_grid_becomes_unmounted(self, mock_os_exists, mock_os_isdir, mock_get_mount_point,
                                  mock_get_data_dir_to_mount_from_file, log_error, log_warning, log_info, dir_mock):
    """
    Test when grid2 becomes unmounted
    """
    mock_os_exists.return_value = True    # Indicate that history file exists

    # Initially, all grids were mounted
    mock_get_data_dir_to_mount_from_file.return_value = {self.grid0: "/dev0", self.grid1: "/dev1", self.grid2: "/dev2"}

    # Grid2 then becomes unmounted
    mock_get_mount_point.side_effect = ["/dev0", "/dev1", "/"] * 2
    mock_os_isdir.side_effect = [False, False, False] + [True, True, True]
    # Function under test
    mounted_dirs_helper.handle_mounted_dirs(fake_create_dir, self.params.dfs_data_dir, self.params.data_dir_mount_file, update_cache=False)
    for (name, args, kwargs) in log_info.mock_calls:
      print args[0]

    error_logs = []
    for (name, args, kwargs) in log_error.mock_calls:
      error_logs.append(args[0])    # this is a one-tuple
    error_msg = "".join(error_logs)

    self.assertEquals(1, log_error.call_count)
    self.assertTrue("Directory /grid/2/data became unmounted from /dev2 . Current mount point: / ."
                    " Please ensure that mounts are healthy. If the mount change was intentional, you can update the contents of "
                    "/var/lib/ambari-agent/data/datanode/dfs_data_dir_mount.hist." in error_msg)

  @patch("resource_management.libraries.functions.mounted_dirs_helper.Directory")
  @patch.object(Logger, "info")
  @patch.object(Logger, "warning")
  @patch.object(Logger, "error")
  @patch.object(mounted_dirs_helper, "get_dir_to_mount_from_file")
  @patch.object(mounted_dirs_helper, "get_mount_point_for_dir")
  @patch.object(os.path, "isdir")
  @patch.object(os.path, "exists")
  def test_grid_becomes_remounted(self, mock_os_exists, mock_os_isdir, mock_get_mount_point,
                                  mock_get_data_dir_to_mount_from_file, log_error, log_warning, log_info, dir_mock):
    """
    Test when grid2 becomes remounted
    """
    mock_os_exists.return_value = True    # Indicate that history file exists

    # Initially, all grids were mounted
    mock_get_data_dir_to_mount_from_file.return_value = {self.grid0: "/dev0", self.grid1: "/dev1", self.grid2: "/"}

    # Grid2 then becomes remounted
    mock_get_mount_point.side_effect = ["/dev0", "/dev1", "/dev2"] * 2
    mock_os_isdir.side_effect = [False, False, False] + [True, True, True]

    # Function under test
    mounted_dirs_helper.handle_mounted_dirs(fake_create_dir, self.params.data_dir_mount_file, self.params.data_dir_mount_file, update_cache=False)

    for (name, args, kwargs) in log_info.mock_calls:
      print args[0]

    for (name, args, kwargs) in log_error.mock_calls:
      print args[0]

    self.assertEquals(0, log_error.call_count)

  def test_get_mounts_with_multiple_data_dirs(self):
    self.assertEquals([], mounted_dirs_helper.get_mounts_with_multiple_data_dirs(["/", "/hodoop", "/tmp"], "/hadoop/data,/tmp"))
    self.assertEquals([("/", ["/hadoop/data", "/tmp"])], mounted_dirs_helper.get_mounts_with_multiple_data_dirs(["/"], "/hadoop/data,/tmp"))

  def test_may_manage_folder(self):
    # root, no history file, manage_dirs_on_root = True
    # folder should be managed
    dirs_unmounted=set()
    self.assertEquals(True, mounted_dirs_helper._may_manage_folder(dir_='/grid/0/data', last_mount_point_for_dir=None, is_non_root_dir=False, dirs_unmounted=dirs_unmounted, error_messages = [], manage_dirs_on_root = True, curr_mount_point = '/'))
    self.assertEquals(dirs_unmounted, set())

    # root, no history file, manage_dirs_on_root = False
    # folder should not be managed
    dirs_unmounted=set()
    self.assertEquals(False, mounted_dirs_helper._may_manage_folder(dir_='/grid/0/data', last_mount_point_for_dir=None, is_non_root_dir=False, dirs_unmounted=dirs_unmounted, error_messages = [], manage_dirs_on_root = False, curr_mount_point = '/'))
    self.assertEquals(dirs_unmounted, set(['/grid/0/data']))

    # non root, no history file, manage_dirs_on_root = False
    # folder should be managed
    dirs_unmounted=set()
    self.assertEquals(True, mounted_dirs_helper._may_manage_folder(dir_='/grid/0/data', last_mount_point_for_dir=None, is_non_root_dir=True, dirs_unmounted=dirs_unmounted, error_messages = [], manage_dirs_on_root = False, curr_mount_point = '/'))
    self.assertEquals(dirs_unmounted, set())

    # unmounted to root, manage_dirs_on_root = True
    # folder should not be managed
    dirs_unmounted=set()
    self.assertEquals(False, mounted_dirs_helper._may_manage_folder('/grid/0/data', '/grid/0', True, dirs_unmounted, [], False, '/'))
    self.assertEquals(dirs_unmounted, set(['/grid/0/data']))

    # unmounted to root, manage_dirs_on_root = False
    # folder should not be managed
    dirs_unmounted=set()
    self.assertEquals(False, mounted_dirs_helper._may_manage_folder(dir_='/grid/0/data', last_mount_point_for_dir='/grid/0/data', is_non_root_dir=False, dirs_unmounted=dirs_unmounted, error_messages = [], manage_dirs_on_root = False, curr_mount_point = '/'))
    self.assertEquals(dirs_unmounted, set(['/grid/0/data']))

    # same mount = root, manage_dirs_on_root = False
    # folder should not be managed
    dirs_unmounted=set()
    self.assertEquals(False, mounted_dirs_helper._may_manage_folder(dir_='/grid/0/data', last_mount_point_for_dir='/', is_non_root_dir=False, dirs_unmounted=dirs_unmounted, error_messages = [], manage_dirs_on_root = False, curr_mount_point = '/'))
    self.assertEquals(dirs_unmounted, set())

    # same mount = root, manage_dirs_on_root = True
    # folder should be managed
    dirs_unmounted=set()
    self.assertEquals(True, mounted_dirs_helper._may_manage_folder(dir_='/grid/0/data', last_mount_point_for_dir='/', is_non_root_dir=False, dirs_unmounted=dirs_unmounted, error_messages = [], manage_dirs_on_root = True, curr_mount_point = '/'))
    self.assertEquals(dirs_unmounted, set())

    # mount changed to non root, manage_dirs_on_root = False
    # folder should not be managed
    dirs_unmounted=set()
    self.assertEquals(False, mounted_dirs_helper._may_manage_folder('/grid/0/data', '/', True, dirs_unmounted, [], False, '/grid/0'))
    self.assertEquals(dirs_unmounted, set(['/grid/0/data']))


text:
``` diff
 namespace System.ComponentModel.DataAnnotations {
     public class DisplayFormatAttribute : Attribute {
+        public Type NullDisplayTextResourceType { get; set; }
+        public string GetNullDisplayText();
     }
     public class RangeAttribute : ValidationAttribute {
+        public bool ConvertValueInInvariantCulture { get; set; }
+        public bool ParseLimitsInInvariantCulture { get; set; }
     }
 }
```


text:
#import <IDEKit/IDEActivityReporter.h>

@class IDEActivityReport;

@interface IDESnapshotActivityReporter : IDEActivityReporter
{
    id _snapshotStartObserver;
    id _snapshotEndObserver;
    id _snapshotRestoreStartObserver;
    id _snapshotRestoreEndObserver;
    IDEActivityReport *_activeCreationReport;
    IDEActivityReport *_activeRestoreReport;
}

+ (void)initialize;
- (void).cxx_destruct;
- (void)_updateWithValue:(BOOL)arg1 forCreation:(BOOL)arg2;
- (id)initWithWorkspace:(id)arg1;
- (void)primitiveInvalidate;

@end