text:
Q: OR and PAR statements in haskell for the WHILE language i'm trying to write in Haskell the WHILE language from my Theory of Programming subject.
Everything was being defined recursively at first, so code was flowing. Then we reached statements, and derivation trees appeared, even though i could still transform that into recursive definitions. Until we got into the OR and PAR statements.
The 2 big-step axioms for the OR statement:    (S1 OR S2)

*

*If   < S1, s> -> s'   then   < S1 OR S2, s> -> s'

*If   < S2, s> -> s'   then   < S1 OR S2, s> -> s'

The 2 small-step axioms for the OR statement:
 - < S1 OR S2 , s > => < S1 , s >
 - < S1 OR S2 , s > => < S2 , s >
where S1 and S2 are Statements and s, s' are functions Var -> Int
Apparently a good way to achieve this behaviour is randomize which of S1 or S2 gets executed when we run S1 OR S2 .
Luckily i began my monad research months ago, reaching already the System.Random module and the State monad (monad Transformers are still unknown for me), so i can imagine some approaches (which i dislike)

*

*Get some "random" seed from both S1 and S2, something like (length . show), and passing that to System.Random . But i know that going that way leads to always choosing the same statement from S1 OR S2 when both S1 and S2 are fixed.

*Define new data (something like SpecialSTM) for the OR and PAR statements, so i can change the types of my functions (mainly semanticaSTM) to add some IO and real randomness .

So, is there a solution allowing me to keep the types just as they are now, but get some reasonable behaviour in the OR and PAR statements?
Here is all my code:
module WhileV4
  (
  -- La sintaxis:
    Bin(Cero, Uno)
  , Entero(N1,N2)
  , AritVar(Avar)
  , BoolVar(Bvar)
  , Aexpr(A1,A2,Sum,Mult,Rest)
  , Bexpr(Verdadero,Falso,Iguales,Distintos,MayorOigual,MenorOigual,Mayor,Menor,NO,Y,O,Entonces,Sii)
  , Stm(AssA,AssB,Skip,Comp,Si,Mientras,Repetir)

  -- La semantica:
  , semanticaN
  , semanticaA
  , semanticaB
  , freeAV
  , freeAV'
  , freeBV
  , subsA
  , subsA'
  , subsB
  , newStateA
  , newStateB
  , semanticaSTM

  -- Otros:
  , mkEnt  -- para crear Enteros a partir de cadenas de 0s y 1s
  , (.:)   -- sinonimo infijo de Comp (otra opcion, usar la clase Monoid --> TO DO)
  , (>+)
  , (>*)
  , (>-)
  , (=:)   -- asignacion para variables aritmeticas, sinonimo infijo
  , (==:)  -- asignacion para variables booleanas, sinonimo infijo
  , (=.=)
  , (=/=)
  , (<.=)
  , (>.=)
  , factorial
  , euclides

  ) where

import Data.Char (digitToInt)
import qualified Data.Set as S

import Control.Applicative
import Data.Maybe

----------------------------------------------------------
-- TEMA 1
----------------------------------------------------------

-- Comparando con lo visto en clase:
--   Num ~ Entero , Var ~ AritVar , Aexp ~ Aexpr , Bexp ~ Bexpr , Stm ~ Stm
--     Los constructores de cada expresion tienen distinta notacion para evitar interferencias con Haskell.
--     Faltan las BoolVar (se dejan como ejercicio en clase).
--   N ~ semanticaN , State ~ Astate , A ~ semanticaA
--     Definiciones de "definicion composicional" e "induccion estructural".
--     Observacion sobre la semantica de (-a)
--     Ej 1.8: Demostrar que las ecuaciones para A definen una funcion total.
--     Visto en clase: N es funcion total
--   B ~ semanticaB
--     Ej 1.10: Demostrar que las ecuaciones para B definen una funcion total.
--     Ej 1.11: (a) Se extiende Bexp a Bexp'; extender la funcion semantica B (ya implementado)
--              (b) Demostrar que para cada b' en Bexp' existe b en Bexp tal que b' y b son equivalentes.
--   FV ~ freeAV
--     Lema 1: Sean s,s' en State tales que para todo x en FV(a), s x == s' x  =>  A[[a]]s == A[[a]]s'
--     Ej 1.13: Definir el conjunto de variables libres para una expresion booleana y demostrar un resultado similar al Lema 1.
--     ERROR: freeBV no es lo que pide el ejercicio 13 (pide freeAV')
--   substitucion ~ subsA  ,  actualizar estado ~ newStateA
--     Ej 1.14: Demostrar que A[[ a[y->a0] ]]s = A[[a]](s[y->A[[a0]]s]) para cualquier estado s.
--     Ej 1.15: Definir la substitucion de expresiones booleanas b[y->a0] y demostrar un resultado similar al del ejercicio anterior.

data Bin = Cero | Uno
  deriving Show

-- Para hacerlo como en clase:
-- data Entero = N1 Bin | N2 Entero Bin
-- pero podria hacerlo con listas que total tambien son recursivas
-- newtype Entero = N [Bin]
-- pero me toca las narices la lista vacia asi que voy a hacerlo como en clase

data Entero = N1 Bin | N2 Entero Bin
  deriving Show

semanticaN :: Entero -> Int
semanticaN (N1 Cero)   = 0
semanticaN (N1 Uno)    = 1
semanticaN (N2 n Cero) = 2 * semanticaN n
semanticaN (N2 n Uno)  = (2 * semanticaN n) + 1

data AritVar = Avar String
  deriving (Eq, Ord, Show)

data BoolVar = Bvar String
  deriving (Eq, Ord, Show)
-- el Ord lo necesito para hacer uniones de (Set AritVar) y (Set BoolVar)

data Aexpr = A1 Entero | A2 AritVar | Sum Aexpr Aexpr     | Mult Aexpr Aexpr      | Rest Aexpr Aexpr

data Bexpr = Verdadero | Falso      | Iguales Aexpr Aexpr | Distintos Aexpr Aexpr | MayorOigual Aexpr Aexpr | MenorOigual Aexpr Aexpr | Mayor Aexpr Aexpr  | Menor Aexpr Aexpr
                       | NO Bexpr   | Y Bexpr Bexpr       | O Bexpr Bexpr         | Entonces Bexpr Bexpr    | Sii Bexpr Bexpr         | B BoolVar         -- Bvar String

data Stm   = AssA AritVar Aexpr     | AssB BoolVar Bexpr  | Skip                  | Comp Stm Stm            | Si Bexpr Stm Stm        | Mientras Bexpr Stm | Repetir Stm Bexpr
                                    | Abortar             | Asegurar Bexpr Stm    | Or Stm Stm              | Par Stm Stm
                                    | Iniciar Dec

semanticaA :: Aexpr -> (AritVar -> Int) -> Int
semanticaA (A1 ent) s     = semanticaN ent
semanticaA (A2 var) s     = s var
semanticaA (Sum a1 a2)  s = (semanticaA a1 s) + (semanticaA a2 s)
semanticaA (Mult a1 a2) s = (semanticaA a1 s) * (semanticaA a2 s)
semanticaA (Rest a1 a2) s = (semanticaA a1 s) - (semanticaA a2 s)

semanticaB :: Bexpr -> (AritVar -> Int) -> (BoolVar -> Bool) -> Bool
semanticaB Verdadero _ _ = True
semanticaB Falso     _ _ = False
semanticaB (Iguales a1 a2)     s _ =  (semanticaA a1 s) == semanticaA a2 s
semanticaB (Distintos a1 a2)   s _ =  (semanticaA a1 s) /= semanticaA a2 s
semanticaB (MayorOigual a1 a2) s _ =  (semanticaA a1 s) >= semanticaA a2 s
semanticaB (MenorOigual a1 a2) s _ =  (semanticaA a1 s) <= semanticaA a2 s
semanticaB (Mayor a1 a2)       s _ =  (semanticaA a1 s) > semanticaA a2 s
semanticaB (Menor a1 a2)       s _ =  (semanticaA a1 s) < semanticaA a2 s
semanticaB (B boolvar)       s1 s2 =  s2 boolvar
semanticaB (NO bexpr)        s1 s2 =  not (semanticaB bexpr s1 s2)
semanticaB (Y b1 b2)         s1 s2 =  (semanticaB b1 s1 s2) && (semanticaB b2 s1 s2)
semanticaB (O b1 b2)         s1 s2 =  (semanticaB b1 s1 s2) || (semanticaB b2 s1 s2)
semanticaB (Entonces b1 b2)  s1 s2 =  semanticaB (NO (b1 `Y` (NO b2))) s1 s2
semanticaB (Sii b1 b2)       s1 s2 =  (semanticaB b1 s1 s2) == (semanticaB b2 s1 s2)

freeAV :: Aexpr -> S.Set AritVar
freeAV (A1 _)       = S.empty
freeAV (A2 avar)    = S.singleton avar
freeAV (Sum a1 a2)  = (freeAV a1) `S.union` (freeAV a2)
freeAV (Mult a1 a2) = (freeAV a1) `S.union` (freeAV a2)
freeAV (Rest a1 a2) = (freeAV a1) `S.union` (freeAV a2)

freeAV' :: Bexpr -> S.Set AritVar
freeAV' Verdadero = S.empty
freeAV' Falso     = S.empty
freeAV' (Iguales a1 a2)     = (freeAV a1) `S.union` (freeAV a2)
freeAV' (Distintos a1 a2)   = (freeAV a1) `S.union` (freeAV a2)
freeAV' (MayorOigual a1 a2) = (freeAV a1) `S.union` (freeAV a2)
freeAV' (MenorOigual a1 a2) = (freeAV a1) `S.union` (freeAV a2)
freeAV' (Mayor a1 a2)       = (freeAV a1) `S.union` (freeAV a2)
freeAV' (Menor a1 a2)       = (freeAV a1) `S.union` (freeAV a2)
freeAV' (B boolvar)         = S.empty
freeAV' (NO bexpr)          = freeAV' bexpr
freeAV' (Y b1 b2)           = (freeAV' b1) `S.union` (freeAV' b2)
freeAV' (O b1 b2)           = (freeAV' b1) `S.union` (freeAV' b2)
freeAV' (Entonces b1 b2)    = (freeAV' b1) `S.union` (freeAV' b2)
freeAV' (Sii b1 b2)         = (freeAV' b1) `S.union` (freeAV' b2)

freeBV :: Bexpr -> S.Set BoolVar
freeBV Verdadero = S.empty
freeBV Falso     = S.empty
freeBV (Iguales a1 a2)     = S.empty
freeBV (Distintos a1 a2)   = S.empty
freeBV (MayorOigual a1 a2) = S.empty
freeBV (MenorOigual a1 a2) = S.empty
freeBV (Mayor a1 a2)       = S.empty
freeBV (Menor a1 a2)       = S.empty
freeBV (B boolvar)         = S.singleton boolvar
freeBV (NO bexpr)          = freeBV bexpr
freeBV (Y b1 b2)           = (freeBV b1) `S.union` (freeBV b2)
freeBV (O b1 b2)           = (freeBV b1) `S.union` (freeBV b2)
freeBV (Entonces b1 b2)    = (freeBV b1) `S.union` (freeBV b2)
freeBV (Sii b1 b2)         = (freeBV b1) `S.union` (freeBV b2)

subsA :: Aexpr -> AritVar -> Aexpr -> Aexpr
subsA (A1 ent) _ _     = (A1 ent)
subsA (A2 avar) v a    = if avar == v then a else (A2 avar)
subsA (Sum a1 a2)  v a = Sum (subsA a1 v a) (subsA a2 v a)
subsA (Mult a1 a2) v a = Mult (subsA a1 v a) (subsA a2 v a)
subsA (Rest a1 a2) v a = Rest (subsA a1 v a) (subsA a2 v a)

subsA' :: Bexpr -> AritVar -> Aexpr -> Bexpr
subsA' Verdadero _ _ = Verdadero
subsA' Falso     _ _ = Falso
subsA' (Iguales a1 a2)     v a = Iguales (subsA a1 v a) (subsA a2 v a)
subsA' (Distintos a1 a2)   v a = Distintos (subsA a1 v a) (subsA a2 v a)
subsA' (MayorOigual a1 a2) v a = MayorOigual (subsA a1 v a) (subsA a2 v a)
subsA' (MenorOigual a1 a2) v a = MenorOigual (subsA a1 v a) (subsA a2 v a)
subsA' (Mayor a1 a2)       v a = Mayor (subsA a1 v a) (subsA a2 v a)
subsA' (Menor a1 a2)       v a = Menor (subsA a1 v a) (subsA a2 v a)
subsA' (B boolvar)      v a = (B boolvar)
subsA' (NO bexpr)       v a = NO (subsA' bexpr v a)
subsA' (Y b1 b2)        v a = (subsA' b1 v a) `Y` (subsA' b2 v a)
subsA' (O b1 b2)        v a = (subsA' b1 v a) `O` (subsA' b2 v a)
subsA' (Entonces b1 b2) v a = (subsA' b1 v a) `Entonces` (subsA' b2 v a)
subsA' (Sii b1 b2)      v a = (subsA' b1 v a) `Sii` (subsA' b2 v a)

subsB :: Bexpr -> BoolVar -> Bexpr -> Bexpr
subsB Verdadero _ _ = Verdadero
subsB Falso     _ _ = Falso
subsB b@(Iguales a1 a2)     _ _ = b
subsB b@(Distintos a1 a2)   _ _ = b
subsB b@(MayorOigual a1 a2) _ _ = b
subsB b@(MenorOigual a1 a2) _ _ = b
subsB b@(Mayor a1 a2)       _ _ = b
subsB b@(Menor a1 a2)       _ _ = b
subsB (B boolvar)      v b = if boolvar == v then b else (B boolvar)
subsB (NO bexpr)       v b = NO (subsB bexpr v b)
subsB (Y b1 b2)        v b = (subsB b1 v b) `Y` (subsB b2 v b)
subsB (O b1 b2)        v b = (subsB b1 v b) `O` (subsB b2 v b)
subsB (Entonces b1 b2) v b = (subsB b1 v b) `Entonces` (subsB b2 v b)
subsB (Sii b1 b2)      v b = (subsB b1 v b) `Sii` (subsB b2 v b)

newStateA :: (AritVar -> Int) -> AritVar -> Int -> (AritVar -> Int)
newStateA s y n x = if x == y then n else (s x)

newStateB :: (BoolVar -> Bool) -> BoolVar -> Bool -> (BoolVar -> Bool)
newStateB s y b x = if x == y then b else (s x)

----------------------------------------------------------
-- TEMA 2
----------------------------------------------------------

-- Comparando con lo visto en clase:
--   configuracion ~ Config  ,  transicion ~ Transicion
--   Defs: La ejecucion de una sentencia S en un estado s:   (¬ terminar = ciclar)
--     termina sii existe un estado s' tal que <S,s> -> s'
--     cicla sii no existe ningun estado s' tal que <S,s> -> s'
--   Ej 2.4: Determinar si las sentencias terminan / ciclan (o no) siempre:
--     while ¬(x=1) do (y := y*x ; x := x-1)
--     while 1<=x do (y := y*x ; x := x-1)
--     while true do skip
--   Def: S1 equivale semanticamente a S2 sii para todo s en State, <S1,s> -> s' si y solo si <S2,s> -> s'
--   Lema 2: {while b do S} es semánticamente equivalente a {if b then (S; while b do S) else skip}
--   Ej 2.6:
--     Demostrar que (S1;S2);S3 y S1;(S2;S3) son semanticamente equivalentes
--     Demostrar que en general S1;S2 no es semanticamente equivalente a S2;S1
--   Ej 2.7: Extender el lenguaje While con la sentencia  repeat S until b
--     Demostrar que {repeat S until b} es semanticamente equivalente a {S; if b then skip else (repeat S until b)}

type Astate = AritVar -> Int

type Bstate = BoolVar -> Bool

type Config  =  (Stm,Astate,Bstate)

type Transicion = Config -> (Astate,Bstate)

semanticaSTM :: Transicion
semanticaSTM (AssA x a, s1, s2) = let n = semanticaA a s1 in (newStateA s1 x n , s2)
semanticaSTM (AssB x b, s1, s2) = let n = semanticaB b s1 s2 in (s1 ,newStateB s2 x n)
semanticaSTM (Skip, s1, s2)           = (s1,s2)
semanticaSTM (Comp stm1 stm2, s1, s2) = let (s1' , s2') = semanticaSTM (stm1,s1,s2) in semanticaSTM (stm2,s1',s2')
semanticaSTM (Si b stm1 stm2, s1, s2) = if semanticaB b s1 s2 then semanticaSTM (stm1,s1,s2) else semanticaSTM (stm2,s1,s2)
semanticaSTM (Mientras b stm, s1, s2) = if semanticaB b s1 s2 then aux else (s1,s2)
  where aux =  let (s1' , s2') = semanticaSTM (stm,s1,s2) in semanticaSTM (Mientras b stm, s1', s2')
semanticaSTM (Repetir stm b,  s1, s2) = if semanticaB b s1 s2 then semanticaSTM (stm,s1,s2) else aux
  where aux = let (s1' , s2') = semanticaSTM (stm,s1,s2) in semanticaSTM (Repetir stm b , s1', s2')
semanticaSTM (Abortar ,       s1, s2) = error "La ejecucion del programa ha sido interrumpida por Abortar"
semanticaSTM (Asegurar b stm, s1, s2) = if (semanticaB b s1 s2) then semanticaSTM (stm,s1,s2) else error ("La ejecucion del programa ha sido interrumpida porque no se puede asegurar la condicion " ++ show b)
-- semanticaSTM (Or stm1 stm2 , s1, s2) = ???
-- semanticaSTM (Par stm1 stm2, s1, s2) = ???

----------------------------------------------------------
-- TEMA 3
----------------------------------------------------------

data Dec = DvA (String,Aexpr) Dec | DvB (String,Bexpr) Dec | NoMasVariables

----------------------------------------------------------
-- COSAS EXTRA
----------------------------------------------------------

-- Sinonimos infijos:

(.:) :: Stm -> Stm -> Stm
stm1 .: stm2 = Comp stm1 stm2

(>+) :: Aexpr -> Aexpr -> Aexpr
a1 >+ a2 = Sum a1 a2

(>*) :: Aexpr -> Aexpr -> Aexpr
a1 >* a2 = Mult a1 a2

(>-) :: Aexpr -> Aexpr -> Aexpr
a1 >- a2 = Rest a1 a2

(=:) :: AritVar -> Aexpr -> Stm
avar =: a  = avar `AssA` a

(==:) :: BoolVar -> Bexpr -> Stm
bvar ==: b = bvar `AssB` b

(=.=) :: Aexpr -> Aexpr -> Bexpr
a1 =.= a2  =  Iguales a1 a2

(=/=) :: Aexpr -> Aexpr -> Bexpr
a1 =/= a2  =  Distintos a1 a2

(<.=) :: Aexpr -> Aexpr -> Bexpr
a1 <.= a2  =  MenorOigual a1 a2

(>.=) :: Aexpr -> Aexpr -> Bexpr
a1 >.= a2  =  MayorOigual a1 a2

crearEntero :: [Int] -> Entero
crearEntero []     = error "No se puede crear un Entero con la lista vacia"
crearEntero (n:ns) = foldl f aux ns
  where
    f ent 0 = N2 ent Cero
    f ent 1 = N2 ent Uno
    aux     = if (n == 0) then (N1 Cero) else (N1 Uno)

mkEnt :: String -> Entero
mkEnt = crearEntero . map digitToInt

{- PRUEBAS EN PANTALLA
*While> mkEnt "100"
N2 (N2 (N1 Uno) Cero) Cero
*While> semanticaN (mkEnt "100")
4
*While> semanticaN (mkEnt "112")
*** Exception: While.hs:(41,5)-(42,24): Non-exhaustive patterns in function f
-}

a1 = Sum (A2 (Avar "x")) (A1 (N1 Uno))
x = Avar "x"
y = Avar "y"
z = Avar "z"
m = Avar "m"
n = Avar "n"
n0 = (N1 Cero)
n1 = (N1 Uno)
n2 = mkEnt "10"
n3 = mkEnt "11"
n4 = mkEnt "100"
n5 = mkEnt "101"
n6 = mkEnt "110"
n7 = mkEnt "111"
n8 = mkEnt "1000"
n9 = mkEnt "1001"
n10 = mkEnt "1010"
n11 = mkEnt "1011"
a2 = Rest (Sum (A2 x) (A2 y)) (Mult (A2 z) (A1 n5))
m' = A2 m
n' = A2 n

factorial :: Stm
factorial = (y =: (A1 n1)) .: (Mientras (NO (Iguales (A2 x) (A1 n1))) ((y=:(Mult (A2 y) (A2 x))) .: (x=:(Rest (A2 x) (A1 n1)))))

stateA1 :: Astate
stateA1 (Avar "_") = 5

stateB1 :: Bstate
stateB1 _ = True

euclides :: Stm
euclides = Mientras (NO (m' =.= n')) (Si (m' <.= n') (n =: (n' >- m')) (m =: (m' >- n')))

stA1 :: Astate
stA1 (Avar x) = if x=="n" then 20 else (if x=="m" then 8 else 0)

probandoShow :: Stm
probandoShow = Si Verdadero euclides factorial

{- pruebas en pantalla:
*While> :t   fst $ semanticaSTM (factorial, stateA1, stateB1)
fst $ semanticaSTM (factorial, stateA1, stateB1) :: Astate
*While> let aux = fst $ semanticaSTM (factorial, stateA1, stateB1) in map aux [x,y]
[1,120]
(0.03 secs, 7942288 bytes)
*While> let aux = fst $ semanticaSTM (factorial, const 16, stateB1) in map aux [x,y]
[1,20922789888000]
(0.02 secs, 0 bytes)
*While> product [1..16]
20922789888000
(0.00 secs, 0 bytes)
*While> let aux = fst $ semanticaSTM (factorial, const 20, stateB1) in map aux [x,y]
[1,2432902008176640000]
(0.02 secs, 0 bytes)
*While> let aux = fst $ semanticaSTM (factorial, const 21, stateB1) in map aux [x,y]
[1,-4249290049419214848]
(0.00 secs, 0 bytes)

*WhileV3>  let aux = fst $ semanticaSTM (euclides, stA1, stateB1) in map aux [n,m]
[4,4]
-}

-- instance Eq Entero where
--   n1 == n2 = (semanticaN n1) == (semanticaN n2)

-- instance Ord Entero where
--   compare n1 n2 = compare (semanticaN n1) (semanticaN n2)

instance Show Aexpr where
  show (A1 n)        = (show . semanticaN) n
  show (A2 (Avar x)) = x
  show (Sum a1 a2)   = '(' : (show a1) ++ " + " ++ (show a2) ++ ")"
  show (Mult a1 a2)  = '(' : (show a1) ++ " * " ++ (show a2) ++ ")"
  show (Rest a1 a2)  = '(' : (show a1) ++ " - " ++ (show a2) ++ ")"

instance Show Bexpr where
  show Verdadero = "Verdadero"
  show Falso     = "Falso"
  show (Iguales a1 a2)     = '(' : (show a1) ++ " = " ++ (show a2) ++ ")"
  show (Distintos a1 a2)   = '(' : (show a1) ++ " /= " ++ (show a2) ++ ")"
  show (MayorOigual a1 a2) = '(' : (show a1) ++ " >= " ++ (show a2) ++ ")"
  show (MenorOigual a1 a2) = '(' : (show a1) ++ " <= " ++ (show a2) ++ ")"
  show (Mayor a1 a2)       = '(' : (show a1) ++ " > " ++ (show a2) ++ ")"
  show (Menor a1 a2)       = '(' : (show a1) ++ " < " ++ (show a2) ++ ")"
  show (B (Bvar x))        = x
  show (NO bexpr)          = '(' : 'N' : 'o' : ' ' : (show bexpr) ++ ")"
  show (Y b1 b2)           = '(' : (show b1) ++ " Y " ++ (show b2) ++ ")"
  show (O b1 b2)           = '(' : (show b1) ++ " O " ++ (show b2) ++ ")"
  show (Entonces b1 b2)    = '(' : (show b1) ++ " => " ++ (show b2) ++ ")"
  show (Sii b1 b2)         = '(' : (show b1) ++ " <=> " ++ (show b2) ++ ")"

instance Show Stm where
  show s = "\n" ++ showStm s 0 ++ "\n"

showStm :: Stm -> Int -> String
showStm s n =  let esp k = take k (repeat ' ') in
  case s of
    (AssA (Avar x) a) -> (esp n) ++ "(" ++ x ++ " := " ++ (show a) ++ ")"
    (AssB (Bvar y) b) -> (esp n) ++ "(" ++ y ++ " :== " ++ (show b) ++ ")"
    Skip              -> (esp n) ++ "No hacer nada"
    (Comp s1 s2)      -> (showStm s1 n) ++ "; \n" ++ (showStm s2 n)
    (Si b s1 s2)      -> (esp n) ++ "Si " ++ (show b) ++ "\n" ++ (esp $ n+2) ++ "entonces \n" ++ (showStm s1 (n+4)) ++ "\n" ++ (esp $ n+2) ++ "en otro caso \n" ++ (showStm s2 (n+4))
    (Mientras b s)    -> (esp n) ++ "Mientras se cumpla " ++ (show b) ++ " hacer \n" ++ (showStm s (n+4))
    (Repetir s b)     -> (esp n) ++ "Repetir " ++ "\n" ++ (showStm s (n+4)) ++ "\n" ++ (esp $ n+2) ++ "hasta que " ++ (show b)


text:
Q: OSC library working on iOS6 with ARC Now I'm looking for OSC library which working on iOS6 with ARC.
I tried vvOSC at first.
But I got an error with "- (NSString *) stringByDeletingLastAndAddingFirstSlash;"
Maybe Compiler can't find the method.
Then I tried to compile liblo for iOS6. I googled the way to do that. But I couldn't find an example. I have no idea with UINIX, so I gave up liblo.
Then I tried CocoaOSC. Actually the sample code works fine with iPhone simulator6.1. But The example doesn't use ARC and when I used CocoaOSC on my project which uses ARC, I got so many errors. I removed memory management things in CocoaOSC like 'autorelease, retain, etc..'.
I am kind of new at Objective-C. So I don't think I can resolve CocoaOSC problem with ARC.
So if someone knows good OSC library for iOS6 with ARC. Please tell me that.
Excuse for my poor English.
Thanks,

A: You can mix and match ARC and non-ARC code. You simply need to set the -fno-objc-arc compiler flag for each implementation file you want to not use ARC. This will allow you to easily mix non-ARC libraries with ARC code.
Given this, is there a specific reason why you need an ARC library?

redpajama_set_name: RedPajamaStackExchange


text:
Q: FFMPEG move source video up inside overlay image frame box I'm trying to put video inside frame box like this one

I tried to use overly filter, but the video edges, were covered by the frame  , I want at least the lower edge of the video to be moved up (e.g 20px or y=-90) to match with the frame inside border, but I didn't know what code to used to change the source video coordinates .
this is my command
ffmpeg -y -i source.mp4 -i 480_border.png -filter_complex "overlay=x=0:y=0" effict0.mp4

A: So what you need to do is scale the video, then overlay. Also the first stream of overlay is the background so it should be inversed here.
ffmpeg -y -i 480_border.png -i source.mp4 -filter_complex "\
[1:v]scale=w=1280:h=720[src];\
[0:v][src]overlay=x=20:y=20[vid]" \
-map [vid] -c:v libx264 -preset slow -c:a copy \
effict0.mp4

Just need to scale the video to the right dimensions.


text:
Q: Change getSupportActionBar().setTitle value from another class I have a class that gets actionbarsherlock oncreate and sets default values. How can I change this values from another class ?
sample codes that doesnt work :
public class MyActivity extends SlidingFragmentActivity {
 public static String abs;

@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       abs = "text";
       getSupportActionBar().setTitle(abs);
}
}

External class:
MyActivity.abs = "new value";

A: It is definitely not the recommended way to set the title, however, it should work if you remove the assignment abs = "text"; ...
public class MyActivity extends SlidingFragmentActivity {
    public static String abs;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       getSupportActionBar().setTitle(abs);
    }
}

... and call MyActivity.abs = "new value";some where before the activity is created the first time.
Anyhow I'd propose to pass the title as an extra into the activity ...
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("title", "Another Headline");
context.startActivity(intent);

... and evaluate that one from the intent:
public class MyActivity extends SlidingFragmentActivity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle extras = getIntent().getExtras();
        String title = "Default Headline";
        if (extras != null && extras.containsKey("title")) {
            title = intent.getStringExtra("title");
        }

        getSupportActionBar().setTitle(title);
    }
}

p.s. setting title after creation:
If you can reference the activity directly, for instance because you are in a fragment, you might add a method like ...
public class MyActivity extends SlidingFragmentActivity {

    public void setTitle(String title) {
        this.getSupportActionBar().setTitle(title);
    }

    ....
}

... and call it accordingly:
getActivity().setTitle("Another Headline");

The most sophisticated way to pass any kind of arguments to existing activities allowing them to process them in any way would be using a BroadcastReceiver:
public abstract class MyActivity extends SlidingFragmentActivity {

    public static final String SET_TITLE_ACTION = "com.myapp.SET_TITLE_ACTION";
    public static final IntentFilter INTENT_FILTER = createIntentFilter();

    private SetTitleReceiver setTitleReceiver = new SetTitleReceiver();

    private static IntentFilter createIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SET_TITLE_ACTION);
        return filter;
    }

    protected void registerSetTitleReceiver() {
        registerReceiver(setTitleReceiver, INTENT_FILTER);
    }

    protected void unRegisterSetTitleReceiver() {
        unregisterReceiver(setTitleReceiver);
    }

    public class SetTitleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SET_TITLE_ACTION)) {
                Bundle extras = intent.getExtras();
                if (extras != null && extras.containsKey("title")) {
                    title = intent.getStringExtra("title");
                    this.getSupportActionBar().setTitle(title);
                }
            }
        }
    }
}

Any Activity class that should be able to receive a title change has to register the BroadcasdtReceiver in onResume() and unregister it in onPause(). This way you can set the title of these activity instance by sending a broadcast event from anywhere:
Intent intent = new Intent(MyActivity.SET_TITLE_ACTION);
intent.putExtra("title", "Another Headline");
context.sendBroadcast(intent);

Hope this helps ... Cheers!

A: It doesn't work because your just changing the reference abs is pointing to.
If you want to change the title pass the SherlockActivity as a parameter to your method.
Example:
public class MyActivity extends SherlockActivity {

@Override
    protected void onCreate(final Bundle savedInstanceState) {
        new ChangeTitle(this).setTitle("test title");
    }
}

class ChangeTitle {
    String title;
    SherlockActivity activity;

    public ChangeTitle(SherlockActivity activity) {
        this.activity = activity;
    }

    public void setTitle(String title) {
        this.title = title;
        activity.getSupportActionBar().setTitle(this.title);
    }
}


text:
Q: Schoology API OAuth 1.0 throwing 404 error while calling auth/authorize endpoint I am using schooly API which follows OAuth 1.0 and following this documentation: https://developers.schoology.com/api-documentation/authentication#toc-item-3
I am able to get request token using this endpoint: https://api.schoology.com/v1/oauth/request_token
But when I try to call authorize API: https://api.schoology.com/v1/oauth/authorize, I am getting error 404 Not found.

A: The default auth url is this: https://www.schoology.com/oauth/authorize.
If the user is in a district with its own schoology url like cityschool.schoology.com then you would use an auth url like this: https://cityschool.schoology.com/oauth/authorize.
I found this out by examining the source code of their PHP library here: https://github.com/schoology/schoology_php_sdk/blob/master/SchoologyApi.class.php#L365


text:
Q: Create a TabBar Controller with a Master-detail template? I created master-detail template for the ipad application and now I want to add Tab Bar to either master view or detail view. I can easily add tab bar controller using editor->embed in ->tab bar controller. However when I run application tab bar is not showing.
Tab bar is showing in storyboard but I am also unable to add extra tab bar items. What am I doing wrong thanks?

A: You should embed the navigation controller (of either the master or detail VC) in a tab bar controller, then delete the connection between the split view controller and that navigation controller. Finally, remake the connection from the split view controller to the tab bar controller. You'll also need to make several code changes, because the template code refers to the detail controller by its hierarchy in the split view controller, which will now be different.


text:
Q: Empty Translations collections from custom model in index.html.twig sylius I created a custom entity "Faq" with their routes .
When I make a dump of "faqs" in my index.html.twig Faq#translations#collection is empty.
I need a "question"and a "response" in the collection.
In my database all fields are present in FaqTranslation.
What I've could missed?
Sorry for my poor English.
Thanks .
result dump(faqs)
Faq {#3359 ▼
-id: 2
#translations: PersistentCollection {#3369 ▼
-snapshot: []
-owner: Faq {#3359}
-association: array:16 [ …16]
-em: EntityManager {#2123 …11}
-backRefFieldName: "translatable"
-typeClass: ClassMetadata {#3361 …}
-isDirty: false
#collection: ArrayCollection {#3371 ▼
-elements: []
}
#initialized: false
}
#translationsCache: []
#currentLocale: "fr_FR"
#currentTranslation: null
#fallbackLocale: "en_US"
}

Faq Entity
<?php
namespace AppBundle\Entity;

use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\TranslatableInterface;
use Sylius\Component\Resource\Model\TranslatableTrait;

/**
 * Faq
 */
class Faq implements ResourceInterface, TranslatableInterface
{
    use TranslatableTrait {
        __construct as private initializeTranslationsCollection;
    }

    public function __construct()
    {
        $this->initializeTranslationsCollection();
    }
    /**
     * @var int
     */
    private $id;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

        /**
     * Set response
     *
     * @param string $response
     *
     * @return FaqTranslation
     */
    public function setResponse($response)
    {
        return $this->getTranslation()->setResponse($response);

    }

    /**
     * Get response
     *
     * @return string
     */
    public function getResponse()
    {
        return $this->getTranslation()->getResponse();
    }

    /**
     * Set question
     *
     * @param string $question
     *
     * @return FaqTranslation
     */
    public function setQuestion($question)
    {
        return $this->getTranslation()->setQuestion($question);

    }

    /**
     * Get question
     *
     * @return string
     */
    public function getQuestion()
    {
        return $this->getTranslation()->getQuestion();
    }
    /**
     * Set locale
     *
     * @param string $locale
     *
     * @return FaqTranslation
     */
    public function setLocale($locale)
    {
        return $this->getTranslation()->setLocale($locale);
    }

    /**
     * Get locale
     *
     * @return string $locale
     */
    public function getLocale()
    {
        return $this->getTranslation()->getLocale();
    }
    /**
     * {@inheritdoc}
     */
    protected function createTranslation()
    {
        return new FaqTranslation();
    }

}

FaqTranslation Entity
<?php

namespace AppBundle\Entity;

use Sylius\Component\Resource\Model\AbstractTranslation;
use Sylius\Component\Resource\Model\ResourceInterface;

/**
 * FaqTranslation
 */
class FaqTranslation extends AbstractTranslation implements ResourceInterface
{
    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $response;

    /**
     * @var string
     */
    private $question;

    protected $locale;
    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set response
     *
     * @param string $response
     *
     * @return FaqTranslation
     */
    public function setResponse($response)
    {
        $this->response = $response;

        return $this;
    }

    /**
     * Get response
     *
     * @return string
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * Set question
     *
     * @param string $question
     *
     * @return FaqTranslation
     */
    public function setQuestion($question)
    {
        $this->question = $question;

        return $this;
    }

    /**
     * Get question
     *
     * @return string
     */
    public function getQuestion()
    {
        return $this->question;
    }

    /**
     * Set locale
     *
     * @param string $locale
     *
     * @return FaqTranslation
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;

        return $this;
    }

    /**
     * Get locale
     *
     * @return string $locale
     */
    public function getLocale()
    {
        return $this->locale;
    }
}

views/Faq/index.html.twig
{% extends '@SyliusShop/layout.html.twig' %}

{% block content %}
{{ dump(faqs.translations.toArray)}}
{% endblock %}

A: The dump can return a empty collection because is not initialized, try with {{ dump(faq.translations.toArray }}. PersistenCollections are initalized when are used, e.g. when get at least one element.


text:
Q: After POST request, don't get into success call back (javascript) My problem is that the page which requested a post request is gone, and then just shows me a JSON data string which come from server. Please let me know how can I just get the response data without redirecting(?) page.
Client POST Request
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Login Form</title>

  <link rel="stylesheet" type="text/css" href="../../semantic/dist/semantic.min.css">
  <link rel="stylesheet" type="text/css" href="../../semantic/dist/login.css">

Sign in

  <form class="form-signin" method="post">

      <input type="text" name = "user_id" placeholder="Email">

      <input type="password" name = "user_pw" placeholder="password">

      <input type="submit" value="sign in" class="ui button large fluid green">

Register

    </form>

Server POST Response
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({message : "success"}));

result
{"message":"success"}

A: In order, to prevent redirecting, you should use preventDefault() function.

A: If you want to handle the POST with an Ajax request, you should not use HTML posting.
Change your HTML as follows:
<form class="form-signin">

      <input type="text" name = "user_id" placeholder="Email">

      <input type="password" name = "user_pw" placeholder="password">

      <input type="button" value="sign in" class="ui button large fluid green">

Register

</form>

So remove the POST method on your form tag and remove the 'submit' type on your button field.
I added type="button" but you may also use type="text" if your css handles the rendering.


text:
Q: TypeError: argument of type 'int' is not iterable? What does it mean? ClassNames = studentname and score
if studentname not in ClassNames:
   ClassNames = ClassNames.append(studentname)
for studentname in filename and ClassNames <= 3:
    FirstResult.append(score)
    SecondResult.append|(score)
    ThirdResult.append(score)

The if line gives me the error:
TypeError: argument of type 'int' is not iterable

A: ClassNames = studentname and score

most likely sets the variable ClassNames to score which sounds like it could by of int.
By calling
if studentname not in ClassNames:
    ...

you iterate through ClassNames to find studentname, but like your error says, int is not iterable.
Further problems:

*

*list.append() works inplace and returns None

*ClassNames <= 3 makes only sense, if it is an int

A: Your ClassName is result of boolean operation and, so it can take value either True or False (0 or 1). Because it is non-iterable type, you are getting this error.
Re-think what data you want to keep in your ClassName.


text:
Q: Does gsutil mv command share files publicly in flight? I've just moved around 33.7k files from a bucket's top-level to a subdirectory via
gsutil -m mv gs://[BUCKET_NAME]/\*.json gs://[BUCKET_NAME]/dumps/
While the files were in flight, my boss was in the webinterface of Cloud Storage and she saw that some files were shared publicly:

I immediately checked the permissions for the listed files via gsutil ls -L gs://[BUCKET_NAME]/dumps/[SOME_FILE].json, but they looked fine after the move and before nothing was shared publicly.
After checking the the documentation I saw that there is a -p option to preserve ACLs. But I don't know if this would have prevented the situation as my default bucket ACL looks like this:
gsutil defacl get gs://[BUCKET_NAME]
[
  {
    "entity": "project-owners-xxx",
    "projectTeam": {
      "projectNumber": "xxx",
      "team": "owners"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-editors-xxx",
    "projectTeam": {
      "projectNumber": "xxx",
      "team": "editors"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-viewers-xxx",
    "projectTeam": {
      "projectNumber": "xxx",
      "team": "viewers"
    },
    "role": "READER"
  }
]

A: gsutil mv has the same options by default than gsutil cp, and this command, by default, does not copy the objects ACL.
The -p will take in account the ACL of each object. As the origin and destination bucket, in this case, are the same, you have to set an ACL on the bucket if you want to keep the files private.

A: Looking at the screenshot you provided, it seems you're in the top-level of the bucket (I assume the blue "s" in the top-left corner is from the word "Buckets", directly above the "Name" column).  In this case, you're looking at the objects that have not been moved yet.  After moving the objects from gs://BUCKET/ to gs://BUCKET/subdir/, if your defacl as shown is correct, the objects under the subdir/ prefix should not be publicly visible.
As for why your top-level objects were publicly viewable in the first place, your guess is as good as mine :)


text:
Q: A question based on location of roots using information about derivative at some points I am trying some questions asked in masters of mathematics exam of my university and I was unable to solve this particular problem.

Let $f:\mathbb{R} \rightarrow \mathbb{R}$ be twice continuous function with $f(0) = f(1) = f'(0) = 0$. Then which one of the following is true:

*

*$f"$ is zero function.

*$f"(0)=0$.

*$f"(x) = 0$ for some $x \in (0, 1)$.

*$f"$ never vanishes.
Options 1., 2. and 3. can be negated by taking $f(x) = x^{2} \cdot (x-1)$.
Can anyone please tell how to rigorously prove $3$rd option?

A: Assuming you mean $f\in C^2$, i.e. $f$ twice continuously differentiable.  Recall Rolle's theorem
Hint:

Apply it twice.

Details if you really want to not work:

First for $f\colon [0,1]\to\mathbb{R}$ and we have some $c_1\in(0,1)$ such that $f'(c_1)=0$.  Then for $f'\colon[0,c_1]\to\mathbb{R}$ and you have option (3).


text:
Q: summation of a finite sequence? What is the summation of the finite sequence:
$$\sum\limits_{i = 1}^n {\frac{1}{i}\left( {\begin{array}{*{20}{c}}
{2i - 2}\\
{i - 1}
\end{array}} \right)\left( {\begin{array}{*{20}{c}}
{2n + 2 - 2i}\\
{n + 1 - i}
\end{array}} \right)} $$
My professor leave us the answer: $\frac{{2n}}{{n + 1}}\left( {\begin{array}{*{20}{c}}
{2n}\\
n
\end{array}} \right)$, if I remembered it right.
But why such a complex summation has such a neat closed form expression? I'm stupid:(

A: Hint. You may use the same technique exposed here.
From
$$
\sum_{i=0}^{\infty} \binom{2i}i x^i=\frac{1}{\sqrt{1-4x}},\quad |x|<\frac14, \tag1
$$
by integration, you get
$$
\sum_{i=1}^{\infty} \frac1i\binom{2i-2}{i-1} x^i=\frac{1}{2}\left(1-\sqrt{1-4x} \right),\quad |x|<\frac14. \tag2
$$
and then use the Cauchy product.


text:
Q: React router - page does not render until I do a browser refresh I have tried to decouple my components a bit more and I ran into this weird bug. I obscured the other general imports. All components import properly and work.
What happens is I land on "/", then I click a button to navigate to dashboard it's a blank page (the URL did change). Then I hit refresh in my browser and the correct component displays. This also happens if I go back to my landing page; it's blank until I refresh.
In my app component
import history from './services/history';
import Routes from './routes';

function App() {
  return (
    <Router history={history}>
      <Routes />
    </Router>
  );

my history component (super simple)
import { createBrowserHistory} from 'history';

const history = createBrowserHistory();

export default history;

and finally my routes:
import Landing from "../pages/landing/landing.page"
import Dashboard from "../pages/dashboard/dashboard.page.jsx"

export default function Routes() {
  return (
    <Switch>
      <Route path="/" exact component={Landing}/>
      <Route path="/dashboard" component={Dashboard}/>
    </Switch>
  );

Here is my landing page, which I click the button to navigate to "/dashboard"
import { Link } from "react-router-dom";

function Landing () {
  return (
    <div class="landing-container">
      <Link to="/dashboard"><button> Setup Tests </button></Link>

    </div>
  )
}

export default Landing;

A: It looks like you're now using Router from react-router-dom. From my understanding, you have to import BrowserRouter in terms of browser use. So your code would look like:
import { BrowserRouter } from "react-router-dom";

function App() {
  return (
    <BrowserRouter history={history}>
      <Routes />
    </Router>
  );
}


text:
Q: Acquiring Widget's state to not build it again I followed this tutorial to create this cool route transition.
As far as I understand, the exit widget is rebuilt every time there is a route change, so it's state (for example scroll position) is not preserved. is there any way to preserve this state?
I tried using GlobalKey() and it seems to be working, but when the page changes, the exit widget is just a blank white screen for a millisecond before actually being the exit screen.


text:
Q: Vulnerability fix for Apache Commons Text with wso2 carbon libraries I am looking out for suggestions on the recent vulnerability(https://blogs.apache.org/security/entry/cve-2022-42889) which is also coming from the wso2 IS 5.11 binary downloaded from(https://github.com/wso2/product-is/releases/tag/v5.11.0) and the carbon libraries we are using in custom plugins like:
<groupId>org.wso2.carbon.identity.framework</groupId><artifactId>org.wso2.carbon.identity.mgt</artifactId>
<version>5.18.187</version>

<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.identity.application.authentication.framework</artifactId>
<version>5.18.187</version>

<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.identity.provisioning</artifactId>
<version>5.18.187</version>

As there any upgrades to these which is compatible with wso2 IS v5.11?

A: From wso2 advisories, it is mentioned that the vulnerability has no impact on the products [1] since the preconditions are not met and the team promises of fixing the vulnerable versions and (paid) customers will be able to obtain it through their security update once it is available. Along with this effort, the public fix will be done for the current public branch and will be available if you build the product-is from the repository. The timeline for the public fix is yet to be known.
And the suggested upgrade would be to 1.10.0 of Apache Commons Text library for 5.11.0.
This library comes to Identity server 5.11 pack mainly through Forget me tool. And in the latest release (wso2is-6.0.0), forget me tool has been externalized[2] which could be used in the product on demand.
Refer:
[1] https://docs.wso2.com/display/Security/CVE-2022-42889
[2] https://is.docs.wso2.com/en/latest/deploy/remove-references-to-deleted-user-identities/#building-the-identity-anonymization-tool


text:
Q: push notification disappear on screen My iPhone's screen is locked and sometimes, when I send push notifications a from PHP script, it disappears automatically. What can be the reason for this issue?
I use background fetch execution for didReceiveRemoteNotification:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)   (UIBackgroundFetchResult))completionHandler {

    NSLog(@"Notification received: %@", userInfo);

    completionHandler(UIBackgroundFetchResultNewData);

    // 100 lines of code

}


text:
Q: AWS Route53 to external DNS service A record I have brought example.com from one of address sellers.
On AWS I have Application Load Balancer.
I have created Route53 hosted zone and added this load balancer as A record alias:

How should I receive this records constant IP address to link my external DNS A record to this Route53?
I can't put CNAME to example.com, only sub-domain. When adding IP from Test Record Set IP list, they are changing from time to time.

A: You want to switch to using a Network Load balancer to get a consistent IP address.

Static IP support
Network Load Balancer automatically provides a static IP per Availability Zone (subnet) that can be used by applications as the front-end IP of the load balancer.
https://aws.amazon.com/elasticloadbalancing/details/#details

Also you'll want to switch to an ALIAS instead of an A record.

Queries to Alias records that are mapped to Elastic Load Balancers,
  Amazon CloudFront distributions, AWS Elastic Beanstalk environments,
  and Amazon S3 website buckets are free
https://aws.amazon.com/route53/pricing/


text:
Q: Uploading recording file stream to aws s3 in PHP is very slow In my application I can record video and save it to aws s3 bucket using vueJS as front end and Laravel php as backend.
I am using ffmpeg to upload recording stream to s3 bucket.
1 min video taking 4 mins and
3 mins video taking 9 mins (Always not successfully uploaded, some times it fails)
Below is the code in backend.
public function video_upload(Request $request)
    {
                // Response Declaration
                $response=array();
                $response_code = 200;
                $response['status'] = false;
                $response['data'] = [];
                // Validation
                // TODO: Specify mimes:mp4,webm,ogg etc
                $validator = Validator::make(
                $request->all(), [
                'file' => 'required',
                ]
                );
                if ($validator->fails()) {
                $response['data']['validator'] = $validator->errors();
                return response()->json($response);
                }
                try{
                    $file = $request->file('file');
                    //covert
                    $ffmpeg = FFMpeg\FFMpeg::create();
                    $video = $ffmpeg->open($file);

                    $format = new X264();
                    $format->on('progress', function ($video, $format, $percentage) {
                        echo "$percentage % transcoded";
                    });

                    $video->save($format, 'output.mp4');
                    //end convert
                    $file_name =  str_replace ('/', '', Hash::make(time())).'.mp4';

                    $file_folder = 'uploads/video/';
                    // Store the file to S3

                    // $store = Storage::disk('s3')->put($file_folder.$file_name, file_get_contents($file));
                    $store = Storage::disk('s3')->put($file_folder.$file_name, file_get_contents('output.mp4'));
                    if($store){
                        // Replace old file if exist
                        //delete the file from public folder
                        $file = public_path('output.mp4');
                        if (file_exists($file)) {
                            unlink($file);
                        }

                        if(isset($request->old_file)){

                            if(Storage::disk('s3')->exists($file_folder.basename($request->old_file))) {
                                 Storage::disk('s3')->delete($file_folder.basename($request->old_file));
                            }
                        }
                    }
                    $response['status'] = true;
                    $response['data']= '/s3/'.$file_folder. $file_name;

                }catch (\Exception $e) {
                    $response['data']['message']=$e->getMessage()."line".$e->getLine();
                    $response_code = 400;
                }
                return response()->json($response, $response_code);
    }

I was researching on Transfer Acceleration and multipart upload but question is do i do from aws end or in backend.


text:
Q: Change layout without calling onCreate I have an activity with two layout files, one each for portrait and landscape modes. I see that the onCreate method is called each time I change orientation. I tried using
android:configChanges = "orientation"

in the manifest file, but it only reads the portrait layout. Is there a way I can set the layout to the landscape mode without calling onCreate?

A: If you use android:configChanges = "orientation", you must override the onConfigurationChanged(...) method of your Activity. Check the newConfig parameter for the new orientation then manually set the layout you want.
See the following links:
onConfigurationChanged(Configuration newConfig)
Handling the Configuration Change Yourself

A: You could create two layout folders. One for portrait mode and one for landscape.
layout and layout-land.

A: This is a fact of life with android. You need to develop your activity around the fact it can be destroyed at any minute due to a configuration change like the screen's orientation changing.
Save all the the information used to build the screen in on pause and recreate it in onCreate.

A: If you want your activity be only in landscape mode, you set this attribute for the activity in the AndroidManifest.xml:
        android:screenOrientation="landscape"

You can put your layout.xml files in such folders for different screen orientations:

*

*res\layout-land

*res\layout-port


text:
Q: Has the Galactic Empire ever conducted large scale ground battles? The Galactic Empire was at its prime after the end of the Clone Wars and prior to the Battle of Endor. The Battle of Jakku saw most of the Imperial Navy, Army & Stormtrooper Corps committed and wiped out.
I've seen only two mentions by an Imperial officer to "prepare for ground assault" so far: Agent Kallus to pursue Captain Rex and Darth Vader at the Battle of Hoth. Both times, the full deployment is just a handful of AT-ATs and whatever they can carry onboard.
From the rise of the Empire to before the Battle of Jakku, did the Empire conduct any large-scale ground assaults to the order of what is seen during the Clone Wars on any single planet - an actual war operation?
Please distinguish between canon and Legends.

A: In canon, the Empire participated in several large-scale ground battles before the Battle of Jakku.
In 2 BBY, the Empire participated in the Battle of Atollon.

The Empire's ground-forces were composed of Stormtroopers, AT-DPs and AT-ATs.
In 0 BBY, the Empire fought in the Battle of Scarif.

The Empire's ground-forces were composed of Stormtroopers, Shoretroopers, Death troopers and ACT-ATs.
In 0 ABY, the Empire waged war against the ore-dukes of Shu-Torun.

It was comprised of multiple battles involving Stormtroopers, Magma troopers, battle droids and AT-ATs, as well as Shu-Torun loyalist forces that supported the Empire.
The Siege of Inyusu Tor occurred in 3 ABY.

The Empire's ground-forces were composed of Stormtroopers, Magma troopers, Imperial shock troopers, Jump troopers, Shadow Troopers, Viper probe droids
AT-STs and AT-ATs.
In 3 ABY, the Empire launched an attack on the Rebel base on Hoth.

The Empire's ground-forces were composed of Stormtroopers, Snowtroopers, AT-ATs, AT-STs and Juggernaut Tanks.
In 5 ABY, the Empire defended itself against the New Republic in the Battle of Kuat Drive Yards.

The Empire's ground-forces were composed of AT-TEs, AT-ACTs, AT-ATs and AT-STs.
The Battle of Jakku also qualified as as a ground-battle partaken in by the Empire.

In this battle, the Empire's ground-forces were made up of AT-ATs, AT-STs, Stormtroopers and Sandtroopers.
There are too many Legends battle to list here, but they can be seen on this Wookieepedia page.


text:
Q: REST Communication between microservices - Abstract away from host or port in REST call I just started diving into the microservices topic, so please excuse if this is a stupid question.
Let's say I have two microservices, one providing a REST api and one being an angular microservice for a nice frontend. The angular microservice is expected to communicate with the other microservice.
I saw many examples implementing this and its basically not a big deal. I am well aware of that. However, in all these examples I saw something like this in the angular microservice:
this.http.get('http://....:8080....');

At first I was just happy to get it running. However, right now I am wondering whether such implementations do not tightly couple the services to each other. In the http URL, we see the host and the port is also fix. That might work well in some cases, but, if our microservice e.g. chooses a port dynamically, we already have a problem right? Then we can't define the port in the other microservice in such a way. The same holds for the host information. If the microservice might be running on different hosts, we cannot always just define the host statically.
Please correct me if I'm wrong. Is there any way we can abstract away from these details, i.e. the host or the port but is there another way to find this out dynamically? Or are there other good alternatives for the communication between microservices that don't imply this problem?
I saw examples of services using a service registry. By means of this, we can abstract away from this a bit - no? Is this the only possibility? I am not sure whether this is relevant here, but so far I'm using Spring Boot to implement my microservices.

A: I think there is a confusion here, Microservices should be built around business capability and that means that your Microservice will include both the frontend and the backend. Frontend shouldn't be considered as a microservice.
Frontend could access the backend using sub domain name like http://api.example.com

A: In addition to what Hossam posted, I played around with Consul now. For this purpose, I studied e.g. the following Blog. Using Consul, I can do something like the following:restTemplate.getForObject('http://city-service/rest/city/capital', ...); instead of restTemplate.getForObject('http://localhost:8080/rest/city/capital', ...);. This should also work for other service registries. I still do not not how to do this in e.g. Angular, but perhaps I will create a new question for this.


text:
Q: Dynamically readjusting fields sequence on remove method I added two fields in my form; "Event Data" and "Event Details" using JavaScript. It facilitates the user to add as many events as he wants. Everything is working perfect except the following two issues.

*

*If I add let's say 5 events and remove the no. 2 event. The sequence of the rest of my events is like this 1,3,4,5 but they are supposed to look like 1,2,3,4

*Also, after removal of the no. 2 event, if I add the new event, it is created at number 5; so my sequence of events looks like this 1,3,4,5,5..
How can I modify my script to make my events rearrange automatically?

var tableCount = 1;
var index = 1;

$(document).on('click', 'button.add_time', function(e) {
  e.preventDefault();
  tableCount++;

  $('#timeTable').clone().attr('id', "timeTable" + tableCount).appendTo('#table');

  $('#timeTable' + tableCount).find("input").val("");

  index++;
  $('#timeTable' + tableCount + ' .aa').html(tableCount);
});

$(document).on('click', 'button.removeTime', function() {
  var closestTable = $(this).closest('table');
  if (closestTable.attr('id') != "timeTable") {
    closestTable.remove();
  }
  tableCount--;
  if (tableCount < 1) {
    tableCount = 1;
  }
  return false;
});

      1

        <button class="btn form-control btn-danger removeTime">Remove Events</button>

        <input placeholder="Event Date" name="events[]" class="input-lg" type="text" onfocus="(this.type='date')">

      1
      Event Description:

        <input name="event_descriptions[]" type="text" placeholder="Event description:" />

  <button class="add_time btn btn-info">Add More Events</button>

A: You can create some function which will get called everytime you clicked on remove button .In this function you need to loop through all tables leaving first one and then use .find() to add new value  i.e : count to that td where 1,2..etc are displayed.Also , you need to change id of your table using $(this).attr("id", "timeTable" + newvalue);
Demo Code :

var tableCount = 1;
var index = 1;

$(document).on('click', 'button.add_time', function(e) {
  e.preventDefault();
  tableCount++;

  $('#timeTable').clone().attr('id', "timeTable" + tableCount).appendTo('#table');

  $('#timeTable' + tableCount).find("input").val("");

  index++;
  $('#timeTable' + tableCount + ' .aa').html(tableCount);
});

$(document).on('click', 'button.removeTime', function() {
  var closestTable = $(this).closest('table');
  if (closestTable.attr('id') != "timeTable") {
    closestTable.remove();
  }
  tableCount--;
  resetValues(); //call to reset values
  if (tableCount < 1) {
    tableCount = 1;
  }
  return false;
});

function resetValues() {
  counter = 2; //initialze to 2 because 1 is fixed
  //looping through table not first one
  $(".tg:not(:first)").each(function() {
    //find .aa class replace its counter
    $(this).find('.aa').text(counter);
    $(this).attr('id', "timeTable" + counter);
    counter++;
  })
}

      1

        <button class="btn form-control btn-danger removeTime">Remove Events</button>

        <input placeholder="Event Date" name="events[]" class="input-lg" type="text" onfocus="(this.type='date')">

      1
      Event Description:

        <input name="event_descriptions[]" type="text" placeholder="Event description:" />

  <button class="add_time btn btn-info">Add More Events</button>


text:
Q: Laravel Multi Auth set up issue I have installed Multi Auth following instructions by ollieread at https://github.com/ollieread/multiauth, but i'm missing some point here.
I got this error when running my app before replacing the configuration for auth (config/auth.php):

ErrorException
  Missing argument 1 for Illuminate\Auth\AuthManager::createDriver(), called in     /private/var/www/portal-varejo/www/vendor/laravel/framework/src/Illuminate/Support/Manager.php     on line 81 and defined

Im pretty sure that whats missing is this (from documentation):

Custom Auth Drivers
At this current moment in time, custom Auth drivers written for the base Auth class will not >work. I'm currently looking into this particular issue but for the meantime, you can work >around this by changing your closure to return an instance of Ollieread\Multiauth\Guard >instead of the default.

How can i do that? What closure i'm supposed to change?
Running Laravel 4.1 here.

A: You need to comment out 'Illuminate\Auth\AuthServiceProvider' and 'Illuminate\Auth\Reminders\ReminderServiceProvider' from app/config/app.php.


text:
Q: There is an Endless loop about forEach and map when I learning eloquentjavascript chapter6
My english is poor can't describe the problem in detail so I paste my practice code:http://jsbin.com/exusox/3/edit
Endless loop when you click the butten.
I've tested my code,I found the endless loop in this code:
function extractFootnotes(paragraphs){
    var footnotes=[],currentNum=0;
    function dealWithFootnote(fragment){
      if(fragment.type=="footnote"){
        currentNum++;
        fragment.number=currentNum;
        footnotes.push(fragment);
        return {type:"reference",number:currentNum};
      }
      else{
        return fragment;
      }
    }
    //run here ,endless loop happened.I've tested forEach,the i++ can't work.
    forEach(paragraphs,function(paragraph){
      paragraph.content=map(dealWithFootnote,paragraph.content);
    });

    return footnotes;
  }

  function forEach(array,action){
    for(i=0;i<array.length;i++)
      action(array[i]);
  }

  function map(func,array){
    var result=[];
    forEach(array,function(element){
      result.push(func(element));
    });
    return result;
  }

Why this happen and How can I reduce my code?Thanks.
My Practice Code

A: The variable "i" in your "forEach" function is a global variable.  You should declare it with var:
function forEach(array, action) {
  var i;
  // ... etc
}

Thus when one call to "forEach" involves an action that will itself call "forEach", the same variable "i" will be reset.
It's a good idea to put this at the top of your code:
"use strict";

That tells the interpreter to apply some newer rules to the code, and it'd show you an error like that.


text:
Q: unable to bind the object from component controller to view in angular 1.5 I have a scenario where i need to bind the object from component controller to view which is the response coming from service.
when I am binding that object in html it is binding as empty object which I initialized. But after getting the response it is not updating.
Script:
  (function() {
        app.component('tabComponent', {
            bindings: {
                toggle: '<',
                oUserDetails: '<'
            },
            templateUrl: 'components/tabComponent/tabComponent.html',
            controller: tabComponentCtrl
        })

        function tabComponentCtrl(mainService) {
            this.emailPattern = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
            this.phNumberPattern = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
            this.namePattern = /^[a-zA-Z ]{1,15}$/;
            this.aEmployeeTypes = ["option1", "option2", "option3", "xyz", "abc", "lmn"];
            this.toggle = true;
            this.oUserDetails = {};
            /* for getting json data*/
            mainService.fnGerUserDetails().then(function(response) {
                this.oUserDetails = response;
                console.log(this.oUserDetails); //response
          }, function(response) {
                alert('error')
            });
            console.log(this.oUserDetails); //{}
            /*  for updating data to read only form*/
            this.fnSendData = function() {
                this.toggle = true;
            };
        }
    })();

Html:
    <md-content class="tabs-color">
    <md-tabs md-dynamic-height="" md-border-bottom="">

        <md-tab label="Tab1">
            <md-content class="md-padding">

                    <form name="userForm" data-ng-submit="$ctrl.fnSendData()">
                        <md-input-container class="md-block">
                            Name:
                            <input type="text" name="userName" ng-model="$ctrl.oUserDetails.name" ng-pattern="$ctrl.namePattern" ng-readonly="$ctrl.toggle" required>

UserName is required.

Must be maximum 15 characters only

                        </md-input-container>
                        <md-input-container class="md-block">
                            Email:
                            <input type="email" name="userEmail" ng-model="$ctrl.oUserDetails.email" ng-pattern="$ctrl.emailPattern" ng-readonly="$ctrl.toggle" required>

Email is required.

Email Is Invalid

                        </md-input-container>
                        <md-input-container class="md-block">
                            Phone Number:
                            <input type="text" name="phNumber" ng-model="$ctrl.oUserDetails.phoneNumber" ng-pattern="$ctrl.phNumberPattern" ng-readonly="$ctrl.toggle" required>

Phone Number is required

Must be a valid 10 digit phone number

                        </md-input-container>
                        <md-input-container class="md-block">
                            Location:
                            <input type="text" name="location" ng-model="$ctrl.oUserDetails.location" ng-readonly="$ctrl.toggle" ng-pattern="$ctrl.namePattern">
                        </md-input-container>
                        Employee Type:
                        <md-select ng-model="$ctrl.oUserDetails.employmentType" class="md-no-underline" ng-disabled="$ctrl.toggle" md-selected-text="$ctrl.fnGetSelectedText()">
                            <md-optgroup label="$ctrl.aEmployeeTypes">
                                <md-option data-ng-repeat="type in $ctrl.aEmployeeTypes" value="{{type}}">{{type}}</md-option>
                            </md-optgroup>
                        </md-select>{{text}}
                        <md-input-container class="md-block" ng-if="$ctrl.oToggle.showOrg">
                            Organization:
                            <input type="text" name="organization" ng-model="$ctrl.oUserDetails.organization" ng-readonly="$ctrl.toggle" required>

Organization is required

                        </md-input-container>
                        <md-input-container class="md-block" ng-if="$ctrl.oToggle.showExp">
                            Experiance:
                            <input type="text" name="location" ng-readonly="$ctrl.toggle" ng-model="$ctrl.oUserDetails.yearsOfExperiance" required>

Location is required

                        </md-input-container>
                        <md-input-container class="md-block" ng-if="$ctrl.oToggle.showOther">
                            Others:
                            <input type="text" name="others" ng-readonly="$ctrl.toggle" ng-model="$ctrl.oUserDetails.employmentType" required>

Others is required

                        </md-input-container>
                        <md-button type="submit" class="md-primary" aria-label="Save Data" ng-readonly="$ctrl.toggle">Send</md-button>
                    </form>

            </md-content>
        </md-tab>
    </md-tabs>
</md-content>

json:
  {
    "status": 200,
    "msg": "user details",
    "devMsg": "token expired.",
    "data": {
        "img": "https://image.freepik.com/free-icon/user-image-with-black-background_318-34564.png",
        "name": "xyz",
        "email": "xyz@gmail.com",
        "employmentType": "option2",
        "phoneNumber": "9876543210",
        "location": "Hyderbad",
        "yearsOfExperiance": 5,
        "organization": "abc"
    }
}

Here $ctrl.oUserDetails is binding as {} instead of that response.

A: I guess, the issue is because of using 'this' inside callback function.
Here:
mainService.fnGerUserDetails().then(function(response) {
                this.oUserDetails = response;// here 'this' is callback function
                console.log(this.oUserDetails); //response
          }

So, this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables.
Try this.
function tabComponentCtrl(mainService) {
             var that = this;
            this.emailPattern = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
            this.phNumberPattern = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
            this.namePattern = /^[a-zA-Z ]{1,15}$/;
            this.aEmployeeTypes = ["option1", "option2", "option3", "xyz", "abc", "lmn"];
            this.toggle = true;
            that.oUserDetails = {};
            /* for getting json data*/
            mainService.fnGerUserDetails().then(function(response) {
            that.oUserDetails = response; // assigning response to new variable.

          }, function(response) {
                alert('error')
            });

            console.log(that.oUserDetails); //{}
            /*  for updating data to read only form*/
            this.fnSendData = function() {
                this.toggle = true;
            };
        }

Edit:
Using ES6 syntax:
mainService.fnGerUserDetails().then((response)=> {
                this.oUserDetails = response;
                console.log(this.oUserDetails); //response
          }


text:
Q: Solution to Diffusion Equation in similar (but slightly different) situations On an old PDE exam I'm looking through for my finals, a multiple-part question comes as:

(a) Solve the diffusion equation with mixed Neumann-Dirichlet BC's:
  \begin{align}
&u_t=u_{xx}, \quad 0<x<\frac{1}{2}, \quad t>0\\
&u(0,t)=0\\
&u_x\left(\frac{1}{2},t\right)=0\\
&u(x,0)=\begin{cases}0\quad \text{for } 0 < x<\frac{1}{4}\\
1 \quad \text{for }\frac{1}{4}<x<\frac{1}{2}\end{cases}
\end{align}

This was fairly standard (but quite tedious), I believe the correct solution is:
$$\Large{u(x,t) = \frac{2\sqrt{2}}{\pi}\sum_{n=1}^{\infty} \frac{(-1)^{\lfloor\frac{n}{2}\rfloor} }{2n-1} \sin((2n-1)\pi x)e^{-(2n-1)^2\pi^2t}}$$

(b) Explain (without redoing any computations) why the same function $u(x, t)$ found in part (a) also solves this equation with Dirichlet BCs only:
  \begin{align}
u_t=u_{xx}, \quad 0<x<1, \quad t>0\\
u(0,t)=u(1,t)=0\\
u(x,0)=\begin{cases}1\quad \text{for } \frac{1}{4} < x<\frac{3}{4}\\
0 \quad \text{otherwise}\end{cases}
\end{align}

I haven't been to explain this as thoroughly as I'd like to, but the only part in the solution of (a) that depends on $x$ is the $\sin$ function. And on the interval $(0,\pi)$, $\sin$ is symmetric about $\frac{\pi}{2}$, then similarly our function will be dominated by the first term when $n=1$ and hence will attain a maximum when $\sin(\pi x)$ reaches its maximum and hence $x=\frac{1}{2}$. So our fourier series will be symmetric about $\frac{1}{2}$ on the interval $\left(\frac{1}{4} ,\frac{3}{4}\right)$ ?

(c) Now solve the same equation as in part (b) with an inhomogenous Dirichlet BC:
  \begin{align}
&u_t=u_{xx}, \quad 0<x<1, \quad t>0\\
&u(0,t)=0\\
&u(1,t)=1\\
&u(x,0)=\begin{cases}1\quad \text{for } \frac{1}{4} < x<\frac{3}{4}\\
0 \quad \text{otherwise}\end{cases}
\end{align}

For this I tried to devise a solution $w(x,t)=u(x,t)-v(x,t)$, which solves the situation
\begin{align}
&w_t=w_{xx}, \quad 0<x<1, \quad t>0\\
&w(0,t)=0\\
&w(1,t)=0\\
&w(x,0)=u(x,0)-v(x,0)
\end{align}
So then $v(x,t)$ solves:
\begin{align}
&v_t=v_{xx}, \quad 0<x<1, \quad t>0\\
&v(0,t)=0\\
&v(1,t)=1\\
\end{align}
To which I took trivially $v(x,t)=x$ causing the initial condition of $w$ to be
$$w(x,0)=\begin{cases}-x \quad 0<x<\frac{1}{4}\\
1-x \quad \frac{1}{4} < x \frac{3}{4} \\
-x \quad \frac{3}{4}<x<1\end{cases}$$
And hence if I find the solution to the PDE involving $w(x,t)$ my final solution should just be $u(x,t)=w(x,t)+x$ (which honestly isn't as simple as it sounds, because the integration to determine the fourier coefficient in the infinite series solution by using the initial condition is quite tedious)?
Does my reasoning on part (b) and (c) seem correct?
Is there a more efficient or elegant way to go about this question ?

A: For (b), notice that the initial condition is the even reflection of the initial condition of (a) through $x=1/2$. So you can look at the original $u$ (defined only on $(0,1/2)$) and then extend it to $(0,1)$ by even reflection through $x=1/2$. That is define $u(1/2+x,t)=u(1/2-x,t)$ for $x \in (0,1/2)$. This gives the Dirichlet condition on the left and right for free. Then you note that actually the original function already provides the formula for this reflection (which I don't think has any particular deep significance).
Now why did the right endpoint condition in the original problem need to be homogeneous Neumann? One way to view that is to notice that the even reflection will only be $C^1$ for $t>0$ with that condition, because the even reflection automatically has the property $u_x(1/2^-,t)=-u_x(1/2^+,t)$.
Regarding (c) I don't really see any better way than yours. The requisite integrals can be done, though.


text:
Q: Jenkins artifactory maven step fails silently using maven assembly plugin (Artifactory plugin 3.5.0) I'm having problems building jar-with-dependencies using the Jenkins Artifactory plugin, which succeeds in other maven environments (Netbeans, Eclipse). I resolved an initial out-of-memory problem and two artifacts that weren't visible to the Artifactory mirror, and the log appears to show all of the dependencies being found and downloaded as expected. However, after the final dependency loads, the build step fails without any indication as to cause.
Previous builds have succeeded using the maven-jar-plugin, but for this particular integration we also want to build a jar containing all of the dependencies. I'm using maven-assembly-plugin 3.1.0, maven 3.5, Jenkins Artifactory plugin 3.5.0. Is there any way to identify what is causing the failure? The only exception in the log is "Maven build failed", which is not informative. Alternately, is there a better way to assemble a jar containing all dependencies, which has a track record with Artifactory?


text:
Q: Does a universal set really violate Cantor's Theorem over $\mathbf{ZFC}$? It's well known that a universal set, $U$, in ZFC, leads to a number of problems; such as Russell's Paradox when combined with specification. Another popular issue, as cited by Wikipedia is that

Because this power set is a set of sets, it would necessarily be a subset of the set of all sets, provided that both exist. However, this conflicts with Cantor's theorem that the power set of any set (whether infinite or not) always has strictly higher cardinality than the set itself.

This makes immediate sense at first glance. However, this feels more like a proof that the cardinality of a universal set simply behaves unexpectedly. In particular, there is one subtlety of Cantor's Theorem which has raised a question for me: The proof that $\text{card}(X)<\text{card}({\mathcal{P}(X))}$ is a result relying on the assumption that some map $f:X\to\mathcal{P}(X)$ exists at all.
Thus my question is, can such a map really exist for a universal set? If not, then its cardinality cannot be compared with its power set, thus cannot be said to violate Cantor's Theorem.

My work so far:
Of course, I realized this concern of mine can be easily disproven by an example construction of any function $f:U\to \mathcal{P}(U)$. Actually, since $U$ is its own powerset by virtue of containing all of its subsets, we just have to construct some $f:U\to U$. I assume this could be done in theory using replacement, but precisely how is beyond my grasp; hence any insight would be greatly appreciated.

A: Consider $x\mapsto\{x\}$. (Note that in theories like $\mathsf{NF(U)}$ which do have a universal set, this doesn't correspond to a function!)
Incidentally, this doesn't really use replacement at all - Separation is enough (applied to the putative set $U\times\mathcal{P}(U)$). More generally, $\mathsf{ZF}$ (or indeed much less) proves that every set injects into its powerset.


text:
Q: Can someone please explain this definition of a "Random Variable" to me in laymans terms?
The above picture is the definition of a random variable, which I have trouble understanding. Could someone please explain this in laymans' terms?

A: The sample space $\Omega$ models the collection of all possible outcomes of a random experiment.
In practice, though, we often don't care about $\Omega$, for at least two reasons:
1. The outcomes might not be encoded as numbers, and you can't do arithmetic with things that aren't numbers!
For example, suppose you sit around with a group of three friends, John, Paul, and Ringo, sitting in a circle, and you place a bottle in the center, and then you spin it, and whomever the bottle points to has to sing a Beatles song. The easiest way to represent $\Omega$ here is a set of five possible outcomes, based on who the bottle points to:
$$\Omega=\left\{\text{you, John, Paul, Ringo, no one}\right\}$$
These aren't numbers! It doesn't make much sense to talk about the "average value" of the outcome of this experiment, because the outcomes aren't "values" we can "average"!
A random variable is a way of turning possibly non-numerical outcomes into real numbers. For example, consider the random variable $X$ defined on $\Omega$ that maps you to $1$, John to $2$, Paul to $3$, Ringo to $4$, and no one to $5$. It certainly does now make sense to ask for the "average value" of $X$, because at least the values of $X$ are numbers!
2. Even if $\Omega$ is represented as a set of numbers, you might be interested only in a certain aspect of the set $\Omega$: you might not care about all the information it contains.
Go back to the example above. Suppose you just care whether the bottle points to a person who was actually a member of The Beatles. For this problem, you might as well treat John, Paul, and Ringo as a single outcome, and you and no one as another outcome. So you could define the random variable $Y$ that maps John, Paul, and Ringo to $1$ but you and no one to $0$. Asking for the probability that $P(Y=1)$, for example, is then just code for asking for the probability that the bottle points to someone who was in the Beatles.

A: As the definition states, a random variable is a function whose codomain is real numbers. For instance, consider the sample space $\Omega = [0,1]$, and the function $X(\omega)$ defined as follows:
$$X(\omega) = \begin{cases}
  1, & 0 \leq \omega < 1/6 \\
  2, & 1/6 \leq \omega < 2/6 \\
  3, & 2/6 \leq \omega < 3/6 \\
  4, & 3/6 \leq \omega < 4/6 \\
  5, & 4/6 \leq \omega < 5/6 \\
  6, & 5/6 \leq \omega \leq 1.
\end{cases}$$
It's a function in the ordinary sense; you tell me an input in the domain (such as $0.3$) and I can give you an output (such as $2$). You could graph this, if you wanted, and it would be a boring step function on the interval $[0,1]$.
Where this becomes meaningful is when we equip $[0,1]$ with a probability measure $\mathbb P$. Intuitively, we will give up control over the inputs, and we will instead let Tyche, goddess of fortune, choose the input. She will choose the inputs according to the measure $\mathbb P$. So if we (for instance) put the ordinary Borel measure on $[0,1]$ with the Borel $\sigma$-algebra, then she will choose something in the interval $[1/2, 1]$ half the time, she will very commonly choose something in the interval $[0.1, 0.9]$, she will rarely choose something in the interval $[0, 0.001]$, and so on. Notice that with this framing, you can now see $X$ as a die roll, because it will be each of $\{1, \dots, 6\}$ with probability $1/6$.
After a particular $\omega$ is chosen, we plug it into $X$, and the output $X(\omega)$ is the realization of the random variable. Intuitively, we ask Tyche to choose an $\omega$, so she chooses $\omega = 0.953817$, which makes $X(\omega) = 6$, corresponding to rolling a die and having it land on $6$.
What makes it a random variable is the fact that it is rarely evaluated on particular inputs. Usually, all we do is talk about distributions, meaning we focus on questions of the form, "What is the measure (probability) of the subset of $\Omega$ that would cause $X$ to map onto the set $S$?" Generally, we just use a shorthand $\mathbb P(X \in S)$ for this. In the above example, if $S = \{3, 4\}$, then the collection of $\Omega$ that would cause $X$ to map there is $[2/6, 4/6)$, which has measure $2/6$. This is why we say the probability of rolling a $3$ or $4$ is $2/6$.
A final note: Notice that $\Omega$ wasn't actually that important at all. What if I'd used the sample space $\Omega = \{1, 2, 3, 4, 5, 6\}$ itself, with a uniform probability measure (i.e. $\mathbb P(a) = 1/6$ for each $a$), and $X(\omega) = \omega$? Suddenly I'd have a function that functionally does the exact same thing as the first example, meaning that in some very real sense, it's essentially the same random variable.


text:
Q: Bootstrap modal enable background I want my bootstrap modal be open but the page in the background still to be clickable.
There are a few solutions available on the web and stackoverflow (like How do I make the background of a modal clickable) which I tried but I could not get it to work. I'm working with Firefox and IE11.
What I try to achieve: Have a button at the side of the page that opens the modal, do stuff with model content, close modal either with click on button in header or with click on button that opened the modal.
There is a working Bootply example where I try to adapt stuff from, without much success so far.
This is how far I've got:
Modal
(the html below gets generated in javascript, I just give you the output for better readability)

                     <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                    <button type="button" class="btn btn-success " id="submitButton">Submit</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal" >Cancel</button>

Javascript
var modal = $('#bootstrapModal');
$('.modal-backdrop', modal).css('display', 'none');
$('.modal-dialog',modal).css('pointer-events', 'none');
$('.modal-content',modal).css('pointer-events', 'all',);

$(modal).modal('show');

What I get is a modal with no backdrop but the possibility to interact with the background (background looks like it's active, but it's not). I get the same effect with
$(modal).modal({backdrop: 'static', keyboard: false});

or when replacing 'static' in backdrop with false.
Any ideas?

A: You have to change/override the .modal class. When your window is open, if you inspect the background with your web inspector, you will see everything is contained in a div with the classes: modal, fade and in.
The "modal" class has the following css properties, which sets it to cover the whole screen, making your site unclickable.
.modal {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1050;
    display: none;
    overflow: hidden;
    -webkit-overflow-scrolling: touch;
    outline: 0;
}

You would have to remove the fixed property or modify the top,right,bottom and left properties. However, if you removed the fixed property, you will not be able to use the z-index property, which gives your pop-up the overlay effect.

A: if I understand the problem you must put div behind the model and give it full width and height of page


text:
Q: programmatically adding "matlab function" block to simuliink can anyone tell me how to add the "MATLAB Function" block to a simulink model which I am constructing programmatically? Once I add it, I will also need to know how to modify the code, which doesn't seem to be hiding inside any of the parameters I get from get_param(my_fcn_block,'ObjectParameters').
As a workaround I'm currently saving a customised block to my library and inserting this with add_block('my_lib/my_fcn_block','my_fcn_block')


text:
Q: CSS Built-In Content Not Working I have a slideshow in my website and I wanted to use the cool looking content built-in with CSS. I am pretty sure my code is right, but for some reason, the arrows show up as boxes. I don't know what is happening. Here is my code:

.slider .nav-next:before,
.slider .nav-previous:before {
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  text-transform: none !important;
}

.slider .nav-next:before,
.slider .nav-previous:before {
  position: relative;
}

.slider .nav-next {
  right: 0;
}

.slider .nav-next:before {
  content: '\f105';
  right: -0.05em;
}

.slider .nav-previous {
  left: 0;
}

.slider .nav-previous:before {
  content: '\f104';
  left: -0.05em;
}

A: Maybe the problem is that in your HTML you are using div class = "slide" and in your CSS you are editing the style of .slider {... try editing the div class's on your HTML to slider and see if that works.

A: Why don't you just include fontawesome cdn in your hrml head an then use this inside  tags.

You are getting boxes instead of arrows because they are not been referenced in the right way.


text:
Q: Using poisson regression for continuous data? Can the poisson distribution be used to analyze continuous data as well as discrete data?
I have a few data sets where response variables are continuous, but resemble a poisson distribution rather than a normal distribution. However, the poisson distribution is a discrete distribution and is usually concerned with numbers or counts.

A: If you're talking about using a Poisson response in a generalized linear model, then yes, if you are willing to make the assumption that the variance of each observation is equal to its mean.
If you don't want to do that, another alternative may be to transform the response (e.g. take logs).

A: The key assumption of a generalized linear model that's relevant here is the relationship between the variance and mean of the response, given the values of the predictors. When you specify a Poisson distribution, what this implies is that you are assuming the conditional variance is equal to the conditional mean.* The actual shape of the distribution doesn't matter as much: it could be Poisson, or gamma, or normal, or anything else as long as that mean-variance relationship holds.
* You can relax the assumption that the variance equals the mean to one of proportionality, and still usually get good results.


text:
Q: How do you re-order months in the x-axis for ggplot (R Studio)? I am trying to plot a line chart using ggplot but I can't seem to get the months in the x-axis in chronological order instead of alphabetical. Any help is greatly appreciated. This is my current code:
df <- data.frame(Months=c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"),
                Attacks=c(49, 70, 49, 44, 53, 35, 33, 36, 47, 40, 44, 32))

ggplot(data=df, aes(x=Months, y=Attacks, group=1)) +
  geom_line()+
  geom_point()

A: The answer with ggplot2 is almost always factor.
In this case, all of the months are explicitly as listed in one of R's base datasets, month.name:
### validate my assumption *here*
all(df$Months %in% month.name)
# [1] TRUE

### convert to a factor, order defined by `month.name`
df$Months <- factor(df$Months, levels=month.name)


text:
Q: Undefined variable in OpenCart i got alot of these messages
Notice: Undefined variable: config_facontact_address in /home/oclasico/public_html/catalog/view/theme/shoppa/template/common/footer.tpl on line 50
i already seen this answer
Undefined variable (opencart)
, and i tried to do it , but i didn`t find the code to replace :(
and here is my footer.tpl  line 50 look like
<?php if ($config_facontact_address) { ?>

<?php echo $config_facontact_address; ?>

             <?php } ?>

my OpenCart Version 1.5.4
thanks

A: variable $config_facontact_address is not set,
to avoid this error use if(isset($config_facontact_address))

A: The reason why it's undefined is because it hasn't been set in the controller file first.
Opencart uses the MVC architecture, varibles are defined in the Controller, then used within the Template / View files. For this reason, it will always evaluate false using isset()
The code missing from the controller file (located: catalog/controller/common/footer.php) would be:
    $this->data['config_facontact_address'] = $this->config->get('config_facontact_address');

If your not comfortable editing the controller, then you can replace your problem code with this:
    <?php if ($this->config->get('config_facontact_address')) { ?>

<?php echo $this->config->get('config_facontact_address'); ?>

    <?php } ?>


text:
Q: Comparing 2 objects of the same class (overriding == operator) c++ I'm new to c++ (coming from Java and C#), and I'm trying to override the == operator in one of my classes so I can see if I have 2 object that have the same value for a given property.  I've been doing a bunch of googling and trying to make something that works.  What I need is for the == operator to return TRUE when 2 objects have the same _name text.
Here's the header file:
//CCity.h -- city class interface
#ifndef CCity_H
#define CCity_H

#include <string>

class CCity
{
friend bool operator ==(CCity& a,  CCity& b)
{
    bool rVal = false;
    if (!(a._name.compare(b._name)))
        rVal = true;
    return rVal;
}
private:
    std::string _name;
    double _x; //need high precision for coordinates.
    double _y;
public:
    CCity (std::string, double, double); //Constructor
    ~CCity (); //Destructor
    std::string GetName();
    double GetLongitude();
    double GetLatitude();
    std::string ToString();
};
#endif

In my main() method:
    CCity *cit1 = new CCity("bob", 1, 1);
    CCity *cit2 = new CCity("bob", 2, 2);
    cout<< "Comparing 2 cities:\n";
    if (&cit1 == &cit2)
        cout<< "They are the same \n";
    else
        cout << "They are different \n";
    delete cit1;
    delete cit2;

The problem is that my code in the friend bool operator == block never gets executed.  I feel like I'm doing something wrong with either how I'm declaring that operator, or how I'm using it.

A: & takes the address of (you're comparing pointers), when really you want to dereference using *:
if (*cit1 == *cit2)
    cout<< "They are the same \n";

Anyway, there is absolutely no point to using pointers here, let alone dumb ones.
Here's how it would look without them (the proper way):
CCity cit1("bob", 1, 1);
CCity cit2("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (cit1 == cit2)
    cout<< "They are the same \n";
else
    cout << "They are different \n";

Also, as WhozCraig mentions, consider using const-ref parameters for your operator== function since it shouldn't modify the arguments.

A: With this code:
CCity *cit1 = new CCity("bob", 1, 1);
CCity *cit2 = new CCity("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (&cit1 == &cit2)
    cout<< "They are the same \n";
else
    cout << "They are different \n";

You are comparing the pointers to the pointers to the CCity instances.
You want something like this:
CCity *cit1 = new CCity("bob", 1, 1);
CCity *cit2 = new CCity("bob", 2, 2);
cout<< "Comparing 2 cities:\n";
if (*cit1 == *cit2)
    cout<< "They are the same \n";
else
    cout << "They are different \n";


text:
Q: Corrupted MBR, MBR repair does not recognise Alright here's how I got to this point.
I tried to partition my external drive so that I could install multiple OS's on it, 3 linux distros, 1 being ubuntu, and a partition for windows.
So I used Gparted and the drives came out fine according to it, but when I booted into windows to check from their it showed most of them as raw, so thinking something went wrong I decided to boot into Gparted again and just create a new partition table and start making new partitions again. Now after I created the new partition table all things just started going to hell and I finally realized I somehow screwed up the MBR.
Now the drive isn't recognized by Gparted half the time and it is unable to do anything to it.
So one person recommended I use MBR Repair to repair the MBR so I said sure, downloaded it and booted into it, and it recognized all my drives but the one with the corrupt mbr.
I've read you can manually repair the MBR and there are a few other tools that may be slightly better than MBR Repair but I figured I'd come here for a sound opinion.
I also read something about somebody using the same make drive to copy it's mbr and just replace the corrupted drives mbr, which makes me wonder, since I have ; Seagate 500 Gig Goflex (Corrupted MBR), Seagate 500 Gig desktop FreeAgent (Fine) and a Seagate 250 Gig Portable Expansion drive (Fine).

A: I don't think anything was wrong with your MBR or your drive when the newly created partitions showed up as raw. I'm afraid I don't know why it sometimes can't be selected by the drop down menu in gparted. Some background may help you understand what should be happening, however.
First: the MBR. For an external drive the MBR is only a container for the primary partition table. That table takes up most of the last 64 bytes of the MBR, which is itself the first 512 bytes of data on the drive.
For a bootable drive the MBR contains code to load the beginning of grub, or to load the beginning of the first bootable partition (e.g. Windows or DOS). The latter is usually pretty interchangeable and you can use the Windows utilities to replace a vanilla one for that matter. If the drive needs something special there, however, it could use a special manufacturer provided MBR. For recent drives that's probably pretty unusual.
When you used gparted you specified a type for each partition. You should make sure that those are correct.
The partitions are raw until you create file systems on them. They can be Ext 3, for Unix, or NTFS or a version of FAT for Windows. For Ubuntu this is usually done by the Ubuntu installer. gparted wrote a new primary partition table at the end of the external disks MBR, and maybe wrote some other partition information elsewhere if you defined any external partitions. The Ubuntu installer will fill the partitions you tell it to with the file systems you tell it to create, wiping out any data there. Then they will no longer be raw (though the swap one will be).
When installing Ubuntu the system will also want to install GRUB2 to produce a boot window to select what system to boot. By default this goes on the primary disk (the one the system boots from). This changes the code in the first part of the MBR on that drive and installs Grub2 on some (usually) free space between the MBR and the end of the first track. (The MBR is the first sector of the first track of a drive).
Grub could also be installed on the MBR on secondary disk if you can tell your BIOS to boot from there.
It can also be installed into partitions on the secondary disk. If you do that you need to be sure the code in the MBR is good, the one installed by Windows would work fine. The partition with Grub installed would have to be marked as the bootable one.
When you are booting Windows, Grub finds the partition it is on and then loads the first sector of its partition, just like the original MBR did. When booting a Linux kernel Grub actually loads the whole kernel and starts it up.
Since the primary partition table takes up most of the last 64 of the last 66 bytes of the MBR you can't simply use a sector copy to replace it without wiping out your partition table. If you've done that, however, you should be able to use gparted to recreate it. gparted shouldn't wipe out the code part of the MBR in any case.

A: Copying an MBR from One Drive to Another
This will wipe out the partition information, and therfore all of the information, on the target drive. If, by chance, the whole target drive contains a file system (the target drive is unpartitioned but formatted) it will wipe out that file system. Don't do this if you have any doubts and even then be sure you specify the drive names correctly.
If you want to try to copy an MBR from one drive to another, say from /dev/hda to /dev/sga here's one way:

*

*Make sure the drive itself, and any partitions on it, are unmounted. You can use the file folder right below the Window Dash button to see what is mounted and unmount anything that is mounted. It's in the sidebar under Devices on the top left. Click on the little eject button to unmount. If anything is mounted on the target drive I wouldn't expect to be able to write to the MBR using the method below, with an MBR recovery tool, or with gparted. This might be a good time to see if gparted can access the drive reliably.

*Open a terminal window. Enter the mount command without arguments to display everything mounted to be doubly sure nothing is mounted on the target drive.

*Enter a command similar to sudo dd if=/dev/sda of=/dev/sga bs=512 count=1, substituting /dev/sda with the source drive and /dev/sga with the target drive. This should copy the first sector of of the first drive to the first sector of the second. if= specifies the source and of= specifies the output.

A: The MBR is not the problem since you created a fresh one with gparted already, and even if it were wrong, would not make the whole drive not show up.  Either there is a problem with the drive itself or the connection to it.  Open the disk utility and run the SMART diagnostics on the drive.


text:
Q: fit mapPanel in tabPanel I use extjs4.1 with geoext2 in my web app.
I want to load mapPanel to tabPanel via ajax and it fill tabPanel height and width.
If i set mapPanel height and width i can see it in tabPanel but it can't fill tabPanel because i set it height and width.Following code:
mapPanel = Ext.create("GeoExt.panel.Map", {
            renderTo: "mappanel",
            height: 575,
            width: 1124,
            map:map,
            zoom: 11,
            tbar : toolbar
        });
var tabs = Ext.create('Ext.tab.Panel', {
            region: 'center', // a center region is ALWAYS required for border layout
            deferredRender: false,
            activeTab: 0,     // first tab initially active
            items: [{
                title: 'History',
                autoScroll: true
            }, {
                title: 'Center Panel',
                autoScroll: true
            }]
        });

I insert MapPanel to tabPanel when user click on grid column that has icon via following code.
var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        columnLines: true,
        columns: [
            {
                menuDisabled: true,
                sortable: false,
                xtype: 'actioncolumn',
                width: 20,
                items: [{
                    icon   : '<?php echo Yii::app()->baseUrl.'/images/icons/show.png';?>',
                    tooltip: 'Show Map',
                    handler: function(grid, rowIndex, colIndex) {
                        var rec = store.getAt(rowIndex);
                        var jsonData = Ext.encode(store.proxy.reader.jsonData);
                        tabs.remove(tabs.getComponent(2));
                        tabs.insert(2,{
                            title:'Map',
                            layout: 'fit',
                            loader: {
                                scripts: true,
                                autoLoad :true,
                                params:{
                                    history:jsonData,
                                    index:rowIndex
                                },

                                failure : function(){
                                    alert('failed');
                                },
                                url: '<?php echo Yii::app()->createUrl('MapWidget/HistoryMap');?>'

                            }
                        });
                        tabs.setActiveTab(2);
                        tabs.doLayout();
                       }
                }]
            },
...

But when i clean height and width in mapPanel options i can't see it in tabPanel!
How can i load mapPanel to tabPanel to fill it's content?

A: From the docs

Do not use this option if the Component is to be a child item of a
  Container. It is the responsibility of the Container's layout manager
  to render and manage its child items.

Here's some example code for loading components remotely in the correct way: http://dev.sencha.com/deploy/ext-4.1.0-gpl/examples/component-loader/component-loader.html


text:
Q: Duvida sobre fechamento do $ionicLoading.hide() Meu problema é o seguinte. Estou recebendo um json de um webservice e fazendo insert ou update em um banco sqlite no dispositivo uso o $ionicLoading.show() ao clicar no botão e o mesmo fecha quando acaba a requisição com o servidor. Só que devido ser muitos dados o processamento no banco continua e eu queria fechar o loading somente quando acabar o processamento de dados no banco. Alguém teria alguma ideia do que fazer ?

A: Você poderia chamar o dismiss() do loading apenas no retorno da chamada do serviço?
Por exemplo:

 let loading = this.loadingController.create({
        content : "Loading..."
    });
loading.present();

service.getServico(items => {
          loading.dismiss();
        }
  });