<?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 Teo Parashkevov on Medium]]></title>
        <description><![CDATA[Stories by Teo Parashkevov on Medium]]></description>
        <link>https://medium.com/@theo.parashkevov?source=rss-31325f5591db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xJxbjQb5Cr6IXi6QRFYPJQ.jpeg</url>
            <title>Stories by Teo Parashkevov on Medium</title>
            <link>https://medium.com/@theo.parashkevov?source=rss-31325f5591db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:46:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@theo.parashkevov/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[[Systemd] systemctl manual]]></title>
            <link>https://medium.com/@theo.parashkevov/systemd-systemctl-manual-c47da5cf8439?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/c47da5cf8439</guid>
            <category><![CDATA[systemd]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 09:25:42 GMT</pubDate>
            <atom:updated>2023-08-20T09:25:42.220Z</atom:updated>
            <content:encoded><![CDATA[<p>A clarifying explanation of the <strong>systemctl</strong> command manual</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ev4qlHNuXPaMQD-1MRqI9w.png" /></figure><p>Greetings, fellow developers and Linux enthusiasts! Today, we’re embarking on an in-depth journey into the world of systemctl, a command that has become the linchpin of modern Linux administration. Join me as we explore every nook and cranny of this indispensable tool, from the comprehensive manual pages to hands-on, real-world examples.</p><h3>1. The systemctl Manual Page (man)</h3><p>Our expedition begins with a crucial resource, the man page for systemctl. To access this treasure trove of knowledge, simply type the following command in your terminal:</p><pre>man systemctl</pre><p>The manual page is a dense but invaluable source of information. It comprehensively covers systemctl, its subcommands, and options, providing you with a deep understanding of its capabilities. Don&#39;t underestimate the power of this resource; it&#39;s your ultimate guide to mastering systemctl.</p><h3>2. The Usefulness of systemctl in Modern Linux Administration</h3><p>Before we dive into practical examples, let’s explore why systemctl is so essential in contemporary Linux administration. This command has redefined the way we manage services, delivering streamlined control, enhanced stability, and simplified workflows.</p><p>As an administrator or developer, mastering systemctl is paramount. It empowers you to effortlessly start, stop, enable, disable, and monitor services. This level of control ensures your system operates smoothly and efficiently, adapting to your needs.</p><h3>3. Example: A Simple Service File Configuration</h3><p>To illustrate the practicality of systemctl, let&#39;s create a systemd service that periodically sends an email containing CPU and memory load information. Begin by crafting a service file, e.g., /etc/systemd/system/load-monitor.service:</p><pre>[Unit]<br>Description=Load Monitor Service<br><br>[Service]<br>ExecStart=/usr/bin/python3 /path/to/your/script.py<br>Restart=always<br>User=yourusername<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>This service, once enabled and started, will execute your Python script. Customize the paths and usernames as needed.</p><h3>4. Example: Timer Service</h3><p>Now, let’s schedule this service using a timer unit. Create a timer unit, e.g., /etc/systemd/system/load-monitor.timer:</p><pre>[Unit]<br>Description=Load Monitor Timer<br><br>[Timer]<br>OnCalendar=*-*-* *:*:00<br>Persistent=true<br><br>[Install]<br>WantedBy=timers.target</pre><p>This timer triggers your load-monitor.service every minute. To put it into action, enable and start it:</p><pre>systemctl enable load-monitor.timer<br>systemctl start load-monitor.timer</pre><h3>5. Reading the Systemd Service Log</h3><p>To keep tabs on your service and diagnose any issues, journalctl is your trusty companion. For our example, you can view logs for load-monitor.service with this command:</p><pre>journalctl -u load-monitor.service</pre><h3>6. Commonly Used journalctl Commands</h3><p>Let’s expand our knowledge with essential journalctl commands for effective log management:</p><ul><li>To display logs with the newest entries first and include additional information:</li><li>journalctl -xe</li><li>To filter logs for a specific unit (service or timer):</li><li>journalctl -u unit_name</li><li>To view logs from a specific time range:</li><li>journalctl --since &quot;yyyy-mm-dd HH:MM:SS&quot; --until &quot;yyyy-mm-dd HH:MM:SS&quot;</li><li>To follow logs in real-time as they’re written:</li><li>journalctl -f -u unit_name</li><li>To clear old logs and free up disk space:</li><li>journalctl --vacuum-time=3d</li></ul><p>These commands grant you a deeper understanding of your systemd-managed services and enable you to diagnose issues effectively.</p><h3>Conclusion</h3><p>In conclusion, systemctl and journalctl are indispensable tools in the realm of Linux administration. Armed with this knowledge and our real-world examples, you&#39;re now well-prepared to manage services with finesse, ensuring the optimal performance of your Linux system. So, go ahead, explore, and master the art of systemctl for a more efficient and reliable Linux experience.</p><p>Stay tuned for more in-depth Linux tutorials and expert tips right here on my Medium blog.</p><p>Disclaimer: Exercise caution when working with systemd services in production environments, and always test thoroughly in a safe setting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c47da5cf8439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Data Structure] Binary Trees (2)]]></title>
            <link>https://medium.com/@theo.parashkevov/data-structure-binary-trees-2-f7a4da5d4a65?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a4da5d4a65</guid>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 09:12:06 GMT</pubDate>
            <atom:updated>2023-08-20T09:14:13.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Data Structures] Binary Trees (2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2rS7MU-K3bkNQh8nuViPg.jpeg" /></figure><h3>Introduction</h3><p>Welcome back, fellow Pythonistas, to another edition of my programming blog! Today, we embark on a comprehensive journey into the fascinating world of Binary Trees using Python. Binary Trees are foundational data structures that lie at the heart of computer science and can be leveraged to solve a myriad of complex problems efficiently. In this post, we will explore the fundamentals of Binary Trees, dissect their properties, dive into practical Python code examples, and master various traversal algorithms.</p><h3>What is a Binary Tree?</h3><p>At its core, a Binary Tree is a hierarchical data structure composed of nodes, each of which has at most two children, referred to as the left child and the right child. The top node of a Binary Tree is known as the root. These trees are incredibly versatile and can be employed to solve various computational problems such as searching, sorting, and representing hierarchical structures.</p><h3>Anatomy of a Binary Tree</h3><p>Before we delve into coding, let’s understand the fundamental components of a Binary Tree:</p><ol><li><strong>Node:</strong> A single element in a Binary Tree containing data and references to its left and right children (if they exist).</li><li><strong>Root: </strong>The topmost node of the tree, from which all other nodes descend.</li><li><strong>Parent Node: </strong>A node that has one or more child nodes.</li><li><strong>Child Node:</strong> A node that is a descendant of another node.</li><li><strong>Leaf Node:</strong> A node with no children.</li><li><strong>Depth:</strong> The level or distance of a node from the root, with the root having depth 0.</li><li><strong>Height:</strong> The maximum depth of the tree.</li></ol><h3>Implementing Binary Trees in Python</h3><p>Let’s get our hands dirty and implement a Binary Tree in Python. Below is a simplified example of a Binary Tree Node class and a basic Binary Tree class:</p><pre>class Node:<br>    def __init__(self, data):<br>        self.data = data<br>        self.left = None<br>        self.right = None<br><br>class BinaryTree:<br>    def __init__(self, root_data):<br>        self.root = Node(root_data)p</pre><h3>Traversing a Binary Tree</h3><p>One of the fundamental operations on Binary Trees is traversal, which allows us to visit all nodes in a specific order. Here are five common methods for traversing Binary Trees: Prefix (Preorder), Infix (Inorder), Postfix (Postorder), Depth-First Search (DFS), and Breadth-First Search (BFS).</p><h4>Prefix (Preorder) Traversal</h4><p>In a Prefix traversal, we visit the current node before moving on to its children. Here’s a Python implementation:</p><pre>def prefix(node):<br>    if node:<br>        print(node.data)    # Process the current node<br>        prefix(node.left)   # Recur on the left subtree<br>        prefix(node.right)  # Recur on the right subtree</pre><h4>Infix (Inorder) Traversal</h4><p>In an Infix traversal, we visit the left subtree, then the root, and finally the right subtree. Here’s a Python implementation:</p><pre>def infix(node):<br>    if node:<br>        infix(node.left)    # Recur on the left subtree<br>        print(node.data)    # Process the current node<br>        infix(node.right)   # Recur on the right subtree</pre><h4>Postfix (Postorder) Traversal</h4><p>In a Postfix traversal, we visit the left subtree, then the right subtree, and finally the root. Here’s a Python implementation:</p><pre>def postfix(node):<br>    if node:<br>        postfix(node.left)   # Recur on the left subtree<br>        postfix(node.right)  # Recur on the right subtree<br>        print(node.data)     # Process the current node</pre><h4>Depth-First Search (DFS)</h4><p>DFS explores as far as possible along a branch before backtracking. There are two common variants of DFS: Preorder (which we’ve seen before) and Postorder. Here’s a Python implementation of Postorder DFS:</p><pre>def postorder_dfs(node):<br>    if node:<br>        postorder_dfs(node.left)   # Recur on the left subtree<br>        postorder_dfs(node.right)  # Recur on the right subtree<br>        print(node.data)           # Process the current node</pre><h4>Breadth-First Search (BFS)</h4><p>BFS explores all the nodes at the current depth before moving to the next depth. Here’s a Python implementation of BFS:</p><pre>from collections import deque<br><br>def bfs(node):<br>    if node is None:<br>        return<br>    <br>    queue = deque()<br>    queue.append(node)<br>    <br>    while queue:<br>        current = queue.popleft()<br>        print(current.data)  # Process the current node<br>        <br>        if current.left:<br>            queue.append(current.left)<br>        if current.right:<br>            queue.append(current.right)</pre><h3>Putting It All Together</h3><p>Now, let’s apply these traversal methods to our sample Binary Tree:</p><pre># Creating the Binary Tree<br>root = Node(1)<br>root.left = Node(2)<br>root.right = Node(3)<br>root.left.left = Node(4)<br>root.left.right = Node(5)<br><br># Performing traversals<br>print(&quot;Prefix (Preorder) Traversal:&quot;)<br>prefix(root)<br>print(&quot;\nInfix (Inorder) Traversal:&quot;)<br>infix(root)<br>print(&quot;\nPostfix (Postorder) Traversal:&quot;)<br>postfix(root)<br>print(&quot;\nPostorder DFS Traversal:&quot;)<br>postorder_dfs(root)<br>print(&quot;\nBreadth-First Search (BFS) Traversal:&quot;)<br>bfs(root)</pre><p>Running this code will generate the traversal outputs as described above.</p><h3>Conclusion</h3><p>Binary Trees are a rich field of study in computer science, and they underpin many algorithms and data structures. In this blog post, we’ve explored their fundamentals, various traversal methods, and even deepened our understanding with DFS and BFS. Binary Trees can be used to solve complex problems efficiently, and mastering them is a significant step in becoming a proficient Python developer.</p><p>As you continue your journey in Python programming, remember that choosing the right traversal method depends on your specific problem. Understanding when and how to apply each traversal method is essential for mastering Binary Trees in Python.</p><p>In future posts, we’ll explore more advanced topics like balancing Binary Trees, implementing Binary Search Trees, and using Binary Trees in practical applications. Until then, happy coding!</p><p>As always, feel free to leave your thoughts and questions in the comments below. Happy coding, Python enthusiasts!</p><p>Thank you for joining me in this comprehensive exploration of Binary Trees and their traversal methods. I hope you found this blog post informative and inspiring. Stay tuned for more in-depth Python programming insights in future articles. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a4da5d4a65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Systemd] Units made simple]]></title>
            <link>https://medium.com/@theo.parashkevov/systemd-units-made-simple-39d7e35cd835?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/39d7e35cd835</guid>
            <category><![CDATA[systemd]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 17:54:50 GMT</pubDate>
            <atom:updated>2023-08-22T18:31:21.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OdF98MG3y1x-zH9Z.png" /></figure><p>Hey there, fellow tech enthusiasts! 👋 Welcome back to another exciting edition of my personal programming blog. Today, we’re diving deep into the realm of Linux system management with a focus on Systemd. Whether you’re a seasoned Linux user or just stepping into the world of open-source awesomeness, understanding Systemd can significantly level up your system administration game.</p><h3>Embracing Systemd: A Modern Approach to Init Systems</h3><p>If you’ve been around Linux for a while, you might recall the traditional SysV init system. While it served its purpose, it had limitations that hindered efficient system management. Enter Systemd, a modern init system that takes a comprehensive approach to managing services, daemons, and the entire boot process.</p><p>Systemd’s advantages are numerous:</p><ol><li>Parallel Startup: Systemd boots services in parallel, slashing boot times and enhancing system responsiveness.</li><li>Service Dependency Handling: It automates service dependencies, ensuring services start in the right order to avoid issues.</li><li>Logging and Journaling: Systemd’s journaling system provides centralized, structured logs that are easy to search and analyze.</li><li>Resource Control: Systemd enables fine-grained control over system resources, enhancing stability and predictability.</li><li>Easy Configuration: With its unit configuration files, Systemd simplifies service configuration and customization.</li></ol><p>Now that we’ve set the stage, let’s dive into some hands-on examples.</p><h3>Exploring Systemd Configuration: A Glimpse into the Magic</h3><p>Example 1: Managing a Web Server (nginx)</p><p>Suppose you’re running a powerful web server like nginx. Managing it with Systemd is a breeze. Create a unit file at /etc/systemd/system/nginx.service:</p><pre>[Unit]<br>Description=The nginx HTTP and reverse proxy server<br>After=network.target<br><br>[Service]<br>Type=forking<br>ExecStartPre=/usr/sbin/nginx -t -q<br>ExecStart=/usr/sbin/nginx<br>ExecReload=/usr/sbin/nginx -s reload<br>ExecStop=/bin/kill -s QUIT $MAINPID<br>PrivateTmp=true<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Now, with a simple systemctl command, you can control nginx:</p><ul><li>systemctl daemon-reload: Reload the updated systemd services.</li><li>systemctl start nginx: Start the nginx service.</li><li>systemctl stop nginx: Stop the nginx service.</li><li>systemctl restart nginx: Restart the nginx service.</li><li>systemctl enable nginx: Enable nginx to start at boot.</li><li>systemctl disable nginx: Disable nginx from starting at boot.</li></ul><p>Example 2: Running a Custom Python Script</p><p>Let’s say you’ve written a fantastic Python script that needs to run as a background service. Create a unit file at /etc/systemd/system/my_python_script.service:</p><pre>[Unit]<br>Description=My Custom Python Script<br>After=network.target<br><br>[Service]<br>Type=simple<br>ExecStart=/usr/bin/python3 /path/to/your/script.py<br>Restart=always<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>With this setup, you can manage your Python script like any other service:</p><ul><li>systemctl daemon-reload: Reload the updated systemd services.</li><li>systemctl start my_python_script</li><li>systemctl stop my_python_script</li><li>systemctl restart my_python_script</li><li>systemctl enable my_python_script</li><li>systemctl disable my_python_script</li></ul><h3>Wrapping Up</h3><p>Congratulations, you’ve just scratched the surface of Systemd’s capabilities! By embracing this modern init system, you’re setting yourself up for efficient service management and streamlined system administration. Remember, the key is to explore, experiment, and adapt these examples to suit your specific needs.</p><p>As always, stay curious and keep tinkering with technology. Until next time, happy coding, and may your services always start promptly and your logs be ever insightful! 🚀🐧</p><p>Catch you in the next blog post!</p><p><em>Teo ParashkevovSenior Python Developer &amp; Linux Enthusiast</em></p><p><em>P.S. Have any questions or want to share your own Systemd experiences? Drop a comment below, and let’s spark a discussion!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39d7e35cd835" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Craft: Unveiling the Power of Design Patterns in Python]]></title>
            <link>https://medium.com/@theo.parashkevov/mastering-the-craft-unveiling-the-power-of-design-patterns-in-python-8e429b332d86?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e429b332d86</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 12:33:03 GMT</pubDate>
            <atom:updated>2023-08-11T12:33:03.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReCl1N-Qhcx9MlJJ1zA91g.jpeg" /></figure><p>Greetings, fellow Pythonistas! Today, let’s dive into the captivating world of software design patterns and explore why they are an indispensable toolkit for any seasoned developer. 🚀</p><p><strong>Understanding the Essence of Design Patterns</strong></p><p>Imagine you’re an architect crafting a majestic skyscraper. Just as architects follow blueprints to ensure structural integrity and functionality, software developers utilize design patterns to guide the construction of reliable and maintainable code. Design patterns are reusable solutions to recurring problems that arise during software development. They offer a common language that helps teams communicate, maintain, and enhance their codebases effectively.</p><p>In Python, a versatile and expressive programming language, these design patterns come to life, showcasing their adaptability and elegance.</p><p><strong>1. Creational Patterns</strong></p><p>Creational patterns focus on object creation mechanisms, allowing us to create objects in a manner suitable for the situation at hand. One classic example is the <strong>Singleton Pattern</strong>. Imagine a configuration manager that should exist in only one instance throughout the application’s lifecycle. The Singleton Pattern ensures that this instance is shared across various components, preventing unnecessary duplication and preserving resources.</p><p><strong>2. Structural Patterns</strong></p><p>Structural patterns center around object composition, facilitating the creation of larger structures from smaller components. Consider the <strong>Decorator Pattern</strong>. Picture a scenario where you want to add new functionalities dynamically to existing objects without altering their structure. The Decorator Pattern achieves this by attaching additional responsibilities to objects, like adding toppings to a pizza without changing its core ingredients.</p><p><strong>3. Behavioral Patterns</strong></p><p>Behavioral patterns address how objects interact and communicate with one another. One widely used example is the <strong>Observer Pattern</strong>. Think of a weather station broadcasting updates to multiple displays. The Observer Pattern enables these displays to receive real-time updates from the weather station, ensuring consistency across the board.</p><p><strong>4. Architectural Patterns</strong></p><p>Architectural patterns provide high-level solutions for structuring entire applications. The <strong>Model-View-Controller (MVC)</strong> pattern is a prime example. In a web application, the MVC pattern separates the application logic into three interconnected components: the Model (data and business logic), the View (user interface), and the Controller (handles user input). This separation fosters modularity and maintainability.</p><p><strong>5. Concurrency Patterns</strong></p><p>Concurrency patterns tackle the challenges of parallel execution and multithreading. Consider the <strong>Thread Pool Pattern</strong>. In scenarios where tasks need to be executed concurrently without overwhelming the system, a thread pool manages a collection of worker threads, optimizing resource utilization and improving overall performance.</p><p><strong>In Conclusion</strong></p><p>Design patterns are not just a fancy concept; they are the backbone of software engineering. By leveraging these patterns, we empower ourselves to tackle complex problems with elegant solutions, enhance code maintainability, and promote effective communication among team members. As Python developers, our versatile language perfectly complements the implementation of various design patterns, allowing us to craft exceptional software systems.</p><p>So, the next time you embark on a coding journey, remember the power that design patterns bring to your arsenal. Happy coding, and may your patterns be ever in your favor! 💡🐍</p><p><em>Do you find design patterns intriguing? Have you had any “aha!” moments while using them in your projects? Share your thoughts and experiences in the comments below! And if you’re hungry for more Pythonic insights, don’t forget to hit that follow button. Until next time!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e429b332d86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Data Structures] Binary Tree]]></title>
            <link>https://medium.com/@theo.parashkevov/data-structures-binary-tree-55d0e55e0b3e?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d0e55e0b3e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 18:08:04 GMT</pubDate>
            <atom:updated>2023-04-26T18:08:04.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXCn7Pf0VqFmazSWa1eurw.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Binary_tree">Wikipedia</a></figcaption></figure><h3>Introduction</h3><p>In computer science, a data structure is a way of organizing and storing data in a computer so that it can be accessed and used efficiently. One of the most popular data structures used in computer science is the binary tree. In this article, we will explore what a binary tree is, how it works, its advantages and disadvantages, and how to implement it in Python.</p><h3>What is a Binary Tree?</h3><p>A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. The topmost node of the tree is called the root node. If a node has no children, it is called a leaf node. Each node in the binary tree can have at most two children, and the left child is always smaller than the parent node, and the right child is always greater than the parent node.</p><p>Binary trees are used in many different areas of computer science, including data storage, search algorithms, and artificial intelligence.</p><h3>How Does a Binary Tree Work?</h3><p>Binary trees are hierarchical data structures. Each node in the tree has a parent node, except for the root node, which has no parent. The nodes in the binary tree are organized in a specific way, with the left child node being smaller than the parent node, and the right child node being larger than the parent node. This organization makes it easy to search for specific nodes in the tree.</p><h4>Advantages of Binary Trees</h4><p>Binary trees have several advantages over other data structures. Here are a few of them:</p><ol><li>Fast searching: Binary trees have fast search times because they are organized in a specific way that allows for quick access to specific nodes.</li><li>Efficient memory usage: Binary trees use memory efficiently because they only store two child nodes for each parent node.</li><li>Easy to implement: Binary trees are relatively easy to implement compared to other data structures.</li><li>Versatile: Binary trees can be used in a variety of applications, including data storage, search algorithms, and artificial intelligence.</li></ol><h4>Disadvantages of Binary Trees</h4><p>Binary trees also have some disadvantages, including:</p><ol><li>Unbalanced trees: If a binary tree is unbalanced, with more nodes on one side of the tree than the other, it can lead to slower search times.</li><li>Slow insertion and deletion: If a binary tree is not balanced, inserting and deleting nodes can be slow.</li><li>Limited number of child nodes: Binary trees can only have two child nodes per parent node, which can limit their usefulness in some applications.</li></ol><h3>Implementing a Binary Tree in Python</h3><p>In Python, we can implement a binary tree using classes and methods. Here is an example of a binary tree implemented in Python:</p><pre>class Node:<br>    def __init__(self, data):<br>        self.left = None<br>        self.right = None<br>        self.data = data<br><br>class BinaryTree:<br>    def __init__(self):<br>        self.root = None<br><br>    def add_node(self, data):<br>        if not self.root:<br>            self.root = Node(data)<br>        else:<br>            self._add_node(data, self.root)<br><br>    def _add_node(self, data, node):<br>        if data &lt; node.data:<br>            if node.left:<br>                self._add_node(data, node.left)<br>            else:<br>                node.left = Node(data)<br>        else:<br>            if node.right:<br>                self._add_node(data, node.right)<br>            else:<br>                node.right = Node(data)<br><br>    def print_tree(self):<br>        if self.root:<br>            self._print_tree(self.root)<br><br>    def _print_tree(self, node):<br>        if node:<br>            self._print_tree(node.left)<br>            print(str(node.data) + &#39; &#39;)<br>            self._print_tree(node.right)</pre><p>Node and BinaryTree. The Node class represents a single node in the binary tree, while the BinaryTree class represents the entire binary tree.</p><p>The Node class has three attributes: left, right, and data. left and right are pointers to the left and right child nodes, respectively, while data is the value stored in the node.</p><p>The BinaryTree class has two methods: add_node and print_tree. The add_node method adds a new node to the binary tree. If the root node does not exist, the new node becomes the root. Otherwise, the _add_node method is called to recursively find the correct location for the new node in the tree.</p><p>The _add_node method compares the value of the new node with the value of the current node. If the value of the new node is less than the value of the current node, the method recursively searches the left child node. If the value of the new node is greater than the value of the current node, the method recursively searches the right child node.</p><p>The print_tree method prints the contents of the binary tree in ascending order. It first calls the _print_tree method to recursively print the left subtree, then prints the value of the current node, and finally calls the _print_tree method to recursively print the right subtree.</p><h3>Conclusion</h3><p>In conclusion, binary trees are an important data structure in computer science. They are efficient for searching, use memory efficiently, and are easy to implement. However, they can be limited by their unbalanced nature, slow insertion and deletion times, and the fact that they can only have two child nodes per parent node.</p><p>In this article, we discussed what a binary tree is, how it works, its advantages and disadvantages, and how to implement it in Python. We hope this article has been informative and helpful for those interested in learning about binary trees.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d0e55e0b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Data Structures] Linked List]]></title>
            <link>https://medium.com/@theo.parashkevov/data-structures-linked-list-57e617d10142?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/57e617d10142</guid>
            <category><![CDATA[linked-list-cycle]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 07:45:05 GMT</pubDate>
            <atom:updated>2023-04-25T07:45:05.720Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*pZHdzheTmbrHtFncaptncA.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Linked_list">Wikipedia</a></figcaption></figure><h3>Introduction</h3><p>Linked lists are a popular data structure used in computer science for storing and manipulating data. They are a dynamic data structure, meaning that their size can change at runtime, unlike static data structures like arrays. In this article, we will explore what linked lists are, how they work, their advantages and disadvantages, and how to implement them in Python.</p><h3>What is a Linked List?</h3><p>A linked list is a collection of nodes that are connected to each other through pointers. Each node contains two fields: data and a pointer to the next node in the list. The first node is called the head of the list, and the last node is called the tail. The tail node’s pointer points to NULL or None, indicating the end of the list.</p><p>There are two types of linked lists: singly linked lists and doubly linked lists. In a singly linked list, each node has a pointer that points to the next node in the list. In a doubly linked list, each node has two pointers, one that points to the next node and another that points to the previous node.</p><h3>How do Linked Lists Work?</h3><p>Linked lists work by manipulating pointers. When a new node is added to the list, it is assigned a pointer that points to the next node in the list. When a node is deleted from the list, the pointer of the previous node is updated to point to the next node, effectively removing the node from the list.</p><p>Linked lists are useful for situations where you need to insert or delete items from a list frequently. Unlike arrays, which require shifting all elements to the right or left when inserting or deleting an element in the middle, linked lists only require updating pointers.</p><h4>Advantages of Linked Lists</h4><ol><li>Dynamic Size: Linked lists can grow and shrink dynamically at runtime, unlike arrays, which have a fixed size.</li><li>Fast Insertion and Deletion: Linked lists can insert and delete items quickly because they only need to update pointers, unlike arrays, which require shifting all elements to the right or left.</li><li>Efficient Memory Usage: Linked lists can use memory more efficiently than arrays because they only allocate memory for the nodes that are needed.</li><li>Versatility: Linked lists can be used to implement various data structures, such as stacks, queues, and hash tables.</li></ol><h4>Disadvantages of Linked Lists</h4><ol><li>Slow Access Time: Linked lists have slower access times than arrays because they need to traverse the list to find a specific node.</li><li>Memory Overhead: Linked lists require extra memory to store the pointers, which can lead to a higher memory overhead than arrays.</li><li>Lack of Random Access: Unlike arrays, which allow random access to elements, linked lists require traversing the list to access a specific element.</li></ol><p>Implementing Linked Lists in Python</p><p>Here is a simple implementation of a singly linked list in Python:</p><pre>class Node:<br>    def __init__(self, data=None, next_node=None):<br>        self.data = data<br>        self.next_node = next_node<br><br>class LinkedList:<br>    def __init__(self):<br>        self.head = None<br><br>    def insert_at_beginning(self, data):<br>        node = Node(data, self.head)<br>        self.head = node<br><br>    def insert_at_end(self, data):<br>        if self.head is None:<br>            self.head = Node(data, None)<br>            return<br>        current_node = self.head<br>        while current_node.next_node:<br>            current_node = current_node.next_node<br>        current_node.next_node = Node(data, None)<br><br>    def delete(self, data):<br>        if self.head is None:<br>            return<br>        if self.head.data == data:<br>            self.head = self.head.next_node<br>            return<br>        current_node = self.head<br>        while current_node.next_node:<br>            if current_node.next_node.data == data:<br>                current_node<br><br>    def print_list(self):<br>        current_node = self.head<br>        while current_node:<br>            print(current_node.data)<br>            current_node = current_node.next_node</pre><p>In the code above, we define a `Node` class to represent each node in the linked list. The `Node` class has two fields: `data` and `next_node`. The `data` field stores the value of the node, and the `next_node` field is a pointer to the next node in the list.</p><p>We then define a `LinkedList` class that has a `head` field that points to the first node in the list. The `LinkedList` class has three methods:</p><p>1. `insert_at_beginning`: Inserts a new node at the beginning of the list.</p><p>2. `insert_at_end`: Inserts a new node at the end of the list.</p><p>3. `delete`: Deletes a node from the list.</p><p>4. `print_list`: Prints the values of all the nodes in the list.</p><h3>Conclusion</h3><p>Linked lists are a powerful data structure that is widely used in computer science. They are versatile, and efficient, and allow for dynamic sizing. While they have some disadvantages, such as slower access times and higher memory overhead than arrays, linked lists are a great choice for situations where frequent insertion and deletion of items are needed.</p><p>In this article, we discussed what linked lists are, how they work, their advantages and disadvantages, and how to implement them in Python. We hope that this article has given you a better understanding of linked lists and their uses.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57e617d10142" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Data Structures] Hash table]]></title>
            <link>https://medium.com/@theo.parashkevov/data-structures-hash-table-41aa58fd81df?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/41aa58fd81df</guid>
            <category><![CDATA[hash-table]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 05:57:38 GMT</pubDate>
            <atom:updated>2023-04-24T05:57:38.222Z</atom:updated>
            <content:encoded><![CDATA[<p>Clarification on some of the concepts and properties regarding Hash tables (HT)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aDKjLObTbkjcvO10fCkYg.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Hash_table">Wikipedia</a></figcaption></figure><h3>Introduction</h3><p>In this article, I will try to explain the concept of Hash Table and will present the advantages and disadvantages of implementing such structures in software systems.</p><h3>Concept of a HT</h3><p><a href="https://en.wikipedia.org/wiki/Hash_table"><strong>Wikipedia</strong></a>: In computing, a <strong>hash table</strong> (<strong>hash map</strong>) is a data structure that implements an associative array abstract data type, a structure that can map keys to values. A hash table uses a hash function to compute an <em>index</em>, also called a <em>hash code</em>, into an array of <em>buckets</em> or <em>slots</em>, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored. Ideally, the hash function will assign each key to a unique bucket, but most hash table designs employ an imperfect hash function, which might cause hash <em>collisions</em> where the hash function generates the same index for more than one key. Such collisions are typically accommodated in some way.</p><p>A Hash Table is a centralized data store that maps keys to values based on a mapping function “hash function”. One of the requirements for a given function to be called a hash function is the associative aspect. Namely, when the function receives the input data, it must be able to map all of it, if not possibly most of it, to the desired mapping space. Another requirement is for the output data of the hash function to be uniformly distributed, this reduces the probability of collisions and increases search speed.</p><p>In a more simplified manner, you could argue that a Hash Table is an array of size N with the added ability to hash a particular type of input data and use the generated hash code to index that input data under the array.</p><p>An important distinction to be made is that the generated hash code is used to index the Hash Table where the actual data is stored. A simple description of the search process of a hash table is as follows:</p><ol><li>The key for a specific value is given as input to the hash function</li><li>The hash function generates a hash code</li><li>The hash code is used to index the Hash Table</li><li>Once indexed successfully, the Hash Table returns the value at that specific index.</li></ol><h4>Properties of HT</h4><ul><li><strong>Centralization </strong>— The hash table stores all its keys and values as a local object.</li><li><strong>Hash function</strong> — A mathematical function that performs mapping from one mapping space to another, with a minimum amount of collisions between data points and a uniform distribution of the hashed (output) data.</li><li><strong>Uniform distribution of hash values</strong> — this is a symmetric probability distribution wherein a finite number of values are equally likely to be observed; every one of <em>n</em> values has equal probability 1/<em>n</em>.</li><li><strong>Load factor </strong>— the parameter that describes the proportion of assigned hashed values to the free space (buckets) in the hash table. As the number of entries occupied in the hash table increases, this leads to an increase in the Load factor, therefore worsening the performance of the hash table on a particular lookup.</li></ul><h4>Advantages of HT</h4><ul><li><strong>Constant time search / insert / delete </strong>— In the most desirable situation, where there is no collision between entries, the hash table is at its optimal state. This leads to fast (<strong>constant time O(1)</strong>) search of a particular entry. This concept applies to deletion and insertion as well.</li></ul><h4>Disadvantages of HT</h4><ul><li><strong>Collisions</strong> —If the hash function is not chosen properly, it may result in producing the same index for multiple inputs, making indexing very difficult. This reduces the optimal search / insert / delete time from being constant time to a much more longer time period. [ <strong>Example</strong> ] If we chose to deal with collisions using a linked list, this will increase the time complexity with a <strong>O(n’)</strong> amount. Where<strong> O(n’)</strong> is linear time to go through the whole length n’ of the linked list. <strong>Here n’ is not the same as n; n is the size of the Hash Table.</strong></li><li><strong>NULL values not allowed </strong>— Hash Tables do not allow for NULL values to be</li></ul><h4>Collision Resolution</h4><p>Collisions are an inevitable part of hash tables. Fortunately, there are some ways to counter and tackle collisions.</p><ul><li><strong>Chaining </strong>— For whenever a particular key after being hashed produces a collision with the value of another, store them in a <strong>Linked List</strong>. The collided items are chained together through a single<strong> Linked List</strong>, which can be traversed to access the item with a unique search key. This method does pose some risks in reducing the search speed of the hash table because a Linked List has a <strong>Time complexity of O(n’)</strong>, where n’ is the size of the Linked List. We can mitigate this in some way, by ordering the Linked List, this does not bring a significant improvement to the overall reduced time complexity of the Hash Table, however, theoretically, it does improve this problem.</li><li><strong>Sparse Chaining</strong> — This technique relies on the concept of “buckets”. Each bucket is a separate hash table that can grow and shrink dynamically. When a collision occurs, the key-value pair is inserted into the appropriate bucket using its own hash function. If the bucket becomes too full, it can be resized to accommodate more entries.</li></ul><h3>Example</h3><p>This implementation uses a list of lists to implement chaining. Each bucket is a list of key-value pairs stored as tuples. The `insert()` method appends the key-value pair to the end of the corresponding bucket. The `search()` method searches for the key in the corresponding bucket and returns the corresponding value if found. The `delete()` method removes the key-value pair from the corresponding bucket.</p><pre>class HashTable:<br>    def __init__(self):<br>        self.size = 10<br>        self.table = [[] for _ in range(self.size)]<br><br>    def hash_function(self, key):<br>        return hash(key) % self.size<br><br>    def insert(self, key, value):<br>        hash_val = self.hash_function<br>        self.table[hash_val].append((key, value))<br><br>def search(self, key):<br>    hash_val = self.hash_function(key)<br>    bucket = self.table[hash_val]<br>    for k, v in bucket:<br>        if k == key:<br>            return v<br>    raise KeyError(&#39;Key not found&#39;)<br><br>def delete(self, key):<br>    hash_val = self.hash_function(key)<br>    bucket = self.table[hash_val]<br>    for i, (k, v) in enumerate(bucket):<br>        if k == key:<br>            del bucket[i]<br>            return<br>    raise KeyError(&#39;Key not found&#39;)</pre><h3>Conclusion</h3><p>In conclusion, hash tables are an efficient data structure that offers fast and constant-time lookup. They are widely used in computer science and have a wide range of applications.</p><p>Python’s built-in dictionary data type is implemented using hash tables, making it a powerful tool for storing and retrieving data. When implementing your own hash table, it is important to choose an appropriate hash function and collision resolution strategy to ensure efficient lookup times.</p><p>Chaining and open addressing are two common collision resolution strategies, each with its own advantages and disadvantages. Overall, hash tables are a versatile and efficient data structure that every programmer should have in their toolbox.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41aa58fd81df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[C programming] Resource management system using Telegram Bot]]></title>
            <link>https://medium.com/the-code-vault/c-programming-resource-management-system-using-telegram-bot-6c92ec462d0f?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c92ec462d0f</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 13:55:19 GMT</pubDate>
            <atom:updated>2021-11-09T13:55:19.667Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide to creating a system resource information messaging system using the Telegram Bot API in C/C++</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8-RrGzqGilZ-pHsPf_YIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYojeXXFq_YNMnDcPtu7Gg.gif" /><figcaption>GIF</figcaption></figure><h3>Introduction</h3><p>The increasing popularity of alternative messaging apps like Telegram, Signal, Tox and many others, has led to a rapid development in a variety of aspects in these social platforms. More capabilities have been added in order to stay competitive in the market; APIs have been gradually broadening their features.</p><p>This <em>development expansion</em> has given both users and developers a vast range of opportunities to implement their own systems on-top of these APIs.</p><p>In this article I will be describing the process of creating a simple telegram bot service using a specialized C/C++ library and systemd services on Linux.</p><h3>The TgBot-cpp Library</h3><p>This library gives the programmer a wide variety of classes and functions which communicate with the Telegram API. The library can be found on <a href="https://github.com/reo7sp/tgbot-cpp">GitHub</a>, as well as documentation <a href="https://reo7sp.github.io/tgbot-cpp/index.html">here</a>.</p><p>The library consists of 3 modules:</p><ul><li><strong>General </strong>— The API class, the Bot class, EventBroadcaster class [event management is done here] and the TelegramBotException class</li><li><strong>Types </strong>— Basic types like, TextMessage, AuidoMessage, FileMessage, Chat, …</li><li><strong>Net </strong>— takes care of the HTTP communication as well as the SSL encryption</li></ul><p>These 3 modules lay the foundation to all Telegram Bots that use this library. The usual process of creating a bot object and binding it to a real Telegram Bot is simple.</p><ol><li>A Telegram Bot object is instantiated with a <em>token</em> parameter</li><li>Various event handlers are bind to the bot object depending on the situation and the event type.</li><li>The bot object enters the main loop where it waits for event and executes callbacks respectively.</li></ol><h3>Creating a Telegram Bot</h3><p>As show in the official website <a href="https://core.telegram.org/bots">here</a>, creating a Telegram Bot does not require any special programming skills. The process is quite simple, and anyone with an active Telegram account can create a number of bots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*TIhxb6tTrnwsG-4v" /><figcaption>Bot Father</figcaption></figure><p>As described in the <a href="https://core.telegram.org/bots#6-botfather">Bot Father</a> section, the <strong>first step</strong> in creating a Bot is to open a chat with Bot Father — Telegrams specialized Frond-end for creating other bots. Then send the command /newbot(<em>strings starting with “/” represent commands to be executed by the bots </em>) to the chat with Bot Father. The <strong>third step</strong> is to provide the newly created Bot with a <em>display name</em> and a <em>username</em>. After all the above steps have been completed successfully, Bot Father will display general information about the newly created bot.</p><p>The most important piece of information regarding your bot is the <strong>TOKEN</strong>. <strong>Only</strong> through the <strong>token</strong> can one access the capabilities of the bot and program specialized software for bot management. The token usually is a string with the following format: &lt;bot_id&gt;:&lt;bot_access_key&gt;</p><p>The important parameters (as listed in the original documentation) for any Telegram Bot are shown below :</p><ul><li>The <strong>name</strong> of your bot is displayed in contact details and elsewhere.</li><li>The <strong>Username</strong> is a short name, to be used in mentions and t.me links. Usernames are 5–32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username <strong>must</strong> end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’.</li><li>The <strong>token</strong> is a string along the lines of 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw that is required to authorize the bot and send requests to the <a href="https://core.telegram.org/bots/api">Bot API</a>. Keep your token secure and store it safely, it can be used by anyone to control your bot.</li></ul><h3>System Architecture</h3><h4>Main Goal</h4><p>The main goal of the program that I will be showing here is to send messages to a particular char in Telegram. The contents of these messages shall be acquired from files within a specific directory. This can be very useful, especially in system administration. In my particular case, I have important information like CPU usage, RAM usage, CPU temperature, etc. which in some extreme situations, needs to be managed, in some sense, <em>directly</em> by me. In order to be notified immediately of a particular circumstance, I need something to act immediately and send that information directly to me. I designed this simple program to make use of the Telegram API and send me information directly to my Telegram account.</p><h4>Architecture</h4><p>The architecture of the system is quite simple. I will divide each feature of this system into a specific module. In order to get the needed information from the system, like CPU, RAM etc. I have written other programs/scripts that fetch that particular information, format it and store it in files on the filesystem. This is the <em>information gathering </em>module. The <em>communication</em> module is the program that we will discuss today in this article — the Telegram Bot; It checks the files for new information and sends the new information directly to the chat that I have opened with this Bot. The<em> system manger</em> module here is represented by <strong>systemd</strong>. I have created a simple service that is responsible for the Telegram Bot and its child processes. Simply said, the design of this system goes something along the lines of:</p><p><em>There are some scripts that are execute and gather information about the system; They write that information into files; The Telegram Bot program will create </em><strong><em>N</em></strong><em> processes for each file that needs to be watched. Each process is responsible for one file </em><strong><em>only</em></strong><em>; If a file gets modified, a message will be sent to the recipient using the Telegram Bot API with the modified file contents. All of this will be managed by a systemd service.</em></p><p>In order to make things clear, I would like to conceptually divide the <em>content information</em> from the actual <em>perpetrator</em> which will send messages through the Telegram Bot API. The program responsible for the Telegram Bot will <strong>not</strong> deal with or manage any files on the filesystem, it will <strong>only</strong> be allowed to <strong>read</strong> a particular file and nothing more. This will increases the security of the system overall. The main reason being the <strong>low coupling</strong> of the module responsible for file management and the module responsible for sending the messages. Another reason I believe increases the level of security is the fact that even if, <em>one day</em>, a particular <strong>bug</strong> is found in the Telegram API that grants access to the remote executing program, the program itself will not have many features/options that give the attacker any type of advantage over the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEF-jHuUgI0i41seEkMxig.png" /><figcaption>Fig. 1</figcaption></figure><p>Figure 1 provides a simple example of how the system architecture will look. In this example there are 5 resources that need to be managed by the system —<strong> CPU</strong> usage, <strong>RAM</strong> usage, <strong>Net</strong>work traffic, system <strong>temp</strong>erature and some <strong><em>other</em></strong> resource. There are 5 jobs belonging to the <em>information gathering </em>module which write information to their respective files on the filesystem. The main Telegram Bot process creates 5 child processes to manage each resource file. Each child process is responsible for one file only and it checks its file descriptor every M milliseconds for modifications. If the file has been modified, the contents are sent to the Telegram Bot object shared by all child processes and then sent to a specific chat. If the file has not been modified, the child process does not execute any additional code.</p><h4><em>1. Information gathering module</em></h4><p><em>This paragraph is mainly informative and therefore does not dive deep in specifics on how to implement such modules.</em></p><p>This module consists mainly of bash scripts, that are executed at a given interval. the output of these scripts is then <em>piped </em>&gt;&gt; to a file, which later on the Telegram Bot process reads.</p><p>You can implement your own information gathering module by again using bash scripts, compiling a program, overwriting files through the network by another machine etc.</p><h4>2. Communication module</h4><p><em>This paragraph describes the design of the communication module, responsible for reading the file contents and sending messages to the appointed chat id.</em></p><p>The main Telegram Bot process will be responsible for the creation of <strong>N</strong> child processes, which will constantly be checking if their designated file has been modified. On Figure 1 the main Telegram Bot process is represented as a blue square, each child process is a line inside the square which gets information from a specific file on the filesystem. For example, the <em>CPU process</em> reads the <em>cpu.file.txt</em> every M milliseconds and keeps track of the last modified timestamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5A18_pp75uSCokHKEN14g.png" /><figcaption>Fig.2</figcaption></figure><p>In order to optimize this service a bit, we can implement an <em>environment variable</em> specific for each child process. This <em>environment variable</em> will contain the value of the <em>last_modified_timestamp</em> of the respective file [in Unix time]. In this way, each child process is self-sufficient and does not rely on anything else for its execution. The environment variable names are shown on Figure 2 in each child process box in green.</p><p><strong>[ Note ]</strong> In GNU/Linux when a process creates a child process, the child process is “<em>granted access</em>” to the parent processes’ resources i.e. environment variables. However, the child does not share its environment with its parent.</p><p>Once this environment variable has been set, it is then compared to the real-time <em>last_modified_timestamp</em> every M milliseconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-XGIsEfca5Ib3OwXYuCFg.png" /><figcaption>Fig. 3</figcaption></figure><p>Figure 3 shows the process of sending the file contents from the cpu.file.txt. After the cpu get info job has written the new content to the file, the modified flag has changed. As this happens, the child process responsible for the cpu file has waited M milliseconds and therefore can go and compare the <em>last_modified_timestamp</em> value, stored in <strong>CPU_ENV_VAR</strong> with the current modified flag of the file. Because the file was modified within the M millisecond “<em>sleep</em>” time period of the child process, the two modified values do not match. Therefore, the contents of the file have to be sent to the Telegram Bot object, which is shared among all child processes. After that the Telegram Bot object can call <em>send_message()</em> function and send the new file content to a specific chat [chat_id].</p><p>The process of sending the modified file contents with the help of the Telegram Bot object is the same amongst all child processes.</p><h4>3. System Manager module</h4><p><em>This paragraph describes the design of the system manager module, responsible for the creation and termination of any Telegram Bot service here.</em></p><p>The system manager module will be able to create and manage any given Telegram Bot service. This module consists of a give number of telegram bot services — systemd service files located in the /etc/systemd/system/ directory. Each service will have its main process [<strong>ExecStart=</strong>] set to the already compiled Telegram Bot executable. The executable will take 2 arguments; the first argument will be the configuration directory that stores the resource files needed to be watched; the second argument will be process verbosity.</p><p>Termination of the service and all its subsequent child processes will also be managed through systemd. Because the main parent process will create N number of child processes and then exit [<strong>return 0</strong>] this leaves these N child processes in the CGroup of the service. In order to stop the service these child processes need to be stopped/terminated.</p><p>[ <strong>Note</strong> ] If you are not familiar with systemd unit file syntax or need a reminder of how some simple services are created, I encourage you to go read my article <a href="https://medium.com/the-code-vault/systemd-simple-service-examples-ce586afeed27"><strong><em>[Systemd] simple service examples</em></strong></a>.</p><h3>[Code] Communication module</h3><p><em>The code repository for this project is located </em><a href="https://github.com/theoparashkevov/Telegram-Bot-C-CPP"><strong><em>here[GitHub]</em></strong></a><em>. You are free to use and modify it </em>[✌️🏼] <em>. If you find any errors or have any suggestions, please let me know be contacting me here or on other platforms.</em></p><p>The <em>communication module</em> is separated into 3 files: <strong>main.cpp, config.h </strong>and<strong> config.cpp</strong>. As you are familiar with C/C++ the main.cpp file contains the main function; the config.h is the header file and config.cpp is the implementation of the config header. I have decided to use this simple structure in order to contain most of the program within a small number of files, as well as having a clear logical distinction between them.</p><p>The basic program logic contains the following functions:</p><ul><li>A function responsible for the creation of environment variables inside a given process;</li><li>A function responsible for</li></ul><h4>The config.h Header</h4><p>This header file contains include directives for the required libraries, definitions for length and size of different buffers and variables, and also function declarations.</p><ul><li><strong>ENV_CHAR_VARIABLE_LENGTH </strong>— defines the length of the environment variable name for each child process [<strong>default: 16 bytes</strong>]</li><li><strong>SIZE_ENV_CHAR_VARIABLE </strong>— defines the size of the environment variable for each child process [<strong>default: 16 bytes</strong>]</li><li><strong>SIZE_FILE_NAME </strong>— defines the size of the file name buffer to be read from the filesystem [<strong>default 256 characters i.e. 256 bytes</strong>]</li><li><strong>CONTENT_BUFFER_SIZE </strong>— the size of the buffer that will store the contents of the file of each child process [<strong>default 4 MB</strong>]</li></ul><p>Inside <strong>config.h</strong> there is also a structure called <strong>directory_files</strong>, which includes two variables; <em>_p</em> which is the pointer to an allocated space where the file names of a particular directory are stored; <em>_count</em> which returns the number of files in that particular directory. This structure is used in the return type of the function <strong>list_files_in_directory()</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSyE1-qUYLYfKWnxxsZg3A.jpeg" /><figcaption><strong>config.h</strong></figcaption></figure><p>Function declarations include the following functions:</p><ul><li><strong>create_environment_variable() </strong>— creates environment variable with name <em>_name</em> and value <em>_val</em> inside the invoking process.</li><li><strong>send_message_to_char()</strong> — sends a message to <em>_chat_id</em> after comparing <em>env_var_name</em> with its previous value; this is the environment variable name for the variable that stores the <em>last_modified_timestamp</em>. <em>_flag</em> is a flag for verbosity. <em>_file_path</em> is the path to the file from which to read its contents. <em>TgBot::Bot * b</em> is a pointer to the common Telegram Bot object from TgBot-cpp library that is shared amongst all child processes.</li><li><strong>list_files_in_directory()</strong> — indexes files inside the <em>_dir_path</em> directory and returns a <em>directory_files</em> structure.</li><li><strong>get_file_last_modified_time()</strong> — returns the <em>last_modified_timestamp</em> of a file with path <em>_file_path</em> [default format: Unix time]</li><li><strong>get_file_name() </strong>— returns the name of the file without the .xxx extension/format</li><li><strong>get_folder_name()</strong> — returns the converted <em>long long integer</em> value of a numerical folder name i.e. when a folders name is the <em>chad_id</em> it gets converted from an array of characters to a <em>long long integer</em>.</li></ul><h4>The config.cpp Implementation</h4><p>The config.cpp file contains implementations of the function definitions from the config.h header file.</p><ul><li><strong>int create_environment_variable(char * _name, char * _val) </strong>— This function takes two parameters _name and _val and creates an environment variable in the current process using the <a href="https://man7.org/linux/man-pages/man3/setenv.3.html"><strong>setenv() </strong>function</a>. We add <strong><em>fflush(stdout)</em></strong> because when a child process is called and executes this function inside systemd service, the journal program that keeps logs of each service in systemd will not get the output of <strong><em>printf()</em></strong> unless flushed. [ <strong>Important</strong> ] If not flushed, this buffer (stdout) can grow a lot and consume a vast amount of memory resource.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*-CMCE2BZkaeAba2r_rtpqw.jpeg" /><figcaption><strong>create_environment_variable()</strong></figcaption></figure><ul><li><strong>void send_message_to_chat(unsigned long long int _chat_id, char * env_var_name, TgBot::Bot *b, char * _file_path, int _flag)</strong> — This function is basically one big infinite while loop. This function is called once a new child process has been successfully created. Therefore keeping each child process inside its own infinite loop.</li></ul><p>Firstly, this functions tries to get the environment variable env_var_name and its value. If this process is not successful, the loop is broken and there is nothing else to do. Therefore the programmer must investigate this issue.</p><p>Once the <strong>environment variable</strong> with the <em>last_modified_timestamp</em> has been gotten, then the function executes <em>get_last_modified_time()</em> onto the file with path <em>_file_path</em>. Then this value gets stored inside a string <em>_last_modified_char</em>. Afterwards the environment variable value and the current last modified time stamp are to be compared. If they differ this means that the file has been modified within the sleep period, therefore a message must be send to chat_id. If they are the same nothing is to be done.</p><p>Secondly, the file contents must be acquired. We allocate <strong>CONTENT_BUFFER_SIZE</strong> amount of space for the contents of the file. Afterwards while the content of the file is being looped over a temporary character stores the current character of the file content in the content buffer. Once the <strong>E</strong>nd <strong>O</strong>f the <strong>F</strong>ile has been reached, we append 0x00 to indicate the end of the content buffer. After this procedure has been done, we can close the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMg5ONeAhPQyVjAMQO4LKw.jpeg" /><figcaption><strong>send_message_to_chat() 1</strong></figcaption></figure><p>Thirdly, after the information from the file has been copied to the content buffer, it must be appended inside a message variable of type string. This message variable is later passed to the <em>sendMessage()</em> function by the Telegram Bot object. Sending a message using the Telegram Bot object must be enclosed inside a try..catch.. block because of error prevention. For example, if for some reason the machine that is running this service is not connected to the internet and does not have the possibility to contact the Telegram API, then sending a message will result in an error. We catch 2 types of errors inside this block: 1) a system error and 2) TgException error.</p><p>Finally, we clean up all the allocated space for the buffers and flush all the <em>printf</em> statements to <em>stdout </em>and we sleep for 5 seconds. This is the final statement that gets executed before running the loop again from the beginning.</p><p>[ <strong>Note</strong> ] When <em>_flag</em> is set to 1, the print statements get executed, when <em>_flag</em> is set to 0 the print statements are not executed. This is a simple implementation of verbosity management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2hwTEykihhNW_nV065Fgg.jpeg" /><figcaption><strong>send_message_to_chat() 2</strong></figcaption></figure><ul><li><strong>directory_files * list_files_in_directory(char * _dir_path ) </strong>— This function takes one parameter, namely <em>_dir_path</em> and allocates a piece of memory to store the names of the files listed in that particular directory. Afterwards, this allocated memory block is being pointed to by pointer <em>_p</em> of the structure <strong>directory_files</strong> and also the number of files present inside the directory is saved inside the variable <em>_count</em> inside that same structure. Here we have already predefined <strong>SIZE_FILE_NAME</strong>, therefore we allocate that much memory for the name of the first file listed inside the directory. We want to exclude the <em>“.”</em> and <em>“..”</em> paths, that being the reason why we have a conditional statement inside the while loop. On each iteration of the loop a new file from the directory is listed, then it is compared if it matches the excluded paths. If not, we <strong>reallocate</strong> i.e. <strong>expand</strong> the currently allocated memory block with filenames to have place for one more file name. We also increment the number of currently listed files. Finally, the function returns a pointer to a structure holding a pointer pointing to the beginning of the already expanded memory block with file names and a <em>_count</em> variable holding the number of listed files.</li></ul><p>[ <strong>Note</strong> ] The increment for the file names here is <strong>SIZE_FILE_NAME</strong>, <strong>not</strong> 1. This is the reason for having the line _current_file = _return_val + ( n * <strong>SIZE_FILE_NAME</strong> ) . Basically, for each new file name that must be stored in the per-allocated memory space there must be <strong>SIZE_FILE_NAME</strong> bytes, no matter if the file name is long enough to fill the whole <strong>SIZE_FILE_NAME</strong> space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*ALu_NgngCL018HT43m1ACg.jpeg" /><figcaption><strong>list_files_in_directory()</strong></figcaption></figure><ul><li><strong>long long int get_file_last_modified_time(char *_file_path) </strong>—This function acquires the last modified timestamp for a particular file using the <strong>stat</strong> structure and <strong>stat()</strong> function. On success the result is returned in Unix time, otherwise -1 is the return value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*8bC1L1qgBuOXn8liPvy_JA.jpeg" /><figcaption><strong>get_file_last_modified()</strong></figcaption></figure><ul><li><strong>char * get_file_name(char * _file_name_w_extension) </strong>— This function has a parameter that is the file name with extension. This parameter is run through a for loop starting from the first character in the file name and looping through the whole name until the pointer has reached the ‘.’ character. Then the newly created <em>file_name_no_extension</em> is appended an end of string character “\0” indicating the termination of the loop and end of the file name. This new file name is then returned by the function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*foq-nBiHHbeP8G-gBapOUw.jpeg" /><figcaption><strong>get_file_name()</strong></figcaption></figure><ul><li><strong>unsigned long long int get_folder_name( char * _path, int _size)</strong> — This function has two parameters <em>_path</em>, indicating the path to the folder and <em>_size</em>, indicating the length of the path string. For example /home/user/.config/telegram_bot/123456789/will be the _path parameter and 42 will be its length. The function starts from the end of the string skipping the last 2 characters. Then we loop the string until we have encountered a ”/” character indicating that the directory name has been fully looped through. On each iteration we reduce the current character value by 48 [the ASCII number for the ‘0’ character] producing an integer value corresponding to its character. On each iteration we also multiply the base by 10 and add the sum to the result, namely getting the 10th place 100th place 1000th place .. number and summing them all together.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*tGC-2NlEKZVvOY0nxPbuEQ.png" /><figcaption><strong>get_folder_name()</strong></figcaption></figure><h4>The main.cpp Program</h4><p>The main.cpp file contains the execution sequence of the designed architecture. The sequence of function execution is broken up into several parts.</p><p>Firstly, we pass 2 arguments to the main program: the path to the directory containing the files that are going to be watched by each child process and a verbosity parameter. The directory that is being passed as the 1st argument must be named after the desired chat id to which the Telegram Bot will send the messages. For example /home/user/.config/telegram_bot/123456789/is a valid path and /home/user/.config/telegram_bot/chatBot100/ is <strong>NOT</strong> a valid path.</p><p>Secondly, before compiling the program, please make sure that the token variable is set to the the desired Telegram Bots’ token. Otherwise, there will be no communication with the Telegram API.</p><p>Afterwards the program continues its execution by converting the chat id folder name to a long long integer and storing its value inside the <em>_chat_id</em> variable. Then the files under that specific directory are listed inside the <em>_files</em> <strong>directory_files</strong> structure.</p><p>Consequently, the program enters a for loop looping over the number of files inside the directory. We pass each filename through the function that reduces the passed string value to only a file name without any extensions. Then we get the <em>last_modified_timestamp</em> flag of the current file and create an environment variable with this value.</p><p>Finally, a new process is <a href="https://www.man7.org/linux/man-pages/man2/fork.2.html"><em>forked</em></a> for the current file name and assigned the recently created environment variable. From this point on the child process enters the while loop inside the <strong>send_message_to_chat()</strong> function and the parent process continues looping through the files and spawning child processes.</p><p>[ <strong>Note</strong> ] When looping through the files in the directory_files structure, the increment is <strong>not</strong> 1, rather than the predefined <strong>SIZE_FILE_NAME</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*3JCczl1MGl2yrhOIepjpFw.jpeg" /><figcaption><strong>main()</strong></figcaption></figure><p>[ <strong>Note</strong> ] In order to compile the program correctly, you need to have the <strong>TgBot</strong>, <strong>Boost system</strong>, <strong>SSL</strong>, <strong>Cryptography</strong> and <strong>Threading</strong> libraries installed on your system and point the library files to the compiler.</p><pre>g++ main.cpp config.h config.cpp -o telegram_bot --std=c++11 -I/usr/local/include -<strong>lTgBot</strong> -<strong>lboost_system</strong> -<strong>lssl</strong> -<strong>lcrypto</strong> -<strong>lpthread</strong></pre><h3>[Code] System Manager module</h3><p>In the System Manager module we create a simple systemd service that is going to execute our already compiled Telegram Bot executable. The executable has 2 parameters, as we already discussed, these parameters are the directory which stores the resource files and a verbosity flag.</p><p>[ <strong>Note</strong> ] Make sure to have <strong>KillMode=</strong> set to process. This is not recommended in regular process management, but here this is the simplest solution to stopping the service with just one command.</p><p><em>If set to </em><em>process, only the main process itself is killed (not recommended!)</em></p><p>For more information please visit <a href="https://www.freedesktop.org/software/systemd/man/systemd.kill.html"><strong>this</strong></a> link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*QlQ8pcN_1qWIQP2gz25YMA.jpeg" /><figcaption>systemd telegram-bot service</figcaption></figure><p>In order to stop/kill the service and all its CGroup processes use systemctl kill &lt;telegram-bot.service&gt;</p><h3>Final Results</h3><p>The final product can be seen on the image below. Here I am showing how to start the Telegram Bot systemd service. This is also a demonstration of the response time of the Telegram Bot system when a particular file get modified.</p><p>We can conclude that this resource management system is quite reliable and robust. I hope</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYojeXXFq_YNMnDcPtu7Gg.gif" /><figcaption>GIF</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c92ec462d0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-code-vault/c-programming-resource-management-system-using-telegram-bot-6c92ec462d0f">[C programming] Resource management system using Telegram Bot</a> was originally published in <a href="https://medium.com/the-code-vault">The Code Vault</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Data Structures] Distributed hash table]]></title>
            <link>https://medium.com/the-code-vault/data-structures-distributed-hash-table-febfd01fc0af?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/febfd01fc0af</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 11:39:01 GMT</pubDate>
            <atom:updated>2021-10-25T11:39:01.644Z</atom:updated>
            <content:encoded><![CDATA[<p>A clarification on some of the concepts and properties regarding Distributed hash tables (DHT)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gzXEVOy8ye47tzZYkimfw.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Distributed_hash_table">Wikipedia</a></figcaption></figure><h3>Introduction</h3><p>With the rise of cryptocurrencies in recent years, the topic of “Decentralization” in general has gained a substantial amount of popularity. As <em>decentralization</em> finds its way into the vocabulary of more and more people with enthusiasm for technology, the greater the probability for those people to become misinformed about the underlying concepts in that particular technology. These topics should be handles with care, they are not something that can be explained in a ~10 min. video, therefore a substantial amount of determination and logical robustness is required from the consumer of such information.</p><p>In this article, I will try to explain the concept of Distributed Hash Table and will present the advantages and disadvantages of implementing such structures in software systems.</p><h3>Concept of a DHT</h3><p><a href="https://en.wikipedia.org/wiki/Distributed_hash_table"><strong>Wikipedia</strong></a>: A <strong>distributed hash table</strong> (<strong>DHT</strong>) is a distributed system that provides a lookup service similar to a hash table: key-value pairs are stored in a DHT, and any participating node can efficiently retrieve the value associated with a given key. The main advantage of a DHT is that <strong>nodes</strong> can be <strong>added or removed </strong>with <strong>minimum work around re-distributing keys</strong>. Responsibility for maintaining the mapping from keys to values is distributed among the nodes, in such a way that <strong>a change in the set of participants causes a minimal amount of disruption</strong>. This allows a DHT to scale to extremely large numbers of nodes and to handle continual node arrivals, departures, and failures.</p><p>A <strong>Distributed Hash Table</strong> is a decentralized data store that looks up data based on key-value pairs. Every node in a DHT is responsible for a set of keys and their associated values/resources. A key may be assigned to a hash value of a specific variable or the hashed contents of a particular file resource on the system. Furthermore, the key is a unique identifier for its associated data value, which can be any form of data [file, variable, etc.], created by running the value through a hashing function. A node may be responsible for one or many keys, depending on the architecture of the network of nodes.</p><h4>Properties of DHT</h4><ul><li><strong>Autonomy and decentralization</strong> — nodes collectively form the system without any central coordination.</li><li><strong>Fault tolerance </strong>— the system should be reliable (in some sense) even with nodes continuously joining, leaving, and failing</li><li><strong>Scalability </strong>— the system should function efficiently even with thousands or millions of nodes.</li></ul><h4>Advantages of DHT</h4><ul><li><strong>Resilience to change in active node number</strong> — It’s highly resilient to network leavers/joiners or other big changes around the network; changes in the number of active nodes is handled very well by the network.</li><li><strong>Automatic data distribution </strong>— Data is automatically distributed, according to specific configuration options. The specific way how data is eventually organized depends on the chosen strategy in the design.</li><li><strong>Data loss resilience </strong>— Data is replicated across nodes, so it’s difficult to have a permanent loss of a particular set of data, <strong><em>but not impossible</em></strong>.</li><li><strong>Decentralization </strong>— There is no central entity responsible for data management and query handling.</li></ul><h4>Disadvantages of DHT</h4><ul><li><strong><em>Probable</em> data loss </strong>— The probability of data loss exists as DHT doesn’t provide absolute guarantees on data consistency and integrity.</li><li><strong>Decentralization </strong>— There is no authority in the network that can handle and prioritize queries, which can lead to network overload.</li><li><strong>Speed of a query</strong> — the speed of a particular query depends on the specific architectural implementation of DHT; It can range from O(n) to O(logN)</li></ul><h3>Example</h3><h4>0. Creating the network; Assigning Node IDs</h4><p>In this example we will create a DHT with 8 Nodes. These 8 nodes will be connected, such that the network forms conceptually a “circle” starting from the first node. Each node will be assigned an ID from the following array of IDs {10, 20, 30, 40, 50, 60 ,70, 80 }. The first Node will have an ID of 10, the second; an ID of 20 and so forth. (Fig. 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUqm1hM-Fwfegi2pdzIkpw.png" /><figcaption>Figure 1</figcaption></figure><p>Each Node will have a successor (the node immediately after the current node that is connected in the network i.e. the next node) and a predecessor (the node immediately before the current node that is connected in the network i.e. the previous node). (Fig. 2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gS0Wlrmxsnr42rbjsAe52Q.png" /><figcaption>Figure 2</figcaption></figure><h4>1. Resource assignment based on Node ID</h4><p>Let us consider that the main purpose of the DHT in this example is to store the contents of a particular set of files. The specific content of each file does not matter for this example, however I would like to use file contents in order to make the example seem closer to a real world problem.</p><p>Suppose that we have 8 files that contain very important information; file1, tile2, … In a normal Hash table we would either hash the absolute path to the file, or the relative path to the file, or even hash all the file contents. Regardless of the choice, the output of the hash will be the “key” in the key-value pair in our hash table. In this example, for simplicity reasons, the output of our hashed files will be the following array of keys {15, 25, 35, 45, 55, 65, 75, 85}. (Fig. 3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8opYv3RuKcMpiKyVKI-nw.png" /><figcaption>Figure 3</figcaption></figure><p>Now that the key-value pair is available, a “resource distribution” scheme must be chosen. In this example I will keep things simple and will chose the resource distribution rule to be as follows:</p><p>“<em>Resource with key </em><strong><em>N</em></strong><em> will be managed by Node with ID </em><strong><em>M</em></strong><em>, where </em><strong><em>M &lt; N</em></strong><em> and M is the biggest ID number in the set</em>”</p><p><strong>[ Note ]</strong> If there is a resource with N=25 and you have 3 Nodes with IDs 10 20 and 30, this particular resource will be managed by the Node with ID M = 20, not 30 because its &gt; 25 and not 10, because 20 exists and is &gt; 10.</p><p>Creating this simple DHT can be seen on Fig. 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRf6G-KtbVAH_RFzFmRntw.png" /><figcaption>Figure 4</figcaption></figure><h4>2. Removing a Node from the network</h4><p>In order to remove a node from the network, first what needs to be decided is where its key is going to be stored after the removal of the node. If we want to remove the node with ID 80, we need to assign its currently stored key [85] to some other node. In this example we will follow a basic rule, that says that <em>when removing a node, all its stored keys shall be assigned to its successor</em>.</p><p><strong>[ Note ]</strong> This rule was arbitrary chosen for this example, there are many other ways to manage key of nodes that are going to be removed in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKvItCprxzLqkUM3jYHTIA.png" /><figcaption>Figure 5</figcaption></figure><p>Therefore, in the process of removing node 80, node 10 will be additionally assigned key 85, hence after the removal of node 80, node 10 will store key 15 and key 85. (Fig. 5)(Fig. 6)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HS4_bWKcU4xu9O2Qsd_4qA.png" /><figcaption>Figure 6</figcaption></figure><h4>3. Adding a Node to the network</h4><p>When a new node wants to join the DHT network, depending on its position relative to who is its successor/predecessor, the node will acquire a different key. In this example, we will bring back the Node with ID 80 inside the DHT network. The constrain that we will use in this example is that, if on leaving, a nodes key was assigned to its <strong>successor</strong>, then when bringing that node inside the network, the new node will acquire a new key from its <strong>predecessor</strong>, relative to its <strong>new position</strong>.</p><p><strong>[ Note ]</strong><em> Here I am </em><strong><em>not</em></strong><em> applying the rule </em>“<em>Resource with key </em><strong><em>N</em></strong><em> will be managed by Node with ID </em><strong><em>M</em></strong><em>, where </em><strong><em>M &lt; N</em></strong><em> and M is the biggest ID number in the set</em>”<em>. If we had to apply this rule, there would be only </em><strong><em>one</em></strong><em> correct position for a node with ID 80</em></p><p>Following the above declared rule, we get 7 possible positions, <em>marked with green</em>, for Node 80. We can observe that relative to the position of the node that needs to be inserted inside the network, the assigned key varies. When Node 80 goes between nodes 70 and 10, it will receive and be responsible for storing key 75; when Node 80 goes between nodes 10 and 20, it will receive and be responsible for <strong>either</strong> key 15 <strong>or</strong> 85. (Fig. 7)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LygPsyd68Ptd4mLwhL4HOg.png" /><figcaption>Figure 7</figcaption></figure><h4>4. Querying the network for a particular resource [<strong>O(n)</strong>]</h4><p>When performing a query for a specific key on the network, the parameter with the greatest wight is “connectivity”. Connectivity here means the number of direct connections a node has to other nodes, i.e. how many successors / predecessors does a given node have.</p><p><strong>[ Note ]</strong> In some cases, the number of predecessors does not signify great importance, simply because the term <em>predecessor</em> is only theoretically used for simplifying the concept of this particular data structure. In reality, a Distributed Hash Table can be implemented with little as a Linked List [Circular Linked List] composed of Node objects that contain fields for ID, Key and a successor pointer. Simply said, the term predecessor would be defined as so: <em>The number of nodes that have their successor pointer pointing to a particular node</em>. <strong>In this case</strong>, in our example each node would have <strong>only</strong> one node pointing to it, therefore only one predecessor. (only node 10 <strong>would be</strong> pointing to node 20, only node 20 <strong>would be</strong> pointing to node 30 …) This is not very practical, because of the fact that the direction in which the query would propagate would always be the same, therefore the complexity of this type of algorithm would stay constant.</p><p>Executing a query on the network, in this example, would have <strong>O(n) </strong>complexity. The reason for this is the following:</p><p>Let us consider that Node 10 would like to obtain the value for key 85. It first needs to locate where that particular resource is stored, i.e. Node 80. Initially Node 10 would query its successor with the theoretical question <em>“Do you have key 85?”</em>. If its successor, in this case Node 20. does not have key 85 it will continue <em>asking</em> this question to its successor and so on until Node 80 gets <em>asked</em>. This process illustrates the <em>forward propagation </em>of the query, shown on Fig 8. as red arrows.</p><p>Once Node 80 receives the query and confirms that it manages key 85, Node 80 would return the message to its caller. Namely, the query would propagate backwards to the initial node that sent it — Node 10.</p><p>Because we are traversing <strong>linearly</strong> through the whole network in both directions, the complexity of this implementation of a DHT is <strong>O(n)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30fTJXMdWF-9vaNKhv3IDQ.png" /><figcaption>Fig 8</figcaption></figure><h4>5. Querying the network for a particular resource [<strong>O(logN)</strong>]</h4><p>We saw in section for, that querying a network with linear architecture implementation has a significantly large complexity — O(n). In order to reduce this complexity we can add additional <em>links</em> / <em>shortcuts</em> to other nodes. Basically, a node would have an additional pointer named <em>shortcut</em> that would point to another, much more distant node. In our example, each node will have a shortcut to the <em>(i+3)th</em> node. (Node 10 would have a shortcut pointing to Node 40, Node 20 would have a shortcut pointing to Node 50 etc.) The shortcut implementation of this architecture is shown on Figure 9. The yellow lines represent shortcuts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tnmkE79XWnJJ34bKVQwrQ.png" /><figcaption>Figure 9</figcaption></figure><p>Executing a query on the network, in this example, would have <strong>O(logN) </strong>complexity. The reason for this is the following:</p><p>Let us consider that Node 10 again would like to obtain the value for key 85. It first needs to locate where that particular resource is stored, i.e. Node 80. Now, depending on the specific implementation of this algorithm <strong>( </strong><a href="https://en.wikipedia.org/wiki/Chord_(peer-to-peer)"><strong>Chord</strong></a><strong> )</strong>,the query would propagate in a different way.</p><p>However, in this example for the means of simplicity, we will say that <em>the querying node would propagate through its shortcut, </em><strong><em>if and only if</em></strong><em> its successor does not have a direct connection to the node that contains the key that is being queried.</em></p><p>Namely, if Node 20 was directly connected to Node 80, then Node 10 would receive its information through Node 20. If Node 20 does <strong>not</strong> have a direct connection to Node 80, then Node 10 sends the query to propagate through Node 40 [its <strong>shortcut</strong>]</p><p>The query propagation process in this example would look like this. Node 10 sends an initial query asking<em> “Do you have key 85?”</em> to Node 20. Node 20 asks its successor, Node 30; Node 30 does not have key 85, therefore responds to Node 20 with this information; Node 20 tells Node 10 that none of its successors are responsible for key 85; Node 10 sends the query to its shortcut, Node 40; The same process is repeated for Node 40, until eventually the query ends up at Node 70, which is directly connected to Node 85, which is responsible for key 85. This process is illustrated using <strong>red</strong> arrows on Figure 10. After the node responsible for key 85 has been found the response travels back to Node 10 via the same route it took initially. The response rout is illustrated on Figure 10 using <strong>green</strong> arrows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmmMu22ntNEfY5xgzs1opw.png" /><figcaption>Figure 10</figcaption></figure><p>Because we are <strong>not</strong> traversing <strong>linearly</strong> through the whole network in both directions, the complexity of this implementation of a DHT is <strong>O(logN)</strong>. Please, review the <a href="https://en.wikipedia.org/wiki/Chord_(peer-to-peer)"><strong>Chord algorithm</strong></a> for a detailed explanation of this implementation.</p><h3>Software applications that use DHT</h3><h4><strong>Ethereum</strong></h4><p><strong>Ethereum</strong> is a decentralized, open-source blockchain with smart contract functionality. <strong>Ether</strong> is the native cryptocurrency of the platform. Amongst cryptocurrencies, <strong>Ether</strong> is second only to Bitcoin in market capitalization. The node discovery protocol in the Ethereum blockchain network stack is based on a slightly modified implementation of Kademlia (DHT).</p><h4>I2P</h4><p>The <strong>Invisible Internet Project</strong> (<strong>I2P</strong>) is an anonymous network layer that allows for censorship-resistant, peer-to-peer communication. Anonymous connections are achieved by encrypting the user’s traffic, and sending it through a volunteer-run network of roughly 55,000 computers distributed around the world. Given the high number of possible paths the traffic can transit, a third party watching a full connection is unlikely. The software that implements this layer is called an “I2P router”, and a computer running I2P is called an “I2P node”. I2P is free and open sourced, and is published under multiple licenses.</p><h4>The Tox protocol</h4><p><strong>Tox </strong>(protocol) is a peer-to-peer instant-messaging and video-calling protocol that offers end-to-end encryption, based on DHT. The stated goal of the project is to provide secure yet easily accessible communication for everyone.</p><h4><strong>Oracle Coherence</strong></h4><p><strong>Oracle Coherence</strong> is a Java-based distributed cache and in-memory data grid, intended for systems that require high availability, high scalability and low latency, particularly in cases that traditional relational database management systems provide insufficient throughput, or insufficient performance.</p><h4>Freenet</h4><p><strong>Freenet</strong> is a peer-to-peer platform for censorship-resistant, anonymous communication. It uses a decentralized distributed data store to keep and deliver information, and has a suite of free software for publishing and communicating on the Web without fear of censorship.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=febfd01fc0af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-code-vault/data-structures-distributed-hash-table-febfd01fc0af">[Data Structures] Distributed hash table</a> was originally published in <a href="https://medium.com/the-code-vault">The Code Vault</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Privacy] Web browser user agents]]></title>
            <link>https://medium.com/the-code-vault/privacy-web-browser-user-agents-b4e9fd38a0d0?source=rss-31325f5591db------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4e9fd38a0d0</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[web-browser]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Teo Parashkevov]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 15:15:27 GMT</pubDate>
            <atom:updated>2021-11-01T18:22:28.097Z</atom:updated>
            <content:encoded><![CDATA[<p>How to anonymize yourself on the web using the <strong>user agent</strong> setting</p><h3>Introduction</h3><p>It is clear that in recent years a substantial amount of companies have changed their business models of operation to a more web-centric way of marketing and providing products and services. This, unsurprisingly, has led to an increase in the amount of user/customer data that needs to be aggregated in order to provide a more wholesome service. Therefore, much of today&#39;s web architecture relies on gathering statistical data from the users end-point device.</p><p>Web browsers were the earliest pieces of software to encounter this type of change. Actually, even before companies started to gather statistical user data, web browsers were sending all kinds of end-point device information. The user agent string is part of the Header that a browser may include when initializing a connection to a particular server. The reason being, “back in the day” when browsers did not agree upon a specific interpretation of a particular file/webpage/multi media file etc. , the server had to send a specific web page architecture that corresponded with the way that particular browser was going to interpret it.</p><p>The reason for having user agent information in the request of each connection header was valid for that particular time period. Nevertheless, nowadays most browsers “agree” on almost everything, however the user agent information is still being sent. Yet its purpose has expanded to a field closer to statistics rather than computer science.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvTTngGY79VwCQd-rvk6Zw.png" /></figure><p>In this article I will try to focus the readers attention towards one of modern web browsers privacy problems that we all face in this day an age, that is web browser user agents. I will give specific advice regarding static and dynamic change of web browser user agents and also some additional advice for a safer web browsing experience.</p><h3>What is a web browser user agent ?</h3><h4><a href="https://developer.mozilla.org/en-US/docs/Glossary/User_agent"><strong>Mozilla MDN Web Documentations</strong></a><strong>:</strong></h4><p><strong><em>A user agent is a computer program representing a person</em></strong><em>, for example, a </em><strong><em>browser</em></strong><em> in a Web context. Besides a browser, a user agent could be a </em><strong><em>bot</em></strong><em> scraping webpages, a </em><strong><em>download manager</em></strong><em>, or </em><strong><em>another app</em></strong><em> accessing the Web. Along with each request they make to the server, browsers include a self-identifying </em><em>User-Agent HTTP header called a user agent (UA) string. This string often identifies the browser, its version number, and its host operating system.</em></p><p><em>Spam bots, download managers, and some browsers often send a fake UA string to announce themselves as a different client. This is known as user agent spoofing.</em></p><p><em>The user agent string can be accessed with JavaScript on the client side using the </em><em>NavigatorID.userAgent property.</em></p><h4><a href="https://en.wikipedia.org/wiki/User_agent"><strong>Wikipedia</strong></a>:</h4><p><em>In </em><a href="https://en.wikipedia.org/wiki/Computing"><em>computing</em></a><em>, a </em><strong><em>user agent</em></strong><em> is any software, acting on behalf of a </em><a href="https://en.wikipedia.org/wiki/User_(computing)"><em>user</em></a><em>, which “retrieves, renders and facilitates end-user interaction with Web content”. A user agent is therefore a special kind of </em><a href="https://en.wikipedia.org/wiki/Software_agent"><em>software agent</em></a><em>.</em></p><p><em>Some prominent examples of user agents are </em><a href="https://en.wikipedia.org/wiki/Web_browsers"><em>web browsers</em></a><em> and </em><a href="https://en.wikipedia.org/wiki/Email_client"><em>email readers</em></a><em>. Often, a user agent acts as the </em><a href="https://en.wikipedia.org/wiki/Client_(computing)"><em>client</em></a><em> in a </em><a href="https://en.wikipedia.org/wiki/Client%E2%80%93server_model"><em>client–server system</em></a><em>. In some contexts, such as within the </em><a href="https://en.wikipedia.org/wiki/Session_Initiation_Protocol"><em>Session Initiation Protocol</em></a><em> (SIP), the term user agent refers to both end points of a communications session.</em></p><h4>Examples</h4><p><strong>Example 1</strong>:</p><pre><em>Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0</em></pre><p><strong>Example 2</strong>:</p><pre>Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0</pre><p><strong>Example 3</strong>:</p><pre>Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15</pre><h4>User agent string structure</h4><pre>&lt;Browser software name&gt; (&lt;Operating System&gt; &lt;version&gt;; &lt;x86/x64 system&gt;; &lt;other system info&gt;) &lt;layout engine&gt; / &lt;layout engine version&gt; &lt;Browser software full name&gt; &lt;Browser software full version&gt;</pre><h3>The advantages/disadvantages of changing the user agent</h3><h4>Advantages</h4><ol><li>Gives a certain degree of protection against target specific malware</li><li>Confuses tracking algorithms, therefore increasing the degree of web anonymity</li><li>Randomizing user agents on every webpage you visit drastically reduce the chances of a hacker attack.</li></ol><h4>Disadvantages</h4><ol><li>Reduces the quality of product advertisement relevance to a certain degree</li><li>May lead to unrelated search, product suggestions.</li></ol><h4>Check your user agent @ <a href="https://developers.whatismybrowser.com/">https://developers.whatismybrowser.com/</a></h4><p><a href="https://developers.whatismybrowser.com/">User Agents - Parser and API - Easily decode any user agent</a></p><h3>Mozilla Firefox</h3><p>Setting the user agent globally involves the setup of the <strong>general.useragent.override</strong> variable in the <strong>about:config</strong> preference panel. Type <strong>about:config &gt; (accept the risk) &gt; search for general.useragent.override. </strong>Then change the user agent string to the desired user agent.</p><p>Setting <strong>general.useragent.override </strong>string to the desired user agent string and restarting Firefox is the whole process of changing the user agent.</p><p>A useful add-on: <a href="https://addons.mozilla.org/en-US/firefox/addon/uaswitcher/">User-Agent-Switcher</a></p><p><a href="https://addons.mozilla.org/en-US/firefox/addon/uaswitcher/">User-Agent Switcher - Get this Extension for 🦊 Firefox (en-US)</a></p><p>(<a href="https://support.mozilla.org/en-US/kb/how-reset-default-user-agent-firefox">How-to guide</a>)</p><h3>Google Chrome</h3><p>Setting the user agent globally involves the setup of the <strong>useragent </strong>string variable. Open <strong>DevTools &gt; (Show Network conditions) &gt; Network conditions &gt; User agent. </strong>Then choosing the desired user agent. If the desired user agent is not listed, you can choose “custom” and specify the user agent string.</p><p>Setting <strong>useragent </strong>string to the desired user agent string and restarting Chrome is the whole process of changing the user agent.</p><p>A useful add-on: <a href="https://chrome.google.com/webstore/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=en">User-Agent-Switcher</a></p><p><a href="https://chrome.google.com/webstore/detail/user-agent-switcher-and-m/bhchdcejhohfmigjafbampogmaanbfkg?hl=en">User-Agent Switcher and Manager</a></p><p>(<a href="https://developer.chrome.com/docs/devtools/device-mode/override-user-agent/">How-to guide</a>)</p><h3>Microsoft Edge</h3><p>Setting the user agent globally involves the setup of the <strong>useragent </strong>string variable. Open <strong>DevTools &gt; (Show Network conditions) &gt; Network conditions &gt; User agent. </strong>Then choosing the desired user agent. If the desired user agent is not listed, you can choose “custom” and specify the user agent string.</p><p>Setting <strong>useragent </strong>string to the desired user agent string and restarting Edge is the whole process of changing the user agent.</p><p><a href="https://microsoftedge.microsoft.com/addons/detail/useragent-switcher/npjnioaeoicmjokbdpfiecnbildopjad">Microsoft Edge Addons</a></p><p>A useful add-on: <a href="https://microsoftedge.microsoft.com/addons/detail/useragent-switcher/npjnioaeoicmjokbdpfiecnbildopjad">User-Agent-Switcher</a></p><p>(<a href="https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/device-mode/override-user-agent">How-to guide</a>)</p><h3>Opera</h3><p>Specifying user agent for Opera requires opening the <strong>opera.dll </strong>file with a HEX editor and changing the hard coded user agent string. This DLL file can be located inside the opera profile path. If you do not know where this directory is on your OS, go to opera:about in Opera and scroll down to Profile section. Another workaround is to enable <em>“Reduce User-Agent request header”</em> flag, from opera:flags</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Ke4fjxLG4AlBEEgjHX87Fw.png" /></figure><p>Creating a specific user agent for a specific website is also an option not only for Opera, but for all other web browsers. Here are the steps that need to be performed on Opera, in order to accomplish this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*0aw1zNVhar3z9jurUnezAQ.png" /></figure><p>A useful add-on: <a href="https://addons.opera.com/en/extensions/details/user-agent-switcher-5/">User-Agent-Switcher</a></p><p><a href="https://addons.opera.com/en/extensions/details/user-agent-switcher-5/">User-Agent Switcher</a></p><h3>Apple Safari</h3><p>Setting the user agent globally involves going in the menu bar and selecting <strong>Develop &gt; User Agent</strong>, then choosing the desired user agent. If the desired user agent is not listed, you can choose “<em>other</em>” and specify the user agent string.</p><p><em>To enable Develop menu tab go to </em><strong><em>Preferences &gt; Advanced &gt; Enable Develop menu in bar</em></strong><em>.</em></p><p>Setting <strong>useragent </strong>string to the desired user agent string and restarting Safari is the whole process of changing the user agent.</p><h3>Suckless Surf</h3><p>As all suckless utilities, surf has command line arguments for all its parameters. The one corresponding to the user agent is -u . If you need a randomized user agent on each instance of Surf, you can use the environment variable SURF_USERAGENT. Surf uses this environment variable if the -u is not specified.</p><h3>Additional advice</h3><p>Usually, if the browser executable is being called from the command line. You can specify the user agent using your browser executable specific option for user agent.</p><p>Example:</p><pre>user@hostname: surf -u &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15&quot;</pre><p>Example:</p><pre>C:\Program Files\Opera\launcher.exe --user-agent=&quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36&quot;</pre><p>In addition you can write a simple script/program to randomize user agents from a given list inside a file. However, most of the add-ons i have listed support this randomization capability, therefore you can either do it for fun or write something even better than what the add-ons provide. 😃</p><h3>Conclusion</h3><p>Changing the browser user agent is not an universal remedy for online privacy protection. Yet, it is one simple step that can be accomplished without the need for specialized knowledge on the users side.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4e9fd38a0d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-code-vault/privacy-web-browser-user-agents-b4e9fd38a0d0">[Privacy] Web browser user agents</a> was originally published in <a href="https://medium.com/the-code-vault">The Code Vault</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>