Safe HaskellNone

AronModule

Synopsis

Documentation

print_ascii_c :: IO () Source #

How to build AronModule.hs | ghc --make AronModule.hs

Strict ByteString Char8 Strict ByteString UTF8 Lazy ByteString Char8 <http://hackage.haskell.org/package/utf8-string-1.0.1.1/docs/Data-ByteString-Lazy-UTF8.html Lazy ByteString UTF8

  • KEY: haskell ffi, c function SEE: UsersaaamyfilebitbuckethaskellffiAronCLibFFI.c

print_ascii_f :: IO () Source #

  • KEY: haskell ffi, c function SEE: UsersaaamyfilebitbuckethaskellffiAronCLibFFI.c

class Cnum a where Source #

Overloading the sin, cos to avoid Haskell crazy strict type | TODO: add test cases

Methods

_sqrt :: a -> Float Source #

_sin :: a -> Float Source #

_cos :: a -> Float Source #

Instances

Instances details
Cnum Double Source # 
Instance details

Defined in AronModule

Methods

_sqrt :: Double -> Float Source #

_sin :: Double -> Float Source #

_cos :: Double -> Float Source #

Cnum Float Source # 
Instance details

Defined in AronModule

Methods

_sqrt :: Float -> Float Source #

_sin :: Float -> Float Source #

_cos :: Float -> Float Source #

Cnum Int Source # 
Instance details

Defined in AronModule

Methods

_sqrt :: Int -> Float Source #

_sin :: Int -> Float Source #

_cos :: Int -> Float Source #

Cnum Integer Source # 
Instance details

Defined in AronModule

Methods

_sqrt :: Integer -> Float Source #

_sin :: Integer -> Float Source #

_cos :: Integer -> Float Source #

class Dnum a b where Source #

No much to say

  • Division is painful in Haskell
  • Try to overload _div for many types
  • TODO: add more combination?
  • TODO: add test cases

Associated Types

type DivType a b Source #

Methods

_div :: a -> b -> DivType a b Source #

Instances

Instances details
Dnum Double Int Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Double Int Source #

Methods

_div :: Double -> Int -> DivType Double Int Source #

Dnum Double Integer Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Double Integer Source #

Methods

_div :: Double -> Integer -> DivType Double Integer Source #

Dnum Float Int Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Float Int Source #

Methods

_div :: Float -> Int -> DivType Float Int Source #

Dnum Float Integer Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Float Integer Source #

Methods

_div :: Float -> Integer -> DivType Float Integer Source #

Dnum Int Float Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Int Float Source #

Methods

_div :: Int -> Float -> DivType Int Float Source #

Dnum Integer Double Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Integer Double Source #

Methods

_div :: Integer -> Double -> DivType Integer Double Source #

Dnum Integer Float Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Integer Float Source #

Methods

_div :: Integer -> Float -> DivType Integer Float Source #

Dnum Integer Integer Source # 
Instance details

Defined in AronModule

Associated Types

type DivType Integer Integer Source #

Methods

_div :: Integer -> Integer -> DivType Integer Integer Source #

class Add a b where Source #

Associated Types

type SumTy a b Source #

Methods

addd :: a -> b -> SumTy a b Source #

Instances

Instances details
Add Double Int Source # 
Instance details

Defined in AronModule

Associated Types

type SumTy Double Int Source #

Methods

addd :: Double -> Int -> SumTy Double Int Source #

Add Double Integer Source # 
Instance details

Defined in AronModule

Associated Types

type SumTy Double Integer Source #

Methods

addd :: Double -> Integer -> SumTy Double Integer Source #

Add Int Double Source # 
Instance details

Defined in AronModule

Associated Types

type SumTy Int Double Source #

Methods

addd :: Int -> Double -> SumTy Int Double Source #

Add Integer Double Source # 
Instance details

Defined in AronModule

Associated Types

type SumTy Integer Double Source #

Methods

addd :: Integer -> Double -> SumTy Integer Double Source #

Num a => Add a a Source # 
Instance details

Defined in AronModule

Associated Types

type SumTy a a Source #

Methods

addd :: a -> a -> SumTy a a Source #

data CodeBlock Source #

define record for all the code blocks can not define [TS.Text] => sqlite3 does not support [TS.Text]

Constructors

CodeBlock 

Fields

Instances

Instances details
Eq CodeBlock Source # 
Instance details

Defined in AronModule

Methods

(==) :: CodeBlock -> CodeBlock -> Bool

(/=) :: CodeBlock -> CodeBlock -> Bool

Read CodeBlock Source # 
Instance details

Defined in AronModule

Methods

readsPrec :: Int -> ReadS CodeBlock

readList :: ReadS [CodeBlock]

readPrec :: ReadPrec CodeBlock

readListPrec :: ReadPrec [CodeBlock]

Show CodeBlock Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> CodeBlock -> ShowS

show :: CodeBlock -> String

showList :: [CodeBlock] -> ShowS

FromRow CodeBlock Source # 
Instance details

Defined in AronModule

Methods

fromRow :: RowParser CodeBlock

ToRow CodeBlock Source # 
Instance details

Defined in AronModule

Methods

toRow :: CodeBlock -> [SQLData]

data SqliteMaster Source #

Constructors

SqliteMaster 

Fields

Instances

Instances details
Eq SqliteMaster Source # 
Instance details

Defined in AronModule

Methods

(==) :: SqliteMaster -> SqliteMaster -> Bool

(/=) :: SqliteMaster -> SqliteMaster -> Bool

Read SqliteMaster Source # 
Instance details

Defined in AronModule

Methods

readsPrec :: Int -> ReadS SqliteMaster

readList :: ReadS [SqliteMaster]

readPrec :: ReadPrec SqliteMaster

readListPrec :: ReadPrec [SqliteMaster]

Show SqliteMaster Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> SqliteMaster -> ShowS

show :: SqliteMaster -> String

showList :: [SqliteMaster] -> ShowS

FromRow SqliteMaster Source # 
Instance details

Defined in AronModule

Methods

fromRow :: RowParser SqliteMaster

ToRow SqliteMaster Source # 
Instance details

Defined in AronModule

Methods

toRow :: SqliteMaster -> [SQLData]

data UpdateCodeBlock Source #

Constructors

UpdateCodeBlock 

Fields

Instances

Instances details
Show UpdateCodeBlock Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> UpdateCodeBlock -> ShowS

show :: UpdateCodeBlock -> String

showList :: [UpdateCodeBlock] -> ShowS

Generic UpdateCodeBlock Source # 
Instance details

Defined in AronModule

Associated Types

type Rep UpdateCodeBlock :: Type -> Type

FromJSON UpdateCodeBlock Source # 
Instance details

Defined in AronModule

Methods

parseJSON :: Value -> Parser UpdateCodeBlock

parseJSONList :: Value -> Parser [UpdateCodeBlock]

ToJSON UpdateCodeBlock Source # 
Instance details

Defined in AronModule

Methods

toJSON :: UpdateCodeBlock -> Value

toEncoding :: UpdateCodeBlock -> Encoding

toJSONList :: [UpdateCodeBlock] -> Value

toEncodingList :: [UpdateCodeBlock] -> Encoding

type Rep UpdateCodeBlock Source # 
Instance details

Defined in AronModule

type Rep UpdateCodeBlock = D1 ('MetaData "UpdateCodeBlock" "AronModule" "main" 'False) (C1 ('MetaCons "UpdateCodeBlock" 'PrefixI 'True) ((S1 ('MetaSel ('Just "pid") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer) :*: S1 ('MetaSel ('Just "newcode") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String)) :*: (S1 ('MetaSel ('Just "begt") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer) :*: S1 ('MetaSel ('Just "endt") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer))))

data UpdateCodeBlockX Source #

Constructors

UpdateCodeBlockX 

Fields

Instances

Instances details
Show UpdateCodeBlockX Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> UpdateCodeBlockX -> ShowS

show :: UpdateCodeBlockX -> String

showList :: [UpdateCodeBlockX] -> ShowS

Generic UpdateCodeBlockX Source # 
Instance details

Defined in AronModule

Associated Types

type Rep UpdateCodeBlockX :: Type -> Type

FromJSON UpdateCodeBlockX Source # 
Instance details

Defined in AronModule

Methods

parseJSON :: Value -> Parser UpdateCodeBlockX

parseJSONList :: Value -> Parser [UpdateCodeBlockX]

ToJSON UpdateCodeBlockX Source # 
Instance details

Defined in AronModule

type Rep UpdateCodeBlockX Source # 
Instance details

Defined in AronModule

type Rep UpdateCodeBlockX = D1 ('MetaData "UpdateCodeBlockX" "AronModule" "main" 'False) (C1 ('MetaCons "UpdateCodeBlockX" 'PrefixI 'True) ((S1 ('MetaSel ('Just "pidx") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer) :*: S1 ('MetaSel ('Just "pidlistx") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 [Integer])) :*: (S1 ('MetaSel ('Just "newcodex") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String) :*: (S1 ('MetaSel ('Just "begtx") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer) :*: S1 ('MetaSel ('Just "endtx") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer)))))

data CodeBlockReply Source #

Constructors

CodeBlockReply 

Fields

Instances

Instances details
Show CodeBlockReply Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> CodeBlockReply -> ShowS

show :: CodeBlockReply -> String

showList :: [CodeBlockReply] -> ShowS

Generic CodeBlockReply Source # 
Instance details

Defined in AronModule

Associated Types

type Rep CodeBlockReply :: Type -> Type

FromJSON CodeBlockReply Source # 
Instance details

Defined in AronModule

Methods

parseJSON :: Value -> Parser CodeBlockReply

parseJSONList :: Value -> Parser [CodeBlockReply]

ToJSON CodeBlockReply Source # 
Instance details

Defined in AronModule

Methods

toJSON :: CodeBlockReply -> Value

toEncoding :: CodeBlockReply -> Encoding

toJSONList :: [CodeBlockReply] -> Value

toEncodingList :: [CodeBlockReply] -> Encoding

type Rep CodeBlockReply Source # 
Instance details

Defined in AronModule

type Rep CodeBlockReply = D1 ('MetaData "CodeBlockReply" "AronModule" "main" 'False) (C1 ('MetaCons "CodeBlockReply" 'PrefixI 'True) ((S1 ('MetaSel ('Just "ok") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String) :*: S1 ('MetaSel ('Just "retcmd") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String)) :*: (S1 ('MetaSel ('Just "retdata") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String) :*: (S1 ('MetaSel ('Just "retbegt") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer) :*: S1 ('MetaSel ('Just "retendt") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer)))))

data ReplyCode Source #

Constructors

ReplyCode 

Fields

Instances

Instances details
Show ReplyCode Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> ReplyCode -> ShowS

show :: ReplyCode -> String

showList :: [ReplyCode] -> ShowS

Generic ReplyCode Source # 
Instance details

Defined in AronModule

Associated Types

type Rep ReplyCode :: Type -> Type

Methods

from :: ReplyCode -> Rep ReplyCode x

to :: Rep ReplyCode x -> ReplyCode

FromJSON ReplyCode Source # 
Instance details

Defined in AronModule

Methods

parseJSON :: Value -> Parser ReplyCode

parseJSONList :: Value -> Parser [ReplyCode]

ToJSON ReplyCode Source # 
Instance details

Defined in AronModule

Methods

toJSON :: ReplyCode -> Value

toEncoding :: ReplyCode -> Encoding

toJSONList :: [ReplyCode] -> Value

toEncodingList :: [ReplyCode] -> Encoding

type Rep ReplyCode Source # 
Instance details

Defined in AronModule

type Rep ReplyCode = D1 ('MetaData "ReplyCode" "AronModule" "main" 'False) (C1 ('MetaCons "ReplyCode" 'PrefixI 'True) (S1 ('MetaSel ('Just "rcmd") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Text) :*: (S1 ('MetaSel ('Just "rerror") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Text) :*: S1 ('MetaSel ('Just "stdoutx") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Text))))

data CommandService Source #

Constructors

CommandService 

Fields

Instances

Instances details
Show CommandService Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> CommandService -> ShowS

show :: CommandService -> String

showList :: [CommandService] -> ShowS

Generic CommandService Source # 
Instance details

Defined in AronModule

Associated Types

type Rep CommandService :: Type -> Type

FromJSON CommandService Source # 
Instance details

Defined in AronModule

Methods

parseJSON :: Value -> Parser CommandService

parseJSONList :: Value -> Parser [CommandService]

ToJSON CommandService Source # 
Instance details

Defined in AronModule

Methods

toJSON :: CommandService -> Value

toEncoding :: CommandService -> Encoding

toJSONList :: [CommandService] -> Value

toEncodingList :: [CommandService] -> Encoding

type Rep CommandService Source # 
Instance details

Defined in AronModule

type Rep CommandService = D1 ('MetaData "CommandService" "AronModule" "main" 'False) (C1 ('MetaCons "CommandService" 'PrefixI 'True) (S1 ('MetaSel ('Just "cmdServ") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String) :*: (S1 ('MetaSel ('Just "paramArg") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String) :*: S1 ('MetaSel ('Just "inputData") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String))))

type CSSPro = (String, String) Source #

epsilon__ :: Double Source #

div' :: Int -> Int -> Double Source #

division is painful like hell in Haskell

divInteger :: Integer -> Integer -> Double Source #

divII :: (Num a, Fractional a) => Integer -> Integer -> a Source #

Num => a ring

  • Addition
  • Addition inverse
  • Multiplcation
  • Multiplcation identity
  • Associativity
  • Distribution over multiplication

class Num a where (+):: a -> a -> a (-)::a -> a -> a (*)::a -> a -> a abs:: a -> a negate::a -> a signum::a -> a fromIntegral Integer -> a

  • Fractional => field class Num a => Fractional a where (/)::a -> a -> a recip :: a -> a fromRational :: Rational -> a

rf :: (Real a, Fractional b) => a -> b Source #

KEY: real to Fractional

fi :: (Integral a, Num b) => a -> b Source #

KEY: Integral to Num

mat :: [[Integer]] Source #

simple matrix can be used in GHCi

matr :: [[Ratio Integer]] Source #

mat' :: [[[Char]]] Source #

eps :: (Num a, Ord a) => a -> a -> a -> Bool Source #

data C Source #

Implement complex number operations

Constructors

C 

Fields

  • x :: Float
     
  • y :: Float
     

Instances

Instances details
Eq C Source # 
Instance details

Defined in AronModule

Methods

(==) :: C -> C -> Bool

(/=) :: C -> C -> Bool

Num C Source # 
Instance details

Defined in AronModule

Methods

(+) :: C -> C -> C

(-) :: C -> C -> C

(*) :: C -> C -> C

negate :: C -> C

abs :: C -> C

signum :: C -> C

fromInteger :: Integer -> C

Show C Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> C -> ShowS

show :: C -> String

showList :: [C] -> ShowS

data RedisGroup Source #

Constructors

Haskell 
Java 
Snippet 
Cpp 

con :: C -> C Source #

KEY: complex conjugate

mag :: C -> Float Source #

KEY: complex magnitude

norm :: C -> Float Source #

re :: C -> Float Source #

im :: C -> Float Source #

co :: C -> (Float, Float) Source #

toPolar :: C -> (Float, Float) Source #

Convert Cartesian Coordinates to Polar Coordinates

toCard :: (Float, Float) -> C Source #

Convert Polar Coordinates to Cartesian Coordinates

loge :: Double -> Double Source #

approximate nature log function with Integral function

\[ \log_e x = \int_{1}^{x} \frac{d t}{t} \]

  • Partition the interval \( x \gt 1, [1, x] \text{ or } x \lt 1, [x, 1] \) to \( n = 100 \)
  • Compute each step value on x-axis \( 1 + \frac{k - 1}{n}, k \gt 1 \) or \( \frac{1 - k}{n} - 1, k < 1\)
  • Compute the average hight of \( \frac{1}{x} \) between \( x_{i}, x_{i+1} \), \( h_i = \frac{f (x_i) + f(x_{i+1})}{2} \)
  • The width of each step is \( w = (k - 1) \times \frac{1}{n} \)
  • Each \(i\) rectangle area is \( w \times h_i \)
  • Total area of all rectanges are \( \sum_{i=1}^{n} w \times h_i \)
  • NOTE: if \( k \) is close to \( n = 100 \), then \( \log_e \) is not longer accurate value.
  • NOTE: There is no rational polynomial to approximate \( \log_e \) in large value in fast speed.
  • approximate_log_e

sqrtC :: C -> C Source #

square root for Complex number

sqrtC' :: C -> C Source #

radianToDegree :: Float -> Float Source #

  radianToDegree::Float->Float
  radianToDegree x = x*r where r = 180/pi
  

degreeToRadian :: Float -> Float Source #

  degreeToRadian::Float->Float
  degreeToRadian x = x*d where d = pi/180
  

tri :: C -> (Float, Float, Float) Source #

data GPoint Source #

Constructors

GPoint Int Int 

getX :: GPoint -> Int Source #

getY :: GPoint -> Int Source #

toUpperStr :: String -> String Source #

KEY: upper case string

Same as upperStr

lowerStr :: String -> String Source #

KEY: lower case string

Same as toLower

upperStr :: String -> String Source #

KEY: upper case string

Same as toUpperStr

upperChar :: Char -> Char Source #

KEY: upper case

toLowerStr :: String -> String Source #

Lower string

https://hoogle.haskell.org/?hoogle=tolower tolower>

toLowerStr s = foldr(\x y -> (toLower x):y) [] s

concatStr :: [String] -> String -> String Source #

KEY: concat string with delimter string s, concat str, join string

concatStr ["dog", "cat"] [] => "dogcat"
concatStr ["dog", "cat"] " " => "dog cat"
concatStr ["dog", "cat"] ":" => "dog:cat"

cat :: String -> IO () Source #

KEY: cat string, concat string

cat ["dog", "cat"] => "dogcat"

KEY: cat file, like command line cat

cat "/tmp/x.html"

readDirMatchKey :: FilePath -> String -> String -> IO [(String, String)] Source #

KEY: read file, find pattern, read dir and find pattern, read all keys

 p <- getEnv "j"
readDirMatchKey p "\\.java$" "KEY:"
   [
   ,
       ( "        KEY: system.in, standard input"
       , "Userscatmyfilebitbucketjavatry_scanner.java"
       )
   ,
       ( "            // KEY: word boundary "
       , "Userscatmyfilebitbucketjavatry_word_boundary.java"
       )
   ]
   

containStr :: String -> String -> Bool Source #

Check whether a string p contains a string s pattern

  • Use regex to check match
"^dog"
"dog$"
matchTest (mkRegex p) s
 containStr "^dog"  "dog cat" => True

str = "dog cat"
p = "dog"
containStr p str == return True
containStr p s   == matchTest (mkRegex p) s

containAscii :: String -> Bool Source #

Check non-ascii char in a string

containNonAsciiList :: [String] -> [(Integer, String)] Source #

Check non-ascii char in a [String]

check file whether it contains non-ASCII char or line

[(Line #, Line)] = [(Integer, String)]

matchAny :: String -> String -> Maybe (Int, Int) Source #

match once string and return Maybe (index, length)

matchAny (mkRegex "dog|cat") "mydog" => Just (2, 3)

See matchOnce or matchAll matchAll

matchAnyRegex :: Regex -> String -> Maybe (Int, Int) Source #

match once string and return Maybe (index, length)

matchAnyRegex (mkRegex "dog|cat") "mydog" => Just (2, 3)

See matchOnce or matchAll matchAll

type SKey = String Source #

matchScore :: SKey -> String -> (Int, String) Source #

Match a string using index as score

type SKey = String

matchScoreList :: SKey -> [String] -> [(Int, String)] Source #

Match a string using index as score

type SKey = String

fileContainNonAscii :: FilePath -> IO [(Integer, String)] Source #

Check non-ascii char in a file

Jupyterlab

fileContain :: FilePath -> String -> IO [String] Source #

file has all the lines which contain a pattern

fileHas :: (String -> Bool) -> FilePath -> IO [String] Source #

file has all the lines which contain a pattern

Same as fileContain

filterList :: (Bool -> Bool) -> [String] -> [String] -> [String] Source #

filter out a list of pattern from a list of string

[ mbox{De Morgan's laws: union and intersection} begin{aligned} A ∪ (B ∩ C) &= (A ∩ B) ∪ (A ∩ B) (A ∪ B)^¬ &= A^¬ ∩ B^¬ (A ∩ B)^¬ &= A^¬ ∪ B^¬

end{aligned} ]

filterList id ["a", "b"]  ["aa", "kk", "ab"] ⇒ ["ab"]
filterList id ["a"]      ["aa", "kk", "ab"] ⇒ ["aa", "ab"]
  • \( (A ⊗ B)^¬ = A^¬ ⊕ B^¬ \)
  • not containStr "a" \( ⊕ \) "b"
filterList not ["a", "b"] ["aa", "bb", "ab"] ⇒ ∅

intersectSet :: (Eq a, Hashable a) => [a] -> [a] -> [a] Source #

KEY: intersection of two lists, intersection of two sets

  • Deprecated

diffList :: (Eq a, Hashable a) => [a] -> [a] -> ([a], [a]) Source #

KEY: Difference between two lists

   cx = ["a", "b"]
   cy = ["a", "c"]
   diffList cx cy => (["b"], ["c"])
   

interList :: (Eq a, Hashable a) => [a] -> [a] -> [a] Source #

KEY: Intersection between two lists

   cx = ["a", "b"]
   cy = ["a", "c"]
   diffList cx cy => (["b"], ["c"])
   

intersectFile :: FilePath -> FilePath -> IO [String] Source #

intersection of two files

filterNonEmpty :: [String] -> [String] Source #

KEY: filter non empty string, no empty line

containPrefix :: String -> String -> Bool Source #

Check whether str contains sub as prefix

containPrefix "dog" "dogcat"  => True
containPrefix "dog" " dogcat" => False

containSuffix :: String -> String -> Bool Source #

KEY: Check whether str contains sub as suffix

containPrefix "cat" "dogcat"  => True
containPrefix "cat" "dogcat " => False

hasPrefix :: String -> String -> Bool Source #

KEY: Check whether str has sub as prefix

containPrefix "cat" "dogcat"  => True
containPrefix "cat" "dogcat " => False

hasSuffix :: String -> String -> Bool Source #

hasStr :: String -> String -> Bool Source #

isImage :: String -> Bool Source #

check image, check png file

lsTable :: String -> IO [[String]] Source #

ls table

replaceFileLineEscape :: String -> String -> FilePath -> IO [String] Source #

KEY: without any regex substitute,

ISSUE: See replaceFileLine ISSUE: See replaceList

   let sub = "\"  -- sub is one character => len sub == 1
   pp $ len sub
   ls <- replaceFileLineEscape "abc" sub  "tmp11.x"
   writeFileList "tmp22.x" ls
   

replaceFileLineEscapeStrict :: FilePath -> String -> String -> IO [String] Source #

strWithSlash :: String -> String Source #

KEY: string with escape character

ISSUE: See replaceFileLine replaceList replaceFileLineEscape

   let s = ""
   let s1 = show "\"
   let s2 = dropEnd 1 $ drop 1 s1
   let s2 =      writeFileList "tmpx.x" [s2]  -- write s2 to file
   
   

replaceFileLine :: String -> String -> FilePath -> IO [String] Source #

KEY: without any regex substitute, remove string and append

ISSUE: See replaceFileLineEscape ISSUE: See replaceList

   let sub = "\"  -- sub is one character => len sub == 1
   let sub' = dropEnd 1 $ drop 1 $ show sub
   pp $ len sub
   ls <- replaceFileLine "abc" sub'  "tmp11.x"
   writeFileList "tmp22.x" ls
   

redisExtractCppAronLib :: String -> [String] -> [([String], Integer, [String])] Source #

KEY: Generate [([String], Integer, [String])] from captureCppFun

   [(
       [ "AronLib.e"
       , "AronLib.ew"
       , "AronLib.ewl"
       , "AronLib.ewli"
       , "AronLib.ewlin"
       , "AronLib.ewline"
       , "AronLib.i"
       , "AronLib.in"
       , "AronLib.ine"
       , "AronLib.l"
       , "AronLib.li"
       , "AronLib.lin"            <-  [String]
       , "AronLib.line"
       , "AronLib.n"
       , "AronLib.ne"
       , "AronLib.new"
       , "AronLib.newl"
       , "AronLib.newli"
       , "AronLib.newlin"
       , "AronLib.newline"
       , "AronLib.w"
       , "AronLib.wl"
       , "AronLib.wli"
       , "AronLib.wlin"
       , "AronLib.wline"
       ]
   , 40007                        <- Integer
   , [ "void newline(){" ]        <- [String]
   )
   ]
   
   [([String], Integer, [String])]
   

readTagsFile :: FilePath -> IO [(String, String)] Source #

       etags -e -f $PWDTAGS $cpplibAronLib.h $bclibAronCLibNew.h       
              ↑ 
              + -> has to be before '-f'
   
   [
       ( "string removeIndex(string s, int inx) {"
       , "removeIndex"
       ),
       ( "vectorT removeIndex(vectorT& vec, int inx){"
       , "removeIndex"
       ),
       ( "vectorT removeIndexRange(vectorT& vec, int fromInx, int toInx){"
       , "removeIndexRange"
       )
   ]
   

extraTags :: [String] -> [(String, String)] Source #

KEY: extra function from emacs TAGS file

       etags -e -f $PWDTAGS $cpplibAronLib.h $bclibAronCLibNew.h       
              ↑ 
              + -> has to be before '-f'
   

replaceList :: [String] -> String -> String -> [String] Source #

KEY: Replace a matching string with other string

replaceList [" pat ", "  pat"] "pat" "sub" ⟹   [" sub ", "  sub"]

ERROR: "\" and "\\" with same output

  let n = "\"
  let m = "\\"
  let n' = subRegex(mkRegex "abc") "abc" n
  let m' = subRegex(mkRegex "abc") "abc" m
  pp $ n' == m'
  

searchSplitAny :: String -> String -> [(String, String, String)] Source #

Search a pattern and partition it three parts: [(String, String, String)]

   searchSplitAny "my cat eats my 123 cat"  "[[:digit:]]+"
   [("my cat eats my ","123"," cat")]
   > searchSplitAny "my cat eats my 123 cat 44a"  "[[:digit:]]+"
   [("my cat eats my ","123"," cat 44a"),(" cat ","44","a")]
   

searchSplitWord :: String -> String -> [(String, String, String)] Source #

search and replace WORD only

   searchSplit "mydog dog-- dog pig cat" "dog"
   [("my","dog"," dog-- dog pig cat"),(" ","dog","-- dog pig cat"),("-- ","dog"," pig cat")]
   

searchReplaceAny :: String -> String -> String -> String Source #

KEY: search replace any char, substitude string

  • The code is based on matchAllText in package: TDFA as TD
   searchReplaceAny "mydog dog-- dog pig cat" "dog" "[\0]" => "my[dog] [dog]-- [dog] pig cat"
   
  • Regex is from TDFA, NOT Text.Regex
word => "[[:alpha:]]+"
  • NOTE: support ONE String only, e.g. searchReplace s "dog" "[\0]"
  • TODO: support multiple words, e.g. searchReplace s "dog|cat" "[\0]"

See searchReplace

TODO: add test

searchReplaceAnyTup :: String -> (String, String) -> String Source #

searchReplaceAnySBS :: ByteString -> ByteString -> ByteString -> ByteString Source #

searchReplace :: String -> String -> String -> String Source #

Search replace word, the code is based on matchAllText in package: Text.Regex.TDFA as TD

let s = "mydog dog-- dog pig cat dog fox"
searchReplace s "dog" "[\\0]"
"mydog [dog]-- [dog] pig cat [dog] fox"
  • Text.Regex => subRegex does not support word boundary
r  = makeRegex ("\\<" ++ word ++ "\\>")::TD.Regex -- word boundary
  • Regex is from TDFA, NOT Text.Regex >word => "[[:alpha:]]+"
  • NOTE: support ONE word only, e.g. searchReplace s "dog" "[\0]"
  • TODO: support multiple words, e.g. searchReplace s "dog|cat" "[\0]"

See searchReplaceAny

Sun 31 May 13:05:58 2020 1. Fixed bug: if no matches, then the origin string should be returned 2. Moved searchSplit outside so that searchReplaceAny can use it.

   searchSplit "mydog dog-- dog pig cat" "dog"
   [("my","dog"," dog-- dog pig cat"),(" ","dog","-- dog pig cat"),("-- ","dog"," pig cat")]
   
   > searchReplace "mydog dog-- dog pig cat" "dog" "[\0]"
   "mydog [dog]-- [dog] pig cat"
   > searchReplaceAny "mydog dog-- dog pig cat" "dog" "[\0]"
   "my[dog] [dog]-- [dog] pig cat"
   >
   

searchReplaceWord :: String -> (String, String) -> String Source #

Same as searchReplace but it is better name

search and replace word

interleave :: [a] -> [a] -> [a] Source #

interleave two lists

interleave ["a", "b"] ["a1", "b1"]
["a", "a1", "b", "b1"]

Use two operation tran or transpose and concat

concat (tran [xs, ys])

SO Ref

intersperseInner :: a -> [a] -> [a] Source #

intersperseInner a list

Same as intersperse from Data.List

intersperseInner "-", [] = []
intersperseInner "-", ["a"] = ["a"]
intersperseInner "-", ["a", "b"] = ["a", "-", "b"]

listIn :: a -> [a] -> [a] Source #

Add sth between list

listIn "-", [] = []
listIn "-", ["a"] = ["a"]
listIn "-", ["a", "b"] = ["a", "-", "b"]
concat $ listIn "-" ["a", "b"]  -- "a-b"

same as intersperseOuter but it is better name

listOut :: a -> [a] -> [a] Source #

Add sth OVER the list

listOut "-", [] = []
listOut "-", ["a"] = ["-", "a", "-"]
listOUt "-", ["a", "b"] = ["-", "a", "-", "b", "-"]
concat $ listOut "-" ["a", "b"]  -- "-a-b-"

Same as intersperseInner but it is better name

intersperseOuter :: a -> [a] -> [a] Source #

intersperseOuter a list

intersperseOuter "-", [] = []
intersperseOuter "-", ["a"] = ["-", "a", "-"]
intersperseOuter "-", ["a", "b"] = ["-", "a", "-", "b", "-"]

repeat' :: Integer -> a -> [a] Source #

repeat a n times

repeat' 0 'a' => ""
repeat' 0 "a" => []
repeat' 3 'a' => aaa
repeat' 3 "a" => ["a", "a", "a"]

repeatN :: Integer -> a -> [a] Source #

repeat n times

repeat's 0 'a' => "'
repeat's 0 "a" => []
repeat's 3 "pig" => ["pig", "pig", "pig"]
  • Use repeatN instead of repeat`

replicateN :: Integer -> a -> [a] Source #

repeat n times

repeat's 0 'a' => "'
repeat's 0 "a" => []
repeat's 3 "pig" => ["pig", "pig", "pig"]
  • same as replicate but Integer type

replicate' :: Int -> a -> [a] Source #

replicate n times

replicate' 4 'a' => "aaaa"

fillList :: Integer -> [Integer] -> [Integer] Source #

fill a list with missing number

fillList 0 [1, 2, 4, 7]
[1, 2, 0, 4, 0, 0 7]

fillList 0 [-1, 2, 4, 6, 10]
[-1,0,0,2,0,4,0,6,0,0,0,10]
   pp $ fillList 0 [] == []
   pp $ fillList 0 [0] == [0]
   pp $ fillList 0 [1] == [1]
   pp $ fillList 0 [1, 2] == [1, 2]
   pp $ fillList 0 [1, 3] == [1, 0, 3]
   

readFileStrict :: FilePath -> IO String Source #

KEY: read file strictly

See readFile SIO.run::NFData sa => SIO sa -> IO sa SIO.readFile::FilePath -> SIO String

readFileListStrict :: FilePath -> IO [String] Source #

KEY: read file strictly, return a list of string

See readFile

readFileBSList :: FilePath -> IO [ByteString] Source #

readfile to list of ByteString

readFileBS :: FilePath -> IO ByteString Source #

read file and return strict ByteString

readFileSText :: FilePath -> IO Text Source #

read file and return strict Text Text

IO Data.Text.IO

readFileSTextList :: FilePath -> IO [Text] Source #

read file to list of Text

See linesSText readFileSText

charToStrictByteString :: Char -> ByteString Source #

Char to strict ByteString

plines :: String -> [String] Source #

KEY: break newlines

Like the lines function from Prelude, but treat the "\r\n" and "\r" sequences as newlines too, not just "\n".

breakNewline :: String -> (String, String) Source #

See plines

replaceByteStringFile :: FilePath -> ByteString -> ByteString -> IO ByteString Source #

KEY: replace pattern inside a file, replace string in a file

  • NOTE: It only replace one string in a file, NOT all strings

See readFileRepPat, searchReplaceAny, searchReplace

replaceFileWithBSToNew :: FilePath -> (ByteString, ByteString) -> FilePath -> IO () Source #

KEY: replace pattern inside a file, new file is created. Old file is NOT modified

See readFileRepPat, searchReplaceAny, searchReplace, replaceByteStringFile

replaceFileWithStrToNew :: FilePath -> (String, String) -> FilePath -> IO () Source #

replaceFileWithStr :: String -> String -> FilePath -> IO () Source #

KEY: replace file with string, substitude string with a pattern

  • replace all words in a file with pattern string

EXAMPLE: replaceDirWithStr pat sub dir

ISSUE: if sub contains \\ then, only one '\' is written to fname

NOTE: replace word only

    file.x
       replaceMe

     sub =
          begin{pmatrix}
          a & b             c & d
          
          end{pmatrix}

    replaceFileWithStr "replaceMe" sub "tmpf.x"

    cat tmpf.x
          begin{pmatrix}
          a & b             c & d
          
          end{pmatrix}
   

replaceFileWithWord :: String -> String -> FilePath -> IO () Source #

Search and replace word inside a file, the code is based on matchAllText in package: Text.Regex.TDFA as TD

See searchReplace replace word only

let s = "mydog dog-- dog pig cat dog fox"
searchReplace s "dog" "[\\0]"
"mydog [dog]-- [dog] pig cat [dog] fox"

replaceFileListWord :: [(String, String)] -> FilePath -> IO () Source #

Search replace words with a list of tuple in a file

See searchReplaceListWord and searchReplace

 > searchReplaceListWord [("dog", "cat")] "mydog dog"
 > "mydog cat"
 

replaceFileListStr :: [(String, String)] -> FilePath -> IO () Source #

Search replace String with a list of tuple in a file

See searchReplaceListStr and searchReplaceAny

 > searchReplaceListStr [("dog", "cat")] "mydog dog"
 > "mydog cat"
 

searchReplaceListWord :: [(String, String)] -> String -> String Source #

Search replace words with a list of tuple

See replaceFileListWord and searchReplace and searchReplaceAny

   > searchReplaceListWord [("dog", "cat")] "mydog dog"
   > "mydog cat"
   

searchReplaceListStr :: [(String, String)] -> String -> String Source #

Search replace words with a list of tuple

See replaceFileListWord and searchReplace and searchReplaceAny

   > searchReplaceListStr [("dog", "cat")] "mydog dog"
   > "mydog cat"
   

replaceDirWithStr :: String -> String -> FilePath -> IO () Source #

KEY: replace pattern with a string in all file in a dir

replaceRegex :: Regex -> String -> String -> String Source #

KEY: replace string, substitute string

Use subRegex

   -- Remove all punctuation
   replaceRegex (mkRegex "[[:punct:]]") "[mya,b,c]" ""  ⇒ myabc


   let r1 = mkRegex "google"
   let input = "http://google.com"
   let replacement = "[yahoo]"
   putStrLn $ subRegex r1 input replacement  -- http://[google].com
   

readFileRepPat :: FilePath -> ByteString -> ByteString -> IO ByteString Source #

KEY: replace pattern inside a file, replace str in file, substitude str in a file

replaceByteStringFile

   bs <- readFileRepPat "src/searchForm.html" "replaceSearchForm" $ toSBS $ optionHtml autoList
   

replaceFileWithPat :: FilePath -> ByteString -> ByteString -> IO ByteString Source #

KEY: replace pattern inside a file, replace str in file, substitude str in a file

replaceByteStringFile readFileRepPat

   bs <- replaceFileWithPat "src/searchForm.html" "replaceSearchForm" $ toSBS $ optionHtml autoList
   

toStrictBS :: ByteString -> ByteString Source #

Convert Lazy ByteString to Strict ByteString

Data.ByteString => Data.ByteString.Lazy

strictBSToString :: ByteString -> String Source #

Convert Strict ByteString to String

strictBSToString = strictTextToStr . strictByteStringToStrictText

emptySBS :: ByteString Source #

Empty Strict ByteString

toSBS :: Typeable a => a -> ByteString Source #

Convert anything to Strict ByteString

toLBS :: Typeable a => a -> ByteString Source #

Convert anything to Lazy ByteString

toSText :: Typeable a => a -> Text Source #

Convert String, ByteString, Text to Strict Text

   let st1 = let s = "a"::String in toSText s -- OK
   let st2 = toSText ("a"::String)            -- OK
   let st3 = toSText $ "a"::String            -- Error
   

toLText :: Typeable a => a -> Text Source #

Convert anything to Lazy Text

toStr :: Typeable a => a -> String Source #

Convert anthing to String

  • Lazy Text to String
  • Strict Text to String
  • Lazy ByteString to String
  • Strict ByteString to String

catMaybe :: Maybe [a] -> Maybe [a] -> Maybe [a] Source #

can be replaced with following:

(++) <$> (Just [1]) <*> (Just [2])

removeSpace :: String -> String Source #

remove white space from string

See trim trimEnd trimStart

removeSpace " a b c " => "abc"

isEmpty :: String -> Bool Source #

escapeHtml :: String -> String Source #

Escape Html special characters, e.g. only [<, >] currently, remove angle bracket

Html special characters can be added ><, >, '\', %

escapeAmpersand :: String -> String Source #

escape amperspand & \( \Rightarrow \) '&#38'

escapePartial :: String -> String Source #

escape <, >, '\'', '"'

escapeXML :: String -> String Source #

escape XML special characters <, >, '\'', '"', &

removeIndex :: Int -> [a] -> [a] Source #

Remove element from a list

removeRowCol

principleSubmatrix

insertIndexAt ⟹ insert to the next index

removeIndex 1 [1,2,3]
[1, 3]

removeIndex 3 []
[]


removeIndex 1 "abc"
"ac"
       removeIndex 100 [1, 2] => [1, 2]
       removeIndex -1  [1, 2] => [1, 2]
   

removeIndex_new :: Integer -> [a] -> [a] Source #

removeRowCol :: Integer -> Integer -> [[a]] -> [[a]] Source #

Remove specific row and column from a given matrix

removeRowCol 1 2  -- remove the first row and second column

removeIndex

principleSubmatrix

[ M =begin{bmatrix} 1 & 2 & 3 4 & 5 & 6 7 & 8 & 9

end{bmatrix} rightarrow begin{bmatrix} 4 & 6 7 & 9

end{bmatrix} ]

principleSubmatrix :: Int -> [[a]] -> [[a]] Source #

Principle submatrix

Principle submatrix is a square matrix obtained by removing the same set of rows and columns.

removeIndex

removeRowCol

principleSubmatrix 1 mat

[ M = begin{bmatrix} a & b & c d & e & f g & h & i end{bmatrix}

rightarrow begin{bmatrix} a & c g & i end{bmatrix}

]

dropEnd :: Integer -> [a] -> [a] Source #

drop n elements from the end

pp $ dropEnd 3 "abcd" == "a"

takeEnd :: Integer -> [a] -> [a] Source #

take n elements from the end

pp $ takeEnd 3 "abcd" == "bcd"

takeX :: Integer -> [a] -> [a] Source #

take support negative number

     if n >= 0 then take n
     else           takeEnd (-n)
   

dropX :: Integer -> [a] -> [a] Source #

drop support negative number

     if n >= 0 then drop n
     else           dropEnd (-n)
   

takeWhileX :: (a -> Bool) -> [a] -> [a] Source #

same takeWhile

from GHC.List

takeBS :: Integer -> ByteString -> ByteString Source #

take BS.ByteString

dropBS :: Integer -> ByteString -> ByteString Source #

drop BS.ByteString

splitBS :: Word8 -> ByteString -> [ByteString] Source #

split BS.ByteString

BS.split (c2w_ 'a') "aXaXa" => ["", "X", "X", ""]

trimWS :: String -> String Source #

trim whitespace from the whole string, NOT just head and tail

see trim head and tail

trimWS s   = filter(not . isSpace) s

trimAll :: String -> String Source #

trimAll == trimWS, better name:)

trimT :: Text -> Text Source #

Trim leading and tailing white space from Data.Text String, trim text, remove white space

trim String

trimT TS.Text

trimT = Data.Text.strip

Data.Text

trimBoth :: String -> String Source #

trimBoth == trim, better name:)

trimLBS :: ByteString -> ByteString Source #

trim lazy ByteString

  • trim leading/trailing whitespace

trimStart :: String -> String Source #

Remove whitespace characters from the start of string.

" dog" => "dog"

trimEnd :: String -> String Source #

Remove whitespace characters from the end of string.

" a b c " => " a b c"
"abc"     => "abc"

splitListEmptyLine :: [String] -> [[String]] Source #

split list of string when string is empty/space

["dog", " ", "", "cat"] => [["dog"], [], ["cat"]]

splitListHalf :: [String] -> ([String], [String]) Source #

split list into half

  • split list into half, ["a", "b", "c"] => (["a", "b"], ["c"])

t1 :: (a, b, c) -> a Source #

t2 :: (a, b, c) -> b Source #

t3 :: (a, b, c) -> c Source #

tuplify2 :: [a] -> (a, a) Source #

tuples to list

tuplify3 :: [a] -> (a, a, a) Source #

splitListWhen :: (a -> Bool) -> [a] -> [[a]] Source #

split list 2d with lambda function

Use splitWhen from Internals

   splitListWhen(x -> x == "b") ["a", "b"] => [["a"], []]
   splitListWhen(x -> x == "b") ["b", "c"] => [[], ["c"]]
   splitListWhen(x -> x == "b") ["b"] => [[], []]

   splitListWhen(x -> x == []) [["a"], ["b"], [], ["c"]]
   [[["a"], ["b"]], [["b"]]]
   

lengthcurve :: (Double -> Double) -> (Int, Int) -> Double Source #

Calculate the length of a curve for *any* functions

\[ f(x) = x^2 \quad x \in [0, 1] \]

length_of_curve

f x = x*x
lengthcurve f (0, 1)
1.4689349039867374

[ begin{align*} & text{Divide the curve into } n text{ parts} &x_i in {x_0, x_1, x_2, cdots, x_{n-1}, x_n} &f(x_i) in {f(x_0), f(x_1), f(x_2), cdots, f(x_{n-1}), f(x_n) } &y_i in {x_0^{2}, x_1^{2}, x_2^{2}, cdots, x_{n-1}^{2}, x_n^{2} } s &= sum_{i=1}^{n} sqrt{(x_{i-1} - x_i)^2 + (y_{i-1} - y_i)^2} s_1 &= sqrt{(x_0 - x_1)^2 + (x_0^{2} - x_1^2)^2} s_2 &= sqrt{(x_1 - x_1)^2 + (x_1^{2} - x_2^2)^2} vdots s_{n-1} &= sqrt{(x_{n-2} - x_{n-1})^2 + (x_{n-2}^{2} - x_{n-1}^2)^2} s_n &= sqrt{(x_{n-1} - x_n)^2 + (x_{n-1}^{2} - x_n^2)^2} \ s &= sum_{i=1}^{n} sqrt{(x_{i-1} - x_i)^2 + (y_{i-1} - y_i)^2} s &= sum_{i=1}^{n} sqrt{ Delta x_{i}^2 + Delta y_{i}^2} qquad end{align*}

# 2356 "UsersaaamyfilebitbuckethaskelllibAronModule.hs" ]

lengthcurveInter :: (Double -> Double) -> (Int, Int) -> Int -> Double Source #

Calculate the length of a curve for *any* functions in a given interval

\[ f(x) = x^2 \quad x \in [0, 1] \]

lengthcurveInter f (0, 1) 200

isBalanced3 :: String -> String -> Bool Source #

KEY: balance bracket, check balanced bracket

    []   => True
    [{}] => True
    [}   => False
    [{]} => False
   

isBalanced2 :: String -> String -> (String, Bool) Source #

findBalance :: [(Integer, String)] -> String -> ([(Integer, String)], Bool) Source #

Find all bracket '{, }' until they are balanced

   "{{ {    <- 1
        }   <- 2
       }    <- 3
   }        <- 4
   }"       <- 5
   return  => ([(5,"}")],True)
   

balanceBracket

isBalanced :: String -> Bool Source #

KEY: balance brackets

   pp $ isBalanced "" == True
   pp $ isBalanced "{" == False
   pp $ isBalanced "}" == False
   pp $ isBalanced "{}" == True
   pp $ isBalanced "}{" == False
   pp $ isBalanced "{}{" == False
   pp $ isBalanced "}{}" == False
   

balanceBracket

strToLazyText :: String -> Text Source #

String to Lazy Text

lazyTextToStr :: Text -> String Source #

strToStrictText :: String -> Text Source #

KEYS: string to strict text, str to strict text, str to text

String to Text

strictTextToStr :: Text -> String Source #

Strict Text to String

KEY: strict text to str, text to string

lazyTextToLazyByteString :: Text -> ByteString Source #

lazy Text to lazy ByteString

KEY: lazy Text to lazy ByteString

lazyByteStringToLazyText :: ByteString -> Text Source #

strictTextToStrictByteString :: Text -> ByteString Source #

strict Text to strict ByteString

strictByteStringToStrictText :: ByteString -> Text Source #

Convert Strict ByteString to Strict Text

strictByteStringToLazyByteString :: ByteString -> ByteString Source #

lazyByteStringToStrictByteString :: ByteString -> ByteString Source #

Convert lazy ByteString to strict ByteString

strictTextToLazyText :: Text -> Text Source #

lazyTextToStrictText :: Text -> Text Source #

Lazy Text to Strict Text

strToStrictByteString :: String -> ByteString Source #

String to Strict ByteString, String to ByteString, str to ByteString

strToStrictByteString = strictTextToStrictByteString . strToStrictText

strToLazyByteString :: String -> ByteString Source #

String to lazy ByteString, only for ASCII, not for unicode

   str1 = "好"
   str2 = "good"

   main = do
           pp ((LC8.unpack $ LC8.pack str1) == str1) -- False
           pp ((LC8.unpack $ LC8.pack str2) == str2) -- True
   

ppad :: Show a => [[a]] -> [[[Char]]] Source #

padding whitespace to 2d list or matrix

jsonDecode :: FromJSON a => String -> Maybe a Source #

KEY: String to Maybe DA.FromJSON

See toLBS

   toLBS::Typeable a => a -> BL.ByteString
   

jsonToRecord :: FromJSON a => FilePath -> IO (Maybe a) Source #

KEY: JSON to record, JSON file to record

   SEE: UsersaaamyfilebitbucketstackprojectJsonAeson

   -- JSON file
   {"editorbeg":100,
    "editorend":200,
    "editorfile":"try919591",
    "editorcmd":"save",
    "editorcode":"Hello World",

    "mycat":{"name":"meowmers",
             "age":1,"list":["dog","cat"]
            }
   }
   --

   data EditorCode = EditorCode{
     editorbeg::Integer,
     editorend::Integer,
     editorfile::String,
     editorcmd::String,
     editorcode::String,
     mycat::Cat
     } deriving (Show, Generic)

   instance DA.ToJSON EditorCode where
     toEncoding = DA.genericToEncoding DA.defaultOptions

   instance DA.FromJSON EditorCode

   data Cat = Cat { name :: Text,
                    age :: Int,
                    list :: [String]
                  } deriving (Show, Generic)

   instance DA.ToJSON Cat where
     toEncoding = DA.genericToEncoding DA.defaultOptions

   instance DA.FromJSON Cat

   meowmers = Cat { name = "meowmers",
                    age = 1,
                    list = ["dog", "cat", "independency Injection"]
                  }

   editCode = EditorCode {
     editorbeg = 100,
     editorend = 200,
     editorfile = "try919591",
     editorcmd = "save",
     editorcode = "Hello World",
     mycat = meowmers
   }

   decodeStr <- jsonToRecord "/tmp/json.json" :: IO (Maybe EditorCode)
   case decodeStr of
     Nothing -> Prelude.putStrLn "Not a Valid JSON file"
     (Just x) -> Prelude.putStrLn $ show x
   

compileJava :: FilePath -> IO ExitCode Source #

Compile java file

  • Given an absoluate path
  • return and ExitCode
  • The function is used in filewatcher.
docExitCode <- compileJava "/Users/cat/myfile/bitbucket/testfile/compileJavaTest.java"
case docExitCode of
     ExitSuccess -> sys "notify.sh \"gene_javadoc.sh => ExitSuccess\""
     ExitFailure x -> sys "notify.sh \"gene_javadoc.sh => ExitFailure\""

pm :: Show a => String -> [[a]] -> IO () Source #

Print matrix with label, print matrix with string,

pm "my matrix" mat
------------------------------------my matrix-----------------------------------
[1,2,3]
[4,5,6]
[7,8,10]

pls :: [String] -> IO () Source #

print list of string without double quotes

  • rename: ps => pls (Wed Oct 16 22:18:00 2019)

ps :: String -> IO () Source #

KEY: print string without double quotes

printMat :: Show a => [[a]] -> IO () Source #

KEY: print matrix, print 2d list

SEE pmat matrixToStr let ls = [[1..4] | _ <- [1..4]] printMat ls

pmat :: Show a => [[a]] -> IO () Source #

KEY: print matrix, print 2d list

SEE printMat matrixToStr let ls = [[1..4] | _ <- [1..4]] pmat ls

pMat :: Show a => [[a]] -> IO () Source #

matrixToStr :: Show a => [[a]] -> [String] Source #

KEY: matrix to string, 2d list to string, print matrix

SEE printMat

  > ls = [[1..4] | x <- [1..4]]
  > s = matrixToStr ls
  > mapM_ putStrLn s
    1 2 3 4
    1 2 3 4
    1 2 3 4
    1 2 3 4
  > wfl "tmpkk.x" s
  > :!cat tmpkk.x
    1 2 3 4
    1 2 3 4
    1 2 3 4
    1 2 3 4
  

psTab :: Integer -> String -> IO () Source #

prefix n tabs

psTab 3 "dog"

pa :: Show a => [[a]] -> IO () Source #

print matrix, show matrix

paa :: Show a => [[a]] -> IO () Source #

KEY: print matrix, print string without double quotes

listSlide :: [a] -> Int -> [[a]] Source #

  • KEY: list slide, list sliding, window sliding, sliding window
  • @ listSlide [a b c d] 2 > [[a, b], [b, c], [c, d]]

listSlide [a b c d] 5 > []

partList :: Int -> [a] -> [[a]] Source #

Partition list to n chunks

UPDATE: Thursday, 16 November 2023 14:42 PST FIXBUG: partList 0 [1, 2] => in infinite loop

Note: print partList n [] will cause error since print needs concrete type

split list to n blocks

   >partList 2 [1, 2, 3, 4, 5]
   >[[1,2], [3, 4],[5]]
   
   >partList 2 [1, 2, 3, 4, 5, 6]
   >[[1,2], [3, 4],[5, 6]]

   > partList 0 [1, 2]
   > [[1, 2]]

   > partList -1 [1, 2]
   > [[1, 2]]
   

partList2_delete :: Int -> [a] -> [[a]] Source #

Partition list to n chunks

Deprecated: Use: partListDiff

partListDiff :: Int -> Int -> [a] -> [[a]] Source #

Partition list to n chunks

Note: print partList n [] will cause error since print needs concrete type

split list to n blocks @ partListDiff 1 2 [1, 2, 3, 4] ↑ ↑ | + -> block size | + -> distance 1

> [1, 2]

2, 3
3, 4
@

getLineX :: IO String Source #

KEY: read line, read input, flush stdout

    hFlush stdout >> getLine
   

copyFileX :: FilePath -> FilePath -> IO () Source #

KEY: copy file, copyFile

copyFile from Directory

cp :: FilePath -> FilePath -> IO () Source #

KEY: copy file, copyFile

copyFile from Directory copyFileX

spanA :: (a -> Bool) -> [a] -> ([a], [a]) Source #

See span

splitSPC :: String -> [String] Source #

KEY: split string with "[ ]+"

splitBlock :: [String] -> String -> [[String]] Source #

KEY: split file with Regex e.g. empty line

NOTE: use better name, splitTable ? @ ls <- readFileToList "tmpx.x" let lss = splitBlock ls "^[[:space:]]*" => split file with whitespace pp lss

let lss = splitBlock ls "^[[:space:]]*(---){1,}[[:space:]]*" => split file "---" let lss = splitBlock ls "^[[:space:]]*(===){1,}[[:space:]]*" => split file "==="

let lss = splitBlock ["a", " ", "b"] "^[[:space:]]*" => [["a"], ["b"]] let lss = splitBlock ["a", "n", "b"] "^[[:space:]]*" => [["a"], ["b"]] let lss = splitBlock ["a", "t", "b"] "^[[:space:]]*" => [["a"], ["b"]]

  • - It works in WhiteSpace

let lss = splitBlock ["a", " ", "b"] "^[[:space:]]*" => [["a"], ["b"]] let lss = splitBlock ["a", "n", "b"] "^[[:space:]]*" => [["a"], ["b"]] let lss = splitBlock ["a", "t", "b"] "^[[:space:]]*" => [["a"], ["b"]] @

NOTE: IT DOES NOT WORK if Empty string in the list. See following. let lss = splitBlock ["a", "", "b"] "^[[:space:]]*" => [["a", "", "b"]]

TestFile

parseFileBlock :: String -> String -> [String] -> [(Integer, [String])] Source #

KEY: parse file and partition it into blocks according to patterns: bs ws

bs = "^[[:space:]]*(---){1,}[[:space:]]*" -- split with delimiter "---"
ws = "[,. ]"                              -- split with [,. ]
parseFileBlock bs ws ["rat",
                      "-----",
                      "my dog eats my cat, my cat eats my dog."
                     ]
[(0, ["rat"]), (1, ["my", "dog", "eats", "my", "cat"])]

Test_File

prefix :: String -> [String] Source #

KEY: all prefix strings from given string

prefixSuffix :: String -> [String] Source #

lengthK :: Int -> String -> [String] Source #

substring length k

lengthK 2 ["abcd"]
["ab", "bc", "cd"]

substr :: Int -> String -> [[String]] Source #

substring length from 1 to len s

substr 1 "abc"
["a", "b", "c", "ab", "bc", "abc"]

allSubstr :: String -> [[String]] Source #

all substrings length from 1 to len s

allSubstr "abcd"
[["a","b","c","d"],["ab","bc","cd"],["abc","bcd"],["abcd"]]

unique :: Ord a => [a] -> [a] Source #

unique, remove duplicate elements from a list

Convert the list to Set and convert the Set back to List unique does not keep the order of elements

   2 3 4 4 5 3 5 => Remove from the right => 2 3 4 5 3
   2 3 4 4 5 3 5 => Remove from the left  => 2 3 4 3 5
   

uniqueOrder keeps the order of elements from left \( \Rightarrow \) right

uniqueOrder :: Ord a => [a] -> [a] Source #

remove duplicated elements and keep the order from left to right

   ["a", "b", "a", "b"] => ["a", "b"]
   s = ["a"]
   s = ["a", "b"]
   "a" elem s => ["a", "b"]
   "b" elem s => ["a", "b"]
   

Recur from the right => left instead of (x:cx)

The runtime will be \( \color{red}{\mathcal{O}(n^2)} \)

NOTE: can be better algorithm

mergeListList :: [[String]] -> [[String]] -> [[String]] Source #

mergeList :: [a] -> [a] -> [a] Source #

mergeListLen :: [a] -> [a] -> Maybe [a] Source #

mergeSortList :: Ord a => [a] -> [a] -> [a] Source #

merge two sorted lists | [1, 4] [3] => [1, 3, 4]

iterateList :: [a] -> (a -> IO ()) -> IO () Source #

unwrap :: Maybe a -> a Source #

codeCapture :: String -> String Source #

binarySearch :: Ord a => a -> [a] -> Bool Source #

Binary Search

qqsort :: (a -> a -> Bool) -> [a] -> [a] Source #

quick sort with lambda function

bad version

qqsort(\x y -> len x < len y) ["tiger", "dog"]  => ["dog", "tiger"]

sort :: Ord a => [a] -> [a] Source #

Sort list in nature ordering, e.g. [2, 1] => [1, 2]

sqVec :: Ord a => Vector a -> Vector a Source #

Quick Sort in Vector, Did not see any speed decreasing

quickSort :: [Int] -> [Int] Source #

quicksort better version

quickSort' :: [Int] -> [Int] Source #

nice version

  • TODO rename it

quickSort1 :: Ord a => [a] -> [a] Source #

Use quickSortAny, Deprecated

  • note: quickSort1 [] -- get error
print quickSort1 ([]::Int)  -- it works

quickSortAny :: Ord a => [a] -> [a] Source #

Quick Sort for any type, same as quickSort1, just a better name

mergeSortedList :: Ord a => [a] -> [a] -> [a] Source #

merge sorted list

rotateRight :: Integer -> [a] -> [a] Source #

rotate a list to the right

rotateRight 2 [1, 2, 3]
[2, 3, 1]

rotateLeft2 :: [[a]] -> [[a]] Source #

rotate a 2d matrix to the left

rotateLeft2 mat 

rotateRight2 :: [[a]] -> [[a]] Source #

rotate a 2d matrix to the right

rotateRight2 mat 

rotateLeft :: Integer -> [a] -> [a] Source #

rotate a list to the left

rotateLeft 2 [1, 2, 3]
[3, 1, 2]

mergeSortC :: (a -> a -> Bool) -> [a] -> [a] Source #

Merge sort for any type

  • TODO rename it

mergeSort :: [Int] -> [Int] Source #

Merge sort for Int

mergeSortM :: (Num a, Eq a) => [[a]] -> [[a]] Source #

Merge sort for matrix, special merge sort

   [0, 1]  [1]         => False
   [0, 1]  [1, 1]      => True
   [1, 1]  [0, 1]      => False
   [0, 1, 0] [1, 0, 0] => True
   

groupCount :: [String] -> [(String, Integer)] Source #

groupCount == groupBy . sort

groupCount ["a", "b", "a"] => [("b", 1), ("a", 2)]
groupCount == groupBy . sort
  • See groupBy

vimLink :: IO () Source #

Create Symbol link for vim under home

.vimrc -> $b/vim/vim.vimrc
  • simplify link file in new system
  • it might not be very useful

watchDir :: FilePath -> IO Bool Source #

Watch directory

  • If any file is modified, then return True
  • If a file is added to directory, then return True
  • The delay is one second

fileModTime :: FilePath -> IO EpochTime Source #

KEY: file modification time, timestamp, epoch time in second

EpochTime \( \Rightarrow \) Int64

fileModTimeInt :: FilePath -> IO Int Source #

KEY: file modification time, timestamp, epoch time in second

KEY: epochtime to int

EpochTime \( \Rightarrow \) Int

EpochTime \( \Rightarrow \) Int64

fromEnum Int64 \( \Rightarrow \) Int

fileModTimeInteger :: FilePath -> IO Integer Source #

KEY: file modification time, timestamp, epoch time in second

EpochTime \( \Rightarrow \) Int64 fromIntegral Int \( \Rightarrow \) Integer

intToCTime :: Int -> CTime Source #

KEY: convert int to CTime

Use toEnum

EpochTime \( \Rightarrow \) Int64

dirModified :: FilePath -> IO [EpochTime] Source #

return a list of timestamps that any files is modified in a directory

EpochTime \( \Rightarrow \) Int64

fileSizeA :: FilePath -> IO Integer Source #

KEY: Get file size in byte

See hFileSize openFile ReadMode Handle

readSnippet :: FilePath -> IO [([String], [String])] Source #

Read Snippet file $bsnippetssnippet.hs

   main:*.hs: my dog, my cat
   my fox eats my rat
   
output:
[([head1], [head1_content1]), ([head2], [head2_content2])]
[(["main", "*.hs", "my cat", "my dog"], ["main:*.hs: my dog, my cat","my fox eats my rat "])]

readFileLatin1ToList

 $b/snippet/snippet.hs
partition blocktexts into list

parse the header => latex_eqq:*.tex: latex equation
return [(["latex_eqq", "latex equation"]), ["latex_eqq:*.tex: latex equation", "code block"])]

TODO: write readSnippet for Data.ByteString ?

HELP: gx file://Userscatmyfilebitbucketstackprojectjupyterlab/jupyterlab.html

snippet_test.hs

readSnippetStr :: FilePath -> IO [(String, String)] Source #

readSnippetStr without any split

See readSnippet

[("key_name:*.tex: latex", "key_name:*.tex: latex\nline 1\n\line2"])]
readSnippetStr::FilePath->IO [(header, codeblock)]

readSnippetToDatabase :: FilePath -> Connection -> IO () Source #

KEY: Read snippet file, insert into database, snippet to database, snippet to db

  • read snippet file, insert to database sqlite3

See CodeBlock data CodeBlock = CodeBlock { id :: Int64 , header :: TS.Text , codeblock :: TS.Text } deriving (Eq, Read, Show)

queryDatabaseToFile :: FilePath -> Connection -> IO () Source #

Query Table CodeBlock and write to a file

mapM_ :: Monad m => (a -> m b) -> [a] -> IO()

How To Use It

    import           Database.SQLite.Simple
    import           Database.SQLite.Simple.FromRow
    import           Database.SQLite.Simple.FromField
    import           Database.SQLite.Simple.ToField
    import           Database.SQLite.Simple.Internal
    import           Database.SQLite.Simple.Ok

    codeBlocks <- query_ conn "SELECT id, header, codeblock from CodeBlock" :: IO [CodeBlock]
    let codeList = map (x -> lines . toStr . codeblock $ x) codeBlocks
    mapM_ (b -> do
                 writeToFileAppend fp b
          ) codeList
    

mysqlQuery :: IO () Source #

KEY: Haskell connect to mysql

mysql-haskell

create user 'user1'@'localhost' identified by 'password';    # mysql => create new user
GRANT select, update, delete ON *.* TO 'user1'@'localhost';  # grand permission
GRANT ALL ON *.* to 'user1'@'localhost';                     # grand all permissions
ALTER USER 'user1'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'   # program can connect to
--------------------+
mysql> source /tmp/user.file
--------------------+
sudo mysql -u user1 -p   # password
---------------------
mysql> CREATE DATABASE testdb   # create database in mysql
mysql> USE testdb               # use testdb - database
mysql> source mytable.sql       # load table, source table, add table
   DROP TABLE mytable;
   CREATE TABLE mytable(
       id INTEGER NOT NULL AUTO_INCREMENT,
       name TEXT NOT NULL,
       email TEXT NOT NULL,
       PRIMARY KEY(id)
   );
   INSERT INTO mytable(name, email) VALUES("name1", "mailgmail.com");
   INSERT INTO mytable(name, email) VALUES("name2", "mailgmail.com");
   INSERT INTO mytable(name, email) VALUES("name3", "mail@gmail.com");
   

strToStrictByteString

createConfigMap :: [[(String, String)]] -> HashMap String (HashMap String String) Source #

Create a config map for different OS

Use it to replace readConfig

   config =[
            [("os", "darwin")],
             [
               ("testdb",          "myfilebitbuckettestfile/test.db"),
               ("webappdb",        "myfilebitbuckettestfile/haskellwebapp2.db"),
               ("host",            "http://localhost"),
               ("snippetpath",     "myfilebitbucketsnippets/snippet.hs"),
               ("port",            "8000"),
               ("readSnippetFile", False)
             ]
           ]
   

readFileRemote :: FilePath -> FilePath -> IO () Source #

read file remotely and write to local file

readFileRemote "https://some.com/file.txt"  "/tmp/file.xt"

readFileRemoteToList :: FilePath -> IO ByteString Source #

read file remotely and return IO BL.ByteString

bs <- readFileRemoteToList "https://some.com/file.txt"

readFileLatin1 :: FilePath -> IO String Source #

readFile2d :: Read a => FilePath -> IO [[a]] Source #

Read generic type from a file and conver to two dim list, read table

   fn = "tmpf.x"
   
   tmpf.x
   1 2 3
   3 4 5

   ls <- readFile2d fn :: IO[[Integer]]
   pre ls

   fn = "tmpf.x"
   
   tmpf.x
   0.2 0.3
   0.1 0.5

   ls <- readFile2d fn :: IO[[Float]]
   ls ls
   

FIX: trim string before read it

readFileToInteger2d :: FilePath -> IO [[Integer]] Source #

read two dim matrix from a file, read a list of list Integer from a file

readFile2d for different type

p1 = "/Users/cat/myfile/bitbucket/testfile/matrix.txt"
lss <- readFileToInteger2d p1
pa lss

orgList :: [String] -> [String] Source #

Read dir, all dir or files in [String]

There is error when reading some non utf8 or weird char.

Deprecated, use readFileLatin1ToList

 hGetContents: invalid argument (invalid byte sequence)

["f1", "f2"]

Emacs Org mod forms a list

["dog", "cat"] => ["|", "dog", "|", "cat", "|"]

orgTable :: FilePath -> [[String]] -> IO () Source #

Emacs Org mode forms a table

  • | cat | dog |
  • | cow | pig |

writeToFile :: FilePath -> [String] -> IO () Source #

Write [String] to file

writeFileBS :: FilePath -> ByteString -> IO () Source #

Write BS.ByteString to file

  • writeFileBS used BS.writeFile, nothing else
writeFileBS "file.x" (strToStrictByteString "data")

writeFile

writeFileListBS :: FilePath -> [ByteString] -> IO () Source #

Write [BS.ByteString] to file

  • writeFileListBS uses BS.writeFile and BS.concat, nothing else

writeFile

writeToFileAppend :: FilePath -> [String] -> IO () Source #

append list to file

TODO: rename it

Same as writeFileListAppend

writeFileListAppend :: FilePath -> [String] -> IO () Source #

append list to file

TODO: rename it

Same as writeToFileAppend

nToFractMat :: (Real a, Fractional b) => [[a]] -> [[b]] Source #

Matrix: Integer to Fractional, convert integer matrix to Fractional matrix

see nToNumMat

class (Num a)=>Fractional a where
class (Num a, Ord a)=> Real where
class (Real a, Enum a)=> Integral where

toNum :: Num a => Integer -> a Source #

Conver Integer to Num

nToNumMat :: Num b => [[Integer]] -> [[b]] Source #

Convert an Integer matrix to an Num Matrix

see nToFractMat

rToRatMat :: Real a => [[a]] -> [[Rational]] Source #

Matrix: Real to Rational

see nToFractMat, nToNumMat

data Rational = Ratio Integer

writeToFile2dMat :: (Num a, Fractional a, Show a) => FilePath -> [[a]] -> IO () Source #

Write an 2d Matrix to file, write an 2d list to file, write matrix to file

see writeToFileMat

[ begin{bmatrix} 1 & 2 3 & 4 end{bmatrix} Rightarrow

begin{matrix} 1 & 2 3 & 4 end{matrix}

]

m = [[1, 2], [3, 4]]
writeToFile2dMat "/tmp/m.x" m
:!cat /tmp/m.x

writeToFileMat :: FilePath -> [[String]] -> IO () Source #

write String matrix to file

see writeToFile2dMat

filtermap :: (a -> Maybe b) -> [a] -> [b] Source #

KEY: filter and map simultaneous

filtermap(\x -> elem x ['a', 'e', 'i', 'o', 'u', 'y'] then Nothing else Just (toUpper x)) "abc"
remove all the vowels and toUpper => "BC"

Prepend an element to a list if available. Leave the list as it is if the first argument is Nothing. Variant of map which deletes elements if the map function returns Nothing.

https://snipplr.com/view/59474/simultaneous-filter-and--map/

putStrLnBS :: ByteString -> IO () Source #

putStrBS :: ByteString -> IO () Source #

bs :: [[Double]] -> [Double] -> [Double] -> [Double] Source #

Backward substitute

Given an upper triangle matrix \(A\) and a vector \(\vec{b}\), solve for \(x\)

backward_substitute

\[ Ax = b \] [ A = begin{bmatrix} 1 & 2 0 & 4 end{bmatrix}

begin{bmatrix} x_1 x_2

end{bmatrix} = begin{bmatrix} b_1 b_2

end{bmatrix} ]

fs :: [[Double]] -> [Double] -> [Double] -> [Double] Source #

forward substitute

Given a lower triangle matrix \(A\) and a vector \(\vec{b}\), solve for \(x\)

backward_substitute

\[ Ax = b \] [ A = begin{bmatrix} 1 & 0 2 & 4 end{bmatrix}

begin{bmatrix} x_1 x_2

end{bmatrix} = begin{bmatrix} b_1 b_2

end{bmatrix} ]

listDot :: Num a => [a] -> [a] -> a Source #

listDots :: Num a => [[a]] -> [[a]] -> a Source #

scaleList :: Num a => a -> [a] -> [a] Source #

listScale :: Num a => [a] -> a -> [a] Source #

listAdd :: Num a => [a] -> [a] -> [a] Source #

listSub :: Num a => [a] -> [a] -> [a] Source #

listMul :: Num a => [a] -> [a] -> [a] Source #

listNeg :: Num a => [a] -> [a] Source #

dim :: [[a]] -> (Int, Int) Source #

Find the dimension of a matrix -> (nrow, ncol)

dim [] => (0, 0)

NOTE: there is bug >dim [1]

zipWithArr :: Num a => (a -> a -> a) -> IOArray Int a -> IOArray Int a -> IO (IOArray Int a) Source #

zipWith two mutable array

TODO: change Int to generic type with forall a. ? Problem: when you initialize the array, you need a concrete type such as Int, Float Solution: constrain to (Num a) type

zipWithArrToList :: Num a => (a -> a -> a) -> IOArray Int a -> IOArray Int a -> IO [a] Source #

zipWith two mutable array, and convert to list

TODO: change Int to generic type with forall a. ? Problem: when you initialize the array, you need a concrete type such as Int, Float Solution: constrain to (Num a) type

det :: Num a => [[a]] -> a Source #

Use co-factor expantion to find a determinant of n by n matrix.

  • co-factor expantion
  • It is very slow.
  • Note: \( \det M = \det M^{T} \)
  • NOTE: the function should not been used for Floating type

Proof

multiMatInt :: [[Int]] -> [[Int]] -> [[Int]] Source #

matrix multiplicaiton in Int

multiVec :: Num a => [[a]] -> [a] -> [[a]] Source #

KEY: matrix multiply a column vector

NOTE: return a column-matrix, the vector is in the first column

INPUT: column-matrix RETURN: column-matix

   -- treat v as column vector
   fw "mat"
   printMat mat
   v = [1, 2, 3]
   fw "v"
   v
   m1 = mat multiVec v
   fw "m1"
   printMat m1
 

multiVecL :: Num a => [[a]] -> [a] -> [a] Source #

multiMatStr :: [[String]] -> [[String]] -> [[String]] Source #

Matrix multiplication in String

   m1 =
   ["a","b"]
   ["c","d"]
   m2 =
   ["x","y"]
   ["z","w"]

   > mapM_ print $ multiMatStr m1 m2
   ["axbz","aybw"]
   ["cxdz","cydw"]

   > mapM_ print m1
   ["a","b"]
   ["c","d"]

   > mapM_ print m2
   ["x","y"]
   ["z","w"]

   > pmat mat
   1 2 3
   4 5 6
   7 8 10
   > pmat $ tran mat
   1 4 7
   2 5 8
   3 6 10
   > pmat $ (map . map) (r -> concatStr r "+") $ (out . zipWith) (a b -> show a ++ "x" ++ show b) mat $ tran mat
   "1x1+2x4+3x7"  "1x2+2x5+3x8"  "1x3+2x6+3x10"
   "4x1+5x4+6x7"  "4x2+5x5+6x8"  "4x3+5x6+6x10"
   "7x1+8x4+10x7" "7x2+8x5+10x8" "7x3+8x6+10x10"
   >
   

cart :: [[a]] -> [[a]] -> [[([a], [a])]] Source #

 cart::[[a]] ->[[a]] -> [[([a], [a])]]
 cart cx cy = tran $ [[(x, y) | x <- cx] | y <- tran cy]
 

multiMatDouble :: [[Double]] -> [[Double]] -> [[Double]] Source #

matrix multiplication in Double multiMatDouble::[[Double]]->[[Double]]->[[Double]] multiMatDouble a b = [ [sum $ zipWith (*) ar bc | bc <- (L.transpose b)] | ar <- a]

multiMatR :: [[Rational]] -> [[Rational]] -> [[Rational]] Source #

matrix multiplication in Rational Number

 > pmat matr
 1 % 1 2 % 1 3 % 1
 4 % 1 5 % 1 6 % 1
 7 % 1 8 % 1 10 % 1

 > pmat $ multiMatR matr matr
 30 % 1  36 % 1  45 % 1
 66 % 1  81 % 1  102 % 1
 109 % 1 134 % 1 169 % 1
 

multiMatNum :: Num a => [[a]] -> [[a]] -> [[a]] Source #

multiMat :: Num a => [[a]] -> [[a]] -> [[a]] Source #

KEY: Use outer product to compute matrix multiplication.

[ begin{bmatrix} 1 & 2 & 3 4 & 5 & 6 7 & 8 & 9

end{bmatrix} ]

  • use outer product to compute matrix mulitplication
  • outer(col_1 row_1) + outer(col_2 row_2) + outer(col_3 row_3)
  • matrix multiply vector
  -- column vector
  [[1],
   [2],
   [3]]
  -- row vector
   [[1, 2, 3]]

  -- matrix * vector

  -- matrix m
  m = [
       [1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]
      ]
  -- vector V
    [a,
     b, 
     c]
   to matrix form
   v = [
        [a, 0, 0],
        [b, 0, 0],
        [c, 0, 0]
       ]
   matrix multiply vector
   m * v
  

[ begin{bmatrix} 1 & 2 & 3 4 & 5 & 6 7 & 8 & 9 end{bmatrix}

times begin{bmatrix} 1 2 3 end{bmatrix} Can be written as following

begin{bmatrix} 1 & 2 & 3 4 & 5 & 6 7 & 8 & 9 end{bmatrix}

times begin{bmatrix} 1 & 0 & 0 2 & 0 & 0 3 & 0 & 0 end{bmatrix}

]

matDiv :: [[Integer]] -> Integer -> [[Integer]] Source #

multiRatMat :: [[String]] -> [[String]] -> [[String]] Source #

matrix multiplication in String/Rational

sumRatList :: [String] -> String Source #

addR :: String -> String -> String Source #

matId :: Num a => Int -> [[a]] Source #

KEY: identity matrix

  matId 3
  out (a b -> a == b ? 1 $ 0) [1..3] [1..3]
  

matZero :: Num a => Int -> [[a]] Source #

KEY: zero matrix

  matId 3
  out (_ _ -> 0) [1..3] [1..3]
  

ratToInt :: String -> String Source #

Convert Rational to Integer:

>>> ratToInt "3/1"
3

normalR :: String -> String Source #

normalR -3-1 = 31, 3-2 => -32

reduceForm :: [[String]] -> [[String]] Source #

reduceForm list of rational

reduce :: [Integer] -> [Integer] Source #

reduce numerator and denominator:

>>> reduce 6/2
3/1

stringToFloat :: String -> Float Source #

Convert string to Float, string to Double

stringToFloat "123"
123

stringToFloat "123.3"
123.3

stringToFloat "a"
error

strToF :: String -> Float Source #

stringToListInt :: String -> [Int] Source #

Convert string to a list of Int

stringToListInt "[1, 2]"
[1, 2]

stringToListInt "[1..3]"
error

Text.Read

word :: String -> (String, String) Source #

split first word by delimiter: isSpace

split "my dog eats my cat"
("my", "dog eats my cat")

parser

sentence :: String -> [String] Source #

split all words with delimiter: isSpace

parser

print $ sentence "dog cat 133"
["dog", "cat", "133"]

isWord :: String -> Bool Source #

Check a string whether it is a word or not

 Word is defined as  "^[[:alpha:]]+$"
isWord "dog"
True

isWord "dog1"
False

isWord::String -> Bool
isWord s = matchTest (mkRegex "^[[:alpha:]]+$") s

isInWord :: Char -> Bool Source #

Check a string whether it is a word or not

Word should be defined as [a-zA-Z0-9_] according to vim doc :h pattern

hasWordChar :: String -> Bool Source #

Check whether String contain Word char

     Word = [a-zA-Z0-9_]
     hasWordChar "abc_efg"  -- True
     hasWordChar "abc-"     -- False
   

isZeroPos :: String -> Bool Source #

Non negative integer

  • \( 0, 1, 2, \cdot \)

perm :: [a] -> [[[a]]] Source #

Permutation of any type, the algo is based on prefix string

permutation_tree

   fun (prefix, int index, removeIndex(index str))
   
 perm "12"
[["12", "21"]]

TODO: fix, the code has error.

perm2 :: Eq a => [a] -> [[a]] Source #

Permutation of any type

The code is based on prefix string algorithm

 perm "12"
[["12", "21"]]
       abc
       a p(bc)
          b p(c)
            c p()
          c p(b)
            b p()
       b p(ac)
         a p(c)
           c p()
         c p(a)
           a p()
       c p(ab)
         a p(b)
           b p()
         b p(a)
           a p()
   
       abc
           a   bc
               b c
                   [[]]
               c b
                   [[]]

           b   ac
               a c
                   [[]]
               c a
                   [[]]

           c   ab
               a b
                   [[]]
               b a
                   [[]]
   

rangeNum :: Eq a => Integer -> [a] -> [[a]] Source #

KEY: facebook interview question

  • find all the list that in increasing order, and the length is n
rangeNum 3 [1, 2, 3, 4]
[1, 2, 3], [2, 3, 4], [1, 2, 4]

perm3 :: [a] -> [[a]] Source #

And other Permutation

SO

1, 2, 3

x : xs 1 [2,3] x : xs 2 [3] x : xs 3 []

perm([1, 2, 3]) 1 : perm([2, 3]) 2 : perm([3]) 3: perm([])

1 2 3
[2 3 1] [3 1 2] x : cx x:cx x : cx 1:[2,3] 2:[3,1] 3:[1,2] 1:[3,2] 2:[1,3] 3:[2,1]

splitR :: String -> [Integer] Source #

multR :: String -> String -> String Source #

multRL :: String -> [String] -> [String] Source #

normR :: [String] -> [String] -> String Source #

getVec :: Int -> [[a]] -> [[a]] Source #

normList :: Floating a => [[a]] -> [[a]] Source #

Normalize a list as vector

 [[1, 2, 3]]     is row vector
 [[1], [2], [3]] is column vector
 

\[ \| \vec{v} \| = \sqrt{x^2 + y^2 + z^2} \quad \text{ where } \vec{v} = \begin{bmatrix} x & y & z \end{bmatrix} \]

proj :: [String] -> [String] -> [String] Source #

projn :: Fractional a => [[a]] -> [[a]] -> [[a]] Source #

projection from u onto v in n dimensional list | | puv = (u v /v) v | |

rMatrixUpperTri :: Num c => [[[c]]] -> [[[c]]] -> [[c]] Source #

Form a almost R matrix: almost an upper triangle matrix

QR_Decomposition [ R' = begin{bmatrix} leftv_1 right & leftv_2 right & leftv_3 right emptyset & leftv_2 right & leftv_3 right emptyset & emptyset & leftv_3 right

end{bmatrix} quad R = begin{bmatrix} leftv_1 right & leftv_2 right & leftv_3 right 0 & leftv_2 right & leftv_3 right 0 & 0 & leftv_3 right

end{bmatrix} R' neq R

]

rejection :: Fractional a => [[[a]]] -> [[[a]]] -> [[[a]]] Source #

rejection \(v_k\) onto span of \( \{ a_1 \dots a_{k-1} \} \)

QR_Decomposition \[ a_k = v_k - \sum_{i=1}^{k-1} \frac{\left<v_k, a_i \right>}{\left<a_i, a_i \right> } a_i \]

  • v3 projects onto \( \{a_1, a_2 \} \)
a3 = v3 - ((projn v3 a1) + (projn v3 a2))
  • if the matrix is singular then one of \( \left\| a_k \right\| = 0 \)
  • that can be used to determinate the determinant of a matrix, but not the sign of a determinant
  • compute the determiant is hard problem: \( \mathcal{O}(n^3) \), there is better algo.

qrDecompose' :: [[Double]] -> ([[Double]], [[Double]]) Source #

QR decomposition or QR factorization

QR_Decomposition

  • Given \(M\) is square matrix, there exists a pair of matrices \( Q \) is unitary matrix and \( R \) is upper triangle matrix such that: \[ M = QR \]

addRL :: [String] -> [String] -> [String] Source #

Addition for two list of Rational strings

addRL ["1/2", "1/2"] ["1/2", "1/2"]
["1/1", "1/1"]

divR :: String -> String -> String Source #

Division for Rational string

divR "1/2" "3/4"
"2/3"

divR' :: Integer -> Integer -> String Source #

invR :: String -> String Source #

subR :: String -> String -> String Source #

negR :: String -> String Source #

negList :: [String] -> [String] Source #

subRL :: [String] -> [String] -> [String] Source #

eightQueen :: [[Integer]] -> [(Integer, Integer)] -> Integer -> Integer -> [[Integer]] Source #

The algorithm uses backtrack.

  • Move top left corner to right and down
  • IF the move is valid THEN set (c, r) = 1, AND move one level down to (c+1, 0)
  • IF the move is not valid THEN move to (c, r+1)
  • Move (c,r) from left to right
  • IF (c,r) is valid move
  • THEN go down one level deep, => (c+1,0)
  • ELSE goto (c, r+1)
  • IF (c, r) is the right most position, AND IF (c,r) is valid move
  • THEN go down to (c+1, 0)
  • ELSE backtrack => take the previous valid move and reset (c,r)=0 AND check whether (c, r+1) is valid move.
  • IF (c, 0) is the bottom level,
  • THEN we are done!
let m1 = geneMat 10 Zero
pa $ eightQueen m1 [] 0 0

sumLeft :: [[Integer]] -> Integer -> Integer -> Integer Source #

sumRight :: [[Integer]] -> Integer -> Integer -> Integer Source #

rep2d :: (Integral n1, Integral n2) => [[a]] -> n1 -> n2 -> a -> [[a]] Source #

Replace element in position (c, r) with element n in 2d matrix. replace element, replace matrix, replace 2d array

replace1d :: Int -> (a -> a) -> [a] -> [a] Source #

Replace index p element with a function f

  replace1d 1 (const 2) [0, 0, 0] -- [0, 2, 0]
  

replace2d :: a -> (Int, Int) -> [[a]] -> [[a]] Source #

Replace index (c, r) element with a value v

   replace2d 1 (const 2) [0, 0, 0] -- [0, 2, 0]
   replace2d 5 (2, 1) [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
   [[1,1,1],[1,1,1],[1,5,1]]

  

diag1 :: Num a => [[a]] -> [a] Source #

get the diagonal of the matrix

uptri :: [[a]] -> [[a]] Source #

get upper triangle of matrix

leftDiagonal :: [[Integer]] -> Integer -> Integer -> [Integer] Source #

Collect all the elements from left diagonal of a matrix.

   mat = [
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 10]
         ]
   leftDiagonal mat 0 0
   [7, 5, 3]
   

rightDiagonal :: [[Integer]] -> Integer -> Integer -> [Integer] Source #

Collect all the elements from right diagonal of a matrix.

   mat = [
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 10]
         ]
   rightDiagonal mat 0 0
   [10, 5, 1]
   

reverseWord :: String -> String Source #

reverse words in string

rw :: String -> String Source #

tran :: [[a]] -> [[a]] Source #

Transpose matrix

[ begin{bmatrix} a & b c & d end{bmatrix} Rightarrow

begin{bmatrix} a & c b & d end{bmatrix}

]

  • NOTE: > map tail [[1], [2]] => [[], []]
   -- Fri 14 Oct 23:32:14 2022 
   -- The code DOES NOT work if the matrix:
   m = [[1, 2], [3]]
   
   tran::[[a]]->[[a]]
   tran [] = []
   tran ([]:_) = []
   tran x = (map head x):tran(map tail x)

    [1, 2, 3] : 
   x0 = [1, 2, 3] => [2, 3] => [3] => [] => []
   x1 = [4, 5, 6] => [5, 6] => [6] => [] => []
   x2 = [7, 8, 9] => [8, 9] => [9] => [] => []
                
                       1 :  <-  4 :    <-   7 : []

                       2 :  <-  5 :    <-   8 : [] 

                       3 :  <-  6 :    <-   9 : []


                       (9 ) <-  (8)  <-  (7)
                       (6)  <-  (5)  <-  (4)
                       (3)  <-  (2)  <-  (1) 

   

sortRow :: [[Integer]] -> [[Integer]] Source #

concat operator | pp $ "n=" +: fun x | (+:)::(Show a)=> String-> a -> String | (+:) s a = s ++ (show a)

sort row for list of list

upperTri :: [[Integer]] -> [[Integer]] Source #

Tranform the matrix to echolon/upper triangle form

KEY: upper triangle, matrix to upper triangle

  • Thu Jan 10 23:29:20 2019
  • gx Matrix to Upper Triangle
  • gf Userscatmyfilebitbucketmathupper_triangle.tex
  • Note: the determinant is different than the original matrix
  • Thu Jan 10 23:29:27 2019
  • Add lcm to the multiplier, make matrix dim from 6 to 13
  • TODO: fix the num overflow issue
  • Wednesday, 15 May 2024 11:45 PDT
  • Update: Use mergeSortC with compare function

upperTri' :: [[Rational]] -> [[Rational]] Source #

divI :: Fractional a => Integer -> Integer -> a Source #

Division is painful

   class (Num a)=> Fractional  a where
       (/):: a -> a -> a

   divI::(Fractional a)=>Integer -> Integer -> a

   class Num a where
       fromInteger::Integer -> a

   class (Num a, Ord a)=> Real a where


   fromIntegral::(Integral a, Num b) => a -> b
   fromIntegral = fromInteger . toInteger

   class (Real a, Enum)=> Integral a where   [1]
   toInteger(Real a, Enum a)=> a -> Integer  [2]
   fromInteger::(Num a)=>Integer -> a        [3]

   proof:
   [1] [2] [3] =>
   fromIntegral(Num a) => Integral -> a

   

inverse :: [[Double]] -> ([[Double]], [[String]]) Source #

Find the invertible matrix, return ([[]], [[]]) if the matrix is singular

  • The code does not check whether the matrix is singular or not
m <- randomMatrix 7 7  -- Int matrix
m' = (map . map) rf m  -- Double matrix
inverse m'

inverse::(Integral a, Fractional a, Real a, Show a, Eq a)=>[[a]]->([[a]], [[String]])
inverse::(Fractional a, Show a, Eq a)=>[[a]]->([[a]], [[String]])
  • TODO: Remove division

odds :: [a] -> [a] Source #

evens :: [a] -> [a] Source #

isInver :: (Fractional a, Ord a) => [[a]] -> Bool Source #

check whether a matrix is singular using QR_Decompoisition

isInvertible :: [[Integer]] -> Bool Source #

Multiply all the diagonal elements and check whether the product is zero or not

Algorithm:

  1. Find the upper triangle of m
  2. Multiply all the diagonal entries
  3. If their product is NOT zero then it is invertible, otherwise singular
   -- Test case:
   rm <- randomMatrix 100 100
   pp $ isInvertible rm
   

ident :: Integer -> [[Integer]] Source #

Generate n dimentional identity matrix

ident' :: Num a => Int -> [[a]] Source #

identS :: Integer -> [[String]] Source #

mlist :: Integer -> [Integer] -> [Integer] Source #

Integer multiply integer list

reverse $ 9 x [9, 8] = [8, 8, 2]

randomTemp :: IO String Source #

KEY: random temp file name, random tmp file

   randomTemp::IO String  -- randomTemp  =>  tmp223423423.txt
   

drawInteger :: Integer -> Integer -> IO Int Source #

KEY: random Integer

  • generate Integer from x to y random number

randomInteger :: Integer -> Integer -> IO Integer Source #

KEY: random Integer

randomDouble :: Int -> IO [Double] Source #

Generate list of Double in \( x \in [0 \dots n], n = 100 \)

[0.3, 0.4, 0]

Use randomFrac

randomFloat :: Int -> IO [Float] Source #

Generate list of Double in \( x \in [0 \dots n], n = 100 \)

[0.3, 0.4, 0]

Use randomFrac

randomFrac :: Fractional a => Int -> IO [a] Source #

Generate list of Fractional in \( x \in [0 \dots n], n = 100 \)

[0.3, 0.4, 0]

Num and Fractional are type class so you can NOT do [Num] or [Fractional]

Type class in Haskell is similar like interface in Java, but there are many differences

e.g. Integer implement Num => Integer is a concrete class e.g. Fractional inherits from Num => Fractional type class e.g. Float implement Fractional => Float is concrete class

randomList :: Integer -> IO [Integer] Source #

generate random of list Integer

randIntList :: Int -> (Int, Int) -> IO [Int] Source #

List of random Int

NOTE: Use randomIntegerList

   randomIntList::Integer ->(Integer, Integer) -> IO [Integer]
   randomIntList 0 _ = return []
   randomIntList n (s, e)= do
     r <- randomRIO (s, e)
     rs <- randomIntList (n - 1) (s, e)
     return (r:rs)
   

randomIntList :: Int -> (Int, Int) -> IO [Int] Source #

list of random Int

Same as randIntList SEE: randomIntegerList

randomIntegerList :: Integer -> (Integer, Integer) -> IO [Integer] Source #

randomMatrix :: Num a => Int -> Int -> IO [[a]] Source #

Generate \( m \times n \) random matrix.

geneRandMat :: Num a => (Int, Int) -> IO [[a]] Source #

Generate \( m \times n \) random matrix.

Same as randomMatrix

data Mat Source #

generate zero matrix

Constructors

Zero 
Id 

geneMat1ToN :: Num a => Integer -> [[a]] Source #

Generate a matrix from 1 to \( n \times n \) with dimention n

geneMat1ToN 2
[[1, 2],
 [3, 4]]

geneMatMN :: Integer -> Integer -> [[Integer]] Source #

Generate a matrix from 1 to \( m \times n \)

geneMat1ToN 2 3
[[1, 2, 3],
 [4, 5, 6]]

geneMat :: Integer -> Mat -> [[Integer]] Source #

generate zero or identity matrix |

help :: IO () Source #

cmd :: [String] -> IO () Source #

Add more doc here

compileHaskellToBin :: String -> String -> IO () Source #

Compile haskell code to $ffmybinmyHaskell => create symbol link $sym/sym | [file:myHaskell.hs] [sym:symbol] link name in $sym

strCompareIC :: String -> String -> Bool Source #

compare two string ignore cases

baseName :: FilePath -> String Source #

file base name

KEY: file extension, extension, basename, base name, file ext

baseName "/dog/file.txt" => "file"
takeFileName gives "file.ext"
takeDirectory gives "/directory"
takeExtension gives ".ext"
dropExtension gives "/directory/file"
takeBaseName gives "file"
"/directory" </> "file.ext".
"/directory/file" <.> "ext".
"/directory/file.txt" -<.> "ext".

dropExt :: FilePath -> String Source #

takeExt :: FilePath -> String Source #

takeName :: FilePath -> String Source #

take file name

See takeFileName

dropName :: FilePath -> FilePath Source #

drop file name from a path

See dropFileName

takeDir :: FilePath -> FilePath Source #

KEY: take directory only, same as dropName

See dropFileName dropName

  • It is the same name as in Python AronLib.py

dropNameT :: Text -> Text Source #

KEY: dropName TS.Text

dropExtT :: Text -> Text Source #

KEY: dropExt TS.Text

baseNameT :: Text -> Text Source #

Take the base name from dir in Text

takeFileNameT :: Text -> Text Source #

gotoCurrDir :: IO () Source #

Goto current directory, use in script

dirWalk :: FilePath -> (FilePath -> IO [String]) -> IO [String] Source #

KEY: Walking directory with filter or lambda function: upper case file extension

  • if there is file, then append it to list
  • otherwise, walking inside the dir
  • Pass lambda func: (FilePath -> IO [String]) as argument
   -- ls all files recursively
   let f fn = return [fn] in dirWalk f "/tmp"

   let f fname = takeExtension fname == ".png" then return [fname] else return []
   ls <- dirWalk f "/tmp"

   ls dirWalk (x - x == ".png") "/tmp"
   

dirWalkPathList :: (FilePath -> IO [String]) -> [FilePath] -> IO [String] Source #

KEY: walk through a list of dir

   p1 <- getEnv "m"
   p2 getEnv "www">= x -> return $ x / "pdf"
   dirWalkPathList (p -> let ex = takeExt p in ex == ".tex" ? return [x] $ return []) [p1, p2]
   

lsCurr :: String -> IO [String] Source #

KEY: list all files in dir, not recursive

lsDir :: FilePath -> IO [FilePath] Source #

getDirContent :: FilePath -> IO [FilePath] Source #

get directory contents

lsRegex :: String -> RegexStr -> IO [String] Source #

KEY: list file with regex match, see lsRegexFull, list file with filter, file filter

ff <- lsRegex (getEnv j) "\\.java$" -- list all java file
ff <- lsRegex (getEnv j) "^try"     -- list all file names starts with "try"

touch :: FilePath -> IO () Source #

KEY: touch a file

rm :: FilePath -> IO () Source #

remove file only, delete file

isDir :: FilePath -> IO Bool Source #

check whether a given file is a directory or symbol link to a directory

isDir p = doesDirectoryExist p

doesDirectoryExist

Also see isFile

dirExist :: FilePath -> IO Bool Source #

isFile :: FilePath -> IO Bool Source #

fExist :: FilePath -> IO Bool Source #

Check if file exist

NOTE: ONLY for file

fileExistA :: FilePath -> IO Bool Source #

doesExistF :: FilePath -> IO Bool Source #

fe :: FilePath -> IO Bool Source #

Same as fExist

rmDir :: FilePath -> IO () Source #

remove directory recursive

rm "dir"

pwd :: IO () Source #

Show current directory

cd :: FilePath -> IO () Source #

change dir

setCurrentDir :: FilePath -> IO () Source #

set current directory

en :: String -> IO String Source #

KEY: get environment variable, getEnv

SEE: getEnv

cc :: String -> IO () Source #

g :: IO () Source #

sleepSec :: Int -> IO () Source #

Sleep n seconds

sleepSec 2

sleep :: Int -> IO () Source #

sleep 1 sec = 100000

asplitPath :: FilePath -> [String] Source #

split path

asplitPath "/dot/cat/"
["dog", "cat"]

asplitPath "dot/cat/"
["dog", "cat"]

asplitPath "/dot/cat"
["dog", "cat"]

asplitPath "dot/cat"
["dog", "cat"]

splitPathA :: FilePath -> [FilePath] Source #

splitPathA from System.FilePath.Posix.splitPath

splitPathA "/dog/cat/"
["/", "dog/", "cat/"]

splitPathA "/dog/cat"
["/", "dog/", "cat"]

splitPathA "dog/cat"
["dog/", "cat"]

splitPathA "/"
["/"]

splitPathA "./"
["./"]

take' :: Integral n => n -> [a] -> [a] Source #

takeIf :: (a -> Bool) -> [a] -> [a] Source #

take all the elements if \( f(x) \) condition is true

  • It is same as takeWhile
takeIf (\x -> head x == '-') ["-a", "-b", "cc"]
["cc"]

dropIf :: (a -> Bool) -> [a] -> [a] Source #

drop all the elements if \( f(x) \) condition is true

  • It is same as dropWhile
dropIf (\x -> head x == '-') ["-a", "-b", "cc"]
["-a", "-b"]

dropIf (\x -> x == ' ') "   abc"
"abc"

takeN :: Integral n => n -> [a] -> [a] Source #

Integer type

drop' :: Integral n => n -> [a] -> [a] Source #

pathBase :: FilePath -> FilePath Source #

dropPath :: Integer -> String -> String Source #

dropPathEnd :: Integer -> String -> String Source #

takePath :: Integer -> String -> String Source #

takePathEnd :: Integer -> String -> String Source #

copyRename :: FilePath -> String -> IO () Source #

  1. copy FilePath to "/tmp" | 2. move the file back to dir with newName | copy file and rename it in the same dir

copyFileToDir :: FilePath -> FilePath -> IO () Source #

If source is valid file and dest is valid dir, otherwise error

createFile :: FilePath -> IO () Source #

create empty file

listDirFilter :: FilePath -> String -> IO [FilePath] Source #

List file with a Regex filter

SEE: Same as lsFileFilter

e.g. all html files >ls <- listDirFilter pa "\.html$"

lsFileFilter :: FilePath -> String -> IO [FilePath] Source #

List file with a Regex filter

SEE: Same as listDirFilter

e.g. all html files >ls <- lsFileFilter pa "\.html$"

copyDir :: FilePath -> FilePath -> IO () Source #

copy dir to other dir

mv :: FilePath -> FilePath -> IO () Source #

rename dir or file => dir or file

rename :: FilePath -> FilePath -> IO () Source #

mv file, rename file

renameAllFile :: String -> String -> IO () Source #

rename all files in path, e.g. s=XXX img.JPG => img_XXX.JPG

mvFiles :: String -> String -> IO () Source #

mvFile :: FilePath -> FilePath -> IO () Source #

mkdir :: FilePath -> IO () Source #

Create directory, make directory

mkdirp :: FilePath -> IO () Source #

sfilter :: String -> [String] -> [String] Source #

setCursorPos :: Int -> Int -> IO () Source #

KEY: set cursor position, move cursor

+ - - - - - > | | | - - + (nrow, ncol) | | V

       ESC[{line};{col}H
       ESC[{line};{col}f
             ↑ 
             + -> move cursor to line 
   

Escape code

setCursorPosStr :: Int -> Int -> String Source #

getTerminalSize :: IO (Int, Int) Source #

KEY: get terminal size, get screen size, get console size

getScreenSize :: IO (Int, Int) Source #

KEY: get screen size, get console size

sys :: String -> IO ExitCode Source #

Do not need to return IO [String] like run

If command error, process will not be terminated unless following error:

  • PermissionDenied
  • ResourceExhausted
  • UnsupportedOperation

More detail system

  • following will not work if use run
mapM (\x -> run "git lone " ++ x) listdir
  • change to
mapM (\x -> system "git clone " ++ x) listdir
system::String -> IO ExitCode
sys s = system s

Use inside GHCi or use :! cmd in GHCi

ExitCode See ExitCode document

  • Defines the exit codes that a program can return.
      data ExitCode
           = ExitSuccess -- ^ indicates successful termination;
           | ExitFailure Int
               -- ^ indicates program failure with an exit code.
               -- The exact interpretation of the code is
               -- operating-system dependent.  In particular, some values
               -- may be prohibited (e.g. 0 on a POSIX-compliant system).
           deriving (Eq, Ord, Read, Show, Generic)
   

typeChar :: Typeable a => a -> Bool Source #

The power of typeable

Data.Typeable

linesBS :: ByteString -> [ByteString] Source #

Check type of list of String

Data.Typeable

Check type of list of ByteString

Data.Typeable

Check type of String

Data.Typeable

linesSText :: Text -> [Text] Source #

KEY: lines for strict Text

Deprecated USE: linesST

linesST :: Text -> [Text] Source #

KEY: lines for strict Text

isHex :: Char -> Bool Source #

Check if char is hex.

  • Same as isHexDigit

isHexStr :: String -> Bool Source #

Does string contain hex only.

  • See isHexDigit

isDigitStr :: String -> Bool Source #

Does string contain digit only.

  • See isDigit

isLetterStr :: String -> Bool Source #

Does string contain letter only.

isLetterChar :: Char -> Bool Source #

Check letter

  • It is same as isLetter

isDigitChar :: Char -> Bool Source #

Check digit

  • It is same as isDigit

run' :: String -> IO () Source #

run shell cmd, send output to std_out

  • run' does not wait for the process to finish

run :: String -> IO [String] Source #

Run shell cmd, capture std_out

  • some issue with waitForProcess
  • it might be deadlock, e.g. run "ps aux"
  • man ps -x => still d't underand why the process is not terminated
  • top command issue => process is not terminated
  • 1. Change it to System, there is issue with the function
  • TODO: fix it:o
  • There is still some issues, use system instead, Tue Jan 28 11:46:22 2020

runCmd :: String -> IO [String] Source #

runShell :: String -> IO (ExitCode, Text, Text) Source #

Run shell command with Turtle lib, shell command (ExitCode, stdoutx, stderr)

   (e2, so, si2) <- runShellcmd
   if e2 /= ExitSuccess then let rcode = ReplyCode{rcmd="", rerror = si2, stdoutx=si2}
                                 replyJson = toSBS $ DA.encode $ rcode
                             in response $ responseNothingBS replyJson
   else do
       pp so
       let replyCode = ReplyCode{rcmd="", rerror="", stdoutx= so}
       let replyJson = toSBS $ DA.encode $ replyCode
       response $ responseNothingBS replyJson
   

See runSh, runRawCmd, run

runShell is same as runSh, cmd is String

Turtle shellStrictWithErr

   shellStrictWithErr
       :: MonadIO io
       => Text
       -- ^ Command line
       -> Shell ByteString
       -- ^ Chunks of bytes written to process input
       -> io (ExitCode, ByteString, ByteString)
       -- ^ (Exit code, stdoutx, stderr)
   shellStrictWithErr cmdline =
       systemStrictWithErr (Process.shell (Data.Text.unpack cmdline))
   

df :: Fractional a => (a -> a) -> a -> a Source #

Differentiate on \(f(x)\)

Find the first derivative at \( x \) on function \( (a \rightarrow a)) \)

x = 1.0
df (\x ->x^2) x
2.0

\( f(x) = x^2 \Rightarrow f'(x) = 2x \Rightarrow f'(1.0) = 2.0 \)

First derivative on f or slop of f at point x

\( f'(x) = \lim_{h \rightarrow 0} \frac{f(x + h) - f(x)}{h} \)

tangent :: Fractional a => (a -> a) -> a -> a -> a Source #

Compute the tangent equation at point \((x_0, f(x_0))\) for function \( f \)

Find a tangent equation at \( x_0 = 1.0 \) in \( f(x) = x^2 \)

tanglent (\x -> x^2) 0 1

Tangent equation:

\( f'(x) = \frac{y - y_0}{x - x_0} \)

\( y = f'(x_0)(x - x_0) + y_0 \)

e.g.

\( f(x) = x^2 \)

\( \Rightarrow f'(x_0) = 2x_0 \)

\( f (x) = x^2 \) where \( x = x_0 \)

\( y = 2x_0(x - x_0) + y_0 \) where \( y_0 = f (x_0) \)

\( f' (x_0) = \frac{y - y_0}{x - x0} \)

\( y = f'(x_0)(x - x_0) + y_0 \)

tangentVec :: Fractional a => (a -> a) -> a -> a -> (a, a) Source #

Compute the tangent vector at point (x0, f x0)

prime :: [Integer] Source #

Generate prime number with Sieve Algorithm

oneRoot :: (Double -> Double) -> Double -> Double -> Double -> Maybe Double Source #

Find root for any polynomial function

  • Partition the interval [x0, xn] into list = [x0, x1) [x1, x2) [x2, x3) ..[x(n-1), xn)
  • Concat [xn, xn] with the list since the left boundary is checked only
  • Note: f(xn) might be zero, we need to check the xn boundary
  • TODO: need to check f(xn), DONE, concat [xn, xn] to the list

Good test cases:

\( f(x) = x^2 - 4 \quad x \in [-2, 2] \)

\( f(x) = x^5 -4x^4 + 0.1x^3 + 4x^2 - 0.5 \quad x \in [-4, 4] \Rightarrow \) 5 solutions

  • limitation:
  • if each subinterval contains two or more values, then ONLY one value can be found
  • subinterval can be adjusted in arbitrary small
[0, 2] (2-0)/2 = [0, 1, 2] = [0, 1) ∪ [1, 2) ∪ [2, 2]

rootList :: (Double -> Double) -> Double -> Double -> Double -> Integer -> [Maybe Double] Source #

Find all the roots for a given close interval: [1, 2], 1 or 2 might be the root |

outer :: Num a => [a] -> [a] -> [[a]] Source #

outer product = col ⊗ row

  • Sun O21 00:00:05 2018

out :: (a -> b -> c) -> [a] -> [b] -> [[c]] Source #

generic outer product or sth, inspired by APL

Update: Switch row and column to similar to 2d array or APL outer product

   out (x y -> x == y ? 1 $ 0) [1, 2, 3] [1 2]

      | 1 | 2 |
   -----------+
   1  | x | 0 |
   -----------+
   2  | 0 | x |
   -----------+
   3  | 0 | 0 |
   -----------+

   -- identity matrix
   > m = out (a b -> a == b ? 1 $ 0) [1..4] [1..4]
   > pmat m
   1 0 0 0
   0 1 0 0
   0 0 1 0
   0 0 0 1
   

outerSum :: Num a => [a] -> [a] -> [[a]] Source #

outer sum

outerMod :: Integral a => [a] -> [a] -> [[a]] Source #

outer modulus = col

outerStr :: (a -> a -> a) -> [[a]] -> [[a]] -> [[a]] Source #

KEY: outer product for string

DATE: Wednesday, 28 February 2024 12:10 PST

 > v0 = [
         ["x"],
         ["y"]
        ]
 > h0 = [["x", "y"]]
 > 
 > printMat $ outerStr (a b -> a ++ b) v0 h0
 > "xx" "xy"
 > "yx" "yy"
 

(⦶) :: Integral a => [a] -> [a] -> [[a]] Source #

KEY: symbol operator, unicode operator

(‖) :: Integer -> Integer -> Integer Source #

vcol :: [[a]] -> Int -> [[a]] Source #

Get column

Same as getColumn

   m
   [[1, 2]
    [3, 4]]

   tran m
   [[1, 3]
    [2, 4]]

   vrow [[1, 3]    n
         [2, 4]]
   

getColumn :: [[a]] -> Int -> [[a]] Source #

get column

Same as vcol

vrow :: [[a]] -> Int -> [[a]] Source #

get row

Same as getRow

getRow :: [[a]] -> Int -> [[a]] Source #

get row

Same as vrow

zipWith2 :: Num a => (a -> a -> a) -> [[a]] -> [[a]] -> [[a]] Source #

zipWith in two dimensions, zipWith matrix

   zipWith2(Num a) => (a -> a -> a) ->[[a]] ->[[a]] -> [[a]]
   zipWith2 f a b = [ zipWith f ra rb | (ra, rb) <- zip a b]

   zipWith2::(Num a)=>(a ->a ->a)->[[a]]->[[a]]->[[a]]
   zipWith2 f m1 m2 = zipWith(x y -> zipWith(x1 y1 -> f x1 y1) x y) m1 m2
   

data XNode Source #

Constructors

XNode (HashMap Char XNode) Bool 

Instances

Instances details
Eq XNode Source # 
Instance details

Defined in AronModule

Methods

(==) :: XNode -> XNode -> Bool

(/=) :: XNode -> XNode -> Bool

Show XNode Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> XNode -> ShowS

show :: XNode -> String

showList :: [XNode] -> ShowS

insertTries :: String -> XNode -> XNode Source #

insert operation for Tries data structure

let xn = insertTries "a" (XNode M.empty False)
let xxn = insertTries"ab" xn
pp $ "containsTries=" <<< (containsTries "a" xxn == True)
pp $ "containsTries=" <<< (containsTries "ab" xxn == True)
  1. If String is empty return XNode is the end of a word
  2. If x points to Nothing(x is not on the Tries), then recur to cx
  3. If x points to an XNode, then recur to cx

insertTriesList :: [String] -> XNode -> XNode Source #

Insert list of strings to Tries, see insertTries

containsTries :: String -> XNode -> Bool Source #

contain operation for Tries data structure

let xn = insertTries "a" (XNode M.empty False)
let xxn = insertTries"ab" xn
pp $ "containsTries=" <<< (containsTries "a" xxn == True)
pp $ "containsTries=" <<< (containsTries "ab" xxn == True)

data Tree a Source #

Most functions are related to Binary Search Tree

  • Thu Nov 8 21:24:37 2018

Constructors

Empty 
Node a (Tree a) (Tree a) 

Instances

Instances details
Eq a => Eq (Tree a) Source # 
Instance details

Defined in AronModule

Methods

(==) :: Tree a -> Tree a -> Bool

(/=) :: Tree a -> Tree a -> Bool

Show a => Show (Tree a) Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> Tree a -> ShowS

show :: Tree a -> String

showList :: [Tree a] -> ShowS

insertNode :: Ord a => Tree a -> a -> Tree a Source #

insertFromList :: Ord a => Tree a -> [a] -> Tree a Source #

Insert a list of element into a Tree

data LeafyTree a Source #

Constructors

Branch [LeafyTree a] 
Leaf a 

Instances

Instances details
Foldable LeafyTree Source #

foldMap combine foldable monoid type to a monoid

Monoid and Foldable

   class Foldable t where
       foldMap ::(Monoid m) => (a -> m) -> t m -> m

   a -> m, a function converts any type to monoid type

   -- what is the identity?
   class Semigroup a => Monoid a where
       mempty :: a
       mconcat :: [a] -> a

   main = do
           let tree1 = Leaf "a"
           let s = foldMap id tree1
           pp s
           let tree2 = Branch [Leaf "a"]
           pp $ foldMap id tree2
           let tree3 = Branch [Leaf "a", Leaf "b", Branch [Leaf "a2", Leaf "b2"]]
           pp $ foldMap id tree3
           pp $ foldMap (Sum . length) tree3
   
Instance details

Defined in AronModule

Methods

fold :: Monoid m => LeafyTree m -> m

foldMap :: Monoid m => (a -> m) -> LeafyTree a -> m

foldMap' :: Monoid m => (a -> m) -> LeafyTree a -> m

foldr :: (a -> b -> b) -> b -> LeafyTree a -> b

foldr' :: (a -> b -> b) -> b -> LeafyTree a -> b

foldl :: (b -> a -> b) -> b -> LeafyTree a -> b

foldl' :: (b -> a -> b) -> b -> LeafyTree a -> b

foldr1 :: (a -> a -> a) -> LeafyTree a -> a

foldl1 :: (a -> a -> a) -> LeafyTree a -> a

toList :: LeafyTree a -> [a]

null :: LeafyTree a -> Bool

length :: LeafyTree a -> Int

elem :: Eq a => a -> LeafyTree a -> Bool

maximum :: Ord a => LeafyTree a -> a

minimum :: Ord a => LeafyTree a -> a

sum :: Num a => LeafyTree a -> a

product :: Num a => LeafyTree a -> a

inorder :: Tree a -> [a] Source #

Inorder insection

maxlen :: Tree a -> Integer Source #

Maximum number of levels of a Tree

head' :: [a] -> a Source #

Better head

  • TODO: Use better error message

isBST :: Ord a => Tree a -> Bool Source #

check whether a Tree is Binary tree

defintion of BST

  • Null is BST
  • Left subtree is BST
  • Right subtree is BST
  • minimum of left subtree is less than parent node
  • maximum of right subtree is greater than parent node

binsert :: Tree Integer -> Tree Integer -> Tree Integer Source #

Binary tree insection

isSym :: Tree a -> Bool Source #

Check whether a binary tree is symmetric or not

Rename sym to isSym

lca :: Eq a => Tree a -> a -> a -> Maybe a Source #

Lease common ancestor

  • assume two nodes are in the tree
  • if two nodes are in the same path then the top node will be LCA

buildTree :: [Char] -> [Char] -> Tree Char Source #

Build binary tree from preorder and inorder

  • Get the root from preorder , the first element is the header
  • Get the leftsubtree and rightsubtree from inorder with the root from previous step
  • Partition the preorder and inorder with previous two steps
  • Use smaller preorder and inorder on the left subtree and right subtree to do recursion calls
       2
     1    3 => 1 2 3   inorder

       2
     1    3 => 2 1 3   preorder
   

Build Tree from preorder and inorder

Serialize and Deserialize Binary Tree with marker '#'

anagram :: String -> [String] -> [String] Source #

Find all anagrams from a list of strings

anagram "dog" ["god", "cat", "ogd"]
["god", "ogd"]

redisExtractAronModule :: String -> [String] -> [([String], Integer, [String])] Source #

Extract AronModule.hs functions out

gx file://Userscatmyfilebitbucketstackprojectjupyterlab/readAronModule.html

Example

   [(
       [ "AronModule.f"
       , "AronModule.fu"
       , "AronModule.fun"
       , "AronModule.funx"
       , "AronModule.n"
       , "AronModule.nx"
       , "AronModule.u"
       , "AronModule.un"
       , "AronModule.unx"
       , "AronModule.x"
       ]
   , 30003
   , [ "funx::(Integral a, Num b) => a -> b" ]
   )]
   

redisExtractJavaMethod :: String -> [String] -> [([String], Integer, [String])] Source #

KEY: Parse Java method name, extract method name and form a list [([String], Integer, [String])]

File format: jname = "UserscatmyfilebitbucketjavalibAron.java"

The list can be used in Redis Server

["line1", "line2"] -> [([k0, k1], 1, ["line1"])]
   ["line1", "line2"] -> [([k0, k1], 1, ["line1"])]

   Logger logInit(String className, String fName){}

   (
       [ Aron.I
       , Aron.In
       , Aron.Ini
       , Aron.Init
       , "Aron.g"
       , "Aron.gI"
       , "Aron.gIn"
       , "Aron.gIni"
       , "Aron.gInit"
       , "Aron.i"
       , "Aron.it"
       , "Aron.l"
       , "Aron.lo"
       , "Aron.log"
       , "Aron.logI"
       , "Aron.logIn"
       , "Aron.logIni"
       , "Aron.logInit"
       , "Aron.n"
       , "Aron.ni"
       , "Aron.nit"
       , "Aron.o"
       , "Aron.og"
       , "Aron.ogI"
       , "Aron.ogIn"
       , "Aron.ogIni"
       , "Aron.ogInit"
       , "Aron.t"
       ]
   , 10002
   , [ "Logger logInit(String className, String fName){" ]
   )
   

redisExtractJavaMethodWithPackage :: String -> [String] -> [([String], Integer, [String])] Source #

KEY: Parse Java method name, extract method name and form a list [([String], Integer, [String])]

File format: jname = "UserscatmyfilebitbucketjavalibAron.java"

The list can be used in Redis Server

["line1", "line2"] -> [([k0, k1], 1, ["line1"])]

redisExtractSnippet :: [([String], [String])] -> [([String], Integer, [String])] Source #

KEY: extract code block from Userscatmyfilebitbucketsnippetssnippet.hs

gx file://Userscatmyfilebitbucketstackprojectjupyterlab/redisSnippet.html

snippet_tmp.hs

   cab
   c      -> cab dog
   ca     -> cab dog
   cab    -> cab dog

   c   -> 100
   ca  -> 100
   cab -> 100

   100 -> cab dog
   

textArea :: Integer -> Integer -> String -> String Source #

Html textarea textArea row col string textArea 4 5 "dog"

htmlTable :: [[String]] -> [String] Source #

Generate html table from list of string

  • gx file://Userscatmyfilebitbucketstackprojectjupyterlab/htmlTable.html
   table
   trtd a1 /td td a2 /td /tr
   trtd b1 /td  td b2 /td/tr
   /table

   [
    "table"
    "trtd a1 /td td a2 /td /tr"
    "trtd b1 /td  td b2 /td/tr"
    "/table"
   ]

   

htmlTableRowCol :: Int -> Int -> [String] Source #

Generate r row and c col table

htmlTableRowColSText :: Integer -> Integer -> [Text] Source #

Generate r row and c col table

getOS :: IO String Source #

Find the name of OS from environment_variable OSTYPE

  • Some OS might not set the environment variable name: OSTYPE
  • OSTYPE might be set manually in file such as .profile
  • Currently it supports MacOS and FreeBSD
  • MacOS = "darwin"
  • FreeBSD = "freebsd"

data ShellHistory Source #

Project HOMEmyfilebitbucketstackprojectInsectHistoryToSqlite3

Constructors

ShellHistory 

Fields

Instances

Instances details
Eq ShellHistory Source # 
Instance details

Defined in AronModule

Methods

(==) :: ShellHistory -> ShellHistory -> Bool

(/=) :: ShellHistory -> ShellHistory -> Bool

Read ShellHistory Source # 
Instance details

Defined in AronModule

Methods

readsPrec :: Int -> ReadS ShellHistory

readList :: ReadS [ShellHistory]

readPrec :: ReadPrec ShellHistory

readListPrec :: ReadPrec [ShellHistory]

Show ShellHistory Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> ShellHistory -> ShowS

show :: ShellHistory -> String

showList :: [ShellHistory] -> ShowS

FromRow ShellHistory Source #

import Database.SQLite.Simple.FromRow | two fields: shId, shcmd

Instance details

Defined in AronModule

Methods

fromRow :: RowParser ShellHistory

ToRow ShellHistory Source #

import Database.SQLite.Simple.ToRow

Instance details

Defined in AronModule

Methods

toRow :: ShellHistory -> [SQLData]

insertShellHistory :: String -> String -> IO () Source #

Insert dot_bash_history to sqlite3

KEY: insert history, history sqlite3, insert .bash_history to sqlite3

  • Need to create symlink to ~/.bash_history

home <- getEnv HOME hisFile = home / "myfilebitbucketshelldot_bash_history"

  1. drop ShellHistory table
  2. create table ShellHistory
  3. read dot_bash_history
  4. insert all cmds to ShellHistory
   home <- getEnv HOME
   let dbfile = home / "myfilebitbucketdatabase/ShellHistory.db"
   >sqlite3 dbfile
   >.table
   >SELECT * FROM ShellHistory
   
   data Query = Query{fromQuery::TS.Text}

   insert_table = Query {fromQuery = toSText "INSERT INTO ShellHistory (shcmd) VALUES (?)"}
   

UPDATE: Wednesday, 17 November 2021 15:41 PST hisdb = "myfilebitbucketdatabase/ShellHistory.db" bashHis = "myfilebitbucketshell/dot_bash_history"

queryShellHistory :: String -> IO [String] Source #

filter out lines in history file

  hisdb  = "myfilebitbucketdatabase/ShellHistory.db"
  bashHis = "myfilebitbucketshell/dot_bash_history"
  

appNotify :: String -> IO () Source #

Apple notify shell script, macos script,

redisGet :: String -> IO (Maybe String) Source #

Redis get value

  • Redis default Connection Info
   defaultConnectInfo

   connectHost           = "localhost"
   connectPort           = PortNumber 6379 -- Redis default port
   connectAuth           = Nothing         -- No password
   connectDatabase       = 0               -- SELECT database 0
   connectMaxConnections = 50              -- Up to 50 connections
   connectMaxIdleTime    = 30              -- Keep open for 30 seconds
   

Redis_Database

Get Value from a key

It uses Default Connection

See redisSet

   GHCi:
   redisSet "key1" "value1"
   redisGet "key1"
   

redisGetConn :: Connection -> String -> IO (Maybe String) Source #

Get value from Redis db

  • Redis default Connection Info
   defaultConnectInfo

   connectHost           = "localhost"
   connectPort           = PortNumber 6379 -- Redis default port
   connectAuth           = Nothing         -- No password
   connectDatabase       = 0               -- SELECT database 0
   connectMaxConnections = 50              -- Up to 50 connections
   connectMaxIdleTime    = 30              -- Keep open for 30 seconds
   

See: redisGet and redisSet

redisSet :: String -> String -> IO () Source #

Redis set key value

Set key and value in Redis

It uses Default Connection

See redisGet

   GHCi:
   redisSet "key1" "value1"
   redisGet "key1"
   

redisSetConn :: Connection -> String -> String -> IO () Source #

redisSetConnSByteString :: Connection -> ByteString -> ByteString -> IO () Source #

redisConnectDefault :: IO Connection Source #

redisDisconnect :: Connection -> IO () Source #

KEY: redis disconnect, destroy resource, destroy connection, destroy redis

  conn <- redisConnectDefault
  RED.disconnect conn
  

checkCSSColorFormat :: Text -> Bool Source #

check CSS color format,

"#334455"  => valid
"#333"     => valid
"#1234567" => not valid

cssToStr :: (String, String) -> String Source #

concatStyle :: [(String, String)] -> String Source #

concat style fields: ("color", "red") => "color:red;"

fun444 :: Int -> Int Source #

fun555 :: Int -> Int Source #

pf :: PrintfType r => String -> r Source #

C style printf, string format

  • import Text.Prinf
    printf::PrintfType => r -> s

    printf "%.2f" 3.0
    3.00
    let n = 3::Int
    let f = rf n
    printf "%.2f, %.2f" f f

    let name = "dog"
    let weight = 20
    printf "(%s)=(%d)"
    "(dog)=(20)"

    let s = pf "%.2f" 3.1415
    pp s

    c      character               Integral
    d      decimal                 Integral
    o      octal                   Integral
    x      hexadecimal             Integral
    X      hexadecimal             Integral
    b      binary                  Integral
    u      unsigned decimal        Integral
    f      floating point          RealFloat
    F      floating point          RealFloat
    g      general format float    RealFloat
    G      general format float    RealFloat
    e      exponent format float   RealFloat
    E      exponent format float   RealFloat
    s      string                  String
    v      default format          any type
   

Printf

p :: Show s => s -> IO () Source #

print output, similar Print.java

pp2 :: (MonadIO m, Show a) => a -> m () Source #

fl :: IO () Source #

pw :: Show s => String -> s -> IO () Source #

line with color

psTab 5 (color Green (replicate 80 -))

fpp :: Show s => String -> s -> IO () Source #

fw :: String -> IO () Source #

ff :: Show var => String -> var -> IO () Source #

(?) :: Bool -> a -> a -> a infix 1 Source #

KEY: ternary operator like c++, if else

   let x = 3 in x > 3 ? "> 3" $ " < 3"
   

(<<<) :: Show a => String -> a -> String infixl 1 Source #

readConfig :: FilePath -> IO (HashMap String (HashMap String String)) Source #

Parse a text file and return HashMap String (HashMap String String)

  • OS specific config file

Config file could have the following format. @

os = macOS

↑ + → os has to be in the file.

host = localhost
path = /usr/home/user
os = linux

↑ + → os has to be in the file.

host = myhost
path = /usr/home/user

return

HashMap String (HashMap String String) = [("macOS", (fromList [("host", "localhost"), ("path", "/usr/home/user")))]
   * Update Fri Mar 13 21:52:36 2020
   * Add skip comment code
   * Saturday, 24 September 2022 21:13 PDT
   * Update String with double quotes

   
  • - comment
  • - gf $bhaskellwebapp2config.txt host = localhost @

Use createConfigMap instead

concatFile :: FilePath -> FilePath -> FilePath -> IO () Source #

concat two files to a thrid file

extractNumFromStr :: String -> Integer Source #

KEY: extract a first number from a string.

strToIntegerMaybe :: String -> Maybe Integer Source #

KEY: convert String to Maybe Integer

strToStrictByteString "12" => Just 12
strToStrictByteString "01" => Just 1
strToStrictByteString "00" => Just 0
strToStrictByteString " 1" => Nothing
strToStrictByteString "1a" => Nothing

gcdList :: [Integer] -> Integer Source #

commentLine :: String -> String -> String Source #

commentCode :: String -> [String] -> [String] Source #

takeBetweenExc :: String -> String -> [String] -> [String] Source #

KEY: take strings between beg and end

NOTE: take the First pair of ONLY @ takeBetweenExc "beg" "end" ["a", BEG, "c", END "d"] => ["c"]

takeBetweenExc "beg" "end" ["a", BEG, "c", END "d", BEG, "k", END] => ["c"] @

takeIndexBetweenInc :: (Int, Int) -> [a] -> [a] Source #

KEY: take elements between both indices

   takeIndexBetweenInc (3, 4) [0..10]
   => [3, 4]
   

maxList :: [Int] -> Int Source #

printBox :: Integer -> [String] -> IO () Source #

KEY: console ansi box, console textbox, ansi textbox, escape code, ascii code

See Ansi_Box_Drawing

   -- BEG
   -- KEY: ansi color, console color
   import Rainbow
   import System.Console.Pretty (Color (..), Style (..), bgColor, color, style, supportsPretty)
   import qualified System.Console.ANSI as AN
   -- END

   -- move 4 tabs to the right
   printBox 4 ["dog", "cat"]

        ⌜-------⌝
        |dog    |
        |cat    |
        ⌞-------⌟
   

printBoxColor :: Color -> Integer -> [String] -> IO () Source #

KEY: console ansi box, console textbox, ansi textbox

See Ansi_Box_Drawing

printBox with Color

   data System.Console.Pretty.Color
     = Black
     | Red
     | Green
     | Yellow
     | Blue
     | Magenta
     | Cyan
     | White
     | Default

   -- Defined in ‘System.Console.Pretty’
   instance [safe] Enum System.Console.Pretty.Color
   -- Defined in ‘System.Console.Pretty’


   -- BEG
   -- KEY: ansi color, console color
   import Rainbow
   import System.Console.Pretty (Color (..), Style (..), bgColor, color, style, supportsPretty)
   import qualified System.Console.ANSI as AN
   -- END

   -- move 4 tabs to the right
   printBox 4 ["dog", "cat"]

        ⌜-------⌝
        |dog    |
        |cat    |
        ⌞-------⌟
   

printBoxColor2 :: Integer -> Integer -> [String] -> IO () Source #

splitWhileStr :: (Char -> Bool) -> String -> (String, String) Source #

getLineFlush :: IO String Source #

replaceFileLineNoRegex :: FilePath -> String -> String -> IO () Source #

KEY: replace line with NO Regex

NOTE: "a & b \" has issue use regex replace

   file: x.x
   line 1
   latexcode_replace123
   line 2

   replaceLineNoRegex "tmpx.x" "latexcode_replace123" "a & b \"
   

replaceLineNoRegexListTuple :: [String] -> [(String, String)] -> [String] Source #

runSh :: Text -> IO (ExitCode, Text, Text) Source #

Run shell command with Turtle lib

See runShell

   (e2, so, si2) <- runSh $ toSText cmd
   if e2 /= ExitSuccess then let rcode = ReplyCode{rcmd="", rerror = si2, stdout=si2}
                                 replyJson = toSBS $ DA.encode $ rcode
                             in response $ responseNothingBS replyJson
   else do
       pp so
       let replyCode = ReplyCode{rcmd="", rerror="", stdout= so}
       let replyJson = toSBS $ DA.encode $ replyCode
       response $ responseNothingBS replyJson
   

Turtle shellStrictWithErr

   shellStrictWithErr
       :: MonadIO io
       => Text
       -- ^ Command line
       -> Shell ByteString
       -- ^ Chunks of bytes written to process input
       -> io (ExitCode, ByteString, ByteString)
       -- ^ (Exit code, stdout, stderr)
   shellStrictWithErr cmdline =
       systemStrictWithErr (Process.shell (Data.Text.unpack cmdline))
   

SEE: runShStr

runShStr :: String -> IO (ExitCode, String, String) Source #

KEY: run String command

  (ExitCode, out, err) <- runShStr "grep error tmpa.x"
  if ExitCode == ExitSuccess then putStrLn out else putStrLn err
  

SEE: runSh

clear :: IO () Source #

KEY: clear screen, clear terminal

pp :: Show s => s -> IO () Source #

runRawCmd :: String -> [String] -> IO [String] Source #

Prevent shell expand argument variable, e.g '$1', '$2'

  • KEY: shell not expand, shell literal, shell expand, shell escape variable, shell raw variable
    runRawCmd "write_to_shell" ["cat $1 $2"] --  cat $1 $2
   
  • Usage runRawCmd "ls" [] runRawCmd "ls" ["-la"]
  • waitForProcess to finish or exitFailure

ls :: IO () Source #

Try to replace as many as shell command as possible

  • shell ls command
  • See how far I can go
  • write many shell commands as possible
  • try to emulate shell commands
  • Sat Feb 1 23:40:55 2020

getPwd :: IO FilePath Source #

get current dir

getpwd :: IO FilePath Source #

get current dir

getPwd getCurrentDirectory

lsFile :: String -> IO [String] Source #

KEY: list file

  • Sat Feb 1 22:25:09 2020
  • FOUND ERROR: don't use the function, it creates zombie process
  • Sun Feb 2 13:12:01 2020
  • Fixed ERROR with runRawCmd

lsStr :: String -> IO [String] Source #

KEY: list file

  • Wed 28 Sep 21:24:18 2022

drawInt :: Int -> Int -> IO Int Source #

KEY: random Integer

  • Generate Int from x to y random number
   System.Random randomR :: (Random a, RandomGen g) => (a, a) -> g -> (a, g)
                                                                 ↑        ↑ 
                                                 + -  - - - - -  +        |
                                                 |             + - - -  - + 
                                                 |             | 
   System.Random getStdRandom :: MonadIO m => (StdGen -> (a, StdGen)) -> m a
   

lsFileFull :: String -> IO [String] Source #

KEY: list of FULL path files

lsFileFull "."
lsFileFull "/dog/cat"
  • Sat Feb 1 22:25:09 2020
  • FOUND ERROR: don't use the function, it creates zombie process
  • Sat Feb 1 23:33:12 2020
  • Fixed ERROR with runRawCmd
  • NOTE: list of full path
  • See lsFileFull => list full path

type RegexStr = String Source #

lsRegexFull :: String -> RegexStr -> IO [String] Source #

KEY: list full path with regex match, see lsRegex, list file with filter, file filter, file path with regex

lsRegexFull "." "\\.hs$"
lsRegexFull "/tmp" "\\.hs$"

lsFullRegex :: String -> RegexStr -> IO [String] Source #

Deprecated, use lsRegexFull

list full path with regex match

lsRegexFull "." "\\.hs"
lsRegexFull "/tmp" "\\.hs"

randomInt :: Int -> Int -> IO Int Source #

KEY: random Int

writeFileStr :: FilePath -> String -> IO () Source #

KEY: write a string to file

Use writeFile

writeFile::FilePath -> String -> IO()
writeFileStr = writeFile

writeFileOver :: FilePath -> String -> IO () Source #

Overwrite a file

writeFileList :: FilePath -> [String] -> IO () Source #

Better name: write a list to file

c2w_ :: Char -> Word8 Source #

Char to word8, char to int

  • readFile to ByteString
ls <- BS.readFile "/tmp/b.x"
lsBS = BS.split (c2w_ '\n') ls

intToString :: Integer -> String Source #

Convert Integer to string, int to str

>>> intToString 123
"123"

integerToString :: Integer -> String Source #

Convert Integer to string, int to str

>>> integerToString 123
"123"

integerToInt :: Integer -> Int Source #

Convert Integer to Int

Use fromInteger

intToCharDigit :: Int -> Char Source #

Int to digit char

     intToCharDigit 3  => '3'
     intToCharDigit 31 => Exception
   

Use intToDigit

extractStr :: (Integer, Integer) -> String -> String Source #

Extract a string from a string

See extract or Extract

class Extract source where
  before :: Int -> source -> source
  after  :: Int -> source -> source
  extract:: (Int, Int) -> source -> source

instance Extract String where
  extract :: (Int, Int) -> String -> String

extractStr::(index, len) -> String  -> String

integerToBinary :: Integer -> String Source #

charToDecimal :: Char -> Int Source #

charToDecimalInteger :: Char -> Integer Source #

charToIntX :: Char -> Int Source #

deprecated

NOTE: confusing naming Monday, 24 July 2023 12:09 PDT NOTE: DO NOT USE any more

deprecated

NOTE: confusing naming Monday, 24 July 2023 12:09 PDT NOTE: DO NOT USE any more

char0to9ToInt :: Char -> Int Source #

KEY: char digit to Int

integerToCharDigit :: Integer -> Char Source #

deprecated

stringToInteger :: String -> Integer Source #

Convert string to Integer, str to int, str to num, string to num

stringToInteger "123"
123

stringToInteger "a"
error

strToInteger :: String -> Integer Source #

String to Integer

alias of stringToInteger

stringToInt :: String -> Int Source #

KEY: Convert string to Integer, str to int, str to num, string to num, string to int

stringToInt "123"
123

stringToInt "a"
error
  • Read is a typeclass all the instance need to implement following method @ strToInteger :: String -> Integer strToInteger s = foldr (+) zipWith(x y -> (digitToInt x) * 10^10) (reverse s) [0..]

    class Read a where read :: String -> a

instance Read Integer where read s = strToInteger s @

read "123"::Int

Text.Read

strToInt :: String -> Int Source #

String to Int, str to Int

Same as stringToInt

pre :: (MonadIO m, Show a) => a -> m () Source #

KEY: pretty print

       print tuple, print list, print two dimensions list
       print record
       print list of tuple
       use pPrint
   
[("a", "b"), ("c", "d")]

Simple

prex :: (MonadIO m, Show a) => a -> m () Source #

prel :: Show a => [[a]] -> IO () Source #

print 2d list

readFileLatin1ToList :: FilePath -> IO [String] Source #

use latin1 encoding to avoid error when reading non ASCII characters

URL: https://hackage.haskell.org/package/base-4.18.0.0/docs/System-IO.html#t:TextEncoding

FIXED: bug, read file contains unicode does not work properly. @ -- Monday, 24 July 2023 15:47 PDT -- DO NOT use latin1

latin1 :: TextEncoding utf8 :: TextEncoding

Change: hSetEncoding latin1 To hSetEncoding utf8 @

readFileList :: FilePath -> IO [String] Source #

Read a file and return a String

readFileStr :: FilePath -> IO String Source #

readFileDouble :: FilePath -> IO [[Double]] Source #

read file data, covert each line to [Double] => [[Double]]

   tmpx.x
   3.14 2.0
   1.0  2.0

   ls <- readFileDouble "tmpx.x"

   [[3.14, 2.0], 
    [1.0,  2.0]]
   

readFileFloat :: FilePath -> IO [[Float]] Source #

read file data, covert each line to [Float] => [[Float]]

   tmpx.x
   3.14 2.0
   1.0  2.0

   ls <- readFileFloat "tmpx.x"

   [[3.14, 2.0], 
    [1.0,  2.0]]
   

readFileInt :: FilePath -> IO [[Int]] Source #

read file data, covert each line to [Int] => [[Int]]

   tmpx.x
   3  2
   1  2

   ls <- readFileInt "tmpx.x"

   [[3, 2], 
    [1, 2]]
   

timeNowPico :: IO Integer Source #

(round . (* 10^12)) <$> getPOSIXTime

timeNowNano :: IO Integer Source #

(round . (* 10^9)) <$> getPOSIXTime

timeNowMicro :: IO Integer Source #

(round . (* 10^3)) <$> getPOSIXTime

timeNowMilli :: IO Integer Source #

(round . (* 10^6)) <$> getPOSIXTime

timeNowSecond :: IO Integer Source #

Same as timeNowSec

(round . (* 1)) <$> getPOSIXTime

timeNowSec :: IO Integer Source #

getLocalTime :: IO LocalTime Source #

get local time with TimeZone

getLocalTime

2020-07-08 12:14:46.10179

LocalTime

utcTime <- getCurrentTime
z <- getCurrentTimeZone
let utc = utcToLocalTime z utcTime
return utc

getLocalDate :: IO String Source #

KEY: get local date, get current time

"2019-05-27 12:57:41.520758 PDT"

getDate :: IO String Source #

KEY: get local date, get current time

s <- getLocalDate
putStr s
2019-05-27 12:57:41.520758 PDT

dateStr :: IO String Source #

KEY: get local date, get current time

s <- dateStr 
putStr s
2019-05-27 12:57:41.520758 PDT

date :: IO () Source #

KEY: print local date, print current time

Use getLocalDate

"2019-05-27 12:57:41.520758 PDT"

getTime :: IO String Source #

KEY: get local current time, local time, time zone

NOTE getCurrentTime is UTC timezone only,

getTimeDay time with day

return $ (show hour) ++ ":" ++ (show minute) ++ ":" ++ (show second)

showTime :: IO () Source #

trim :: String -> String Source #

Trim, remove whitespace characters from either side of string.

see trimWS all whitespace

splitStr :: RegexStr -> String -> [String] Source #

KEY: split string, split str

NOTE: DOES NOT Support String contains unicode

   > splitStr "25151" "abc25151def"

   > splitStr "::" "dog::cat" => ["dog", "cat"]

   > let s = "25151 abc 25151"
   "房 abc 房"
   > splitStr "25151" s
   *** Exception: user error (Text.Regex.Posix.String died: (ReturnCode 13,"repetition-operator operand invalid"))
   > splitWhen

   > splitWhenFirstNoRegex "25151" s
   Just (""," abc 25151")
   

splitStrChar :: RegexStr -> String -> [String] Source #

Partition string to [String] according to character class []

   splitStrChar "[,.]" "dog,cat,cow.fox" => ["dog", "cat", "cow", "fox"]y
   splitStrChar::String->String->[String]
   splitStrChar r s = splitWhen(x -> matchTest rex (x:[])) s
               where
                   rex = mkRegex r
   
splitStrRegex => splitStrChar

splitStrCharTrim :: RegexStr -> String -> [String] Source #

Split String. trim and Remove empty String

   splitStrCharTrim "[,.]" " dog,fox. " => ["dog", "fox"]
   

matchAllBS :: ByteString -> ByteString -> [(MatchOffset, MatchLength)] Source #

Match all pat from a given str

len :: (Foldable t, Num b) => t a -> b Source #

Better length function

  • Convert Int to polymorphic values
  • Convert Int to Num
  • fromIntegral::(Integral a, Num b)=> a -> b

splitStrTuple :: String -> String -> (String, String) Source #

split key and value

splitStrTuple "="  "host = localhost" => (host, localhost)
  • TODO: fix the function if host = dog = cat => ("host", "dogcat")

logFile :: FilePath -> [String] -> IO () Source #

logFile2 :: FilePath -> [String] -> IO () Source #

logFileTmp :: [String] -> IO () Source #

logFileNoName :: [String] -> IO () Source #

logFileGEx :: Bool -> String -> [String] -> IO () Source #

logFileG :: [String] -> IO () Source #

logFileGT :: String -> [String] -> IO () Source #

logFileMat :: Show a => String -> [[a]] -> IO () Source #

logFileSBS2 :: FilePath -> [ByteString] -> IO () Source #

showIntAtBaseX :: Integral a => a -> (Int -> Char) -> a -> ShowS Source #

KEY: binary, octedecimal, hexadecimal, int to hexadecimal

See showIntAtBase from Numeric

   showIntAtBaseX 2 intToDigit 10 ""  => binary
   showIntAtBaseX 8 intToDigit 10 ""  => octal
   showIntAtBaseX 10 intToDigit 10 "" => decimal
   showIntAtBaseX 16 intToDigit 10 "" => hexadecimal

   -- hexadecimal to decimal
   showIntAtBaseX 10 intToDigit (hexToInt "ff") ""
   

integerToHex :: Integer -> String Source #

KEY: integer to hexadecimal

intToHex :: Integer -> String Source #

hexToInt :: String -> Integer Source #

KEY: Integer to hexadecimal

integerToHex::Integer -> String -- Use Numeric showInt integerToHex n = showInt n ""

KEY: hexadecimal to Integer

unescape :: String -> String Source #

KEY: escape char to unescape char, int to unicode

   "\x2206" => "x2206"
   

intToUnicode :: Int -> Char Source #

KEY: int to unicode

     hex: x2206 => ∆
   

hexToUnicode :: String -> Char Source #

KEY: hexadecimal to unicode

intToChar :: Int -> Char Source #

int to unicode, int to char

See hexToUnicode intToUnicode

hexToChar :: String -> Char Source #

hexadecimal to Char or Unicode

See hexToUnicode intToChar

ρ :: [a] -> Int Source #

data FrameCount Source #

Constructors

FrameCount 

Fields

Instances

Instances details
Eq FrameCount Source # 
Instance details

Defined in AronModule

Methods

(==) :: FrameCount -> FrameCount -> Bool

(/=) :: FrameCount -> FrameCount -> Bool

Show FrameCount Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> FrameCount -> ShowS

show :: FrameCount -> String

showList :: [FrameCount] -> ShowS

resetRefFrame :: IORef FrameCount -> IO () Source #

readRefFrame2 :: IORef FrameCount -> Integer -> IO (Int, Bool, FrameCount) Source #

KEY: animate counter

    (count, isNext, currRef) <- readRefFrame2 refCount 200

         refFrame (timeNowMilli>= x -> newIORef FrameCount{frameTime = x, frameCount = 1})

         (count, isNext, currRef) <- readRefFrame refFrame

         -- count   => start from 1 to 100, 1 <= count <= 100 and stop at 100
         -- isNext  => Bool, the delay is <= 20::Integer then True else False
         -- currRef => old Ref or updated Ref dependen on whether isNext is True or False

         when isNext $ do
           draw1
           draw2
 

fileSizeStrToNum :: String -> Float Source #

KEY: file size unit, Kilobyte or Magebyte NOT Gigabyte, Terabyte or Petabyte

     fileSizeStrToNum 31M => 31 * 1024
     fileSizeStrToNum 20K => 20
   

whichGetPath :: String -> IO FilePath Source #

KEY: which in shell, which pdflatex

openFileUtf8 :: MonadIO m => FilePath -> IOMode -> m Handle Source #

KEY: open file with UTF-8 encoding, read file with UTF-8 encoding

with-utf8 with-utf8

readFileUtf8 :: MonadIO m => FilePath -> m Text Source #

KEY: read file with UTF-8 encoding, readfile utf8

with-utf8 with-utf8

scientificToFloat :: RealFloat a => Int -> a -> String Source #

scientific notation to normal notation

     scientificToFloat 3 3.1415e-2  -- 0.031
     sciToFloat 3 3.1415e-2  -- 0.031

     showFFloat (Just 3) 3.1415e-2 ""  -- 0.031
   

sciToFloat :: RealFloat a => Int -> a -> String Source #

scientific notation to normal notation

     scientificToFloat 3 3.1415e-2  -- 0.031
     sciToFloat 3 3.1415e-2  -- 0.031

     showFFloat (Just 3) 3.1415e-2 ""  -- 0.031
   

colorfgStr :: Integer -> String -> String Source #

KEY: Terminal color, term color, term background color, shell color, escape code sequence

http://localhost/html/indexTerminalColorandEscapeCodeSequence.html

   colorfgStr::Integer -> String -> String -- putStrLn $ colorfgStr 200 Hello
   colorfgStr n s = fg ++ color ++ s ++ reset
          where
            fg = "x1b[38;5;"
            color = (show n) ++ "m"
            reset = "x1b[0m"
   
     Use 256 Colors in terminal

     Set foreground color: x1b[38;5; {color code}m x1b[0m
     Set background color: x1b[48;5; {color code}m x1b[0m
                              |           |            |
                              |           |            |-> reset color
                              |           |-> RGB color (0-255)
                              |
                              |->  38 => foreground
                              |->  48 => background


     24 bit RGB (Truecolor)
     {r}    {g}       {b}
     8bits  8bits     8bits = 24bits

     32 bit RGBA
     {r}    {g}       {b}    {a}
     8bits  8bits     8bits  8bits

     2^10 = 1024
     2^5 = 32 x 32 = 940 + 64 = 1024
     2^24 = (2^10)^2 * 2^2 = 1024 x 1024 = 1M*2^2 = 4M

     Set foreground color: x1b[38;2;{r};{g};{b}mx1b[0m
     Set background color: x1b[48;2;{r};{g};{b}mx1b[0m
                              |           |            |
                              |           |            |-> reset color
                              |           |-> RGB color (0-255)
                              |
                              |->  38 => foreground
                              |->  48 => background


     putStrLn $ colorfgStr 200 Hello
   

SEE: color Pretty

colorbgStr :: Int -> String -> String Source #

KEY: Terminal color, term color, term background color, shell color, color background string

putStrLn $ colorbgStr 200 "Hello"
   colorbgStr::Int -> String -> String -- putStrLn $ colorbgStr 200 Hello
   colorbgStr n s = bg ++ color ++ s ++ reset
          where
            bg = "x1b[48;5;"
            color = (show n) ++ "m"
            reset = "x1b[0m"

   -- Use AronToken
   let s = "( 1 + 2 = 3 )"
   putStr $ (concat . colorToken) $ tokenize s
   

SEE: AronToken SEE: tokenize colorToken SEE: colorfgStr SEE: color Pretty

createProcessPipeData :: String -> [String] -> String -> IO (Maybe Handle, ExitCode) Source #

KEY: pipe data to external process

 ls = ["dogn", "catn"]
            |
            |
            ↓
           pipe | createPipe
            |
            ↓
         External Process
         "alignmentStr -p kk"
            |
            ↓
         Handle = hout
            |
            ↓
         hGetContents hout
            |
            ↓
          putStr


   let ls = [""12"", ""34  "", ""5 6     ""]
   mayStOut <- createProcessPipeData "alignmentStr" ["-p", "kk"] ls
   case mayStOut of
        Just hout -> hGetContents hout >>= x -> length x seq putStr x
        _        -> putStrLn "nothing"

writeFileSText :: FilePath -> Text -> IO () Source #

KEY: write Strict Text to file

writeFileLText :: FilePath -> Text -> IO () Source #

KEY: write Lazy Text to file

pad :: Num a => Int -> a -> [a] -> [a] Source #

KEY: padding zero to a list

Thu 2 Nov 12:06:19 2023 NOTE: disable it because Arrow use the same operator

KEY: padding zero to a list

padding left >pad 2 0 [1, 2]

padding right >pad (-2) 0 [1, 2]

nzero :: Num a => Int -> [a] Source #

KEY: list of zero

shiftMatrixLeft :: Num a => Int -> [[a]] -> [[a]] Source #

KEY: shift each row of matrix to left and padding with zero

  let m = [[1, 2, 3]
          ,[3, 4, 5]
          ,[6, 7, 8]]
  let shiftMat = shiftMatrixLeft 3 m
 

shellHighlight :: String -> [String] Source #

  • - data System.Console.Pretty.Color
  • - = Black
  • - | Red
  • - | Green
  • - | Yellow
  • - | Blue
  • - | Magenta
  • - | Cyan
  • - | White
  • - | Default
  • -

blockBegEnd :: (String -> Bool) -> (String -> Bool) -> [String] -> [[String]] Source #

KEY: extra BEG_xxx and END_xxx block from a file, extra code block, begin block, end block

   let f = containStr BEG_
   let g = containStr END_

   b <- getEnv "scr"
   let p = b / "AronLib.sh"
   ls <- readFileList p
   pre $ blockBegEnd f g ls

   

pick :: (a -> Bool) -> [a] -> ([a], [a]) Source #

KEY: pick from a list

   let (optls, numls) = pick (hasStr "-") ["-n", "-f", "10", "1", "5"] 
   optls = ["-n", "-f"
   numls = ["10", "1", "5"]
   

containAll :: Ord a => [a] -> [a] -> Bool Source #

KEY: Check cx within cy

   containAll [1, 2], [1, 2, 3] => True
   

combin :: Int -> [a] -> [[a]] Source #

KEY: m choose n, combination

URL: https://wiki.haskell.org/99_questions/Solutions/26

L.tails = mytails

   mytails :: [a] -> [[a]]
   mytails [] = [[]]
   mytails (x:cx) = (x:cx):(mytails cx)

   mytails [1, ll2, 3]
   [[1, 2, 3], [2, 3], [3]]
  
   combin 2 [1, 2, 3]
   [[1,2],[1,3],[2,3]]

   tails [1, 2, 3]
   [1, 2, 3], [2, 3], [3], []


   Explanation:
   1 2 3 4

   1 2 3 4      2 3 4        3 4         4           []
   1 (c(n-1))   2 (c(n-1))   3(c(n-1))   4(c(n-1))   
     2 3 4        3 4          4
       3 4          4
         4
     
   

drawRectBar :: (Pixel px, PrimMonad m) => MutableImage (PrimState m) px -> (Int, Int) -> (Int, Int) -> Int -> [Int] -> px -> m () Source #

histogram :: FilePath -> IO () Source #

KEY: draw histogram from a file

   tmpx.x
   1
   3 
   9
   20
   14

   histogram tmpx.x
   

insertIndexAt :: Int -> a -> [a] -> [a] Source #

KEY: insert to the next index

SEE removeIndex

isInList :: String -> [String] -> Bool Source #

KEY: Check str is in the list

removeFirstList :: Ord a => a -> [a] -> [a] Source #

KEY: remove the FIRST match from a list NOTE: Better name

removeFromList :: Ord a => a -> [a] -> [a] Source #

NOTE: Deprecated, bad name USE: removeFirstList

readFileInteger2d :: FilePath -> IO [[Integer]] Source #

KEY: read file 2d string to integer

Write APL data to file and read it from it

   m ← 3 3 3 ⍴ 10 ? 10
         m
    8 10  5
    2  3  1
    7  4  9
           
    6  8 10
    5  2  3
    1  7  4
           
    9  6  8
   10  5  2
    3  1  7

   (⊂↓⎕FMT m) ⎕NPUT 'tmpx'
   ⎕cmd 'cat tmpx'

   File:
   1 2 3
   3 4 5

   3 4 5
   3 3 9 

   => [[Integer]]
   

readFileFloat2d :: FilePath -> IO [[Float]] Source #

KEY: read file 2d string to Float

Write APL data to file and read it from it

   mf ← 3 3 3 ⍴ ? 10 ⍴ 0
         mf
   0.875658736   0.4130345348  0.7661493221 
   0.05092898876 0.7344701699  0.5883291622 
   0.08133906822 0.6499611783  0.203398563  
                                            
   0.7316870476  0.875658736   0.4130345348 
   0.7661493221  0.05092898876 0.7344701699 
   0.5883291622  0.08133906822 0.6499611783 
                                            
   0.203398563   0.7316870476  0.875658736  
   0.4130345348  0.7661493221  0.05092898876
   0.7344701699  0.5883291622  0.08133906822

   (⊂↓⎕FMT mf)⎕NPUT'tmpy'

   File:
   1.1 2.0 3.1
   2.1 3.3 3.3

   2.1 3.3 3.3

   => [[Float]]
   

readTable :: FilePath -> IO [[String]] Source #

Read table like string from a file

alignTable :: [String] -> [[String]] Source #

KEY: alignment, column table, align column, format table

   table 1:
   "a  b   c"
   "e f  g"
     ↓ 

   table 1:
   "a" "b" "c"
   "e" "f" "g"

   

columnTable :: [String] -> [[String]] Source #

KEY: alignment, column table, align column, format table

   table 1:
   "a  b   c"
   "e f  g"
     ↓ 

   table 1:
   "a" "b" "c"
   "e" "f" "g"
   

trimList :: [String] -> [String] Source #

trim list of String

   ["", "", "a", " b ", " "] => ["a", "b"]
   

trimListST :: [Text] -> [Text] Source #

trim list of strict Text

Text

   ["", "", "a", " b ", " "] => ["a", "b"]
   

stepList :: [a] -> Int -> [([a], [Int])] Source #

KEY: Generate a step list

SEE: splitWhenFirstNoRegex and splitWhenLastNoRegex

       stepList "abcd" 2 ⟹  
       [
           ( "ab"
           ,
               [ 0
               , 1
               ]
           )
       ,
           ( "bc"
           ,
               [ 1
               , 2
               ]
           )
       ,
           ( "cd"
           ,
               [ 2
               , 3
               ]
           )
       ]
   

splitWhenFirstNoRegex :: String -> String -> Maybe (String, String) Source #

KEY: split a string without Regex, String can contain unicode

   > splitWhenFirstNoRegex "=" "25151 abc=123=456"
   Just ("25151 abc","123=456")


   > splitStr "25151" "abc25151def"

   > let s = "25151 abc 25151"
   "房 abc 房"

   > splitStr "25151" s
   *** Exception: user error (Text.Regex.Posix.String died: (ReturnCode 13,"repetition-operator operand invalid"))
   > splitWhen

   > let s = "25151 abc 25151"
   > splitWhenFirstNoRegex "25151" s
   Just (""," abc 25151")

   

splitWhenLastNoRegex :: String -> String -> Maybe (String, String) Source #

KEY: split a string without Regex, String can contain unicode

   > splitWhenLastNoRegex "=" "25151 abc=123=456"
   Just ("25151 abc=123","456")
   

splitStrCharNoRegex :: String -> String -> [String] Source #

KEY: Split String to a list

       pre $ splitStrCharNoRegex "NUL" "123NULabcd0efghNUL"

       [ "123"
       , "abcd"
       , "efgh"
       ]

       pre $ splitStrCharNoRegex "0" "123NULabcd0efghNUL"

       [ "123"
       , "abcd"
       , "efgh"
       ]
   

printFile :: FilePath -> IO () Source #

withFile, print file

frequenceCount :: Ord a => [a] -> [(a, Int)] Source #

KEY: count the frequence of items

SEE: groupBy SEE: 'L.groupBy . sort' @ frequenceCount ["a", "b", "a", "b", "c"] [("a",2), ("b",2), ("c",1)]

frequenceCount [1, 2, 1, 3] [(1, 2), (2, 1), (3, 1)] @

data FileBlock Source #

Constructors

DropHead 
DropLast 
DropIndex Int 
PrintIndex Int 
PrintHead 
PrintLast 
PrintAll 
Append String 
AppendList [String] 
Prepend String 
NumberOfBlock 

Instances

Instances details
Eq FileBlock Source # 
Instance details

Defined in AronModule

Methods

(==) :: FileBlock -> FileBlock -> Bool

(/=) :: FileBlock -> FileBlock -> Bool

Show FileBlock Source # 
Instance details

Defined in AronModule

Methods

showsPrec :: Int -> FileBlock -> ShowS

show :: FileBlock -> String

showList :: [FileBlock] -> ShowS

fileBlock :: FilePath -> String -> FileBlock -> IO () Source #

KEY: Monday, 17 July 2023 14:55 PDT FIXED: Make delimiter and separator are the same.

splitPrefix :: (a -> Bool) -> [a] -> ([a], [a]) Source #

KEY: split prefix let t(h, t) = splitPrefix (x -> x /= ' ') ":abcd efgh ijkl mnop qrst uvwx yz" (":abcd"," efgh ijkl mnop qrst uvwx yz")

NOTE:break == splitPrefix break (== ' ') ":ab c" => (":ab", " c") @

breakFirst :: (a -> Bool) -> [a] -> ([a], [a]) Source #

grepx :: ByteString -> FilePath -> IO () Source #

catx :: FilePath -> IO () Source #

clipBoardcp :: String -> IO () Source #

KEY: clipboard, pbcopy, pbpaste, copy and paste

pbcopy :: String -> IO () Source #

clipBoardpa :: IO [String] Source #

pbpaste :: IO [String] Source #

hasSubstr :: String -> String -> Bool Source #

      print $ hasSubstr "ab" "xxabb" == True
      print $ hasSubstr "axb" "xxabb" == False 
      print $ hasSubstr "" "xxabb" == True 
      print $ hasSubstr "xab" "xxabb" == True
  

hasStrBlock :: String -> [String] -> [[String]] Source #

   hasStrBlock "abc" ["abc", "kk", "--", "aaa"]
   [["abc", "kk"] ["aaa"]]
   

powerSet :: [a] -> [[a]] Source #

KEY: power set, powerset

    [] => [[]]
    [1] => (x:[]) [[1]] ++ [[]] => [[], [1]]
    [1,2] => (1:[2]) => map (1:) $ [[],[2]) ++ [[], [2]]
                 => [[1],[1,2]] ++ [[], [2]]
                 => [[], [1], [2], [1,2]]
    

swap :: (Int, Int) -> [a] -> [a] Source #

KEY: swap list

printMat3 :: Show a => IOArray (Int, Int, Int) a -> IO () Source #

KEY: print array, print 2d array

 let a = 1; b = 2; c = 3
 ls <- DAO.newListArray ((0, 0, 0), (a, b, c)) [1..((a + 1) * (b + 1)) * (c + 1)] :: IO(IOArray (Int, Int, Int) Int)
 printMat3 ls
 

printMat2 :: Show a => IOArray (Int, Int) a -> IO () Source #

KEY: print array, print 3d array

 let a = 2; b = 3
 ls <- DAO.newListArray ((0, 0), (a, b)) [1..((a + 1) * (b + 1))] :: IO(IOArray (Int, Int) Int)
 printMat2 ls
 

cap :: IO a -> IO String Source #

KEY: capture stdout from print

 Silently from silently package

 fun :: IO()
 fun = print "capture string"

 str <- capture_ $ fun
 print str
 

readAndParse :: Read a => FilePath -> IO a Source #

KEY: read file and convert to Haskell type

    (x, y) <- readAndParse "tmpa" :: IO (Float, Float)
  

readMaybeParse :: Read a => FilePath -> IO (Maybe a) Source #

multiMatArr :: (Ix a, Ix b, Ix c, Num n) => Array (a, b) n -> Array (b, c) n -> Array (a, c) n Source #

NOTE: The runtime is very slow SEE: RunTime

  -- https://www.haskell.org/tutorial/arrays.html

  let ln = 500
  m1 geneRandMat (ln, ln) <& join
  let ar1 = array ((0, 0),(ln - 1, ln - 1)) [((i, j), let ix = i * ln + j in m1 !! ix)
                                             | i <- range (0, ln - 1),
                                               j <- range (0, ln - 1)]

  let a0 = array ((0, 0), (1, 1)) [((i, j), i + j) | i <- range (0, 1), j <- range (0, 1)]
  let a1 = array ((0, 0), (1, 1)) [((i, j), i + j) | i <- range (0, 1), j <- range (0, 1)]
  let m = multiMatArr a0 a1
  print a0
  fw ""
  print a1
  fw "m"
  print m
  fw "ar1 x ar1"
  old <- timeNowMicro
  let m2 = multiMatArr ar1 ar1
  wfl "tmpx.x" $ map show $ elems m2
  new <- timeNowMicro
  let diff = new - old
  fw "diff="
  print diff
 

compareArray :: [Int] -> [Int] -> Int Source #

Orphan instances

Num a => Num [a] Source #

any dimension list

  • 2*[1, 2] = [2, 4]
  • [1, 2]+[3, 4] = [4, 6]
  • 2*[[1, 2]] = [[2, 4]]
Instance details

Methods

(+) :: [a] -> [a] -> [a]

(-) :: [a] -> [a] -> [a]

(*) :: [a] -> [a] -> [a]

negate :: [a] -> [a]

abs :: [a] -> [a]

signum :: [a] -> [a]

fromInteger :: Integer -> [a]