5 Mart 2016 Cumartesi

JSP-1



Scriptlet :
Html kodu içerisine Java kodu eklemek için scriptlet‘ler kullanılır. bu kullanım sırasında Java kodları <%  ve  %> işaretleri arasına yazılır.
<Html>

<Body>
<%
// kullanılmak istenen java kodu
%>
</Body>
</Html>

  • Bir class’ın Servlet olabilmesi için HttpServlet class’ından extends olması gerekli ve yeterlidir.
  • PrintWriter out = response.getWriter(); 
PrintWriter class’ından out adında bir obje oluşturduk ve bu objeye kullanıcaya verilecek olan yanıt ( response ) a yazma ozelliğini atadık. bu sayede “out.println( )” metodunu kullanarak response‘mizi tasarlıyoruz. aynı HTML sayfası yazar gibi satır satır kullanıcıya gösterilecek olan sayfayı (response ) tasarlıyoruz.
  • int birincisayi = Integer.parseInt(request.getParameter(“birincisayi”));  kodunda gördüğünüz request.getParameter( ) metodu servlet’de yazılan input ların değerlerini almamıza yaramaktadır. inputların  içerisine yazdığımız name=”” değerlerini bu metoda parametre olarak göndererek bu işlemi gerçekleştiririz.
  •  Daha sonra output içerisinde biraz farklı bir kullanımla bunu değişkenleri ekrana yazdırdık. <%= ve %> tagları arasına değişkenimizi yazarak. ben burada Expression kullandım. aslında burada yazdığımız <%=username%> kodu <% out.print ( username ) ; %> kodunun aynısıdır. ama daha kolay bir kullanım olduğu için expression kullanmayı tercih ettim. siz iki şekilde de kullanabilirsiniz. görüldüğü gibi zor bir yanı yok.
  • Servis metodunda çıktı üretmeyen kod parçaları yazılmak istendiği zaman ( bu bir metod yada değişken olabilir.) declaration‘lardan istifade edilir. kullanım şekli <%! ve %> tagları arasına java kodlarının yazılması şeklindedir.
  • JAR:Java da yazılmış bir uygulamanın çalışabilmesi için gerekli kütüphanelerin bulunduğu sıkıştırılmış bir dosyadır. 
  • Once you connect to the database and, in the process, create a Connection object, the next step is to create a Statement object. The createStatement method of the JDBC Connection object returns an object of the JDBC Statement type.

    Example: Creating a Statement Object
    Statement stmt = conn.createStatement(); 
      
    
    
    The Statement object is used to run static SQL queries that can be coded into the application.
     
    ORNEK: JSP içine html kodu yazarak kullanıcıdan veri alma


     


    Calıstırdıgımızda ekrana bu butonlar gelir.
     
     Programın outputunu ise html sayfasında degil eclipse console da goruruz.
     
    Ornek: Simdi ise aynı sekilde html formu ile kullanıcıdan inputlar alalım ama bu sefer
     responselar html sayfasında donsun.
     
    Index.jsp miz aynı kalır.Sadece servletimizde degişiklik yaparız.

     
     
     
     
    outputumuz ise su sekilde olur. 
     
     
     
     
    SCRIPLETS: <% %> tagleri arasına java kodları yazarız.Eger <%= %> kullanılmıssa burda sadece
    bir parametre olusturup kullanmamız gereklidir.
     
    <%= request.getParameter("name")%>
     
    RequestDispatcher defines an object that receives requests from the client and sends them
     to any resource(such as servlet, HTML file or JSP file) on the server.
     
    POSTGRESQL TABLOSUNUN İSTEDİGİMİZ BİR SATIRINA VERİ EKLEME:
    
    
    INSERT INTO tablo_adı(..,..,..,...) VALUES(..,..,..,..);
    
    
    Mesele user adında bir tablomuz olsun. bu tablonun user_id, user_name ve password gibi satırları 
    olsun.Bu tablonun 7 satırına bir veri eklemek istedigimizi dusunelim.
     
    INSERT INTO user(user_id,user_name,password) VALUES(7,'gamze','jfsjkel');
     
     
     
    
    
    
    


JSP-2



  • Mesela tablonun user_name i gamze olan satırını dondurmek isteyelim.
SELECT * FROM user where user_name='gamze';

bu sekilde yazınca aldıgımız sonuc :
7 gamze seklinde olur.

  • Tablonun herhangi bir satırındaki veriyi degistirme:
7 satırda bulunan user_name i gamze degil de gamze sen yapmak isteyelim.
UPDATE user SET user_name='gamze_sen' where user_id=7;
SELECT * FROM user;


Bu iki satırı yazıp teker teker calsıtırdgımızda 7 satırda artık gamze degil de gamze sne yazdıgını goruruz.
  • Tabloda bulunan satırları silmek istedigimizi varsayalım:
Mesela id si 5 ten buyuk olan satırları silelim.
DELETE FROM user where user_id>5;
SELECT * FROM user;

Bu sekilde sadece id si 5 ve 5 ten kucuk olan satırları goruruz.
  • Database talks in SQL but Java does not know how to talk in SQL.It needs a translator called JDBC(Java DataBase Connector).
ACID = Atomicity Consistency Isolation Durability 
  • Atomicity:  Based on all or nothing. Herhangi bir error, power failure veya crash durumunda statementlardan biri calısmazsa digerleri de calısmaz. Calısma durumunda da hepsi calısır.
<-- This is HTML Comment -->
<%-- This is JSP Comment--%>


JSP Expression Tag:

<%= statement %>

Sonuna ; koymaya gerek yoktur.
    
index.jsp

     <html>   
      <body>
       Current Time: <%= java.util.Calendar.getInstance().getTime() %>
      </body>
      </html> 
 
  
Kullanıcıdan user name alan bir ornek:



index.jsp
     <html>
       <body>
       <form action="welcome.jsp"> 
       <input type="text" name="uname"><br/>       
       <input type="submit" value="go"> 
       </form>   
       </body>
       </html>
  welcome.jsp
       <html>  
       <body> 
       <%= "Welcome "+request.getParameter("uname") %>
       </body>
       </html> 

SELENIUM

Selenium u kurmak icin
  • http://www.seleniumhq.org/download/ adresine git.
  • 2.9.0 a tıkla.
  • Selenium u ekle.
  • Highlight Elements baslıgı altındakı Downloads kısmına tıkla.Onu da ekle.
    Sonra Implıcıt Wait baslıgı altındakı downloads kısmını tıkla.Onu da ekle.
    Bu Kadar .......


    (FirePath ve Fire Bug u da ekle.)


JAVA-Bir zar atıldıgında her bir yuzeyin kac defa geldiginin tablosunu yazdıran kod

package javaCalisma01;
import java.util.Random;
public class main2 {
    public static void main(String[] args){
        Random dice = new Random();
        int frequency[] = new int[7];// bizim 1 ile 6 arasındaki sayıların kac kere
        //geldigini ogrenmemiz lazım.bunun icin 1 ile 6 arası sayılar lazım.Bunu
        //saglamak icin icin ancak 7 degerini verebiliriz.1 ile 6 arasını kullanıp
        //0 ı kullanmayız.eger 6 yapsaydık 0dan 5e kadar olacaktı.Bizim 0a ihtiyacımız
        //olmucaktı ama 6 ya ihtiyacımız var.
        for(int i=1;i<6;i++){
            ++frequency[dice.nextInt(6)+1];
        }
        System.out.println("Numbers\tValues");
        for(int i=1;i<frequency.length;i++){
            System.out.println(i+"\t"+frequency[i]);
        }
    }
}



Output su sekildedir:
Number    Frequencies
1                   1
2                   1
3                   0
4                   4
5                   0
6                   4

Örnek 2:Kactane oldugunu bilmedigimiz sayıların ortalamasını hesaplama:

public class main1 {
    public static void main(String[] args){Scanner scan = new Scanner(System.in);
        System.out.println(average(10,30,40,20,50));
       
       
    }
    public static int average(int...numbers){
        int total=0;
        for(int x:numbers)
            total+=x;
        return total/numbers.length;
    }
}

Java da RANDOM !

Java da random kullanmak tıpkı scanner ın kullanımına benzer.
  • Öncelikle import etmemiz gerekir.
import java.util.Random;
  • Sonra scanner da oldugu gibi bir obje olusturmalıyız.
Random zar = new Random();
  • Daha sonra scanner da  kullanıcadan aldıgımız inputu bir degiskene atadıgımız gibi random dan gelen degeri de bir degiskene atamalıyız.
int deger = zar.nextInt(6); 
  • Ancak bu sekilde 0 ile 5 arasında degerler dondurur.Oysaki zarın degerleri 1 ile 6 arasındadır. Bunun icin 1 eklememiz gerekir.Su sekilde:
int deger = zar.nextInt(6)+1;



Ornek bir kod eklemek gerekirse:

import java.util.Random;
public class main1 {
    public static void main(String[] args){
        Random dice = new Random();
        int number;
        for(int counter=0;counter<10;counter++){
            number = dice.nextInt(6)+1;
            System.out.print(number+" ");
        }
    }


Bu kodun cıktısı ise su sekildedir.
1 2 5 2 6 5 3 4 2 2
 Her sey aslında scanner ile obje olusturmak gibi.Mesela array icin:
Scanner scan = new Scanner;
int arr[] = new int[10];



SYSTEM CALL NEDİR?

Os, direk hardware e erisebilir.Ancak user rogramaarının direk erisimi yoktur.Kernel in bunu yapmasının sebebi kernel os'u user program malware lerinden korumaktır.Ancak user programları hardware e erismek isteyebilir.Ornegin web kamera yı kullanarak resimlere erismek icin.Ancak bunu dogrudan yapamaz. Bunun icin Os a request gonderir. Bu requeste system call denir.





THREAD HATASI

thread creating code : home da.

#include <stdio.h>
#include <pthread.h>

void* thread_func(void* parameter){
        int i=0;
        for(i=0;i<5;i++){
                printf("%d\n",i);
                sleep(5);
        }
        return 0;
}

int main(int argc,char **argv){
        pthread_t thread_handle;
        int ret = pthread_create(&thread_handle,0,thread_func,0);
        if(ret != 0){
                printf("error creating thread! %d",ret);
                return 1;
        }
        pthread_join(thread_handle,0);
        return 0;
}







Calıstırmak icin :

 gcc -o thread1 thread1.c -lpthread
 ./thread1



output:
0
1
2
3
4

sql komutları

"INSERT INTO VALUES("+ id+",'"+name+"')"

"INSERT INTO table1 VALUES (" + id + ",'" + name+ "')";

"INSERT INTO table VALUES("+id+",'"+name+"')";


"INSERT INTO table1 VALUES("+id+",'"+name+"')"



"INSERT INTO table1 VALUES("+id+",'"+name+"')";

8099



Scheme Calısmalarım-Bazı kodlar



  • factoriel with lambda
                  (define fact 

                        (lambda (a)

                                 (if (= a 1) 1

                                        (* a (fact (- a 1))))))

          >(fact 5)
           120
  • fibonacci recursion ile 
(define (fib n)
  (cond ((= n 0) 0)
        ((= n 1) 1)
        (else (+ (fib (- n 1)) (fib (- n 2))))))


  • fibonacci iteration ile
(define (fibo x)
  (fib-iter 1 0 x))
(define (fib-iter a b x)
  (cond ((= x 0) b)
        (else (fib-iter (+ a b) a (- x 1)))))


  •  Exponation recursion
(define (uzeri x y)
  (cond ((= y 0) 1)
        (else (* x (uzeri x (- y 1))))))



  • Exponantion Iteration

(define (ussu a b)
  (ussu-iter 1 a b))
(define (ussu-iter x a b)
  (cond ((= b 0) x)
        (else (ussu-iter (* x a) a (- b 1)))))


  •  Farklı bir sekilde liste uzunlugu bulma
> (define list-length (lambda (list) (if (null? list) 0 (+ 1 (list-length (cdr list))))))
> (define lst '(1 2 3 4))
> (list-length lst)
4

  •  Sum of list elements

    (define sum-list (lambda (list) (if (null? list) 0 (+ (car list) (sum-list (cdr list))))))
    > (sum-list lst)
    10

  • Product of list elements


> (define prod-list (lambda (list) (if (null? list) 1 (* (car list) (prod-list (cdr list))))))
> (prod-list lst)
24

  •  Bir listedeki en buyuk elemanı bulma

(define lst '(1 5 3 7 4))
(define (getlargest a_list)
  (cond
    ((null? a_list)      
     #f)
    ((null? (cdr a_list))
     (car a_list))
    ((< (car a_list) (cadr a_list))
     (getlargest (cdr a_list)))
    (else
     (getlargest (cons (car a_list) (cddr a_list))))))
  • En buyuk elemanı bulma 2.YOL
(define (en-buyuk-eleman list) (cond ((empty? list) (error "empty list"))
                                     ((= (length list) 1) (car list))
                                     (else (max (car list) (en-buyuk-eleman (cdr list))))))

  • Determining whether a list contains that item or not
(define (find item list)(cond ((empty? list) false)
                              ((= item (car list)) true)
                              (else (find item (cdr list)))))

  • Listeye eleman ekleme

(define (eleman-ekle eleman liste)
  (cond ((or (empty? liste) (<= eleman (car liste))) (cons eleman liste))
        (else (cons (car liste) (eleman-ekle eleman (cdr liste))))))

  •   Listedeki elemanları sıralama

(define (eleman-ekle eleman liste)
  (cond ((or (empty? liste) (<= eleman (car liste))) (cons eleman liste))
        (else (cons (car liste) (eleman-ekle eleman (cdr liste))))))
(define (sort-liste liste)
  (cond ((empty? liste) empty)
        (else (eleman-ekle (car liste) (sort-liste (cdr liste))))))

  •  Listeyi tersten yazdırma

(define (ters l) (if (empty? l) empty
                           (append (ters (cdr l)) (list (car l)))))
İlişkisel Operatörler (Relational Operators)
İlişkisel Operatörler Scheme dilinde mevcuttur:
(= x 1)      x, 1 ise true döner
(< x y)      x, y dan küçük ise true döner
(<= x y)      x, y dan küçük veya eşitse true döner
(> x y)      x, y dan büyük ise true döner
(>= x y)      x, y dan büyük veya eşit ise true döner
(eq? x y)      x ve y ayni ise true döner
(eqv? x y)      x ve y işlevsel olarak ayni ise true döner
(equal? x y)      x veya aynı yapıda olup ayni içeriğe sahip ise true döner
Type Predicates (Predicate sonucu true ya da false donen fonksiyonlardir.)
Scheme programlama dilinde Tip Yüklemleri şunlardır:
(procedure? x)       x fonksiyon ise true döndürür
(null? x)           x boş bir liste ise true döndürür
(zero? x)           x sıfır ise true döndürür
(odd? x)           x tek ise true döndürür
(even? x)           x çift ise true döndürür
(boolean? x)        x Boolean ise true döndürür
(number? x)          x sayi ise true döndürür
(pair? x)          x bir çift ise true döndürür
(symbol? x)          x bir sembol ise true döndürür
LET KOMUTU
 Let komutuyla programın belirli bir alanına değişkenlere isteğiniz üzere değer ataması yapabilirsiniz. Belirlenen değerler o kod blok’u içinde geçerlidir. Kod blogundan çıkınca, değişkenlere atanmış değerler geçerli olmayacaktır.

(define x 45)
(let ((x 36)) (sqrt x))
 (sqrt x)
6
Goruldugu gibi x e atanan son degere gore program calısır.

Diger bir ornek:

> (define x 15)
>(let ((x 1) (y x) (+ x y))
>16



Burada x'e 1 degeri atanmıs y'ye ise x'in degeri olan 15 degeri (global degeri) atanmıstır.Sondaki toplamanın sonucu 16 cıkacaktır.




Soru1:
(define x 10)
(let ((x (* x x)) (y (+ x 10)))
(+ x y 10))
Cevabını bulunuz. (En altta)

Matematik Fonksiyonlar
(exp x) e^x in sonucunu döndürür
(log x) x sayısının logaritma değerini döndürür
(sqrt x) x kökünün karesini döndürür
(max x1 x2…) Verilen listeden en büyük sayıyı döndürür
(min x1 x2…) Verilen listeden en küçük sayıyı döndürür
(quotient x1 x2) x1/x2 kesrinin bölümünün sonucunu döndürür
(remainder x1 x2) x1/x2 kesrinin bölümünün sonucunu döndürür
(modulo x1 x2) x1 in x2 ye modüle sonucunu dündürür
(gcd num1 num2 …) Verilen listenin en büyük ortak böleni döndürür
(lcm num1 num2 …) Verilen listenin en küçük ortak çarpanını döndürür
(expt base power) taban^küvvet sonucunu döndürür
(sin x),(cos x),(tan x),(asin x),(acos x),(atan x) trigonometrik fonksiyonlar
  • TOPLAMA

(define (list-toplami list) (cond ((empty? list) 0)

                                  (else (+ (list-toplami (cdr list)) (car list)))))

  • LAMBDA ILE TOPLAMA 
(define toplam (lambda (list) (if (empty? list) 0 (+ (toplam (cdr list)) (car list)))))




An Example Program

The purpose of the following function is to help balance a checkbook. The function prompts the user for an initial balance. Then it enters the loop in which it requests a number from the user, subtracts it from the current balance, and keeps track of the new balance. Deposits are entered by inputting a negative number. Entering zero (0) causes the procedure to terminate and print the final balance.
(define checkbook (lambda ()

; This check book balancing program was written to illustrate
; i/o in Scheme. It uses the purely functional part of Scheme.

        ; These definitions are local to checkbook
        (letrec

            ; These strings are used as prompts

           ((IB "Enter initial balance: ")
            (AT "Enter transaction (- for withdrawal): ")
            (FB "Your final balance is: ")

            ; This function displays a prompt then returns
            ; a value read.

            (prompt-read (lambda (Prompt)

                  (display Prompt)
                  (read)))

            ; This function recursively computes the new
            ; balance given an initial balance init and
            ; a new value t.  Termination occurs when the
            ; new value is 0.

            (newbal (lambda (Init t)
                  (if (= t 0)
                      (list FB Init)
                      (transaction (+ Init t)))))

            ; This function prompts for and reads the next
            ; transaction and passes the information to newbal

            (transaction (lambda (Init)
                      (newbal Init (prompt-read AT)))))

; This is the body of checkbook;  it prompts for the
; starting balance

  (transaction (prompt-read IB)))))







http://www.scheme.com/tspl3/examples.html


cevap1 :130








Finding the given number is perfect or not.

For a number to be perfect ; sum of divisors of that number that are smaller than the number must equal to that number.For example lets look for 6. 1 + 2 + 3 = 6. So 6 is perfect number. 28 and 496 and 8128 are also perfect number.


(define sumBolum
  (lambda (x y z)
    (if (< x y)
        (if (equal? 0 (remainder y x)) (sumBolum (+ x 1) y (+ z x)) (sumBolum (+ x 1) y z))
        z)))
(define perfectNumber
  (lambda (a)
    (if (equal? a (sumBolum 1 a 0)) #t #f)))

>(perfectNumber 6)
#t
>(perfectNumber 28)
#t
>(perfectNumber 8)
#f



HTML - DROPDOWN MENU YARATMA

<select name="ay">
<option value="x" selected>Ay secin</option>
<option value="1">Ocak</option>
<option value="2">Subat</option>
<option value="3">Mart</option>
<option value="4">Nisan</option>
.....
</select>









SPRING - DEPENDENCY INJECTION VS. INVERSION OF CONTROL

Consider you have an application which has a text editor component and you want to provide spell checking. Your standard code would look something like this:
public class TextEditor {
   private SpellChecker spellChecker;
   
   public TextEditor() {
      spellChecker = new SpellChecker();
   }
}
What we've done here is create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario we would instead do something like this:
public class TextEditor {
   private SpellChecker spellChecker;
   
   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
}
Here TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to TextEditor at the time of TextEditor instantiation and this entire procedure is controlled by the Spring Framework.




BIR DOSYADAKI KELIMEYI DEGISTIRME

mesela masaustunde txt miz olsun.icinde merhaba ben gamze gamze gamze yazsin.

cd Desktop

sed -i s/gamze/tugce/g deneme.txt

burda gamze yazisi kalici olarak(i sayesinde) tugce ye donusur. g sayesinde de tum gamzeler tugce olur.
g olmazsa sadece bir tanesi degisir.