<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arda Erdoğan on Medium]]></title>
        <description><![CDATA[Stories by Arda Erdoğan on Medium]]></description>
        <link>https://medium.com/@ardaerdogav?source=rss-934f7f192c9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w2eJDgGXAiZhcACnIdU9Ww.jpeg</url>
            <title>Stories by Arda Erdoğan on Medium</title>
            <link>https://medium.com/@ardaerdogav?source=rss-934f7f192c9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:26:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ardaerdogav/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RNN-MDN: Makine Öğrenmesinde Belirsizliği Yakalayan Gizli Kahraman]]></title>
            <link>https://medium.com/@ardaerdogav/rnn-mdn-makine-%C3%B6%C4%9Frenmesinde-belirsizli%C4%9Fi-yakalayan-gizli-kahraman-0c61dfc502c7?source=rss-934f7f192c9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c61dfc502c7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mixture-density-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Arda Erdoğan]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 01:32:37 GMT</pubDate>
            <atom:updated>2026-02-28T01:32:37.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*6mSZOElcawu7h6vIZuYR3g.png" /></figure><p>2015’ten bu yana yapay zekâ alanındaki gelişim hızı neredeyse logaritmik bir artış gösteriyor. Modeller büyüyor, yetenekler genişliyor, kullanım alanları çeşitleniyor. Bu hız, benim gibi hevesli insanların da (genç ya da yetişkin fark etmeksizin) “öğrenmek” için doğru kaynağı aramasına neden oldu. Hepimiz en az bir kez yapay zekâ ile üretilmiş kedi videolarını, YouTube’da dolaşan içerikleri ya da sosyal medyada karşılaştığımız yapay zekâ üretimi taraftar görsellerini gördük; çoğumuz da “Ben de denemek istiyorum” dedik. Ben de o noktadan başlayıp araştırmaya, öğrenmeye ve sadece kullanıcı olmak yerine üretici tarafta durmaya karar verdim.</p><p>Fakat işin içine girince bir gerçek çok netleşti: Konular hızlı gelişiyor, literatür yeni ve özellikle Türkçe kaynak bulmak zor. Açık olayım; yapay zekânın hangi dalına dalsam, konuyu öğrenene kadar İngilizceyi çözmüş oluyordum. Bu yüzden, özellikle Generative AI tarafında (görsel ve video üretimi gibi alanlarda) başlangıç seviyesinde yapılandırılmış Türkçe kaynak azlığını biraz olsun azaltmak için bu seriyi oluşturmak istedim. Hem bilmeyen öğrenecek, hem bilen pekiştirmiş olacak.</p><p>Bu yazıda serinin önemli bir yapı taşını ele alacağız: <strong>RNN-MDN (Recurrent Neural Network + Mixture Density Network)</strong>. Eğer makine öğrenmesine yeni adım atıyorsanız da, hâlihazırda aşina olup daha derin bir çerçeve arıyorsanız da hedef aynı: Konuyu anlaşılır bir şekilde oturtmak.</p><h3>1. Bölüm Sonu: &quot;Tek Cevap&quot; Paradoksunun Sonu</h3><p>Bir robotun bir sonraki adımını tahmin etmeye çalıştığınızı hayal edin. Geleneksel modeller genellikle otoriterdir; size tek bir emir verir: <strong>“Şuraya git.”</strong> Peki ya önünde bir engel varsa ve gitmesi gereken iki mantıklı yol bulunuyorsa?</p><p>Klasik modeller burada &quot;ortalama&quot; bir yol bulmaya çalışırken genellikle çuvallar. <strong>RNN-MDN</strong> ise dürüsttür; size belirsizliği açıkça ifade eder: <em>“Sola gitme ihtimali %70, sağa gitme ihtimali %30.”</em> Yani tek bir tahmin yerine, size <strong>olası geleceklerin bir yelpazesini</strong> sunar. Bu yaklaşım, &quot;tek bir doğru cevabın&quot; olmadığı gri alanlarda yapay zekaya adeta bir &quot;sezgi&quot; kazandırır.</p><p>Şimdi gelin, bu sezginin arkasındaki mühendisliğe; hem teorik hem de teknik detaylara adım adım bakalım.</p><h3>2. Bölüm: RNN-MDN — Belirsizliği Yönetmek</h3><p>Hayat, deterministik (kesin) formüllerin içine sığmayacak kadar karmaşıktır. Bir hava durumu tahmincisi &quot;Yarın yağmur yağacak&quot; dediğinde, aslında devasa bir olasılıklar bulutuyla uğraşıyordur. Sadece yağmurun yağıp yağmayacağı değil, şiddeti ve süresi de birer değişkendir.</p><p>İşte <strong>RNN-MDN (Recurrent Mixture Density Network)</strong>, tam da bu noktada devreye giren hibrit bir kahramandır.</p><h4>Bu İşbirliğinin Sırrı Nedir?</h4><p>Modeli iki farklı uzmanlığın evliliği olarak düşünebiliriz:</p><ol><li><strong>RNN (Hafıza):</strong> Verinin geçmişine bakar. &quot;Buraya kadar nasıl geldik?&quot; sorusunu yanıtlar. Sıralı verileri (cümleler, hisse fiyatları, hareketler) işleyerek bir bağlam oluşturur.</li><li><strong>MDN (Olasılık):</strong> İşlenen bu veriyi alır ve tek bir sayı üretmek yerine bir <strong>olasılık dağılımı</strong> oluşturur. &quot;Bundan sonra neler olabilir ve hangisi ne kadar mantıklı?&quot; sorusuna odaklanır.</li></ol><h3>Neden RNN-MDN Kullanmalıyız?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/658f8057d5c4deef4dbc4748236f3f28/href">https://medium.com/media/658f8057d5c4deef4dbc4748236f3f28/href</a></iframe><p><strong>Kısa bir tarihçe ve vizyon:</strong> Bu model, 1994&#39;te <strong>Christopher Bishop</strong> tarafından temelleri atılan MDN yapısının, <strong>Alex Graves</strong>&#39;in çalışmalarıyla RNN&#39;lere entegre edilmesiyle doğdu. Yeni başlayanlar için bu, makine öğrenmesinin &quot;kesinlik&quot; hapishanesinden &quot;olasılık&quot; özgürlüğüne kaçışıdır. Uzmanlar içinse belirsizliği modellemede bir devrimdir.</p><h3>RNN ile MDN’nin Dansı: Farkları Anlayalım</h3><p>RNN-MDN’yi anlamak için, bileşenlerini ayrı ayrı ele alalım. Önce standart RNN’i hatırlayalım, sonra MDN’nin büyüsünü ekleyelim.</p><p><strong>Standart RNN nasıl çalışır?</strong> RNN’ler, “hafızalı” ağlardır. Bir cümle okurken önceki kelimeleri unutmazsınız ya? RNN de öyle: Her adımda girdiyi alır, önceki “gizli durum” (hidden state) ile birleştirir ve bir çıktı üretir. Matematiksel olarak:</p><ul><li>Gizli durum:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*97lgboKp8JNiih1GJgzSdg.png" /></figure><ul><li>Çıktı: Tek bir değer veya vektör, örneğin bir sayı (regresyon) veya sınıf olasılıkları (softmax).</li></ul><p>Ama sorun şu: RNN’ler deterministik — yani tek bir “en iyi” cevap verir. Gerçek hayatta ise cevaplar belirsiz olabilir. Örneğin, bir çizimde bir sonraki nokta “ortalama” bir konumdaysa, ama aslında iki ayrı yol varsa, model “yanlış ortalama” alır ve saçma bir sonuç üretir.</p><p><strong>RNN-MDN’de ne değişir?</strong> MDN, RNN’in çıktısını olasılıksal hale getirir. Çıktı, bir “Gauss karışımı” (mixture of Gaussians) olarak modellenir — yani birkaç tane çan eğrisi (normal dağılım) karıştırılır.</p><p>Deterministik vs. Probabilistik: Klasik RNN “Y=5” der. MDN “Y’nin %40&#39;ı 3 civarında, %60&#39;ı 7 civarında dağılmış” der. Bu, belirsizliği yakalar ve modelin daha esnek öğrenmesini sağlar.</p><p>Sezgisel benzetme: Klasik RNN bir okçu gibi tek atış yapar. RNN-MDN ise okları birden fazla hedefe dağıtır ve “Hangi hedef daha olası?” diye söyler. Bu, overfitting’i (aşırı uyumu) azaltır ve gerçekçi tahminler üretir.</p><h3>Mimariyi Adım Adım İnceleyelim: Nasıl Çalışır?</h3><p>Şimdi mimariyi parçalara ayıralım. Görselleştirmek için basit bir şema düşünün: RNN bir zincir gibi sıralı veriyi işler, MDN ise son halkada olasılıkları hesaplar.</p><h3>Adım 1: RNN Katmanı — Sıralı Veriyi İşleme</h3><ul><li>Giriş: Zaman serisi verisi (x1, x2, …, xT), örneğin, bir cümlenin kelimeleri.</li><li>İşlem: Her adımda gizli durum güncellenir. LSTM veya GRU gibi varyantlar kullanırsanız (ki genellikle öyle), vanishing gradient sorununu çözer.</li><li>Çıktı: Her zaman adımında bir gizli vektör (h_t) — bu, MDN’ye feed edilir.</li></ul><p>Şematik (basitçe):</p><pre>Input: x1 → x2 → x3<br>RNN:   h1 → h2 → h3</pre><p>Yeni başlayanlar için: RNN’i bir hikaye anlatıcısı gibi düşünün — her cümle öncekiyle bağlantılı.</p><h3>Adım 2: MDN Çıkış Katmanı — Belirsizliği Modelleme</h3><p>RNN’in h_t’sini alır ve bir tam bağlantılı katmanla üç parametre üretir:</p><ul><li><strong>π (pi):</strong> Karışım ağırlıkları — “Kaç farklı senaryo var ve her birinin yüzdesi ne?” Örneğin, π1=0.6 (%60), π2=0.4 (%40). Toplam her zaman 1 olur (softmax ile).</li><li><strong>μ (mu):</strong> Her senaryonun ortalaması — “Bu senaryoda değer yaklaşık nerede?” Örneğin, μ1=3.2, μ2=7.5.</li><li><strong>σ (sigma):</strong> Her senaryonun standart sapması — “Bu senaryo ne kadar belirsiz?” Düşük σ kesinlik, yüksek σ yayılma anlamına gelir (exp ile pozitif tutulur).</li></ul><p>Matematiksel formül:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*0a2XZ4Hyzc1Fd8y-2_jNqg.png" /></figure><p>Sezgisel: MDN’yi bir parti planlayıcısı gibi hayal edin. “Misafirler %60 ihtimalle pizza ister (μ=orta baharatlı, σ=az varyans), %40 hamburger (μ=az pişmiş, σ=çok varyans).”</p><p>Uzmanlar için: Karışım sayısı K (örneğin 20–50) veri karmaşıklığına göre seçilir. Parametreler h_t’den lineer dönüşümle elde edilir.</p><h3>Adım 3: Loss Fonksiyonu — Modeli Eğitme</h3><p>Klasik modeller MSE (ortalama kare hata) kullanır — gerçek y ile tahmin arasındaki farkı cezalandırır. RNN-MDN ise Negative Log-Likelihood (NLL) kullanır:</p><ul><li>Loss:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*ULC8S307rcEw6ZpDQa_T9A.png" /></figure><ul><li>Anlamı: “Gerçek y’nin modelin dağılımındaki olasılığı ne kadar yüksek?” Maksimize etmek için minimizasyon yapılır.</li></ul><p>Bu, modelin belirsizliği ödüllendirmesini sağlar. Eğer veri multimodal ise, model birden fazla Gauss’la kapsar.</p><h3>Gerçek Dünyada RNN-MDN: Örnekler ve Uygulamalar</h3><p>Teoriyi somutlaştıralım.</p><ul><li><strong>El Yazısı Üretimi:</strong> Bir AI’ya “a” harfini çizdirin. Standart RNN ortalama bir “a” çizer, ama RNN-MDN farklı stiller üretir, çünkü π’ler farklı varyasyonları ağırlandırır.</li><li><strong>Finans:</strong> Hisse tahmini. Piyasa belirsizse, model “Yükselme %70” diyebilir.</li><li><strong>Robotik:</strong> Bir robot topu yakalarken, topun yolu belirsizse MDN birden fazla trajektori önerir.</li></ul><h3><strong>Uygulama: RNN-MDN’i Adım Adım İnşa Edelim</strong></h3><p>Teoriyi anlattık, sezgiyi oturttuk. Şimdi bunu somutlaştıralım.</p><p>Bu bölümde, PyTorch kullanarak basit ama teknik olarak doğru bir RNN-MDN modeli kuracağız. Amacımız yalnızca “çalışan bir kod” görmek değil; modelin gerçekten multimodal (çok modlu) bir yapıyı nasıl öğrendiğini anlamak.</p><p>Örnek problemimiz şu olacak:</p><ul><li>Bir sinüs dalgası üretelim.</li><li>Ancak çıktıyı iki farklı modla üretelim: sin(x) + 1 veya sin(x) — 1.</li><li>Yani aynı geçmiş için iki farklı gelecek mümkün olacak.</li></ul><p>Bu durumda klasik bir regresyon modeli genellikle iki modu ortalamaya zorlanır. RNN-MDN ise iki ayrı olasılığı öğrenebilir.</p><p>Kod şu bölümleri içerecek:</p><ol><li>Multimodal veri üretimi</li><li>RNN + MDN model tanımı</li><li>Numerically stable Negative Log-Likelihood loss</li><li>Eğitim döngüsü</li><li>Sampling (modelin gerçekten dağılımdan örnek üretmesi)</li></ol><p>Kodun içinde özellikle şu noktalara dikkat edeceğiz:</p><ul><li>σ (sigma) değerini stabil üretmek</li><li>Log-Sum-Exp trick ile sayısal taşmaları önlemek</li><li>Karışım bileşenlerinden örnekleme yapmak</li></ul><p>Aşağıdaki örnek tek parça halinde çalışır durumdadır ve doğrudan PyTorch ortamında denenebilir.</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>import torch.optim as optim<br>import numpy as np<br>import math</pre><pre># 1) MULTIMODAL VERİ OLUŞTURMA</pre><pre># Amaç:<br># Aynı geçmiş için iki farklı gelecek mümkün olsun.<br># Böylece MDN gerçekten &quot;multimodal&quot; yapıyı öğrenmek zorunda kalsın.</pre><pre>def generate_data(num_sequences=2000, seq_len=20):<br>    X, Y = [], []</pre><pre>for _ in range(num_sequences):<br>        # Rastgele faz seçiyoruz<br>        start = np.random.uniform(0, 2*np.pi)<br>        x_vals = np.linspace(start, start + 3, seq_len + 1)</pre><pre>base_signal = np.sin(x_vals)</pre><pre># İki modlu yapı: +1 veya -1 offset<br>        mode = np.random.choice([-1.0, 1.0])<br>        y_vals = base_signal + mode</pre><pre># Next-step prediction problemi<br>        X.append(y_vals[:-1])<br>        Y.append(y_vals[1:])</pre><pre>X = torch.tensor(X, dtype=torch.float32).unsqueeze(-1)<br>    Y = torch.tensor(Y, dtype=torch.float32).unsqueeze(-1)</pre><pre>return X, Y</pre><pre>inputs, targets = generate_data()</pre><pre># 2) RNN + MDN MODELİ</pre><pre>class RNN_MDN(nn.Module):<br>    def __init__(self, input_size=1, hidden_size=64, num_mixtures=2):<br>        super().__init__()</pre><pre>self.num_mixtures = num_mixtures</pre><pre># LSTM sıralı bağımlılıkları öğrenir<br>        self.rnn = nn.LSTM(input_size, hidden_size, batch_first=True)</pre><pre># Her mixture için 3 parametre üretir: pi, mu, sigma<br>        self.fc = nn.Linear(hidden_size, num_mixtures * 3)</pre><pre>def forward(self, x):<br>        batch_size, seq_len, _ = x.shape</pre><pre>rnn_out, _ = self.rnn(x)<br>        out = self.fc(rnn_out)</pre><pre># (B, T, 3K) -&gt; (B, T, K, 3)<br>        out = out.view(batch_size, seq_len, self.num_mixtures, 3)</pre><pre># Parametreleri ayırıyoruz<br>        pi = F.softmax(out[..., 0], dim=-1)        # mixture weights<br>        mu = out[..., 1]                           # means<br>        sigma = F.softplus(out[..., 2]) + 1e-6     # stabil pozitif sigma</pre><pre>return pi, mu, sigma</pre><pre># 3) NUMERICALLY STABLE MDN LOSS</pre><pre># Log-Sum-Exp kullanıyoruz.<br># Direkt olasılık hesaplamak numerically unstable olur.</pre><pre>def mdn_loss(pi, mu, sigma, y):<br>    &quot;&quot;&quot;<br>    pi: (B, T, K)<br>    mu: (B, T, K)<br>    sigma: (B, T, K)<br>    y: (B, T, 1)<br>    &quot;&quot;&quot;</pre><pre>y = y.expand_as(mu)</pre><pre># Gaussian log probability<br>    log_prob = -0.5 * (<br>        ((y - mu) / sigma) ** 2<br>        + 2 * torch.log(sigma)<br>        + math.log(2 * math.pi)<br>    )</pre><pre># log(pi)<br>    log_pi = torch.log(pi + 1e-8)</pre><pre># log-sum-exp<br>    log_sum = torch.logsumexp(log_pi + log_prob, dim=-1)</pre><pre>return -log_sum.mean()</pre><pre># 4) MODELİ EĞİTME</pre><pre>model = RNN_MDN()<br>optimizer = optim.Adam(model.parameters(), lr=0.003)</pre><pre>epochs = 20</pre><pre>for epoch in range(epochs):<br>    pi, mu, sigma = model(inputs)<br>    loss = mdn_loss(pi, mu, sigma, targets)</pre><pre>optimizer.zero_grad()<br>    loss.backward()<br>    optimizer.step()</pre><pre>print(f&quot;Epoch {epoch+1:02d} | Loss: {loss.item():.4f}&quot;)</pre><pre>print(&quot;Eğitim tamamlandı.\n&quot;)</pre><pre># 5) SAMPLING (MDN&#39;NİN EN GÜÇLÜ YANI)</pre><pre>def sample_from_mdn(pi, mu, sigma):<br>    &quot;&quot;&quot;<br>    Tek timestep için sample üretir.<br>    &quot;&quot;&quot;</pre><pre># Önce hangi mixture&#39;dan örnek alacağımızı seçiyoruz<br>    categorical = torch.distributions.Categorical(pi)<br>    mixture_idx = categorical.sample()</pre><pre># Seçilen mixture parametrelerini alıyoruz<br>    chosen_mu = mu.gather(-1, mixture_idx.unsqueeze(-1)).squeeze(-1)<br>    chosen_sigma = sigma.gather(-1, mixture_idx.unsqueeze(-1)).squeeze(-1)</pre><pre># Gaussian&#39;dan örnekleme<br>    normal = torch.distributions.Normal(chosen_mu, chosen_sigma)<br>    sample = normal.sample()</pre><pre>return sample</pre><pre># 6) MODEL GERÇEKTEN İKİ MOD ÖĞRENDİ Mİ?</pre><pre>with torch.no_grad():<br>    pi, mu, sigma = model(inputs[:1])</pre><pre>print(&quot;Son timestep mixture weights:&quot;, pi[0, -1])<br>    print(&quot;Son timestep mu değerleri:&quot;, mu[0, -1])</pre><h3>Sonuç: Belirsizliği Kucaklayın</h3><p>RNN-MDN, makine öğrenmesinin geleceğini temsil ediyor: Belirsizliği bir sorun değil, bir fırsat olarak görmek. Bu yazı boyunca adım adım ilerleyerek, hem temel sezgileri hem teknik detayları dengeledik. Artık zihninizde net bir çerçeve var, RNN sıralı veriyi yönetir, MDN olasılıkları ekler.</p><p>Eğer bu konuyu denemek isterseniz, yukarıdaki PyTorch örneğiyle başlayın. Sorularınız varsa lütfen yorumlarda sorun ve ulaşmaktan çekinmeyin! 😊</p><p><em>Bu yazı, konuyu sindirilebilir kılmak için benzetmeler ve adımlar kullandı. Kaynaklar: Bishop’un orijinal MDN makalesi ve Graves’in RNN uygulamaları.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c61dfc502c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Java: Variables, Loops, & OOP Basics]]></title>
            <link>https://medium.com/@ardaerdogav/getting-started-with-java-variables-loops-oop-basics-7efdff57a75b?source=rss-934f7f192c9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7efdff57a75b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Arda Erdoğan]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 19:41:10 GMT</pubDate>
            <atom:updated>2024-09-23T19:43:25.146Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java for Beginners: Mastering Variables, Loops, and OOP</h3><h4>Join me on my journey to understanding Java’s fundamentals, from handling variables and loops to overcoming the challenges of object-oriented programming.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyDmz1YRHm7J169TaPDj9w.png" /><figcaption>Java Logo</figcaption></figure><p>If you’re just starting with Java programming, you’re in good company! I’m new to it myself and, like many of you, I’ve had my fair share of “Aha!” moments along with some frustrating hurdles. In this post, I want to walk you through the fundamentals of Java: variables, loops, and object-oriented programming (OOP). Along the way, I’ll share some of the challenges I encountered and how I overcame them, so you can avoid similar pitfalls!</p><h3>1. Understanding Variables in Java</h3><p>Variables are one of the building blocks of any programming language, and Java is no exception. They act as containers for storing data values, and you’ll use them constantly.</p><h4>Types of Variables</h4><p>In Java, variables are strongly typed, meaning you need to declare the type of data a variable will hold. The most common types you’ll encounter are:</p><ul><li><strong>int</strong>: For integers (whole numbers)</li><li><strong>double</strong>: For decimal numbers</li><li><strong>boolean</strong>: For true/false values</li><li><strong>String</strong>: For text</li></ul><p>Here’s a simple example:</p><pre>int age = 25;       // stores a whole number<br>double salary = 2500.50;  // stores a decimal value<br>boolean isJavaFun = true;  // stores a true/false value<br>String name = &quot;Alice&quot;;  // stores a string</pre><h4>My Challenge with Variables</h4><p>Initially, I struggled with the idea that Java is statically typed, meaning you have to specify the type of each variable. This was confusing for me, as I was more familiar with dynamically typed languages where the type is assigned automatically. To get through this, I started creating small programs where I deliberately used different data types, testing how Java handles each one. This hands-on approach really helped me solidify my understanding of variable types.</p><h3>2. Mastering Loops: The Key to Repetition</h3><p>Loops are essential in programming because they allow you to repeat a block of code multiple times. In Java, the most commonly used loops are for, while, and do-while.</p><h4>The for Loop</h4><p>The for loop is perfect when you know in advance how many times you want to iterate. Here&#39;s a basic structure:</p><pre>for (int i = 0; i &lt; 5; i++) {<br>    System.out.println(&quot;Loop iteration: &quot; + i);<br>}</pre><p>This loop will print the iteration number from 0 to 4. You can think of it as:</p><ol><li><strong>Initialization</strong> (int i = 0): Setting up a counter.</li><li><strong>Condition</strong> (i &lt; 5): The loop runs as long as this is true.</li><li><strong>Increment</strong> (i++): Incrementing the counter by 1 on each iteration.</li></ol><h4>The while Loop</h4><p>The while loop keeps running as long as the condition is true. For example:</p><pre>int count = 0;<br>while (count &lt; 5) {<br>    System.out.println(&quot;Count: &quot; + count);<br>    count++;<br>}</pre><h4>The do-while Loop</h4><p>The do-while loop is similar to the while loop, but it guarantees that the loop will run at least once, even if the condition is false at the beginning.</p><pre>int number = 6;<br>do {<br>    System.out.println(&quot;This runs at least once, even if condition is false.&quot;);<br>} while (number &lt; 5);</pre><h4>My Challenge with Loops</h4><p>When I first started with loops, I kept running into infinite loops — situations where the loop never ended! This happens if you forget to update the loop variable (e.g., forgetting i++ in a for loop). To avoid this, I began commenting out each part of my loop and running small test cases. It’s important to always check your loop condition carefully.</p><h3>3. Demystifying Object-Oriented Programming (OOP)</h3><p>If you’re new to Java, you’ll quickly discover that it is an object-oriented language. This means that the focus is on creating objects — blueprints that model real-world entities. OOP principles help keep your code organized, scalable, and reusable.</p><h4>The Four Pillars of OOP</h4><ul><li><strong>Encapsulation</strong>: Grouping data (variables) and methods (functions) that operate on the data into a single unit, known as a class.</li></ul><pre>class Car {<br>    String model;<br>    int year;<br><br>    public void displayInfo() {<br>        System.out.println(&quot;Model: &quot; + model + &quot;, Year: &quot; + year);<br>    }<br>}</pre><ul><li><strong>Inheritance</strong>: A way to create new classes based on existing ones, inheriting fields and methods.</li></ul><pre>class Vehicle {<br>    String type;<br>}<br><br>class Car extends Vehicle {<br>    String model;<br>}</pre><ul><li><strong>Polymorphism</strong>: The ability to present the same method or object in different forms. Essentially, a single action can behave differently depending on the object calling it.</li></ul><pre>class Animal {<br>    public void sound() {<br>        System.out.println(&quot;Some sound&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br>    public void sound() {<br>        System.out.println(&quot;Bark&quot;);<br>    }<br>}<br><br>Animal myDog = new Dog();<br>myDog.sound();  // This will print &quot;Bark&quot;</pre><ul><li><strong>Abstraction</strong>: Hiding complex implementation details and showing only the necessary parts to the user.</li></ul><pre>abstract class Shape {<br>    abstract void draw();<br>}<br><br>class Circle extends Shape {<br>    void draw() {<br>        System.out.println(&quot;Drawing a circle&quot;);<br>    }<br>}</pre><h4>My Challenge with OOP</h4><p>The concept of creating classes and objects was new to me. At first, I wasn’t sure why we needed to use classes — why not just write all code in one place? But as I started writing larger programs, I saw how OOP helps in organizing code. The hardest part was understanding inheritance and polymorphism. To overcome this, I created several small projects, experimenting with class hierarchies and method overriding. This practice gave me a clearer picture of how everything fits together.</p><h3>4. Tips for Overcoming Challenges in Java</h3><p>During my Java journey, I faced many roadblocks, but I managed to push through with a few strategies that may help you too:</p><ul><li><strong>Start Small</strong>: Break down complex topics into smaller, manageable chunks. Don’t try to grasp everything at once.</li><li><strong>Experiment Often</strong>: Try writing small programs that test one concept at a time. For example, write a program that only deals with loops or one that focuses solely on using variables.</li><li><strong>Learn from Mistakes</strong>: Don’t be afraid to make errors. Debugging is where most of the learning happens. Every error message is a clue to what’s going wrong, so take time to understand and solve it.</li><li><strong>Ask for Help</strong>: Don’t hesitate to reach out to the community. There are many resources online, from forums to videos, where other developers are happy to help.</li></ul><h3>5. Conclusion</h3><p>Java might seem overwhelming at first, but once you start understanding the basics — like variables, loops, and OOP — it all begins to make sense. These building blocks will form the foundation of everything you’ll create as a Java developer. Take your time, experiment with code, and don’t be afraid to make mistakes!</p><p>Sharing my journey as a beginner helped me reinforce my own learning, and I hope this post helps you on your Java journey. Whether you’re struggling with loops, trying to figure out classes, or just getting started with variables, remember that persistence is key. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7efdff57a75b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security Roles: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ardaerdogav/spring-security-roles-a-comprehensive-guide-e134eafaabef?source=rss-934f7f192c9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e134eafaabef</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Arda Erdoğan]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 05:11:48 GMT</pubDate>
            <atom:updated>2024-06-07T05:11:48.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*v8OZpwI6L2GmLu5-rXffRg.jpeg" /></figure><h3>Introduction</h3><p>In today’s dynamic web environment, securing applications is more critical than ever. One of the essential components of application security is managing user permissions and roles. Spring Security provides a robust framework for handling these through concepts like GrantedAuthority and Role. In this article, we’ll dive deep into these concepts, understanding their differences, and how they play a vital role in securing your Spring-based applications.</p><h4>What is a GrantedAuthority?</h4><p>A GrantedAuthority is essentially a “permission” or a “right” granted to a user. It’s a key concept in Spring Security, allowing you to define what actions a user can perform within an application.</p><ul><li><strong>Permissions as Strings</strong>: In practice, GrantedAuthority instances are usually represented as strings (like &quot;READ_PRIVILEGES&quot; or &quot;WRITE_PRIVILEGES&quot;). These strings help in identifying the permissions and enabling access control checks.</li><li><strong>Role of getAuthority()</strong>: The method getAuthority() in a GrantedAuthority returns the string representation of the permission. This helps in deciding if a user should be granted access to a resource or not.</li></ul><h4>Implementing GrantedAuthority in Spring Security</h4><p>To assign GrantedAuthority to a user, you typically implement the UserDetailsService interface. This service returns a UserDetails implementation containing the necessary GrantedAuthority instances.</p><pre>import org.springframework.security.core.GrantedAuthority;<br><br>public class SimpleGrantedAuthority implements GrantedAuthority {<br>    private String authority;<br><br>    public SimpleGrantedAuthority(String authority) {<br>        this.authority = authority;<br>    }<br><br>    @Override<br>    public String getAuthority() {<br>        return this.authority;<br>    }<br>}</pre><p>In this example, SimpleGrantedAuthority is a basic implementation where we store and retrieve the authority as a string.</p><h4>Understanding Roles in Spring Security</h4><p>Roles in Spring Security are essentially GrantedAuthority instances with a naming convention. Typically, roles start with the prefix ROLE_ (e.g., ROLE_USER, ROLE_ADMIN). This convention helps in differentiating roles from other types of authorities.</p><ul><li><strong>Roles as Authorities</strong>: A role is a special type of GrantedAuthority. For instance, ROLE_ADMIN is just a GrantedAuthority that follows a specific naming pattern.</li><li><strong>Spring Security Role Management</strong>: In Spring Security, roles are handled distinctly, especially in security expressions and access decision voters like RoleVoter. Prior to Spring Security 4, roles and authorities were often treated interchangeably. From Spring Security 4 onwards, roles with the ROLE_ prefix are consistently handled, making it easier to manage role-based access controls.</li></ul><h4>Role and Authority Management in Spring Security 4+</h4><p>Spring Security 4 brought consistency in how roles are handled. For example, hasRole(&#39;ADMIN&#39;) and hasAuthority(&#39;ROLE_ADMIN&#39;) are equivalent because Spring automatically adds the ROLE_ prefix when you use hasRole.</p><pre>@PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>public String adminAccess() {<br>    return &quot;Access granted to admin.&quot;;<br>}</pre><p>In this code, @PreAuthorize is used to secure the method, ensuring only users with the ADMIN role can access it.</p><h4>Practical Use Cases of GrantedAuthority and Roles</h4><p>Consider a scenario where you have users with different roles and permissions. An admin might have permissions to delete accounts, create new users, and run batch jobs, while a regular user might only have read access to account information.</p><p><strong>Example Roles and Operations</strong>:</p><ul><li>ROLE_ADMIN might include permissions like OP_DELETE_ACCOUNT, OP_CREATE_USER, OP_RUN_BATCH_JOB.</li><li>ROLE_USER might include permissions like OP_READ_ACCOUNT.</li></ul><p><strong>Mapping Roles to Authorities</strong>:</p><pre>@Entity<br>class Role implements GrantedAuthority {<br>    @Id<br>    private String id;<br><br>    @ManyToMany<br>    private final List&lt;Operation&gt; allowedOperations = new ArrayList&lt;&gt;();<br><br>    @Override<br>    public String getAuthority() {<br>        return id;<br>    }<br><br>    public Collection&lt;GrantedAuthority&gt; getAllowedOperations() {<br>        return allowedOperations;<br>    }<br>}<br><br>@Entity<br>class User {<br>    @Id<br>    private String id;<br><br>    @ManyToMany<br>    private final List&lt;Role&gt; roles = new ArrayList&lt;&gt;();<br><br>    public Collection&lt;Role&gt; getRoles() {<br>        return roles;<br>    }<br>}<br><br>@Entity<br>class Operation implements GrantedAuthority {<br>    @Id<br>    private String id;<br><br>    @Override<br>    public String getAuthority() {<br>        return id;<br>    }<br>}</pre><p>In this pseudo-code, roles and operations are mapped to the user. Each role is a GrantedAuthority that can have multiple operations associated with it.</p><h4>Security Context with GrantedAuthority</h4><p>When a user logs in, the UserDetailsService collects all the roles and associated operations and includes them in the security context.</p><ul><li><strong>Admin’s Security Context</strong>: ROLE_ADMIN, OP_DELETE_ACCOUNT, OP_READ_ACCOUNT, OP_RUN_BATCH_JOB</li><li><strong>User’s Security Context</strong>: ROLE_USER, OP_READ_ACCOUNT</li></ul><p>The UserDetails.getAuthorities() method should return all these authorities to ensure proper access control.</p><h3>Conclusion</h3><p>Understanding GrantedAuthority and Role is crucial for implementing a robust security mechanism in Spring-based applications. By appropriately assigning and managing these authorities, you can enforce precise and flexible access controls, enhancing the overall security posture of your application.</p><h4>References</h4><ul><li><a href="https://docs.spring.io/spring-security/site/docs/current/reference/html5/">Spring Security Documentation</a></li><li><a href="https://docs.spring.io/spring-security/site/docs/4.0.x/reference/html/migration-3.2.html">Migrating from Spring Security 3 to 4</a></li></ul><p>By adhering to these principles and effectively leveraging GrantedAuthority and Role in your application, you can create a secure, scalable, and maintainable security architecture.</p><p>If you found this article helpful, make sure to share it with your peers and follow for more insights on Spring Security and application development best practices.</p><p><em>This article is written by Arda Erdoğan, a passionate software developer with expertise in Java and Spring ecosystem.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e134eafaabef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Better Code with SOLID Principles]]></title>
            <link>https://medium.com/@ardaerdogav/writing-better-code-with-solid-principles-b73f08f3fcf3?source=rss-934f7f192c9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b73f08f3fcf3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Arda Erdoğan]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 22:31:53 GMT</pubDate>
            <atom:updated>2024-06-03T22:31:53.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*35nGcF6UPSQCAPNbebJWcw.png" /><figcaption>Solid Principles</figcaption></figure><p>Have you ever been told that your code <strong><em>isn’t great</em>?</strong></p><p>If so, don’t worry, it happens to everyone as they learn. The good news is, improving your code is pretty simple — if you’re up for it. One of the best ways to do that is by learning some basic programming design principles.</p><p>These principles act as a guide to becoming a better programmer. Today, we’ll look at five important principles summed up in the acronym SOLID. As the famous <strong>Robert C. Martin</strong>, also known as “<strong>Uncle Bob</strong>,” once said,</p><blockquote>“The goal of software design is to always produce code that is easy to change.”</blockquote><p>And that’s exactly where <strong>SOLID</strong> comes in to help.</p><h3>What Are SOLID Principles?</h3><p>SOLID stands for five design principles that aim to make software designs more understandable, flexible, and maintainable:</p><ul><li><strong>S</strong>ingle Responsibility Principle (SRP)</li><li><strong>O</strong>pen/Closed Principle (OCP)</li><li><strong>L</strong>iskov Substitution Principle (LSP)</li><li><strong>I</strong>nterface Segregation Principle (ISP)</li><li><strong>D</strong>ependency Inversion Principle (DIP)</li></ul><p>Let’s dive into each principle with examples in <strong>Java</strong>.</p><h4>1. Single Responsibility Principle (SRP)</h4><p>A class should have only one reason to change, meaning it should have only one job or responsibility. This makes your code more modular and easier to maintain.</p><p>As Uncle Bob says, <em>“A module should be responsible to one, and only one, user or stakeholder.”</em></p><p><strong>Bad Practice:</strong></p><pre>public class Person {<br>    private String name;<br>    private int age;<br><br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    public void sendEmail(String message) {<br>        System.out.println(&quot;Sending email to &quot; + name + &quot;: &quot; + message);<br>    }<br><br>    public void calculateTax() {<br>        int tax = age * 100;<br>        System.out.println(name + &quot;&#39;s tax: &quot; + tax);<br>    }<br>}</pre><p>In this example, the Person class has more than one responsibility. It handles both email sending and tax calculation, which are unrelated tasks.</p><p><strong>Good Practice:</strong></p><pre>public class Person {<br>    private String name;<br>    private int age;<br><br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}<br><br>public class EmailSender {<br>    public void sendEmail(Person person, String message) {<br>        System.out.println(&quot;Sending email to &quot; + person.getName() + &quot;: &quot; + message);<br>    }<br>}<br><br>public class TaxCalculator {<br>    public void calculateTax(Person person) {<br>        int tax = person.getAge() * 100;<br>        System.out.println(person.getName() + &quot;&#39;s tax: &quot; + tax);<br>    }<br>}</pre><p>Here, we have separated the responsibilities into different classes, making each class have a single responsibility.</p><h4><strong>2. Open/Closed Principle (OCP)</strong></h4><p>Software entities should be open for extension but closed for modification. This means that you should be able to add new functionality without changing the existing code.</p><p>Bertrand Meyer, who coined this principle, stated,</p><blockquote>“A module will be said to be open if it is still available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs.”</blockquote><p><strong>Bad Practice:</strong></p><pre>public class Shape {<br>    private String shapeType;<br>    private double width;<br>    private double height;<br><br>    public Shape(String shapeType, double width, double height) {<br>        this.shapeType = shapeType;<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    public double calculateArea() {<br>        if (&quot;rectangle&quot;.equals(shapeType)) {<br>            return width * height;<br>        } else if (&quot;triangle&quot;.equals(shapeType)) {<br>            return (width * height) / 2;<br>        }<br>        return 0;<br>    }<br>}</pre><p>This code violates the OCP because every time a new shape is added, we have to modify the Shape class.</p><p><strong>Good Practice:</strong></p><pre>public abstract class Shape {<br>    public abstract double calculateArea();<br>}<br><br>public class Rectangle extends Shape {<br>    private double width;<br>    private double height;<br><br>    public Rectangle(double width, double height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    @Override<br>    public double calculateArea() {<br>        return width * height;<br>    }<br>}<br><br>public class Triangle extends Shape {<br>    private double width;<br>    private double height;<br><br>    public Triangle(double width, double height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    @Override<br>    public double calculateArea() {<br>        return (width * height) / 2;<br>    }<br>}</pre><p>Here, we can add new shapes by creating new classes that extend the Shape class without modifying the existing code.</p><h4>3. Liskov Substitution Principle (LSP)</h4><p>Subtypes must be substitutable for their base types without altering the correctness of the program. This means that a subclass should override the base class methods in a way that does not break functionality from a client’s point of view.</p><p><strong>Bad Practice:</strong></p><pre>public class Bird {<br>    public void fly() {<br>        // Birds can fly<br>    }<br>}<br><br>public class Duck extends Bird {<br>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Duck is flying.&quot;);<br>    }<br>}<br><br>public class Ostrich extends Bird {<br>    @Override<br>    public void fly() {<br>        throw new UnsupportedOperationException(&quot;Ostriches can&#39;t fly.&quot;);<br>    }<br>}</pre><p><strong>Good Practice:</strong></p><pre>public abstract class Bird {<br>    public abstract void move();<br>}<br><br>public class Duck extends Bird {<br>    @Override<br>    public void move() {<br>        System.out.println(&quot;Duck is flying.&quot;);<br>    }<br>}<br><br>public class Ostrich extends Bird {<br>    @Override<br>    public void move() {<br>        System.out.println(&quot;Ostrich is running.&quot;);<br>    }<br>}</pre><p>Here, we have a more general move method that is implemented appropriately in each subclass, adhering to the LSP.</p><h4>4. Interface Segregation Principle (ISP)</h4><p>No client should be forced to depend on methods it does not use. This means that creating specific interfaces for different clients is better than having a general-purpose interface.</p><p>As Uncle Bob says,</p><blockquote>“Clients should not be forced to depend upon interfaces that they do not use.”</blockquote><p><strong>Bad Practice:</strong></p><pre>public interface Animal {<br>    void walk();<br>    void swim();<br>    void fly();<br>}<br><br>public class Dog implements Animal {<br>    @Override<br>    public void walk() {<br>        System.out.println(&quot;Dog is walking.&quot;);<br>    }<br><br>    @Override<br>    public void swim() {<br>        // Dogs can&#39;t swim<br>    }<br><br>    @Override<br>    public void fly() {<br>        // Dogs can&#39;t fly<br>    }<br>}</pre><p>In this example, the Dog class is forced to implement methods it doesn&#39;t use (swim and fly).</p><p><strong>Good Practice:</strong></p><pre>public interface Walkable {<br>    void walk();<br>}<br><br>public interface Swimmable {<br>    void swim();<br>}<br><br>public interface Flyable {<br>    void fly();<br>}<br><br>public class Dog implements Walkable {<br>    @Override<br>    public void walk() {<br>        System.out.println(&quot;Dog is walking.&quot;);<br>    }<br>}<br><br>public class Fish implements Swimmable {<br>    @Override<br>    public void swim() {<br>        System.out.println(&quot;Fish is swimming.&quot;);<br>    }<br>}<br><br>public class Bird implements Walkable, Flyable {<br>    @Override<br>    public void walk() {<br>        System.out.println(&quot;Bird is walking.&quot;);<br>    }<br><br>    @Override<br>    public void fly() {<br>        System.out.println(&quot;Bird is flying.&quot;);<br>    }<br>}</pre><p>Here, we have created specific interfaces for each action, and the classes implement only the interfaces they need.</p><h4>5. Dependency Inversion Principle (DIP)</h4><p>High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g., interfaces or abstract classes). This principle aims to decouple high-level and low-level modules by introducing abstractions.</p><p>Uncle Bob states,</p><blockquote>“High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.”</blockquote><p><strong>Bad Practice:</strong></p><pre>public class SQLDatabase {<br>    public void fetchData() {<br>        System.out.println(&quot;Fetching data from SQL database...&quot;);<br>    }<br>}<br><br>public class ReportGenerator {<br>    private SQLDatabase database;<br><br>    public ReportGenerator(SQLDatabase database) {<br>        this.database = database;<br>    }<br><br>    public void generateReport() {<br>        database.fetchData();<br>        System.out.println(&quot;Generating report...&quot;);<br>    }<br>}</pre><p>Here, ReportGenerator directly depends on SQLDatabase, making it hard to switch databases.</p><p><strong>Good Practice:</strong></p><pre>public interface Database {<br>    void fetchData();<br>}<br><br>public class SQLDatabase implements Database {<br>    @Override<br>    public void fetchData() {<br>        System.out.println(&quot;Fetching data from SQL database...&quot;);<br>    }<br>}<br><br>public class MongoDatabase implements Database {<br>    @Override<br>    public void fetchData() {<br>        System.out.println(&quot;Fetching data from MongoDB...&quot;);<br>    }<br>}<br><br>public class ReportGenerator {<br>    private Database database;<br><br>    public ReportGenerator(Database database) {<br>        this.database = database;<br>    }<br><br>    public void generateReport() {<br>        database.fetchData();<br>        System.out.println(&quot;Generating report...&quot;);<br>    }<br>}</pre><p>In this example, ReportGenerator depends on the Database interface, allowing it to work with any database implementation.</p><h3>Conclusion</h3><p>In the ever-evolving world of software development, adhering to the SOLID principles can help you create more maintainable, flexible, and robust code. As Uncle Bob puts it,</p><blockquote>“The principles are not about making software easy to write, they are about making it easy to read, easy to understand, and easy to change.”</blockquote><p>Embracing these principles will not only improve your coding skills but also prepare you to tackle larger and more complex projects with confidence. Happy coding!</p><p>I just publish my research in a simple way. <strong>Let’s connect!</strong></p><p><a href="http://www.linkedin.com/in/ardushka">www.linkedin.com/in/ardushka</a> | <a href="https://x.com/ardazlata">https://x.com/ardazlata</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b73f08f3fcf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping with Python: Data Collection and Analysis]]></title>
            <link>https://medium.com/@ardaerdogav/web-scraping-with-python-data-collection-and-analysis-f23b3d559e52?source=rss-934f7f192c9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f23b3d559e52</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Arda Erdoğan]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 01:50:16 GMT</pubDate>
            <atom:updated>2023-03-25T01:53:24.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, I will give an example of a project for Web Scraping and analyzing data using Python.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEbPfwYCO0HyRjBeuvUd9g.png" /></figure><p>This project will collect product data from a simple example site and then analyze this data. For example, you can collect headlines on a news site, product prices in a store, or data on a stock.</p><p>You know that <strong>Python libraries are indispensable</strong>. Let’s proceed by simply introducing the libraries as well.</p><h4>#Request</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*hu7GObqOUlXWH-qLxNum1g.png" /><figcaption>Requests Python</figcaption></figure><p>The “<strong>requests</strong>” library is a library that enables <strong>HTTP</strong> operations in Python. You can get their content by sending <strong>GET</strong> and <strong>POST</strong> requests to websites.</p><p>For example, the following code block allows connecting to the “example.com” website in Python:</p><pre>import requests<br><br>url = &#39;http://example.com&#39;<br>r = requests.get(url)<br>print(r.text)</pre><h4>#Beautiful Soup</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*VAhoXzBGSPaztlsUA2HbnQ.png" /></figure><p>Beautiful Soup is an HTML and XML parsing library used in the Python programming language. It is used to extract and manipulate data from web pages. It allows you to find and manipulate the contents of the pages.</p><p>The “Beautiful Soup” library allows not only scraping data from web pages, but also analyzing this data. For example, the following code block takes the <strong>“h1”</strong> headers from the <strong>“example.com”</strong> website:</p><pre>from bs4 import BeautifulSoup<br>import requests<br><br>url = &#39;http://example.com&#39;<br>r = requests.get(url)<br>soup = BeautifulSoup(r.content, &#39;html.parser&#39;)<br>headers = soup.find_all(&#39;h1&#39;)<br>for header in headers:<br>    print(header.text)</pre><p>With these two libraries, it is quite easy to collect data from an e-commerce site. The basic steps of the project are as follows:</p><ol><li>Connect to the website and get its content.</li><li>Parse the data and collect the necessary information.</li><li>Save the collected data to a file or database.</li><li>Analyze data and show results.</li></ol><pre>from bs4 import BeautifulSoup<br>import requests<br>import csv<br><br>url = &#39;https://www.example.com/products&#39;<br>r = requests.get(url)<br>soup = BeautifulSoup(r.content, &#39;html.parser&#39;)<br><br>products = []<br><br>for product in soup.find_all(&#39;div&#39;, class_=&#39;product&#39;):<br>    name = product.find(&#39;h3&#39;).text.strip()<br>    price = product.find(&#39;div&#39;, class_=&#39;price&#39;).text.strip()<br>    rating = product.find(&#39;span&#39;, class_=&#39;rating&#39;).text.strip()<br>    products.append({&#39;name&#39;: name, &#39;price&#39;: price, &#39;rating&#39;: rating})<br><br>with open(&#39;products.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    writer = csv.DictWriter(file, fieldnames=[&#39;name&#39;, &#39;price&#39;, &#39;rating&#39;])<br>    writer.writeheader()<br>    for product in products:<br>        writer.writerow(product)</pre><p>This code block takes all the products from “example.com/products” and creates a dictionary with the product name, price, and rating. This data is then saved in a CSV file named “products.csv”.</p><p>This example demonstrates the Web Scraping process and saving the collected data. This data can then be analyzed with many different data analysis tools. For example, in Python you can use the Pandas library to export data to a DataFrame and then generate graphs and statistics.</p><p><em>Thanks for reading. I hope this post was helpful.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f23b3d559e52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread ve Process]]></title>
            <link>https://medium.com/@ardaerdogav/thread-ve-process-6b383f20fe9?source=rss-934f7f192c9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b383f20fe9</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[process]]></category>
            <dc:creator><![CDATA[Arda Erdoğan]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 16:25:22 GMT</pubDate>
            <atom:updated>2023-03-21T16:27:40.012Z</atom:updated>
            <content:encoded><![CDATA[<p>Thread kavramını programlama dilleri üzerinden örneklerle değil, işletim sistemindeki davranışı üzerinden konuşacağız. Harici olarak paralel programlama, multi-threading gibi konuları da yüzeyden ele alacağız.</p><h4>Thread Nedir?</h4><p>Thread, bir işletim sistemi içinde çalışan bağımsız bir iş parçacığıdır. Genelde Türkçe’ye “İplik” olarak geçse de ligth-weight process olarak da nitelendirilebilir. Bir process’in birden fazla işi aynı anda yapmasını sağlayan yapılara thread denir. Bir işlem, birçok thread içerebilir ve her thread, işlemdeki diğer thread’lere göre bağımsız bir şekilde çalışabilir.</p><p>Thread’ler program kodu, data, dosyalar gibi işletim sistemi kaynaklarını ortak kullanır. Eğer bir process, birden fazla thread’e sahipse; birden fazla görevi eş-zamanlı yapabilir. Günümüzdeki modern bilgisayarlarda çalışan yazılım uygulamalarının çoğu multi-thread çalışırlar. Uygulamalar, çok sayıda thread’e sahip tek process şeklinde geliştirilirler. Bir web tarayıcı, bir thread ile veri aktarımı yapabilir. Başka thread ile verileri ekranda görüntüleyebilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*k8xesVw-sJs82SjDL5XsaA.jpeg" /><figcaption>2 thread, 1 işi birlikte yapabilmek için T zamanda yol alıyorlar.</figcaption></figure><p>Thread aynı anda sadece tek bir iş yapabilir. Kısaca <strong>N adet thread N adet iş yapabilir.</strong> Thread’ler çok çekirdekli işlemcilerde farklı çekirdeklerde eş zamanlı olarak çalıştırılabilirler. Buna paralel programlama denir.</p><p>Özet olarak: Thread (iş parçacığı) kullanımı, birden fazla işlemin tek bir akışı paylaşarak neredeyse eşzamanlı bir şekilde gerçekleşmesini sağlar.</p><p>Not-1: “Neredeyse eş zamanlı” cümlesinin yazılma nedeni ise bazı threadler çalışma mantığına göre milisaniye bazında çalıştığı için ve yazılım testlerinde servis yada önyüz testlerinde farklılık gösterdiği, işlemcilerde ise sistemler üzerindeki çalışma şekli diğerlerine göre farklı olduğu için bu yazılmıştır.</p><p>Thread’ler, tek bir işlemciye sahip sistemlerde bile çoklu görev yürütmeyi mümkün kılar. Bir iş parçacığı, diğer bir iş parçacığına ihtiyaç duymadan çalışabilir ve diğer iş parçacıklarının çalışmasını etkilemez. Bu nedenle, thread’ler bir işlemciyi en üst düzeyde kullanarak işlemlerin daha hızlı yürütülmesine yardımcı olabilir.</p><h4>1. User Thread</h4><p>Kullanıcı thread’leri, bir uygulama veya işlem içinde oluşturulur ve uygulama seviyesinde çalışır. Bu thread’ler, işlemci tarafından işlenen iş parçacıklarıdır ve işletim sistemi tarafından yönetilmezler. Kullanıcı thread’leri, işlemci işlemlerinin yanı sıra kullanıcı işlemiyle ilişkili tüm verileri de işleyebilirler. Kullanıcı thread’leri hızlı bir şekilde oluşturulabilir ve yönetimi kolaydır.</p><h4>2. Kernel Thread</h4><p>Kernel thread kavramı, process içinde yer alan ve kernel seviyesinde yönetilen bir thread türüdür. Kernel thread’ler işletim sistemi tarafından zamanlanmaktadır. Bu tip thread’ler sadece kernel modda çalışmaktadır.</p><p>Kernel thread’leri, işletim sistemi çekirdeği tarafından oluşturulur ve yönetilir. Bu thread’ler, işletim sistemi seviyesinde çalışır ve işletim sistemi kaynaklarına erişebilirler. Çekirdek thread’leri, bir uygulamanın yanı sıra işletim sistemi işlemlerini de işleyebilirler. Çekirdek thread’leri daha güçlü bir yönetim gerektirir ve genellikle işletim sistemi tarafından otomatik olarak oluşturulur ve yönetilirler.</p><blockquote>User thread’lerde bir thread sistem çağrılarını bloklayan bir operasyon gerçekleştirirse tüm process bloklanır. Kernel thread’lerde ise bir thread bloklasa bile farklı bir thread çalışmasına devam edebilir.</blockquote><h3>Process</h3><p>Çalışan programlara process denir. Örnek olarak Word, Excel ve benzeri başka bir uygulama henüz çalışmıyorken bir programdır. Programlar çalıştırıldığında process olarak nitelendirilir. Process’ler hayatlarına tek bir thread ile başlar ve bu thread’e <strong>main thread</strong> adı verilmektedir. Diğer thread’ler ise programın çalışma esnasında sistem fonksiyonları tarafından yaratılmaktadır.</p><p>Bilgisayar bilimlerinde process terimi, belleğe yüklenmiş ve işlemcide (CPU) yürütülmekte olan bir program olarak tanımlanmaktadır. Uygulamalar diskte çalışmaz halde bulunurken ise program olarak tanımlanır. Bir program, kendi başına pasif komut yığınıdır ve işlem ise bu komutların aktif olarak yürütülmesidir.</p><p>Bir process kendi içerisinde başka bir process daha oluşturabilir, bu process’e ise <strong>child process</strong> adı verilir.</p><h4>Process &amp; Thread Farkları</h4><ul><li>Process, yürütülebilir bir dosya veya programdır.</li><li>Thread ise, bir işlem içinde yürütülen bir iş parçacığıdır.</li><li>Process, kendi adres alanında çalışır ve kaynakları kendi başına yönetir.</li><li>Thread, aynı işlem içindeki diğer thread’lerle kaynakları paylaşır ve işlem kaynaklarını kullanır.</li><li>Process, bir işlemi yöneten ve planlayan işletim sistemi tarafından yönetilir.</li><li>Thread, bir işlem içindeki iş parçacıklarını yöneten işletim sistemi tarafından yönetilir.</li><li>Process, başka bir process tarafından veya işletim sistemi tarafından başlatılabilir.</li><li>Thread, bir process tarafından oluşturulabilir.</li><li>Process’ler, birbirleriyle işbirliği yapmak için işletim sistemi aracılığıyla iletişim kurmak zorundadır.</li><li>Thread’ler, aynı işlem içindeki diğer thread’lerle işbirliği yapabilir ve birbirlerine mesaj gönderebilir.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*MKFT-CsefwutN4uut7HXRg.png" /></figure><ol><li><strong>Thread oluşturma</strong>: İşletim sistemi veya programlama dili, bir thread oluşturmak için gerekli fonksiyonları çağırır ve yeni bir thread oluşturur. Bu işlem genellikle bir başlatıcı fonksiyonu belirtmek ve thread’in çalışacağı özellikleri (örneğin, öncelik, bellek boyutu vb.) tanımlamak gibi parametreleri belirtmek için bir arayüz sağlar.</li><li><strong>Thread yürütme</strong>: Oluşturulan thread, işletim sistemi veya programlama dilinin thread yönetim mekanizmeleri tarafından planlanır ve yürütülür. Thread’in yürütülmesi, thread’in başlatıcı fonksiyonunu çalıştırmak ve belirtilen özelliklere göre kaynakları kullanmak anlamına gelir.</li><li><strong>Thread senkronizasyonu</strong>: Birden fazla thread’in aynı anda çalıştırıldığı durumlarda, thread’ler arasında senkronizasyon sağlanması gerekir. Bu, thread’ler arasında veri paylaşımı veya senkronize edilmiş bir işlem gerçekleştirmek için gerekli olabilir. Bu senkronizasyon, işletim sistemi veya programlama dilinin sağladığı senkronizasyon mekanizmaları kullanılarak gerçekleştirilir.</li><li><strong>Thread sonlandırma</strong>: Thread’in çalışması tamamlandığında veya hata durumlarında, işletim sistemi veya programlama dili thread’i sonlandırır. Thread sonlandırma işlemi, thread’in tüm kaynaklarını serbest bırakmak, paylaşılan verileri güncellemek veya temizlemek ve thread’in çalışması sırasında oluşabilecek herhangi bir hata durumunu ele almak için gerekli işlemleri gerçekleştirir.</li></ol><p>EKSTRA:</p><p><strong>Paralellism</strong>, birden fazla işlemci ya da çekirdekte aynı anda işlem yapılması anlamına gelmektedir. <strong>Concurrency</strong> ise tek bir process üzerinde eş zamanlı olarak birden fazla operasyonun gerçekleşmesidir.</p><p><strong>Daha fazlası:<em> </em></strong><a href="https://www.linkedin.com/in/ardaizlata/"><em>https://www.linkedin.com/in/ardaizlata</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b383f20fe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Arduino and how does it work?]]></title>
            <link>https://medium.com/@ardaerdogav/what-is-arduino-and-how-does-it-work-5b102f4174c0?source=rss-934f7f192c9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b102f4174c0</guid>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[diy]]></category>
            <dc:creator><![CDATA[Arda Erdoğan]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 22:26:13 GMT</pubDate>
            <atom:updated>2023-03-19T22:26:13.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Arduino is an open source hardware and software platform and is often used for embedded systems and robotic applications. Arduino is simple and easy to use and can be used in a variety of projects as it is compatible with many sensors and actuators.</p><figure><img alt="Arduino logo" src="https://cdn-images-1.medium.com/max/593/1*sCwOD22bycvCEXJn6lH9Dg.png" /><figcaption>Arduino Logo</figcaption></figure><h4><strong>Basic Parts of Arduino</strong></h4><p>Arduino has basic components such as microcontroller, USB port, input/output pins and power supply. The microcontroller is the brain where the programs run. In Arduino, usually ATMega328P or ATMega2560 microcontrollers are used. The USB port is used for programming the Arduino and data communication by connecting to the computer. Input/output pins allow data exchange between Arduino and other devices. The power supply is used to power the Arduino. The Arduino is usually powered by a USB cable or an external power supply.</p><figure><img alt="Arduino Uno R3" src="https://cdn-images-1.medium.com/max/900/1*KJZi1JUX1VNjf_VoHykshQ.jpeg" /></figure><h4>Arduino IDE</h4><p>Arduino IDE (Integrated Development Environment) is a software development environment used to program Arduino. Arduino IDE has a simple user interface and uses C++ as its programming language. Arduino IDE simplifies coding, compiling and uploading.</p><figure><img alt="Arduino IDE" src="https://cdn-images-1.medium.com/max/1024/1*VMOJhwaS_JwQhpoEVJFxgg.png" /><figcaption>Arduino IDE</figcaption></figure><h4>Coding</h4><p>Arduino coding is based on the C++ programming language and usually requires basic programming knowledge. Arduino coding is used to create programs that control and change the state of the input/output pins. Various projects can be performed, such as controlling the flashing of an LED or reading data from a sensor and displaying it on an LCD screen.</p><h4>Sample Projects</h4><p>Automatic Plant Irrigation System: You can automatically control the plant irrigation system by using a sensor that measures the moisture level of the soil.</p><p>Distance Meter: You can measure distance using an ultrasonic sensor. For example, it can be used to measure the distance in front of a robot to avoid an obstacle.</p><p>RGB LED Control: By using an Arduino to control RGB LEDs, you can create lighting effects in different colors.</p><p>RFID Lock System: You can create a lock system using RFID cards. When users swipe the correct card, the lock can be unlocked, otherwise it may remain locked.</p><p>Human Motion Detection System: Using <strong>PIR sensor</strong>, you can detect human movements in an area. For example, you can make a system that alerts you if thieves break in when no one is home.</p><p>Sound-Controlled RGB LED: Using Arduino, you can measure the sound level through the microphone sensor and shine the RGB LEDs in different colors to create a light show with music.</p><p>Digital Clock: Using the<strong> RTC module</strong> and an LCD screen, you can create a digital clock. You can also display alarm system or date and time information by adding additional features.</p><p>Besides these examples, many different projects can be done with Arduino. All you have to do is define an idea and buy the necessary components and start coding.</p><h4>Conclusion</h4><p>Arduino is constantly evolving as it is an open source platform. Therefore, there is no limit to the projects that can be done with Arduino. For high school students, Arduino is a great opportunity to practice and learn about programming and electronics. Students can develop their creativity and problem-solving skills by implementing many projects with Arduino. Besides, since there are many Arduino related resources available, it is possible for students to learn more and add different features to their projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b102f4174c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>