21 Temmuz 2021 Çarşamba

Amazon Web Service (AWS) Veri Tabanları

Giriş
Veri tabanları şöyle
1. Relational Database Service (RDS)
    Postgres, MySQL, etc. with Full SQL Support. AWS RDS yazısına taşıdım
2. RedShift
    Data warehouse with Full SQL Support
3. ElastiCache
4. DynamoDB
    NoSQL database : DynamoDB yazısına taşıdım
5. Aurora
    Serverless databases with Full SQL Support. AWS Aurora yazısına taşıdım

6. Database migration service (DMS)
7. Elastic Map Reduce (EMR)
8. Keyspaces
    Managed Cassandra (key value) with Some - CQL
9. Neptune
    Graph database with Some - openCypher
10. Timestream
    Time series database with Partial SQL support
11. Quantum Ledger
    Cryptographically verified transactions with Some - PartiSQL
12. Athena
    Ad-hoc queries on S3 with Some - CTAS. AWS Athena yazısına taşıdım
13. Babelfish
    MSFT SQL Server on Aurora with Full SQL support

Bir tablo şöyle

AWS Redshift yazısına taşıdım

Elastic Map Reduce (EMR)
Açıklaması şöyle
AWS excels at managing large amounts of data transformations at scale and with parallel processing.

Amazon EMR, Amazon Batch, and AWS Lambda are all suitable for this, each with its own purpose.

- Amazon EMR can be used if you want to dedicate a cluster to large data transformations.
- Amazon Batch can be used for large batch processes to scale up and down automatically.
- AWS Lambda can be used to execute custom data transformation in parallel at unmatched speed.







Mercator Projection

Haritaların Özellikleri
Açıklaması şöyle
Conformal
A conformal map projection preserves angles, in which any angle on a conformal map is true to their corresponding equivalent on Earth. If city A, city B and city C create a 60° angle at city B on a globe, this will be shown as such on a conformal projection. When we look for directions, we would want the 90° angle between road X and road Y in real life to also be portrayed as 90° on our map for easier navigation. This is not possible on a non-conformal map.

Equal area
As hinted by its name, an equal area projection preserves the sizes of areas as how they exist on the globe. It is therefore more reasonable to compare sizes of regions with an equal area map rather than with any other projection type, as it preserves landmass size most accurately. Shapes, however, will still be distorted.

Equidistant 
An equidistant map preserves distance, but only within a specific parameter. Some equidistant projections allow accurate distance measurement between two points on a meridian, which is the vertical line on our maps also known as a longitude (the equivalent of latitude, on the other hand, is called a parallel). Others require a central point, from which the distance is correctly measured. An equidistant map with London as its center, for example, accurately presents distances between London and any other point on the map, but not between Paris and Lisbon.

Compromise
Compromise map projections do not preserve any property and are therefore not appropriate for any calculation. However, they are the most suitable for general reference purposes compared to any of the previous types. A compromise map does not need to strictly maintain its accuracy, and as such, its priority is on reducing visual distortions to achieve landmass shapes as similar as possible as these on the globe.
Mercator Conformal Bir Harita
Açıklaması şöyle
Prior to Mercator’s chart, there was a strong chance of being lost during long distance sailings, especially across the ocean. Early sailing maps only displayed approximate sailing directions and rough distance measurements. These were not accurate, but often they covered small areas only, and thus their mistakes were rather inconsequential. This was extensively improved by Mercator. With his projection, seafarers would first mark their start and end point, and then connect these with a straight line. They would measure the angle between said line and any of the meridians it cuts through. Finally, upon sailing, they would only need to maintain this angle from their starting point until they arrived at their destination — all within the level of accuracy that was unheard of before. Needless to say, the Mercator projection revolutionized navigation.

Eleştiri
Mercator Avrupa'yı olduğundan büyük gösterir. Açıklaması şöyle
The immense distortion of the size of Europe and North America, leaving the rest of the world (often represented by Africa) seemingly small and powerless. 
Eğer ölçüleri tam görmek istiyorsak Gall-Peters Projection kullanılabilir.

19 Temmuz 2021 Pazartesi

GraphQL Schema

Giriş
Açıklaması şöyle. Schema tanımlama için kullanılan dile Schema Definition Language (SDL) deniliyor.
GraphQL has its own type system. This system is used to define the schema of an API. Basically, the syntax for writing schemas is known as Schema Definition Language or SDL.
Nesneler type Foo şeklinde tanımlanıyor. Alanların sonunda ! işareti varsa bu alan mecburidir anlamına geliyor. Yani es geçilemez. Açıklaması şöyle
The ! mark signifies that these are mandatory fields.

Örnek - String
Şöyle yaparız
type Query {
  shows(titleFilter: String): [Show]
}

type Show {
  title: String
  releaseYear: Int
}
Örnek - Int
Şöyle yaparız
type Employee {
  id: String!
  name: String!
  phone: String!
  age: Int!
}
Örnek - tehlikeli kod
Şu kod tehlikeli
type Query {
  album(id: ID!): Album
}
type Album {
  photos(first: Int): [Photo]
}
type Photo {
  album: Album
}

query maliciousQuery {
  album(id: ”some-id”) {
    photos(first: 9999) {
      album {
        photos(first: 9999) {
          album {
            photos(first: 9999) {
              album {
                #... Repeat this 10000 times...
              }
            }
          }
        }
      }
    }
  }
}

16 Temmuz 2021 Cuma

Golang

Giriş
2009 yılında Google tarafından geliştirilmeye başlandı. Yine Google tarafından geliştirilen Node.js'in rakibi. Bazı özellikleri şöyle

- C++ gibi bir standart kütüphaneye sahip
- Makine koduna derleniyor.
- Garbage Collection yapıyor.

Bir kitap burada

Go komutu
Örnek - get
Şöyle yaparız
go get solace.dev/go/messaging
Örnek - mod
Şöyle yaparız
mkdir funWithEDA && cd "$_"
go mod init GoEDA
Örnek - run
Şöyle yaparız
go run foo.go
Docker ve Golang
Örnek - multistage ve root olmayan kullanıcı
Şöyle yaparız
FROM golang:alpine3.15 as builder

WORKDIR /path
COPY . .

RUN go mod download
RUN go build -o "app" .

FROM alpine:3.15.5

WORKDIR /path

RUN apk update \
  && apk -U upgrade \
  && apk add --no-cache ca-certificates bash gcc \
  && update-ca-certificates --fresh \
  && rm -rf /var/cache/apk/*

RUN addgroup app_user && adduser -S app_user -u 1000 -G app_user

COPY --chown=app_user:app_user --from=builder /path/app .

RUN chmod +x /path/app

USER app_user

ENTRYPOINT ["/path/app"]
main metodu
Örnek
Şöyle yaparız
package main

import (
  "io"
  "net/http"
)

func main() {
  http.HandleFunc("/", helloWorld)
  http.ListenAndServe(":3000", nil)
}

func helloWorld(w http.ResponseWriter, r *http.Request) {
  io.WriteString(w, "Hello world!")
}
Import
Şöyle yaparız
package main

import (
  "fmt"
  "os"
  "os/signal"
  "strconv"
  "time"
  ...
)

func main() {
  ...
}
Import
Şöyle yaparız
package main
import (
 "net/http"
"github.com/labstack/echo/v4"
)
func main() {
  e := echo.New()
  e.GET("/", func(c echo.Context) error {
    var myarr [3]string
    myarr[0] = "Hello"
    myarr[1] = "From"
    myarr[2] = "GoLang"
    return c.JSON(http.StatusOK, myarr)
  })
  e.Logger.Fatal(e.Start(":8080"))
}

Fmt Paketi
Örnek - %v
Şöyle yaparız
fmt.Printf("Added %v %v \n", newPerson.first_name, newPerson.last_name)
Örnek
Şöyle yaparız
reader := bufio.NewReader(os.Stdin)

fmt.Print("Enter a first name: ")
firstName, _ := reader.ReadString('\n')
if firstName != "\n" {
  firstName = strings.TrimSuffix(firstName, "\n")
}
Time paket
Örnek
Şöyle yaparız
package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}
Değişken Tanımlama
Yeni değişkene ilk değer atama := ile yapılır. Sonradan değer arama = ile yapılır
Örnek
Şöyle yaparız
func main() {
  v1 := "some variable"
  var v2 = "some other variable"
  v1 = "now v1 has a different value"
  v2 = " same with v2"
  fmt.Print(v1, v2)
}
Pointers
Örnek
Şöyle yaparız
func main() {
  v1 := "some variable"
  // v2 is now a pointer to v1
  var v2 *string = &v1
  fmt.Print(v2) // prints the memory address of v1
}

Slices and maps
Örnek
Şöyle yaparız
func main() {
  v1 := []int{1, 2, 3}
  v1 = append(v1, 4)
 
  fmt.Println(len(v1)) // 4
  fmt.Println(v1[1])   // 2
  fmt.Println(v1[1:3]) // [2 3]
 
  v2 := make(map[string]string)
  v2["hello"] = "world"
 
  v3, ok := v2["hello"]
  fmt.Println(ok, v3)  // true world
}

Error Handling
Örnek
Şöyle yaparız
func test(input int) error {
  if input < 0 {
    return errors.New("less than zero")
  }
  return nil
}
func main() {
  err := test(-1)
  if err != nil {
    fmt.Print(err)
  }
}
Function Tanımlama
Typescript'e benziyor. func kelimesi ile başlıyor. Döndürülen tip en sona yazılıyor. Parametre tipleri de parametre isminden sonra geliyor.

Örnek
Şöyle yaparız. 
func someFunc(n int) int {
}
Interface ve Struct Tanımlama
Örnek
Şöyle yaparız
type Animal interface {
  Speak() string
}
type Dog struct {
  Name string
}
// here we define Speak as a method on Dog
// it takes a pointer receiver, but you 
// could also remove the *
func (d *Dog) Speak() string {
  return fmt.Sprintf("I am %s", d.Name) 
}
func main() {
  var dog Animal = &Dog{
    Name: "Cooper",
  }
 
  fmt.Println(dog.Speak())
}
Örnek - Struct
Şöyle yaparız
package main

import (
  "encoding/json"
  "net/http"
)

type ReqBody struct {
  Name string `json:"name"`
}

func main() {
  http.HandleFunc("/", HelloServer)
  http.ListenAndServe(":3000", nil)
}

func HelloServer(w http.ResponseWriter, r *http.Request) {
  var reqBody ReqBody
  json.NewDecoder(r.Body).Decode(&reqBody)
  w.Header().Set("Content-Type", "application/json")
  json.NewEncoder(w).Encode(reqBody)
}
pipeline
Blocking Queue gibidir
Örnek
Şöyle yaparız. "go foo" ile coroutine çalıştırılıyor. Yani Java karşılığı "Virtual Thread". "<-" ile de pipeline'a veri gönderiliyor ve veri okunuyor
package main

import "fmt"

func sum(s []int, c chan int) {
    sum := 0
    for _, v := range s {
        sum += v
    }
    c <- sum // send sum to c
}

func main() {
    s := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    go sum(s[:len(s)/2], c)
    go sum(s[len(s)/2:], c)
    x, y := <-c, <-c // receive from c

    fmt.Println(x, y, x+y)
}
Bunun Java karşılığı şöyle
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;

public class main {
  static void sum(int[] s, int start, int end, BlockingQueue<Integer> queue) 
  throws InterruptedException {
    
    int sum = 0;
    for (int i = start; i < end; i++) {
      sum += s[i];
    }
    queue.put(sum);
  }


  public static void main(String[] args) throws InterruptedException {
    int[] s = {7, 2, 8, -9, 4, 0};
    var queue = new ArrayBlockingQueue<Integer>(1);
    Thread.startVirtualThread(() -> {
      sum(s, 0, s.length / 2, queue);
    });
    Thread.startVirtualThread(() -> {
      sum(s, s.length / 2, s.length, queue);
    });
    int x = queue.take();
    int y = queue.take();

    System.out.printf("%d %d %d\n", x, y, x + y);
  }
}



14 Temmuz 2021 Çarşamba

GraphQL Mutation - CRUD İşlemleridir

Giriş
POST isteği ile gönderilir. JSON döner. Mutation ile create, update, delete işlemleri yapılır. Mutation bir sonuç dönebilir.
Metodun içine gönderilecek parametreler yazılır, döndürülecek sonuçlar ise süslü parantez içindedir.
Örnek
Şöyle yaparız. Burada name ve country değerleri gönderiliyor. Sonuç olarak yine aynı parametreler isteniyor.
mutation {
  createAuthor(name: 'Brandon Sanderson', country: "USA") {
    name
    country
  }
}
Eğer yeni bir kayıt yaratsaydık ve sonuç olarak id isteseydik şöyle yaparız
mutation {
  createAuthor(name: 'Brandon Sanderson', country: "USA") {
    id
  }
}

Örnek
Şöyle yaparız
mutation {
  project_tracker {
    createTicket(title : "New ticket", author_id : 11824) {
      id
    }
  }
}
Açıklaması şöyle
In our example, the createTicket mutation accepts two arguments for creating a ticket: title and author_id. On ticket creation, we return the $id of the newly created ticket. Just like the query, the mutation is a root object type. Mutations, for the most part, are very flexible and can return whatever you desire: scalars such as int, string, bool, and core types like the Ticket, or even custom response objects. Similar to queries, if the mutation field returns an object type, you can ask for nested fields. 
Örnek
Şöyle yaparız
type Author {
  id: ID!
  firstName: String!
  lastName: String!
}

type Query {
  findAllAuthors: [Author]!
  countAuthors: Long!
}

type Mutation {
  newAuthor(firstName: String!, lastName: String!) : Author!
}

13 Temmuz 2021 Salı

Load Balancer

Giriş
Load balancer ayrı bir cihazdır. Yükü dağıtacağı sunucuların listesini bilir. Bir sunucu bakım veya arıza için kapatılırsa load balancer listesinden silinir.

Load Balancer tarafından kullanılacak algoritma tamamen kendi çözmek istediğimiz problem ile ilgili olabilir. Örneğin Load Balancer müşteriyi kendisine en yakın sunucuya yönlendirme algoritması kullanabilir. Bir örnek şöyle
Load Balancer: It is used to divide the traffic, i.e., to balance the load on basis of some algorithms or some strategy defined by us.

We can define the strategy, the person who lives nearest to the particular shop should go to that shop.
L4 vs L7 Load Balancer
Açıklaması şöyle
L4 : Makes balancing decision only on IP address , tcp port. Cannot see request header, client, type etc.
L7 : Has info about url, message, request type, header, client everything. Can route request based on type of request

Use L4 when you need to make simple reliable and fast balancing decision on server load, which has reliable TCP connection. Use L7 when you need to route request to appropriate resource server, such as image request will go to image server etc.
HAProxy
HAProxy yazısına taşıdım

Load Balancer Algoritmaları
4 tanesi şöyle
1. Random Algorithm
2. Round-Robin Algorithm
3. Weighted Round-Robin
4. Hash Algorithm

2 Temmuz 2021 Cuma

RabbitMQ Kurulum

Giriş
Windows'a kurulum için bir yazı burada. RabbitMQ Erlang ile çalıştığı için önce Erlang kurulumu yapmak gerekir.

Docker
İki tane image var
1. rabbitmq:3-management : Bu image ile management plugin etkin geliyor
2. rabbitmq

Örnek - docker
Şöyle yaparız. 1562 portu "http://localhost:15672/" yani dashboard için gerekir.
docker run -d --hostname my-rabbit --name rabbitmq-dlx
-p 15672:15672 -p 5672:5672 rabbitmq:3-management
Örnek
Şöyle yaparız
docker run -d --name some-rabbit 
  -p 4369:4369 
  -p 5671:5671 
  -p 5672:5672 
  -p 15672:15672 
  rabbitmq

# Enable management plugin
docker container exec -it some-rabbit 
  rabbitmq-plugins enable rabbitmq_management

Örnek - Docker
docker-compose.yml dosyasına şöyle yazarız
version: '3.7'
services:
  avc-rabbit:
    image: rabbitmq:3-management
    container_name: rabbitmq
    ports:
      - "15672:15672"
      - "5672:5672"
Çalıştırmak için şöyle yaparız
docker-compose up -d
Örnek - Komut Satırı
Şöyle yaparız
cd C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.7\sbin

rabbitmq-server.bat start
Web Management Console
C:\Program Files\RabbitMQ Server\rabbitmq_server-X\sbin\ altındaki şu komut çalıştırılır. Böylece artık management console'a giriş yapabiliriz.
rabbitmq-plugins.bat enable rabbitmq_management
Açıklaması şöylehttp://localhost:15672 adresine guest:guest olarak bağlanabiliyoruz.
15672 exposes a web management page that you can check out by opening a browser, navigating to http://localhost:15672, and using the credentials guest:guest.
Açıklaması şöyle
RabbitMQ has a user-friendly interface that lets you monitor and handle your RabbitMQ server from a web browser. Among other things, queues, connections, channels, exchanges, users and user permissions can be handled (created, deleted, and listed) in the browser, and you can monitor message rates and send/receive messages manually.
Exchanges Sekmesi
Şeklen şöyle. Burada yeni exchange de eklenebilir.


Shovel Plugin
Bu eklenti ile kuyrukta çok fazla bekleyen mesajlar "Dead Letter Exchange" yani ölü mesaj kuyruğuna gönderilebilir.