<?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 Gollu Ajay on Medium]]></title>
        <description><![CDATA[Stories by Gollu Ajay on Medium]]></description>
        <link>https://medium.com/@golluajay9?source=rss-133a3ed3518c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bIk6S4cM2b6gRCWWqOq2pg.jpeg</url>
            <title>Stories by Gollu Ajay on Medium</title>
            <link>https://medium.com/@golluajay9?source=rss-133a3ed3518c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:48:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@golluajay9/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[Real-Time Image Compression using SVD]]></title>
            <link>https://medium.com/@golluajay9/real-time-image-compression-using-svd-66ac29ecaf73?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/66ac29ecaf73</guid>
            <category><![CDATA[image-compression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[svd]]></category>
            <category><![CDATA[algebra]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 09:57:31 GMT</pubDate>
            <atom:updated>2024-12-01T03:07:52.237Z</atom:updated>
            <content:encoded><![CDATA[<p>Singular Value Decomposition (SVD) for image compression — ideal for anyone interested in data science and efficient data representation.</p><p>The Concept<br>SVD is a powerful tool in data science, breaking down complex data (like images) into simpler, structured components. For images, this translates into capturing the essence of an image while significantly reducing its size. It’s like taking a “snapshot” of the most important features of an image without storing every single detail!</p><p>Project Highlights<br>Adjustable Compression Level: Users can choose the level of compression they want (via a “k-value” slider) and instantly see how much of the image’s original quality is retained. The k-value represents the number of features kept — higher values mean more detail, lower values mean smaller files.</p><p>Data Optimization in Action: SVD doesn’t just shrink files; it demonstrates how dimensionality reduction helps in applications ranging from image processing to recommendation systems in data science.</p><p>Why SVD Matters in Data Science ?<br>This project reinforces how SVD and similar techniques can handle large, complex datasets effectively, a crucial skill in data science where we often work with high-dimensional data that needs simplifying.</p><p>This has been an eye-opening exploration into the practical power of linear algebra in data science! 💡</p><p>Why Grayscale?<br>Grayscale images are lighter than full-color ones because they contain only intensity values, not RGB color details. This makes them ideal for applications where color isn’t essential, letting us reduce file sizes even further.<br>By applying SVD to grayscale images, we preserved structure while significantly compressing the data — a simple yet powerful way to manage storage and processing.</p><p>Check out the project on GitHub: <a href="https://github.com/GolluAjay/Image-compression-svd">https://github.com/GolluAjay/Image-compression-svd</a></p><pre>from flask import send_file<br>from PIL import Image<br>import numpy as np<br><br>def compress_image_svd(image, k):<br>    # Convert image to grayscale for SVD<br>    original_image = image.convert(&#39;L&#39;)<br>    image_matrix = np.array(original_image)<br>    <br>    # Apply SVD<br>    U, S, Vt = np.linalg.svd(image_matrix, full_matrices=False) <br>    <br>    # Keep only the top-k singular values<br>    U_k = U[:, :k]<br>    S_k = np.diag(S[:k])<br>    Vt_k = Vt[:k, :]<br>    <br>    # Reconstruct the image using top-k components<br>    compressed_image_matrix = np.dot(U_k, np.dot(S_k, Vt_k))<br>    <br>    # Convert matrix to image<br>    compressed_image = Image.fromarray(np.clip(compressed_image_matrix, 0, 255).astype(&#39;uint8&#39;))<br><br>    # Calculate Frobenius Norm of the approximation error<br>    frobenius_norm = np.linalg.norm(image_matrix - compressed_image_matrix, &#39;fro&#39;)<br>    <br>    return compressed_image, frobenius_norm, S.size</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNT9pQ1h9C5I%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNT9pQ1h9C5I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNT9pQ1h9C5I%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/23c49dd522c19a1e42510b6c4c8a997d/href">https://medium.com/media/23c49dd522c19a1e42510b6c4c8a997d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66ac29ecaf73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Product Recommendation System Using SVD]]></title>
            <link>https://medium.com/@golluajay9/building-a-product-recommendation-system-using-svd-69b0fa1b2da0?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/69b0fa1b2da0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[matrice]]></category>
            <category><![CDATA[singular-values]]></category>
            <category><![CDATA[svd]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 08:22:48 GMT</pubDate>
            <atom:updated>2024-10-20T14:45:45.852Z</atom:updated>
            <content:encoded><![CDATA[<p>In e-commerce, a <strong>product recommendation system</strong> helps users discover new products by predicting their preferences based on past behavior. One effective technique for building such a system is <strong>Singular Value Decomposition (SVD)</strong>. Let’s explore how SVD can be applied to product recommendation systems and how it works under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*ieaLPUiJ1HmmRzn5OEYKkw.png" /></figure><h3><strong>What is a Product Recommendation System?</strong></h3><p>A product recommendation system aims to suggest relevant products to users based on their interaction history. It can use either:</p><ul><li><strong>Collaborative Filtering</strong>: Recommends products based on what similar users have liked or bought.</li><li><strong>Content-Based Filtering</strong>: Recommends products based on the features of items users have shown interest in.</li></ul><p><strong><em>SVD</em></strong><em> falls under collaborative filtering</em>, where user-product interactions (ratings, clicks, purchases) are analyzed to make recommendations.</p><h3><strong>The Role of SVD in Recommendation Systems</strong></h3><p><em>SVD is used to decompose a user-product interaction matrix into smaller matrices that capture the hidden patterns between users and products. The matrix decomposition can predict missing entries, such as how much a user might like a product they haven’t interacted with yet.</em></p><h3>Example: Product Recommendation with SVD</h3><h4>1. User-Product Interaction Matrix</h4><p>Consider a matrix where <strong><em>rows represent products</em></strong> and <strong><em>columns represent users</em></strong>, and each entry contains a rating (or interaction score) from a user for a product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*AKpsJK7KTqrJKUiRGJ3Lig.png" /></figure><p>Here:</p><ul><li>Product 1: Rated 5 by User 1 and 3 by User 3.</li><li>Product 2: Rated 4 by User 2 and 3 by User 4.</li><li>Product 3: Rated 4 by User 1 and 5 by User 4.</li></ul><h4>2. SVD Decomposition</h4><p>Performing SVD on this matrix A, we decompose it into three matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*0S_L4NBOGmPcelzXRIRGaw.png" /></figure><ul><li><strong>U</strong>: Represents <strong>products</strong> in the latent feature space.</li><li><strong>V^T(V transpose)</strong>: Represents <strong>users</strong> in the latent feature space.</li><li><strong>Σ</strong>: Contains the <strong>singular values</strong>, capturing the importance of each latent feature.</li></ul><p><strong>Steps to Compute U (Left Singular Matrix)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*NDSvq9F2VfcVEH7d6Kx_Ug.png" /></figure><h4>Summary of the Entries(product-product similarity):</h4><ol><li><strong>Diagonal entries</strong>: These are the <strong>self-dot products</strong> of each row in A, showing the overall magnitude of interactions for each product (or entity represented by the row).</li><li><strong>Off-diagonal entries</strong>: These show the <strong>similarity</strong> between different products (or entities) based on their interaction vectors (rows in A). A value of 0 means orthogonal (no similarity), while non-zero values show a degree of similarity.</li></ol><h4>In Context of SVD:</h4><ul><li>The diagonal entries of AA^T provide insight into the importance of each product (or row entity) in the system.</li><li>The eigenvectors of AA^T will form the columns of matrix U, representing the left singular vectors.</li></ul><p><strong>Steps to Compute V^T(Right Singular Matrix)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OhNwProbGRM6RUChQ-EmVQ.png" /></figure><h4>Summary of the Entries(user-user similarity):</h4><ol><li><strong>Diagonal entries</strong> of A^TA represent the strength of interactions of each <strong>user</strong> with all products.</li><li><strong>Off-diagonal entries</strong> of A^TA indicate the similarity between two users based on their interaction patterns with the products. Non-zero values indicate some level of shared interest in the same products.</li></ol><h4>In Context of SVD:</h4><ul><li>The <strong>eigenvectors</strong> of A^TA will form the <strong>right singular vectors</strong> (columns of V) in the SVD, which represent the latent features of the users.</li><li>The <strong>singular values</strong> (diagonal entries of Σ) are derived from the square roots of the eigenvalues of A^TA (or AA^T).</li></ul><p><em>Thus, A^T A helps us understand the relationships and similarities between the </em><strong><em>users</em></strong><em>, which is critical for building user-based recommendation systems.</em></p><h3>What do the singular values in Σ represent?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*UBevpdmnRMaSU1NeUcOm5Q.png" /></figure><h4>Practical Interpretation of Singular Values in a Recommendation System:</h4><ul><li><strong>Higher singular values</strong> capture the most important patterns of interaction between users and products (e.g., major preferences or trends shared by many users).</li><li><strong>Lower singular values</strong> represent less significant patterns, possibly noise or very niche interactions that are not as crucial for making general recommendations.</li><li>By truncating small singular values, you can still build an effective recommendation system with reduced computational complexity, while retaining the most important information about user-product relationships.</li></ul><h3>Dimensionality Reduction using SVD with k-truncation</h3><p>In recommendation systems, the primary goal of <strong>dimensionality reduction</strong> using SVD is to retain the most significant patterns in the data while reducing the complexity of the matrix. This is done by truncating the SVD to keep only the top k singular values and their corresponding singular vectors. This reduced representation captures the major patterns of interaction between users and items, enabling efficient recommendation generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*lOUe8cKjuxZUDdKVJF8gKw.png" /></figure><h3>Why Dimensionality Reduction with k?</h3><ul><li><strong>Noise reduction</strong>: By keeping only the top k components, we discard the smaller singular values, which might represent noise or less important variations in the data.</li><li><strong>Efficiency</strong>: Reducing the number of features helps make the computation faster while still retaining the most important information.</li><li><strong>Improved generalization</strong>: A lower-rank approximation reduces the risk of overfitting and helps improve recommendation accuracy by capturing general patterns instead of niche or noisy interactions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69b0fa1b2da0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Advanced Go Features: Generics, Interfaces, and Concurrency]]></title>
            <link>https://medium.com/@golluajay9/exploring-advanced-go-features-generics-interfaces-and-concurrency-67ab1c62541f?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/67ab1c62541f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 05:12:17 GMT</pubDate>
            <atom:updated>2024-09-08T05:12:17.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j91X4o6a3msD3YwpEoNaIg.png" /></figure><p>In Go, we can explore a wide range of features that make it a powerful language for both simple and advanced programming tasks. Whether it’s working with <strong>generics</strong>, <strong>interfaces</strong>, or <strong>concurrency</strong>, Go has you covered. In this blog, I’ll walk through some examples to demonstrate how these features work and highlight why they are important.</p><p>Let’s dive into the code and break it down.</p><h3>1. Structs, Methods, and Custom Types</h3><p>We start by defining various methods for geometric shapes such as <strong>Circle</strong>, <strong>Square</strong>, and <strong>Rectangle</strong>. Here’s a quick example of how we can define a Circle struct with methods that calculate its perimeter and area:</p><pre>package methods<br><br>type Circle struct {<br>    Radius float64<br>}<br><br>func (c Circle) Perimeter() float64 {<br>    return 2 * math.Pi * c.Radius<br>}<br><br>func (c Circle) Area() float64 {<br>    return math.Pi * c.Radius * c.Radius<br>}</pre><p>In Go, it’s common to define methods on structs. The Perimeter() and Area() methods calculate the respective values based on the circle&#39;s radius.</p><p><strong>Note: As you probably noticed, there are no classes in the Go programming language, but we can mimic this by declaring functions on types.</strong></p><h3>2. Custom Types with Methods</h3><p>In the code, we also define a custom type CustomInt that extends the native int type. This allows us to add custom methods like Double() to CustomInt:</p><pre>type CustomInt int<br><br>func (ci CustomInt) Double() int {<br>    return int(ci * 2)<br>}</pre><p>Now, you can use CustomInt and its methods just like any other type:</p><pre>var b methods.CustomInt = 7<br>fmt.Println(b.Double()) // Output: 14</pre><h3>3. Interfaces</h3><p>Go interfaces allow us to define a set of methods that a type must implement. Here, we define the Geometry interface:</p><pre>package interfaces<br><br>type Geometry interface {<br>    Perimeter() int<br>    Area() int<br>}</pre><p>Any type that implements Perimeter() and Area() methods can be treated as a Geometry. This allows us to use polymorphism effectively. For example:</p><pre>var re interfaces.Geometry = methods.Rectangle{Length: 3, Breath: 5}<br>Details(re)</pre><p>The Details() function accepts any type that implements the Geometry interface, providing flexibility and extensibility.</p><h3>4. Type Assertions and Type Switches</h3><p>Go’s type assertion lets us extract the dynamic type of an interface. Here’s an example where we check if re is a Square or Rectangle:</p><pre>if v, ok := re.(methods.Square); ok {<br>    fmt.Printf(&quot;Is a Square with value %v\n&quot;, v)<br>} else {<br>    fmt.Println(&quot;Not a Square&quot;)<br>}</pre><p>Additionally, Go’s type switch allows you to handle multiple types in a more readable way:</p><pre>switch re.(type) {<br>case methods.Square:<br>    fmt.Println(&quot;Square&quot;)<br>case methods.Rectangle:<br>    fmt.Println(&quot;Rectangle&quot;)<br>default:<br>    fmt.Println(&quot;Unknown type&quot;)<br>}</pre><h3>5. Generics in Go</h3><p>Generics were introduced in Go 1.18, providing a way to write reusable functions that work with different types. For instance, we have a Contains() function that checks if a slice contains a given element:</p><pre>func Contains[T comparable](arr []T, x T) bool {<br>    for _, v := range arr {<br>        if v == x {<br>            return true<br>        }<br>    }<br>    return false<br>}</pre><p>This function works with any type that supports comparisons (like int, string, etc.), making it highly versatile.</p><h3>6. Concurrency in Go</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fj9PHBhM9DIRZ35lfMHF_w.jpeg" /></figure><p>Go’s concurrency model is one of its most compelling features, built around <strong>goroutines</strong> and <strong>channels</strong>. Here’s a quick look at how you can send messages between goroutines using channels:</p><pre>ch := make(chan string, 2)<br>go sendMessage(&quot;Hello&quot;, ch)<br>go sendMessage(&quot;World&quot;, ch)<br><br>fmt.Println(&lt;-ch)<br>fmt.Println(&lt;-ch)</pre><p>We also use <strong>mutexes</strong> to manage access to shared data and prevent race conditions:</p><pre>type MutualExclusive struct {<br>    mutex sync.Mutex<br>    value int<br>}<br><br>func (me *MutualExclusive) Double() {<br>    me.mutex.Lock()<br>    me.value *= 2<br>    me.mutex.Unlock()<br>}</pre><p>The <strong>WaitGroup</strong> ensures that all goroutines finish execution before the program proceeds:</p><pre>wg := &amp;sync.WaitGroup{}<br>wg.Add(5)<br><br>for i := 0; i &lt; 5; i++ {<br>    go func(i int) {<br>        a3[i] *= 3<br>        fmt.Println(&quot;Goroutine&quot;, i)<br>        wg.Done()<br>    }(i)<br>}<br><br>wg.Wait()</pre><h3>Conclusion</h3><p>By using Go’s features like <strong>generics</strong>, <strong>interfaces</strong>, and <strong>concurrency</strong>, we can create efficient, flexible, and safe applications. Go’s type system, along with its concurrency model, makes it well-suited for modern programming challenges. I hope this exploration inspires you to experiment with Go and leverage its advanced features to solve real-world problems!</p><p>If you found this helpful, feel free to leave a comment or ask questions. Happy coding!</p><p>References book: <a href="https://www.amazon.in/Modern-Web-Development-real-world-programming-ebook/dp/B0BY8NFZDL">https://www.amazon.in/Modern-Web-Development-real-world-programming-ebook/dp/B0BY8NFZDL</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67ab1c62541f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Basic Concepts in Golang]]></title>
            <link>https://medium.com/@golluajay9/a-comprehensive-guide-to-basic-concepts-in-golang-3a3ba2cd002e?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a3ba2cd002e</guid>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[basic-programs]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 04:17:29 GMT</pubDate>
            <atom:updated>2024-09-07T04:17:29.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Golang, or Go, is a statically typed, compiled language designed for simplicity, efficiency, and robustness. This blog will walk you through fundamental concepts in Go, using practical examples to illustrate the language’s capabilities. Whether you’re new to Go or brushing up on your skills, this guide will cover a wide range of topics.</p><h3>Introduction: Hello, World!</h3><p>The traditional starting point in any language is a simple “Hello, World!” program. In Go, this can be achieved with a single line:</p><pre>fmt.Println(&quot;Hello World!!!&quot;)</pre><p>This is followed by other print statements that provide output for various examples in this blog.</p><h3>Basic Arithmetic</h3><p>Arithmetic operations are straightforward in Go. Here’s an example that adds two integers:</p><pre>a := 5<br>b := 7<br>c := a + b<br>fmt.Println(&quot;Result is: &quot;, c)</pre><p>In this example, we declare and initialize variables a and b, then calculate their sum and print the result.</p><h3>Working with External Packages</h3><p>Go allows you to import and use external packages. For instance, you can access exported members from another package:</p><pre>import &quot;partice/export&quot;</pre><pre>fmt.Println(&quot;Export package members\n&quot;, export.Exported)</pre><p>This code snippet imports the export package and prints the exported member.</p><h3>Rune and String Conversion</h3><p>Go has a specific type called rune, representing a Unicode code point. You can convert a rune to a string like this:</p><pre>var d rune = &#39;f&#39;<br>fmt.Println(&quot;Rune character as string\n&quot;, string(d))</pre><p>This converts the rune f into its string representation.</p><h3>Variable Declarations</h3><p>You can declare multiple variables with different types in one line:</p><pre>var x, y, z = 1, 2, 3<br>var j = false<br>fmt.Println(&quot;Variables\n&quot;, x, y, z, j)</pre><p>Here, x, y, and z are integers, while j is a boolean.</p><h3>Global and Local Variables</h3><p>Global variables are declared outside functions, making them accessible throughout the package:</p><pre>var globalVar int = 3</pre><pre>func main() {<br>	localVar := 6<br>	fmt.Println(&quot;Global Variable: &quot;, globalVar, &quot;\nLocal Variable: &quot;, localVar)<br>}</pre><p>This code demonstrates the use of a global variable globalVar and a local variable localVar.</p><h3>Type Conversion</h3><p>Go allows explicit type conversion, as shown here:</p><pre>var a1 int = 5<br>var b1 float32 = float32(a1)<br>fmt.Println(&quot;Type conversion\n&quot;, b1)</pre><p>This converts an integer a1 to a float b1.</p><h3>Constants and Iota</h3><p>The iota keyword simplifies constant generation:</p><pre>const (<br>	ZERO = iota<br>	ONE<br>	TWO<br>	THREE<br>	FOUR<br>)<br>const FIVE = iota // resets iota<br>fmt.Println(&quot;Constants\n&quot;, ZERO, ONE, TWO, THREE, FOUR, FIVE)</pre><p>The iota keyword increments with each new constant, making it perfect for enumerations.</p><h3>Pointers</h3><p>Pointers store memory addresses of variables. You can manipulate data directly through pointers:</p><pre>var a2 int = 10<br>var p *int = &amp;a2<br>*p = 15<br>fmt.Println(&quot;Pointer complex dtype\n&quot;, a2)</pre><p>This example modifies the value of a2 through a pointer p.</p><h3>Structs</h3><p>Structs allow you to create custom data types. Here’s how to define and use a struct:</p><pre>type Person struct {<br>	name string<br>	age  int<br>}</pre><pre>ajay := Person{name: &quot;Ajay&quot;, age: 23}<br>var copyAjay *Person = &amp;ajay<br>copyAjay.age = 8<br>bunny := Person{&quot;bunny&quot;, 22}<br>fmt.Println(&quot;Struct complex dtype\n&quot;, *copyAjay, bunny)</pre><p>Structs encapsulate related data, and Go supports pointers to structs for efficient data manipulation.</p><h3>Arrays</h3><p>Arrays are fixed-size collections of elements of the same type:</p><pre>var z1 [7]int<br>var a3 = [7]int{1, 3, 4}<br>a3[5] = 9<br>a3[6] = 88<br>fmt.Println(&quot;Array complex dtype\n&quot;, z1, a3, len(a3))</pre><p>In this example, we declare and manipulate an array.</p><h3>Slices</h3><p>Slices are dynamically-sized arrays:</p><pre>var a4 = []int{1, 2, 3, 4}<br>var d1 = a4[1:3]<br>var d2 = append(a4, d1...)<br>var d3 = append(d2, 8, 109)<br>fmt.Println(&quot;Slice\n&quot;, len(d1), cap(d1), d2, d3)</pre><p>Slices offer more flexibility than arrays, and you can perform operations like slicing and appending.</p><h3>Maps</h3><p>Maps store key-value pairs and provide fast lookups:</p><pre>var countryMap = make(map[string]string)<br>countryMap[&quot;fr&quot;] = &quot;France&quot;<br>countryMap[&quot;in&quot;] = &quot;India&quot;<br>delete(countryMap, &quot;fr&quot;)</pre><pre>fmt.Println(&quot;Map complex dtype\n&quot;, countryMap)</pre><p>This code demonstrates map creation, insertion, and deletion of elements.</p><h3>Conditional Statements</h3><p>Go supports traditional if-else and switch statements:</p><pre>if code == &quot;fr&quot; {<br>	fmt.Println(&quot;France&quot;)<br>} else {<br>	fmt.Println(&quot;Not found&quot;)<br>}</pre><pre>switch code {<br>case &quot;fr&quot;:<br>	fmt.Println(&quot;France&quot;)<br>case &quot;in&quot;:<br>	fmt.Println(&quot;India&quot;)<br>default:<br>	fmt.Println(&quot;Not found&quot;)<br>}</pre><p>You can use if-else for simple conditions and switch for more complex logic.</p><h3>Loops</h3><p>Go has various loop structures, including traditional for loops, while-like loops, and range-based loops:</p><pre>for i := 0; i &lt; 10; i++ {<br>	fmt.Printf(&quot;2 x %v = %v\n&quot;, i+1, 2*(i+1))<br>}</pre><pre>sum := 0<br>for _, v := range a3 {<br>	sum += v<br>}<br>fmt.Printf(&quot;Sum of %v = %v\n&quot;, a3, sum)</pre><p>Loops are versatile, and you can iterate over slices, maps, and arrays using range.</p><h3>Defer</h3><p>The defer statement schedules a function to run after the surrounding function completes, in a LIFO (Last In, First Out) order:</p><pre>defer fmt.Println(&quot;2&quot;)<br>fmt.Println(&quot;1&quot;)</pre><p>This outputs 1 followed by 2, demonstrating the deferred execution.</p><h3>Functions</h3><p>Go functions are first-class citizens, and you can define them with varying complexity:</p><pre>func pi() float64 {<br>	return 3.14159<br>}</pre><pre>func add(a, b int) int {<br>	return a + b<br>}</pre><p>You can also pass functions as parameters or return functions:</p><pre>func calc(fn func(int, int) int) int {<br>	return fn(999, 1)<br>}</pre><pre>func multiply(param int) func(int) int {<br>	return func(i int) int {<br>		return i * 2<br>	}<br>}</pre><p>This demonstrates Go’s powerful support for higher-order functions.</p><h3>Closures</h3><p>Closures capture the surrounding environment and are useful for state management:</p><pre>func calc1() func() int {<br>	a := 5<br>	return func() int {<br>		a += 1<br>		return a<br>	}<br>}</pre><p>Here, the returned function remembers and modifies the a variable from the enclosing function.Conclusion</p><p>This blog has covered a wide range of Go basics, from variables and constants to functions and more complex data types like structs, arrays, slices, and maps. Go’s simplicity and efficiency make it an excellent language for both beginners and experienced developers. Explore these concepts further and build your own Go projects to deepen your understanding.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a3ba2cd002e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing the PDF.js Viewer for Secure Viewing]]></title>
            <link>https://medium.com/@golluajay9/customizing-the-mozilla-pdf-js-viewer-for-secure-viewing-68392d24cde2?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/68392d24cde2</guid>
            <category><![CDATA[pdfview]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[jspdf]]></category>
            <category><![CDATA[custom-web-pdf]]></category>
            <category><![CDATA[webpdf]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 06:40:34 GMT</pubDate>
            <atom:updated>2024-08-18T01:57:41.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web PDF Viewer for Secure Viewing</h3><p>In today’s digital world, sharing sensitive documents securely is a top priority. Often, we want to allow users to view PDFs but prevent them from downloading, printing, or manipulating the file in any way. Thankfully, Mozilla’s <strong>PDF.js</strong> is an excellent open-source library that allows you to embed PDF viewers into your website. In this guide, we’ll walk through customizing the <strong>PDF.js</strong> viewer to restrict PDF interactions so users can only view, but not download, print, or use other tools on the PDF.</p><h3>Prerequisites</h3><p>Before we dive into customization, you need the following:</p><ul><li>A basic understanding of HTML, JavaScript, and some command-line experience.</li><li>Mozilla’s <strong>PDF.js</strong> repository, which you can find <a href="https://github.com/mozilla/pdf.js">here</a>.</li><li>Access to a text editor like Nano or Visual Studio Code.</li></ul><p>Let’s jump in!</p><h3>Step 1: Clone the PDF.js Repository</h3><p>Start by cloning the <strong>PDF.js</strong> repository from GitHub onto your local machine:</p><pre>git clone https://github.com/mozilla/pdf.js.git<br>cd pdf.js</pre><p>Once you’re inside the pdf.js folder, you’ll be dealing with the core files, particularly in the web directory.</p><h3>Step 2: Edit the Viewer.html File</h3><p>Navigate to the <strong>viewer.html</strong> file located in the web folder. This is where the primary configuration and UI changes to the PDF.js viewer take place:</p><pre>cd web<br>nano viewer.html</pre><p>In this file, you can make several modifications to disable unwanted functionalities, such as downloading and printing.</p><h3>Step 3: Disable the Download Option</h3><p>By default, the <strong>PDF.js</strong> viewer provides users with a download button in the toolbar. We need to remove or hide this option.</p><p>Inside the viewer.html, search for the following line which corresponds to the download button:</p><pre>&lt;button id=&quot;download&quot; class=&quot;toolbarButton download hiddenLargeView&quot; title=&quot;Download&quot; tabindex=&quot;33&quot; data-l10n-id=&quot;download&quot;&gt;<br>  &lt;span data-l10n-id=&quot;download_label&quot;&gt;Download&lt;/span&gt;<br>&lt;/button&gt;</pre><p>Remove this block of code to completely eliminate the download button from the toolbar.</p><p>Alternatively, you can hide it using CSS. Add this style in the viewer.css file:</p><pre>#download {<br>    display: none;<br>}</pre><h3>Step 4: Restrict Printing</h3><p>Next, you want to prevent users from printing the PDF. Similar to the download button, locate the print button in the viewer.html file:</p><pre>&lt;button id=&quot;print&quot; class=&quot;toolbarButton print hiddenMediumView&quot; title=&quot;Print&quot; tabindex=&quot;32&quot; data-l10n-id=&quot;print&quot;&gt;<br>  &lt;span data-l10n-id=&quot;print_label&quot;&gt;Print&lt;/span&gt;<br>&lt;/button&gt;</pre><p>Remove or hide the print button by either deleting this block of code or adding a style rule in the CSS:</p><pre>#print {<br>    display: none;<br>}</pre><h3>Step 5: Disable Right-Click and Other Tool Access</h3><p>Disabling right-click is a simple but effective way to prevent users from using browser tools to save or manipulate the PDF. To achieve this, you can add the following JavaScript to the viewer.html or in a custom JavaScript file linked in the HTML:</p><pre>document.addEventListener(&#39;contextmenu&#39;, function(e) {<br>    e.preventDefault();<br>});</pre><p>This will disable the right-click context menu when viewing the PDF.</p><h3>Step 6: Restrict Interaction with the Browser Developer Tools</h3><p>Although completely blocking access to developer tools isn’t possible, we can limit user interaction with shortcuts like right-click and “Save as.” You can add keyboard event listeners to disable common shortcut keys:</p><pre>document.addEventListener(&#39;keydown&#39;, function(e) {<br>    // Disable Ctrl + S (Save)<br>    if (e.ctrlKey &amp;&amp; e.key === &#39;s&#39;) {<br>        e.preventDefault();<br>        alert(&quot;Saving is disabled.&quot;);<br>    }<br>    <br>    // Disable Ctrl + P (Print)<br>    if (e.ctrlKey &amp;&amp; e.key === &#39;p&#39;) {<br>        e.preventDefault();<br>        alert(&quot;Printing is disabled.&quot;);<br>    }<br>});</pre><p>While these techniques are not foolproof, they can deter casual users from misusing your PDF content.</p><h3>Step 7: Run and Test Your Custom Viewer</h3><p>Once you’ve made these changes, you’ll want to build and test the modified viewer. You can use <strong>npm</strong> to install the necessary dependencies and run the viewer locally:</p><pre>npm install<br>npx gulp server</pre><p>This will serve the PDF viewer locally on a development server. Open the provided URL in your browser to test whether your custom viewer is working as expected without the download and print functionalities.</p><p>and then you can open:</p><ul><li><a href="http://localhost:8888/web/viewer.html">http://localhost:8888/web/viewer.html</a>?file=&lt;URL&gt;</li></ul><h3>Conclusion</h3><p>By following these steps, you’ve successfully customized the <strong>PDF.js</strong> viewer to limit user interaction with your PDF files. This can be incredibly useful when sharing sensitive documents or when you want to maintain tighter control over how your content is accessed.</p><p>Keep in mind, however, that even though you’ve restricted downloading and printing, more advanced users may still find ways around these restrictions (e.g., using browser developer tools). Therefore, you should consider additional layers of security, such as document encryption or watermarking, if your use case requires even tighter controls.</p><p>Now that you’ve tailored the PDF.js viewer to your needs, you can confidently deploy it knowing that your documents are more secure.</p><p>Feel free to explore other features and customizations in <strong>PDF.js</strong>, and enhance your document-viewing experience further!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68392d24cde2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting Keyboard Visibility in Android TV using Kotlin and Jetpack Compose]]></title>
            <link>https://medium.com/@golluajay9/detecting-keyboard-visibility-in-android-tv-using-kotlin-and-jetpack-compose-30ae372a771c?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30ae372a771c</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-tv]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[windowinsets]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 09:15:12 GMT</pubDate>
            <atom:updated>2024-08-07T09:15:12.472Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we’ll explore how to detect keyboard visibility changes in an Android TV application using Kotlin and Jetpack Compose. This can be particularly useful for managing UI elements dynamically based on whether the keyboard is visible or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IheRinHr3oruj6fWycZQHg.png" /></figure><h3>Prerequisites</h3><p>Before we begin, ensure you have the following:</p><ul><li>Android Studio installed</li><li>Basic knowledge of Kotlin and Jetpack Compose</li></ul><h3>Setting Up the Project</h3><p>Start by creating a new Android project with Jetpack Compose support. Once you have your project ready, open the MainActivity.kt file.</p><h3>MainActivity Implementation</h3><p>In the MainActivity, we will set up the content using Jetpack Compose and add a listener to detect window insets changes. This will allow us to determine if the keyboard is visible or not.</p><p>Here’s the complete code for the MainActivity:</p><pre>package com.example.keyboardvisibility<br><br>import android.os.Bundle<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.material3.Surface<br>import androidx.compose.runtime.mutableStateOf<br>import androidx.compose.runtime.remember<br>import androidx.compose.runtime.Composable<br>import androidx.core.view.ViewCompat<br>import androidx.core.view.WindowInsetsCompat<br>import com.example.keyboardvisibility.ui.theme.KeyboardVisibilityTheme<br><br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            KeyboardVisibilityTheme {<br>                Surface(color = MaterialTheme.colorScheme.background) {<br>                    MainScreen()<br>                }<br>            }<br>        }<br><br>        // Listen to window insets changes to detect keyboard visibility<br>        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content)) { _, insets -&gt;<br>            val isKeyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime())<br>            keyboardVisibilityViewModel.updateKeyboardVisibility(isKeyboardVisible)<br>            insets<br>        }<br>    }<br>}<br><br>@Composable<br>fun MainScreen() {<br>    val isKeyboardVisible = remember { mutableStateOf(false) }<br>    val keyboardVisibilityViewModel = remember { KeyboardVisibilityViewModel() }<br><br>    keyboardVisibilityViewModel.isKeyboardVisible.observeAsState().value?.let { visible -&gt;<br>        isKeyboardVisible.value = visible<br>    }<br><br>    // Your UI components go here<br>    // You can use isKeyboardVisible.value to conditionally render UI based on keyboard visibility<br>}</pre><h3>ViewModel Implementation</h3><p>For managing keyboard visibility state, we use a simple ViewModel. Here&#39;s how you can implement it:</p><pre>package com.example.keyboardvisibility<br><br>import androidx.lifecycle.LiveData<br>import androidx.lifecycle.MutableLiveData<br>import androidx.lifecycle.ViewModel<br><br>class KeyboardVisibilityViewModel : ViewModel() {<br>    private val _isKeyboardVisible = MutableLiveData(false)<br>    val isKeyboardVisible: LiveData&lt;Boolean&gt; get() = _isKeyboardVisible<br><br>    fun updateKeyboardVisibility(isVisible: Boolean) {<br>        _isKeyboardVisible.value = isVisible<br>    }<br>}</pre><h3>Conclusion</h3><p>By following these steps, you can easily detect keyboard visibility changes in your Android TV application using Kotlin and Jetpack Compose. This can help you manage your UI more effectively, ensuring a better user experience. Feel free to customize the MainScreen composable to react to keyboard visibility changes as needed.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30ae372a771c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Basic Game Engine with SFML and ECS: A PingPong Game Example]]></title>
            <link>https://medium.com/@golluajay9/building-a-basic-game-engine-with-sfml-and-ecs-a-pingpong-game-example-d20e5325d9cd?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d20e5325d9cd</guid>
            <category><![CDATA[sfml]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[game-engine]]></category>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 17:25:26 GMT</pubDate>
            <atom:updated>2024-07-21T17:55:07.876Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of game development, creating a robust engine is essential for managing game logic, rendering, and interactions. In this blog, we’ll dive into the foundational elements of a simple game engine built with SFML (Simple and Fast Multimedia Library) and the Entity-Component-System (ECS) architecture, using a PingPong game as our example.</p><h4>What is ECS?</h4><p>The ECS architecture is a design pattern that separates the data (components) from the behavior (systems) of game entities. This pattern allows for flexible and scalable game design. In ECS:</p><ul><li><strong>Entities</strong> are general-purpose objects.</li><li><strong>Components</strong> are data holders.</li><li><strong>Systems</strong> contain the logic that processes entities with specific components.</li></ul><h4>Overview of Our Game Engine</h4><p>Our game engine uses SFML for rendering and input handling, while ECS manages game objects and their behaviors. The main components and systems include:</p><ol><li><strong>Components</strong>: Define data for entities.</li><li><strong>Systems</strong>: Implement the logic for processing entities with specific components.</li><li><strong>Entity</strong>: Represents game objects by holding various components.</li><li><strong>Game</strong>: Manages game loop and interactions.</li></ol><h4>Components</h4><p>Components are the building blocks of entities. Here’s a quick look at the components used in our PingPong game:</p><ul><li><strong>AIComponent</strong>: Manages AI behavior and velocity for entities.</li></ul><pre>class AIComponent : public Component<br>{<br>public:<br>    AIComponent(float speed = 0.0f, bool isPaddle = false);<br>    void setVelocity(const sf::Vector2f &amp;velocity);<br>    sf::Vector2f getVelocity() const;<br>    float getSpeed() const;<br>    bool getIsPaddle() const;<br><br>private:<br>    float speed;<br>    bool isPaddle;<br>    sf::Vector2f velocity;<br>};</pre><ul><li><strong>BoundingBoxComponent</strong>: Defines the bounding box for collision detection.</li></ul><pre>class BoundingBoxComponent : public Component {<br>public:<br>    sf::Vector2f min;<br>    sf::Vector2f max;<br>    BoundingBoxComponent(const sf::Vector2f&amp; min, const sf::Vector2f&amp; max)<br>        : min(min), max(max) {}<br>};</pre><ul><li><strong>CollisionComponent</strong>: Manages collision bounds using SFML’s FloatRect.</li></ul><pre>class CollisionComponent : public Component {<br>public:<br>    CollisionComponent(const sf::FloatRect&amp; bounds);<br>    sf::FloatRect getBounds() const;<br>    void setBounds(const sf::FloatRect&amp; bounds);<br><br>private:<br>    sf::FloatRect bounds;<br>};</pre><ul><li><strong>InputComponent</strong>: Handles user input with SFML’s Keyboard.</li></ul><pre>class InputComponent : public Component {<br>public:<br>    std::unordered_map&lt;sf::Keyboard::Key, bool&gt; keyMap;<br>    bool isKeyPressed(sf::Keyboard::Key key) const;<br>    void setKey(sf::Keyboard::Key key, bool pressed);<br>};</pre><ul><li><strong>SpriteComponent</strong>: Manages sprites and textures for rendering.</li></ul><pre>class SpriteComponent : public Component<br>{<br>public:<br>    sf::Sprite sprite;<br>    sf::Texture texture;<br>    SpriteComponent(const std::string &amp;filePath);<br>    void setSizeBasedOnWindow(const sf::RenderWindow &amp;window);<br>    void setSize(float width, float height);<br>    void setPosition(float x, float y);<br>    sf::Sprite &amp;getSprite();<br>};</pre><ul><li><strong>TransformComponent</strong>: Handles entity positions and transformations.</li></ul><pre>class TransformComponent : public Component {<br>public:<br>    sf::Vector2f position;<br>    TransformComponent(float x = 0, float y = 0);<br>    void setPosition(float x, float y);<br>    void setPosition(const sf::Vector2f&amp; pos);<br>    void translate(float x, float y);<br>    void translate(const sf::Vector2f&amp; offset);<br>    sf::Vector2f getPosition() const;<br>};</pre><h4>Systems</h4><p>Systems contain the logic that operates on entities with specific components:</p><ul><li><strong>AISystem</strong>: Updates AI logic and handles movement.</li></ul><pre>class AISystem : public System {<br>public:<br>    void update(float deltaTime) override;<br>    void update(float deltaTime, sf::RenderWindow&amp; window, std::shared_ptr&lt;Entity&gt; ball);<br>};</pre><ul><li><strong>CollisionSystem</strong>: Handles collisions between entities.</li></ul><pre>class CollisionSystem : public System {class CollisionSystem : public System {<br>public:<br>    void update(float deltaTime) override;<br>private:<br>    void handleCollision(std::shared_ptr&lt;Entity&gt; entityA, std::shared_ptr&lt;Entity&gt; entityB);<br>};<br>public:<br>    void update(float deltaTime) override;<br>private:<br>    void handleCollision(std::shared_ptr&lt;Entity&gt; entityA, std::shared_ptr&lt;Entity&gt; entityB);<br>};</pre><ul><li><strong>InputSystem</strong>: Processes user input.</li></ul><pre>class InputSystem : public System {<br>public:<br>    void update(float deltaTime) override;<br>};</pre><ul><li><strong>RenderSystem</strong>: Handles rendering of entities.</li></ul><pre>class RenderSystem : public System {<br>public:<br>    void render(sf::RenderWindow&amp; window);<br>    void update(float deltaTime) override;<br>};</pre><h4>Entity and System Integration</h4><p>Entities are created with components attached, and systems operate on entities based on the components they possess. For example:</p><p><strong>Entity</strong>:</p><pre>class Entity<br>{<br>public:<br>    void addComponent(std::shared_ptr&lt;Component&gt; component);<br>    template &lt;typename T&gt;<br>    std::shared_ptr&lt;T&gt; getComponent();<br><br>private:<br>    std::vector&lt;std::shared_ptr&lt;Component&gt;&gt; components;<br>};</pre><p><strong>System</strong>:</p><pre>class System<br>{<br>public:<br>    virtual ~System() = default;<br>    void addEntity(std::shared_ptr&lt;Entity&gt; entity);<br>    virtual void update(float deltaTime) = 0;<br><br>protected:<br>    std::vector&lt;std::shared_ptr&lt;Entity&gt;&gt; entities;<br>};<br><br>inline void System::addEntity(std::shared_ptr&lt;Entity&gt; entity) {<br>    entities.push_back(entity);<br>}</pre><p>Component:</p><pre>#pragma once<br><br>class Component<br>{<br>public:<br> virtual ~Component() = default;<br>};</pre><h4>The Game Loop</h4><p>The Game class is responsible for managing the game loop, processing events, updating systems, and rendering.</p><pre>class Game<br>{<br>public:<br>    Game();<br>    void run();<br><br>private:<br>    void processEvents();<br>    void update(sf::Time deltaTime);<br>    void handleKeyEvent(sf::Keyboard::Key key, bool isPressed);<br>    void render();<br>    void resizeBackground();<br><br>    sf::RenderWindow mWindow;<br>    sf::Texture backgroundTexture;<br>    sf::Sprite backgroundSprite;<br><br>    std::shared_ptr&lt;Entity&gt; player;<br>    std::shared_ptr&lt;Entity&gt; ball;<br>    std::shared_ptr&lt;Entity&gt; opponentPaddle;<br><br>    RenderSystem renderSystem;<br>    InputSystem inputSystem;<br>    AISystem aiSystem;<br>    CollisionSystem collisionSystem;<br>};</pre><p>In summary, this basic game engine combines SFML for graphics and input with an ECS architecture to manage entities and their behaviors. This structure provides a solid foundation for developing more complex games and can be extended with additional features as needed. Happy coding!</p><p>****Absolutely! For a more detailed look at the game engine and its implementation, including the complete code and additional insights, please visit the GitHub repository: <a href="https://github.com/GolluAjay/PingPong">PingPong Game Engine</a>. There, you’ll find a comprehensive exploration of the game’s architecture, components, and systems, which will provide a deeper understanding of how everything ties together.***</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UuiwM9nSYOXmqqe7tdn4g.png" /><figcaption>PingPong</figcaption></figure><p>Where in the above image we configure the left paddle as the player and the right paddle and ball as AI entities</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d20e5325d9cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Decentralized Chat App with OrbitDB and libp2p in Node.js]]></title>
            <link>https://medium.com/@golluajay9/building-a-decentralized-chat-app-with-orbitdb-and-libp2p-in-node-js-6404bdd8fbde?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6404bdd8fbde</guid>
            <category><![CDATA[chat-app-development]]></category>
            <category><![CDATA[decentralized]]></category>
            <category><![CDATA[libp2p]]></category>
            <category><![CDATA[ipfs]]></category>
            <category><![CDATA[orbitdb]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 16:00:23 GMT</pubDate>
            <atom:updated>2024-03-02T16:42:30.114Z</atom:updated>
            <content:encoded><![CDATA[<p>Decentralized applications (dApps) are gaining popularity for their ability to provide secure and censorship-resistant communication. In this tutorial, we’ll explore the creation of a simple decentralized chat application using OrbitDB and libp2p in Node.js.</p><h3>Prerequisites</h3><p>Before getting started, make sure you have Node.js installed on your machine. You can download it from <a href="https://nodejs.org/">nodejs.org</a>.</p><h3>Setting Up the Project</h3><ol><li>Create a new directory for your project and navigate into it.</li></ol><pre>mkdir decentralized-chat-app<br>cd decentralized-chat-app</pre><p>2. Initialize a new Node.js project.</p><pre>npm init -y</pre><p>3. Install the required dependencies.</p><pre>npm install @chainsafe/libp2p-gossipsub @orbitdb/core blockstore-level helia libp2p-kad-dht</pre><p>4. Create an index.js file and copy the provided script into it.</p><pre>/**<br> * A simple nodejs script which launches an orbitdb instance and creates a db<br> * with a single record.<br> *<br> * To run from the terminal:<br> *<br> * ```bash<br> * node index.js<br> * ```<br> * or<br> * ```bash<br> * node index.js /orbitdb/&lt;hash&gt;<br> * ```<br> */<br>import { createHelia } from &quot;helia&quot;;<br>import { createOrbitDB, OrbitDBAccessController } from &quot;@orbitdb/core&quot;;<br>import { createLibp2p } from &quot;libp2p&quot;;<br>import { identify } from &quot;@libp2p/identify&quot;;<br>import { mdns } from &quot;@libp2p/mdns&quot;;<br>import { yamux } from &quot;@chainsafe/libp2p-yamux&quot;;<br>import { tcp } from &quot;@libp2p/tcp&quot;;<br>import { gossipsub } from &quot;@chainsafe/libp2p-gossipsub&quot;;<br>import { noise } from &quot;@chainsafe/libp2p-noise&quot;;<br>import { LevelBlockstore } from &quot;blockstore-level&quot;;<br>import fs from &quot;fs&quot;;<br>import readline from &quot;readline&quot;;<br><br>const libp2pOptions = {<br>  peerDiscovery: [mdns()],<br>  addresses: {<br>    listen: [&quot;/ip4/0.0.0.0/tcp/0&quot;],<br>  },<br>  transports: [tcp()],<br>  connectionEncryption: [noise()],<br>  streamMuxers: [yamux()],<br>  services: {<br>    identify: identify(),<br>    pubsub: gossipsub({ emitSelf: true }),<br>  },<br>};<br><br>const rl = readline.createInterface({<br>  input: process.stdin,<br>  output: process.stdout,<br>});<br><br>const id = process.argv.length &gt; 2 ? 2 : 1;<br><br>const getNewId = (currentId) =&gt; {<br>  let newId = currentId;<br>  if (process.argv.length &gt; 2) {<br>    while (fs.existsSync(`./orbitdb/${newId}`)) {<br>      newId += 1;<br>    }<br>  }<br>  return newId;<br>};<br><br>const _newId = getNewId(id);<br><br>const blockstore = new LevelBlockstore(`./ipfs/${_newId}`);<br><br>const libp2p = await createLibp2p(libp2pOptions);<br><br>const ipfs = await createHelia({ libp2p, blockstore });<br><br>const orbitdb = await createOrbitDB({<br>  ipfs,<br>  id: `nodejs-${_newId}`,<br>  directory: `./orbitdb/${_newId}`,<br>});<br><br>let db;<br><br>const askQuestion = (_newId) =&gt; {<br>  // Ask the user to input messages<br>  rl.question(&quot;Type a message to send: &quot;, async (message) =&gt; {<br>    await db.add({ from: _newId, message });<br><br>    if (message === &quot;exit&quot;) {<br>      // Close the readline interface and end the process<br>      rl.close();<br>      await db.close();<br>      await orbitdb.stop();<br>      await ipfs.stop();<br>      process.exit(0);<br>    } else {<br>      askQuestion(_newId);<br>    }<br>  });<br>};<br><br>if (process.argv.length &gt; 2) {<br>  const remoteDBAddress = process.argv.pop();<br>  db = await orbitdb.open(remoteDBAddress);<br><br>  // Listen for incoming messages<br>  db.events.on(&quot;update&quot;, (event) =&gt; {<br>    const latestMessage = event.payload.value;<br><br>    process.stdout.write(&quot;\r&quot;);<br><br>    if (latestMessage.from !== _newId) {<br>      console.log(<br>        `Received message from peer ${latestMessage.from}: ${latestMessage.message}\n`<br>      );<br>    }<br><br>    askQuestion(_newId);<br>  });<br><br>  askQuestion(_newId);<br>} else {<br>  db = await orbitdb.open(&quot;chat-app&quot;, {<br>    AccessController: OrbitDBAccessController({ write: [&quot;*&quot;] }),<br>    replicate: true,<br>  });<br><br>  console.log(`Your database address: ${db.address.toString()}`);<br><br>  // Listen for incoming messages<br>  db.events.on(&quot;update&quot;, (event) =&gt; {<br>    const latestMessage = event.payload.value;<br><br>    process.stdout.write(&quot;\r&quot;);<br><br>    if (latestMessage.from !== _newId) {<br>      console.log(<br>        `Received message from peer ${latestMessage.from}: ${latestMessage.message}\n`<br>      );<br>    }<br><br>    askQuestion(_newId);<br>  });<br><br>  askQuestion(_newId);<br>}<br><br>process.on(&quot;SIGINT&quot;, async () =&gt; {<br>  console.log(&quot;exiting...&quot;);<br><br>  await db.close();<br>  await orbitdb.stop();<br>  await ipfs.stop();<br>  process.exit(0);<br>});</pre><h3>Understanding the Code</h3><p>The provided Node.js script sets up a decentralized chat application using OrbitDB and libp2p. Let’s break down the main components:</p><ul><li>libp2pOptions: Configuration options for libp2p, including peer discovery, addresses, transports, encryption, and services like identity and pubsub.</li><li>getNewId: A function to generate a new ID for the peer.</li><li>blockstore: Uses LevelDB to store blocks for libp2p.</li><li>libp2p: Creates a libp2p instance with the specified options.</li><li>ipfs: Initializes an IPFS instance using the Helia library.</li><li>orbitdb: Creates an OrbitDB instance using the IPFS instance.</li><li>askQuestion: Asks the user to input messages and adds them to the database.</li><li>db: Represents the OrbitDB database.</li></ul><h3>Running the Application</h3><ol><li>To create the first peer and initialize the database, run:</li></ol><pre>node index.js</pre><p>2. For subsequent peers, run:</p><pre>node index.js /orbitdb/&lt;hash&gt;</pre><p>Replace &lt;hash&gt; with the hash generated for the first peer&#39;s database address.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNZ2gkuYSs-yO06OcKkkDQ.png" /><figcaption>First Peer Initiation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThOrPSAC-HmV7ghBLqdBbQ.png" /><figcaption>Second Peer initiation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPYJCSxDtK6gxwdPGGymyw.png" /><figcaption>first peer console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ey3Ez7mOt_nKEKwK3B11KQ.png" /><figcaption>Second peer console</figcaption></figure><h3>Conclusion</h3><p>Congratulations! You’ve created a decentralized chat application using OrbitDB and libp2p in Node.js. This project demonstrates the power of decentralized technologies in building resilient and censorship-resistant communication platforms. Feel free to experiment and extend the functionality to suit your needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6404bdd8fbde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster than REST: Building a Real-time Chat Application with gRPC and Node.js]]></title>
            <link>https://medium.com/@golluajay9/get-start-with-grpc-building-a-real-time-chat-application-with-grpc-and-node-js-884b680adabc?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/884b680adabc</guid>
            <category><![CDATA[faster-then-restapi]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[real-time-chat]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 15:03:40 GMT</pubDate>
            <atom:updated>2024-01-20T15:53:39.116Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Real-time communication is crucial in many applications, and gRPC (Google Remote Procedure Call) provides an efficient way to implement real-time features. In this tutorial, we’ll walk through building a simple real-time chat application using gRPC and Node.js.</p><h3>Prerequisites</h3><p>Before we dive into the code, make sure you have the following installed:</p><ul><li>Node.js</li><li>npm (Node Package Manager)</li></ul><h3>Setting Up the Project</h3><ol><li>Create a new Node.js project and install the necessary packages:</li></ol><pre>npm init -y<br>npm install @grpc/grpc-js @grpc/proto-loader path winston</pre><p>2. Define the Protocol Buffers (proto) file (realtime.proto) that describes the service and messages.</p><pre>syntax = &quot;proto3&quot;;<br><br>service RealtimeService {<br>  rpc Connect (ClientInfo) returns (ConnectionResponse);<br>  rpc SendMessage (Message) returns (stream Message);<br>  rpc BroadcastMessage (stream Message) returns (BroadcastResponse);<br>}<br><br>message ClientInfo {<br>  string clientId = 1;<br>}<br><br>message ConnectionResponse {<br>  string message = 1;<br>}<br><br>message Message {<br>  string clientId = 1;<br>  string content = 2;<br>}<br><br>message BroadcastResponse {<br>  string senderClientId = 1;<br>  string content = 2;<br>}</pre><p>3. Implement the gRPC server in Node.js:</p><pre>const grpc = (&quot;@grpc/grpc-js&quot;);<br>const protoLoader = require(&quot;@grpc/proto-loader&quot;);<br>const path = require(&quot;path&quot;);<br>const winston = require(&quot;winston&quot;);<br><br>const logger = winston.createLogger({<br>  format: winston.format.simple(),<br>  transports: [new winston.transports.Console()],<br>});<br><br>const PROTO_PATH = path.join(__dirname, &quot;proto&quot;, &quot;realtime.proto&quot;);<br><br>const packageDefinition = protoLoader.loadSync(PROTO_PATH, {<br>  keepCase: true,<br>  longs: String,<br>  enums: String,<br>  defaults: true,<br>  oneofs: true,<br>});<br><br>const realtimeProto =<br>  grpc.loadPackageDefinition(packageDefinition).RealtimeService;<br><br>const server = new grpc.Server();<br><br>const activeClients = new Map();<br>let clientId = undefined;<br><br>server.addService(realtimeProto.service, {<br>  Connect: (call, callback) =&gt; {<br>    const { clientId } = call.request;<br>    logger.info(`Client ${clientId} connected`);<br><br>    // Store the client&#39;s call object for later use<br>    activeClients.set(clientId, call);<br><br>    const response = {<br>      message: `Connection established for client ${clientId}`,<br>    };<br>    callback(null, response);<br>  },<br><br>  SendMessage: (call) =&gt; {<br>    const { clientId, content } = call.request;<br>    logger.info(`Received message from client ${clientId}: ${content}`);<br><br>    // Respond to the client<br>    const response = { clientId, content: `Message received: ${content}` };<br>    call.write(response);<br>    // call.end();<br>  },<br><br>  BroadcastMessage: (call) =&gt; {<br>    console.log(call);<br>    call.on(&quot;data&quot;, (message) =&gt; {<br>      clientId = message.clientId;<br>      logger.info(<br>        `Received broadcast message from client ${message.clientId}: ${message.content}`<br>      );<br><br>      // Broadcast the message to all connected clients (excluding the sender)<br>      activeClients.forEach((client, id) =&gt; {<br>        if (id !== message.clientId) {<br>          const response = {<br>            senderClientId: message.clientId,<br>            content: message.content,<br>          };<br>          logger.info(<br>            `Broadcasting message to client ${id}: ${response.content}`<br>          );<br>          client.write(response);<br>        }<br>      });<br>    });<br><br>    call.on(&quot;end&quot;, () =&gt; {<br>      if (clientId) logger.info(`Client ${clientId} stopped broadcasting`);<br>      else logger.info(`Client stopped broadcasting`);<br>    });<br>  },<br>});<br><br>const PORT = 50051;<br>const HOST = &quot;localhost&quot;;<br><br>server.bindAsync(<br>  `${HOST}:${PORT}`,<br>  grpc.ServerCredentials.createInsecure(),<br>  () =&gt; {<br>    logger.info(`Server running at ${HOST}:${PORT}`);<br>    server.start();<br>  }<br>);</pre><h3>Running the Application</h3><p>Run the Node.js server:</p><pre>node server.js</pre><h3>Testing the Chat Application</h3><ol><li>Connect clients to the server using the Connect method.</li><li>Send messages using the SendMessage method.</li><li>Observe real-time message broadcasting using the BroadcastMessage method.</li></ol><h3>Postman Request Calls:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYlJswVvegXfr9Kv8zzpug.png" /><figcaption>RealtimeService/Connect Method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLvLf_obOdQYFtIOCEkg4g.png" /><figcaption>RealtimeService/SendMessage Method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9u2z-dzyNdC1OsGCpxFOQ.png" /><figcaption>RealtimeService/BroadcastMessage Method</figcaption></figure><h3>Conclusion</h3><p>In this tutorial, we’ve built a simple real-time chat application using gRPC and Node.js. gRPC provides a powerful and efficient way to implement real-time features, making it a suitable choice for various applications.</p><h3>Next Steps</h3><ul><li>Enhance the chat application by adding user authentication.</li><li>Implement additional features like message persistence and user presence.</li></ul><h3>Resources</h3><ul><li><a href="https://grpc.io/">https://grpc.io/</a></li><li>https://grpc.io/docs/languages/node/basics/</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884b680adabc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Euler Problem 54 :Poker hands]]></title>
            <link>https://medium.com/@golluajay9/project-euler-problem-54-poker-hands-cac6f970fdd0?source=rss-133a3ed3518c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cac6f970fdd0</guid>
            <category><![CDATA[project-euler]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[poker-hand]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gollu Ajay]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 09:34:33 GMT</pubDate>
            <atom:updated>2023-11-12T09:35:07.359Z</atom:updated>
            <content:encoded><![CDATA[<p>Question: <a href="https://www.freecodecamp.org/learn/project-euler/project-euler-problems-1-to-100/problem-54-poker-hands">https://www.freecodecamp.org/learn/project-euler/project-euler-problems-1-to-100/problem-54-poker-hands</a></p><p>Solution: using JavaScript.</p><pre>const CARDS_VALUED = {<br>  2: 1,<br>  3: 2,<br>  4: 3,<br>  5: 4,<br>  6: 5,<br>  7: 6,<br>  8: 7,<br>  9: 8,<br>  T: 9,<br>  J: 10,<br>  Q: 11,<br>  K: 12,<br>  A: 13,<br>};<br><br>function findTwoPairs(arr) {<br>  let pairCount = {};<br>  let max = -1;<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (pairCount[arr[i]]) {<br>      pairCount[arr[i]]++;<br>    } else {<br>      pairCount[arr[i]] = 1;<br>    }<br>  }<br><br>  let pairs = 0;<br>  for (let key in pairCount) {<br>    if (pairCount.hasOwnProperty(key)) {<br>      if (pairCount[key] === 2) {<br>        pairs++;<br>        if (max &lt; CARDS_VALUED[key]) {<br>          max = key;<br>        }<br>      }<br>    }<br>  }<br><br>  return [pairs === 2, max];<br>}<br><br>function findThreeOfSameValue(arr) {<br>  let pairCount = {};<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (pairCount[arr[i]]) {<br>      pairCount[arr[i]]++;<br>    } else {<br>      pairCount[arr[i]] = 1;<br>    }<br>  }<br><br>  for (let key in pairCount) {<br>    if (pairCount.hasOwnProperty(key)) {<br>      if (pairCount[key] === 3) {<br>        return key;<br>      }<br>    }<br>  }<br><br>  return 0;<br>}<br><br>function findFourOfSameValue(arr) {<br>  let pairCount = {};<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (pairCount[arr[i]]) {<br>      pairCount[arr[i]]++;<br>    } else {<br>      pairCount[arr[i]] = 1;<br>    }<br>  }<br><br>  for (let key in pairCount) {<br>    if (pairCount.hasOwnProperty(key)) {<br>      if (pairCount[key] === 4) {<br>        return key;<br>      }<br>    }<br>  }<br><br>  return 0;<br>}<br><br>function getPair(arr) {<br>  let pairCount = {};<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (pairCount[arr[i]]) {<br>      pairCount[arr[i]]++;<br>    } else {<br>      pairCount[arr[i]] = 1;<br>    }<br>  }<br><br>  for (let key in pairCount) {<br>    if (pairCount.hasOwnProperty(key)) {<br>      if (pairCount[key] === 2) {<br>        return key;<br>      }<br>    }<br>  }<br><br>  return 0;<br>}<br><br>function findNextHigher(arr, value) {<br>  return [<br>    ...new Set(<br>      arr<br>        .map((item) =&gt; item.slice(0, -1))<br>        .map((value) =&gt; CARDS_VALUED[value])<br>        .sort((a, b) =&gt; a - b)<br>    ),<br>  ].slice(-1 * value, -1 * (value - 1))[0];<br>}<br><br>function getLevelOfPlayer(player) {<br>  const suits = player.map((item) =&gt; item.slice(-1));<br>  const values = player.map((item) =&gt; item.slice(0, -1));<br><br>  const orderCheckList = values.map((value) =&gt; CARDS_VALUED[value]);<br>  orderCheckList.sort((a, b) =&gt; a - b);<br><br>  if (new Set(suits).size === 1) {<br>    const royalRank = Object.keys(CARDS_VALUED).filter(<br>      (k) =&gt; CARDS_VALUED[k] &gt;= 9<br>    );<br>    if (new Set(values).size === 5) {<br>      if (values.filter((value) =&gt; royalRank.includes(value)).length === 5)<br>        return [10, orderCheckList[4]];<br>    }<br><br>    let flag = true;<br>    for (let i = 0; i &lt; orderCheckList.length - 1; i++) {<br>      if (orderCheckList[i + 1] - orderCheckList[i] !== 1) {<br>        flag = false;<br>        break;<br>      }<br>    }<br>    if (flag) return [9, orderCheckList[4]];<br>  }<br>  if (findFourOfSameValue(values))<br>    return [8, CARDS_VALUED[findFourOfSameValue(values)]];<br><br>  if (findThreeOfSameValue(values) &amp;&amp; getPair(values))<br>    return [7, CARDS_VALUED[findThreeOfSameValue(values)]];<br><br>  if (new Set(suits).size === 1) return [6, orderCheckList[4]];<br><br>  let flag = true;<br>  for (let i = 0; i &lt; orderCheckList.length - 1; i++) {<br>    if (orderCheckList[i + 1] - orderCheckList[i] !== 1) {<br>      flag = false;<br>      break;<br>    }<br>  }<br>  if (flag) return [5, orderCheckList[4]];<br><br>  if (findThreeOfSameValue(values))<br>    return [4, CARDS_VALUED[findThreeOfSameValue(values)]];<br><br>  if (findTwoPairs(values)[0])<br>    return [3, CARDS_VALUED[findTwoPairs(values)[1]]];<br><br>  if (getPair(values)) return [2, CARDS_VALUED[getPair(values)]];<br><br>  return [1, orderCheckList[4]];<br>}<br><br>function pokerHands(arr) {<br>  let player1Level = 0;<br>  let player2Level = 0;<br>  let count = 0;<br>  for (let set of arr) {<br>    const player1 = set.split(&quot; &quot;).slice(0, 5);<br>    const player2 = set.split(&quot; &quot;).slice(5);<br>    player1Level = getLevelOfPlayer(player1);<br>    player2Level = getLevelOfPlayer(player2);<br>    if (player1Level[0] &gt; player2Level[0]) {<br>      count++;<br>    } else if (player1Level[0] === player2Level[0]) {<br>      let c = 1;<br>      if (player1Level[1] &gt; player2Level[1]) count++;<br>      else if (player1Level[1] === player2Level[1]) {<br>        const nextHighestPlayer1 = findNextHigher(player1, c + 1);<br>        const nextHighestPlayer2 = findNextHigher(player2, c + 1);<br><br>        console.log(player1,player2,player1Level,player2Level);<br>        // if (nextHighestPlayer1 &gt; nextHighestPlayer2) count++;<br>      }<br>    }<br>  }<br>  console.log(count);<br>  return count;<br>}<br><br>const testArr = [<br>  &quot;8C TS KC 9H 4S 7D 2S 5D 3S AC&quot;,<br>  &quot;5C AD 5D AC 9C 7C 5H 8D TD KS&quot;,<br>  &quot;3H 7H 6S KC JS QH TD JC 2D 8S&quot;,<br>  &quot;TH 8H 5C QS TC 9H 4D JC KS JS&quot;,<br>  &quot;7C 5H KC QH JD AS KH 4C AD 4S&quot;,<br>];<br><br><br>pokerHands(testArr);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cac6f970fdd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>