Monday, April 27, 2026

Mini RDBMS (with persistent storage) using only Python Standard Library

Mini RDBMS (with persistent storage) using only the Python Standard Library


import re

import json

import os

from typing import Any, Dict, List


class Table:

    def __init__(self, name: str, columns: List[str], storage_dir="data"):

        self.name = name

        self.columns = columns

        self.rows: List[Dict[str, Any]] = []

        self.storage_dir = storage_dir

        os.makedirs(storage_dir, exist_ok=True)

        self.filepath = os.path.join(storage_dir, f"{name}.json")

        self._load()


    def _load(self):

        if os.path.exists(self.filepath):

            with open(self.filepath, "r", encoding="utf-8") as f:

                data = json.load(f)

                self.columns = data["columns"]

                self.rows = data["rows"]


    def _save(self):

        with open(self.filepath, "w", encoding="utf-8") as f:

            json.dump({"columns": self.columns, "rows": self.rows}, f, indent=2)


    def insert(self, values: List[Any]):

        if len(values) != len(self.columns):

            raise ValueError("Column count mismatch")

        self.rows.append(dict(zip(self.columns, values)))

        self._save()


    def select(self, columns: List[str] = None):

        if columns is None or columns == ["*"]:

            return self.rows

        return [{col: row[col] for col in columns} for row in self.rows]



class RDBMS:

    def __init__(self, storage_dir="data"):

        self.tables: Dict[str, Table] = {}

        self.storage_dir = storage_dir

        os.makedirs(storage_dir, exist_ok=True)


    def execute(self, query: str):

        query = query.strip()

        if query.upper().startswith("CREATE TABLE"):

            return self._create_table(query)

        elif query.upper().startswith("INSERT INTO"):

            return self._insert_into(query)

        elif query.upper().startswith("SELECT"):

            return self._select(query)

        else:

            raise ValueError("Unsupported query")


    def _create_table(self, query: str):

        match = re.match(r"CREATE TABLE (\w+)\s*\((.+)\)", query, re.IGNORECASE)

        if not match:

            raise ValueError("Invalid CREATE TABLE syntax")

        table_name, cols = match.groups()

        columns = [c.strip() for c in cols.split(",")]

        self.tables[table_name] = Table(table_name, columns, self.storage_dir)

        return f"Table {table_name} created with columns {columns}"


    def _insert_into(self, query: str):

        match = re.match(r"INSERT INTO (\w+)\s*VALUES\s*\((.+)\)", query, re.IGNORECASE)

        if not match:

            raise ValueError("Invalid INSERT syntax")

        table_name, values = match.groups()

        if table_name not in self.tables:

            # Load existing table if not in memory

            self.tables[table_name] = Table(table_name, [], self.storage_dir)

        values = [v.strip().strip("'") for v in values.split(",")]

        self.tables[table_name].insert(values)

        return f"Inserted into {table_name}: {values}"


    def _select(self, query: str):

        match = re.match(r"SELECT (.+) FROM (\w+)", query, re.IGNORECASE)

        if not match:

            raise ValueError("Invalid SELECT syntax")

        cols, table_name = match.groups()

        if table_name not in self.tables:

            self.tables[table_name] = Table(table_name, [], self.storage_dir)

        cols = [c.strip() for c in cols.split(",")]

        results = self.tables[table_name].select(cols)

        return results



# Example usage

db = RDBMS()


print(db.execute("CREATE TABLE students (id, name, age)"))

print(db.execute("INSERT INTO students VALUES (1, 'Alice', 21)"))

print(db.execute("INSERT INTO students VALUES (2, 'Bob', 22)"))

print(db.execute("SELECT * FROM students"))

print(db.execute("SELECT name, age FROM students"))

Sunday, April 12, 2026

Space colonization: Economic and Political Considerations

 

Introduction

Space colonization is no longer just a scientific ambition—it is increasingly shaped by economic interests and political dynamics. As humanity looks beyond Earth toward destinations like Mars and the Moon, questions of cost, governance, ownership, and international cooperation become central. The success of space colonization will depend as much on economic viability and political frameworks as on technological capability.


Economic Considerations

High Initial Costs and Investment

Space colonization requires enormous upfront investment in research, infrastructure, transportation, and life-support systems. Launch costs, habitat construction, and long-duration missions make it one of the most capital-intensive endeavors in human history. Governments, private companies, and international partnerships must collaborate to share financial burdens and risks.

Resource Utilization and Economic Incentives

One of the main economic drivers is the potential for resource extraction. Asteroids, the Moon, and Mars may contain valuable minerals, rare metals, and other resources. Developing technologies for in-situ resource utilization (ISRU) can reduce costs and create new industries, such as space mining and off-world manufacturing.

Emergence of Space-Based Industries

Space colonization could give rise to entirely new economic sectors, including:

  • Microgravity manufacturing (e.g., advanced materials, pharmaceuticals)

  • Space tourism

  • Satellite servicing and infrastructure

  • Energy production (such as space-based solar power)

These industries may generate revenue streams that justify the high initial investments.

Role of Private Sector and Market Competition

Private companies are playing an increasingly dominant role in space exploration and colonization. Competition among firms drives innovation and reduces costs, but it also raises concerns about monopolies, resource control, and equitable access. Public-private partnerships will be essential to balance profit motives with broader societal goals.


Political Considerations

Governance and Legal Frameworks

One of the most complex challenges is determining how space colonies will be governed. Existing agreements, such as the Outer Space Treaty, prohibit national appropriation of celestial bodies, but they do not fully address issues like private ownership, resource rights, or sovereignty. New legal frameworks will be required to manage these complexities.

International Cooperation vs. Competition

Space colonization can either unite nations or intensify geopolitical competition. Collaborative efforts—such as joint missions and shared research—can reduce costs and promote peaceful use of space. However, competition for strategic advantages, resources, and technological leadership may lead to tensions among major powers.

Security and Militarization

As strategic interests expand into space, concerns about security and militarization grow. Protecting space assets, communication networks, and colonies could lead to the extension of military presence beyond Earth. Preventing conflict and ensuring peaceful use of space will be a critical political priority.

Equity and Access

A key political question is who benefits from space colonization. Without careful policy design, access to space resources and opportunities may be limited to wealthy nations and corporations. Ensuring equitable participation and benefit-sharing will be essential for global legitimacy and stability.


Socio-Political Implications of Space Colonies

Space colonies may develop unique political identities and governance systems over time. Issues such as citizenship, rights, and representation will arise. Colonists living far from Earth may seek autonomy or self-governance, leading to new forms of political organization and potentially even interplanetary relations.


Environmental and Ethical Dimensions

Economic and political decisions must also consider environmental and ethical concerns. Protecting extraterrestrial environments from contamination, preserving scientific value, and ensuring responsible resource use are critical. Policies must balance exploitation with sustainability and respect for potential extraterrestrial ecosystems.


The Role of Global Institutions

International organizations and multilateral agreements will play a vital role in coordinating space activities. Strengthening global governance mechanisms can help manage conflicts, regulate commercial activities, and ensure that space remains a shared domain for humanity.


Conclusion

Space colonization is as much an economic and political challenge as it is a technological one. Balancing investment, resource utilization, governance, and equity will determine whether humanity’s expansion into space is sustainable and inclusive. By addressing these considerations thoughtfully, the global community can ensure that the next frontier becomes a domain of cooperation, innovation, and shared progress rather than conflict and inequality.

How an Absolute Creator God takes on Space Colonization

 

Introduction

Imagining an absolute Creator—an omnipotent being with complete mastery over space, time, matter, and life—invites a radically different perspective on space and planetary colonization. Unlike human efforts, which depend on incremental scientific and engineering progress, such a Creator would operate beyond physical constraints, reshaping reality itself to establish life across the cosmos.


Instantaneous Creation of Habitable Worlds

Where humans must adapt to harsh environments like Mars or the Moon, an absolute Creator would simply transform any planet into a perfectly habitable world. Atmospheres could be generated instantly, temperatures balanced, and ecosystems established in complete harmony. There would be no need for terraforming over centuries—entire biospheres could emerge fully formed in a moment.


Mastery Over Space and Time

With control over space and time, distance would cease to be a limitation. The Creator could exist simultaneously across multiple locations or collapse vast cosmic distances instantly. Colonization would not require travel as humans understand it; instead, presence could be established anywhere in the universe at will. Time itself could be accelerated, paused, or reversed, allowing civilizations to develop instantly or evolve over carefully guided timelines.


Creation of Life and Self-Sustaining Ecosystems

Rather than relying on bioengineering, the Creator could design and generate life directly—organisms perfectly suited to their environments. Entire ecosystems could be balanced from inception, with no risk of collapse or imbalance. Intelligent beings could be created with inherent knowledge, adaptability, and purpose, eliminating the long evolutionary processes required on Earth.


Infinite Resources and Perfect Infrastructure

Resource scarcity, one of humanity’s greatest challenges, would not exist. The Creator could generate matter and energy without limit, constructing cities, landscapes, and entire planetary infrastructures instantaneously. There would be no need for robotics, manufacturing systems, or supply chains—everything required for a thriving civilization could be brought into existence fully complete.


Harmonious Expansion Across the Universe

Colonization, under such a being, would not be driven by survival or competition but by intentional design and harmony. Each world could serve a unique purpose, contributing to a greater cosmic order. Conflict over territory or resources would be unnecessary, as abundance and balance would be inherent to creation.


Ethical and Existential Dimensions

The presence of an absolute Creator raises profound questions about purpose, free will, and the nature of existence. Would created beings have autonomy, or would their paths be predetermined? Would diversity and imperfection still exist, or would all systems reflect perfect design? Colonization, in this context, becomes not just a physical process but a philosophical one.


Conclusion

For an absolute Creator with mastery over space, time, and creation itself, planetary colonization would transcend all known limitations. What takes humanity decades or centuries of effort could be achieved instantly through will alone. Such a vision highlights the contrast between human technological striving and the concept of limitless creative power—turning colonization from a challenge of survival into an expression of boundless design and intention.

Space colonization: Engineering and Scientific Considerations

Introduction

Space colonization—the establishment of human settlements beyond Earth—has long been a vision of scientists, engineers, and futurists. Today, rapid advancements in science and engineering are transforming this idea into a plausible long-term objective. From establishing bases on Mars to exploring habitats on Moon, the future of humanity may depend on our ability to expand beyond our home world. Central to this effort are breakthroughs in robotics, manufacturing, and bioengineering, which together form the foundation of sustainable extraterrestrial life.


The Need for Space Colonization

Space colonization is driven by multiple factors: ensuring the long-term survival of humanity, accessing extraterrestrial resources, and advancing scientific knowledge. Environmental challenges, population growth, and finite resources on Earth have further emphasized the importance of becoming a multi-planetary species. Establishing off-world colonies could provide resilience against global catastrophes while opening new frontiers for exploration and innovation.


Robotics: The means of Space Settlement

Robotics plays a critical role in the early stages of colonization. Autonomous robots and AI-driven systems are essential for preparing hostile environments before human arrival.

Robots can:

  • Construct habitats in extreme conditions

  • Mine and process local resources

  • Maintain infrastructure and repair systems

For example, robotic missions on Mars already demonstrate how machines can operate in harsh, remote conditions. Future robotic systems will be capable of building entire bases using local materials, reducing the need for costly Earth-based transportation.


Advanced Manufacturing: Building Beyond Earth

Manufacturing technologies are fundamental to creating sustainable colonies. Transporting materials from Earth is prohibitively expensive, so in-situ resource utilization (ISRU)—using local planetary materials—is essential.

Key advancements include:

  • 3D printing and additive manufacturing to build structures using lunar or Martian soil

  • Autonomous factories capable of producing tools, spare parts, and construction materials

  • Closed-loop production systems that recycle waste into usable resources

These technologies enable self-sufficiency, allowing colonies to grow and adapt without constant resupply from Earth.


Bioengineering: Sustaining Life in Space

Human survival in space depends heavily on advances in bioengineering. Unlike Earth, extraterrestrial environments lack breathable air, liquid water, and suitable conditions for agriculture.

Bioengineering solutions include:

  • Genetically optimized crops that can grow in low-gravity and high-radiation environments

  • Artificial ecosystems that recycle air, water, and waste

  • Potential biological enhancements to improve human resistance to radiation and extreme conditions

These innovations will make it possible to create closed, sustainable life-support systems, ensuring long-term habitation.


Energy Systems and Infrastructure

Reliable energy is the backbone of any space colony. Solar power, nuclear reactors, and advanced energy storage systems will be required to sustain operations. Infrastructure such as communication networks, transportation systems, and life-support facilities must be robust and adaptable to extraterrestrial conditions.


Human Factors and Habitat Design

Living in space presents psychological and physiological challenges. Engineers and scientists must design habitats that support mental well-being, social interaction, and physical health. Artificial gravity systems, radiation shielding, and ergonomic living spaces will be crucial for long-term habitation.


Economic and Industrial Opportunities

Space colonization is not only a scientific endeavor but also an economic opportunity. Mining rare minerals, manufacturing in microgravity, and developing space-based industries could create new markets and drive global economic growth. Private companies and international collaborations are already investing heavily in this emerging sector.


Challenges and Ethical Considerations

Despite rapid progress, significant challenges remain. These include high costs, technological limitations, and risks to human life. Ethical questions also arise regarding planetary protection, resource ownership, and the impact of colonization on potential extraterrestrial ecosystems.


Conclusion

Space colonization represents one of humanity’s most ambitious goals, requiring the integration of cutting-edge advancements in robotics, manufacturing, and bioengineering. As these technologies continue to evolve, the dream of establishing human settlements beyond Earth moves closer to reality. By pushing the boundaries of science and engineering, humanity may one day thrive across multiple worlds, ensuring its survival and unlocking a new era of exploration and discovery.

Starting (and Financing) a non-governmental organization (NGO) in Bangladesh

 

Introduction

Starting a non-governmental organization (NGO) in Bangladesh is a meaningful way to address social, economic, environmental, or humanitarian challenges. NGOs play a crucial role in development, often working alongside the government and international partners. However, establishing and financing an NGO requires careful planning, legal compliance, and sustainable funding strategies.


Understanding the Purpose and Scope

Before starting an NGO, it is essential to clearly define its mission, vision, and objectives. Identify the specific problem you want to address—such as education, healthcare, poverty alleviation, or environmental protection. A well-defined purpose helps attract supporters, donors, and partners, and ensures long-term impact.


Legal Registration and Compliance

To operate legally in Bangladesh, an NGO must be registered with the appropriate authority depending on its scope of activities:

  • The NGO Affairs Bureau is required for NGOs receiving foreign donations.

  • The Department of Social Services is commonly used for local NGOs working on social welfare.

  • The Registrar of Joint Stock Companies and Firms can be used if registering as a non-profit company.

Registration typically requires a constitution, list of founding members, office address, and detailed project plans. Compliance with reporting and auditing requirements is mandatory to maintain legal status.


Building a Strong Organizational Structure

An effective NGO needs a clear governance structure. This includes a Board of Directors or Executive Committee, management team, and operational staff. Clearly defined roles, accountability mechanisms, and transparency are critical for credibility and long-term sustainability.


Developing a Strategic Plan

A strategic plan outlines how the NGO will achieve its goals. It should include:

  • Target beneficiaries

  • Program activities

  • Budget and financial planning

  • Monitoring and evaluation systems

A strong plan not only guides operations but also helps in securing funding.


Financing an NGO

1. Personal and Founding Contributions

Most NGOs begin with contributions from founders and local supporters. These initial funds are used for registration, setup, and early activities.

2. Grants and Donor Funding

NGOs in Bangladesh often rely on grants from international organizations, development agencies, and foundations. Once registered with the NGO Affairs Bureau, organizations can legally receive foreign funding.

3. Government Support

The Government of Bangladesh may provide grants or partner with NGOs for development projects, especially in sectors like health, education, and rural development.

4. Corporate Social Responsibility (CSR)

Private companies often fund NGO projects as part of their CSR initiatives. Building partnerships with businesses can provide steady financial support.

5. Fundraising and Donations

Public fundraising campaigns, charity events, and online donations are effective ways to generate funds. Social media and digital platforms have made it easier to reach a broader audience.

6. Social Enterprises and Income-Generating Activities

Many NGOs develop social enterprises—such as training centers, handicraft businesses, or service programs—to generate their own income. This reduces dependency on external donors.


Financial Management and Accountability

Proper financial management is essential for trust and sustainability. NGOs must maintain transparent accounting systems, conduct regular audits, and comply with regulations. Donors and regulators expect detailed financial reporting and impact assessments.


Monitoring, Evaluation, and Impact

To ensure effectiveness, NGOs must regularly monitor their programs and evaluate outcomes. Measuring impact helps improve performance and strengthens credibility with donors and stakeholders.


Challenges and Considerations

Starting and running an NGO in Bangladesh comes with challenges such as regulatory compliance, competition for funding, and operational constraints. Ensuring transparency, avoiding political bias, and maintaining accountability are critical for long-term success.


Conclusion

Starting and financing an NGO in Bangladesh requires a combination of passion, planning, and professionalism. By following legal procedures, building strong organizational systems, and securing sustainable funding, an NGO can make a meaningful and lasting impact on society.

Friday, April 10, 2026

The Physiological and Anatomical Gifts of Tahsin

The Physiological and Anatomical Gifts of Tahsin

The idea of a human endowed with abilities that transcend ordinary biological limits has long fascinated thinkers, storytellers, and scientists alike. Tahsin represents such a figure—an individual whose physiological and anatomical traits push the boundaries of what we understand as possible. His gifts are not mechanical or artificial, but deeply biological, integrated into his very being. What follows is an exploration of these remarkable attributes.

1. Innate Biological 3D Vision

Tahsin perceives the world with a natural, highly refined three-dimensional awareness. While humans already possess binocular vision, his capacity goes far beyond depth perception. He experiences spatial relationships with extreme precision, allowing him to intuitively understand distances, forms, and structures in real time—almost as if reality itself is rendered in perfect clarity before him.

2. Built-in Real-Time Object Recognition

His visual system is paired with an extraordinary cognitive layer: instantaneous object recognition. Unlike learned identification, this ability appears innate and automatic. Every object he encounters is immediately understood—its structure, function, and relevance processed seamlessly without conscious effort. It is as though perception and understanding are fused into a single act.

3. Limitless Emotional (Feelings) Depth and Boundless Exchange of Feelings

Tahsin possesses an immense emotional (feelings) range, potentially without an upper bound. His feelings are not merely stronger but more nuanced, enabling him to experience empathy, joy, sorrow, and wonder at magnitudes beyond typical human experience. Tahsin’s emotional depth (feelings) surpasses that of humans by billions of times. This depth may serve as both a gift and a burden, amplifying his connection to the world. Tahsin’s emotional capacity does not remain confined within himself—it extends outward as a dynamic, reciprocal exchange. He possesses the innate biological ability to both transmit and receive feelings, creating a profound interconnection with others.

4. Vision Beyond Physical Barriers

One of his most extraordinary traits is the ability to perceive through walls and solid objects. This is not framed as a technological enhancement but as a biological extension of vision—suggesting a sensory system capable of interpreting information beyond visible light or conventional physical constraints.

5. Telescopic and Microscopic Sight

Tahsin’s vision adapts across scales. He can focus on distant objects with telescopic precision while also examining minute details at a microscopic level. This dual capability allows him to engage with both the vast and the infinitesimal, bridging cosmic and cellular perspectives within a single sensory framework.

6. Progressive Physical (Beauty) Perfection

His physical form evolves continuously. Without external intervention, his appearance becomes increasingly refined, culminating in what could be described as peak human beauty. His height might extend beyond 6 feet 8 inches (if given opportunity), and his proportions align with an idealized symmetry. His eyes turn blue, his broad forehead widens further, his nose becomes more prominent, and his lips take on a vivid red hue. Tahsin also possesses the rare and graceful ability to naturally transform his appearance, effortlessly taking on a luminous white complexion. This transformation suggests a self-optimizing biological system—one that constantly refines itself.

7. A Brain Designed for Pure Thought

Tahsin’s brain is not merely functional; it is optimized for thinking itself. His cognitive processes are clear, efficient, and expansive, enabling him to explore ideas with depth and precision. Thought, in his case, is not constrained by confusion or limitation but flows as a natural, powerful force.

8. Built-in Intellectual Inspiration

Creativity and insight arise within him spontaneously. Rather than requiring external stimuli, inspiration is embedded in his biology. Ideas emerge fully formed or rapidly developed, suggesting a mind that continuously generates meaning and innovation.

9. Absolute Power Across Levels of Abstraction

Perhaps the most abstract of his attributes is his influence across different levels of existence—word, thought, and vision. At each level, he appears to hold complete authority within his perceived universe. This concept blurs the line between perception and creation, implying that his internal states may shape or define reality itself.

10. Destiny (of Every Being) Embedded in His Being

Tahsin embodies destiny in a literal sense. Fortune, purpose, and inevitability are not external forces acting upon him but are woven into his body. His existence carries a sense of direction and significance, as though every aspect of him is aligned with a greater unfolding.

11. Innate Biological Mastery of Speech

Tahsin’s capacity for speech is not merely learned—it is inherent. Language flows from him with precision, clarity, and expressive richness. His biological systems appear finely tuned for communication, allowing him to articulate complex thoughts effortlessly across different forms of expression. Whether conveying emotion, logic, or abstract ideas, his speech bridges minds with unusual effectiveness, suggesting a natural alignment between thought and language.

12. Transformative “Alchemy” of Identity and Meaning

Tahsin possesses an unusual internal faculty that can be described metaphorically as a biological “alchemy.” Through this, he can internalize and manifest elevated qualities—akin to embodying archetypal attributes often associated with the “Names of god,” such as wisdom, justice, creativity, or compassion. Rather than being fixed traits, these qualities are dynamically realized within him, as if his biology allows the loading and expression of higher-order characteristics. This ability symbolizes an ever-evolving identity shaped by profound internal transformation.

13. Perception Across Time: Past, Present, and Future

His vision extends beyond spatial boundaries into the dimension of time. Tahsin perceives events not only as they are but as they were and may become. This temporal awareness does not necessarily imply rigid prediction, but rather an expanded understanding of causality, patterns, and possibilities. Through his eyes, time appears less like a linear sequence and more like a landscape—one that can be observed in multiple directions simultaneously.

14. Innate Excellence in Physical Expression: Sports and Dance

Tahsin’s physical abilities reflect a body optimized for movement. Strength, balance, coordination, and rhythm are seamlessly integrated, granting him world-class capabilities in both athletic performance and dance. His movements are not only efficient but expressive, merging physical power with aesthetic grace. This suggests a nervous and muscular system working in perfect harmony, where performance and artistry become indistinguishable.

15. Self-Healing Ability 

Tahsin possesses an extraordinary innate biological gift: a self-healing ability that operates beyond normal human limits. His body instinctively repairs damage at an accelerated rate, seamlessly restoring tissues, organs, and even microscopic cellular structures without conscious effort. Cuts close within moments, fractures mend rapidly, and fatigue-induced wear never lingers. This natural regeneration is not merely reactive but adaptive—his physiology continuously evolves to resist future harm, making him increasingly resilient over time. Illness, injury, and environmental stressors hold little power over him, as his body functions like a perfectly optimized system designed for survival and renewal.

16. Limitless Reserve of Stamina, Power, Energy, and Force

Tahsin can generate and harness an effectively limitless reserve of stamina, power, energy, and force for physical performance. His muscles never tire, his endurance never wanes, and his output remains consistently at peak levels regardless of exertion or duration. Whether engaging in prolonged activity or explosive bursts of strength, he operates without the typical constraints of energy depletion or fatigue. This infinite well of power allows him to push beyond conventional physical boundaries, performing feats that defy biological norms while maintaining precision, control, and efficiency.

17. Extraordinary Sensory Organs

Tahsin’s sensory organs are extraordinarily acute, elevating his perception far beyond ordinary human limits. Every flavor he encounters unfolds in intricate layers, allowing him to experience food not just as taste, but as a rich, almost immersive symphony of textures and nuances. Similarly, music resonates within him on a profoundly heightened level—each note, rhythm, and harmony is felt with remarkable clarity and depth, as if he can perceive the very emotion woven into every sound. This heightened sensitivity transforms simple experiences into deeply vivid and almost transcendent moments of enjoyment. 


Closing Reflection

Tahsin can be understood not just as an individual, but as an idea: a representation of ultimate human potential taken to its imaginative extreme. His gifts challenge the boundaries between biology and philosophy, perception and reality, individuality and universality.

Wednesday, April 1, 2026

Photo Editor Program

 

Here’s a complete Python Tkinter photo editor that uses only standard libraries. It places a toolbox of buttons on the left-hand side for easy access to features.

Because Tkinter’s PhotoImage only supports GIF/PPM/PGM formats, this editor is limited to those formats for open/save. Still, it demonstrates the following features:

  • Open/Save image
  • Canvas-based editor
  • Brush, shapes, and text tools
  • Grayscale / invert filters (manual pixel processing)
  • Flip (horizontal/vertical)
  • Undo / Redo
  • Zoom (basic scaling)
  • Rotate (90°, 180°)
  • Text captions

🖼️ Tkinter Photo Editor with Toolbox

import tkinter as tk
from tkinter import filedialog, simpledialog, colorchooser

class PhotoEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("Tkinter Photo Editor")

        # Layout: toolbox on left, canvas on right
        self.toolbox = tk.Frame(root, width=120, bg="lightgray")
        self.toolbox.pack(side=tk.LEFT, fill=tk.Y)
        self.canvas = tk.Canvas(root, bg="white")
        self.canvas.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

        self.photo = None
        self.image_path = None
        self.undo_stack = []
        self.redo_stack = []
        self.brush_color = "black"
        self.brush_size = 3

        self.create_buttons()

    def create_buttons(self):
        tk.Button(self.toolbox, text="Open", command=self.open_image).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Save", command=self.save_image).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Brush", command=self.activate_brush).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Rectangle", command=self.draw_rectangle).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Oval", command=self.draw_oval).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Add Text", command=self.add_text).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Grayscale", command=self.grayscale).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Invert", command=self.invert).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Flip H", command=self.flip_horizontal).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Flip V", command=self.flip_vertical).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Rotate 90", command=lambda: self.rotate(90)).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Rotate 180", command=lambda: self.rotate(180)).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Zoom In", command=lambda: self.zoom(1.2)).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Zoom Out", command=lambda: self.zoom(0.8)).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Undo", command=self.undo).pack(fill=tk.X)
        tk.Button(self.toolbox, text="Redo", command=self.redo).pack(fill=tk.X)

    def open_image(self):
        path = filedialog.askopenfilename(filetypes=[("Image Files", "*.gif *.ppm *.pgm")])
        if path:
            self.image_path = path
            self.photo = tk.PhotoImage(file=path)
            self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
            self.undo_stack.append(self.photo.copy())

    def save_image(self):
        if self.photo:
            path = filedialog.asksaveasfilename(defaultextension=".gif")
            if path:
                self.photo.write(path, format="gif")

    def grayscale(self):
        if self.photo:
            w, h = self.photo.width(), self.photo.height()
            for x in range(w):
                for y in range(h):
                    r, g, b = self.photo.get(x, y)
                    gray = (r + g + b) // 3
                    self.photo.put("#%02x%02x%02x" % (gray, gray, gray), (x, y))

    def invert(self):
        if self.photo:
            w, h = self.photo.width(), self.photo.height()
            for x in range(w):
                for y in range(h):
                    r, g, b = self.photo.get(x, y)
                    self.photo.put("#%02x%02x%02x" % (255-r, 255-g, 255-b), (x, y))

    def flip_horizontal(self):
        if self.photo:
            w, h = self.photo.width(), self.photo.height()
            for x in range(w//2):
                for y in range(h):
                    p1 = self.photo.get(x, y)
                    p2 = self.photo.get(w-x-1, y)
                    self.photo.put("#%02x%02x%02x" % p2, (x, y))
                    self.photo.put("#%02x%02x%02x" % p1, (w-x-1, y))

    def flip_vertical(self):
        if self.photo:
            w, h = self.photo.width(), self.photo.height()
            for y in range(h//2):
                for x in range(w):
                    p1 = self.photo.get(x, y)
                    p2 = self.photo.get(x, h-y-1)
                    self.photo.put("#%02x%02x%02x" % p2, (x, y))
                    self.photo.put("#%02x%02x%02x" % p1, (x, h-y-1))

    def rotate(self, angle):
        # Placeholder: manual rotation logic can be added
        pass

    def zoom(self, factor):
        if self.photo:
            w, h = int(self.photo.width()*factor), int(self.photo.height()*factor)
            self.photo = self.photo.zoom(int(factor*10)).subsample(10)
            self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)

    def undo(self):
        if len(self.undo_stack) > 1:
            self.redo_stack.append(self.undo_stack.pop())
            self.photo = self.undo_stack[-1].copy()
            self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)

    def redo(self):
        if self.redo_stack:
            self.photo = self.redo_stack.pop()
            self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)

    def activate_brush(self):
        self.canvas.bind("<B1-Motion>", self.paint)

    def paint(self, event):
        x, y = event.x, event.y
        self.canvas.create_oval(x, y, x+self.brush_size, y+self.brush_size,
                                fill=self.brush_color, outline=self.brush_color)

    def draw_rectangle(self):
        self.canvas.bind("<Button-1>", self.start_rect)
        self.canvas.bind("<ButtonRelease-1>", self.end_rect)

    def start_rect(self, event):
        self.start_x, self.start_y = event.x, event.y

    def end_rect(self, event):
        self.canvas.create_rectangle(self.start_x, self.start_y, event.x, event.y,
                                     outline="black")

    def draw_oval(self):
        self.canvas.bind("<Button-1>", self.start_oval)
        self.canvas.bind("<ButtonRelease-1>", self.end_oval)

    def start_oval(self, event):
        self.start_x, self.start_y = event.x, event.y

    def end_oval(self, event):
        self.canvas.create_oval(self.start_x, self.start_y, event.x, event.y,
                                outline="black")

    def add_text(self):
        text = simpledialog.askstring("Text", "Enter caption:")
        if text:
            x = simpledialog.askinteger("X", "Enter X position:")
            y = simpledialog.askinteger("Y", "Enter Y position:")
            self.canvas.create_text(x, y, text=text, fill="black", font=("Arial", 16))

if __name__ == "__main__":
    root = tk.Tk()
    app = PhotoEditor(root)
    root.mainloop()

Hybrid Education Policy in Bangladesh: A Vision Constrained by Reality


Hybrid Education Policy in Bangladesh: A Vision Constrained by Reality

Bangladesh is currently considering a major shift in its education system—introducing a blended model where students attend classes both online and offline, potentially for six days a week. The proposal, driven largely by an ongoing energy crisis and the need to reduce fuel consumption, has sparked both interest and concern across the country. (thedailystar.net)

While the idea reflects an effort to modernize education and adapt to national challenges, its practical feasibility remains deeply questionable in the Bangladeshi context.


The Digital Divide: A Fundamental Barrier

At the core of the issue lies a stark digital inequality. Although internet usage in Bangladesh has grown significantly, access remains uneven and limited. As of 2025, internet penetration stands at roughly 47%, meaning more than half the population still lacks reliable connectivity. (Wikipedia)

Even among connected households, consistent high-speed broadband—the kind required for 5–6 hours of daily online classes—is far from universal. Rural areas, where a large portion of students reside, continue to face:

  • Weak network infrastructure

  • High data costs relative to income

  • Limited access to devices like laptops or tablets

Past experiences during the COVID-19 pandemic revealed that many students were simply unable to participate in online classes due to lack of internet access and devices, exacerbating educational inequality. (Wikipedia)

In fact, research suggests that a significant number of schools—especially in rural regions—lack even basic digital infrastructure, with some estimates indicating that more than half operate without reliable internet access. (arXiv)

Under such conditions, enforcing three full days of online classes risks systematically excluding millions of students.


Economic Strain on Families

The proposed system assumes that families can afford continuous internet usage. However, for many households, especially lower- and middle-income groups, the cost of sustained high-speed internet is prohibitive.

Online education is not a one-time expense—it requires:

  • Monthly broadband or mobile data packages

  • Smartphones or computers for each student

  • Backup power solutions in areas with electricity instability

For a country where many families already struggle with daily expenses, this policy could unintentionally shift the burden of national energy savings onto households.


The Six-Day School Week: A Recipe for Discontent

Alongside hybrid learning, the government is also considering extending the academic week from five to six days. (New Age)

This change could trigger dissatisfaction among students and parents alike. Traditionally, a five-day school week allows time for:

  • Rest and mental recovery

  • Extracurricular activities

  • Private tutoring, which is common in Bangladesh

A six-day system—combined with online workload—may lead to burnout and resistance. Bangladesh has a history of student-led protests on education-related issues, and such a shift could provoke similar reactions, especially if perceived as burdensome or poorly planned.


Urban Advantage vs Rural Disadvantage

The policy is expected to be implemented primarily in metropolitan areas initially. (thedailystar.net)

This highlights another concern: unequal implementation. Urban students, with better internet access and infrastructure, may benefit from the flexibility of hybrid learning. Meanwhile, rural students risk falling further behind, deepening the existing urban-rural education gap.

Such disparities contradict the principle of equitable education and could widen long-term socioeconomic divides.


A Silver Lining: Digital Infrastructure Growth

Despite its challenges, the proposed policy does carry potential benefits.

The demand for online education could accelerate:

  • Expansion of broadband networks

  • Increased competition among internet service providers

  • Growth of digital learning platforms

Urban centers, in particular, may see rapid improvements in internet speed and accessibility as providers respond to rising demand.

Moreover, such a policy could push Bangladesh further toward its “Digital Bangladesh” vision, fostering long-term transformation in education delivery.


Conclusion: Policy Ahead of Infrastructure

The idea of hybrid education is not inherently flawed—in fact, it aligns with global trends. However, in Bangladesh, the policy appears to be moving faster than the infrastructure needed to support it.

Without:

  • Universal and affordable internet access

  • Adequate digital devices

  • Reliable electricity and network stability

the system risks excluding the very students it aims to serve.

A more realistic approach would involve gradual implementation, targeted infrastructure development, and subsidies for disadvantaged students. Otherwise, what is envisioned as a modern educational reform may instead deepen inequality and trigger widespread dissatisfaction.

Mini RDBMS (with persistent storage) using only Python Standard Library

Mini RDBMS (with persistent storage) using only the Python Standard Library import re import json import os from typing import Any, Dict, Li...