<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Aj</title>
    <description>The latest articles on Forem by Aj (@amedalen).</description>
    <link>https://forem.com/amedalen</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F760847%2F0aeb2bc4-8a67-4c5d-96de-e55ff64af36b.jpeg</url>
      <title>Forem: Aj</title>
      <link>https://forem.com/amedalen</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/amedalen"/>
    <language>en</language>
    <item>
      <title>Feet&amp;Yard to meter converter</title>
      <dc:creator>Aj</dc:creator>
      <pubDate>Tue, 21 Jan 2025 03:31:18 +0000</pubDate>
      <link>https://forem.com/amedalen/feetyard-to-meter-converter-407n</link>
      <guid>https://forem.com/amedalen/feetyard-to-meter-converter-407n</guid>
      <description>&lt;p&gt;Hello Everyone &lt;/p&gt;

&lt;p&gt;I'm going to show you how to create a Feet &amp;amp; Yard to Meter converter web app in Rust with Web assembly.&lt;/p&gt;

&lt;p&gt;First you need to install Rust on your PC using this link &lt;code&gt;https://www.rust-lang.org/tools/install&lt;/code&gt; then we need to create the main folder "I named it yardandfeetconverter you can of course name it as you like" that will have all necessary files by using cargo command as the following:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cargo new yardandfeetconverter&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;After that we need to configure cargo.toml file by adding the following&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
[dependencies]
wasm-bindgen = "0.2"

[lib]
crate-type = ["cdylib"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;save the changes and then navigate to src folder in the main folder that we created and rename main.rs file to lib.rs and open it in an editor and add the following code to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use wasm_bindgen::prelude::*;

// Convert yards to meters
#[wasm_bindgen]
pub fn yards_to_meters(yards: f64) -&amp;gt; f64 {
    yards * 0.9144
}

// Convert feet to meters
#[wasm_bindgen]
pub fn feet_to_meters(feet: f64) -&amp;gt; f64 {
    feet * 0.3048
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then save it and open Powershell in windows to create files needed for web using webassembly :&lt;/p&gt;

&lt;p&gt;&lt;code&gt;wasm-pack build --target web&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will create files needed for web.&lt;/p&gt;

&lt;p&gt;After that navigate to the main folder yardandfeetconverter and create index.html file then add the following code to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset="UTF-8"&amp;gt;
  &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
  &amp;lt;title&amp;gt;Yard and Feet to Meters Converter&amp;lt;/title&amp;gt;
  &amp;lt;script type="module"&amp;gt;
    import init, { yards_to_meters, feet_to_meters } from "./pkg/yardandfeetconverter.js";

    async function setup() {
      await init();

      document.getElementById('convert').addEventListener('click', () =&amp;gt; {
        const value = parseFloat(document.getElementById('value').value);
        const type = document.getElementById('unit').value;
        let result;

        if (type === 'yards') {
          result = yards_to_meters(value);
        } else {
          result = feet_to_meters(value);
        }

        document.getElementById('result').innerText = `Result: ${result.toFixed(4)} meters`;
      });
    }

    setup();
  &amp;lt;/script&amp;gt;
  &amp;lt;style&amp;gt;
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      background: linear-gradient(to right, #4facfe, #00f2fe);
    }
    .container {
      text-align: center;
      background: white;
      padding: 2rem;
      border-radius: 10px;
      box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
    }
    input, select, button {
      margin: 10px;
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }
    button {
      background-color: #4facfe;
      color: white;
      cursor: pointer;
    }
    button:hover {
      background-color: #00c4cc;
    }
  &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;div class="container"&amp;gt;
    &amp;lt;h1&amp;gt;Yard &amp;amp; Feet to Meters Converter&amp;lt;/h1&amp;gt;
    &amp;lt;p&amp;gt;Enter a value and select the unit to convert:&amp;lt;/p&amp;gt;
    &amp;lt;input type="number" id="value" placeholder="Enter value" /&amp;gt;
    &amp;lt;select id="unit"&amp;gt;
      &amp;lt;option value="yards"&amp;gt;Yards&amp;lt;/option&amp;gt;
      &amp;lt;option value="feet"&amp;gt;Feet&amp;lt;/option&amp;gt;
    &amp;lt;/select&amp;gt;
    &amp;lt;button id="convert"&amp;gt;Convert&amp;lt;/button&amp;gt;
    &amp;lt;p id="result" style="margin-top: 20px; font-size: 20px;"&amp;gt;&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and save the file and then open Powershell again navigate to the main folder and then start a local server on your computer using the following command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python -m http.server&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;this will create a local server running on port 8000&lt;/p&gt;

&lt;p&gt;so open a web browser page and type in the address field &lt;/p&gt;

&lt;p&gt;&lt;code&gt;localhost:8000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;That's it you've done it now you can convert yards and feet to meters.&lt;/p&gt;

&lt;p&gt;Thank you and happy coding.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>webassembly</category>
      <category>html</category>
      <category>css</category>
    </item>
    <item>
      <title>Time finder of any city in the world in Python + Flask</title>
      <dc:creator>Aj</dc:creator>
      <pubDate>Tue, 10 Dec 2024 23:16:32 +0000</pubDate>
      <link>https://forem.com/amedalen/time-finder-of-any-city-in-the-world-in-python-flask-p3f</link>
      <guid>https://forem.com/amedalen/time-finder-of-any-city-in-the-world-in-python-flask-p3f</guid>
      <description>&lt;p&gt;Hi everyone, I'm going to show you how to create a simple web app in python that will retrieve time in any city in the world.&lt;/p&gt;

&lt;p&gt;First we need to make sure that python is installed you can visit their website for how to install it (&lt;a href="https://www.python.org/downloads/windows/" rel="noopener noreferrer"&gt;https://www.python.org/downloads/windows/&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Then make sure to install Flask to run your app on the web you can install it by opening a command prompt or Powershell in Window and run this command:&lt;br&gt;
&lt;code&gt;pip install flask&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And then to ensure that the app can retrieve any city we need to install this library with this command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;pip install geopy timezonefinder pytz&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then create a folder named time for example you can choose any name and inside it create a file named app.py you can do that by right click anywhere in the empty space inside the folder you created and choose text file then name it to app.py with then open it in text editor I use notepad++ you can download it from this link &lt;br&gt;
(&lt;a href="https://notepad-plus-plus.org/downloads/" rel="noopener noreferrer"&gt;https://notepad-plus-plus.org/downloads/&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Here is the code you need to copy it and paste it inside app.py file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, request, render_template_string
from datetime import datetime
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
import pytz

app = Flask(__name__)

# HTML template
html_template = """
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;City Time Zone&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            color: #333;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .container {
            text-align: center;
            background: #ffffff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            width: 400px;
        }
        h1 {
            font-size: 24px;
            margin-bottom: 20px;
        }
        form {
            margin-bottom: 20px;
        }
        input[type="text"] {
            padding: 10px;
            font-size: 16px;
            width: calc(100% - 24px);
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #007BFF;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .error {
            color: red;
            margin-top: 10px;
        }
        .time {
            margin-top: 20px;
            font-size: 18px;
            font-weight: bold;
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;div class="container"&amp;gt;
        &amp;lt;h1&amp;gt;Enter a City to Get the Current Time&amp;lt;/h1&amp;gt;
        &amp;lt;form method="post"&amp;gt;
            &amp;lt;input type="text" id="city" name="city" placeholder="Enter city name" required&amp;gt;
            &amp;lt;button type="submit"&amp;gt;Get Time&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
        {% if error %}
            &amp;lt;p class="error"&amp;gt;{{ error }}&amp;lt;/p&amp;gt;
        {% endif %}
        {% if time %}
            &amp;lt;p class="time"&amp;gt;The current time in {{ city }} is: {{ time }}&amp;lt;/p&amp;gt;
        {% endif %}
    &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
"""

@app.route('/', methods=['GET', 'POST'])
def index():
    error = None
    current_time = None
    city = None

    if request.method == 'POST':
        city = request.form.get('city')
        if city:
            city = city.strip()
            try:
                # Geocode the city to get latitude and longitude
                geolocator = Nominatim(user_agent="timezone_app")
                location = geolocator.geocode(city)

                if not location:
                    raise ValueError("City not found. Please check the spelling or try another city.")

                # Find the timezone based on latitude and longitude
                tf = TimezoneFinder()
                timezone_name = tf.timezone_at(lng=location.longitude, lat=location.latitude)

                if not timezone_name:
                    raise ValueError("Could not determine the timezone for this location.")

                # Get the current time in the timezone
                timezone = pytz.timezone(timezone_name)
                current_time = datetime.now(timezone).strftime('%Y-%m-%d %H:%M:%S')
            except Exception as e:
                error = str(e)
        else:
            error = "City name cannot be empty."

    return render_template_string(html_template, error=error, time=current_time, city=city)

if __name__ == '__main__':
    app.run(debug=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now your app is almost ready one final step is to start it by using this command in command prompt or Powershell remember you have to navigate to the exact location of your folder and be inside it when you run this command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;python app.py&lt;/code&gt;  &lt;/p&gt;

&lt;p&gt;Then open up a web browser and type in the address field:&lt;br&gt;
&lt;code&gt;localhost:5000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I hope you like it thank you so much and enjoy.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Tic Tac Toe in Rust + Webassembly</title>
      <dc:creator>Aj</dc:creator>
      <pubDate>Tue, 10 Dec 2024 00:30:26 +0000</pubDate>
      <link>https://forem.com/amedalen/tic-tac-toe-in-rust-webassembly-1p73</link>
      <guid>https://forem.com/amedalen/tic-tac-toe-in-rust-webassembly-1p73</guid>
      <description>&lt;p&gt;Hello everyone I'm going to show you how to create a simple Tic-Tac-Toe game in Rust with Webassembly.&lt;/p&gt;

&lt;p&gt;First you need to install Rust you can do that by visiting official site (&lt;a href="https://www.rust-lang.org/tools/install" rel="noopener noreferrer"&gt;https://www.rust-lang.org/tools/install&lt;/a&gt;) &lt;/p&gt;

&lt;p&gt;Then in Windows open a terminal or Powershell and make sure to run it as administrator and type the following command to create needed files and folders for your Rust game &lt;code&gt;cargo new the name you want for the folder&lt;/code&gt; after that navigate to your folder location using file explorer inside src folder which will be created you will find main.rs file right click and rename it to lib.rs &lt;/p&gt;

&lt;p&gt;While you're there you can right click the file to open it in an editor of your choice you can use notepad++ which could be downloaded from (&lt;a href="https://notepad-plus-plus.org/downloads/" rel="noopener noreferrer"&gt;https://notepad-plus-plus.org/downloads/&lt;/a&gt;) and here is the code you need for lib.rs file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use wasm_bindgen::prelude::*;
use serde::Serialize;

#[wasm_bindgen]
pub struct TicTacToe {
    board: Vec&amp;lt;String&amp;gt;,
    current_player: String,
    game_over: bool,
    winner: Option&amp;lt;String&amp;gt;,
}

#[derive(Serialize)]
struct GameState {
    board: Vec&amp;lt;String&amp;gt;,
    current_player: String,
    game_over: bool,
    winner: Option&amp;lt;String&amp;gt;,
}

#[wasm_bindgen]
impl TicTacToe {
    #[wasm_bindgen(constructor)]
    pub fn new() -&amp;gt; TicTacToe {
        TicTacToe {
            board: vec!["".to_string(); 9],
            current_player: "X".to_string(),
            game_over: false,
            winner: None,
        }
    }

    /// Handles a player's turn and returns the updated game state as a JSON string.
    pub fn play_turn(&amp;amp;mut self, index: usize) -&amp;gt; String {
        if self.game_over || !self.board[index].is_empty() {
            return self.get_state();
        }

        self.board[index] = self.current_player.clone();
        if self.check_winner() {
            self.game_over = true;
            self.winner = Some(self.current_player.clone());
        } else if !self.board.contains(&amp;amp;"".to_string()) {
            self.game_over = true; // Draw
        } else {
            self.current_player = if self.current_player == "X" {
                "O".to_string()
            } else {
                "X".to_string()
            };
        }

        self.get_state()
    }

    /// Resets the game to its initial state and returns the game state as a JSON string.
    pub fn reset(&amp;amp;mut self) -&amp;gt; String {
        self.board = vec!["".to_string(); 9];
        self.current_player = "X".to_string();
        self.game_over = false;
        self.winner = None;
        self.get_state()
    }

    /// Returns the current game state as a JSON string.
    pub fn get_state(&amp;amp;self) -&amp;gt; String {
        let state = GameState {
            board: self.board.clone(),
            current_player: self.current_player.clone(),
            game_over: self.game_over,
            winner: self.winner.clone(),
        };
        serde_json::to_string(&amp;amp;state).unwrap()
    }

    fn check_winner(&amp;amp;self) -&amp;gt; bool {
        let win_patterns = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
            [0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
            [0, 4, 8], [2, 4, 6],           // Diagonals
        ];
        win_patterns.iter().any(|&amp;amp;line| {
            let [a, b, c] = line;
            !self.board[a].is_empty()
                &amp;amp;&amp;amp; self.board[a] == self.board[b]
                &amp;amp;&amp;amp; self.board[b] == self.board[c]
        })
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After make sure to save it and then navigate to your main folder and this time right click and edit Cargo.toml file and paste this code in it right at the end of [package] code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
[dependencies]
wasm-bindgen = "0.2" # Enables Wasm interop
serde = { version = "1.0", features = ["derive"] } # For serialization/deserialization
serde_json = "1.0" # Optional, if you use JSON in your app

[lib]
crate-type = ["cdylib"] # Required for WebAssembly

[features]
default = ["wee_alloc"]

[profile.release]
opt-level = "z" # Optimize for size, which is ideal for WebAssembly.

[dependencies.wee_alloc]
version = "0.4.5" # Optional, for smaller Wasm binary size
optional = true

[dev-dependencies]
wasm-bindgen-test = "0.3" # Optional, for testing in Wasm




&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then save it as well and this time we need to get back to our terminal or Powershell and go to your main folder that you created with cargo command at the beginning and make sure you are inside your main folder by typing &lt;code&gt;cd then your folder name&lt;/code&gt; then type this command to create web files and folders needed:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;wasm-pack build --target web&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;After that step you will notice that Webassembly has created more files and folders inside your main folder needed to run Rust code on the web, at this point from file explorer go to your main folder then create a new file by right click anywhere at the empty space inside the main folder that you created with cargo new command and click new then text document rename the new file index.html and open it in code editor in this case for example notepad++ just right click it and choose edit with notepad then paste this HTML code in it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Tic Tac Toe&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0;
            background: linear-gradient(to bottom right, #6a11cb, #2575fc);
            color: white;
        }

        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
        }

        #status {
            font-size: 1.25rem;
            margin-bottom: 20px;
            padding: 10px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 8px;
        }

        #board {
            display: grid;
            grid-template-columns: repeat(3, 100px);
            gap: 10px;
        }

        .cell {
            width: 100px;
            height: 100px;
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.5);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            font-weight: bold;
            color: white;
            box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
            transition: transform 0.2s, background 0.3s;
            cursor: pointer;
        }

        .cell.taken {
            cursor: not-allowed;
            background: rgba(255, 255, 255, 0.5);
            color: black;
        }

        .cell:hover:not(.taken) {
            transform: scale(1.1);
            background: rgba(255, 255, 255, 0.4);
        }

        #reset {
            margin-top: 20px;
            padding: 10px 30px;
            font-size: 1.25rem;
            font-weight: bold;
            color: #6a11cb;
            background: white;
            border: none;
            border-radius: 5px;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
            cursor: pointer;
            transition: background 0.3s, transform 0.2s;
        }

        #reset:hover {
            background: #f0f0f0;
            transform: scale(1.05);
        }

        #reset:active {
            transform: scale(0.95);
        }

        footer {
            margin-top: 20px;
            font-size: 0.9rem;
            opacity: 1.0;
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Tic Tac Toe&amp;lt;/h1&amp;gt;
    &amp;lt;div id="status"&amp;gt;Loading game...&amp;lt;/div&amp;gt;
    &amp;lt;div id="board"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;button id="reset"&amp;gt;Reset Game&amp;lt;/button&amp;gt;
    &amp;lt;footer&amp;gt;Built with ❤️ using Rust and WebAssembly&amp;lt;/footer&amp;gt;
    &amp;lt;script type="module"&amp;gt;
        import init, { TicTacToe } from './pkg/tac.js';

        async function run() {
            await init();

            const game = new TicTacToe();
            const boardElement = document.getElementById('board');
            const statusElement = document.getElementById('status');
            const resetButton = document.getElementById('reset');

            function render() {
                const state = JSON.parse(game.get_state());
                boardElement.innerHTML = '';

                state.board.forEach((cell, index) =&amp;gt; {
                    const cellElement = document.createElement('div');
                    cellElement.className = 'cell' + (cell ? ' taken' : '');
                    cellElement.textContent = cell;
                    if (!cell) {
                        cellElement.addEventListener('click', () =&amp;gt; {
                            game.play_turn(index);
                            render();
                        });
                    }
                    boardElement.appendChild(cellElement);
                });

                if (state.game_over) {
                    statusElement.textContent = state.winner
                        ? `${state.winner} wins! 🎉`
                        : 'It\'s a draw! ✨';
                } else {
                    statusElement.textContent = `Current turn: ${state.current_player}`;
                }
            }

            resetButton.addEventListener('click', () =&amp;gt; {
                game.reset();
                render();
            });

            render();
        }

        run();
    &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just make sure in this line of code &lt;code&gt;import init, { TicTacToe } from './pkg/type the name of javascript file located in pkg folder inside your main folder.js';&lt;/code&gt; inside your main folder wasm command created a folder named "pkg" inside it you will find a javascript file ends in .js extension just make sure to type the name correctly in that line of code to point to it, save it and close the file.&lt;/p&gt;

&lt;p&gt;Now your web application game is ready to launch, just one last thing we need to create a web server to host it in this case just get back to terminal windows or Powershell and navigate to your folder path make sure you're inside the folder using &lt;code&gt;cd&lt;/code&gt; command and initiate the server by typing this command &lt;code&gt;python -m http.server&lt;/code&gt; to install python follow this link (&lt;a href="https://www.python.org/downloads/windows/" rel="noopener noreferrer"&gt;https://www.python.org/downloads/windows/&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Now open a web browser page and type in the address field &lt;br&gt;
&lt;code&gt;http://localhost:8000/&lt;/code&gt; or &lt;code&gt;http://127.0.0.1:8000&lt;/code&gt;  to play the game.&lt;/p&gt;

&lt;p&gt;I hope you enjoy it and apologies for the long post.&lt;/p&gt;

&lt;p&gt;Thank you so much. Enjoy!.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>html</category>
      <category>javascript</category>
      <category>webassembly</category>
    </item>
    <item>
      <title>Currency converter in Rust + WebAssembly</title>
      <dc:creator>Aj</dc:creator>
      <pubDate>Sat, 30 Nov 2024 16:18:58 +0000</pubDate>
      <link>https://forem.com/amedalen/currency-converter-in-rust-webassembly-77p</link>
      <guid>https://forem.com/amedalen/currency-converter-in-rust-webassembly-77p</guid>
      <description>&lt;p&gt;Hi everyone in this post I'm going to show you how to create a simple currency converter written in Rust with WebAssembly, first you need to install Rust using Rust official website below for windows:&lt;/p&gt;

&lt;p&gt;(&lt;a href="https://www.rust-lang.org/tools/install" rel="noopener noreferrer"&gt;https://www.rust-lang.org/tools/install&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;After you install Rust successfully we need to make sure we install WASM or WebAssembly using command below by opening Windows Powershell and run it as administrator:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cargo install wasm-pack&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Cargo is a build system and package manager for Rust.&lt;/p&gt;

&lt;p&gt;We install Wasm pack or WebAssembly to run Rust on Web view and run HTML code so after successfully installing WebAssembly in Windows Powershell choose the path you want to create files for Rust and then type the command below to create folder and files necessary:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cargo new **folder name of your choice here** --lib&lt;/code&gt;&lt;br&gt;
this will create the folder name and files necessary for Rust to run with WebAssembly.&lt;/p&gt;

&lt;p&gt;Then we need to modify Cargo.toml file located in your folder that you created with the above command, right click and edit I use notepad++ (to download notepad++ use this link (&lt;a href="https://notepad-plus-plus.org/" rel="noopener noreferrer"&gt;https://notepad-plus-plus.org/&lt;/a&gt;) so you will get the option to edit file directly.&lt;/p&gt;

&lt;p&gt;in Cargo.toml file write this in it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[dependencies]
reqwest = { version = "=0.11.7", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"

[dev-dependencies]
wasm-bindgen-test = "0.3"

[lib]
crate-type = ["cdylib"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then inside src folder located inside your main folder that first created with Cargo command you will find another file we need to edit it's called lib.rs in this file we will write Rust code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use reqwest::Error;
use serde::Deserialize;
use std::collections::HashMap;

#[derive(Deserialize)]
struct ExchangeRates {
    rates: HashMap&amp;lt;String, f64&amp;gt;,
}

#[wasm_bindgen]
pub async fn convert_currency(base: String, target: String, amount: f64) -&amp;gt; Result&amp;lt;JsValue, JsValue&amp;gt; {
    let url = format!("https://api.exchangerate-api.com/v4/latest/{}", base);

    let response = reqwest::get(&amp;amp;url)
        .await
        .map_err(|err| JsValue::from_str(&amp;amp;format!("Failed to fetch rates: {}", err)))?;

    let rates: ExchangeRates = response.json()
        .await
        .map_err(|err| JsValue::from_str(&amp;amp;format!("Invalid response format: {}", err)))?;

    if let Some(&amp;amp;rate) = rates.rates.get(&amp;amp;target) {
        let converted = amount * rate;
        Ok(JsValue::from_f64(converted)) // Return the converted amount
    } else {
        Err(JsValue::from_str(&amp;amp;format!("Currency {} not found", target)))
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we will get to the part where we need to create folders and files needed for web view.&lt;br&gt;
Open Powershell then navigate to your folder path make sure you're inside the main folder you created with Cargo new command then run this command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;wasm-pack build --target web&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will create folders named pkg and target and other files.&lt;/p&gt;

&lt;p&gt;Then at your main folder that you created with  &lt;code&gt;cargo new folder name here --lib&lt;/code&gt; create HTML file named index.html inside it write this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset="UTF-8"&amp;gt;
  &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
  &amp;lt;title&amp;gt;Currency Converter&amp;lt;/title&amp;gt;
  &amp;lt;style&amp;gt;
    body {
      font-family: Arial, sans-serif;
      background-color: #f0f8ff;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }

    .container {
      background: #ffffff;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      border-radius: 10px;
      padding: 20px 30px;
      width: 350px;
      text-align: center;
    }

    h1 {
      color: #333;
      margin-bottom: 20px;
    }

    label {
      display: block;
      margin: 10px 0 5px;
      font-weight: bold;
      color: #555;
    }

    input {
      width: 100%;
      padding: 10px;
      margin-bottom: 15px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 16px;
    }

    button {
      width: 100%;
      padding: 10px;
      background-color: #007bff;
      border: none;
      border-radius: 5px;
      color: white;
      font-size: 16px;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    button:hover {
      background-color: #0056b3;
    }

    .result {
      margin-top: 20px;
      font-size: 18px;
      color: green;
      font-weight: bold;
    }

    .error {
      margin-top: 20px;
      font-size: 16px;
      color: red;
    }
  &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;div class="container"&amp;gt;
    &amp;lt;h1&amp;gt;Currency Converter&amp;lt;/h1&amp;gt;
    &amp;lt;form id="convert-form"&amp;gt;
      &amp;lt;label for="base"&amp;gt;Base Currency:&amp;lt;/label&amp;gt;
      &amp;lt;input type="text" id="base" name="base" placeholder="e.g., USD" required&amp;gt;

      &amp;lt;label for="target"&amp;gt;Target Currency:&amp;lt;/label&amp;gt;
      &amp;lt;input type="text" id="target" name="target" placeholder="e.g., EUR" required&amp;gt;

      &amp;lt;label for="amount"&amp;gt;Amount:&amp;lt;/label&amp;gt;
      &amp;lt;input type="number" id="amount" name="amount" placeholder="e.g., 100" required&amp;gt;

      &amp;lt;button type="submit"&amp;gt;Convert&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
    &amp;lt;div class="result" id="result"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;div class="error" id="error"&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;

  &amp;lt;script type="module"&amp;gt;
  import init, { convert_currency } from "../pkg/name of your folder.js";

  async function main() {
    await init();

    const form = document.getElementById("convert-form");
    const resultDiv = document.getElementById("result");
    const errorDiv = document.getElementById("error");

    form.addEventListener("submit", async (event) =&amp;gt; {
      event.preventDefault();

      // Clear previous messages
      resultDiv.textContent = "";
      errorDiv.textContent = "";

      const base = document.getElementById("base").value.toUpperCase();
      const target = document.getElementById("target").value.toUpperCase();
      const amount = parseFloat(document.getElementById("amount").value);

      if (isNaN(amount) || amount &amp;lt;= 0) {
        errorDiv.textContent = "Please enter a valid amount.";
        return;
      }

      try {
        const convertedAmount = await convert_currency(base, target, amount);
        if (convertedAmount === null || isNaN(convertedAmount)) {
          throw new Error("Invalid conversion result.");
        }

        resultDiv.textContent = `${amount} ${base} = ${convertedAmount.toFixed(2)} ${target}`;
      } catch (err) {
        errorDiv.textContent = `Error: ${err.message || err}`;
      }
    });
  }

  main();
&amp;lt;/script&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make sure that this line &lt;code&gt;import init, { convert_currency } from "../pkg/**name of your folder.js**";&lt;/code&gt; javascript file found in pkg folder make sure it points to the correct .js file normally it's named after your main folder name ends in .js found inside pkg folder.&lt;/p&gt;

&lt;p&gt;To run your server on local machine navigate to your main folder that we created with &lt;code&gt;cargo new **folder name here** --lib&lt;/code&gt; and run this command to start server on your machine:&lt;br&gt;
&lt;code&gt;python -m http.server&lt;/code&gt;&lt;br&gt;&lt;br&gt;
to install python refer to &lt;br&gt;
(&lt;a href="https://www.python.org/downloads/windows/" rel="noopener noreferrer"&gt;https://www.python.org/downloads/windows/&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;after running the command, open web browser of your choice and type &lt;code&gt;localhost:8000&lt;/code&gt; or &lt;code&gt;127.0.0.1:8000&lt;/code&gt; and the enter.&lt;/p&gt;

&lt;p&gt;You need to enter currency codes for that check this website:&lt;br&gt;
&lt;code&gt;https://taxsummaries.pwc.com/glossary/currency-codes&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Hope you enjoy it and apologies for the long post.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>webassembly</category>
      <category>javascript</category>
      <category>html</category>
    </item>
    <item>
      <title>Currency Converter in python with Flask</title>
      <dc:creator>Aj</dc:creator>
      <pubDate>Fri, 29 Nov 2024 17:06:23 +0000</pubDate>
      <link>https://forem.com/amedalen/currency-converter-in-python-2kh2</link>
      <guid>https://forem.com/amedalen/currency-converter-in-python-2kh2</guid>
      <description>&lt;p&gt;Hi everyone I'll show you today how to create a simple currency converter in Python and Flask to display it on the web.&lt;/p&gt;

&lt;p&gt;First we need to make sure that Flask is installed properly, to do that open Powershell or CMD in windows and make sure to run it as administrator by right click it and then run as Administrator, Flask is easy to install by typing this command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;pip install flask&lt;/code&gt;  &lt;/p&gt;

&lt;p&gt;After installing Python ofcourse you can check this link on how to install Python on windows:&lt;/p&gt;

&lt;p&gt;(&lt;a href="https://www.geeksforgeeks.org/how-to-install-python-on-windows/" rel="noopener noreferrer"&gt;https://www.geeksforgeeks.org/how-to-install-python-on-windows/&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;After installing Flask successfully create a folder named currency_converter and inside that folder create a txt file called app.py and make sure to change extension from .txt to .py and then inside currency_converter folder create another folder named (templates) and make sure that this folder named exactly as templates otherwise Flask won't run, then inside templates folder create a single file named index.html you can just create a txt file then rename it index.html and make sure the extension is .html&lt;/p&gt;

&lt;p&gt;Here is the code for app.py file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, render_template, request, redirect, url_for
import requests

app = Flask(__name__)

API_URL = "https://api.exchangerate-api.com/v4/latest/{}"

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        from_currency = request.form["from_currency"].upper()
        to_currency = request.form["to_currency"].upper()
        amount = float(request.form["amount"])

        # Fetch exchange rate data
        response = requests.get(API_URL.format(from_currency))
        if response.status_code == 200:
            data = response.json()
            rates = data.get("rates", {})
            if to_currency in rates:
                conversion_rate = rates[to_currency]
                converted_amount = amount * conversion_rate
                return render_template(
                    "index.html",
                    converted_amount=converted_amount,
                    from_currency=from_currency,
                    to_currency=to_currency,
                    amount=amount,
                )
            else:
                error = f"Currency '{to_currency}' not found."
                return render_template("index.html", error=error)
        else:
            error = f"Error fetching data for '{from_currency}'."
            return render_template("index.html", error=error)

    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And here is the code for HTML file with css:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Currency Converter&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
        /* General body styling */
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #6dd5fa, #2980b9);
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        /* Centering the container */
        .container {
            background: #ffffff10; /* Semi-transparent white */
            border-radius: 10px;
            padding: 20px 30px;
            max-width: 400px;
            width: 100%;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
            text-align: center;
        }

        /* Header styling */
        h1 {
            font-size: 28px;
            margin-bottom: 20px;
            color: #fff;
            text-shadow: 1px 1px 4px rgba(0, 0, 0, 0.8);
        }

        /* Input and button styling */
        input, button {
            display: block;
            width: 100%;
            margin: 10px 0;
            padding: 12px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
        }

        input {
            background: #ffffff80; /* Semi-transparent white */
            color: #333;
        }

        button {
            background: #2980b9;
            color: #fff;
            font-weight: bold;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        button:hover {
            background: #1e5786;
        }

        /* Result message styling */
        .result {
            background: red;
            padding: 10px;
            border-radius: 5px;
            margin-top: 20px;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.7);
        }

        .result p {
            margin: 0;
            font-size: 18px;
        }

        /* Error message styling */
        .error {
            color: #ff4d4d;
            margin: 10px 0;
            font-weight: bold;
        }

        /* Responsive design */
        @media (max-width: 480px) {
            .container {
                padding: 15px 20px;
            }

            h1 {
                font-size: 22px;
            }

            input, button {
                font-size: 14px;
            }
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;div class="container"&amp;gt;
        &amp;lt;h1&amp;gt;Currency Converter&amp;lt;/h1&amp;gt;
        {% if error %}
            &amp;lt;p class="error"&amp;gt;{{ error }}&amp;lt;/p&amp;gt;
        {% endif %}
        {% if converted_amount %}
            &amp;lt;div class="result"&amp;gt;
                &amp;lt;p&amp;gt;{{ amount }} {{ from_currency }} = {{ converted_amount | round(2) }} {{ to_currency }}&amp;lt;/p&amp;gt;
            &amp;lt;/div&amp;gt;
        {% endif %}
        &amp;lt;form method="POST" action="/"&amp;gt;
            &amp;lt;input type="text" name="from_currency" placeholder="From currency (e.g., USD)" required&amp;gt;
            &amp;lt;input type="text" name="to_currency" placeholder="To currency (e.g., EUR)" required&amp;gt;
            &amp;lt;input type="number" step="0.01" name="amount" placeholder="Amount" required&amp;gt;
            &amp;lt;button type="submit"&amp;gt;Convert&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then open Powershell or CMD and navigate to your currency_converter folder location and type:&lt;br&gt;
&lt;code&gt;flask run&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will create a webserver on your machine with ip and port number as the following:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;http://127.0.0.1:5000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Open a web browser then copy this address and paste it in your browser and try the currency converter.&lt;/p&gt;

&lt;p&gt;For the currency list of codes check this web site:&lt;/p&gt;

&lt;p&gt;(&lt;a href="https://taxsummaries.pwc.com/glossary/currency-codes" rel="noopener noreferrer"&gt;https://taxsummaries.pwc.com/glossary/currency-codes&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Enjoy and thank you so much.&lt;/p&gt;

</description>
      <category>python</category>
      <category>html</category>
      <category>flask</category>
      <category>web</category>
    </item>
    <item>
      <title>Any Country's capital finder in Python</title>
      <dc:creator>Aj</dc:creator>
      <pubDate>Tue, 26 Nov 2024 13:52:34 +0000</pubDate>
      <link>https://forem.com/amedalen/any-countrys-capital-finder-1dfd</link>
      <guid>https://forem.com/amedalen/any-countrys-capital-finder-1dfd</guid>
      <description>&lt;p&gt;Hello Everyone! I'm going to show you how to create an app running on Flask python webframework that will get any country's capital based on user input written in python.&lt;/p&gt;

&lt;p&gt;First you need to create a new folder let's name it country_capital_finder and create a txt file named (app) then change it's extension to be app.py that will be the python file containing the python code, and then inside that folder create another folder named (templates) and inside templates folder create another txt file named index change its extension to index.html, it's very important to create the folder structure and templates folder name exactly as templates otherwise Flask won't be able to run.&lt;/p&gt;

&lt;p&gt;Now the fun part here is the python code for app.py file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, render_template, request
from countryinfo import CountryInfo

app = Flask(__name__)

# Function to get the capital of a country
def get_country_capital(country_name):
    country = CountryInfo(country_name)
    try:
        capital = country.capital()
        return capital
    except:
        return None

@app.route('/', methods=['GET', 'POST'])
def index():
    capital_info = None
    if request.method == 'POST':
        country_name = request.form.get('country_name')
        capital = get_country_capital(country_name)
        if capital:
            capital_info = f"The capital of {country_name} is {capital}."
        else:
            capital_info = f"Sorry, we couldn't find the capital for {country_name}."

    return render_template('index.html', capital_info=capital_info)

if __name__ == '__main__':
    app.run(debug=True)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you're done with python file app.py go to index.html and write this HTML and CSS code in it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Country Capital Finder&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
        body {
            font-family: Arial, sans-serif;
            margin: 50px;
        }
        form {
            margin-bottom: 20px;
        }
        input[type="text"] {
            padding: 10px;
            margin-right: 10px;
            font-size: 16px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
        }
        .result {
            margin-top: 20px;
            font-size: 18px;
            font-weight: bold;
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Find the Capital of a Country&amp;lt;/h1&amp;gt;

    &amp;lt;form method="POST"&amp;gt;
        &amp;lt;label for="country_name"&amp;gt;Enter Country Name:&amp;lt;/label&amp;gt;
        &amp;lt;input type="text" id="country_name" name="country_name" required&amp;gt;
        &amp;lt;button type="submit"&amp;gt;Find Capital&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;

    {% if capital_info %}
        &amp;lt;div class="result"&amp;gt;{{ capital_info }}&amp;lt;/div&amp;gt;
    {% endif %}

    &amp;lt;footer&amp;gt;
        &amp;lt;p&amp;gt;Want to search again? &amp;lt;a href="/"&amp;gt;Click here&amp;lt;/a&amp;gt;&amp;lt;/p&amp;gt;
    &amp;lt;/footer&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that you have all code done we need to first install Flask on your computer if it's not installed using this command by opening CMD or powershell in Windows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;pip install flask&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;Make sure that the folder structure should be as the following:&lt;br&gt;
Main folder country_capital_finder contains a file named app.py and folder named templates, then inside templates folder there is only one file which is index.html.&lt;/p&gt;

&lt;p&gt;Then navigate to country_capital_finder folder from CMD or Powershell in windows and make sure to run the following command while you're at that path:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Flask run&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;Then copy the address below and open a web browser page and paste it in the webpage:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://127.0.0.1:5000" rel="noopener noreferrer"&gt;http://127.0.0.1:5000&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To change ip address to your machine's ip for example type this command:&lt;br&gt;
&lt;code&gt;flask run --host=0.0.0.0&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;to specify the port number type this:&lt;br&gt;
&lt;code&gt;flask run --port=8080&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You should be able to see a box where you can type any country's name and click Find Capital this should display the capital of the country you entered as the screenshot below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5aaesme3c106rsugao1h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5aaesme3c106rsugao1h.png" alt="Image description" width="800" height="312"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Enjoy it and thank you so much. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>flask</category>
      <category>python</category>
      <category>webdev</category>
    </item>
    <item>
      <title>App in html to display any country's flag</title>
      <dc:creator>Aj</dc:creator>
      <pubDate>Mon, 25 Nov 2024 17:59:52 +0000</pubDate>
      <link>https://forem.com/amedalen/app-in-html-to-display-any-countrys-flag-n2e</link>
      <guid>https://forem.com/amedalen/app-in-html-to-display-any-countrys-flag-n2e</guid>
      <description>&lt;p&gt;Hello everyone! I'm pleased to introduce an app in html css and js that displays any country's flag based on user input, the app works only with country codes for example USA will be US in the user input field due to api limitation, for the complete list of country codes pls visit (&lt;a href="https://flagcdn.com/en/codes.json" rel="noopener noreferrer"&gt;https://flagcdn.com/en/codes.json&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;I've created three files HTML JS and CSS, CSS named style.css and JS is script.js and the HTML is index.html&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;First JS code as the following:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('getFlagBtn').addEventListener('click', function() {
    const countryName = document.getElementById('countryInput').value.trim();

    if (countryName === "") {
        alert("Please enter a country name.");
        return;
    }

    // Normalize the country name (convert to lowercase and replace spaces with dashes)
    const formattedCountryName = countryName.toLowerCase().replace(/\s+/g, '-');

    // Fetch flag image from the Flag CDN API
    const flagUrl = `https://flagcdn.com/w320/${formattedCountryName}.png`;

    // Check if the image exists (simple check by testing the image URL)
    const flagImage = new Image();
    flagImage.onload = function() {
        document.getElementById('flagDisplay').innerHTML = `&amp;lt;img src="${flagUrl}" alt="Flag of ${countryName}" /&amp;gt;`;
    };
    flagImage.onerror = function() {
        alert("Flag not found. Please check the country name.");
        document.getElementById('flagDisplay').innerHTML = ''; // Clear any previous flag
    };

    // Start loading the image
    flagImage.src = flagUrl;
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;As for the html check the following:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Country Flag Finder&amp;lt;/title&amp;gt;
    &amp;lt;link rel="stylesheet" href="style.css"&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;div class="container"&amp;gt;
        &amp;lt;h1&amp;gt;Country Flag Finder&amp;lt;/h1&amp;gt;
        &amp;lt;input type="text" id="countryInput" placeholder="Enter country name" /&amp;gt;
        &amp;lt;button id="getFlagBtn"&amp;gt;Get Flag&amp;lt;/button&amp;gt;
        &amp;lt;div id="flagDisplay"&amp;gt;
            &amp;lt;!-- The flag image will be displayed here --&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;script src="script.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Finally for the CSS:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.container {
    text-align: center;
    padding: 20px;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    width: 300px;
}

h1 {
    color: #333;
}

#countryInput {
    padding: 10px;
    margin-top: 10px;
    width: 80%;
    font-size: 16px;
}

button {
    padding: 10px 20px;
    margin-top: 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: #45a049;
}

#flagDisplay {
    margin-top: 20px;
}

img {
    width: 150px;
    height: auto;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope you enjoy it and thank you so much!.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
