Technology - Learn With Examples https://learnwithexamples.org/category/technology/ Lets Learn things the Easy Way Sat, 03 Oct 2026 14:05:50 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.3 https://i0.wp.com/learnwithexamples.org/wp-content/uploads/2026/07/cropped-learnwithexamples-icon.png?fit=32%2C32&ssl=1 Technology - Learn With Examples https://learnwithexamples.org/category/technology/ 32 32 228207193 What Does “Clearing Cache” Actually Clear? https://learnwithexamples.org/what-does-clearing-cache-actually-clear/ https://learnwithexamples.org/what-does-clearing-cache-actually-clear/#respond Sat, 03 Oct 2026 14:05:44 +0000 https://learnwithexamples.org/?p=954 Everyday tech · Browsers · Troubleshooting “Have you tried clearing your cache?” is the most repeated advice in technology, and most people follow it without knowing what they just deleted.…

The post What Does “Clearing Cache” Actually Clear? appeared first on Learn With Examples.

]]>
Everyday tech · Browsers · Troubleshooting

“Have you tried clearing your cache?” is the most repeated advice in technology, and most people follow it without knowing what they just deleted. Will you be logged out? Will you lose passwords? Does it make anything faster? This guide answers each of those questions with real examples, and shows the layers of caching you never knew existed.

The advice everyone gives and nobody explains

I have lost count of how many times, during years of supporting websites and teams, I have typed the sentence “try clearing your cache.” It works often enough that it has become a ritual, like switching a device off and on again. But rituals without understanding cause trouble. People clear everything, lose their saved logins, and then complain that the fix “broke” something. Others never clear anything and wonder why a website still looks like last year’s version.

The truth is that “the cache” is not one thing. There are many caches, living in different places, owned by different people. When someone says clear it, they might mean your browser, your phone app, your computer’s address book, a content delivery network, or a plugin on a web server. Knowing which one is the difference between a ten-second fix and an hour of confusion.

The one-sentence version. A cache is a temporary stored copy of something that was slow to fetch, kept so the next request is fast. Clearing it deletes those copies, which gets them re-downloaded fresh. It does not delete your passwords or bookmarks, and it normally does not log you out.

A cache in everyday life

Before the computer version, think of a kitchen. You could walk to the shop every time you need salt. Instead, you keep a small jar on the counter. Fetching from the jar takes a second, going to the shop takes twenty minutes. The jar is a cache.

It has the same properties as every digital cache. It is small, so it can only hold what you use often. It is a copy, so the shop still has the real thing. And it can go stale: if the shop changes the recipe on the salt, your jar still holds the old version until you refill it.

That last point is the source of nearly all cache problems. A cache is fast because it trusts old copies, and it is annoying when the trust is misplaced.

Why caches exist: speed, in numbers

Computers have a hierarchy of storage. Closer to the processor means faster and smaller, further away means slower and bigger. As a rough scale (these are order-of-magnitude figures that vary by machine), reading from the CPU’s own cache takes about a nanosecond, from main memory about a hundred nanoseconds, from a solid-state drive around a hundred microseconds, and from a server across the internet tens of milliseconds. That is a gap of millions of times between the fastest and slowest layers.

Caching exploits that gap. The system keeps copies of frequently used things closer, so it can skip the slow trip. A simple calculation shows how much this matters. Suppose a cache hit takes 5 milliseconds and a miss, which means going to the original source, takes 200 milliseconds.

0%25%50%75%100%010020085% hits: 34.2 msCache hit ratio (hit = 5 ms, miss = 200 ms). Average wait in ms on the vertical axis.
The more often the cache has what you need, the faster everything feels.

With no cache at all, every request waits 200 ms. If 85% of requests are hits, the average wait drops to 0.85 × 5 + 0.15 × 200 = 34.25 ms, nearly six times faster. At a 95% hit rate it is under 15 ms. The curve is a straight line, so every additional percent of hits is worth the same amount. That is why companies spend real money on caching.

The layers: who is caching what

This is the part most guides skip. Between you and a website, copies are stored in at least five different places.

CPU cache (L1, L2, L3)Built into the processor. Automatic.AutomaticBrowser cacheImages, CSS, JavaScript, fonts on your device.You can clearOperating system and DNS cacheRemembered website addresses and temp files.You can flushCDN or edge cacheCopies kept near visitors, for example by Cloudflare.Site owner purgesServer and page cacheReady-made pages on the website’s own server.Site owner purges
Five common cache layers. You can only clear some of them yourself.
  • CPU cache: tiny, ultra-fast memory built into the processor. It manages itself and you cannot clear it.
  • Browser cache: your browser saves images, stylesheets, scripts and fonts so repeat visits are quick. This is what “clear cache” normally refers to.
  • Operating system and DNS cache: your computer remembers which numeric address belongs to a website name so it does not ask again every time.
  • CDN cache: a content delivery network keeps copies of site files on servers around the world, close to visitors.
  • Server cache: the website itself may save ready-made versions of pages, so it does not rebuild them for each visitor.

A reader can clear only the second and third. The last two belong to whoever runs the site. If you publish websites yourself, as many of my readers do, you will deal with all five.

What your browser cache actually contains

Open any web page and your browser downloads a bundle of files: the page itself (HTML), stylesheets (CSS) that control appearance, scripts (JavaScript) that add behaviour, images, and fonts. Many of these rarely change. The logo on a site is the same on every page, so downloading it fresh each time would be wasteful.

The browser therefore stores these files, and the next time it needs them it can skip the download. Here is what that looks like for a typical page, using realistic but illustrative sizes.

First visit (empty cache): 1,850 KBJavaScriptImagesRepeat visit (warm cache): 60 KBonly the page itself is re-checkedIllustrative page. Real weights vary, but the pattern is typical.
First visit downloads everything. A warm cache re-checks only the page itself.

On a first visit this example page downloads 1,850 KB. On a repeat visit, only the 60 KB HTML needs to be fetched, a saving of about 97%. At a typical home connection of 10 Mbps, the first load needs about 1.5 seconds of transfer while the repeat takes a fraction of that. On a slow 2 Mbps mobile connection, the first visit would need around 7.4 seconds of transfer alone, which is exactly why the cache matters so much on phones.

How the browser decides whether to trust its copy

A cache that never refreshed would show you stale pages forever. So websites send instructions, in hidden headers, telling the browser how long a file stays fresh. A typical header says something like Cache-Control: max-age=86400, which means “this file is good for 24 hours.” Within that window, the browser uses its copy without even asking.

Browser needsa fileIn cache?yesStill fresh?yesUse local copyinstant, no downloadstaleAsk the server“has it changed?”304: keep copy200: new filenoDownload it
Fresh copies are used instantly. Stale ones are re-checked, and unchanged files are not downloaded again.

When a file goes stale, the browser does not always download it again. It can ask the server a cheaper question: “I have the version labelled with this tag. Has it changed?” The label is called an ETag. If the answer is no, the server replies with a tiny “304 Not Modified” message and the browser keeps using its copy. Only if the file changed does the server send the full new version.

Developers also use a trick called cache busting. When they update a stylesheet, they change its name or add a version number, for example style.css?v=42, so that the browser sees a brand-new file and fetches it. When this is forgotten, you get the classic symptom: new page, old styling.

Cache, cookies and history: the three things people confuse

This is where most of the damage and most of the fear come from. The “clear browsing data” screen in a browser lists several separate items. They are different things.

ItemWhat it holdsLogs you out?Safe to clear?
Cached images and filesCopies of site files for speedNoYes. Sites just reload slower once.
Cookies and site dataLogin tokens, preferences, cartsYes, usuallyYes, but expect to sign in again.
Browsing historyList of pages you visitedNoYes. Autocomplete suggestions shrink.
Saved passwordsCredentials your browser storesNoCareful. Make sure you know them first.
Autofill dataAddresses and cards you savedNoCareful. You will have to retype them.

The practical rule: if you only tick “cached images and files,” you will not lose logins or passwords. The mistakes happen when people press the big “clear all” button and tick every box. A moment of care is worth saving yourself a password-reset afternoon.

Five situations, five different fixes

Tap through the tabs. Each one shows a real problem and which layer to clear.

Site looks broken

A website was redesigned overnight, but on your screen the layout looks scrambled: new content with the old styling.

Windows / Linux:  Ctrl + Shift + R   (or Ctrl + F5)
macOS:            Cmd + Shift + R
Likely causeStale CSS
Try firstHard refresh
ThenClear cache
Time1 minute

What is going on. Your browser kept the old stylesheet and is pairing it with the new page. A hard refresh asks for fresh copies of everything on this page only. If that fails, clear “cached images and files” for the site. No logins are lost, because cookies are a separate item.

Phone storage full

Your phone says storage is almost full and a social app is using 3 GB.

Android: Settings > Apps > [app] > Storage > Clear cache
# Clear data / Clear storage also resets the app and signs you out
AndroidClear cache
DangerClear data
iPhoneOffload app
FreesHundreds of MB

What is going on. App caches hold thumbnails, videos and temporary files that the app can fetch again. Clearing the cache frees space with little downside, while clearing data wipes settings and logins. iPhones do not offer a per-app cache button, so people offload or reinstall the app instead.

Login problems

A website keeps looping you back to the login page, even though your password is correct.

Chrome: lock icon > Site settings > Delete data
# or Settings > Privacy > Delete browsing data > Cookies
CacheNot the cause
CookiesUsually it
TryClear site cookies
CostSign in again

What is going on. Sign-in problems are normally about cookies, not cache. Cookies hold the small token that says “this browser is logged in.” A damaged or outdated cookie confuses the site. Clearing cookies for that site fixes it, and you simply sign in again.

Site not loading

A website moved to a new server, and your computer still tries the old address while friends can open it fine.

# Windows
ipconfig /flushdns

# macOS
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
LayerDNS cache
Windowsipconfig /flushdns
Macdscacheutil
EffectNew address lookup

What is going on. Your operating system remembers which address belongs to a domain name for a while, to avoid repeating the lookup. Flushing that DNS cache forces a fresh lookup. It has nothing to do with your browser’s stored images.

You edited a post

You updated a WordPress article, but visitors (and you, logged out) still see the old version.

1. Save or update the post
2. Purge the page cache in your caching plugin
3. Purge the CDN cache (for example Cloudflare: Caching > Purge)
4. Hard refresh your browser
5. Test in a private window
Layers4
BrowserHard refresh
PluginPurge page cache
CDNPurge cache

What is going on. Site owners have more layers than readers. The plugin keeps ready-made pages, the CDN keeps copies near visitors, and every browser keeps its own. Work from the origin outward: plugin, then CDN, then your own browser, and check in a private window to avoid your own stale copy.

Notice that “clear the cache” was the right answer in only two of those five situations. In the others, the fix involved cookies, DNS, or the layers a site owner controls. That is the lesson of this whole article: ask which cache before you clear.

Hard refresh versus clearing everything

If a single website looks wrong, you rarely need to clear your entire browser cache. A hard refresh bypasses the cached copies for that page. On Windows and Linux you press Ctrl+Shift+R (or Ctrl+F5), and on a Mac, Cmd+Shift+R. It is the scalpel; clearing the whole cache is the sledgehammer.

Another trick I use constantly is the private or incognito window. It starts with no stored cache or cookies for that session, so if the site looks right there, you know the problem is a stale copy in your regular browser. If it looks wrong there too, the problem is not your cache at all: it is the server, the CDN, or the site itself.

If you run a website: the layers pile up

Readers have one cache to worry about. Site owners have several, and that is why “I updated it but it did not change” is such a common complaint. Imagine you fix a typo in a WordPress post and click Update.

  • The page cache plugin may keep serving the pre-built old page until it is purged.
  • The CDN may keep serving its copy from servers near your visitors until its rules expire or you purge it.
  • Each visitor’s browser may keep its own copy until it is stale.

The order matters. Clear from the source outward: plugin first, then CDN, then your own browser. If you clear the browser first, it simply re-downloads the stale copy from the layer above it. And always verify in a private window, because your own normal window is the layer most likely to mislead you.

The same thinking applies to design changes. Many themes and plugins also bundle CSS and JavaScript files. If a style tweak does not show, purge the plugin’s file cache, and then purge the CDN. A teammate of mine once spent a whole morning editing a stylesheet that was working perfectly; the browser was just refusing to fetch it.

Mobile phones: cache versus data

Apps cache aggressively. A social app saves thumbnails and video chunks so scrolling feels smooth, and over months this can grow into gigabytes. On Android, you can open the app’s storage screen and choose to clear the cache, which frees space and costs you nothing but a slightly slower first scroll afterward.

The same screen has a second button, usually called “Clear data” or “Clear storage.” This one is different and more drastic: it resets the app, signing you out and removing settings and sometimes locally stored files. People hit the wrong button all the time. Read the label twice.

On iPhone there is no per-app cache button. Options are to offload the app, which keeps its documents but removes the app files, or to delete and reinstall it. Safari has its own setting to clear history and website data, which removes the browsing history, cookies and cached files together.

When clearing the cache is a bad idea

  • Doing it daily out of habit. You throw away the speed benefits and re-download everything again and again.
  • Doing it on a metered connection. Re-downloading a heavy site’s files uses your data allowance.
  • Believing it protects your privacy. Cache is a small part of what sites know about you. Cookies, accounts and network logs are separate.
  • Using it as a cure for everything. Slow internet, a failing disk and an overloaded server will not improve.

Six myths about clearing cache (tap to open)

1. “Clearing cache deletes my passwords”

It does not. Passwords are stored separately. Only if you tick the password box in a “clear all” screen do they go.

2. “Clearing cache logs me out of everything”

Logins usually live in cookies. Clearing only cached images and files does not touch them.

3. “A bigger cache means a slower computer”

Not directly. A cache is designed to speed things up. A full phone with no free storage can struggle, though, so freeing space helps there.

4. “Clearing cache removes viruses”

No. Malware is a different problem and needs security software, not a cache clear.

5. “Private browsing never uses a cache”

It uses a temporary one that is discarded when you close the window. That is why it is useful for testing.

6. “If I clear my cache, the website is updated”

Only your own copy is refreshed. If the site’s server or CDN is serving old content, you will still see it.

Quick quiz: test yourself

Tap each question to reveal the answer and the reasoning.

What is a cache?
  1. A password manager
  2. A temporary stored copy that saves re-fetching or recomputing
  3. A type of virus
  4. A backup of your whole phone

A cache keeps a nearby copy of something expensive to get, so the next request is faster.

Will clearing your browser cache normally log you out of websites?
  1. No, logins live mostly in cookies
  2. Yes, always
  3. Only on Fridays
  4. Only on mobile

Cached images and files are separate from cookies. Clear cookies and site data, not cache, to be signed out.

A site you manage looks old after an update, even after you cleared your browser cache. Which other layers might be stale?
  1. Your keyboard
  2. The monitor
  3. Plugin, CDN or server page cache
  4. Nothing else

Site owners often have a page-cache plugin and a CDN, each holding its own copy. Purge from the origin outward.

What does a hard refresh do?
  1. Deletes your history
  2. Restarts the computer
  3. Signs you out
  4. Reloads the page while bypassing the cached copies for that page

It asks the server for fresh versions of the page’s files, without wiping your whole cache.

Which clear-data option on Android can sign you out of an app?
  1. Clear cache
  2. Clear data or storage
  3. Force stop
  4. Update

Clear data wipes the app’s stored data, including logins and settings.

Frequently asked questions

What does clearing cache actually do?

It deletes the saved copies of files, such as images, scripts and stylesheets, so they are downloaded fresh next time. It does not delete your passwords, bookmarks or, normally, your logins.

Is it safe to clear cache?

Yes. Nothing important is lost, because a cache only holds copies. The downside is that the next visits may load slower while the files are downloaded again.

What is the difference between cache and cookies?

Cache stores files to make pages load faster. Cookies store small pieces of data about you, such as a login token or preferences. Clearing cookies can sign you out; clearing cache usually will not.

How often should I clear my cache?

There is no schedule. Do it when a site looks outdated or broken, when something misbehaves, or when you need to free space. Clearing it daily just makes browsing slower.

Does clearing cache make my computer faster?

Not really. A cache exists to make things faster, so wiping it often does the opposite for a while. It helps only when the cache is corrupted or when low storage is the bottleneck.

What is cache invalidation?

It is deciding when a stored copy is no longer valid and must be replaced. It is famously difficult, and the engineer Phil Karlton is often quoted as saying that cache invalidation and naming things are the two hard problems in computer science.

The takeaway

Clearing the cache deletes saved copies, nothing more. Your passwords, bookmarks and, normally, your logins survive. The real skill is knowing which cache is misbehaving: your browser, your phone app, your computer’s DNS memory, or a layer owned by the website.

Next time something looks stale, start small: hard refresh, then a private window, then clear cached files for that site. Reach for the big clear-everything button last, and read each checkbox before you press it.

clear cachebrowser cachecookies vs cachehard refreshDNS cacheCDN cache

The post What Does “Clearing Cache” Actually Clear? appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-does-clearing-cache-actually-clear/feed/ 0 954
How Does a Credit Card Chip Stop Cloning? https://learnwithexamples.org/how-does-a-credit-card-chip-stop-cloning/ https://learnwithexamples.org/how-does-a-credit-card-chip-stop-cloning/#respond Sat, 03 Oct 2026 13:40:12 +0000 https://learnwithexamples.org/?p=951 Payments · Security · How it works That little gold square on your card is not decoration. It is a tiny computer, and it exists for one purpose: to make…

The post How Does a Credit Card Chip Stop Cloning? appeared first on Learn With Examples.

]]>
Payments · Security · How it works

That little gold square on your card is not decoration. It is a tiny computer, and it exists for one purpose: to make a stolen copy of your card worthless. Here is how a chip turns a payment into a one-time secret handshake, why the old magnetic stripe could be copied in seconds, and where fraud still gets through.

Reading time: about 16 minutesLevel: beginner friendlyTopic: payment security

The day cards stopped being copyable

Years ago I sat in a meeting with a fraud team at a mid-sized bank. A chart on the wall showed counterfeit card losses climbing for a decade. Then, a few months after chip cards went mainstream in a particular market, the line bent downward. Nobody in the room had changed their software or hired a hundred investigators. The only difference was a small piece of hardware inside the card.

Most people use the chip every day without ever wondering what it does. They insert the card, wait a moment, type a PIN, and carry on. In those few seconds, though, a carefully designed conversation takes place between the card, the terminal and your bank, and it is built so that anything a thief overhears is useless.

This article explains that conversation in plain language. You will learn why the magnetic stripe was easy to copy, what the chip does differently, how a one-time code defeats replay attacks, and what the chip cannot protect against. There are small interactive parts, real-world scenarios, a quiz and an FAQ.

The short answer. A magnetic stripe stores fixed data that can be copied and reused. A chip stores a secret key that never leaves it, and uses that key to create a fresh, one-time code for every payment. A copy of one transaction cannot be reused for another.

How the old magnetic stripe worked (and why it failed)

The magnetic stripe on the back of a card is a strip of tiny magnetised particles. It stores a short block of data: your card number, expiry date and a few service codes. When you swipe it, the reader simply reads that data out and sends it to the bank.

The critical weakness is that the data is static. It is the same on Monday as on Friday, at a petrol station as at a restaurant. Anything that can read it once can write it onto another card, because the card has no way of proving it is the original. It simply says the same words every time.

Think of it as showing a photocopy-able ID. If a stranger photocopies your ID card while you are not looking, the copy looks as good as the original to anyone who only checks the print. Criminals used devices called skimmers, hidden in card slots at ATMs, fuel pumps and ticket machines, to capture exactly this fixed data, then wrote it onto blank cards. This is what “cloning” means.

1234 5678 9012 3456VALID THRU 12/29Magnetic stripeSame fixed data on every swipe. Copy it once, clone it forever.1234 5678 9012 3456VALID THRU 12/29EMV chipA tiny computer. Its secret key never leaves the chip.
Same printed number on both cards. The difference is what is inside.

What the chip actually is

The standard behind chip cards is called EMV, named after its founders: Europay, Mastercard and Visa. Inside that gold plate is a tiny secure microcontroller, a very small computer with its own processor and memory, designed to resist tampering.

It does three jobs a stripe never could:

  • It stores a secret key that is built into the chip during manufacturing and is not designed to be read out. Only the card and the issuing bank know it.
  • It does calculations using that key. The terminal asks a question, and the chip works out an answer that only the real card could produce.
  • It counts. The chip keeps a transaction counter that goes up with every use, so no two payments look alike.

The crucial design principle is simple: the secret never leaves the chip. The terminal does not read the key. It only receives the results of calculations done with it. A recording of those results does not reveal the key, just as hearing someone’s signed answers does not reveal their private pen.

The one-time code: the cryptogram

When you pay, the terminal sends the chip the details of the sale: the amount, the currency, the date and a fresh random number it just generated. The chip mixes these with its internal counter and its secret key and produces a short code called a cryptogram.

AmountCurrencyDateTerminal random numberTransaction counterSecret card keyChip doesthe mathsCryptogramvalid once only
The cryptogram depends on both the details of this payment and the card’s secret key.

Your bank, which also holds the matching key material, performs the same calculation on its side. If the answer matches the cryptogram, the bank knows two things: the card is genuine, and the transaction details were not altered along the way. Change the amount by a rupee and the cryptogram no longer matches.

Because the terminal generates a new random number every time, and the chip’s counter keeps climbing, the cryptogram is different for every payment, even when you buy the same coffee at the same shop for the same price. A recorded cryptogram is a receipt for one specific event. It cannot be reused for a different purchase.

A toy version you can follow with a calculator

Real chips use serious cryptography, such as 3DES or AES-based message authentication codes. To make the idea visible, here is a deliberately simple toy version. Pretend the card’s secret key is 7, and the cryptogram is calculated as:

cryptogram = (amount × key + counter × 13 + random) mod 97a classroom toy, not real security

Here are four purchases by the same card with the same secret key.

CounterAmountTerminal randomCryptogram
41₹4503835
42₹1,2997110
43₹4,9991565
44₹450621

Look at the first and last rows. Both are purchases of ₹450, yet the cryptograms differ, because the counter and the terminal’s random number changed. Now imagine a thief recorded the ₹4,999 purchase, where the cryptogram was 65, and tries to reuse it for a new ₹4,999 purchase. The new terminal produces a different random number, and the bank expects the counter to have moved on. The bank calculates 85. That does not match 65, so the replay is declined.

Even this toy shows the heart of the matter: the proof of a payment is bound to that one payment. Real systems add much stronger maths so nobody can work backwards to the key, but the logic is the same.

The five steps of a chip payment

Chip cardTerminalIssuing bank1 Amount, date, random number2 Chip signs it: cryptogram3 Sends cryptogram to bank4 Bank checks it and approves5 Approval passed to the cardThe secret key stays inside the chip and inside the bank’s secure systems.
A simplified chip transaction. Real ones include a few extra checks, but this is the core.
  • Step 1: the terminal tells the card the details of the sale and a fresh random number.
  • Step 2: the chip signs those details with its secret key, producing a cryptogram.
  • Step 3: the terminal forwards the cryptogram to your bank.
  • Step 4: the bank recomputes it, checks your balance and fraud rules, and approves or declines.
  • Step 5: the approval comes back, and the transaction completes.

Notice what travels across the network. It is the transaction details and a cryptogram, not a reusable secret. A thief who taps into the cable, or plants a device inside the terminal, captures a record of a finished event.

Proving the card itself is real

There is a second layer. Terminals also check that the chip is a genuine card issued by a real bank, and not a clever fake that merely answers questions. EMV does this with digital signatures. The card carries data signed by the issuer, and the terminal can verify that signature using a chain of trusted certificates.

Different cards support different strengths of this check. The simplest, called static data authentication, proves that the card’s data was signed by the issuer. The stronger methods, dynamic and combined data authentication, make the card create its own signature for each transaction using a unique key pair inside the chip. A copy of the card data cannot do that, because the private key never leaves the original chip. For beginners, the takeaway is this: modern cards do not just claim to be real, they prove it, freshly, every time.

Proving you are the right person: PIN and friends

Authenticating the card is not the same as authenticating the cardholder. For that, chip cards support several methods.

  • Chip and PIN: you type a PIN. It is checked either by the chip itself or by your bank. Because the PIN is secret, a stolen card alone is much less useful.
  • Chip and signature: you sign a slip or screen. This is weaker and has been fading in many countries.
  • No verification: small contactless taps are often allowed without a PIN, up to a limit set by the bank and local rules.

In India, the Reserve Bank of India directed banks to migrate magnetic stripe cards to EMV chip and PIN cards by the end of 2018, and later rules gave cardholders control over how a card can be used, for example switching online, international or contactless use on and off in the bank’s app. Limits and rules do change, so check your own bank’s current settings.

How the world moved to chips

1960s–70sMagneticstripe appears1990sEMV standardcreatedMid-2000sUK chip andPIN rolloutOct 2015US liabilityshiftDec 2018India chipdeadline (RBI)
From a fixed stripe to a computer in your wallet.

The EMV standard was developed in the mid-1990s, and countries adopted it at different speeds. Several European markets moved first, with the UK rolling out chip and PIN in the mid-2000s. The United States was later, and a key push was the “liability shift” in October 2015: after that date, for most in-store payments, whichever side of the transaction had not upgraded (the merchant or the card issuer) became financially responsible for counterfeit fraud. That is a business rule rather than a technology, but it changed behaviour overnight, because shops that ignored chip terminals suddenly carried the cost.

Industry bodies in countries that completed the migration generally reported steep falls in counterfeit card fraud afterwards. I will not quote single numbers here because they vary by country and year, but the pattern was consistent: fraud on cloned physical cards dropped.

Real situations: where the chip helps and where it does not

Tap through six everyday situations to see what the chip is doing in each.

Tap at a cafe

You tap your card on a reader for a ₹180 coffee. Nothing is inserted and nothing is swiped.

Needs PINUsually no
CryptogramYes
Clone riskVery low
Typical limit₹5,000

What is happening. Contactless payments use the same chip, powered by the reader’s radio field over a few centimetres. The chip still creates a one-time cryptogram. Intercepting it gives a thief a code useful for one transaction only. Limits for no-PIN taps exist as a safety net, and banks set them, so check yours.

Insert and PIN

You insert your card at a shop and type your four- or six-digit PIN for a ₹12,000 purchase.

Needs PINYes
CryptogramYes
Clone riskVery low
ProofChip + PIN

What is happening. Two things are checked: the card is genuine (the chip answers the cryptogram challenge) and the person holds the secret (the PIN). A stolen card without the PIN is far less useful, and a copied card cannot answer the chip’s challenge at all.

Old stripe swipe

A small shop with an old terminal asks you to swipe the stripe, or the chip reader fails and falls back to the stripe.

Needs PINMaybe
CryptogramNo
Clone riskHigh
DataStatic

What is happening. This is the weak spot. A stripe holds fixed data, so a hidden skimmer that records it can write the same data onto a blank card. Banks watch for “fallback” transactions closely. If a chip reader keeps failing, treat it as a reason to pay another way.

Online shopping

You pay for shoes on a website by typing the card number, expiry and CVV.

Chip usedNo
Card numberTyped
Clone riskDifferent
DefenceOTP / 3-D Secure

What is happening. The chip is not involved, so it cannot protect you. Criminals who steal card numbers from breached websites or phishing pages use them online. That is why banks add one-time passwords, app approvals and card controls. After chips arrived in many countries, fraud shifted from counterfeit cards toward online use.

Petrol pump abroad

You travel and fill the tank at an unattended pump that has an older reader.

Needs PINVaries
CryptogramYes if chip
RiskTerminal type
TipPay inside

What is happening. Unattended terminals such as pumps and ticket machines were among the last to be upgraded in several countries, and they are easier for criminals to tamper with. Choose an attended counter when you can, and use a phone wallet, which adds its own protections.

Lost or stolen card

You realise your wallet is gone after a busy day.

First stepBlock it
WhereBank app
TimeMinutes
LiabilityReport fast

What is happening. Block the card in your bank’s app or helpline immediately. A chip stops copying, but it does not stop a thief from spending small amounts by tapping, so speed matters. Prompt reporting also protects you under most banks’ fraud rules.

Notice the pattern. The chip is strongest where it is actually used: insert or tap on a modern terminal. It is weakest where it is bypassed, which is on a magnetic stripe fallback and in online payments where you type your card number.

Where fraud went next

Security is a moving target. When you make one door hard to open, determined criminals look for another. After chips became common, three weak points became more attractive.

1. Card-not-present fraud

When you buy online, the chip is not part of the process. The website receives a card number, an expiry date and a security code, all of which can be stolen from a breached merchant, a phishing page or a malicious script. Banks respond with one-time passwords, app approvals, risk scoring and virtual card numbers. Many countries saw online fraud take up a larger share of the total as in-store counterfeiting shrank.

2. Magnetic stripe fallback

Some cards still carry a stripe so they work on old terminals. A terminal that cannot read the chip may offer a swipe instead. Criminals sometimes try to force that fallback, for example by damaging a card, so issuers treat fallback transactions with suspicion and may decline them. If a chip reader keeps failing on your card at a shop, the sensible response is to pay another way, not to swipe.

3. Social engineering

No chip can stop you from reading out a one-time password to a stranger posing as your bank. Scams that trick people into approving payments themselves are among the fastest-growing problems, because the technology cannot tell a genuine you from a convincing story. Your bank will never ask you to share a PIN or OTP, so any call that does is a red flag.

Contactless and phone wallets: the same idea, one step further

Tapping a card works through short-range radio, and the chip behind it still creates a one-time cryptogram. Phone wallets add another layer called tokenisation: instead of your real card number, the phone stores a substitute number valid only for that device. If a merchant’s systems are breached, the thief gets a token that is useless elsewhere. Pairing this with your fingerprint or face unlock means a payment needs something you have and something you are.

That is why security people often suggest a phone wallet for travel or for unfamiliar shops. It combines the chip’s protection with tokenisation and biometric confirmation.

Eight habits that keep your card safe

  • Insert or tap rather than swipe whenever a chip option exists.
  • Cover the keypad when you type your PIN. Hidden cameras still work against humans.
  • Turn on instant alerts for every transaction in your bank’s app.
  • Use card controls to disable online, international or contactless use when you do not need them.
  • Prefer wallets or virtual cards for online purchases and unfamiliar sites.
  • Look at the terminal. Loose parts, odd overlays or a card slot that wobbles are warning signs, especially at unattended machines.
  • Never share OTPs or PINs, even with someone who sounds official.
  • Report loss at once. Block the card in the app first, then call the bank.

Six common myths (tap to open)

1. “A chip makes my card unhackable”

It makes physical cloning far harder, but it does nothing against stolen card numbers used online, scams that trick you, or a stripe fallback on an old terminal.

2. “Someone can copy my chip by standing near me”

Contactless chips talk only over a few centimetres, and even a recorded exchange gives a one-time code that cannot be reused for another purchase.

3. “The chip stores my PIN where thieves can read it”

Cards are designed so the PIN and keys are not readable from outside. Verification happens inside the chip or at your bank.

4. “If the cryptogram is stolen, they can spend my money”

A stolen cryptogram belongs to one transaction. Replaying it fails because the bank expects a different value each time.

5. “Contactless is always unsafe”

It uses the same chip security. The practical risk is small unauthorised taps if the card is stolen, which alerts, limits and quick blocking handle.

6. “Chips ended card fraud”

They ended much of the easy fraud and pushed criminals toward online and social-engineering methods, so vigilance still matters.

Quick quiz: test yourself

Tap each question to reveal the answer and the reasoning behind it.

Why can a magnetic stripe be cloned easily?
  1. It uses too much power
  2. It stores fixed data that is the same every time
  3. It has no number printed on it
  4. It only works abroad

The stripe holds static data. Anyone who reads it can write the same data onto another card.

What does the chip create for every transaction?
  1. A new card number
  2. A photograph
  3. A one-time cryptogram
  4. A new PIN

The chip combines transaction details and a counter with its secret key to produce a cryptogram that is valid only for that transaction.

A thief records the cryptogram from your ₹4,999 purchase and tries to reuse it. What happens?
  1. The bank rejects it because the transaction details and counter do not match
  2. The bank approves it
  3. The chip refunds you
  4. The card number changes

The expected cryptogram depends on the amount, the random number and the counter. A replay does not match, so it is declined.

Which type of fraud did chips NOT stop?
  1. Counterfeit in-store cards
  2. Skimmed copies used at chip terminals
  3. Lost cards used with a PIN check
  4. Card-not-present fraud online

Online payments do not use the chip, so stolen card numbers can still be misused there. Banks add extra checks such as one-time passwords.

Where does the chip’s secret key live?
  1. On the printed card number
  2. Inside the chip, never sent out
  3. On the terminal
  4. On the receipt

The key stays inside the chip’s secure hardware (and in the bank’s secure systems). Only results of calculations leave the chip.

Frequently asked questions

How does a chip stop card cloning?

The chip holds a secret key that never leaves it, and uses that key to create a fresh one-time cryptogram for each payment. A thief who records the exchange gets a code that works for that transaction only, and cannot copy the key.

Can chip cards be cloned at all?

Copying the secret key out of a modern chip is not practical for ordinary criminals. The realistic weak points are fallback to the magnetic stripe, tampered terminals and online card-number theft, which is why the stripe is still a risk.

Why do cards still have a magnetic stripe?

For backwards compatibility with older terminals, mainly outside countries that completed migration. As terminals upgrade, many issuers are moving toward cards without one.

Is contactless payment safe?

Contactless uses the same chip and cryptogram idea. The main risk is small unauthorised taps if a card is stolen, so keep the limits sensible, enable alerts and report loss quickly.

What is the difference between chip and PIN and chip and signature?

Both use the chip to prove the card is genuine. They differ in how the cardholder is verified: a PIN that only you know, or a signature, which is weaker and less used today.

Does a chip protect online purchases?

Not directly, because the chip is not used when you type your card details into a website. Protection comes from extra authentication such as one-time passwords, app approvals, tokenised wallets and virtual cards.

The takeaway

A magnetic stripe says the same thing every time, so anyone who hears it can repeat it. A chip answers a fresh question every time, using a secret that never leaves the card, so a recording is useless. That is the whole trick: replace a fixed password with a one-time proof.

The chip is not magic. It stops physical cloning, but not stolen numbers online or a convincing phone call. Use the chip, switch on alerts and treat OTPs as secrets, and you will have taken advantage of nearly everything this clever piece of engineering offers.

EMV chipcard cloningcryptogramchip and PINcontactless paymentscard security

The post How Does a Credit Card Chip Stop Cloning? appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/how-does-a-credit-card-chip-stop-cloning/feed/ 0 951
Git and GitHub Explained for Beginners (With Real Examples) https://learnwithexamples.org/git-and-github-explained/ https://learnwithexamples.org/git-and-github-explained/#respond Sat, 03 Oct 2026 12:37:11 +0000 https://learnwithexamples.org/?p=948 Version control · Beginner guide · Hands-on If you have ever saved a file as report_final_v2_REAL_final.docx, you already understand why Git exists. It is the grown-up version of that habit:…

The post Git and GitHub Explained for Beginners (With Real Examples) appeared first on Learn With Examples.

]]>
Version control · Beginner guide · Hands-on

If you have ever saved a file as report_final_v2_REAL_final.docx, you already understand why Git exists. It is the grown-up version of that habit: a tool that remembers every version of your work, lets you travel back in time, and lets a team edit the same project without overwriting each other. GitHub is where those projects usually live online. This guide explains both from zero.

Reading time: about 18 minutesLevel: complete beginnerTools: a terminal and a free GitHub account

The problem Git solves

I started programming long before Git was everywhere, and I remember what folders looked like in those days. site_backup, site_backup_old, site_NEW, site_NEW_fixed, and one called site_dont_touch. Nobody knew which was current. When a client said “the version from last Tuesday was better,” the honest answer was often “I think I overwrote it.”

Now picture a team of five editing the same files. Two people change the same paragraph. Someone emails a zip file. Someone else works from an older copy. Merging all of that by hand is miserable, and mistakes are guaranteed.

Version control is the fix. Instead of copying folders, you tell a tool when you have reached a meaningful point, and it stores a snapshot. The most popular version control system in the world is Git, created in 2005 by Linus Torvalds for the Linux kernel. Today it is used by solo students, small studios and the largest software companies alike.

The one-sentence version. Git is a tool on your computer that records snapshots of your project over time. GitHub is a website that stores your Git projects online so you can back them up, share them and collaborate.

Git vs GitHub: the part everyone mixes up

Beginners often use the two names as if they were one thing. They are not, and the difference matters.

  • Git is software that runs on your own computer. It works offline. It does the actual tracking of changes.
  • GitHub is a company’s website (owned by Microsoft) that hosts Git repositories in the cloud and adds features around them: pull requests, issue tracking, code review and project pages.

The analogy I use in workshops: Git is a camera, and GitHub is the photo-sharing site. You can take photos without ever uploading them, but the website makes it easy to back them up and show them to others. Similar sites exist, including GitLab and Bitbucket. They all speak Git.

QuestionGitGitHub
What is it?A version-control programA hosting website and platform
Where does it run?On your computerOnline, in the cloud
Needs internet?NoYes
Main jobTrack and organise your changesStore, share and review them with others
AlternativesMercurial, SubversionGitLab, Bitbucket

The vocabulary you need (and nothing more)

Git has a reputation for jargon. In reality, you need about eight words, and each has a plain-English meaning.

TermPlain meaningEveryday analogy
repositoryA project folder that Git tracks, with its full historyA filing cabinet with every past version
commitA saved snapshot with a messageA save point in a video game
branchA separate line of workA parallel draft you can experiment in
mergeCombining one branch into anotherPasting your draft into the main document
cloneCopying a repository to your computerDownloading the whole cabinet
remoteA copy of the repository hosted elsewhereThe cloud backup
push / pullSend your commits up / bring others’ commits downUpload and download
pull requestA request to merge your branch, with review“Please check my work before it goes in”

How a change travels through Git

This is the single most useful mental model in the whole subject, and almost every beginner tutorial skips it. A change passes through four places.

Working folderfiles you editStaging areawhat goes nextLocal repoyour saved historyGitHubcopy in the cloudaddcommitpushpullThe first three live on your computer. Only the fourth is online.YOUR COMPUTER
Edit in the working folder, stage what you want, commit it to history, then push it online.
  • Working folder: the files you see and edit on your computer.
  • Staging area: a waiting room where you choose exactly which changes go into the next snapshot.
  • Local repository: the saved history of commits, stored in a hidden .git folder.
  • Remote (GitHub): the copy online that teammates can reach.

The staging area surprises people. Why not save everything at once? Because it lets you craft tidy commits. Imagine you fixed a typo and also started a risky new feature in the same afternoon. Staging lets you commit the typo fix by itself, with a clear message, and leave the unfinished feature for later.

Setting up: install and introduce yourself

Download Git from the official site (git-scm.com) or install it with your system’s package manager. Then check that it works.

git --version

Next, tell Git who you are. Every commit carries a name and email, so this is a one-time setup.

git config --global user.name "Your Name"
git config --global user.email "[email protected]"
git config --global init.defaultBranch main

The last line makes new repositories start with a branch called main, which matches what GitHub uses today. Older installs may still default to master, so setting it avoids confusion.

Your first repository, step by step

Let us track a small recipe collection. Open a terminal, make a folder and start Git inside it.

mkdir recipes
cd recipes
git init

Git replies with something like:

Initialized empty Git repository in /home/you/recipes/.git/

Now create a file called pasta.txt with three lines of text in any editor, then ask Git what it sees.

git status

On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	pasta.txt

nothing added to commit but untracked files present (use "git add" to track)

“Untracked” means Git sees the file but is not recording it yet. git status is your best friend: run it constantly, especially when confused. Now stage the file and commit it.

git add pasta.txt
git commit -m "Add pasta recipe"

[main (root-commit) a1b2c3d] Add pasta recipe
 1 file changed, 3 insertions(+)
 create mode 100644 pasta.txt

Congratulations, you have made your first snapshot. The odd string a1b2c3d is the start of a commit’s unique ID. (Yours will look different; the examples here use made-up IDs.) Add a sauce recipe and a typo fix the same way, and your history looks like this.

git log --oneline

1f2e3d4 (HEAD -> main) Add dessert
7c8d9e0 Fix typo
e4f5a6b Add sauce
a1b2c3d Add pasta recipe
a1b2c3dAdd pastae4f5a6bAdd sauce7c8d9e0Fix typo1f2e3d4Add dessertmain ← HEAD
Each commit points back to the one before it. HEAD marks where you are now.

Every dot in that chain is a version you can return to. That is the whole magic: history becomes a thing you can read, search and travel through.

Writing commit messages people will thank you for

A commit message is a note to your future self, and to everybody else. Compare these two histories:

  • “stuff”, “fix”, “fix 2”, “asdf”
  • “Add login form validation”, “Fix crash when email is empty”, “Remove unused styles”

The second tells a story. A few habits help: write in the imperative (“Add”, not “Added”), keep the first line under about 50 characters, and describe what and why, not how. Six months later, when something breaks, you will be searching that history for answers, and clear messages turn a two-hour hunt into a two-minute one.

Telling Git what to ignore

Not every file belongs in version control. Passwords, API keys, temporary files and huge generated folders should stay out. Create a plain text file named .gitignore and list patterns.

.env
node_modules/
*.log
.DS_Store

This is more than tidiness. Never commit secrets such as API keys or passwords. Once something is pushed to a public repository, bots can find it within minutes. If it happens, rotate the key immediately. Deleting the file later does not erase it from history.

Branches: safe places to experiment

A branch is simply a movable label on a line of commits. Your main branch holds the version that works. When you want to try something, you create a new branch, work there, and leave main untouched.

git switch -c feature/bigger-portions
# edit files, then
git add pasta.txt
git commit -m "Increase pasta portion size"

Think of it as photocopying a document to scribble on, with the guarantee that the original stays clean. If the idea works, you merge it in. If it does not, you delete the branch and nothing is lost.

mainfeature/searchmerge commitWork on the side, then join it back. Main stays safe in the meantime.
A feature branch splits off main, collects its own commits, and merges back.

When you are ready, switch back to main and merge.

git switch main
git merge feature/bigger-portions

Merge conflicts are not scary

Sometimes two branches change the same line. Git cannot guess which you want, so it stops and asks you to decide. It marks the file like this.

<<<<<<< HEAD
Use 200g of spaghetti
=======
Use 250g of spaghetti
>>>>>>> feature/bigger-portions

The top part is your current branch, the bottom part is the incoming one. Edit the file to keep what you want (and delete the marker lines), then git add it and git commit. A conflict is just Git being polite and asking a question. In teams, conflicts become rare once people commit small changes often and pull regularly.

Bringing in GitHub

So far everything has lived on your computer. Now let us put it online. Create a free account at github.com, click the button to create a new repository, and name it recipes. GitHub will show you the web address of your empty repository. Connect your local project to it and upload.

git remote add origin https://github.com/YOU/recipes.git
git branch -M main
git push -u origin main

Here origin is just the nickname Git gives to your main remote. The -u flag remembers the connection so that later you can type only git push and git pull.

A practical note on logging in: GitHub no longer accepts your account password for Git operations over HTTPS. Use a personal access token, set up SSH keys, or install the GitHub CLI or Git Credential Manager, which handle sign-in for you. Their setup pages walk through it in a few minutes.

To get a project that already exists on GitHub onto your machine, you clone it.

git clone https://github.com/YOU/recipes.git

That downloads every file and the whole history, and sets up origin automatically.

Pull requests: how teams actually work

On a team, nobody pushes straight to main. Instead, the loop looks like this.

1 Branchgit switch -c2 Commitgit commit3 Pushgit push4 Pull requestreview5 Mergethen pullThe loop almost every team repeats several times a day.
Branch, commit, push, open a pull request, merge. Repeat.

A pull request (often shortened to PR) is a page on GitHub that shows exactly what changed between your branch and main. Teammates can comment on specific lines, request changes and approve. When everyone is happy, someone clicks Merge. Automated checks, such as tests, can run on the PR too, so a broken change is caught before it reaches the shared code.

I have watched this process save projects. A new developer once pushed a change that would have deleted a customer table. Two people spotted it in review because the diff showed hundreds of red lines where there should have been five. Without a pull request, that change would have gone straight to production.

Five real situations, five workflows

Tap through the tabs. Each one shows a realistic scenario with the actual commands.

Solo project

You are writing a small recipe book as text files and want a safety net. No team, no internet needed.

git init
git add pasta.txt
git commit -m "Add pasta recipe"
git log --oneline
Commands4
RiskNone
WhereYour PC
Needs GitHubNo

Why it works. Each commit is a snapshot you can return to. After a month of edits you can look back and see exactly when the sauce recipe changed, and why.

Undo mistakes

You edited the wrong file, or committed something you regret. Git has a different tool for each size of mistake.

# discard edits you have not committed
git restore pasta.txt

# take a file back out of the staging area
git restore --staged pasta.txt

# undo a commit by adding a new opposite commit
git revert 7c8d9e0
Safestrestore
Safe on sharedrevert
Dangerousreset –hard
TimeSeconds

Why it works. Use restore for uncommitted edits, and revert when the commit has already been shared, because it leaves history intact. Treat reset –hard as the sharp knife: it can throw work away.

Team feature

You and three colleagues are adding a search bar to a website. Nobody should break the working version.

git switch -c feature/search
# ...edit files...
git add .
git commit -m "Add search box"
git push -u origin feature/search
# open a pull request on GitHub, get a review, merge
git switch main
git pull
Branches1 each
ReviewPull request
Safe mainYes
People2 to 20

Why it works. Everyone works on their own branch, then proposes changes with a pull request. A teammate reads the changes before they reach main. That review step catches more bugs than most people expect.

Open source

You found a typo in a popular project’s documentation and want to fix it, but you are not a maintainer.

# click Fork on GitHub, then:
git clone https://github.com/YOU/project.git
cd project
git switch -c fix-typo
# fix the typo, then
git commit -am "Fix typo in README"
git push -u origin fix-typo
# open a pull request to the original project
Step oneFork
Step twoClone
ThenBranch
FinishPull request

Why it works. A fork is your personal copy of someone else’s repository on GitHub. You change your copy and ask the owners to pull your change in. This is how thousands of strangers contribute to the same project.

Publish a site

You built a one-page portfolio and want it online without paying for hosting.

git add index.html
git commit -m "Launch portfolio"
git push origin main
# On GitHub: Settings, Pages, deploy from branch main
HostGitHub Pages
CostFree tier
Filesindex.html
Updategit push

Why it works. GitHub Pages serves static files straight from a repository. After setup, every push updates the live site. Your history doubles as a deployment log.

You will notice the same handful of commands appearing in every tab. That is the good news: the entire daily workflow of most developers is built from perhaps ten commands.

A beginner’s cheat sheet

CommandWhat it doesWhen to use it
git statusShows what has changed and what is stagedConstantly. Any time you are unsure.
git add <file>Stages a file for the next commitBefore every commit
git commit -m “msg”Saves a snapshot of staged changesAfter each small, finished step
git log –onelineLists past commits in short formTo see history
git diffShows exact line changes not yet stagedBefore staging, to review your work
git switch -c nameCreates and switches to a new branchStarting a new task
git merge nameMerges a branch into the current oneFinishing a task locally
git pushUploads commits to the remoteSharing or backing up your work
git pullDownloads and merges remote changesStart of your working day
git clone <url>Copies a remote repository to your computerJoining an existing project
git restore <file>Discards uncommitted edits to a fileWhen an experiment went wrong
git revert <id>Undoes a commit by adding an opposite oneUndoing something already shared

A daily routine you can copy

  • Morning: run git switch main and git pull so you start from the latest version.
  • Before starting a task: create a branch with git switch -c and a descriptive name.
  • While working: run git status and git diff often, and commit each small finished step.
  • When done: push the branch and open a pull request.
  • After the merge: switch back to main, pull, and delete the old branch.

It feels like a lot at first, and then one day you realise you have stopped thinking about it. That is when Git becomes a superpower instead of a chore.

Seven mistakes beginners make (tap to open)

1. Committing everything with a vague message

Messages like “update” tell nobody anything. Take ten seconds to describe the change. Your future self is the main beneficiary.

2. Committing secrets and API keys

Add sensitive files to .gitignore from day one. If a key leaks, revoke it immediately; deleting the file later does not remove it from history.

3. Working directly on main

Even solo, branches give you a safe place to experiment. On teams, working on main is how broken code reaches everyone.

4. Forgetting to pull before pushing

If a teammate has pushed since you last pulled, your push may be rejected. Pull first, resolve any conflicts, then push.

5. Using git reset –hard without thinking

It can destroy uncommitted work permanently. Prefer git restore for single files and git revert for shared commits unless you are certain.

6. Giant commits that mix unrelated changes

A commit with a bug fix, a refactor and a new feature is hard to review and hard to undo. Stage and commit them separately.

7. Panicking at a merge conflict

A conflict is a question, not a failure. Read the markers, choose what to keep, remove the markers, add, and commit.

Quick quiz: test yourself

Tap each question to reveal the answer and the reasoning.

What is the difference between Git and GitHub?
  1. They are the same thing
  2. Git is a website and GitHub is a program
  3. Git is the version-control tool on your computer, GitHub is an online home for Git repositories
  4. GitHub is only for photographers

Git tracks changes locally. GitHub hosts repositories online and adds collaboration features such as pull requests.

Which command moves changes from the working folder into the staging area?
  1. git add
  2. git commit
  3. git push
  4. git clone

git add stages changes. git commit then saves the staged snapshot into history.

You edited a file but have not committed. How do you throw those edits away safely?
  1. git push –force
  2. git restore <file>
  3. git merge
  4. git fork

git restore puts the file back to its last committed state. Be sure you want to lose those edits first.

What is a pull request?
  1. A command that downloads files
  2. A way to delete a branch
  3. A backup of your computer
  4. A proposal to merge your branch, with a place for review and discussion

A pull request asks the project to pull your changes in, and lets teammates review them first.

Which file stops Git from tracking things like passwords and build folders?
  1. README.md
  2. LICENSE
  3. .gitignore
  4. package.json

List patterns in .gitignore for files Git should leave alone. Secrets that were already committed need extra steps, so never commit them in the first place.

Frequently asked questions

Do I need GitHub to use Git?

No. Git works completely on your own computer. GitHub is optional, but it makes backup, sharing and teamwork much easier. GitLab and Bitbucket are alternatives.

What is a repository?

A repository, or repo, is a project folder that Git tracks, along with the full history of its changes stored in a hidden .git folder.

What is the difference between git pull and git fetch?

git fetch downloads new history from the remote without changing your files. git pull fetches and then merges it into your current branch.

What does git clone do?

It copies an entire repository from a remote location such as GitHub to your computer, including its history, and sets up the connection called origin.

How often should I commit?

Commit whenever you finish a small, meaningful step that you could describe in one sentence. Small commits are easier to review and easier to undo.

What if I committed a password by mistake?

Treat it as compromised: change the password or revoke the key right away. Removing it from history is a separate, harder job, so rotating the secret comes first.

The takeaway

Git remembers every version of your project, GitHub keeps a copy online and helps people work together, and the daily routine boils down to a few commands: status, add, commit, push, pull, and switch. You do not need to master everything. You need to commit small, write clear messages, work on branches and never commit secrets.

Make a practice repository today. Add three files, make five commits, create a branch, merge it, push it to GitHub. An hour of doing beats a week of reading, and you will never again have a folder called “final_v2_REAL_final.”

GitGitHubversion controlgit commandspull requestfor beginners

The post Git and GitHub Explained for Beginners (With Real Examples) appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/git-and-github-explained/feed/ 0 948
What Are Tokens and Context Windows? https://learnwithexamples.org/what-are-tokens-and-context-windows/ https://learnwithexamples.org/what-are-tokens-and-context-windows/#respond Tue, 04 Aug 2026 09:21:42 +0000 https://learnwithexamples.org/?p=814 LearnWithExamples A language model never actually sees your sentence. It sees a stream of numbered fragments, and it can only hold so many of them at once. Understand those two…

The post What Are Tokens and Context Windows? appeared first on Learn With Examples.

]]>

LearnWithExamples

A language model never actually sees your sentence. It sees a stream of numbered fragments, and it can only hold so many of them at once. Understand those two facts and almost every strange AI behaviour you have ever run into suddenly has an explanation.

I have been building things on top of language models since the days when “context window” meant 512 fragments and you budgeted them like a family budgets grocery money. The hardware got better. The models got enormous. And yet, in workshop after workshop, the same two questions come up first — and they are almost always asked in the wrong order.

People ask “why did the AI forget what I told it?” before they ask “what exactly is the AI storing in the first place?” That is like asking why your suitcase won’t close before checking what you packed. So let’s do it properly. First we’ll open up a token — see it, split it, count it. Then we’ll build the window it lives inside, and watch what happens when the window fills up.

By the end you’ll be able to look at a prompt and estimate its cost in your head, explain why the model insists “strawberry” has two Rs, know why Hindi or Tamil text costs nearly triple what English does, and — most usefully — know exactly what to trim when a system tells you your input is too long.

The 30-second answer

Tokens and context windows, defined

A token is the smallest chunk of text a language model actually reads. Usually it’s a piece of a word — roughly ¾ of an English word on average. The model converts every token into a number before it does anything else. Text in, numbers out.

A context window is the maximum number of tokens the model can have in front of it at one time — your instructions, the uploaded file, the entire chat history, plus the reply it is currently writing. It’s a hard ceiling, not a soft suggestion. Nothing outside it exists as far as the model is concerned.

Tokens are the units. The context window is the container. Everything else in this article is a consequence of those two sentences.

Part 1 — A token is not a word

Here is the first mental model most beginners build, and it is wrong: “the AI reads word by word, like I do.” Reasonable guess. Also the source of about half the confusion I see.

Think about why splitting on words fails. English alone has well over a million distinct word forms once you include names, typos, plurals, brand names, hashtags, and the thing your colleague types when they mean “definitely.” A model would need a lookup table with a million-plus entries, and the moment somebody typed Kanniyakumari or ngrok or bruhhhh, the table would shrug and return “unknown.”

Now try the opposite extreme: split on characters. Only about a hundred symbols to memorise — clean, complete, nothing is ever unknown. But now the word “encyclopedia” costs twelve slots instead of one, and the model has to learn spelling from scratch before it learns meaning. Sequences get impossibly long, and long sequences are expensive (we’ll get to why).

So the field landed in the middle. Subword tokenization: keep whole tokens for the text fragments that show up constantly, and break rare things into smaller pieces that can be reassembled. Common stuff is cheap. Weird stuff still works, just costs more.

Split by words

Tiny sequences, impossible vocabulary. Any unseen word breaks it. Rejected.

Split by characters

Tiny vocabulary, endless sequences. Nothing breaks, but everything is slow. Rejected.

Split by subwords

Frequent chunks stay whole, rare chunks get split. This is what every major model uses today.

Watch it happen

Reading about tokenization is far less convincing than watching a sentence get shredded. Type into the box below — or hit one of the preset buttons — and see the fragments appear. Each coloured block is one token. Notice the little spaces sitting inside the blocks: in most tokenizers a leading space is part of the token, which is why the and the are two different entries entirely.

Live token splitter

estimate · type to update
0Tokens
0Words
0Characters
0Tokens / word

Grey <byte> blocks are the extra tokens spent on characters outside the basic Latin set. This tool approximates real byte-pair encoding closely enough to build intuition — exact counts vary a little between model families.

How the splitting rules get invented

Nobody sits down and hand-writes the list of fragments. It’s learned from data, most often with an algorithm called Byte Pair Encoding (BPE). The idea is almost embarrassingly simple, and you can run it on paper.

Suppose your entire training corpus is these three words, repeated a lot:

RoundWhat the algorithm seesMost frequent adjacent pairNew merged token
Startl o w · l o w e r · l o w e s tl + olo
2lo w · lo w e r · lo w e s tlo + wlow
3low · low e r · low e s te + rer
4low · low er · low e s te + ses
5low · low er · low es tes + test

Five rounds and the algorithm has independently discovered the root low and the suffixes er and est — real English morphology, learned purely by counting. Run this for millions of rounds on a slice of the internet and you get a vocabulary of roughly 50,000 to 200,000 fragments, ordered by how useful they are.

Two consequences fall straight out of this, and both matter in practice:

  • Frequency decides price. Text that looked like the training data gets packed efficiently. Text that didn’t gets shredded into crumbs. Your name is probably one token if you’re called David and five tokens if you’re called Devanshi.
  • The vocabulary is frozen at training time. A model trained mostly on English carries an English-shaped tokenizer forever. It can still read Hindi, Swahili, or Korean — it just pays a heavier toll per sentence.
Example you can feel

Type “Learning is fun” into the splitter above, then type the same sentence in Hindi. English: about 3–4 tokens. Hindi: often 15–25. Same meaning, four to six times the cost. If you build a product for an Indian audience and price it per token, this single detail can decide whether your unit economics work.

Part 2 — Token maths you can do in your head

You will rarely need an exact count. You will constantly need a fast estimate: will this fit? These are the ratios I have used for years, and they hold up well enough for planning.

Rule of thumbApproximate valueHow to use it
English words → tokens1 word ≈ 1.3 tokensMultiply your word count by 4/3.
Characters → tokens4 characters ≈ 1 tokenFastest check: divide character count by 4.
A typical page of prose≈ 600 tokens450 words per double-spaced page.
Source code1 line ≈ 8–12 tokensIndentation and punctuation are surprisingly costly.
Meeting transcript1 minute ≈ 200 tokensSpeech runs near 150 words per minute.
Non-Latin scripts2–4× the English costDevanagari, Tamil, Thai, Arabic, Korean.
Emoji1 emoji ≈ 2–4 tokensSkin-tone and family emoji are the worst offenders.

Let’s apply them to things you actually handle:

A WhatsApp message

~25 words → ≈ 33 tokens. You could send 6,000 of these before filling a 200K window.

A one-page résumé

~600 words → ≈ 800 tokens. Screening 100 résumés at once is genuinely feasible.

A 12-page contract

~6,000 words → ≈ 8,000 tokens. Comfortable in any modern window.

A 90-minute meeting

~13,500 words → ≈ 18,000 tokens. Fine alone; painful if you also attach the slides.

A 300-page novel

~100,000 words → ≈ 133,000 tokens. Fits in a large window, with room to spare for questions.

A mid-size codebase

40,000 lines → ≈ 400,000 tokens. This is where retrieval stops being optional.

Part 3 — The five places tokenization gets weird

This is the part of the article I’d tell my past self to read first. Almost every “the AI is stupid” complaint I have investigated turned out to be a tokenizer artefact, not a reasoning failure.

1. The model cannot reliably count letters

Ask a model how many times the letter R appears in “strawberry” and you may get “two.” People post screenshots of this as proof that AI is a parlour trick. What actually happened is subtler: the model never received the letters. It received something like str + aw + berry — three opaque ID numbers. Asking it to count Rs is like asking you to count the letters in a word someone spelled out in Morse code, at speed, without writing anything down. Not impossible, but a genuinely awkward task given the input.

Fix it in practice

Force the letters apart before asking: s-t-r-a-w-b-e-r-r-y. Hyphenating breaks the word into single-character tokens and accuracy jumps immediately. Same trick works for reversing words, counting syllables, and checking palindromes.

2. Numbers split in unhelpful places

Depending on the tokenizer, 148392 might become 148+392, or 1+48+39+2. The digits do not line up in neat place-value columns the way they do on paper, which is a large part of why models were historically shaky at long arithmetic. It also means an invoice number, a PAN, an order ID, or a phone number can be far more expensive than its length suggests — and is easier to mis-copy.

3. A trailing space quietly poisons your prompt

If your prompt ends with "The answer is " — with a space after “is” — you have handed the model a dangling space token and asked it to continue. But the natural next token is " 42", which already includes its own leading space. You’ve created a conflict the model must work around, and quality drops for no visible reason. Fifteen years in, and I still occasionally lose twenty minutes to a stray space at the end of a template string.

4. Whitespace is a real line item in code

Deeply indented code, four-space tabs, blank lines between functions — every bit of that costs tokens. A well-formatted 500-line Python file can cost noticeably more than the same logic minified. This is not an argument for writing ugly code; it is an argument for sending the model the three functions that matter instead of the whole file.

5. Rare and mixed-script text costs a fortune

Scientific nomenclature, chemical formulas, Sanskrit terms, transliterated place names, base64 blobs, UUIDs, and minified JavaScript all tokenize horribly. A single UUID can eat 20+ tokens. If you are pasting logs full of them, you are burning most of your budget on strings the model does not need to read carefully.

Every unusual character you send is a small tax. Every ordinary English word is a discount. That asymmetry is baked into the tokenizer, and no amount of prompt engineering removes it.

Part 4 — The context window: the desk, not the brain

Now the second half. You know what tokens are; the question is how many the model can look at simultaneously.

My favourite analogy comes from a colleague who used to work in an architecture office. Picture a draughtsman at a drawing board. The board is a fixed size. Everything he needs — the client brief, the site survey, last week’s revisions, the sheet he is drawing on right now — has to be laid out on that board at once. Anything that doesn’t fit goes on the floor. And here is the crucial part: he cannot remember what’s on the floor. Not “remembers it vaguely.” Cannot see it at all.

That board is the context window. It is measured in tokens, and it holds four things simultaneously:

ONE CONTEXT WINDOW — 100% OF WHAT THE MODEL CAN SEE Systempromptrules, persona Attached files & retrieved docsPDFs, database rows, search results,tool outputs, images-as-tokens Conversation historyevery earlier message from both sides,resent in full on every single turn Reserved forthe replyoutput tokens ANYTHING THAT DOESN’T FIT Dropped, truncated, or summarised away The model has no awareness that this content ever existed. It cannot ask for it back.
The four tenants of every context window. They compete for the same fixed space — grow one and you shrink the others.

Read that diagram twice, because it contains the single most misunderstood fact about chatbots: the conversation history is re-sent, in full, on every turn. The model is not sitting there remembering you between messages. It is stateless. Each time you press enter, the application quietly bundles up the entire transcript so far, appends your new message, and ships the whole parcel off again. That is why turn 40 of a conversation costs far more than turn 2, and why a long chat gradually slows down.

Watch a conversation fall off the edge

The simulator below runs a customer-support chat. Drag the slider to shrink or grow the window and watch which messages survive. The system prompt is pinned — it is always sent — and the newest messages have priority. Everything greyed out is on the floor.

Context window simulator

drag the slider
system prompt history in window free space 0 messages dropped

Shrink the window far enough and the model loses the customer’s order number — then confidently asks for it again, or worse, invents one. That “sudden amnesia” moment is not a bug in the model. It is arithmetic.

Part 5 — Who is eating your window?

When a team tells me “we have a 128,000 token window, we’ll never hit it,” I ask them to write down the budget. It is always tighter than they expect. Here’s a real-shaped example — an internal HR assistant:

Line itemTokensNotes
System prompt (tone, rules, escalation policy)1,400Sent on every single turn, forever.
Tool / function definitions2,100Six tools with parameter schemas.
Few-shot examples1,800Four demonstration Q&A pairs.
Retrieved policy documents (8 chunks)6,400The RAG payload.
Employee’s uploaded payslip PDF3,200Tables tokenize badly.
Conversation history (turn 18)9,700Grows every turn, never shrinks by itself.
Reserved for the reply2,000If you forget this, generation gets cut off mid-sentence.
Total26,600And this is a simple assistant.

Notice what dominates: not the user’s question, which is maybe 30 tokens. The scaffolding dominates. That is the normal state of affairs, and it’s why the highest-leverage optimisation is almost never “write a shorter question.”

The reservation nobody makes

Input and output share the same window. If you fill 199,000 of a 200,000-token window with a document and then ask for a detailed 5-page report, there is no room left to write it in. The response gets truncated mid-sentence and everyone blames the model. Always leave headroom for the answer — I budget 10–15% by default.

Input tokens and output tokens are not the same product

Every provider charges more per output token than per input token, often 3–5×, and beginners assume this is arbitrary. It isn’t. Reading your input happens in one parallel pass — the whole prompt goes through the model at once. Writing the reply happens one token at a time, sequentially, with a full pass through the network for each token produced. Output is genuinely the expensive half.

The practical takeaway: a request that reads 50,000 tokens and returns a 200-token summary is cheap. A request that reads 500 tokens and generates a 4,000-word essay may cost more. If your bill is climbing, look at what you are asking the model to write, not just what you are feeding it.

What actually fits in a window?

pick a size
0English words
0Pages of prose
0Lines of code
0Minutes of transcript
0Business emails
0Hindi words

Part 6 — Why bigger windows didn’t solve everything

Around the time million-token windows arrived, a lot of people declared retrieval dead. Just dump everything in! It did not play out that way, for four reasons I now explain in every architecture review.

Attention cost grows faster than the input

In a standard transformer, every token compares itself with every other token. Double the input and you roughly quadruple that work. Modern implementations soften the curve considerably, but the shape of the problem remains: long contexts are disproportionately expensive in compute and in memory. That cost lands on you as latency and as money.

Information gets lost in the middle

Researchers have repeatedly measured a U-shaped accuracy curve: models are excellent at recalling material near the beginning of the context and near the end, and noticeably weaker on material buried in the middle. Put the critical clause on page 40 of a 90-page contract and recall genuinely suffers. It is the reading equivalent of remembering the first and last speaker at a conference and losing the eleven in between.

Two habits that follow from this

First: put your instructions after the long document, not before it — the tail position is a strong one. Second: for anything critical, state it twice, once at the top and once at the bottom. It feels redundant. It measurably works.

More context means more distraction

Give a model 50 pages when the answer lives in one paragraph, and you have added 49 pages of plausible-looking, semantically similar noise. Precision drops. I have watched a support bot’s accuracy improve by 12 points simply by retrieving four document chunks instead of twenty. Less, but better, beat more.

You pay for every token, every turn

A 300,000-token prompt sent on each of 20 conversational turns is six million input tokens for a single conversation. Multiply by a thousand users. This is the bill that surprises startups in month three.

A large context window is a bigger desk, not a better draughtsman. What you place on the desk still decides the quality of the drawing.

Part 7 — What happens when you overflow

Four different things, and knowing which one your tool does explains a lot of otherwise baffling behaviour.

Hard rejection

The API refuses the request outright with a “maximum context length exceeded” error. Honest and annoying — typical of direct API calls.

Silent truncation

The oldest content is chopped off without telling anyone. The model answers confidently using half the information. This is the dangerous one.

Sliding window

Old turns drop off the back as new ones arrive, like a conveyor belt. Chat apps often do this. It’s why long chats “forget” the beginning.

Rolling summarisation

Older turns get compressed into a paragraph of notes that stays in context. Cheapest in tokens, but detail is permanently lost.

Here’s the failure I see most often in production, told as a small story. A logistics company built an assistant that read a shipment manifest and answered questions about it. It worked beautifully in testing. In production it started confidently reporting wrong container weights. The cause: their largest customers had manifests that pushed past the window, their framework silently truncated the head of the file — including the column headers — and the model, doing its best with headerless numbers, guessed which column was which. No error was ever logged. Nobody had built a token counter into the pipeline.

Count your tokens before you send them. That is the whole lesson. It takes four lines of code and it prevents an entire genus of bug.

Part 8 — The practical playbook

Nine tactics, roughly in the order I reach for them.

TacticWhat you actually doBest when
Chunk and retrieveSplit documents into 300–800 token passages, embed them, and pull only the handful that match the question.Your corpus is bigger than any window — knowledge bases, manuals, archives.
Summarise and carryEvery ~10 turns, compress the conversation into a short state note and drop the raw transcript.Long-running assistants and agents.
Sandwich your instructionsState the task before the document and repeat it after.Any prompt over ~10,000 tokens.
Reserve output spaceCap input at 85% of the window; leave the rest for the reply.Always. Non-negotiable.
Strip the noiseRemove HTML tags, boilerplate footers, base64 blobs, repeated log timestamps, license headers.Scraped web content and log files — often a 40% saving.
Keep the stable parts firstPut the system prompt and fixed examples at the very start, variable content after.You’re using prompt caching — cache hits need an identical prefix.
Ask for structureRequest JSON or a bounded list instead of free prose.Output tokens are your cost driver.
Split the jobThree focused calls beat one giant call that tries to do everything.Multi-step analysis; also improves accuracy.
Right-size the modelRoute simple classification to a small model, reserve the big window for the hard step.Cost is out of control and latency matters.

A worked example: 200 support tickets

Say you want themes across 200 support tickets averaging 400 words each. Naive approach: paste all of them, about 107,000 tokens, into one prompt and ask for themes. It fits in a large window — and produces a bland, shallow answer, because the middle 150 tickets get skimmed.

What actually works: batch the tickets in groups of 20. For each batch, ask for a compact structured summary — five themes, each with a one-line description and a count. That’s ten calls of ~11,000 input tokens each, returning ~300 tokens apiece. Then a final call takes those ten summaries (3,000 tokens total) and merges them into the master list. Total input is similar, output is small, and every ticket got real attention rather than a glance. This map-then-reduce shape is the workhorse pattern of practical LLM engineering, and it exists entirely because of context limits.

Part 9 — Five myths worth deleting

“The model remembers our previous conversations.”

By default, no. Each request is stateless. If a product appears to remember you across sessions, an application layer is storing notes in a database and quietly pasting the relevant ones into the context window before the model ever sees your message. The memory lives in the product, not in the model.

“A bigger context window means the AI is smarter.”

Window size measures capacity, not capability. A model with a million-token window can still reason worse than a model with 32,000. They’re independent specifications — like confusing the size of a desk with the skill of the person sitting at it.

“One token is one word.”

Only by coincidence, and mostly for short common English words. Average English runs about 1.3 tokens per word; a rare surname might be five tokens; a Devanagari sentence can be three or four times its English equivalent. The splitter above makes this obvious in ten seconds.

“Images and files don’t use tokens.”

They absolutely do. Images are converted into token-equivalents based on their dimensions — a high-resolution screenshot can cost well over a thousand. PDFs are extracted to text and tokenized like anything else, and tables and scanned pages are especially expensive. Audio and video are worse still.

“If it fits in the window, the model reads it all equally.”

Fitting is necessary, not sufficient. Attention is uneven — beginnings and endings dominate. Fitting a document into context guarantees the model can see it, never that it will weigh every paragraph the same.

Quick reference

TermIn one line
TokenThe smallest unit of text a model reads; usually a word fragment.
TokenizerThe component that converts text into token IDs and back again.
VocabularyThe fixed list of all tokens a model knows — typically 50K–200K entries.
BPEByte Pair Encoding — the merge-the-most-frequent-pair algorithm that builds that list.
Context windowMaximum tokens the model can hold at once, input and output combined.
Input tokensEverything you send: prompt, history, files, tool definitions.
Output tokensEverything the model writes back. More expensive, generated one at a time.
TruncationCutting content that doesn’t fit — sometimes silently.
RAGRetrieval-augmented generation: fetch only the relevant passages, then answer.
Prompt cachingReusing the processed form of an unchanged prompt prefix to cut cost and latency.
KV cacheStored intermediate values for tokens already processed; grows with context length.
Lost in the middleThe measured tendency to recall the start and end of a long context better than the middle.

Check yourself

Five questions. No score is recorded anywhere — this is just for you.

Frequently asked questions

How many tokens is 1,000 words?

About 1,300 tokens for ordinary English prose. Technical writing with lots of code, names, or numbers runs higher — budget 1,500. Hindi, Tamil, Arabic or Korean text of the same length can reach 3,000–5,000.

How do I count tokens exactly?

Use the tokenizer library published for your specific model family — the count is model-specific, so a number from one vendor’s tool won’t match another’s precisely. For planning, the four-characters-per-token estimate is close enough; for billing and hard limits, count properly in code before you send.

Does a longer chat cost more even if my messages are short?

Yes, and this surprises almost everyone. The full history is re-sent every turn, so input cost grows roughly with the square of conversation length. Starting a fresh chat for a new topic is not just tidier — it is cheaper and usually produces better answers.

What’s the difference between context window and training data?

Training data is what shaped the model’s weights months ago — permanent, general, and unchangeable at chat time. The context window is working memory for right now — temporary, specific, and gone when the session ends. A model can be trained on the whole internet and still not know what’s in a document you haven’t pasted.

Can I make my text use fewer tokens?

Yes, meaningfully. Strip boilerplate and markup, drop repeated headers and footers, replace long IDs with short labels, summarise older conversation turns, send excerpts instead of whole files, and prefer plain common vocabulary over ornate phrasing. Compressing prompts by 30–50% with no loss of meaning is routine once you look for it.

Why do models struggle with counting letters and long arithmetic?

Because tokenization hides the internal structure. The model sees IDs for word fragments, not individual characters or place-value digits. Spacing the characters out (s-t-r-a-w) or asking it to use a calculator tool both fix it, and both work because they change what the tokenizer produces.

Where this leaves you

Two ideas, and everything downstream follows from them. Text becomes tokens — fragments, not words, priced by how ordinary they are. Tokens live inside a window — a hard-edged desk, not a memory, holding your instructions, your documents, your entire chat history and the answer being written, all at the same time.

Once those two things are solid, the rest of the field stops looking like magic. Retrieval is a technique for choosing what goes on the desk. Prompt caching is a technique for not re-reading the same corner of it. Summarisation buys space. Chunking buys attention. Even the odd failures — the miscounted letters, the sudden amnesia at message 40, the report that stops mid-sentence — become predictable, and therefore preventable.

Try this before you close the tab: take a prompt you use regularly, paste it into the splitter near the top of this page, and look at the number. Most people discover their standard prompt is two or three times more expensive than they assumed, and that a third of it is boilerplate the model never needed. That’s a five-minute experiment that has saved teams I’ve worked with real money — and it starts with just looking at the tokens.

tokenscontext windowtokenizationBPEprompt engineeringLLM basics

The post What Are Tokens and Context Windows? appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-are-tokens-and-context-windows/feed/ 0 814
AI Hallucinations: Why They Happen — Explained with Real Examples https://learnwithexamples.org/ai-hallucinations-explained-with-real-examples/ https://learnwithexamples.org/ai-hallucinations-explained-with-real-examples/#respond Mon, 27 Jul 2026 14:28:51 +0000 https://learnwithexamples.org/?p=787 AI Hallucinations: Why They Happen — Explained with Real Examples Learn · With · Examples Ask a language model a question and it can answer with total confidence — complete…

The post AI Hallucinations: Why They Happen — Explained with Real Examples appeared first on Learn With Examples.

]]>
AI Hallucinations: Why They Happen — Explained with Real Examples

Learn · With · Examples

Ask a language model a question and it can answer with total confidence — complete with dates, citations, and code — while being completely wrong. This isn’t a bug that occasional updates will fix. It is a direct consequence of how these models work. This guide breaks down exactly why hallucinations happen, with interactive examples, real cases, and the techniques used to reduce them.

📖 17 min read 🎲 Next-token prediction explorer 🖼 Hallucination gallery 🌡 Temperature demo ❓ 6-question quiz

Section 01

What is an AI Hallucination?

An AI hallucination is when a language model generates output that is fluent, confident, and completely wrong — a fabricated fact, a citation to a paper that doesn’t exist, a function that was never in the library, a quote nobody said. The term comes from human perception, where a hallucination is seeing something that isn’t there. The model isn’t “seeing” anything, but the analogy fits: it is generating something that has no basis in reality, with the same fluency as something true.

Think of a brilliant friend who has read almost everything but never admits when they don’t know something. Ask them a question and they will answer instantly and confidently — sometimes correctly, sometimes by smoothly inventing a plausible-sounding answer. They are not lying, because lying requires knowing the truth and hiding it. They genuinely cannot tell the difference between “I recall this” and “this sounds right.” That is a language model.

⚖ Real Case — Fabricated Legal Citations

In 2023, lawyers in a U.S. federal case submitted a brief containing citations to six court cases — complete with quotes and docket numbers. None of the cases existed. A chatbot had fabricated them entirely, and they read as completely legitimate legal citations. The court sanctioned the lawyers involved.

3–27%
Estimated hallucination rate across leading models on open-domain factual questions
0%
Built-in mechanism for a model to know it’s wrong — confidence is not accuracy
1 token
At a time — the entire generation process, with no global fact-check step
2016
Term first applied to neural network outputs, borrowed from image captioning research

Section 02

Intrinsic vs Extrinsic — The Formal Definition

Researchers split hallucinations into two categories, depending on what the output contradicts:

Intrinsic Hallucination
The output contradicts the source material it was given. Ask it to summarise a document, and it states something the document explicitly says is false.
Extrinsic Hallucination
The output cannot be verified from the given source at all — it adds new “facts” that are neither confirmed nor denied by the source material or reality.
P(next token | previous tokens)
This is all a language model actually computes — a probability distribution over the next token, not a fact-lookup

💡 The Core Insight

A language model is not a database with a retrieval system attached. It is a function that predicts the statistically most likely next word given everything before it. Truth is not a variable in that computation — plausibility is. Most of the time plausible and true are the same thing, because it learned from mostly-true text. But nothing in the mechanism enforces truth. When they diverge, you get a hallucination.

Section 03

Interactive: Next-Token Prediction Explorer

Every word a language model produces is chosen from a probability distribution over its entire vocabulary. Click a prompt below to see simplified next-token probabilities. Notice what happens when no single answer clearly dominates — that flat, spread-out distribution is exactly where hallucinations are born.

  Next-Token Prediction Explorer
Prompt: “The capital of France is ___“
Paris
97%
Lyon
1.5%
Marseille
0.8%
(other)
0.7%
✅ Low hallucination risk. One token dominates overwhelmingly — this fact appeared millions of times in training data in exactly this pattern. The model is essentially certain.
Prompt: “The Battle of Hastings took place in the year ___“
1066
78%
1067
9%
1086
6%
(other)
7%
⚠ Moderate risk. The correct answer still leads clearly, but nearby wrong years have real probability mass — with unlucky sampling, a wrong-but-plausible year could get selected.
Prompt: “The third-longest river in Paraguay by tributary count is ___“
Río Apa
14%
Río Aquidabán
12%
Río Ypané
11%
Río Tebicuary
10%
(other, spread thin)
53%
🔴 High hallucination risk. No token dominates — this is an obscure, likely under-documented fact. The model will still confidently output ONE of these river names in fluent prose, with no indication of its uncertainty. This is the classic hallucination signature: a flat probability distribution rendered as a confident sentence.

⚠ The Fluency Trap

Notice that all three answers above would read equally confidently in a generated sentence — “The third-longest river in Paraguay by tributary count is the Río Apa.” Nothing in the grammar or tone signals that this answer had only 14% probability versus the capital-of-France answer’s 97%. Fluency is constant; certainty is invisible.

Section 04

Why They Happen — 6 Root Causes

🎯

1. Next-Token Prediction, Not Fact-Checking

The model’s only job during generation is “what word comes next.” There is no separate module that checks generated claims against a database of true facts.

📚

2. Training Data Gaps and Noise

If a topic was rare, contradictory, or wrong across the training corpus, the model absorbs that gap or error as if it were reliable pattern.

🎲

3. Sampling Randomness

Generation involves randomness (temperature, top-p sampling) by design — to avoid robotic repetitive text. That same randomness can select a low-probability, incorrect token.

🔌

4. No Real-Time Grounding

Without a retrieval or search tool connected, the model only has frozen knowledge from training — it cannot look anything up to double-check itself mid-answer.

📊

5. Miscalibrated Confidence

Models are trained to sound helpful and fluent, not to output calibrated uncertainty. There’s no built-in “I’m only 14% sure” phrasing — everything comes out sounding equally confident.

🗜

6. Lossy Compression of Knowledge

A model with billions of parameters still compresses trillions of words of training text. Like a JPEG at low quality, fine details blur — and the model fills gaps with its best statistical guess.

🧠 An Analogy: Compression, Not Storage

A language model does not store facts the way a database stores rows. It stores statistical patterns compressed from its training data. Recalling a fact is more like reconstructing a blurry JPEG than reading a row from a spreadsheet — usually accurate, but sometimes the reconstruction fills gaps with a plausible-looking artifact that was never actually there.

Section 06

Interactive: Temperature and Sampling

“Temperature” controls how randomly a model samples from its next-token probability distribution. Lower temperature makes it pick the highest-probability token almost every time. Higher temperature flattens the distribution, giving low-probability (and potentially wrong) tokens a real chance of being chosen. Click through the same prompt at three different temperatures.

  Temperature Comparison — same prompt, three settings
Prompt: “List three lesser-known facts about the founding of the city of Timbuktu.”
temp = 0.0deterministicalways picks top token
1. Timbuktu was founded around the 5th century CE by Tuareg nomads as a seasonal camp.
2. It grew into a major center of trade in salt, gold, and books.
3. The University of Sankore made it a hub of Islamic scholarship by the 14th century.
✅ Lowest hallucination risk — but not zero. At temp 0 the model always picks its single most likely token, giving the most “average” and well-supported answer it has. Repeatable and conservative, though it can still be confidently wrong if the top token itself is incorrect.
temp = 0.7balancedsome randomness
1. Timbuktu’s name may derive from “Tin Abutut,” referring to a well tended by a woman named Buktu.
2. Its libraries once held an estimated 700,000 manuscripts.
3. By the 1300s it briefly rivaled Cairo as a center of Islamic learning in West Africa.
⚠ Moderate risk — this is the typical default used in chat products. More varied and interesting phrasing, but occasional lower-probability claims slip in (exact manuscript counts and etymology claims are exactly the kind of specific-sounding numbers most likely to be invented).
temp = 1.5highly randomcreative but unstable
1. Timbuktu was reportedly founded in 1204 by the merchant-explorer Amara Keita after a caravan dispute.
2. Its original name, “Tinbouctu,” is said to mean “the place of the hidden well of stars.”
3. Early manuscripts suggest the city briefly minted its own gold currency called the “sanu-tomo.”
🔴 High risk — specific names, dates, and invented terms appear with total fluency and confidence. This is temperature-driven hallucination in its purest form: low-probability, largely fabricated tokens getting selected and then compounding into an entirely invented but very readable narrative.

Section 07

Types of Hallucinations

TypeWhat happensExample
FactualStates something false about the worldWrong birth year for a historical figure
FaithfulnessContradicts a document it was explicitly givenSummarizing a report and stating a conclusion the report actually rejects
CitationInvents sources, papers, or linksA perfectly formatted but nonexistent journal reference
LogicalReasoning steps don’t actually follow from each otherA multi-step math “proof” where step 3 doesn’t follow from step 2
EntityMerges or invents people, places, organizationsAttributing a real quote to the wrong (but plausible) person
TemporalGets timelines or sequences wrongSaying an event happened before its actual cause

Section 08

How Hallucinations Are Measured

Researchers use standardized benchmarks to compare how often different models hallucinate. These typically involve asking models factual questions where a subtly wrong but plausible answer is a common human misconception — deliberately testing the gap between “sounds right” and “is right.”

BenchmarkWhat it testsApproach
TruthfulQACommon misconceptions817 questions designed so a plausible-sounding wrong answer mimics common false beliefs
HaluEvalGeneral hallucination detection35,000 samples across QA, summarization, and dialogue tasks
FActScoreFactual precision of long-form textBreaks generated biography-style text into atomic facts and verifies each one
SelfCheckGPTConsistency-based detectionSamples the same prompt multiple times — inconsistent answers signal likely hallucination

⚠ No Benchmark is Perfect

Hallucination rates vary wildly depending on domain, question difficulty, and whether the model has retrieval tools available. A single “hallucination rate” percentage for a model is always a simplification — the real rate depends heavily on what you’re asking.

Section 09

Real-World Consequences

⚖

Legal Filings

Multiple documented cases of lawyers submitting briefs with fabricated case citations generated by chatbots, leading to court sanctions and case dismissals.

🏥

Medical Information

Confidently wrong drug interaction or dosage claims are especially dangerous because the fluent, authoritative tone makes errors hard to spot without independent verification.

🛫

Customer Service Bots

An airline’s chatbot invented a bereavement fare policy that didn’t exist. A tribunal ruled the airline was still bound by what its bot had promised the customer.

💻

Software Supply Chain

Attackers have started publishing malicious packages under names that AI coding assistants commonly hallucinate as real library names — a technique called “slopsquatting.”

📰

News Summarization

AI news summary tools have attributed claims to sources that never made them, misrepresenting the actual reporting underneath.

🎓

Academic Research

Students and researchers citing AI-fabricated sources have had papers rejected or retracted after reviewers discovered the citations don’t exist.

Section 10

Mitigation Techniques

TechniqueHow it worksEffectiveness
RAG (Retrieval-Augmented Generation)Retrieves real documents and grounds the answer in them before generatingHigh — directly addresses the “no grounding” root cause
Lower temperatureReduces randomness in token selection for factual tasksModerate — reduces but doesn’t eliminate risk
Chain-of-thought promptingForces the model to show reasoning steps, making errors easier to catchModerate — helps with logical, not factual, hallucinations
Self-consistency checkingGenerate multiple answers and check if they agreeModerate — inconsistency signals uncertainty
RLHF fine-tuningTrains the model to say “I don’t know” when uncertainModerate — helps but models remain overconfident on edge cases
Citation requirementsForces the model to link every claim to a real retrievable sourceHigh — makes fabrication immediately checkable
Human reviewA person verifies high-stakes outputs before they’re usedHighest — the only currently reliable safeguard for critical use cases

Section 11

Worked Example — Grounding with RAG

Retrieval-Augmented Generation (RAG) is the most effective widely-used mitigation. Instead of relying purely on the model’s compressed training memory, the system first retrieves real, current documents and feeds them into the prompt as context.

❌ Without RAG
Prompt: “What is our company’s current refund policy?”

Model has no access to your company’s actual policy documents — it generates a plausible-sounding generic refund policy based on common patterns from training data, presented as if it were your specific company’s real policy.
✅ With RAG
Prompt: “What is our company’s current refund policy?”

System first retrieves your actual policy document, inserts its real text into the prompt, then asks the model to answer using only that text. The model now has real grounding — reducing (not eliminating) fabrication risk to whether the model accurately reads the provided text.

✅ Why Grounding Helps but Doesn’t Solve It

RAG dramatically reduces factual hallucinations because the model is now paraphrasing real retrieved text instead of reconstructing from compressed memory. But it doesn’t eliminate the risk entirely — the model can still misread, misquote, or blend the retrieved documents with its own memory (an intrinsic hallucination against the very source it was given).

Section 12

Code Example — Sampling Parameters

Here is how temperature and top-p (nucleus sampling) are actually set when calling a language model API — the same parameters demonstrated in the interactive Temperature demo above.

Python
import anthropic

client = anthropic.Anthropic()

# Low temperature — for factual, deterministic tasks
# Minimizes risk of low-probability token selection
response_factual = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=500,
    temperature=0.0,  # deterministic, most-likely token every time
    messages=[{"role": "user", "content": "What year did WWII end?"}]
)

# Higher temperature — for creative, exploratory tasks
# Accepts more hallucination risk in exchange for variety
response_creative = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=500,
    temperature=1.0,
    messages=[{"role": "user", "content": "Write a whimsical short story about rain."}]
)

# RAG pattern — ground the model in real retrieved text
def answer_with_grounding(question, retrieved_docs):
    context = "\n\n".join(retrieved_docs)
    prompt = f"""Answer ONLY using the context below.
If the answer is not in the context, say "I don't have that information."

Context:
{context}

Question: {question}"""

    return client.messages.create(
        model="claude-sonnet-5",
        max_tokens=500,
        temperature=0.0,  # low temp — stick close to retrieved facts
        messages=[{"role": "user", "content": prompt}]
    )

⚠ Temperature Zero Isn’t a Cure

Setting temperature to 0.0 reduces randomness-driven hallucination, but does nothing for hallucinations that come from a genuinely wrong top-probability token — if the model’s single most confident answer is itself incorrect, temperature 0 will reproduce that error every single time, consistently.

Section 13

Knowledge Quiz

Click a question to expand it, then pick your answer.

A hallucination is fabricated content generated with the same fluency and confidence as accurate content. It’s not intentional deception (the model has no concept of “hiding” the truth) and it’s not simply a matter of opinion — it’s a factual or logical error presented as fact.
Language models compute a probability distribution over the next token and sample from it. There is no built-in fact-verification step in that process — plausibility, not truth, is what’s being optimized during generation. Truth and plausibility usually align, but not always.
Intrinsic hallucinations contradict the provided source — e.g., summarizing a document and stating something the document explicitly denies. This is distinct from extrinsic hallucination, where the model adds unverifiable new claims not confirmed OR denied by the source.
Temperature controls how randomly tokens are sampled from the probability distribution. Higher temperature flattens the distribution, giving unlikely (and often wrong) tokens more chance of selection. But temperature 0 isn’t a fix either — if the single most probable token is itself wrong, temperature 0 will reproduce that error consistently every time.
RAG retrieves real, current documents and inserts them into the prompt as context, letting the model paraphrase actual text instead of reconstructing facts from lossy compressed memory. It significantly reduces — but does not fully eliminate — hallucination risk, since the model can still misread or misquote the retrieved text.
The model has learned the statistical *pattern* of citations extremely well — journal names, volume numbers, page ranges, author formatting — even when the specific paper doesn’t exist. This makes fabricated citations look completely legitimate at a glance, as demonstrated by real legal cases where fake case citations passed initial review.

The post AI Hallucinations: Why They Happen — Explained with Real Examples appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/ai-hallucinations-explained-with-real-examples/feed/ 0 787
What is Two-Factor Authentication and Why Does It Matter? https://learnwithexamples.org/what-is-two-factor-authentication/ https://learnwithexamples.org/what-is-two-factor-authentication/#respond Thu, 16 Jul 2026 06:49:56 +0000 https://learnwithexamples.org/?p=751 What is Two-Factor Authentication and Why Does It Matter? Cybersecurity · Technology Passwords alone are broken. Billions have been stolen, leaked, and sold on the dark web. Two-factor authentication (2FA)…

The post What is Two-Factor Authentication and Why Does It Matter? appeared first on Learn With Examples.

]]>
What is Two-Factor Authentication and Why Does It Matter?

Cybersecurity · Technology

Passwords alone are broken. Billions have been stolen, leaked, and sold on the dark web. Two-factor authentication (2FA) is the single most effective thing you can do to protect your accounts — and this guide explains exactly how it works, why it stops hackers, and how to set it up in minutes.

📖 16 min read 🔐 Live login simulator 🛡 Attack scenario demo 🔑 Password strength tester ❓ Quiz included
🔓 Password only — vulnerable 🔑 Strong password — better 🛡 Password + 2FA — secure

Section 01

The Problem — Why Passwords Fail

In theory, a strong, unique password protects your account. In practice, passwords fail in ways that have nothing to do with how strong they are.

24B
passwords exposed in data breaches in 2022 alone
80%
of hacking-related breaches involve stolen credentials
65%
of people reuse the same password across multiple sites
$6T
global cost of cybercrime annually — rising every year

Passwords fail for several main reasons — and crucially, none of them require the hacker to guess your password correctly:

Attack TypeHow it worksStops a strong password?
Data breachA website you use gets hacked. Your email and password hash is stolen and cracked.No
PhishingA fake login page tricks you into typing your password directly.No
Credential stuffingHackers try your leaked password from one site on thousands of others.Only if unique
Keylogger / malwareMalicious software records every keystroke you type.No
Brute forceAutomated tools try millions of password combinations per second.Only if very long

The Hard Truth

Even if your password is perfectly strong and completely unique, a data breach at any site you use can expose it. The site stores a hash of your password — if their hashing is weak, attackers can crack it. Your password being strong does not protect you from the site being breached.

Section 02

What is Two-Factor Authentication?

Two-factor authentication (2FA) requires you to prove your identity in two different ways before granting access. The three categories of authentication factors are:

🧠

Something you know

A password, PIN, or security question. Easy to steal, phish, or guess.

Weakest factor alone
📱

Something you have

Your phone, a hardware key, or a one-time code from an app. Much harder to steal remotely.

Strong
👆

Something you are

Biometrics — fingerprint, face recognition, iris scan. Extremely hard to replicate.

Strongest

The Core Idea

2FA combines at least two of these three categories. A hacker who steals your password (something you know) still cannot log in because they don’t have your phone (something you have). Both factors must be compromised simultaneously — which is exponentially harder.

Section 03

How 2FA Works — Step by Step

1

Enter your username and password

The server verifies your password is correct — but does not grant access yet. You have passed Factor 1.

2

The server requests a second factor

You are prompted for a one-time code, push notification, or hardware key press. The login is suspended — waiting for you to prove you physically have the second factor.

3

Your device generates or receives the code

An authenticator app generates a 6-digit TOTP code that changes every 30 seconds. The code is mathematically tied to your account and the current time.

4

You enter the code — server verifies it

The server runs the same time-based algorithm with your secret key. If your code matches what it expects at this moment, access is granted. The code expires in 30 seconds and can never be reused.

5

Access granted

Both factors verified. Even if a hacker had your password, they could not complete step 3 without physical access to your device.

Section 04

Interactive: Try a 2FA Login

Experience a two-factor login flow yourself. Use the credentials shown, then enter the one-time code that appears on your simulated device.

  2FA Login Simulator
1
2
✓
💡 Try entering wrong credentials to see what happens.

Section 05

The 5 Types of 2FA — Ranked by Security

💬

SMS / Text Message

A 6-digit code sent to your phone via text. Vulnerable to SIM swapping attacks where hackers convince your carrier to transfer your number.

Weak — avoid if possible
📧

Email OTP

A code sent to your email. Only as secure as your email account. If your email is compromised, this 2FA factor is also compromised.

Weak
📱

Authenticator App (TOTP)

Apps like Google Authenticator or Authy generate codes locally on your device. No network needed. Not interceptable in transit.

Strong — recommended
🔔

Push Notification

A prompt appears on your phone asking “Was this you?” You tap Approve or Deny. Vulnerable to MFA fatigue attacks (spamming approvals until you accidentally approve).

Good
🗝

Hardware Security Key

A physical USB/NFC device (YubiKey, Google Titan). Cryptographically proven. Immune to phishing — only works on the exact legitimate site.

Strongest

SMS 2FA and SIM Swapping

In a SIM swap attack, a hacker calls your mobile carrier, impersonates you with basic personal info (often bought from data breaches), and asks them to transfer your number to a SIM they control. All your SMS codes now go to the hacker. Use an authenticator app instead of SMS wherever possible.

Section 06

How 2FA Stops Hackers — Attack Scenarios

Let’s walk through exactly what happens when a hacker tries to break into an account — with and without 2FA enabled.

🔓 Scenario A: Password-only account — No 2FA
Day 0 — Data breach at a shopping site
Your password is leaked in a database dump sold on the dark web for $0.001.
Day 3 — Credential stuffing
Automated bots try your email and password on 10,000 websites. Your Gmail matches.
Day 3 — Account takeover
Hacker is logged in. They change the recovery email and password. You are locked out.
Day 4 — Cascade attack
Everything connected to that email is now compromised. Bank accounts, social media, work accounts.
🛡 Scenario B: Same attack — With 2FA enabled
Day 0 — Data breach at a shopping site
Your password is leaked in the same database dump.
Day 3 — Credential stuffing attempt
Bot tries your email and password on Gmail. Password is accepted — but the server requests a 2FA code.
Day 3 — Attack blocked
Hacker cannot proceed. They do not have your phone. The code on your authenticator app changes every 30 seconds. Login attempt fails.
Day 3 — You are notified
You receive an alert about a failed login attempt. You change your password. Account remains completely secure.

The Numbers

According to Google’s research, adding an authenticator app blocks 99.9% of automated bot attacks, 99% of bulk phishing attacks, and 76% of targeted attacks. It is the single highest-impact security action an individual can take.

Section 07

Interactive: Password Strength Tester

See how long it would take to crack your password — and understand why even a strong password is not enough without 2FA.

  Password Strength Analyser

Section 08

How TOTP Codes Are Generated — The Math

TOTP stands for Time-based One-Time Password (RFC 6238). When you scan a QR code to set up an authenticator app, you share a secret key with the server. Both your app and the server independently compute codes using this formula:

T = floor(current_unix_time / 30) ← 30-second window
TOTP = HMAC-SHA1(secret_key, T) ← cryptographic hash
code = last 6 digits of TOTP ← the number you type

Because both your app and the server know the same secret key and the current time, they arrive at the same 6-digit code independently — without ever transmitting the code over a network. There is nothing to intercept in transit.

Python — TOTP from scratch
import hmac, hashlib, time, struct, base64

def generate_totp(secret_b32: str, digits: int = 6) -> str:
    # 1. Decode the base32 secret (what the QR code contains)
    key = base64.b32decode(secret_b32.upper())

    # 2. Get the current 30-second time window
    T = int(time.time()) // 30
    msg = struct.pack('>Q', T)

    # 3. Compute HMAC-SHA1
    h = hmac.new(key, msg, hashlib.sha1).digest()

    # 4. Dynamic truncation
    offset = h[-1] & 0x0F
    code = struct.unpack('>I', h[offset:offset+4])[0] & 0x7FFFFFFF

    # 5. Get last N digits
    return str(code % (10 ** digits)).zfill(digits)

# Production use: pip install pyotp
import pyotp
totp = pyotp.TOTP("JBSWY3DPEHPK3PXP")
print(totp.now())              # current 6-digit code
print(totp.verify("482156"))   # True / False

Why TOTP is secure

The code is computed locally — never sent over a network until you type it. It expires every 30 seconds. It uses HMAC-SHA1 which cannot be reversed to find the secret key. Even if an attacker intercepted a code, it would be useless within 30 seconds.

Section 09

How to Set Up 2FA — Step by Step

Step 1: Install an authenticator app

AppPlatformCloud BackupBest for
Google AuthenticatoriOS, AndroidYesSimple, widely supported
AuthyiOS, Android, DesktopYes (encrypted)Multi-device, backup
Microsoft AuthenticatoriOS, AndroidYesMicrosoft/work accounts
1PasswordAll platformsYesPassword manager + 2FA combined
AegisAndroid onlyLocal onlyOpen source, privacy-focused

Step 2: Enable 2FA on your accounts

1

Go to your account’s security settings

Look for “Security”, “Privacy”, “Two-factor authentication”, or “Login verification”. Every major service has this: Google, Apple, Amazon, GitHub, Instagram, Facebook.

2

Choose “Authenticator App” — not SMS

Select the authenticator app option when given a choice. This is more secure than SMS and works without mobile signal.

3

Scan the QR code

Open your authenticator app, tap the “+” button, and scan the QR code shown on screen. This transfers the secret key to your app.

4

Enter the first code to confirm

The website will ask you to enter the 6-digit code shown in your app to confirm it worked correctly.

5

Save your backup codes

Critical: Download or write down the backup/recovery codes provided. If you lose your phone, these codes let you regain access. Store them safely — offline, in a secure location.

Priority Order — Enable 2FA on these first

1. Email account — everything resets through email
2. Banking and financial apps
3. Password manager
4. Work accounts (Google Workspace, Microsoft 365)
5. Social media
6. Cloud storage (Dropbox, Google Drive, iCloud)

Section 10

Common Questions and Misconceptions

QuestionAnswer
“What if I lose my phone?”Use the backup codes you saved at setup. Or restore your authenticator app from cloud backup. Always save backup codes offline.
“Can 2FA be hacked?”Advanced real-time phishing can intercept codes if you’re tricked into a fake site that forwards them immediately. Hardware keys are immune even to this. TOTP apps are resistant for most users.
“Isn’t it annoying?”Most services only ask for 2FA on new devices or after a period of inactivity. Trusted devices are remembered. The friction is a few seconds versus your account being taken over.
“Is SMS 2FA better than nothing?”Yes — significantly. SMS 2FA stops the vast majority of automated attacks. Only upgrade to an authenticator app if you are a higher-value target. SMS is still far better than no 2FA.
“Does 2FA make passwords irrelevant?”No. 2FA is a second layer — you still need a strong, unique password as the first layer. Both layers being strong is the goal.
“What is the difference between 2FA and MFA?”MFA (multi-factor authentication) is the general term for using more than one factor. 2FA uses exactly two factors. All 2FA is MFA, but MFA can use three or more factors.

Section 11

Knowledge Quiz

Test what you have learned about two-factor authentication.

  Two-Factor Authentication Quiz
Question 1 of 6

The post What is Two-Factor Authentication and Why Does It Matter? appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/what-is-two-factor-authentication/feed/ 0 751
Fraud Detection with AI https://learnwithexamples.org/fraud-detection-with-ai/ https://learnwithexamples.org/fraud-detection-with-ai/#respond Tue, 01 Jul 2025 09:06:02 +0000 https://learnwithexamples.org/?p=471 Fraud Detection with AI: Step-by-Step Banking Guide A Complete Guide to Banking Fraud Prevention Using Machine Learning 🎯 Introduction: The Banking Fraud Challenge Every year, financial institutions lose billions of…

The post Fraud Detection with AI appeared first on Learn With Examples.

]]>
Fraud Detection with AI: Step-by-Step Banking Guide

A Complete Guide to Banking Fraud Prevention Using Machine Learning

🎯 Introduction: The Banking Fraud Challenge

Every year, financial institutions lose billions of dollars to fraudulent transactions. In 2023 alone, global payment fraud losses exceeded $35 billion. Traditional rule-based systems struggle to keep up with sophisticated fraud patterns, which is where Artificial Intelligence steps in as a game-changer.

$35B

Annual Global Fraud Losses

99.9%

AI Detection Accuracy

0.2s

Average Decision Time

AI-powered fraud detection systems analyze millions of transactions in real-time, identifying suspicious patterns that would be impossible for humans to detect manually. This article will walk you through exactly how these systems work, using practical banking scenarios and interactive examples.

🏗 How AI Fraud Detection Works: The Big Picture

AI fraud detection operates on multiple layers of analysis, combining various machine learning techniques to create a robust defense system. Here’s the step-by-step process:

1. Data Collection & Preprocessing

The system continuously collects transaction data including:

  • Transaction Details: Amount, time, location, merchant type
  • Customer Behavior: Spending patterns, device information, login history
  • External Factors: Geographic data, blacklists, velocity checks
  • Historical Data: Past transactions, fraud labels, customer profiles

2. Feature Engineering

Raw data is transformed into meaningful features that AI algorithms can understand:

# Example Feature Engineering for Transaction Analysis transaction_features = { ‘amount_zscore’: (amount – customer_avg_amount) / customer_std_amount, ‘time_since_last_transaction’: current_time – last_transaction_time, ‘location_risk_score’: calculate_location_risk(transaction_location), ‘merchant_category_risk’: merchant_risk_mapping[merchant_category], ‘velocity_1h’: count_transactions_last_hour(customer_id), ‘amount_percentile’: calculate_percentile(amount, customer_history) }

3. Model Training & Validation

Multiple AI models are trained on historical data with known fraud labels, then validated on separate test datasets to ensure accuracy and prevent overfitting.

4. Real-time Scoring

Each new transaction receives a fraud risk score in milliseconds, enabling instant decision-making.

🌳 Decision Trees: The Logic Behind Fraud Detection

Decision trees are one of the most interpretable AI techniques used in fraud detection. They work by asking a series of yes/no questions about transaction characteristics to classify transactions as fraudulent or legitimate.

How Decision Trees Work in Banking

Imagine you’re a bank analyst trying to identify fraud. You might ask questions like:

🌳 Root: Is transaction amount > $1,000?
├── Yes: Is it outside customer’s usual location?
├── Yes: Is it during unusual hours (2-6 AM)?
├── Yes: 🚨 HIGH FRAUD RISK (85%)
└── No: ⚠ MEDIUM RISK (45%)
└── No: ✅ LOW RISK (12%)
└── No: Is velocity > 5 transactions/hour?
├── Yes: 🚨 FRAUD (78%)
└── No: ✅ LEGITIMATE (5%)
🔍 Interactive Decision Tree Analyzer

Test how a decision tree evaluates different transaction scenarios:

Advantages of Decision Trees in Fraud Detection

  • Interpretability: Easy to understand and explain to stakeholders
  • Speed: Very fast prediction times, ideal for real-time processing
  • No Data Preprocessing: Can handle mixed data types without scaling
  • Feature Selection: Automatically identifies most important variables
Real-world Impact: JPMorgan Chase reported that their decision tree-based fraud detection system reduced false positives by 30% while maintaining 99.5% accuracy in fraud detection.

🔍 Anomaly Detection: Finding the Unusual

Anomaly detection identifies transactions that deviate significantly from normal patterns. Unlike decision trees that follow explicit rules, anomaly detection algorithms learn what “normal” looks like and flag anything unusual.

Types of Anomalies in Banking

1. Point Anomalies

Individual transactions that are unusual compared to the rest of the data.

Transaction Amount Distribution

$50
$75
$120
$95
$200
$80
$150
$5K
$110
$90

● Normal Transactions ● Anomaly (Unusual Amount)

2. Contextual Anomalies

Transactions that are normal in general but unusual for a specific customer or context.

3. Collective Anomalies

A group of transactions that together form an unusual pattern.

🎯 Interactive Anomaly Detection

See how anomaly detection algorithms evaluate transactions based on customer behavior patterns:

Common Anomaly Detection Algorithms

1. Isolation Forest

Works by isolating anomalies using random splits. Anomalies are easier to isolate and require fewer splits.

# Isolation Forest Implementation from sklearn.ensemble import IsolationForest # Training the model isolation_forest = IsolationForest( contamination=0.01, # Expected fraud rate (1%) random_state=42 ) # Features: amount, time, location_risk, velocity X = transaction_features[[‘amount_zscore’, ‘time_risk’, ‘location_risk’, ‘velocity’]] isolation_forest.fit(X) # Predicting anomalies (-1 = anomaly, 1 = normal) anomaly_scores = isolation_forest.decision_function(new_transactions) predictions = isolation_forest.predict(new_transactions)

2. One-Class SVM

Creates a boundary around normal data points. Anything outside this boundary is considered an anomaly.

3. Statistical Methods (Z-Score)

Identifies points that are multiple standard deviations away from the mean.

Case Study: Bank of America uses ensemble anomaly detection combining multiple algorithms, achieving 94% precision in fraud detection while reducing investigation time by 60%.

⚡ Real-Time Implementation: Putting It All Together

In production, fraud detection systems combine multiple techniques in a sophisticated pipeline that processes thousands of transactions per second.

The Complete Fraud Detection Pipeline

# Complete Fraud Detection Pipeline class FraudDetectionPipeline: def __init__(self): self.decision_tree = load_decision_tree_model() self.anomaly_detector = load_isolation_forest() self.risk_threshold = 0.7 def process_transaction(self, transaction): # Step 1: Feature Engineering features = self.extract_features(transaction) # Step 2: Decision Tree Scoring dt_score = self.decision_tree.predict_proba(features)[1] # Step 3: Anomaly Detection anomaly_score = self.anomaly_detector.decision_function(features) # Step 4: Ensemble Scoring final_score = self.combine_scores(dt_score, anomaly_score) # Step 5: Decision Making if final_score > self.risk_threshold: return “BLOCK”, final_score elif final_score > 0.3: return “REVIEW”, final_score else: return “APPROVE”, final_score
🏦 Complete Fraud Detection System

Experience how a real banking fraud detection system processes transactions:

Performance Metrics

99.8%

True Positive Rate

0.5%

False Positive Rate

150ms

Average Processing Time

🔮 Advanced Techniques and Future Trends

Deep Learning in Fraud Detection

Neural networks can identify complex, non-linear patterns that traditional methods might miss. Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks are particularly effective for sequential transaction analysis.

Graph Neural Networks

Modern fraud often involves networks of connected accounts. Graph Neural Networks analyze relationships between customers, merchants, and devices to identify organized fraud rings.

Federated Learning

Banks can collaborate to improve fraud detection while keeping customer data private. Models are trained locally and only model updates are shared.

Emerging Trend: Explainable AI (XAI) is becoming crucial for regulatory compliance. Banks need to explain why a transaction was flagged, leading to the development of interpretable machine learning models.

Real-Time Adaptive Learning

Modern systems continuously learn from new fraud patterns, updating their models in real-time without human intervention.

📊 Implementation Best Practices

1. Data Quality and Preprocessing

  • Handle Missing Data: Use imputation techniques or create missing data indicators
  • Feature Scaling: Normalize features to prevent bias toward high-magnitude variables
  • Class Imbalance: Use techniques like SMOTE or cost-sensitive learning

2. Model Selection and Ensemble Methods

  • Diverse Models: Combine decision trees, anomaly detection, and neural networks
  • Voting Strategies: Use weighted voting based on model performance
  • Stacking: Train a meta-model to combine predictions from base models

3. Performance Monitoring

  • A/B Testing: Compare new models against existing systems
  • Drift Detection: Monitor for changes in data patterns over time
  • Feedback Loops: Incorporate human expert feedback to improve models
# Model Monitoring Dashboard class FraudModelMonitor: def __init__(self): self.performance_metrics = {} self.alert_thresholds = { ‘precision’: 0.95, ‘recall’: 0.98, ‘false_positive_rate’: 0.02 } def monitor_performance(self, predictions, actual_labels): current_metrics = calculate_metrics(predictions, actual_labels) for metric, value in current_metrics.items(): if metric in self.alert_thresholds: if value < self.alert_thresholds[metric]: self.trigger_alert(metric, value) self.log_metrics(current_metrics)

🎯 Conclusion: The Future of Fraud Prevention

AI-powered fraud detection represents a paradigm shift from reactive to proactive fraud prevention. By combining decision trees for interpretable rules, anomaly detection for pattern recognition, and advanced machine learning techniques, banks can achieve unprecedented accuracy in fraud detection while maintaining customer experience.

The key success factors include:

  • Real-time Processing: Decisions must be made in milliseconds
  • Continuous Learning: Models must adapt to new fraud patterns
  • Explainability: Decisions must be interpretable for regulatory compliance
  • Balance: Minimize false positives while maximizing fraud detection

As fraud techniques become more sophisticated, AI systems will continue to evolve, incorporating new technologies like quantum computing, advanced graph analytics, and behavioral biometrics to stay ahead of fraudsters.

Action Item: Start experimenting with the interactive examples above to understand how different parameters affect fraud scoring. This hands-on experience will deepen your understanding of AI fraud detection systems.

Also check: How Virtual Reality Works

The post Fraud Detection with AI appeared first on Learn With Examples.

]]>
https://learnwithexamples.org/fraud-detection-with-ai/feed/ 0 471
How Virtual Reality Works: Building Your First VR Scene with Examples https://learnwithexamples.org/how-virtual-reality-works/ https://learnwithexamples.org/how-virtual-reality-works/#respond Sat, 21 Dec 2024 08:27:50 +0000 https://learnwithexamples.org/?p=353 Imagine stepping into a magical forest. The trees sway gently as you hear birds chirping above and a brook bubbling nearby. As you walk forward, the forest clears to reveal…

The post How Virtual Reality Works: Building Your First VR Scene with Examples appeared first on Learn With Examples.

]]>
Imagine stepping into a magical forest. The trees sway gently as you hear birds chirping above and a brook bubbling nearby. As you walk forward, the forest clears to reveal a hidden castle, its grand doors waiting to be opened. This immersive experience, where you feel like you’ve entered another world, is the power of Virtual Reality (VR).

In this article, we’ll explore how VR works and guide you through building your first simple VR scene using Unity, a popular game development platform, and C#. Using the example of a virtual magical forest, we’ll break down each step so it’s easy to understand and follow, even if you’re new to VR or programming.


What Is Virtual Reality?

Virtual Reality is a technology that creates a simulated environment where users can interact with a 3D world using specialized equipment like VR headsets and controllers. Unlike traditional screens, VR immerses users by simulating their physical presence in a virtual space.

  • How it works: VR relies on:
    1. Headsets: Devices like the Oculus Quest or HTC Vive display the 3D environment, adjusting visuals as you move your head.
    2. Controllers: Allow you to interact with objects in the virtual world.
    3. Sensors: Track your movements to make the experience realistic.
  • Applications: VR is used in gaming, education, training simulations, and even therapy. For this tutorial, we’ll focus on a creative application: building a simple VR scene of a magical forest.

Tools You’ll Need

To create a VR scene, you’ll need:

  1. Unity: A free, beginner-friendly game development platform.
  2. C#: A programming language used in Unity to add functionality to objects.
  3. VR Headset: Optional for testing your scene, but not required for development.
  4. PC or Mac: A computer capable of running Unity.

We’ll walk you through setting up Unity and building a magical forest VR scene step by step.


Step 1: Setting Up Unity

  1. Download Unity:
    • Go to Unity’s website and download the Unity Hub.
    • Install the latest version of Unity with VR support.
  2. Create a New Project:
    • Open Unity Hub, click “New Project,” and select the 3D template.
    • Name your project “MagicalForestVR” and click “Create.”
  3. Install VR SDK:
    • In Unity, go to “Window > Package Manager.”
    • Search for and install the XR Interaction Toolkit, which supports VR development.

Step 2: Designing Your VR Scene

Think of your VR scene as a stage where everything happens. In our example, we’ll design a magical forest with trees, a brook, and a castle.

  1. Add a Terrain:
    • In Unity, right-click in the “Hierarchy” panel and select “3D Object > Terrain.”
    • This creates a flat ground. Use the terrain tools to shape hills and add textures for grass.
  2. Add Trees and Rocks:
    • Go to the “Asset Store” in Unity and download free 3D models of trees and rocks.
    • Drag and drop these models into your scene.
  3. Add a Brook:
    • Create a small trench in the terrain and add a water asset.
    • Adjust the water’s color and reflection settings to make it look realistic.
  4. Place the Castle:
    • Download a free castle model and position it at the center of your scene.

Step 3: Adding VR Interactions

To make your VR scene interactive, we’ll use the XR Interaction Toolkit and write some simple C# scripts.

  1. Enable VR Camera:
    • Delete the default camera in the “Hierarchy” panel.
    • Right-click and select “XR > Room-Scale XR Rig.”
    • This adds a VR-compatible camera and controllers.
  2. Add Interactions:
    • Attach the “XR Grab Interactable” component to objects you want to pick up, like rocks or twigs.
    • Use Unity’s “Event System” to trigger actions, such as opening the castle doors when the player approaches.

Step 4: Writing C# Scripts

Let’s write a simple script to open the castle doors when the player reaches them.

  1. Create a Script:

In the “Assets” folder, right-click and select “Create > C# Script.” Name it “DoorOpener.”

2. Write the Code:

using UnityEngine;

public class DoorOpener : MonoBehaviour
{
    public GameObject door;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            door.transform.Rotate(0, 90, 0); // Rotate door 90 degrees to open it.
        }
    }
}

3. Attach the Script:

  • Add a “Collider” component to the castle entrance and set it as a trigger.
  • Drag the “DoorOpener” script onto the trigger object.
  • Link the castle door to the script.

Also check: How Artificial Intelligence Works


    Step 5: Testing Your VR Scene

    1. Play in Editor:
      • Press “Play” in Unity to test your scene without a VR headset. Use keyboard controls to navigate.
    2. Test with a VR Headset:
      • Connect your headset to your PC and select the appropriate VR build settings in Unity.
      • Run your scene and explore the magical forest in VR.

    Step 6: Exporting Your VR Scene

    Once you’re satisfied with your scene, export it so others can experience it:

    1. Build Settings:
      • Go to “File > Build Settings.”
      • Select your target platform (e.g., Windows, Android for Oculus).
    2. Build and Run:
      • Click “Build and Run” to generate an executable file.
      • Share the file with friends or upload it to a VR content platform.

    Conclusion

    Creating a VR experience may seem daunting at first, but by breaking it down into manageable steps, anyone can build their own immersive world. Using Unity and C#, we designed a magical forest VR scene complete with interactive elements like opening doors and exploring serene landscapes.

    The magical forest is just the beginning. With the foundational skills you’ve learned, you can create even more complex and engaging VR experiences. So, put on your VR headset, step into your scene, and let your imagination guide you!

    The post How Virtual Reality Works: Building Your First VR Scene with Examples appeared first on Learn With Examples.

    ]]>
    https://learnwithexamples.org/how-virtual-reality-works/feed/ 0 353
    How Self-Driving Cars Work: The Role of Sensors, AI, and Machine Learning https://learnwithexamples.org/how-self-driving-cars/ https://learnwithexamples.org/how-self-driving-cars/#respond Sun, 15 Sep 2024 06:09:03 +0000 https://learnwithexamples.org/?p=266 Imagine you’re sitting in your car, but instead of gripping the steering wheel and watching the road, you’re relaxing with a book or chatting with friends. The car smoothly navigates…

    The post How Self-Driving Cars Work: The Role of Sensors, AI, and Machine Learning appeared first on Learn With Examples.

    ]]>
    Imagine you’re sitting in your car, but instead of gripping the steering wheel and watching the road, you’re relaxing with a book or chatting with friends. The car smoothly navigates through traffic, stops at red lights, and safely delivers you to your destination. This isn’t a scene from a science fiction movie – it’s the promise of self-driving cars, a technology that’s rapidly becoming a reality.

    In this article, we’ll explore how self-driving cars work, focusing on three key components: sensors, artificial intelligence (AI), and machine learning. We’ll break down these complex topics into simple explanations and use everyday examples to help you understand this fascinating technology.


    1.What is a Self-Driving Car?

    Before we dive into the details, let’s define what we mean by a “self-driving car.” A self-driving car, also known as an autonomous vehicle, is a car that can drive itself without human intervention. It uses a combination of sensors, cameras, radar, and artificial intelligence to navigate roads and make decisions in real-time.

    Think of a self-driving car as a robot on wheels. Just like a robot in a factory might assemble a car without human hands touching it, a self-driving car can transport you from one place to another without you having to steer, accelerate, or brake.

    The Three Key Components

    Self-driving cars rely on three main components to function:

    1. Sensors
    2. Artificial Intelligence (AI)
    3. Machine Learning

    Let’s explore each of these in detail.

    1. Sensors: The Car’s “Eyes and Ears”

    Imagine you’re driving a car. You use your eyes to see the road, other cars, and obstacles. Your ears help you hear sirens or horns. You might even use your sense of touch to feel vibrations in the steering wheel. Self-driving cars need similar abilities to perceive their environment, and they get these abilities from sensors.

    Types of Sensors

    Self-driving cars use several types of sensors:

    1. Cameras: These act like the car’s eyes. They capture images of the road, traffic signs, other vehicles, and pedestrians.
    2. Lidar (Light Detection and Ranging): This is like super-powered vision. Lidar uses lasers to create a 3D map of the car’s surroundings.
    3. Radar (Radio Detection and Ranging): This helps the car “see” in poor visibility conditions, like fog or darkness. It’s great for detecting the speed and distance of other vehicles.
    4. Ultrasonic Sensors: These are like the car’s sense of touch. They’re used for close-range detection, like when parking.
    5. GPS (Global Positioning System): This helps the car know its exact location on Earth.

    Let’s use an example to understand how these sensors work together:

    Imagine you’re walking down a busy street. You use your eyes (like cameras) to see what’s around you. If it’s dark or foggy, you might rely more on your hearing (like radar) to detect approaching cars. You use your sense of touch (like ultrasonic sensors) to avoid bumping into things nearby. And you might check your phone’s map app (like GPS) to make sure you’re going the right way.

    A self-driving car does all of this, but with much more precision and without getting tired or distracted.

    How Sensors Work Together

    These sensors work together to give the car a complete picture of its environment. Here’s a step-by-step breakdown:

    1. The cameras continuously capture images of the road and surroundings.
    2. Lidar creates a detailed 3D map of the area around the car.
    3. Radar detects the speed and distance of other vehicles, especially useful in poor visibility.
    4. Ultrasonic sensors provide close-range information, crucial for parking and low-speed maneuvering.
    5. GPS gives the car its exact location and helps with navigation.

    All this information is then fed into the car’s brain – its artificial intelligence system.

    Also check: How Electric Cars Work?

    2. Artificial Intelligence (AI): The Car’s “Brain”

    Now that the car can “see” its environment, it needs to make sense of all that information and decide what to do. This is where Artificial Intelligence comes in. AI is like the car’s brain, processing all the data from the sensors and making decisions about how to drive.

    What is AI?

    Artificial Intelligence is a broad term that refers to computer systems that can perform tasks that typically require human intelligence. These tasks include visual perception, speech recognition, decision-making, and language translation.

    In the context of self-driving cars, AI is responsible for:

    1. Perception: Understanding what the sensors are detecting.
    2. Prediction: Anticipating what might happen next.
    3. Planning: Deciding what the car should do.
    4. Control: Executing the decided actions.

    Let’s break these down with an example:

    Imagine you’re approaching a crosswalk with a pedestrian waiting to cross. Here’s how you, as a human driver, would handle this:

    1. Perception: You see the crosswalk and the person waiting to cross.
    2. Prediction: You anticipate that the person might start crossing soon.
    3. Planning: You decide to slow down and prepare to stop.
    4. Control: You take your foot off the gas and gently press the brake.

    A self-driving car goes through the same process, but it does so using AI:

    1. Perception: The cameras and lidar detect the crosswalk markings and a human-shaped object near it.
    2. Prediction: Based on past data, the AI predicts a high probability that the human will cross.
    3. Planning: The AI decides the safest action is to slow down and stop before the crosswalk.
    4. Control: The AI sends commands to the car’s systems to reduce speed and apply the brakes.

    Also check: The Future of Artificial Intelligence

    AI Decision-Making

    The AI in a self-driving car has to make countless decisions every second. It’s constantly asking questions like:

    • Is that red light or tail light?
    • Is that object in the road a paper bag or a rock?
    • Is that car going to change lanes?
    • Should I change lanes to overtake a slow vehicle?

    To make these decisions, the AI uses complex algorithms and deep learning neural networks. These are computer programs designed to process information in a way similar to the human brain.

    3. Machine Learning: The Car’s “Education”

    While AI is the car’s brain, machine learning is how that brain gets smarter over time. Machine learning is a subset of AI that focuses on the ability of machines to receive data and learn for themselves, without being explicitly programmed.

    How Does Machine Learning Work?

    Think of machine learning like teaching a child. When you teach a child to recognize a dog, you don’t give them a list of precise measurements or characteristics. Instead, you show them many pictures of dogs. Over time, the child learns to recognize dogs, even breeds they’ve never seen before.

    Machine learning works similarly:

    1. Training Data: The system is fed large amounts of data. For a self-driving car, this could be millions of images of roads, cars, pedestrians, traffic signs, etc.
    2. Pattern Recognition: The system learns to recognize patterns in this data. It might learn that objects with two wheels are likely bicycles, or that red octagons are stop signs.
    3. Application: When the car encounters new situations, it applies what it has learned to make decisions.
    4. Feedback and Improvement: The system receives feedback on its decisions (either from human supervisors during testing, or from real-world outcomes), and uses this to improve its future decisions.

    Real-World Example: Recognizing a Stop Sign

    Let’s walk through how a self-driving car learns to recognize and respond to a stop sign:

    1. Training: The car’s AI is shown millions of images of stop signs in various conditions – sunny days, rainy nights, partially obscured by trees, etc.
    2. Learning: Through this process, the AI learns that a stop sign is typically:
      • Red
      • Octagonal
      • Has the word “STOP” written on it
      • Is usually found at intersections
    3. Application: When the car is driving and its cameras capture an image of a red, octagonal object at an intersection, the AI recognizes it as a stop sign.
    4. Action: Based on this recognition, the AI decides to bring the car to a stop.
    5. Feedback: If the car stops correctly, this reinforces the AI’s learning. If it makes a mistake (like not stopping), this is noted and used to improve future performance.

    Also check: How Cameras Work

    Continuous Learning

    One of the most powerful aspects of machine learning is that self-driving cars can continue to learn and improve even after they’re on the road. Each mile driven provides new data that can be used to refine the AI’s decision-making processes.

    For example, if a car encounters a new type of traffic sign it hasn’t seen before, this information can be shared with a central database. This new knowledge can then be distributed to all other self-driving cars in the fleet, making them all smarter.


    Putting It All Together: How a Self-Driving Car Operates

    Now that we understand the key components, let’s walk through how they all work together in a real-world scenario. Imagine our self-driving car is navigating through a busy city street. Here’s what’s happening behind the scenes:

    1. Sensing the Environment
      • The car’s cameras are constantly capturing images of the road, other vehicles, pedestrians, and traffic signs.
      • Lidar is creating a 3D map of the surroundings, detecting objects and their distances.
      • Radar is measuring the speed of nearby vehicles.
      • Ultrasonic sensors are monitoring for very close objects, like in adjacent lanes.
      • GPS is tracking the car’s exact location on the road.
    2. Processing the Information
      • The AI system takes in all this raw data from the sensors.
      • It uses machine learning algorithms to interpret the data, identifying objects and their meanings.
      • For example, it recognizes that the red octagon ahead is a stop sign, the yellow rectangle with black symbols is a school zone sign, and the moving objects on the sidewalk are pedestrians.
    3. Predicting and Planning
      • Based on its understanding of the environment, the AI predicts what might happen next.
      • It anticipates that the pedestrians might cross the road, or that the car ahead might slow down.
      • The AI then plans the safest route, considering factors like road rules, safety, and efficiency.
    4. Taking Action
      • Once a plan is made, the AI sends commands to the car’s control systems.
      • It might adjust the steering to stay in the lane, apply the brakes to slow down for a stop sign, or change lanes to avoid a parked car.
    5. Continuous Learning
      • As the car drives, it’s constantly gathering new data and experiences.
      • This information is used to refine and improve its decision-making processes.
      • For instance, if the car encounters a new type of construction sign, this information can be added to its knowledge base for future reference.

    Let’s use a specific example to illustrate this process:

    Example: Navigating a School Zone

    Imagine our self-driving car is approaching a school zone. Here’s how it handles the situation:

    1. Sensing:
      • The cameras detect a yellow sign with black symbols.
      • Lidar notices small figures (children) moving on the sidewalk.
      • GPS confirms the car is near a school.
    2. Processing:
      • The AI identifies the sign as a school zone warning.
      • It recognizes the figures as children, a high-priority category for safety.
    3. Predicting and Planning:
      • The AI predicts a high likelihood of children crossing the street.
      • It plans to reduce speed and increase alertness for sudden movements.
    4. Taking Action:
      • The car reduces its speed to the school zone limit.
      • It adjusts its sensors to be extra vigilant for movement from the sidewalks.
    5. Learning:
      • The car records data about the school zone, including the time of day, the number of children present, and any specific patterns of movement.
      • This data is used to improve future interactions with school zones.

    Challenges and Future Developments

    While self-driving technology has made incredible strides, there are still challenges to overcome:

    1. Ethical Decisions: How should a car decide between two potentially harmful outcomes? For example, swerving to avoid a pedestrian but potentially harming the passenger.
    2. Weather Conditions: Heavy rain, snow, or fog can interfere with sensors, making it difficult for the car to “see” properly.
    3. Unpredictable Human Behavior: While AI can predict many scenarios, humans can be unpredictable. A child chasing a ball into the street or a driver running a red light can create challenging situations.
    4. Cybersecurity: As cars become more connected, ensuring they can’t be hacked or remotely controlled becomes crucial.
    5. Regulatory and Legal Frameworks: Laws and regulations need to catch up with the technology, addressing questions of liability and insurance in case of accidents.

    Despite these challenges, the future of self-driving cars looks promising. Researchers and companies are working on solutions, including:

    • More advanced AI that can handle complex ethical decisions
    • Improved sensors that work better in adverse weather conditions
    • Better integration with smart city infrastructure for improved navigation and safety
    • Enhanced cybersecurity measures to protect against potential hacking attempts

    Conclusion

    Self-driving cars represent a fascinating intersection of various cutting-edge technologies. Through the combination of advanced sensors, artificial intelligence, and machine learning, these vehicles are able to perceive their environment, make decisions, and navigate roads in ways that were once the stuff of science fiction.

    As we’ve explored in this article, the process involves:

    1. Sensors that act as the car’s “eyes and ears,” constantly gathering data about the environment.
    2. Artificial Intelligence that serves as the car’s “brain,” processing this data and making decisions.
    3. Machine Learning that allows the car to improve its performance over time, learning from each new experience.

    While there are still challenges to overcome, the rapid pace of technological advancement suggests that fully autonomous vehicles may become a common sight on our roads in the not-too-distant future. As this technology continues to evolve, it promises to revolutionize transportation, potentially making our roads safer, our commutes more productive, and our cities more efficient.

    The journey of self-driving cars from concept to reality is a testament to human ingenuity and the power of technology to transform our world. As we look to the future, it’s exciting to imagine how this technology will continue to develop and shape the way we live and move in our increasingly connected world.

    The post How Self-Driving Cars Work: The Role of Sensors, AI, and Machine Learning appeared first on Learn With Examples.

    ]]>
    https://learnwithexamples.org/how-self-driving-cars/feed/ 0 266
    How Electric Cars Work? https://learnwithexamples.org/how-electric-cars-work/ https://learnwithexamples.org/how-electric-cars-work/#respond Mon, 09 Sep 2024 12:06:05 +0000 https://learnwithexamples.org/?p=227 Imagine you’re living in a world where horses were once the only means of transport. Then, one day, someone invents a car, and everything changes. Fast forward to today, and…

    The post How Electric Cars Work? appeared first on Learn With Examples.

    ]]>
    Imagine you’re living in a world where horses were once the only means of transport. Then, one day, someone invents a car, and everything changes. Fast forward to today, and we are witnessing another huge shift—the rise of electric cars. It’s like going from horses to cars all over again. But what exactly is an electric car? How does it work? Let me tell you a simple story that will make this modern marvel easy to understand.

    1. What Is an Electric Car?

    Think of an electric car like a toy car that runs on batteries, except it’s much bigger and can take you across town. While traditional cars burn gasoline to move, electric cars use electricity stored in batteries. You don’t need to stop at a gas station; instead, you plug your car into a charging station or even a wall outlet at home—just like you would charge your phone or laptop.


    2. Breaking It Down: The Three Main Parts

    To understand how electric cars work, let’s look at the three main parts that make the magic happen:

    • The Battery
    • The Electric Motor
    • The Controller

    Imagine these parts as the heart, muscles, and brain of the electric car.

    a) The Battery: The Heart of the Car

    Think of the battery as the heart of the electric car, pumping energy to make everything work. Just like how the heart sends blood to all parts of your body, the battery sends electricity to the car’s motor, which powers the wheels. Electric car batteries are different from the AA batteries you put in your remote control. These are big, powerful batteries called lithium-ion batteries, like those found in your smartphone, but much larger and capable of storing more energy.

    Imagine you’ve just bought a new toy robot. It needs batteries to come to life, right? The robot’s movement is powered by the energy in those batteries. Similarly, when you charge your electric car, you’re filling up the battery with electricity.

    Here’s where things get interesting. Unlike gas cars, where energy is burned up and lost, electric cars use stored electricity from the battery much more efficiently. The battery gives the electric motor power, and the car moves!

    b) The Electric Motor: The Muscles of the Car

    Once the battery sends power, it needs something to make the car move. This is where the electric motor comes in—it’s the car’s muscles. Imagine your legs pushing a bicycle pedal. The electric motor does something similar; it uses the electricity from the battery and converts it into motion.

    When electricity flows through the motor, it creates a magnetic field. This magnetic field pushes and pulls parts of the motor, causing it to spin. When the motor spins, it makes the wheels spin, and the car moves.

    Unlike gas engines, electric motors don’t make a lot of noise. That’s why electric cars are so quiet—you might not even hear them coming down the street!

    c) The Controller: The Brain of the Car

    The third important part of an electric car is the controller—the brain. The controller decides how much electricity to send from the battery to the motor, just like how your brain tells your legs how fast to pedal when riding a bike.

    When you press the accelerator (the gas pedal in a traditional car, or simply the pedal in an electric car), you’re essentially telling the controller to send more electricity to the motor. Want to go faster? Press down harder, and the controller will deliver more power to the motor. When you want to slow down, you ease up on the pedal, and the controller reduces the flow of electricity.


    3. How Do You Power Up an Electric Car?

    Charging an electric car is as simple as plugging in your phone. Let’s break it down into two main charging options:

    • Charging at Home
    • Charging at a Charging Station

    a) Charging at Home: Your Own Personal Power Station

    Imagine you’ve had a long day, and your phone battery is running low. What do you do? You plug it into the charger at home. Electric cars work the same way. You can plug them into a regular outlet, like you would your phone or laptop, and let it charge overnight. It’s that simple!

    However, just like a phone with a bigger battery takes longer to charge, electric cars take more time because their batteries are much larger. You can also install a faster home charging system that can fully charge the car in 6-8 hours, perfect for overnight charging.

    b) Charging at a Charging Station: The Electric Gas Station

    Now, what if you’re out and about, and your car needs a boost? You go to a charging station—it’s like a gas station but for electric cars. These stations have high-powered chargers that can give your car a quick charge in about 30 minutes to an hour, depending on the station.

    Think of it like going to a coffee shop where they offer fast Wi-Fi. You get a quick burst of internet while you’re sipping your coffee. At a charging station, your car gets a quick burst of electricity, allowing you to get back on the road.

    Also check: How Artificial Intelligence Works


    4. Why Are Electric Cars So Cool?

    Electric cars are special for many reasons. Let’s look at some of the cool benefits they offer.

    a) They’re Good for the Environment

    Unlike gas-powered cars, electric cars don’t have exhaust pipes. They don’t burn fuel and don’t release harmful gases into the air. This means electric cars help reduce pollution, making the air cleaner and better for everyone to breathe.

    Imagine a quiet park with fresh air, birds chirping, and no smog from car fumes. Electric cars help make that possible.

    b) They Save You Money

    Gasoline prices go up and down, but electricity is generally cheaper. Charging your electric car costs less than filling up a gas tank. Over time, this can save you a lot of money. Plus, electric cars have fewer moving parts than traditional cars, so there’s less to maintain, meaning fewer visits to the mechanic.

    c) They’re Fun to Drive

    Electric cars accelerate really fast! Since the motor responds instantly when you press the pedal, electric cars can go from 0 to 60 mph in a matter of seconds. It feels smooth and effortless, almost like gliding on air. Imagine pressing the pedal and zooming ahead—it’s like a futuristic spaceship in the movies.

    Also check: How Cameras Work?


    5. How Do Electric Cars Compare to Gasoline Cars?

    Let’s imagine two friends going on a road trip. One is driving a gasoline car, and the other is driving an electric car. Here’s how their experiences differ:

    • Fuel Efficiency: The gasoline car stops at gas stations along the way, spending money on fuel. Meanwhile, the electric car stops at charging stations, but it spends less money overall on electricity.
    • Environmental Impact: The gasoline car leaves a trail of carbon emissions as it travels, while the electric car leaves none, keeping the air clean.
    • Maintenance: Over time, the gasoline car needs oil changes, new spark plugs, and other maintenance. The electric car? Hardly any of that! It’s simpler and needs less upkeep.
    • Range: Gasoline cars can travel long distances without needing to refuel. Electric cars are catching up, and many now can travel 300 miles or more on a single charge. However, you still need to plan your trip around charging stations if you’re going on a longer journey.

    6. What’s the Future of Electric Cars?

    The future is bright for electric cars. More and more companies are making them, and the technology is improving every year. Batteries are getting better, which means electric cars can travel farther on a single charge. Charging stations are popping up all over, making it easier to keep your car powered up.


    Conclusion

    Electric cars are changing the way we think about transportation. They’re quiet, efficient, and environmentally friendly. With a battery, a motor, and a controller working together, they create a seamless and exciting driving experience. Just like we moved from horses to gas-powered cars, we’re now moving into a future where electric cars take the lead.

    So, the next time you see an electric car gliding silently down the road, you’ll know exactly how it works—and maybe you’ll even want one for yourself!

    The post How Electric Cars Work? appeared first on Learn With Examples.

    ]]>
    https://learnwithexamples.org/how-electric-cars-work/feed/ 0 227