Skip to main content

Posts

Showing posts with the label Programming

C++ Programming: Functions & OOP

C++ Programming Guide: Functions and OOP C++ Programming: Functions & OOP 1. Functions in C++ A function is a block of code that performs a specific task. Functions allow us to reuse code: we define the code once and call it whenever it is needed. #include <iostream> using namespace std; void myFunction() { int x = 2; int y = 5; cout << "Sum of the two numbers is: " << x + y << endl; } int main() { myFunction(); // Calling the function return 0; } Output: Sum of the two numbers is: 7 2. OOP Concepts in C++ OOP (Object-Oriented Programming) is a paradigm that uses Classes (blueprints) and Objects (instances). It provides a clear structure and helps keep code organized. Note: These concepts apply to C++, as standard C does not support classes. ...

Understanding the Switch Statement

Learning Switch Statements - Smart Example Understanding the Switch Statement The switch statement is used to perform different actions based on different conditions. It is more readable than nested if-else blocks when you have many options to choose from. Context Change: We have taken the logic from a signal processing app and turned it into a Smart Home Controller . Instead of "Sine Waves," we have Eco Mode . Instead of "Rectangular Waves," we have Party Mode (flashing lights). The Complete Source Code Below is the entire code (HTML, CSS, and JavaScript) required to build a working Smart Home dashboard using a switch statement: Full Project Code (index.html) <!DOCTYPE html> <html> <head> <title>Smart Home Dashboard</title> <style> #dashboard { border: 2px solid #333; padding: 20px; width: 30...

REST Architecture Explained

  REST (Representational State Transfer) Architecture What is REST? REST is a software architectural style for designing web services. It defines a set of rules for how web applications communicate over the internet. REST is resource-based : everything on the server is considered a resource , such as: A file An image A row in a database table Each resource can have multiple representations , like JSON, XML, HTML, or plain text. Example: A user record in a database can be accessed in JSON or XML format depending on the client request. Architectural Constraints of REST REST recommends six main constraints that make web services scalable, reliable, and maintainable: 1. Uniform Interface Resources are accessed in a consistent way using URLs. Clients interact with resources through standard methods, decoupling client and server. 2. Statelessness Each client request must contain...

Binary Heaps Explained

  Binary Heaps Explained Binary Heaps Binary heaps are a type of data structure that make it fast to get the smallest or largest item from a collection. They’re super common in algorithms and interviews. What is a binary heap? A binary heap is: A complete binary tree (filled level by level, left to right) That follows the heap property There are two kinds : 1. Min-Heap The smallest element is always at the top (the root) Every parent ≤ its children 2. Max-Heap The largest element is always at the top Every parent ≥ its children Example (Min-Heap) 2 / \ 5 8 / \ 9 10 2 is the smallest → always at the top Tree is filled left to right This is a valid min-heap Important Things to Know Not a Binary Search Tree Heaps do not keep things sorted You only know that the root is min (or max) Us...

Semantic vs Non-Semantic Explained

Semantic vs Non-Semantic Programming Semantic vs Non-Semantic Constructs in Programming In programming, the distinction between semantic and non-semantic constructs extends beyond HTML. It applies to any language, syntax, or code structure, where some elements convey meaning and others exist only for structure, organization, or formatting. 1. What is Semantic in Programming? Semantics refers to the meaning or behavior of code , i.e., what the program does when executed. Semantic constructs communicate meaning to the compiler, interpreter, or programmer. They have a clear, well-defined purpose in the program’s logic. Examples: # Python variable declaration age = 25 # Semantic meaning: store 25 in a variable 'age' # Java loop for(int i = 0; i < 10; i++) { System.out.println(i); // Semantic meaning: print numbers 0-9 } 2. What is Non-Semantic in Programming? Non-semantic constructs are code elements that exist for str...

Python Character Encoding Explained

Python Character Encoding Python Character Encoding 1. Setting Up the Environment First, import the libraries you need and set a seed for reproducibility: import pandas as pd import numpy as np import charset_normalizer np.random.seed(0) 2. What Are Encodings? Character encodings map raw bytes to human-readable text. Using the wrong encoding can produce: Garbled text (mojibake): æ–‡å—化ã?? Unknown characters: ���������� The most common and recommended encoding is UTF-8 . UTF-8 is the standard text encoding in Python 3. Converting non-UTF-8 input into UTF-8 early prevents errors and data loss. 3. Strings vs Bytes in Python Python 3 has two main text types: String ( str ) : human-readable text. Bytes ( bytes ) : raw binary representation of text. # String to bytes text = "This is the euro symbol: €" bytes_text = text.encode(...

Float32 vs Float64

Float32 vs Float64 Float32 vs Float64 Definitions float32: A 32-bit floating point number with ~7 decimal digits of precision. float64: A 64-bit floating point number with ~15–17 decimal digits of precision. Importance of float64 float64 is important because it reduces rounding errors and increases precision, which is crucial in scientific computations, finance, and analytics where accuracy is critical. Comparison Table Feature float32 float64 Size (bytes) 4 8 Precision (decimal digits) ~7 ~15–17 Range (approx) 1e-38 → 1e38 1e-308 → 1e308 Memory Usage Less (good for huge datasets) More (twice as much as float32) Rounding errors Higher risk, especially with many calculations Lower risk, more accurate Use case Gra...

DOM manipulations in JavaScript

Interactive DOM manipulation Experiment with DOM manipulation and see the code behind it. 1. Dynamic Text Update ( textContent ) Output: Nothing yet Code concept: let value = document.getElementById('userInput').value; This retrieves the text typed by the user. We then update the output with: document.getElementById('output').textContent = value; 2. Style Manipulation Change Output Color Code concept: element.style.color = 'red'; This directly modifies the CSS of an element. We toggle between red and blue dynamically. 3. Creating Elements ( appendChild ) Add New Element Container for new elements: Code concept: let div = document.createElement('div'); creates a new div. container.appendChild(div); adds it to the DOM. 4....

Object-Relational Mapping (ORM)

What is ORM? ORM stands for Object-Relational Mapping . It allows you to interact with a relational database using objects in your code instead of raw SQL queries. Essentially, it maps database tables to classes and rows to objects. How it Works Database table → Class Row in table → Instance of class (object) Columns → Attributes of the object SQL queries → Methods on objects Example: Suppose you have a users table in your database: id name email 1 Alice alice@mail.com 2 Bob bob@mail.com from sqlalchemy import Column, Integer, String from sqlalchemy.orm import declarative_base Base = declarative_base() class User(Base): __tablenam...

JS Array & Matrix Concepts

JavaScript Array & Matrix Concepts Demo This demo covers key JavaScript array and matrix operations used in signal processing and general programming. 1. Array Manipulation (1D) // Original binary array let inputBits = [0, 1, 1, 0, 1, 0]; // map(): Convert bits to BPSK symbols (0 -> -1, 1 -> 1) let inputSymbols = inputBits.map(bit => bit===0 ? -1 : 1); console.log('map():', inputSymbols); // [-1, 1, 1, -1, 1, -1] // filter(): Split even and odd indices let s1 = inputSymbols.filter((_, i) => i % 2 === 0); // Even indices let s2 = inputSymbols.filter((_, i) => i % 2 === 1); // Odd indices console.log('filter() s1:', s1); // [-1, 1, 1] console.log('filter() s2:', s2); // [1, -1, -1] // reduce(): Sum of all bits let sumBits = inputBits.reduce((sum, b) => sum + b, 0); console.log('reduce() sum:', sumBits); // 3 // some() / every(): Check conditions let allValid = inputBits.every(b => b===0 || b===1); console.log('ev...

Event Delegation in Javascript

  Event Delegation is a powerful technique in JavaScript that allows you to manage events efficiently by attaching a single event listener to a parent element rather than adding multiple listeners to individual child elements. This approach is widely used in modern web applications, including frameworks like React, to improve performance and scalability.  Event Delegation solves this by attaching one listener to a common ancestor (parent container) and handling events for all child elements that trigger it.    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Event Delegation Bit Validator</title> <style> body{ font-family: Arial, sans-serif; background:#f4f6f9; margin:40px; } .container{ max-width:600px; margin:auto; background:white; padding:30px; border-radius:8px; ...

Real-Time Input Validator Using JavaScript

  Introduction In modern web applications, validating user input in real-time is a key aspect of user experience. For developers working with digital systems, communication protocols, or binary data, ensuring that users enter valid bits (0s and 1s) is crucial. In this tutorial, we will create a Real-Time Bit Input Validator using HTML, CSS, and JavaScript , which checks for valid binary input and even-length sequences instantly without needing to submit a form.     <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real-Time Input Bit Validator</title> <style> body{ font-family: Arial, sans-serif; background:#f4f6f9; margin:40px; } .container{ max-width:600px; margin:auto; background:white; padding:30px; border-radius:8px; box-shadow:0 3px 12px rgba(0,0,0,0.1); } h1{ co...

B-Tree: Definition and Python Example

B-Tree: Definition and Python Example What is a B-Tree? A B-Tree is a self-balancing tree data structure that maintains sorted data and allows search, sequential access, insertions, and deletions in logarithmic time . Each node can have multiple keys . Designed for disk-based storage for efficiency. Commonly used in database indexes . Formal definition: A B-Tree of order m is a tree where each node contains at most m-1 keys, has at most m children, all leaves are at the same depth, and keys within a node are sorted. Why B-Trees Are Used in Databases Efficient for range queries ( > , < , BETWEEN ) Efficient for exact lookups ( = ) Can store many keys per node, reducing disk I/O Supports fast insertion and deletion while staying balanced Practical Python Example We can use the BTre...

From Slow Search to Fast Search Using Indexes

From Slow Search to Fast Search Using Indexes Understanding how indexes improve database performance and why B-Tree indexes are the default in relational databases. The Problem Take this example: The database contains millions of rows. Searching for “Ana” takes a long time. Current Implementation The database checks every single row until it finds Ana. This is called a full table scan . It’s like reading an entire book just to find one word. From Slow Search to Fast Search There’s a better way: use an index . An index works like the index of a book — it allows you to jump directly to the correct page instead of scanning everything. Create an Index CREATE INDEX idx_email ON users(email); Now, when we search for Ana, the database jumps directly to her row instead of scanning the entire table. Search Query SELECT * FROM users WHERE ema...

Handling 1 Million Fake API Requests

What to Do If Your API Suddenly Receives 1 Million Fake Requests If your API suddenly receives 1 million fake requests , your server slows down and logs flood. This is usually a DDoS attack or bot flood. 1. Put Protection in Front of Your Server (Most Important) Use a CDN + Web Application Firewall (WAF) such as: Cloudflare AWS (Shield + WAF) Fastly These services: Block bot traffic before it hits your server Rate-limit abusive IPs Detect DDoS patterns automatically Filter suspicious countries or networks 2. Enable Rate Limiting Node / Express Example const rateLimit = require('express-rate-limit'); app.use(rateLimit({ windowMs: 60 * 1000, max: 100 })); NGINX Example limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s; server { location /api/ { limit_req zone...

How to Reduce 20 Database Queries to One

How to Reduce 20 Database Queries to One If your homepage is triggering 20 separate database queries , that’s usually a classic N+1 query problem or inefficient data loading pattern. The goal is to reduce those queries by batching, eager loading, or restructuring how data is fetched. 1. Fix the N+1 Problem (Most Common Cause) Problem Example SELECT * FROM posts; Then for each post: SELECT * FROM users WHERE id = ?; If you have 20 posts → 1 + 20 = 21 queries. Solution: Use JOIN (Single Query) SELECT posts.*, users.name FROM posts JOIN users ON posts.user_id = users.id; 2. Use Eager Loading for Related Data Laravel Post::with('user')->get(); Django Post.objects.select_related('user') Rails Post.includes(:user) 3. Use Subqueries or Aggregates Instead of Separate Queries Instead of multiple COUNT queries: SELECT post...

Hash Tables Explained

Hash Table A Hash Table is a data structure designed to be fast to work with. Hash Tables are often preferred over arrays or linked lists because searching, adding, and deleting data can be done very quickly, even for large amounts of data. Why Not Arrays or Linked Lists? In a Linked List , finding a person like "Bob" means checking each node one by one until Bob is found. In an Array , finding an element is fast only if we know its index. If we only know the value (like a name), we must compare each element. A Hash Table avoids this by letting us go directly to the correct location using a hash function . Building a Hash Table from Scratch We will build a simple Hash Set to store unique names. Step 1: Start with an Array my_arr...

Binary Tree Explained

Binary Trees vs Arrays and Linked Lists Different data structures organize data in different ways. Each one has strengths and weaknesses depending on whether you care more about fast access, fast insertion, or maintaining order. 1. Arrays An array stores elements next to each other in memory. Index: 0 1 2 3 4 Array: [10, 20, 30, 40, 50] Strengths Very fast direct access to elements arr = [10, 20, 30, 40, 50] print(arr[3]) # O(1) → 40 Weaknesses Insertions and deletions are slow because elements must shift in memory arr.insert(1, 15) # [10, 15, 20, 30, 40, 50] Time Complexity Operation Time Access O(1) Insert / Delete (middle) O(n) 2. Linked Lists A linked list is made of nodes, where each node po...

Async Function

Understanding Async Code (Without the Confusion) Many beginners hear async and think it means doing many things at the same time. That sounds reasonable — but it’s not what async really means. Let’s fix that. The Core Idea Async does NOT mean parallel. Async means deferred. Think of async code as a to-do list . The program finishes what it is doing now, postpones slow tasks, and comes back to them when they are ready. One Brain, One Task Both JavaScript and Python behave like a single person with one brain: They run code top to bottom They do one thing at a time They don’t multitask by default Async allows them to avoid waiting and freezing while slow tasks complete. Real-Life Analogy Imagine cooking: You pu...


Contact Us

Name

Email *

Message *