<?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 Badal Panwar on Medium]]></title>
        <description><![CDATA[Stories by Badal Panwar on Medium]]></description>
        <link>https://medium.com/@badalpanwar007?source=rss-ee21d63c9b1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*t91mGDw7s_xhT3Ub</url>
            <title>Stories by Badal Panwar on Medium</title>
            <link>https://medium.com/@badalpanwar007?source=rss-ee21d63c9b1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:41:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@badalpanwar007/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[From Embeddings to Insights: How Vector Databases Transform Data]]></title>
            <link>https://medium.com/@badalpanwar007/from-embeddings-to-insights-how-vector-databases-transform-data-fd38c0221eee?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd38c0221eee</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 05:09:15 GMT</pubDate>
            <atom:updated>2025-08-25T15:31:55.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a vector</h3><p>In mathematics, a <strong>vector</strong> is an ordered list of numbers that represent a point or a direction in space. For example, [3, 4] describes a point on a 2D graph, while [2, 5, 7] describes a point in 3D space. Each number is called a <strong>dimension</strong>, and together they form coordinates.</p><p>In Artificial Intelligence, we use the same idea, but instead of representing positions in physical space, vectors represent the <strong>meaning of data</strong>. A model takes something like text, an image, or audio and converts it into a high-dimensional vector called an <strong>embedding</strong>. For instance, the sentence <em>“I love code”</em> might become [0.21, -0.34, 0.56, …]. These numbers don’t look meaningful to us, but in this mathematical space, they carry deep semantic information.</p><h3>Vector Database</h3><p>A Vector Database is a special type of database designed to store, index, and search vectors (embeddings) efficiently. While traditional databases (SQL or NoSQL) are great at storing structured data like numbers, strings, and documents, they are not optimized to handle high-dimensional vectors that represent meaning.</p><blockquote>For Example:</blockquote><blockquote>SQL/NoSQL search → WHERE title = ‘Inception’ → exact match.</blockquote><blockquote>Vector DB search → “find movies similar to Inception” → compares vector embeddings of movies to return results like Interstellar or The Matrix.</blockquote><h3><strong>Embeddings</strong></h3><p>An embedding is a numerical representation of data (text, image, audio, video) in the form of a vector. Instead of raw words or pixels, embeddings capture the meaning and context of data so machines can compare them mathematically.</p><p>Embeddings are generated by passing raw data (like text, image, or audio) through a <strong>neural network model</strong> that has been trained on massive datasets.</p><p>For text, words are first <strong>tokenized</strong> into smaller units, then mapped into vectors using an embedding layer. These token vectors are processed through <strong>transformer layers</strong> that capture context and meaning, finally producing a fixed-size vector that represents the whole sentence or document.</p><p>For images, models like <strong>CLIP</strong> use convolutional or vision transformer networks to extract features (shapes, colors, objects) and output a vector.</p><p>For audio, spectrograms are analyzed by deep networks to capture sound patterns in vector form.</p><pre># pip install sentence-transformers<br>from sentence_transformers import SentenceTransformer, util<br><br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br>sentences = [<br>     &quot;Artificial Intelligence is transforming healthcare&quot;,<br>    &quot;Machine learning improves medical image analysis&quot;,<br>    &quot;AI in medical diagnosis&quot;,<br>    &quot;The stock market fluctuates daily&quot;,<br>    &quot;Investors track financial news closely&quot;,<br>    &quot;Hospitals use AI for patient care&quot;<br>]<br><br>embeddings = model.encode(sentences, convert_to_tensor=True)<br>print(embeddings)</pre><p>returns</p><pre># output<br>tensor([[ 0.0349,  0.0413,  0.0496,  ..., -0.0234,  0.0769, -0.0330],<br>        [ 0.0131,  0.0740,  0.1067,  ..., -0.0077, -0.0087, -0.0432],<br>        [ 0.0128,  0.0055,  0.0026,  ...,  0.0745,  0.0242, -0.0446],<br>        [ 0.0508, -0.0394,  0.0619,  ..., -0.0555, -0.0443,  0.0263],<br>        [ 0.0906, -0.0321, -0.0556,  ..., -0.0509, -0.0005,  0.0636],<br>        [-0.0250,  0.0113, -0.0102,  ...,  0.0730,  0.0562, -0.0632]])</pre><h3>Similarity Search in Vector Databases</h3><p>Once data (text, images, audio) is converted into <strong>embeddings (vectors)</strong>, the next step is finding <strong>how close or similar</strong> two vectors are. This is called a <strong>similarity search</strong>. Unlike SQL, where we use = or LIKE for exact matches, vector databases use <strong>mathematical distance metrics</strong>.</p><h4>Common Similarity Measures</h4><p><strong>Cosine Similarity</strong></p><ul><li>Measures the <strong>angle</strong> between two vectors.</li><li>Range: -1 to 1 → higher means more similar.</li><li>Best when the <strong>magnitude doesn’t matter</strong>, only the <strong>direction (meaning)</strong>.</li></ul><pre>query = &quot;AI in medical diagnosis&quot;<br><br># Generate embedding for query<br>query_embedding = model.encode(query, convert_to_tensor=True)<br><br># Perform similarity search<br>cosine_scores = util.cos_sim(query_embedding, embeddings)<br><br>for idx, score in enumerate(cosine_scores[0]):<br>    print(f&quot;{sentences[idx]} -&gt; Similarity: {score.item():.4f}&quot;)</pre><pre>Artificial Intelligence is transforming healthcare -&gt; Similarity: 0.6269<br>Machine learning improves medical image analysis -&gt; Similarity: 0.4423<br>AI in medical diagnosis -&gt; Similarity: 1.0000<br>The stock market fluctuates daily -&gt; Similarity: 0.0464<br>Investors track financial news closely -&gt; Similarity: 0.0802<br>Hospitals use AI for patient care -&gt; Similarity: 0.7147</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*IBlc_9XJ5dlYoIryBTXrJg.png" /></figure><p><strong>Euclidean Distance</strong></p><ul><li>Measures the <strong>straight-line distance</strong> between two vectors in space.</li><li>Smaller distance = more similar.</li><li>Example: Comparing two face embeddings for facial recognition.</li></ul><p><strong>Dot Product</strong></p><ul><li>Measures how much one vector <strong>aligns</strong> with another.</li><li>Higher dot product = stronger similarity.</li><li>Often used in recommendation systems &amp; attention mechanisms.</li></ul><h3>How Vector Databases Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*srhPk_9nh9vkPidk8jL8kA.png" /></figure><p>Data Ingestion: Raw data, such as text documents, images, or audio files, is collected and prepared for processing. Each item can include metadata like IDs, labels, or categories that help identify or filter it later.</p><p>Vectorization: The raw data is passed through an embedding model to convert it into a high-dimensional numerical vector. These embeddings capture the semantic meaning of the data in a format suitable for similarity comparisons.</p><p>Storage in Vector Database: The generated vectors, along with their associated metadata, are stored in a vector database collection. This ensures persistence, easy retrieval, and association between the original data and its embedding.</p><p>The code below creates a collection and generates embeddings, and stores them in QDrant.</p><pre>docker run -p 6333:6333 qdrant/qdrant</pre><pre>pip install qdrant-client sentence-transformers numpy</pre><pre>from qdrant_client import QdrantClient<br>from qdrant_client.models import Distance, VectorParams, PointStruct<br>from sentence_transformers import SentenceTransformer<br><br>model = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br><br>client = QdrantClient(host=&quot;localhost&quot;, port=6333)<br><br>collection_name = &quot;docs&quot;<br><br>sample_documents = [<br>    {<br>        &quot;text&quot;: &quot;Advanced machine learning techniques for natural language processing including transformer architectures, attention mechanisms, and large language models like BERT, GPT, and T5 for text classification and sentiment analysis.&quot;,<br>        &quot;category&quot;: &quot;artificial_intelligence&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Sustainable urban planning with green infrastructure and smart city solutions focusing on renewable energy integration, smart transportation systems, and circular economy principles in Copenhagen and Singapore.&quot;,<br>        &quot;category&quot;: &quot;environmental_science&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Quantum computing applications in cryptography and cybersecurity using Shor&#39;s algorithm and Grover&#39;s algorithm for breaking classical encryption and developing post-quantum cryptography standards.&quot;,<br>        &quot;category&quot;: &quot;computer_science&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Personalized medicine combining genomics and AI for precision healthcare delivery including pharmacogenomics, biomarker discovery, and precision oncology treatments at leading medical institutions.&quot;,<br>        &quot;category&quot;: &quot;medical_research&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Climate change economics analyzing carbon markets, green finance, and transition risks through carbon pricing mechanisms, green bonds, and sustainable finance taxonomy frameworks.&quot;,<br>        &quot;category&quot;: &quot;economics&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Neural interface technology and brain-computer interfaces for treating neurological disorders including invasive and non-invasive BCI approaches, signal processing, and machine learning for neural decoding.&quot;,<br>        &quot;category&quot;: &quot;biomedical_engineering&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Renewable energy storage solutions with advanced battery technologies including lithium-ion, solid-state, flow batteries, and grid-scale deployment for smart grid integration and energy management.&quot;,<br>        &quot;category&quot;: &quot;energy_engineering&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Space exploration technologies for Mars colonization including nuclear propulsion, life support systems, radiation shielding, and in-situ resource utilization for deep space missions and asteroid mining.&quot;,<br>        &quot;category&quot;: &quot;aerospace_engineering&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Artificial neural networks and deep learning algorithms for image recognition, computer vision, and autonomous driving systems using convolutional neural networks and recurrent neural networks.&quot;,<br>        &quot;category&quot;: &quot;artificial_intelligence&quot;<br>    },<br>    {<br>        &quot;text&quot;: &quot;Blockchain technology and cryptocurrency systems for decentralized finance including smart contracts, consensus mechanisms, and distributed ledger applications in financial services.&quot;,<br>        &quot;category&quot;: &quot;computer_science&quot;<br>    }<br>]<br><br>def create_collection():<br>    &quot;&quot;&quot;Create a new collection with proper vector configuration for SentenceTransformer&quot;&quot;&quot;<br>    try:<br>        client.create_collection(<br>            collection_name=collection_name,<br>            vectors_config=VectorParams(size=384, distance=Distance.COSINE)<br>        )<br>        print(f&quot;Collection &#39;{collection_name}&#39; created successfully!&quot;)<br>    except Exception as e:<br>        print(f&quot;Collection might already exist: {e}&quot;)<br><br>def save_simple_documents():<br>    &quot;&quot;&quot;Save simple document data to Qdrant using SentenceTransformer embeddings&quot;&quot;&quot;<br>    points = []<br>    <br>    for i, doc in enumerate(sample_documents, 1):<br>        # Generate embedding using SentenceTransformer<br>        embedding = model.encode(doc[&#39;text&#39;]).tolist()<br>        <br>        point = PointStruct(<br>            id=i,<br>            vector=embedding,<br>            payload={<br>                &quot;text&quot;: doc[&#39;text&#39;],<br>                &quot;category&quot;: doc[&#39;category&#39;]<br>            }<br>        )<br>        points.append(point)<br>    <br>    operation_info = client.upsert(<br>        collection_name=collection_name,<br>        points=points<br>    )<br>    print(f&quot;Saved {len(points)} documents with SentenceTransformer embeddings&quot;)<br>    print(f&quot;Operation status: {operation_info}&quot;)<br><br>print(&quot;\n📁 Creating collection...&quot;)<br>create_collection()<br><br>print(&quot;\n💾 Saving documents with SentenceTransformer embeddings...&quot;)<br>save_simple_documents()</pre><pre>📁 Creating collection...<br>Collection &#39;docs&#39; created successfully!<br><br>💾 Saving documents with SentenceTransformer embeddings...<br>Saved 10 documents with SentenceTransformer embeddings<br>Operation status: operation_id=0 status=&lt;UpdateStatus.COMPLETED: &#39;completed&#39;&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fczsyvNvB3iDkx3jvvgmnA.png" /></figure><p>Indexing: After storing the vectors, the database builds an index (HNSW in Qdrant) to organize the vectors efficiently. Indexing allows the database to perform fast nearest neighbor searches instead of scanning all vectors sequentially.</p><p>Query Processing: When a user submits a query (text, image, or other), it is vectorized using the same embedding model. The resulting query vector represents the semantic meaning of the input in the same high-dimensional space as the stored vectors.</p><p>Retrieval Mechanism: The database performs a similarity search using the query vector against the indexed vectors. It calculates distances (cosine similarity, Euclidean distance, or dot product) to find the most relevant top-k results. Filters can also be applied based on metadata to narrow the search to specific categories.</p><pre>def search_by_text(query_text, limit=3):<br>    &quot;&quot;&quot;Search documents by semantic similarity using SentenceTransformer&quot;&quot;&quot;<br>    # Generate query embedding<br>    query_vector = model.encode(query_text).tolist()<br>    <br>    search_result = client.search(<br>        collection_name=collection_name,<br>        query_vector=query_vector,<br>        limit=limit,<br>        with_payload=True<br>    )<br>    <br>    print(f&quot;\n=== Search Results for: &#39;{query_text}&#39; ===&quot;)<br>    for i, result in enumerate(search_result, 1):<br>        payload = result.payload<br>        print(f&quot;\n{i}. Similarity Score: {result.score:.4f}&quot;)<br>        print(f&quot;Category: {payload.get(&#39;category&#39;, &#39;N/A&#39;)}&quot;)<br>        print(f&quot;Text: {payload.get(&#39;text&#39;, &#39;N/A&#39;)[:150]}...&quot;)<br>        print(&quot;-&quot; * 60)<br>    <br>    return search_result<br><br>print(&quot;\n🔍 Semantic search for AI and machine learning...&quot;)<br>search_by_text(&quot;artificial intelligence and deep learning models&quot;, limit=3)<br><br>print(&quot;\n🔍 Semantic search for renewable energy...&quot;)<br>search_by_text(&quot;clean energy and solar power systems&quot;, limit=2)</pre><pre><br>🔍 Semantic search for AI and machine learning...<br><br>=== Search Results for: &#39;artificial intelligence and deep learning models&#39;<br><br>1. Similarity Score: 0.5846<br>Category: artificial_intelligence<br>Text: Artificial neural networks and deep learning algorithms for image recognition, computer vision, and autonomous driving systems using convolutional neu...<br>------------------------------------------------------------<br><br>2. Similarity Score: 0.3723<br>Category: artificial_intelligence<br>Text: Advanced machine learning techniques for natural language processing including transformer architectures, attention mechanisms, and large language mod...<br>------------------------------------------------------------<br><br>3. Similarity Score: 0.2145<br>Category: biomedical_engineering<br>Text: Neural interface technology and brain-computer interfaces for treating neurological disorders including invasive and non-invasive BCI approaches, sign...<br>------------------------------------------------------------<br><br>🔍 Semantic search for renewable energy...<br><br>=== Search Results for: &#39;clean energy and solar power systems&#39;<br><br>1. Similarity Score: 0.4119<br>Category: energy_engineering<br>Text: Renewable energy storage solutions with advanced battery technologies including lithium-ion, solid-state, flow batteries, and grid-scale deployment fo...<br>------------------------------------------------------------<br><br>2. Similarity Score: 0.3358<br>Category: environmental_science<br>Text: Sustainable urban planning with green infrastructure and smart city solutions focusing on renewable energy integration, smart transportation systems, ...<br>------------------------------------------------------------</pre><h3>Use Cases and Applications</h3><ul><li><strong>Recommendation Systems</strong>: Vector databases enable personalized recommendations by storing and querying user or item embeddings to find similar items, like suggesting products or content based on user preferences in platforms like Netflix or Amazon.</li><li><strong>Natural Language Processing (e.g., Semantic Search, Chatbots)</strong>: They power semantic search by matching queries to relevant documents based on meaning, not just keywords, and enhance chatbots by retrieving contextually similar responses for more natural conversations.</li><li><strong>Image and Video Retrieval</strong>: Vector databases store embeddings of images or videos, enabling fast similarity searches for applications like reverse image search or video content recommendation on platforms like YouTube.</li><li><strong>Anomaly Detection and Fraud Prevention</strong>: By identifying outliers in high-dimensional data, vector databases help detect unusual patterns, such as fraudulent transactions in banking or network intrusions in cybersecurity.</li><li><strong>E-commerce Product Search and Personalization</strong>: Beyond recommendations, vector databases enhance product search by matching user queries to visually or semantically similar products and personalizing shopping experiences based on user behavior.</li><li><strong>Healthcare and Medical Research</strong>: They support matching patient records, medical images (e.g., X-rays, MRIs), or genomic data for diagnosis, treatment planning, or drug discovery by finding similar cases or patterns.</li><li><strong>Finance and Risk Analysis</strong>: Vector databases improve risk assessment by analyzing patterns in financial data and enhance fraud detection through similarity-based clustering of transaction behaviors.</li><li><strong>Content Moderation and Safety</strong>: They enable the detection of harmful or inappropriate content (e.g., text, images) by comparing new content against known examples of flagged material, used in social media platforms.</li><li><strong>Knowledge Management and Enterprise Search</strong>: Vector databases power enterprise search systems by retrieving relevant documents, reports, or internal knowledge bases based on semantic similarity, improving workplace efficiency.</li></ul><h3>Popular Vector Database Solutions</h3><ul><li><strong>Pinecone</strong>: A managed cloud-native vector database optimized for scalability and real-time similarity search, ideal for AI-driven applications.</li><li><strong>Milvus</strong>: An open-source vector database designed for massive-scale similarity search, supporting diverse data types and AI models.</li><li><strong>Weaviate</strong>: An open-source database with built-in machine learning and semantic search capabilities, emphasizing ease of use and modularity.</li><li><strong>Faiss</strong>: An open-source library by Meta AI for efficient similarity search and clustering, optimized for high-dimensional vectors but requires more setup.</li></ul><p>Open-source vector database solutions like Milvus, Weaviate, and Faiss provide flexibility and cost efficiency but demand hands-on infrastructure management. On the other hand, managed services such as Pinecone offer simplicity, seamless scalability, and hassle-free maintenance, though they come with subscription costs. Pinecone shines with its user-friendly interface and smooth cloud integration. Milvus excels at handling massive datasets. Weaviate specializes in semantic search with a modular approach, and Faiss is lightweight and highly customizable, making it ideal for research and experimentation.</p><h3>Conclusion</h3><p>Vector databases are revolutionizing how we use unstructured data, powering everything from smart recommendations to AI-driven research. With platforms like Pinecone, Milvus, Weaviate, and Faiss, finding similar data is faster and smarter than ever. While challenges exist, these databases make high-dimensional searches effortless and open the door to creative AI applications. Simply put, vector databases are the secret sauce making AI more powerful, efficient, and downright fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd38c0221eee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Reliable Data Backup Workflow using Python and Linux]]></title>
            <link>https://medium.com/@badalpanwar007/creating-a-reliable-data-backup-workflow-using-python-and-linux-bfdbbac878ee?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfdbbac878ee</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[backup]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 15:21:57 GMT</pubDate>
            <atom:updated>2023-06-24T15:21:57.541Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital age, the value of data cannot be overstated, and safeguarding it against loss or corruption is of utmost importance. One highly effective method for ensuring data protection is by creating backups, and Google Drive emerges as a reliable and convenient cloud storage solution for this purpose. In this guide, we will delve into the process of automating data backup to Google Drive using Python and shell scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*-CVxGu5KJD1HhY5a3Qv3kw.png" /></figure><p>To automate backup, you can consider the following prerequisites:</p><ol><li>Obtain the necessary OAuth credentials from Google Cloud.</li><li>A Python script that uses PyDrive to backup your files.</li><li>A shell script to run your Python file and create logs.</li><li>A .desktop file to provide a shortcut or launcher for your shell script.</li></ol><h3>Creating OAuth credentials</h3><p>To authenticate our Google account whenever we want to upload data, we need to create an <a href="https://en.wikipedia.org/wiki/OAuth">OAuth</a> credential.</p><p>To create your OAuth credentials. Go to your <a href="https://console.cloud.google.com/">Google Cloud</a> and create a project and generate your credentials.</p><p>After creating your credentials, you would end up with a file named cl<em>ient_secret_(ID).json</em>.</p><h3>Python Script</h3><p>Create a Python environment. Install PyDrive in it.</p><pre>pip install PyDrive</pre><p>Create a Python file. Rename the cl<em>ient_secret_(ID).json file </em>to<em> </em>cl<em>ient_secret.json </em>and it to the same directory as the main python file.</p><pre>from pydrive.drive import GoogleDrive<br>from pydrive.auth import GoogleAuth<br>import os<br>  <br>gauth = GoogleAuth() # Google Authentication<br>gauth.LoadCredentialsFile(&quot;mycreds.txt&quot;) # access local saved oauth credentials.<br><br>if gauth.credentials is None:<br>    # Authenticate if they&#39;re not there using browser<br>    gauth.LocalWebserverAuth()<br>elif gauth.access_token_expired:<br>    # Refresh them if expired<br>    gauth.Refresh()<br>else:<br>    # Initialize the saved creds<br>    gauth.Authorize()<br><br># Save the current credentials to a file<br>gauth.SaveCredentialsFile(&quot;mycreds.txt&quot;)<br><br>drive = GoogleDrive(gauth)<br> <br>path = r&quot;/home/badal/Desktop/upload&quot;   <br>   <br>file_list = drive.ListFile({&#39;q&#39;:&quot;trashed=false&quot;}).GetList()<br>file_list = [i[&#39;title&#39;] for i in file_list]<br><br>for x in os.listdir(path):<br>    folders = drive.ListFile({&#39;q&#39;: &quot;title=&#39;&quot; + x + &quot;&#39; and mimeType=&#39;application/vnd.google-apps.folder&#39; and trashed=false&quot;}).GetList()<br>    path_in = f&quot;/home/badal/Desktop/upload/{x}&quot;<br><br>    for files in os.listdir(path_in):<br>        try:<br>            if not files in file_list: # check file existence in drive<br>                print(f&quot;Uploading =&gt; {files}&quot;)<br>                file2 = drive.CreateFile({&#39;title&#39;:files,&#39;parents&#39;: [{&#39;id&#39;: folders[0][&#39;id&#39;]}]})<br>                file2.SetContentFile(os.path.join(path_in, files))<br>                file2.Upload()<br>            else:<br>                print(f&quot;Already exists =&gt; {files}&quot;)<br>        except:<br>            continue</pre><p><strong>Explanation</strong></p><ol><li>Import the necessary modules.</li><li>Use GoogleAuth() to authenticate.</li><li>Pydrive saves a local credentials file in your working directory. Initially, credentials are not saved. The first time you run the script, you’ll need to enter a verification code via your web browser. It will save the creds into your creds.txt. The second time, it will use the credentials saved in creds.txt.</li><li>Pass your auth to GoogleDrive.</li><li>Add your folder path that needs to be updated. Here I have a folder upload with 3 sub-directories containing various files. Add all the sub-directories to google drive with the same name using the google drive interface or you can use CreateFile to create your folders.</li><li>Check all the files present on your drive to avoid duplicacy.</li><li>Get all the subdirectories. Find the same name folders in GoogleDrive.</li><li>Get all the files in one sub-directory and upload them using CreateFile. Here title refers to as filename and parents to the parent folder. Add content using SetContentFile and finally upload it.</li></ol><h3>Shell Script</h3><p>Create a shell script that notifies you when backup starts, creates logs, and notifies you when the backup is complete.</p><pre>#!/bin/bash<br>notify-send &quot;Backup Started&quot; <br><br>#working directory<br>cd /home/badal/backup<br><br>#activate environment<br>source venv/bin/activate<br><br>#Run script and create logs<br>python3 drive.py &gt; backup_log.txt<br><br>#notify when backup completed<br>notify-send &quot;Backup Completed&quot;</pre><p>backup_logs.txt is saved in your Python file directory.</p><h3>.desktop file</h3><p>Create a .desktop file in your ~/.local/share/applications directory</p><pre>[Desktop Entry]<br>Version=1.0<br>Terminal=false<br>Type=Application<br><br>#Icon Name<br>Name=Upload<br><br># script to be excuted<br>Exec=/home/badal/upload.sh<br><br># Icon Image path<br>Icon=/home/badal/Downloads/upload.png</pre><p>This creates an icon in your menu. You can also add it to your dock. To learn more about .desktop files you can go through <a href="https://medium.com/@badalpanwar007/running-scripts-from-the-linux-gui-a-beginners-guide-7763514e255a">Running Scripts from the Linux GUI: A Beginner’s Guide</a>. It will create a menu icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ETJP_9hluieaQdsbonWog.png" /></figure><p><em>You can also add the shell script to crontab to run it on reboot.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfdbbac878ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chmod — Altering File Permissions]]></title>
            <link>https://medium.com/@badalpanwar007/chmod-altering-file-permissions-8e077dc83e7a?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e077dc83e7a</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 10:04:34 GMT</pubDate>
            <atom:updated>2023-06-09T10:08:54.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chmod — Altering File Permissions</h3><p>chmod changes the file mode bits of each given file according to mode, which can be either a symbolic representation of changes to make or an octal number representing the bit pattern for the new mode bits.</p><p>In simpler words chmod allows users to modify the permissions of files and directories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*Mdpsv4RRlreHl4Rq5dm-1Q.png" /></figure><p>Below is the synopsis of chmod</p><pre>       chmod [OPTION]... MODE[,MODE]... FILE...<br>       chmod [OPTION]... OCTAL-MODE FILE...<br>       chmod [OPTION]... --reference=RFILE FILE...</pre><p><strong>Check permissions of a file/directory</strong></p><p>We can find the existing permissions of a file using ls command. Add -l flag to get more info about the file.</p><pre>ls -l &lt;file_path&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*uxRxl57kqCGDMHKQQ3fpJg.png" /></figure><p>The first character indicates the type of input.</p><ul><li>- indicates a file</li><li>d indicates a directory</li><li>i indicates a link</li></ul><p>You group the next set of letters, at a maximum of 3 for each group. These groups represent corresponding permissions for user, group, and others.</p><p><strong>Chmod uses the below two notations to alter permissions.</strong></p><h3>Symbolic Mode</h3><p>The symbolic mode uses symbols and operators combination to grant or revoke permissions.</p><h4>User Level Permission</h4><p>These operations control permissions on the user level.</p><ul><li>u – Grant permission to a user</li><li>g – Grant permission to a group (A Group of users)</li><li>o – Grant permission to others (who do not come under either of the above).</li></ul><h4>File Level Permission</h4><p>These control permissions on the file level.</p><ul><li>r – Grants read permission</li><li>w – Grant write permission</li><li>x – Grant execute permission</li></ul><h4>Operators</h4><p>These define whether the permission is to be added or removed</p><ul><li>+ – Add permission</li><li>- – Remove permission</li><li>= – Set permissions to specified values</li></ul><p><strong>Using Symbolic Mode</strong></p><ul><li>Read and write for Owner, and Read-only for the group and other:</li></ul><pre>chmod u+rw,go+r [file_name]</pre><h3>Octal Mode</h3><p>The octal notation uses numbers to represent permissions. Each digit represents the permission set for the owner, group, and others. The values 4, 2, and 1 correspond to read, write, and execute permissions.</p><p><strong>Syntax</strong></p><pre>chmod &lt;user&gt;&lt;group&gt;&lt;others&gt; test.sh<br>chmod 777 test.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*fxJs259JJqKQgYF8Xpn1kg.png" /></figure><p><strong>Using Octal Mode</strong></p><p>Remove all permissions</p><pre>chmod 000 test.sh</pre><p>Add all permission to the user and only read to others and groups.</p><pre>chmod 744 test.sh</pre><ul><li>The first number (7) represents permission for a user: 7 = ( 4 (read) +2 (write) +1(execute) )</li><li>The second number (4) represents permissions for a group: 4 (read)</li><li>The third number (4) represents permissions for others: 4 (read)</li></ul><h3>Practical use cases of chmod</h3><p><strong>Grant permission to make a file executable</strong></p><p>Create a simple bash script(test.sh) and execute it. You will end up seeing the “Permission Denied” error message. This is because the file was not in executable format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*SyMjFa6QrHBa0bINy80pyQ.png" /></figure><p>Now add executable permission using chmod +x test.shand check for permissions. It is in the executable format now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*oDZDt0zxcMhHGLvpymXXWQ.png" /></figure><p>similarly, we can revoke permissions using -</p><pre>chmod -x test.sh   #To revoke execute permission<br>chmod -r test.sh   #To revoke readpermission<br>chmod -w test.sh   #To revoke write permission</pre><p><strong>Adding and removing permissions of the Directory</strong></p><p>Create a directory with 2 sub-directories and remove the read permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*HZbBjD_JckJMAXYA_DO7nA.png" /></figure><p>Now try reading the directories content. You will end up seeing the “Permission Denied” error message. But you can read the contents of the child directories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*VSRAsAFe3li33AmPZ_mBOg.png" /></figure><p>Simply altering the parent directory’s permission does not affect the child file/directory permissions. To apply the same permissions to all child directories use -R</p><pre>sudo chmod -R -r testdir</pre><h3>Conclusion</h3><p>Understanding chmod and its various notations empowers users to control access rights effectively. Whether using symbolic or octal notation, chmod offers a wide range of options to manage permissions precisely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e077dc83e7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Scripts from the Linux GUI: A Beginner’s Guide]]></title>
            <link>https://medium.com/@badalpanwar007/running-scripts-from-the-linux-gui-a-beginners-guide-7763514e255a?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7763514e255a</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Tue, 30 May 2023 13:19:34 GMT</pubDate>
            <atom:updated>2023-05-30T13:19:34.960Z</atom:updated>
            <content:encoded><![CDATA[<p>To run a script without having to open a terminal and type the command manually you need to create a GUI shortcut for the script. The GUI shortcuts are created using .desktop files.</p><p>.desktop files are a standard way of creating GUI shortcuts in these desktop environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHFHtg7oyiAORJ4FviS6KA.jpeg" /></figure><p><strong>Locating .destop files</strong></p><p>.destop config files can be found at the following paths:</p><ul><li>default applications: /usr/share/applications/</li><li>Third party applications: /usr/local/share/applications/</li><li>User specific applications: ~/.local/share/applications/</li></ul><h3><strong>Creating a shell script</strong></h3><pre>xdg-open &#39;https://app.slack.com/client/TV310986N/C02K2HJ249&#39;<br>xdg-open &#39;https://housekeeping.comp.com/housekeeping/&#39;<br>xdg-open &#39;https://webmail.comp.com/zimbra/#1&#39;<br>xdg-open &#39;https://comp.atlassian.net/jira/software/c/projects/WBT/boards/75&#39;<br>xdg-open &#39;https://docs.google.com/document/u/0/?tgff=d&#39;                                                   </pre><p>The above shell script opens my commonly used URLs in the default browser.</p><h3><strong>Creating the config file</strong></h3><p>Open the config files folder.</p><pre>cd ~/.local/share/applications/</pre><p>In our case, we will create a file in the user-specific applications folder.</p><pre>vi work.desktop</pre><p>add the below configs</p><pre>[Desktop Entry]<br>Terminal=false<br>Type=Application<br>Name=Work<br>Exec=/home/badal/work.sh<br>Icon=/home/badal/Downloads/work.jpg</pre><p>Name specifies the application&#39;s name.</p><p>Exec specifies the command to run when the application is launched.</p><p>Icon specifies the path to the icon file associated with the application.</p><p>Terminal indicates whether the application should be run in a terminal window. If set to true, the application will be launched in a terminal otherwise, it will run in the background.</p><p>Type parameter specifies the type of the entry. It can be specified as ‘Application’, ‘Link’, ‘Directory’, ‘Service’.</p><p>You can also add some other below params</p><p>StartupNotify determines whether the desktop environment should show a startup notification for the application.</p><p>Comment allows you to provide a description or additional information about the application.</p><p>Save and exit the file. This will add a shortcut to your Applications Menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42V0suZpckLkcYbX-d3iAg.png" /></figure><p>On clicking it opens all the mentioned URLs in the default browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9EMWWxOd8XcVhnk-XhbnZQ.gif" /></figure><p><em>Add this to your dock to easily access it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7763514e255a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Stock Price Notifications with Shell Scripting]]></title>
            <link>https://medium.com/@badalpanwar007/automating-stock-price-notifications-with-shell-scripting-3bd711f512e8?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd711f512e8</guid>
            <category><![CDATA[script]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Sat, 20 May 2023 18:16:39 GMT</pubDate>
            <atom:updated>2023-05-20T18:42:44.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Automation is key to simplifying repetitive tasks and increasing productivity. Shell scripting, a powerful tool available on Linux-based systems, allows us to automate various processes efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*5sVbEENcTGCJCxTit0Qg2A.png" /></figure><p>In this blog post, we will explore how to leverage shell scripting to fetch stock price data from an API and receive real-time notifications on your desktop.</p><p><strong>Prerequisites</strong></p><p>Before we dive into the shell code, let’s make sure we have the necessary prerequisites in place:</p><ol><li>A Linux-based operating system (such as Ubuntu or CentOS).</li><li><strong>Curl </strong>and<strong> jq </strong>installed on your system.</li></ol><pre>sudo apt install curl<br>sudo apt install jq</pre><h3><strong>Shell Script</strong></h3><pre>#!/bin/bash<br>INTERVAL=300<br>while true; <br>do<br>  ad=$(curl -X GET &#39;https://api.stockdata.org/v1/data/quote?symbols=AAPL&amp;api_token=API_TOKEN&#39; | jq &#39;.data[0].price&#39;)<br>  notify-send -i ~/Desktop/apple.png &quot;Stock Price&quot; &quot;$ad&quot;<br>  sleep $INTERVAL<br>done</pre><p><strong>Explanation</strong></p><p>The INTERVAL variable is set to 300, representing the number of seconds to wait between each iteration of the loop.</p><p>To ensure continuous execution, a while loop is implemented, allowing it to run indefinitely.</p><p>To fetch the data,curl command is used to make a GET request to the <a href="https://www.stockdata.org/documentation">StockData API</a>.</p><p>The output from the curl command is then piped to jq, a command-line JSON processor.</p><p>For displaying desktop notifications, employ the notify-send command. You can customize the notification message using the below template.</p><pre>notify-send -i &lt;icon&gt; &lt;title&gt; &lt;Message&gt;</pre><p>Lastly, the sleep command suspends the script’s execution for the specified interval (300 seconds) before the next iteration of the loop begins.</p><p><strong>Execution</strong></p><p>Save your file as notify.sh. On the terminal use the below command</p><pre>./notify.sh</pre><p>This will run your script as long as the terminal is open. To run in the background use nohup</p><p>nohup, short for no hang up is a command in Linux systems that keep processes running even after exiting the shell or terminal. To start a process in the background use the &amp; symbol at the end of the command.</p><pre>nohup ./notify.sh &amp;</pre><p>To kill the nohup job use kill followed by the process id.</p><p>Remember to use this script responsibly and in compliance with the API’s terms of service.</p><p>Happy scripting!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd711f512e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a YouTube Downloader using Python]]></title>
            <link>https://medium.com/@badalpanwar007/creating-a-youtube-downloader-using-python-5f3ae4e7e1ec?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3ae4e7e1ec</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytube]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[download]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 11:15:34 GMT</pubDate>
            <atom:updated>2023-04-11T11:15:34.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oEX8t9F1dbUNpv1t.png" /></figure><p>Here we’ll be discussing how to build a YouTube downloader using Streamlit and Pytube libraries.</p><h4>Pytube</h4><p>Pytube is a lightweight Python library that provides a simple interface for downloading videos from YouTube. It is designed to be easy to use and efficient, with minimal dependencies and a small codebase.</p><h4>Streamlit</h4><p>Streamlit is an open-source Python library that makes it easy to create interactive web applications for data science and machine learning. It is designed to be simple, flexible, and powerful, with a focus on making it easy to prototype and deploy data-driven applications.</p><h3>Getting Started</h3><p>Open up the terminal and run the following command to create a dire<strong>c</strong>tory for the downloader, create a virtual environment for Python, and install all the necessary packages.</p><ul><li><strong>To create the directory and navigate to that directory</strong>:</li></ul><pre>mkdir downloader &amp;&amp; cd downloader</pre><ul><li><strong>To create and activate the Python virtual environment:</strong></li></ul><pre>python3 -m venv denv &amp;&amp; source denv/bin/activate</pre><ul><li><strong>To install Pytube and streamlit:</strong></li></ul><pre>pip3 install pytube streamlit</pre><p><strong>Create a main.py file and follow the steps</strong></p><p><strong>Importing necessary modules</strong></p><pre>import streamlit as st<br>from pytube import YouTube</pre><p><strong>Creating streamlit UI</strong></p><pre>def main():<br>    st.title(&quot;YouTube Downloader&quot;)<br>    st.write(&quot;Enter the YouTube video URL below:&quot;)<br>    url = st.text_input(label=&quot;URL&quot;)<br>    <br>    if st.button(&quot;Download&quot;):<br>        download_video(url)</pre><p>The main function is the main entry point for our Streamlit app. It is responsible for setting up the UI, handling user input, and calling other functions to perform the required tasks.</p><p>First, we set the title of the Streamlit app using the st.title() function. We then use the st.write() function to display a message to the user asking them to enter the YouTube video URL.</p><p>Next, we create a text input field where the user can enter the YouTube video URL using the st.text_input() function.</p><p>At last, we create a download button using the st.button() function. If the user clicks on the button, we call the download_video() function with the url argument to download the video.</p><p><strong>Downloading Video</strong></p><pre>def download_video(url):<br>    yt = YouTube(url)<br>    video = yt.streams.get_highest_resolution()<br>    video.download()<br>    st.write(&quot;Video downloaded successfully!&quot;)</pre><p>This function takes a single argument url, which is the YouTube video URL that the user entered in the Streamlit app.</p><p>First, we create a YouTube object with the given url. We then use the get_highest_resolution() method to get the highest-resolution video available for the given YouTube object.</p><p>Finally, we call the download() method to start the download.</p><p>At the end of the function, we use the st.write() function to display a success message to the user indicating that the video has been downloaded successfully.</p><p>Combining it all together.</p><pre>import streamlit as st<br>from pytube import YouTube<br><br>def download_video(url):<br>    yt = YouTube(url)<br>    video = yt.streams.get_highest_resolution()<br>    video.download()<br>    st.write(&quot;Video downloaded successfully!&quot;)<br><br>def main():<br>    st.title(&quot;YouTube Downloader&quot;)<br>    st.write(&quot;Enter the YouTube video URL below:&quot;)<br>    url = st.text_input(label=&quot;URL&quot;)<br><br>    if st.button(&quot;Download&quot;):<br>        download_video(url)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Last block of code checks if the script is being run directly (as opposed to being imported as a module) and calls the main function if it is.</p><p><strong>Running your app</strong></p><pre>streamlit run main.py</pre><p>This will open a tab in your browser as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UT82BiG4H3-SjFjRgqGkRA.png" /></figure><p>Here enter the URL and click on download. Your video will be downloaded to your main.py file directory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3ae4e7e1ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Step-by-Step Guide to Implementing Full-Text Search in PostgreSQL]]></title>
            <link>https://medium.com/@badalpanwar007/a-step-by-step-guide-to-implementing-full-text-search-in-postgresql-ea66c55b45aa?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea66c55b45aa</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[psql]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 16:51:59 GMT</pubDate>
            <atom:updated>2023-03-26T16:51:59.560Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL’s full text search functionality, which includes tsvector, tsquery, and tsrank, offers a powerful solution for implementing multilingual search capabilities within your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MYjcEtRhdHziAzcO.png" /></figure><h3>to_tsvector</h3><p>to_tsvector is a PostgreSQL function that converts a document or a string into a sorted list of distinct <a href="https://en.wikipedia.org/wiki/Lexeme">lexemes</a>, and returns a textual representation of that list in a format that can be used for full-text search. The resulting vector can then be indexed using a full-text search index, allowing for fast, efficient text search queries.</p><p>Here is the basic syntax of the to_tsvector function:</p><pre>to_tsvector(text)</pre><pre>SELECT to_tsvector(&#39;The quick brown fox jumps over the lazy dog&#39;);</pre><p>The resulting vector would be:</p><pre> &#39;brown&#39;:3 &#39;dog&#39;:9 &#39;fox&#39;:4 &#39;jump&#39;:5 &#39;lazi&#39;:8 &#39;quick&#39;:2</pre><ul><li>the result is a list of lexemes ready to be searched</li><li>stop words (“in”, “a”, “the”, etc) were removed</li><li>the numbers are the position of the lexemes in the document: brown:1 starts at the 1st position whereas fox:4 starts at the 4th position</li></ul><h3>to_tsquery</h3><p>to_tsquery converts a string or a document into a query that can be used for full-text search. It must consist of single tokens separated by the tsquery operators &amp; (AND), | (OR), ! (NOT), and &lt;-&gt; (FOLLOWED BY),</p><p>The basic syntax of the to_tsquery function is as follows:</p><pre>to_tsquery(query_text)</pre><pre>SELECT to_tsquery(&#39;quick &amp; brown&#39;);</pre><p>The &amp; operator here specifies that both words must be present in the document.</p><p>Here is an example of using to_tsquery with a more complex query:</p><pre>SELECT to_tsquery(&#39;quick &amp; (brown | red) &amp; !dog&#39;);</pre><p>This query would search for documents containing the word “quick”, and either “brown” or “red”, but not “dog”.</p><ul><li>the result is a list of tokens ready to be queried</li><li>stop words (“in”, “a”, “the”, etc) were removed</li></ul><p>The resulting query can be used to search for documents that match the query text using the @@ operator. For example, the following query would search for documents containing the words &quot;quick&quot; and &quot;brown&quot;:</p><pre>/* true */<br>SELECT to_tsquery(&#39;quick&amp;brown&#39;) @@ to_tsvector(&#39;The quick brown fox jumps over the lazy dogl&#39;); <br><br>/* true */<br>SELECT to_tsquery(&#39;quick&#39;) @@ to_tsvector(&#39;The quick brown fox jumps over the lazy dog&#39;); <br><br>/* true */<br>SELECT to_tsquery(&#39;brown&#39;) @@ to_tsvector(&#39;The quick brown fox jumps over the lazy dog&#39;); <br><br>/* false */<br>SELECT to_tsquery(&#39;cat&#39;) @@ to_tsvector(&#39;The quick brown fox jumps over the lazy dog&#39;);</pre><h3>ts_rank</h3><p>ts_rank calculates a rank for a document or a set of documents based on how relevant are documents to a particular query.</p><p>The function takes two arguments: the query being used for the search and the document being ranked.</p><p>The basic syntax of the ts_rank function is as follows:</p><pre>ts_rank(query, document)</pre><p>The query argument must be a tsquery object and the document argument must be a tsvector object.</p><p>The ts_rank function returns a value between 0 and 1 that represents the rank of the document in relation to the query. A higher value indicates a better match between the document and the query.</p><p>Here is an example of using ts_rank to rank a document based on a search query:</p><pre>SELECT ts_rank(<br>  to_tsvector(&#39;The quick brown fox jumps over the lazy dog&#39;),<br>  to_tsquery(&#39;quick &amp; brown&#39;)<br>  );</pre><p>The resulting rank would be a decimal value between 0 and 1, indicating how well the document matches the search query.</p><pre>select<br>    keyword,<br>    ts_rank(keyword_vec, to_tsquery(&#39;green|tea|extract&#39;)) rnk<br>from<br>    keyword_master<br>where<br>    keyword_vec @@ to_tsquery(&#39;green|tea|extract&#39;) <br>order by <br>    rnk desc;</pre><pre>              keyword               |     rnk     <br>------------------------------------+-------------<br> pomegranate green tea              | 0.040528473<br> instant green tea                  | 0.040528473<br> green tea premix                   | 0.040528473<br> green chili powder                 | 0.020264236<br> green mango                        | 0.020264236<br> dehydrated green chilli powder     | 0.020264236<br> wooden tea tables                  | 0.020264236<br> coffee extract                     | 0.020264236<br> rice bran solvent extraction plant | 0.020264236<br> jacquard tea towel                 | 0.020264236</pre><p>Here keyword_vec is a tsvector datatype field stored in our database. @@ matches ‘green|tea|extract’ against keyword_vec and returns true or false. Asts_rank is ordered in descending order the keyword matches more with our text query comes first.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea66c55b45aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code with PEP8: Tips and Tricks for Improving Your Python Syntax]]></title>
            <link>https://medium.com/@badalpanwar007/clean-code-with-pep8-tips-and-tricks-for-improving-your-python-syntax-b2e593bac4c?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2e593bac4c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[pep8]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 16:43:09 GMT</pubDate>
            <atom:updated>2023-02-28T16:43:09.664Z</atom:updated>
            <content:encoded><![CDATA[<p>PEP8 is a coding style guide for Python that outlines guidelines and recommendations for writing code that is both easy to read and consistent. Following the PEP8 style guide ensures that your code is readable by other developers and can be easily maintained over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ikgKia_YdkCS9v5bIE29A.jpeg" /></figure><h3>Why is PEP8 important?</h3><p>PEP8 helps to achieve this goal by providing a set of guidelines that make the code more consistent, readable, and less prone to errors. Here are a few reasons why following PEP8 is crucial for any Python developer:</p><ol><li>Code readability: PEP8 makes your code easier to read, which helps other developers understand your code better.</li><li>Consistency: PEP8 makes your code more consistent and will have a uniform appearance.</li><li>Fewer errors: PEP8 reduces the chances of introducing errors into your code by providing a set of rules that are designed to make your code more reliable and predictable.</li></ol><h3>Indentation</h3><p>Use four spaces for indentation rather than tabs. This is because tabs can display differently on different editors, which can cause indentation problems.</p><pre># Good Example<br>if x == 1:<br>    print(&quot;x is 1&quot;)<br>else:<br>    print(&quot;x is not 1&quot;)</pre><pre># Bad Example<br>if x == 1:<br>        print(&quot;x is 1&quot;)<br>else:<br>        print(&quot;x is not 1&quot;)</pre><h3>Line length</h3><p>Keep lines of code to a maximum of 79 characters. If you need to use longer lines, you can break them up into multiple lines.</p><pre># Good Example<br>def long_function_name(<br>        var_one, var_two, var_three,<br>        var_four):<br>    print(var_one)</pre><pre># Bad Example<br>def long_function_name(var_one, var_two, var_three, var_four): print(var_one)</pre><p>Use the binary operator(+, -, *) before the variable, not after it.</p><pre># Good Example<br>total = (maths<br>         + english<br>         + history)</pre><pre># Bad Example<br>total = (maths +<br>         english +<br>         history)</pre><h3>Blank lines</h3><p>Use blank lines to separate sections of code logically.</p><pre># Good Example<br>def function_one():<br>    print(&quot;Function One&quot;)<br><br>def function_two():<br>    print(&quot;Function Two&quot;)<br><br>print(&quot;Main Program&quot;)</pre><pre># Bad Example<br>def function_one():<br>    print(&quot;Function One&quot;)<br>def function_two():<br>    print(&quot;Function Two&quot;)<br>print(&quot;Main Program&quot;)</pre><h3>Naming conventions</h3><p>Proper naming of variables, functions, classes and modules can make your code more readable and easier to understand.</p><p>Here are some of the guidelines for naming conventions:</p><ul><li>Use descriptive and meaningful names.</li><li>Use lowercase for variables and functions, and uppercase for classes.</li><li>Use underscores (_) to separate words in a name.</li><li>Avoid using single-character names, except for simple iterators.</li><li>Use the same naming convention throughout your code.</li></ul><pre># Good Example<br># Use descriptive and meaningful names<br>student_name = &quot;John Doe&quot;<br>course_id = &quot;CS101&quot;<br>grade_average = 85.5<br><br># Use lowercase for variables and functions<br>def calculate_grade(grade_list):<br>    # code to calculate the grade<br>    pass<br><br># Use camelcasefor classes<br>class Student:<br>    # class definition<br>    pass</pre><pre># Bad Example<br># Use meaningless names<br>a = &quot;John Doe&quot;<br>b = &quot;CS101&quot;<br>c = 85.5<br><br># Use mixed case for variables and functions<br>def CalculateGrade(grade_list):<br>    # code to calculate the grade<br>    pass<br><br># Use lowercase for classes<br>class student:<br>    # class definition<br>    pass</pre><h3>Comments</h3><p>Use comments to explain what the code is doing, rather than how the code is doing it. Here are some guidelines for writing comments:</p><ul><li>Use complete sentences and proper grammar.</li><li>Begin comments with a capital letter and end with a period.</li><li>Use inline comments sparingly and only when necessary.</li><li>Use descriptive variable and function names instead of comments.</li></ul><pre># Good Example<br># Calculate the area of a rectangle<br>width = 10<br>height = 20<br>area = width * height<br>print(&quot;Area:&quot;, area)</pre><pre># Bad Example<br>w = 10  # width<br>h = 20  # height<br>a = w * h  # calculate the area<br>print(&quot;Area:&quot;, a)</pre><h3><strong>Whitespace Around Binary Operators</strong></h3><p>Whitespace can be very helpful in expressions and statements when used properly.</p><p>When assigning a value to a default variable in a function.</p><pre># Good example<br>def fun(var=5)<br><br># Badexample<br>def fun(var = 5)</pre><p>When more than one operator is used in a statement.</p><pre># Good Example<br>a = x**2 + 5<br>b = (x+y) * (x-y)<br><br># Bad Example<br>a = x ** 2 + 5<br>b = (x + y) * (x - y)</pre><p>When not to use whitespace.</p><pre># Good Example<br>l = [1, 2, 4]<br>l[1]<br><br># Bad Example<br>l = [ 1, 2, 4, ]<br>l [1]</pre><h3>Imports</h3><p>How to import modules and packages in your code. Here are some guidelines:</p><ul><li>Imports should be grouped in the following order: standard library imports, third-party imports, and local application imports.</li><li>Use a separate line for each import statement.</li><li>Use absolute imports instead of relative imports.</li><li>Do not use wildcard imports.</li></ul><pre># Good Example<br>import os<br>import sys<br><br>import numpy as np<br>import pandas as pd<br><br>from my_module import my_function</pre><pre># Bad Example<br>from my_module import my_function<br>from os import *<br>from my_module import *<br>import numpy as np<br>import pandas as pd</pre><h3>Conclusion</h3><p>PEP8 provides a set of guidelines for writing Python code that is easy to read and maintain. By following these guidelines, you can make your code more consistent, more readable, and easier to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2e593bac4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to RANK() In PostgreSQL]]></title>
            <link>https://medium.com/@badalpanwar007/introduction-to-rank-in-postgresql-29279793eb7c?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/29279793eb7c</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[psql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 09:44:53 GMT</pubDate>
            <atom:updated>2023-02-22T11:22:40.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vmy9L9UEHusdm-uT.png" /></figure><p>The RANK() function in PostgreSQL is a powerful tool for ranking rows in a result set based on a specific column. It assigns ranks to rows within a result set.</p><p>Here is the basic syntax</p><pre>RANK() OVER (<br>    ORDER BY sort_expression [ASC | DESC],...<br>)</pre><p>If two rows have the same value, they will receive the same rank and the next rank will skip the number of rows with the same value.</p><p>The ORDER BY clause sets the order in which the results are to be displayed.</p><pre>SELECT<br>  name, salary, RANK() OVER (ORDER BY salary) AS rank<br>FROM employees;</pre><p>The above query gives the following output:</p><pre> name | salary  | rank <br>------+---------+------<br> John | 20000   | 1<br> Sarah| 30000   | 2<br> Mike | 30000   | 2<br> Jane | 35000   | 3<br> Dave | 38000   | 4<br> Will | 38000   | 4<br> Dave | 38000   | 5</pre><p>Here all employees are arranged in ascending order of their salary. Some of the employees have the same rank due to the same salary.</p><p><strong>Using partition with Rank()</strong></p><p>Partition divides a result set into partitions based on one or more columns. Each partition is treated as a separate group of rows.</p><pre>RANK() OVER (<br>    [PARTITION BY partition_expression, ... ]<br>    ORDER BY sort_expression [ASC | DESC], ...<br>)</pre><p>The PARTITON BY clause creates a partition in the query result where the RANK() function is applied.</p><pre>SELECT<br>   name,<br>   department,<br>   salary,<br>   RANK () OVER ( <br>      PARTITION BY department<br>      ORDER BY salary DESC<br>   ) ranks<br>FROM<br> employees;</pre><p>The above query gives the following output:</p><pre> name | department | salary | rank <br>------+-----------+--------+------<br> John | HR        | 50000  | 1<br> Sarah| HR        | 40000  | 2<br> Dave | HR        | 38000  | 3<br> Jane | HR        | 35000  | 4<br> Mike | IT        | 60000  | 1<br> Tom  | IT        | 55000  | 2<br> Alice| IT        | 50000  | 3<br> Bob  | Marketing | 55000  | 1<br> Lucy | Marketing | 50000  | 2</pre><p>Here data is first partitioned using department then employees in each partition are arranged in ascending order of their salary.</p><p><em>A slight modification of the above query to get the highest salary from each department</em>.</p><pre>SELECT<br>     *<br>FROM<br>  (<br>    SELECT<br>       name,<br>       department,<br>       salary,<br>       RANK () OVER ( <br>          PARTITION BY department<br>          ORDER BY salary DESC<br>       ) rank<br>    FROM<br>     employees) as rn<br>  WHERE rank = 1;</pre><p>The above query gives the following output:</p><pre>name | department | salary | rank <br>------+-----------+--------+------<br> John | HR        | 50000  | 1<br> Mike | IT        | 60000  | 1<br> Bob  | Marketing | 55000  | 1</pre><h3>Conclusion</h3><p>The RANK() function allows you to assign unique rankings to each row based on its value in that column, and the PARTITION BY clause can be used to divide the result set into partitions and apply the ranking function separately to each partition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29279793eb7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Magic Methods]]></title>
            <link>https://medium.com/@badalpanwar007/python-magic-methods-2ce3fb21f65b?source=rss-ee21d63c9b1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ce3fb21f65b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[class]]></category>
            <dc:creator><![CDATA[Badal Panwar]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 14:58:26 GMT</pubDate>
            <atom:updated>2023-02-16T14:59:05.964Z</atom:updated>
            <content:encoded><![CDATA[<p>Magic methods, also known as dunder methods, are special methods that are used to define behavior for certain operations or behaviors that are built into the language. They are denoted by double underscores on both sides of the method name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6FIYXECnxHYnp5Ft2XtNg.png" /></figure><p><strong>Here are some common dunder methods and their usage:</strong></p><p><strong>__init__</strong> is used to initialize the attributes of an object when it is created. It automatically gets called whenever an object is created.</p><pre>class MyClass:<br>    def __init__(self, x):<br>        self.x = x<br><br>my_object = MyClass(5)<br>print(my_object.x)  # Output: 5</pre><p><strong>__str__</strong> returns a string representation of an object. Commonly it is used to provide a more human-readable output of an object.</p><pre>class MyClass:<br>    def __init__(self, x):<br>        self.x = x<br>    def __str__(self):<br>        return f&quot;MyClass with x = {self.x}&quot;<br><br>my_object = MyClass(5)<br>print(my_object)  # Output: MyClass with x = 5</pre><p><strong>__len__</strong> returns the length of an object.</p><pre>class MyList:<br>    def __init__(self, items):<br>        self.items = items<br>    def __len__(self):<br>        return len(self.items)<br>my_list = MyList([1, 2, 3, 4, 5])<br>print(len(my_list))  # Output: 5</pre><p><strong>__add__</strong> is used to define the behavior of the + operator between two objects.</p><pre>class MyNumber:<br>    def __init__(self, x):<br>        self.x = x<br>    def __add__(self, other):<br>        return MyNumber(self.x + other.x)<br><br>a = MyNumber(5)<br>b = MyNumber(10)<br>c = a + b<br>print(c.x)  # Output: 15</pre><p><strong>__eq__</strong> is used to define the behavior of the == operator between two objects.</p><pre>class MyPoint:<br>    def __init__(self, x, y):<br>        self.x = x<br>        self.y = y<br>    def __eq__(self, other):<br>        return self.x == other.x and self.y == other.y<br><br>p1 = MyPoint(0, 0)<br>p2 = MyPoint(0, 0)<br>p3 = MyPoint(1, 1)<br>print(p1 == p2)  # Output: True<br>print(p1 == p3)  # Output: False</pre><p><strong>__getitem__</strong> is used to access the elements of an object using index notation.</p><pre>class MyList:<br>    def __init__(self, items):<br>        self.items = items<br>    def __getitem__(self, index):<br>        return self.items[index]<br><br>my_list = MyList([1, 2, 3, 4, 5])<br>print(my_list[2])  # Output: 3</pre><p><strong>__repr__</strong> returns a string that represents the object in a way that can be used to recreate the object. Typically it is used for debugging.</p><pre>class Person:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br>    <br>    def __repr__(self):<br>        return f&quot;Person(&#39;{self.name}&#39;, {self.age})&quot;<br>    <br>person = Person(&quot;Badal&quot;, 25)<br>print(repr(person))  # Output: &quot;Person(&#39;Badal&#39;, 25)&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ce3fb21f65b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>