11 Ocak 2021 Pazartesi

Cargo Cult Programming

Giriş
Bir şeyin bilinçsize yapılması denince aklıma hep Cargo Kültü geliyor :)

Şifre Uzunluğu En Fazla 8 Karakter Olmalı
Bir Cargo Cult uygulaması

8 Ocak 2021 Cuma

Greedy Algoritmalar

Giriş
Yarışmalarda sorulan 16 çeşit soru var. Bunlar şöyle. Bu liste genişletilebilir.
There are around 16 types of problems that the programmer face while programming, these problems include:

1. Ad-Hoc
2. BigNums
3. Knapsack
4. Greedy
5. Flood Fill
6. Shortest Path
7. Network Flow
8. Complete Search
9. Eulerian Path
10. Two-Dimensional
11. Dynamic Programming
12. Computational Geometry
13. Minimum Spanning Tree
14. Approximate Search
15. Recursive Search Techniques
16. Heuristic Search
4. Greedy Algoritmalar Nedir?
Greedy algoritmalar ilk buldukları çözümü döndürürler. Bu çözüm en optimal çözüm olmak zorunda değildir. Açıklaması şöyle
Sacrificing your time for the best solution is a noble cause, but there may come the times where the best solution is overkill and you don’t always the resources (time, money, etc.) to go after your ideals. In fact, you don’t always need the best solution either, just a fairly good one might suffice.
Hatta bazen çok kötü bir sonuç bile döndürebilirler. Bu gibi durumlarda ya algoritmayı iyileştirmek ya da Dynamic Algorithm kullanmak gerekir.

Örnek - Coin Change Problem
Elimizde çeşitli değerlerde bozuk paralar var. Örneğin {1,5,6,9} TL. Amacımız 11 TL elde etmek. Önce 11'e en yakın parayı seçeriz. Daha sonra kalan değere en yakın parayı seçeriz ve bu böyle devam eder. Kod olarak şöyle
std::vector<int> denominations = {1, 2, 5, 10, 20, 50, 100, 500};

void findMinCoins(int value)
{
  sort(denominations.begin(), denominations.end());

  std::vector<int> answer;

  for (int i = denominations.size() - 1; i >= 0; i--)
  {
    while (value >= denominations[i])
    {
      value = value - denominations[i];
      answer.push_back(denominations[i]);
    }
  }

  std::cout << "The value can be achieved in " << answer.size() << " coins" << std::endl;

  for (int i = 0; i < answer.size(); i++)
  {
    std::cout << answer[i] << " ";
  }
}
 
Örnek - Activity Selection Problem
Elimizde başlangıç ve bitiş zamanları belli faaliyetler olsun. Bunların bir kısmının zamanı çakışacaktır. En fazla faaliyeti seçmek isteyelim. Şu çözümlerden birisi tercih edebiliriz.
1 - En erken başlayan faaliyeti seç. Daha sonra bir sonraki en erken başlayan faaliyeti seç
2 - En erken biten faaliyeti seç. Daha sonra bir sonraki en erken biten faaliyeti seç
3 - En kısa faaliyeti seç. Daha sonra bir sonraki en kısa faaliyeti seç

Örnek - Fractional Knapsack Problem
Elimizde 10 birim alabilen bir kutu olsun. Bu kutuları greedy algoritma ile şöyle doldururuz.
Enter the number of objects: 6
Enter the weight of the objects: 7 5 2 3 5 8
Container 1 contains objects with weight [7.0, 2.0]
Container 2 contains objects with weight [5.0, 3.0]
Container 3 contains objects with weight [5.0]
Container 4 contains objects with weight [8.0]
12. Computational Geometry
Örnek - Curve Fitting Algoritması
Şeklen şöyledir. Elimizde noktalar varsa bu noktaları en iyi şekilde temsil edecek bir doğru bulunması istenir.




Video Kavramları

Giriş 
Video kavramları oldukça karışık. Bazı öğrendiğim şeyleri not etmek istedim

Video için şu kavramları bilmek gerekir. bit sayısı, frame sayısı, çözünürlük, aspect oranı ve kullanılan codec.

Container vs Codec
Açıklaması şöyle
The main difference is that the codec is the actual software that does the compressing of your video file, while the container is the package the final project is delivered in for playback.
Bir başka açıklama şöyle.
Some main definitions:

- A codec (e.g., H.264, HEVC, VP9) is only responsible for the video or audio part, and one or more codecs can be merged into a container.
- A container (e.g., MP4, MKV) is responsible for keeping them together and this is also what you usually open up in your media player of choice.
- A particular encoder (e.g., x264, libvpx) is responsible for turning an input stream into a codec-compliant bitstream. There are often multiple encoders for one particular codec.
 Buradaki şu fark önemli. Codec genellikle sadece bir standart. Bu standardı gerçekleştiren farklı encoder'lar var. Farkı vurgulayan bir açıklama şöyle
Consider the case for H.264. The standard's name is H.264 – that's not the name of the actual encoder. Mainconcept is a very good commercial encoder, whereas x264 is a free and open source one. 
...
The mere fact that you can optimize encoding makes for a competition here. Both encoders will deliver a standardized bitstream that can always be decoded by a H.264-compliant decoder.
Container
Movie dosyalarının çoğu aslında container dosyalardır (avi, quicktime gibi) Bu dosyalar içinde stream'ler bulunur. Bir stream'lerden bir tanesi video stream'dir, diğer ise audio stream'dir. Stream ise frame'lerden oluşur. Frame'ler codec ile yazılır ve okunurlar.

Bazı container formatları şöyle
- AVI
- QUICKTIME
- MOV 
- MP4
SWF . Shockwave Flash aslında bu tam bir video container değil, çok daha fazlası

ffmpef tarafından desteklenen container'ları görmek için şöyle yaparız
ffmpeg -formats

Codec - Çözücüler
- AV1
- DivX 
- HEVC
- MP3
- H.264
- VP9

MP4 Container
Açıklaması şöyle
The most popular video format is MP4, also known as MPEG 4. MP4 is a multimedia container for video, audio, and data, including things like subtitles and still images. Make sure you don’t confuse MPEG 4 and MPEG 4 Audio. MPEG 4 has the file extension .MP4, while MPEG 4 Audio has the file extension .M4A and can only contain audio files. So, why exactly is MP4 so popular? Well it mainly has to do with how ubiquitous it is across a range of devices. Both mobile and desktop devices can playback MP4 video files, so it makes sense that it would be used by most content producers.

MP4 files are played at a constant bit rate (CBR), meaning the quality of your video stream will remain at the same bitrate no matter the variance in your internet bandwidth.

Functional Programming Monad

Giriş
Açıklaması şöyle
Monads are heavily used in most functional programming languages. In Haskell, for example, they are essential and appear everywhere, in all kinds of applications and libraries.                            

On the other hand, monads are rarely used in popular, non-pure-functional programming languages like C#, Java, Python, etc.
Anladığım kadarıyla Monad kullanarak Function Composition yapabiliyoruz. Yani Java ile düşünürsek nested function call gibi düşünülebilir. Bu çağrı zincirinde önce string'in başında/sonunda bulunan boşluklar temizlenir, büyük harfe çevrilir ve başına ünlem işareti konulur.
return appendExclam ( toUpperCase ( trim ( sentence ) ) );
Ancak bu kullanımda bir eksiklik var. Eğer hata bulunursa bunu yukarıdaki metoda geçme yolu yok. Monad bunu da hallediyor.

Kotlin Either Monad
Açıklaması şöyle
- Either type represents values with two possibilities, either Left or Right
- Convention dictates that Left is used for Failure and Right is used for Success.
- Mnemonic: Right also means correct.
İskeleti şöyle
sealed class Either<out A, out B> {
    data class Left<A>(val value: A) : Either<A, Nothing>()
    data class Right<B>(val value: B) : Either<Nothing, B>()
}
Örnek
Şöyle yaparız
data class Account private constructor(val balance: BigDecimal) {

  companion object {
    fun create(initialBalance: BigDecimal): Either<NegativeAmount, Account> =
      if (initialBalance < 0) Either.Left(NegativeAmount)
      else Either.Right(Account(initialBalance))
  }
}




7 Ocak 2021 Perşembe

Fan-Out/Fan-In API Integration Pattern - Aynı Zamanda Aggregator Pattern Denilebilir

Giriş

Bu örüntü API Integration başlığı altına alınmış. Aslında ismi de cafcaflı olmasına rağmen Aggregator, Service Aggregator, Map-Reduce ile benzer şeyler yapıyor. Aslında isimlendirme tam bir keşmekeş. 

Microservice Açısından Bakarsak
Microservice kullananların açıklaması şöyle
In Aggregator Pattern, there are 3 ways to implement it within Microservices application.
1. Scatter Gather Pattern
2. Chained Pattern
3. Branch Pattern
Scatter Gather Pattern : Servisler paralel çağrılır
Chained Pattern : Önce birinci servis çağrılır, onun sonucuyla ikinci servis çağrılır
Branching Pattern : Scatter Gather Pattern ve Chained Pattern karışımı. Baz servisler paralel çağrılır, bazıları ise birbirlerine bağımlı olduğu için sırayla çağrılır.

Integration Pattern Açısından Bakarsak
Scatter Gather denilen şey Fan-Out/Fan-In ile aynı. Yani isteklerin paralel olarak yapılması ve bunların birleştirilip toparlanması.

Nasıl Çalışıyor?
Elimizde bir sürü veri kaynağından veri çekip bunları derleyip toparlayarak sunan bir servis olsun. Bu servis tetiklenince, iş uzun süreceği için istemciye bir tane Correlation ID döndürür.  Bunun açıklaması şöyle
... returns to the initial system a correlation ID (CID), a random string that tells the system, "I received your request, here, save this CID somewhere, and when I have the result, I will give it to you along with that CID to make it possible for you to understand a reply to which request it is."
Daha sonra kullanması gereken tüm veri kaynaklarına mümkünse paralel olarak çağrı başlatır. Bu kısma fan-out deniliyor. Daha sonra gelen cevapları birleştirir ve CID ile birlikte istemciye döner. Bu kısma da fan-in deniliyor.

Ne Zaman Kullanılır?
Açıklaması şöyle
The pattern can be considered each time there is a rather long-running integration process that requires communication with more than one system.

This raises a question of what “long-running” is. The answer lies in whether there is a human being waiting for the results. Generally, people can wait 1-2 seconds for a response before growing impatient. Hence, if the process takes 30 seconds or more, they should not be made to wait as this can only lead to dissatisfaction.

6 Ocak 2021 Çarşamba

Apache Kafka Consumer Group

Consumer Group Nedir?
Açıklaması şöyle. Her consumer'a bir veya daha fazla Partition atanır
What if we have many consumers, but we would like to read the message only once? That is why the concept of consumer group was designed. The idea here is when a consumer belongs to the same group, it will have some subset of partitions assigned to read a message. That helps to avoid the situation of duplicated reads. In the figure below, there is an example of how we can scale data consumption from the topic. When a consumer is making time-consuming operations, we can connect other consumers to the group, which helps to process faster all new events on the consumer level. We have to be careful, though, when we have a too-small number of partitions. We would not be able to scale it up. It means if we have more consumers than partitions, they are idle.
Consumer Group Birden Fazla Topic'i Dinleyebilir
Açıklaması şöyle
A consumer group can subscribe to one or more topics.
Consumer Group'ta Kaç Tane Consumer Olmalı?
Partition sayısı kadar consumer olmalı. Daha  fazla sayıda consumer varsa bunlar idle beklerler. 
Şeklen şöyle

Rebalance Nedir?
Apache Kafka Rebalancing Protocol yazısına taşıdım

4 Ocak 2021 Pazartesi

MongoDB find metodu

Giriş
Belirtilen kritere uyan kayıtları döndürür. Kriter için or, and, not ,min, max kullanılabilir.

Bu metod bir cursor döndürür. cursor kullanırken sayfalamaya (pagination) dikkat etmek gerekir.

Örnek - Tek Alan İçin in
Or örneğinde name alanı am veya fm içeren kayıtları şöyle buluruz.
db.collection.find({ "name": { "$in": ['/am/','/fm' ] } })
Örnek - Tek Alan İçin in ve İkinci Bir Alan
Şöyle yaparız
> db.car.find( {make: {$in: ["ford","hyundai"] } , year: "2017"} ).pretty()
{
 "_id" : ObjectId("600c626932e0e6419cee81a7"),
 "year" : "2017",
 "make" : "hyundai",
 "color" : "white",
 "km" : 22000,
 "price" : 32000
}
{
 "_id" : ObjectId("600c63cf32e0e6419cee81ab"),
 "year" : "2017",
 "make" : "ford",
 "color" : "black",
 "km" : 34000,
 "price" : 28000
}
Örnek - Tek Alan İçin all
And örneğinde name alanı am ve fm içeren kayıtları şöyle buluruz.
db.collection.find({ "name": { "$all": ['/am/','/fm' ] } })
Örnek - Tek Alan İçin not
Not örneğinde name alanı am içermeyen kayıtları şöyle buluruz.
db.collection.find({ "name": { "$not": /am/  } })
Örnek - Çok Alan
Şöyle yaparız
> db.car.find( {make: "ford", year: "2019"} ).pretty()
{
 "_id" : ObjectId("600c63cf32e0e6419cee81af"),
 "year" : "2019",
 "make" : "ford",
 "color" : "white",
 "km" : 8000,
 "price" : 42000
}
Örnek - Çok Alan İçin or
Şöyle yaparız
db.tweets.find({
  $or: [
    { author: { $gt: "def" } },
    { author: "def", _id: { $gt: "abc" } }
]})
.sort({ author: 1, _id: 1 })
.limit(11);