14 decembrie 2014

Design of OO language

Ultima prezentare din #Principles of Programming Languages .
Design & implementare.

Ca design, limbajul suporta crearea obiectelor cu campuri si metode, accesarea lor din afara , precum si mostenire de clase. Mai multe in slide-urile de mai jos.


Implementare: aici (cod, teste, Readme)
-----

In acelasi timp, mi-am adus aminte de un proiect la #Limbaje formale si automate, care presupune parsarea si validarea unui limbaj de programare (aici), folosind Flex. Limbajul are propria sintaxa care se bazeaza pe folosirea tab-urilor. Programul de parsare se ocupa de gestiunea variabilelor, recunoasterea tipurilor de instructiune, etc.

09 decembrie 2014

Eopl3: chapter 9.4 solution to exercise 9.6

> lang.scm__________________________________________________________

        (expression
            ("instanceof" expression identifier)
        instance-exp)

> interp.scm________________________________________________________

        (instance-exp (expr className)
            (let ((hisClass (object->class-name (value-of expr env))))
                (if (eq? className hisClass) (bool-val #t) (bool-val #f))))

_______________________Test:______________________________________ __

class c1 extends object
    field x
    field y
    method initialize ()
        begin
         set x = 11;
         set y = 12
        end
    method m1 ()
        -(x,1)

class c2 extends object
    field x
    method initialize ()
        begin
         set x = 0
        end

let o2 = new c2() in instanceof o2 c1    ;; #f

;; let o2 = new c1() in instanceof o2 c1    ;; #t


alte ex rezolvate de altii: aici

Eopl3: chapter 9.4 solution to exercise 9.16

Adding overloading of methods.
Idea: each method name is stored as methodName*nrParam (thus there can be many possible methods with the same name but different number of parameters.

> classes.scm______________________________________________________

;; when saving a method, *nrParam is appended to method-name

  (define method-decls->method-env
    (lambda (m-decls super-name field-names)
      (map
        (lambda (m-decl) ;; ex 9.16
          (cases method-decl m-decl
            (a-method-decl (method-name vars body)
                ;; append *nrParam to the method-name
                (let ((newMethodName (string-append (symbol->string method-name) "*" (number->string (length vars)))))
                  (list (string->symbol newMethodName)
                    (a-method vars body super-name field-names))))))
        m-decls)))


> interp.scm _______________________________________________________

;; initialize will called as initialize*0 or otherwise, depending on how the object is instantiated from class

        (new-object-exp (class-name rands)
          (let ((args (values-of-exps rands env))
                (obj (new-object class-name)))
            (apply-method
    (find-method class-name (string->symbol (string-append (symbol->string 'initialize) "*" (number->string (length rands)))))
              obj
              args)
            obj))

;; regular method call also will point to the method with the nr of parameters used for call

        (method-call-exp (obj-exp method-name rands)
          (let ((args (values-of-exps rands env))
                (obj (value-of obj-exp env))
                (nrParam (length rands)))
            (apply-method
              (find-method (object->class-name obj)
                (string->symbol(string-append (symbol->string method-name) "*" (number->string nrParam))))
              obj
              args)))

Example of test:___________________________________________________

class c1 extends object
    field x
    field y
    method initialize () % before it would save only this init, ignoring the 2nd one, result was 10
        begin
         set x = 11;
         set y = 12
        end
    method initialize (param)
        begin
         set x = param;
         set y = 12
        end
    method m1 ()
        -(x,1)
    method m1 (param)
        -(x,param)

let o2 = new c1(7) in send o2 m1(4)        % 3, overloading

Eopl3: chapter 9.4 solution to exercise 9.13

Adding final methods (which cannot be overridden).
--------------------------------------------
> lang.scm_____________________________________________________________

        (method-decl
            ("final" "method" identifier
                  "("  (separated-list identifier ",") ")" ; method formals
              expression)
        a-method-decl-final)

;; So we created a new type of method-decl, called a-method-decl-final

> classes.scm___________________________________________________________

;; First we add a new field for the a-method data structure

  (define-datatype method method?
    (a-method
      (vars (list-of symbol?))
      (body expression?)
      (super-name symbol?)
      (field-names (list-of symbol?))
      (isFinal boolean?)
    ))

;; We check for method-decl in 2 cases (regular one + the one added above).
;; In the first case, in case the super-class is not object, we check if the method already existed
;; If yes, we check its status: final or not. If final, don't override, else override;
;; when we override, we set the final field to #f
;; In the 2nd case, same steps basically, but when we override, we set the final field to #t (final)

  (define method-decls->method-env
    (lambda (m-decls super-name field-names)
      (map
        (lambda (m-decl)
          (cases method-decl m-decl
            (a-method-decl (method-name vars body)        ;; create a non-final method
                (if (eq? super-name 'object) (list method-name (a-method vars body super-name field-names #f))
                ;; else check if it didnt exist before in the super class, as a final
                (let ((possibleMethod (find-method super-name method-name)))
                    (if (eq? possibleMethod #f)
                        (list method-name (a-method vars body super-name field-names #f))    ;;  not found before, create the method
                        ;; found before so check if it's final
                        (cases method possibleMethod (a-method (vars body super fnames isFinal)   
                            (if (eq? isFinal #t)
                                (list 'xxx (a-method vars body super-name field-names #f))    ;; make a dummy, don't overwrite
                                (list method-name (a-method vars body super-name field-names #f))    ;; else overwrite
                            )))
                ))))
            (a-method-decl-final (method-name vars body)                ;; final method
                (if (eq? super-name 'object) (list method-name (a-method vars body super-name field-names #t))
                ;; else check if it didnt exist before in the super class, as a final
                (let ((possibleMethod (find-method super-name method-name)))
                    (if (eq? possibleMethod #f)
                        (list method-name (a-method vars body super-name field-names #t))    ;;  not found before, create the method
                        ;; found before so check if it's final
                        (cases method possibleMethod (a-method (vars body super fnames isFinal)   
                            (if (eq? isFinal #t)
                                (list 'xxx (a-method vars body super-name field-names #t))    ;; make a dummy, don't overwrite
                                (list method-name (a-method vars body super-name field-names #t))    ;; else overwrite
                            )))
                )))
        )))
        m-decls)))

;; a small change in find-method

  (define find-method
    (lambda (c-name name)
      (let ((m-env (class->method-env (lookup-class c-name))))
        (let ((maybe-pair (assq name m-env)))
          (if (pair? maybe-pair) (cadr maybe-pair)
            (begin
                (report-method-not-found name) #f)
    ;; ex. 9.13
    )))))


> interp.scm____________________________________________________________

;; a small change to accommodate the new field isFinal

  (define apply-method                   
    (lambda (m self args)
      (cases method m
        (a-method (vars body super-name field-names isFinal) ;; ex 9.13
          (value-of body
            (extend-env vars (map newref args)
              (extend-env-with-self-and-super
                self super-name
                (extend-env field-names (object->fields self)
                  (empty-env)))))))))


__________           _     Test... exemplu_____                ________________

class c1 extends object
    field x
    field y
    method initialize ()
        begin
         set x = 11;
         set y = 12
        end
    final method m1 (a)
        -(x,a)

class c2 extends c1
    method initialize ()
        begin
         super initialize()
        end
    method m1 (a)
        -(a,1)

let o2 = new c2() in send o2 m1(55)        % m1 cannot be overwritten, should write -44

Cursuri noi online care mi-au atras atentia

01 decembrie 2014

ssh fara parola (config & debug)

Presupunem ca avem 2 calc, x1@hostx si y1@hosty.

Pt hostx: in ~/.ssh stergem continutul (daca exista) din fisierele authorized_keys & known_hosts, pentru a o lua de la capat. Daca x1 != y1, se face acelasi lucru si pt hosty.

Rulam pe hostx:
su - x1
ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa

Se transfera fisierul id_dsa.pub pe hosty (daca x1 != y1) si se pune continutul in authorized_keys. Daca x1 == y1, atunci se executa pe oricare dintre hostx sau
hosty:
cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys

Rulam pe hosty:
su -y1
ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa_y1

Idem ca mai sus (transferul id_dsa_y1.pub pe hostx), si se executa pe hostx ceva asemanator cu:
cat ~/.ssh/id_dsa_y1.pub >> ~/.ssh/authorized_keys

!! id_dsa_y1 nu trebuie suprascris peste id_dsa, daca x1 == x2

Acum x1 se poate conecta la y1 fara parola, cu:
ssh y1@hosty
Si vice-versa.

Debug:
* verificare permisiuni pe x1 si y1:
- home directory, directorul .ssh si fisierul authorized_keys sa poata fi scrise (w) doar de owner; citite cel putin de owner (r);
- cheile private trebuie sa poate fi citite si scrise doar de owner, iar cheile publice trebuie sa poata sa fie citite si din exterior (non-owner)
- permisiunile se modifica cu: chmod [value] [fisier]

* daca tot nu merge fara parola, se pot activa mesajele in ssh (verbose) prin:
ssh -vv y1@hosty
Acestea explica mecanismul de conectare si ce anume nu a mers.

09 noiembrie 2014

Grading situation

Cand si studentii s-au plictisit de atatea instructiuni si detalii de tinut cont pentru tema... 
Cand in sfarsit inteleg durerea asistentului care trebuie sa verifice de 30 ori aceleasi si aceleasi instructiuni....
Un student trimite o rezolvare impecabila cu urmatoarele comentarii:
______________________________

# Description: Today we'll be reading a data file of information on the sales of a movie before printing out the information in a tedious-for-the-programmer fashion
# for your viewing pleasure. Afterwards we kick things over to Mike and Stan on "Who Bought the Most Tickets", America's #1 Show. Hopefully I won't get docked.

------------------ urmeaza codul sursa, dupa care:

#Make it look nicer.......or less jumbled since technically that print statement up there already made it look nicer
print()
#I suppose you could say more more nicer, or aesthetic improvement if you want a reason to use the word aesthetic.
print()
#I don't see why you wouldn't. Say it once and see if just doesn't stick....aesthetic.
#Yes I realize the previous 3 comments and this one explaining those 3 comments have little to do with actual code.


#And this one here isn't even commenting on anything. It's just here......floating along...like clouds.

------------------ urmeaza obisnuitul print al rezultatelor -----------
------------------ sau nu:

#I hope I don't get docked for this, but here goes:
print("Statistics (Game Show in this case)")
print("_____________________________________________________________________________________________________________")
print("Total tickets sold: ", total)
print()
print('Stan: "Ladies and Gentlemen, it has been an excitig show so far. Now to announce our winners!!"')
print()
print('Mike: "First up, our award for the most purchased adult tickets goes to: ', maxAdult, 'with a total of', maxAdultTickets,'"')
print()
print('Stan: "And last, but definitely not least, our award for the most purchased child tickets goes to: "')
print('Mike: "Drumroll please!!!!"')
print()
print('Stan: "Ladies and gentlemen!!! YOUR NEW LIGHTWEIGHT HEAVYWEIGHT ADULT CHILDRENS CHAMP OF THE WORLD!!! THE ONE AND ONLY TRUE KING. THE GLORIOUS..."')
print()
print('Mike: "Umm...Stan?"')
print()
print('Stan: "Hmm?, Oh yes, congratulations', maxChild, 'for purchasing the most child tickets with a total of', maxChildTickets, '"')
print()
print('Mike: "Alright folks, that concludes the series finale of Who Bought the Most Tickets. Goodbye and good riddance"')
print("____________________________________________________________________________________________________________")

-------------------- studentul doreste interactiune criptata:

#I'm curious, and apparently I have so little to do in life that I'm about to make a commented out if statement that may or may not receive a reply.
#From you of course

#if (you read these comments):
    #if (You at least cracked a smile and I got a perfect score):
        #Put "Brilliant!!!" (yes, 3 exclamation points) in the comments when you grade

    #elif (You at least cracked a smile and I got close to a perfect score):
        #Write "So Close!!" (this time 2 exclamation points) in the comments when you grade

    #else:
        #Anything beyond the first two conditions is impossible.

#else:
    #Well then there isn't much point to this else statement now is there


---------------- feedback-ul meu ----------------------------------

+0p: output is correct, aesthetic
-0p: it would be great if you stick only with the relevant stuff to output, I appreciate the sense of humor

--------------- conflictul interior intre dorinta de a pastra lucrurile la obiect si incurajarea spicing up the boring grading time este castigat de primul

29 octombrie 2014

Recursivitate in limbajul PROC (EOPL 3) | Simulating recursivity in PROC language, Eopl3

PROC nu suportă recursivitatea.
Pentru a o simula, se folosește artificiul numit y-combinator și se creează un caz de test  în  tests.scm  pentru fiecare operație dorită.


1) Suma nr. 1 ... N

    (sum-1-to-N
"let p = proc(f) proc(x)
    if zero?(x) then 0 else -(((f f) -(x,1)), -(0,x))
in ((p p) 10)" 55)


2) Numerele Fibonacci:  fibo (N) = fibo (N-1) + fibo(N-2)

    (fibonacci "
let p = proc(f) proc(x)
    if zero?(x) then 0 else if zero?(-(x,1)) then 1 else -( ((f  f) -(x,1)), -(0, ((f f) -(x, 2))))
in ((p p) 10)
    " 55)


3) Înmulțirea a două numere

    (x*y
"let p = proc(f) proc(x) proc(y) proc(z)
    if zero?(z) then x else ((((f f) -(x, -(0,y))) y) -(z, 1))
in ((((p p) 0) 6) 7)" 42)


4) Factorial: N! = 1 * 2 * ... * N

    (factorial
"let multipl = proc(a) proc(b)
    let p = proc(f) proc(x) proc(y) proc(z)
        if zero?(z) then x else ((((f f) -(x, -(0,y))) y) -(z, 1))
    in ((((p p) 0) a) b)
in
    let fun = proc (f) proc(x)
        if zero?(-(x,1)) then 1 else ((multipl x) ((f f) -(x,1)))
    in ((fun fun) 5)" 120)

Extensii pentru limbajul LET | EOPL3 Let language extensions - Stack operations

Constructori:
* stack -> list
* push : expVal x list -> list

Observatori:
* top : list -> expVal
* pop : list -> list
* size : list -> num-val


> lang.scm_________________________________________________
;; the grammar
        (expression    ("stack") stack-exp)
        (expression ("push" expression expression) push-exp)
        (expression ("top" expression) top-exp)
        (expression ("pop" expression) pop-exp)
        (expression ("size" "(" expression ")") size-exp)


> interp.scm_______________________________________________ 
 ;; value-of
        (stack-exp ()
            '())
        (push-exp (exp1 exp2)
            (cons (value-of exp1 env) (value-of exp2 env)))
        (top-exp (exp1)
            (car (value-of exp1 env))   
        )
        (pop-exp (exp1)
            (cdr (value-of exp1 env))
        )
        (size-exp (exp1)
            (num-val (length (value-of exp1 env)))
        )


> tests.scm__________________________________________________

        (stack-1 "top stack" error)
        (stack-2 "top push 3 push 4 stack" 3)
        (stack-3 "pop stack" error)
        (stack-4 "pop push 1 push 2 push zero?(0) stack" (2 #t))
        (stack-5 "size(stack)" 0)
        (stack-6 "size(push 100 stack)" 1)
        (stack-7 "let x=1 in let y=2 in top pop push x push -(x,y) push y stack" -1)

_____________________________________________________________

Extensii pentru limbajul LET | EOPL3 Let language extensions for list: cons, car, cdr, ...

Constructori:
* listagoala -> ListofExpval
* adauga : expVal x ListofExpval -> ListofExpval

Observatori:
* primul : ListofExpval -> expVal
* restul : ListofExpval -> ListofExpval
* e_goala : ListofExpval -> Bool

> lang.scm___________________________________________________
;;; in the grammar
        (expression
            ("lista-goala")
        gol-exp)

        (expression 
            ("adauga" expression "la" expression)
        add-exp)

        (expression
            ("primul" "din" expression)
        car-exp)

        (expression
            ("restul" "din" expression)
        cdr-exp)

        (expression
            ("e-goala" "(" expression ")")
        isempty-exp)

> interp.scm__________________________________________________
;; in value-of 
        (gol-exp ()
            '()
        )

        (add-exp (exp1 exp2)
            (cons (value-of exp1 env) (value-of exp2 env)))

        (car-exp (exp1)
            (car (value-of exp1 env)))

        (cdr-exp (exp1)
            (cdr (value-of exp1 env)))

        (isempty-exp (exp1)
            (bool-val (null? (value-of exp1 env))))

> tests.scm____________________________________________________
        (lista-test1 "adauga 5 la adauga 6 la lista-goala" (5 6))
        (lista-test2 "lista-goala" ())
        (lista-test3 "let x=1 in adauga x la lista-goala" (1))
        (lista-test4 "adauga zero?(1) la adauga 5 la adauga let x = 2 in -(x,1) la lista-goala" (#f 5 1))
        (lista-test5 "e-goala(lista-goala)" #t)
        (lista-test6 "e-goala(adauga 3 la lista-goala)" #f)
        (lista-test7 "primul din let x=1 in adauga x la lista-goala" 1)
        (lista-test8 "restul din adauga zero?(1) la adauga 5 la adauga let x = 2 in -(x,1) la lista-goala" (5 1))

> top.scm______________________________________________________
;;; in sloppy->expval  (for tests.scm)
((list? sloppy-val) (map sloppy->expval sloppy-val))

27 octombrie 2014

Extensii pentru limbajul LET | EOPL3 Let language extensions: RECORD

RECORD
> data-structures.scm
;; in define-datatype
    ; Record
    (record-val
        (record (list-of (list-of symbol?) (list-of expval?)))
    )

;; independent function
    ; record
    (define expval->record (lambda (v)
        (cases expval v
            (record-val (record) record)
            (else (expval-extractor-error 'set v)))))


> lang.scm
; constructor for record
        (expression
            ("record" "{" (separated-list identifier ":" expression ";") "}")
        record-exp)
        ; end Record

;; observer: accessing a record
        (expression
            ("(" identifier "." identifier ")")
        access-exp)


> interp.scm
        ; record
        ; ((id1 id2 id3...) (val1 val2 val3...))
        ; returns the same thing but the members "val" are evaluated
        (record-exp (myids myvals)
              (record-val
                (list myids (map (lambda (myval) (value-of myval env)) myvals))
            )
          )

        ;; access record
        (access-exp (id id_inside)
            (letrec ((myrecord (expval->record (value-of (var-exp id) env)))
                    (myfun (lambda (ids vals)
                        (if (null? ids) "Error"
                            (if (eq? (car ids) id_inside) (car vals)
                            ;else
                            (myfun (cdr ids) (cdr vals)))))))
                    ; in
                    (myfun (car myrecord) (cadr myrecord)))
        )


> top.scm
;; in sloppy->expval
    ; for record ((id1 id2 id3...) (val1 val2 val3...))
    ((and (list? sloppy-val) (not (null? sloppy-val))
        (eq? (length sloppy-val) 2))   
        (record-val (list (car sloppy-val)
            (map (lambda (myelem) (sloppy->expval myelem)) (cadr sloppy-val)))))   
    ; end record


> tests.scm
;; test record
        (rec-test "let x=record{y:10; z:20} in x" ((y z) (10 20)))
        (rec-test2 "let x=record{y:10; z:20} in (x.z)" 20)
        (rec-test3 "zero?(record{y:10; z:20})" error)
        (rec-test4 "let y = record {ab:5; cd:30} in if zero?(2) then (y.ab) else (y.cd)" 30) ; 30 is the sloppy-value!!!

(run "let x=record{y:10; z:20} in (x.a)") ----> gives "Error"

Extensii pentru limbajul LET | EOPL3 Let language extensions: SET

SET
> data-structures.scm
;;; inside define-datatype
    (set-val
        (set (list-of expval?))
    )


;;; independent function
    (define expval->set (lambda (v)
        (cases expval v
            (set-val (set) set)
            (else (expval-extractor-error 'set v)))))


> lang.scm
;;; inside expression
        (expression
            ("set" "{" (separated-list expression ",") "}") 
        set-exp)


> interp.scm
;;; inside value-of
        (set-exp (exp1) ; exp1 is a list of expressions
            ;; the return type should be set-val
            (set-val
                (map (lambda (myexp) (value-of myexp env)) exp1)) ; don't make it concrete value inside the set!
        )


> top.scm
;;; inside sloppy->expval
((list? sloppy-val) (set-val (map sloppy->expval sloppy-val)))

> tests.scm
      (set-test-diff1 "-(set {1,2}, 3)" error)                ; can't extract from a set
      (set-test-diff2 "-(5, set {1,2})" error)
      (set-test-zero "zero?(set{1,2})" error)                ; can't test a set for zero
      (set-test-if1 "if set{1,2} then #t else 2" error)        ; can't test if set
      (set-test-if2 "if zero?(2) then 3 else set {1,2}" (1 2))
      (set-test-if3 "if zero?(0) then set{1,2} else 0" (1 2))
      (test-set-let1 "let id =set {1,2,3} in id" (1 2 3))
      (test-set-let2 "let x=1 in set {x, -(x,1), -(x,2)}" (1 0 -1))
      (test-set-set "set {set {1,2}, 5, zero?(3), if zero?(x) then x else 0, let y=1 in set{y,7}}" 
        ((1 2) 5 #f 0 (1 7))) 



Operații pe SET de numere: Union, Intersect, Membership, isEmpty ...

> lang.scm_______________________________________________________

        ;; member check
        (expression
            ("is" expression "member-of" expression)
        memb-exp)

        ;; is empty
        (expression
            ("empty-set?" "(" expression ")")
        empty-exp)
 

        ;; union
        (expression
            ("union" expression "with" expression)
        union-exp)

        ;; intersection
        (expression
            ("intersect" expression "with" expression)
        inter-exp)



> interp.scm___________________________________________________________

        ;; membership ---- works only for numbers inside of set
        (memb-exp (memb setList)
            (letrec ((mymember (expval->num (value-of memb env)))
                (myset (expval->set (value-of setList env)))
                (getMembership (lambda (memberName set)
                        (if (null? set) (bool-val #f)
                            (if (eq? (expval->num (car set)) memberName) (bool-val #t)
                                (getMembership memberName (cdr set)))))))
                (getMembership mymember myset)))


        ;; check if set is empty
        (empty-exp (setList)
            (if (null? (expval->set (value-of setList env))) (bool-val #t)
                (bool-val #f)))

        ;; union --- set of numbers
        (union-exp (set1 set2)
            (letrec ((s1 (expval->set (value-of set1 env)))
                    (s2 (expval->set (value-of set2 env)))
                    (isMember (lambda (mem mylist)
                        (if (null? mylist) #f (if (eq? (expval->num mem) (expval->num (car mylist))) #t (isMember mem (cdr mylist))))))
                    (getUnion (lambda (se1 se2)
                        (if (null? se2) se1
                            (if (not (isMember (car se2) se1)) (getUnion (cons (car se2) se1) (cdr se2))
                                (getUnion se1 (cdr se2)))))))
            (set-val (getUnion s1 s2))))


        ;; intersection --- works for numbers only
        (inter-exp (set1 set2)
            (letrec ((myset1 (expval->set (value-of set1 env)))
                    (myset2 (expval->set (value-of set2 env)))
                    (isMember (lambda (mem mylist)
                        (if (null? mylist) #f (if (eq? (expval->num mem) (expval->num (car mylist))) #t (isMember mem (cdr mylist))))))
                    (find-intersect (lambda (s1 s2 dummy)      
                        (if (null? s1) dummy    ; else
                            (if (isMember (car s1) s2) (find-intersect (cdr s1) s2 (cons (car s1) dummy))
                                (find-intersect (cdr s1) s2 dummy))))))
            (set-val (find-intersect myset1 myset2 '()))))
 

> tests.scm__________________________________________________________

    (test-member1 "is 2 member-of set {1,2,3}" #t)
    (test-member2 "is 4 member-of set {1,2,3}" #f)
    (test-empty1 "empty-set?(set{2,3,4, set{1,2}})" #f)
    (test-empty2 "empty-set?(set{})" #t)
    (test-union1 "union set{1,2} with set{2,3}" (3 1 2))
    (test-union2 "union set{} with set{2}" (2))
    (test-inter1 "intersect set{1,2} with set{2,3}" (2))
    (test-inter2 "intersect set{0,4,2,1,6,3} with set {9,0,2,10}" (2 0))

26 octombrie 2014

Hadoop - comenzi utile

* formatare HDFS
> hadoop namenode -format

* pornire demoni Hadoop
> start-all.sh

* verificare că demonii merg
> jps 

* copiere fișiere in HDFS 
> hadoop dfs -copyFromLocal /tmp/numeFolder /user/anna/numeFolder

* verificare
> hadoop dfs -ls /user/anna/numeFolder

* ștergere fișier: -rm , folder -rmr

* ieșire din safe mode (dacă nu merge ștergerea pe HDFS)
> hadoop dfsadmin -safemode leave

* rulare job
> hadoop jar hadoop-examples-1.2.1.jar [args]

* copiere rezultat din Hadoop
> hadoop dfs -copyToLocal /user/anna/numeFolder /tmp/numeFolderOut 

* goodbye Hadoop
> stop-all.sh 

16 octombrie 2014

Exercițiu în Scheme: numărarea simbolurilor (numSym)

Define a Scheme procedure "numberSym"
numberSym:  S-List -> N-List
Example:
 (numberSym '(b () (a d) a c a)) => (0 ()  (1 2) 1 3 1)
-----------------------------------------------------------------
Traversarea simplă a unei liste:

(define traversal2 
  (lambda (myList)
    (if (null? myList) 
        '()
        (let ((c (car myList)))
          (cons (if (list? c) (traversal2 c) 'x)
                (traversal2 (cdr myList)))))))

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

Traversare cu numărare:

; returns a list with the same structure as myList and with symbols replaced by index 
; numbers. Also returns the list with all distinct symbols found
(define traversal 
  (lambda (myList distinctList)
    (if (null? myList) 
        (list '() distinctList)
        ; else
        (let ((c (car myList)))
          (if (list? c)
              (letrec ((resultC (traversal c distinctList))
                    (resultR (traversal (cdr myList) (cdr resultC))))
                (list (cons (car resultC) (car resultR)) (cdr resultR)))
              ; else if c is a symbol
              (letrec ((position (getIndexList c distinctList))
                       (resultR (traversal (cdr myList) (cdr position))))
                  (list (cons (car position) (car resultR)) (cdr resultR))))))))

(define numberSym (lambda (myList)
                    (car (traversal myList '()))))

---- funcție auxiliară

; returns the index of element in simpleList (after updating it) AND 
; the updated list with appending element if it's new in simpleList
(define posInList (lambda (element simpleList originalList seed)
  (if (null? simpleList) (list (length originalList) (append originalList (list element)))
      (if (eq? element (car simpleList)) (list seed originalList)
          (posInList element (cdr simpleList) originalList (+ 1 seed))))))

(define getIndexList (lambda (element aList)
     (let ((flatList (flatten aList)))
        (posInList element flatList flatList 0))))

---- teste

(display (numberSym '(b b h b a b a))) ; ((0 0 1 0 2 0 2)
(display "\n")
(display (numberSym '((x m b m y) b))) ; ((0 1 2 1 3) 2)
(display "\n")
(display (numberSym '((f) h () (r t b) (x m b m y) b (c (d))))) ; ((0) 1 () (2 3 4) (5 6 4 6 7) 4 (8 (9)))
(display "\n")

13 octombrie 2014

Coursera: software security class - notițe (0)

Link to class -  începe pe 20 oct.

Overview:
correctness -> computers should do
security -> what computers should not do

Undesired behavior:
- confidentiality (storing some information ...)
- integrity (spyware, delete records)
- availability (unable to access ...)

Exploitation of a vulnerability
- defect sw - incorrect behavior
- flaw : defect in design
- bug : defect in implementation

* considering mis-using cases - edge cases

Sw security -> focus on the code
OS security - cannot control all (ex. DBMS)

Firewall - block traffic from particular hosts or TCP ports
IDS = intrusion detection system - more fine-grained, but can hurt performance

Anti virus scanners - operate on files

03 octombrie 2014

Scheme: o implementare procedurală pentru un obiect Environment

Env : mulțimea tuturor funcțiilor care fac corespondență între un Id și o Valoare

Interfața
Constructori:
empty-env : () -> Env       ( nicio corespondență )
extend-env : Id x Val x Env -> Env      ( adaugă o nouă coresp., a.î. f(Id) = Val )

Observatori:
empty-env? : Env -> Boolean
apply->env : Env x Id -> Val     ( află cât este f(Id) )

Specificații
(empty-env? (empty-env)) = #t
(empty-env? (extend-env id val env)) = #f
(apply->env (empty-env) x) = 'Error
(apply->env (extend-env id val env) x) = val,  dacă x == id
                                                           = (apply->env env x) , altfel

Implementare procedurală
#lang racket

; constructor
(define (empty-env)
  (lambda (obs dummy)
    (cond ((eq? 'empty-env? obs) #t)
          ((eq? 'apply-env obs) 'Error))))

; constructor
(define (extend-env s1 v1 env)
  (lambda (obs s2)
    (cond ((eq? 'empty-env? obs) #f)
          ((eq? 'apply-env obs)
             (cond ((eq? s1 s2) v1)
                   (else (apply-env env s2)))))))

; observers
(define (apply-env env v)
  (env 'apply-env v))

(define (empty-env? env)
  (env 'empty-env? 'dummy))

; some tests
(display (empty-env? (empty-env)))
(display (empty-env? (extend-env 'a 2 (empty-env))))

(display "\n")

(display (apply-env (extend-env 'a 2 (empty-env)) 'a))

26 septembrie 2014

Probleme în Scheme: Bintree

Credeam că nu mă voi mai întâlni niciodată cu limbajul Scheme.... dar se pare că m-am înșelat.
Așadar, acest exercițiu (și mai multe exemple în curând):

A Bintree is defined using the following grammar:
Bintree ::= Int
::= ( Symbol Bintree Bintree )
where Int and Symbol are non-terminals representing an integer and a symbol, respectively.
1) Write the following Scheme procedures. These are constructors for Bintree structures.
interior-node : Symbol x Bintree x Bintree -> Bintree
leaf: Integer -> Bintree
A Bintree is constructed using these two constructor. As for example:
(interior-node 'a (interior-node 'b (leaf 10) (leaf 20)) (leaf 30)) 
generates the Bintree '(a (b 10 20) 30)
2. Write the following Scheme procedures. These are observers for Bintree structures.
interior-node?: Bintree -> Boolean
leaf?: Bintree -> Boolean
interior-node->left : Bintree -> Bintree
interior-node->right: Bintree -> Bintree
interior-node->name: Bintree -> Symbol
leaf->value: Bintree -> Int
The first two are predicates: 
  • " interior-node?" tests whether its argument is an interior node constructed using the procedure "interior-node".
  • "leaf?" tests whether its argument is a leaf node, constructed using the procedure "leaf"
The remaining procedures extract elements from the Bintree structure.
  • "interior-node->left" and "interior-node->right" return the left and right nodes of an interior node. They produce errors if the input is not an interior-node.
  • "interior-node->name" returns the 'symbol' used to construct an interior node, and generates error if any other type of node is given.
  • "leaf->value" returns the integer value used to construct the leaf node. It returns error otherwise.
3) Write a procedure "number-leaves" that takes as input a Bintree and also returns a Bintree. The Bintree it returns is identical to its input, except that in the leaf nodes the value is replaced by a number representing the order of the leaf, from left to right (starting with zero).
number-leaves: Bintree -> Bintree
Example:
(number-leaves (interior-node 'a (interior-node 'b (leaf 55) (leaf 77)) (leaf 11))
will produce a bintree equivalent to the following (interior-node 'a (interior-node 'b (leaf 0) (leaf 1)) (leaf 2))
Soluția mea AICI
fișierul de test AICI 

07 septembrie 2014

Cont nou de email cu Outlook = Big Fuss!!!

Iată ce se întâmplă când îți creezi un cont nou cu Outlook și selectezi din greșeală un an al nașterii care te face minor. Ooops, te anunță că ești minor și că ai nevoie de consimțământul părinților. Ok, am greșit, nu sunt minor, de fapt sunt adult. Ce urmează?

Really? 
Trebuie să-mi dau datele bancare către Microsoft ?! Văd bine?! Cât de prost poate fi cineva încât să parcurgă acest pas ?!
După ce că mi-am dat numele, adresa, data nașterii și nr. de telefon pentru a primi confirmarea pe el (!),  se pare că următorul pas este să trimit datele bancare, pentru a demonstra că sunt adult.

Ok, go back. Sunt tot minor, greșisem mai devreme. 
Chiar trebuie să obțin consimțământul unui părinte, accept. Mă loghez cu celălalt cont de Microsoft și mă pregătesc să citesc sub ce condiții „copilul” meu se poate bucura de acest serviciu minunat numit Outlook.


Apăs bucuroasă YES, făcându-mă deocamdată că nu văd o nouă aberație marca Microsoft. Voi fi taxată cu 50 cenți (taxă de caritate). Un serviciu de email care costă !!!!!!!! - dar orice pt copil, nu? Mai departe.....

Fail. Pentru a demonstra că sunt și un părinte adevărat, trebuie să fiu oficial în aceeași țară cu copilul. Și nu sunt. Părintele are în setările contului ca țară România, copilul minor încearcă să se înregistreze din SUA.
Dar ei nu se uită că totul se petrece de pe același IP, deci sunt „lângă copil” acum?!

Nu înțeleg cine a propus acest registration flow atât de complicat și aberant pentru un simplu serviciu de email, care vorba aia, îl ai în 2 pași de la yahoo sau oricare alt furnizor, cu minim de informații. Who cares about the age, parent consent și așa mai departe, într-o lume virtuală în care oricine poate avea orice căsuță poștală cu orice nume și setare whatsoever?! O lume virtuală care a fost construită pe minciună, dacă se poate numi așa.
Microsoft se dovedește a fi extrem de irealist cu restricțiile pe care le impune și chiar jenant în clipa în care cere informații despre cartea de credit. Câtă nesimțire să ai ca sa dai buzna în felul acesta în viața privată a unei persoane doar pentru un serviciu amarât de email?

Și acum, pentru a finaliza testarea, să urmăm același scenariu de creare a unui cont, cu atenție la data nașterii de data asta.

SURPRIZĂ!!!!

Se pare că m-am jucat destul azi, sau s-au plictisit de mine. Mi-am făcut prea multe conturi azi, nu?? 
Cred e gravă situația.. dar oricum, chiar dacă mergea, îmi pierise cheful de a-mi crea un nou cont cu Outlook.

05 iunie 2014

Facultatea de Automatica si Calculatoare RO



O prezentare despre ce înseamnă Automatică & Calculatoare București, se pare, printre cele mai bune făcute până acum..

26 aprilie 2014

Crawling a site with Goutte (php)

Crawling with redirects: NCBI website for aligning protein - Aceasta este o alternativa la instalarea simandicosului Blast si a seturilor de date care ocupa foarte mult spatiu, prin punerea in "carca" a tuturor operatiilor pe seama interfetei de la NCBI pentru alinierea secventelor de proteine.

Crawling-ul are particularitatea de a urmari redirect-urile, putin deranjante la rularea manuala pe site, dar putin mai explicite odata ce Javascript este dezactivat din browser. Crawlerul, by default, are javascript dezactivat, deci el primeste rezultatele corect indiferent de redirectari. Input-ul ales este o secventa de aminoacizi numita hemoglobina, iar rezultatele reprezinta o lista de posibile alinieri.

--------------------------------------------------------------------
require_once 'goutte.phar';
use Goutte\Client;

$aaTest = "MHSSIVLATVLFVAIASASKTRELCMKSLEHAKVGTSKEAKQDGIDLYKHMFEHYPAMKKYFKHRENYTP
ADVQKDPFFIKQGQNILLACHVLCATYDDRETFDAYVGELMARHERDHVKVPNDVWNHFWEHFIEFLGSK
TTLDEPTKHAWQEIGKEFSHEISHHGRHSVRDHCMNSLEYIAIGDKEHQKQNGIDLYKHMFEHYPHMRKA
FKGRENFTKEDVQKDAFFVNKDTRFCWPFVCCDSSYDDEPTFDYFVDALMDRHIKDDIHLPQEQWHEFWK
LFAEYLNEKSHQHLTEAEKHAWSTIGEDFAHEADKHAKAEKDHHEGEHKEEHH";
$link = 'http://blast.ncbi.nlm.nih.gov/Blast.cgi?PROGRAM=blastp&BLAST_PROGRAMS=blastp&PAGE_TYPE=BlastSearch';

//create a new client instance
$client = new Client();

// connect to main page
$crawler = $client->request('GET', $link);
$form = $crawler->selectButton('b1')->form();
$crawler = $client->submit($form, array('QUERY' => $aaTest));

// arrive on second page, has the requestId too
$secondForm = $crawler->filter('form[name=RequestFormat]')->form();
$rid = $secondForm['RID'];
$crawler = $client->submit($secondForm);

//echo "The RID is " . $rid->getValue();

// arrive to the 3rd page on, post on Blast.cgi script
$redirects = 0;
while ($redirects < 50) { // set a max number of acceptable redirects
$nextForm = $crawler->filter('form[id=results]')->form();
sleep(3);
$crawler = $client->submit($nextForm);

// stop when there is a <div id=descrInfo/> in the page meaning final results
$cnt = $crawler->filter('div[id=descrInfo]')->count();
if ($cnt > 0) {
break;
}
$redirects += 1;
}

echo "Redirects ---->>> " . $redirects;
echo $crawler->html(); // pagina finala

17 aprilie 2014

Position weight matrix | detecting binding sites in the promoter region

Cum se creează matricea PWM:
Vrem să detectăm poziții de legătura (binding sites) în genom. Pentru a maximiza probabilitatea de a găsi poziții de legătură într-o secvență, se folosește odd ratio (OR).
Odd ratio = ... = α + ∑ log (x/y) , unde x = P(sequence[i] | binding site), y = P(sequence[i] | ⌐binding site), constanta α = P(binding site) / P(⌐binding site).
x se află din matricea de frecvență a motivului (în care secvența are N caractere, jaspar), y din probabilitățile de fundal (background probability) din fișierul de upstream*.fa .
PWM este matricea formată din valorile pentru odd ratio, în care numărul de coloane este 4, pentru variantele de nucleotide {a, c, g, t}, iar numărul de linii corespunde dimensiunii motivului (1 ≤ i ≤ N).

Cum se detectează pozițiile de legătură:
Se va scana din nou fișierul de upstream, folosind o fereastră glisantă cu dimensiunea N, și pentru fiecare porțiune selectată se calculează scorul adunând valorile corespunzătoare din PWM. Dacă scorul depășește un anumit prag prestabilit, se consideră un binding site.

Aplicație:
Motivul ales este FOXC1, iar genomul este cel pentru mm10 (șoarece).
Se parcurge upstream1000.fa pentru șoarece pentru a calcula probabilitățile de fundal, apoi cu motivul lui FOXC1 se creează matricea PWM. Apoi se scanează upstream din nou pentru a afla pozițiile de legătură. Luând ca prag minim un scor = 2, am afișat mai jos histograma tuturor scorurilor, care seamănă cu curba lui Gauss - iar cele mai des întâlnite scoruri totale sunt între 5 și 7. Numărul total de secvențe al căror scor depășește pragul este în jur de 242.000 , din peste 30.000 gene scanate .


  Sursa cod AICI

14 aprilie 2014

Primul meu spyware -- un keylogger, în Windows 7

Aveți nevoie de: Perl instalat, o pagină personală de internet care să suporte cereri de tip http POST
Unelte folosite aici: Dev C++, Perl (strawberry package), Google App Engine, instsrv.exe & srvany.exe

Idee: Un keylogger ascultă tot ceea ce utilizatorul tipărește prin tastatură și salvează datele respective spre prelucrare. Acesta este în principiu util pentru spionat, interceptat date „confidențiale” ș.a.m.d .

Programul efectiv care ascultă ce s-a tastat este scris în C++ , sursa lui a fost preluată de pe internet și se poate vedea AICI . Sursa se compilează și se execută rezultând un fișier exe. Dacă pur și simplu rulăm executabilul, el va asculta butoanele tastate și le va transfera într-un fișier de log.
Pentru a avea acces la acest fișier de la distanță, un script care rulează „periodic” va citi aceste loguri și le va trimite prin internet. Scriptul realizat de mine este în Perl, citește fișierul de log, îl curăță (trunchiază) și trimite conținutul prin POST către o pagină web - pagina aleasă de mine conține un câmp mare de text care se poate vedea AICI . După http POST, pagina trimite textul primit către o adresă de email setată de mine (dar el se poate la fel de bine salva într-o bază de date personală pentru a nu deranja).
Scriptul în Perl va trebui să ruleze ca un serviciu în Windows, iar logger-ul propriu-zis trebuie de asemenea pornit la fiecare restartare a calculatorului. Pentru rularea scriptului în Perl ca serviciu o explicație pe larg se poate citi AICI. Pentru fișierul exe, el va porni singur ca un proces odată cu restartarea calculatorului dacă îl copiem în Startup (detalii AICI).

Mai multe detalii despre rularea efectivă pe propriul calculator (sau cel al prietenilor :) puteți citi în README.

sursa cod spyware: AICI

03 aprilie 2014

My first Ruby on Rails app & GIT configuration

After Rails is installed:
> rails server

> rails new blog
> cd blog
> rails generate scaffold post title:string body:text
> rails generate scaffold comment post_id:integer body:text
> rake db:migrate

> rake routes
localhost:3000/posts#index

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

GIT commands:
Create new local rep.
> git init
Connecting it to remote repository
> git remote add origin <http-link-remote-rep> ***
Config. username & email
> git config --global user.name "Boomblebee"
> git config --global user.email "mail2...@gmail.com"
Pushing for the first time
> git push origin master

Working dir -> staging area
> add .
Staging area -> local GIT rep.
> commit -m "My message!"
Working dir -> local GIT rep.
> commit -a
Local GIT rep. -> working dir.
> checkout <branch>
> merge <branch>
Check synchronize & the branch you are in
> git status

Local GIT rep -> Remote GIT rep
> push <remote> <branch>
Remote GIT rep -> Local GIT rep
> fetch
Remote GIT rep. -> Working dir.
> pull <remote>  or  clone <remote>

_____________
*** github.com ; bitbucket.org

Quick fix: recuperare bare (panels) in Ubuntu

Cand nimic nu mai merge, si nici terminalul nu se mai deschide:
CTRL+Alt+F6
sudo apt-get install ubuntu-desktop
CTRL+Alt+F7

31 martie 2014

Analiza genetică a populațiilor umane de pe teritoriul României

Arată că:
Există diferențe semnificative din punct de vedere statistic între Valahia și București  la un locus; între Valahia și Grecia la un locus; între Valahia și Turcia  la 3 loci; între Valahia și Italia la 3 loci; între Valahia și Ungaria (Budapesta)  la 5 loci; între Valahia și Belarus la 10 loci  și în final între Valahia și Polonia, la 11 loci. Nu există diferențe majore între Valahia și Croația precum și între Valahia și Serbia. 
 alte lucruri interesante aflați aici

Sequence logo - inaltimea unei nucleotide

La fiecare pozitie 1, 2, 3 ... N , sequence logo reprezinta care geana dintre {a,c,g,t} este dominanta. In sirul ADN/ARN sau de aminoacizi, geana "dominanta" se spune ca indica cat de buna va fi conservarea acelei secvente.
Cunoscand matricea de frecvente, este lesne de calculat "inaltimea" fiecarei nucleotide. Am folosit formulele de aici si le-am aplicat pe doua gene: Mecom & FOXD1. Pentru ambele am preluat matricele de frecventa de pe situl Jaspar.
In fine, algoritmul este foarte simplu si are urmatorul output (pentru FOXD1, din poza):


Figura si rezultatele se interpreteaza astfel: analizand 20 de secvente de lungime 8 fiecare, obtinem ca nucleotida A apare o singura data pe pozitia 1, niciodata pe pozitia 2, .... , intotdeauna pe pozitia 7 si de 7 ori pe pozitia 8. Similar si pentru celelalte gene.
Aplicand formulele, se obtine ca inaltimea maxima 2 apare pentru h(a) la pozitia 4, de exemplu (reflectata si in logo); asadar nucleotida A domina categoric pozitia a patra, in toate cele 20 de secvente analizate. Pe de alta parte, pe pozitia 8, frecventele sunt cele mai apropiate, de 7 ori apare A, de 8 ori apare T, nu putem spune cu precizie cine va domina in viitor (care se va conserva mai bine). Asadar, inaltimea acestor gene e destul de mica pentru fiecare.
O inaltime 0 corespunde genei care nu apare niciodata pe pozitia respectiva.

Arunca o privire pe nucleotideHeight.py


Explicatie: cea mai proasta combinatie, care nu spune nimic, este aceea in care nucleotidele A, C, G, T apar fiecare in proportie de 25% . Aceasta combinatie nu ofera nicio predictie despre modul cum se va conserva secventa in viitor. Aplicand formulele, obtinem entropia H = 4 * (-0.5) log(0.5) = 2 . Asadar, pentru cele 4 nucleotide, entropia maxima este 2 si cea minima poate fi 0 (cand una din nucleotide are probabilitate 1 si restul 0, rezulta H=0). "Inaltimea" celor 4 nucleotide impreuna este insa invers proportionala cu entropia lor - pentru a ilustra acest fapt, inaltimea respectiva va fi luata ca 2 - H. In ceea ce priveste fiecare nucleotida in parte, ele au proportia lor din inaltimea totala care este reprezentata de probabilitate. Astfel sunt afisate logo-urile in grafic.

28 martie 2014

GEM5 example | configuration | commands | with Parsec

### configuration ###
cores: 8
CPU clock: 2GHz
Memory: 1GB
L1-Cache size: 64kB
L1-Cache associativity: 2
L2-Cache size: 256kB
L2-Cache associativity: 16
Parsec Benchmark: streamcluster
Parsec Benchmark size: simdev

###

GEM5 commands (run from gem5 directory):

0) download from [here] the script generator: writescripts.pl & the input set files.

1) run this script to create other scripts, using one of the available benches:
> ./writescripts.pl streamcluster 8
The results will be:
streamcluster_8c_simdev.rcS
streamcluster_8c_simlarge.rcS
streamcluster_8c_simmedium.rcS
streamcluster_8c_simsmall.rcS
streamcluster_8c_test.rcS
2) run the command which creates the configuration & run the generated streamcluster_8c_simdev.rcS script on it:
> ./build/ALPHA/gem5.opt --stats-file=test.out ./configs/example/fs.py --kernel=/localhome/yourUser/M5_system_ALPHA_small/binaries/vmlinux_2.6.27-gcc_4.3.4 --disk-image=/localhome/yourUser/M5_system_ALPHA_small/disks/linux-parsec-2-1-m5-with-test-inputs.img --cpu-clock=2GHz -n 8 --mem-size=1GB --caches --l1d_size=32kB --l1i_size=32kB --l1d_assoc=2 --l1i_assoc=2 --l2cache --l2_size=256kB --l2_assoc=16 --script=/localhome/yourUser/gem5/streamcluster_8c_simdev.rcS
The result of this script is ready in m5out/test.out

4) if you run the configuration without any script, the configuration will be created & you can connect to this computer via telnet, have access to a console and write whatever commands you like.
> ./build/ALPHA/gem5.opt --stats-file=test.out ./configs/example/fs.py --kernel=/localhome/yourUser/M5_system_ALPHA_small/binaries/vmlinux_2.6.27-gcc_4.3.4 --disk-image=/localhome/yourUser/M5_system_ALPHA_small/disks/linux-parsec-2-1-m5-with-test-inputs.img --cpu-clock=2GHz -n 8 --mem-size=1GB --caches --l1d_size=32kB --l1i_size=32kB --l1d_assoc=2 --l1i_assoc=2 --l2cache --l2_size=256kB --l2_assoc=16
Output:
.....
Listening for system connection on port 3456
...
> telnet localhost 3456
> ls