Snippets Collections
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}
/* list with not selector */

.post > *:not( img ):not( video ) {
    margin-left: auto;
    margin-right: auto;
    max-width: 50rem;
    padding-left: 5%;
    padding-right: 5%;
}
/* all ULs after p */
p ~ ul {
background-color: #f00;
}
/* General sibling selector */
h4 ~ p {
    font-weight:bold;
}
/*
General Sibling Combinator
*/

figure ~ p {}
article:first-of-type,
article:last-of-type {
	margin: 10px 0;
}
/* Element not only child */

div p:last-child:not(:only-child) { 
	font-weight: bolder; 
}
/* Select all <a> that are hrefs: */
a[href]{}

/* Select all elements that have a class (useful if JS is adding classes somewhere) */
article[class]{}

/* Select an ID, but with the specificity of a class:  */
section[id="sideBar"]{color: red}

/* Style all links that are fully qualified URLs, knowing that ^ means "starts with": */
a[href^="http"]{}

/* Need to style a link to a ZIP or a PDF? Totally fine, too. Use the $ which means "ends with" */
a[href$=".zip"]:after{content:"(zip)"}

/* Style an image based on one word existing in the alt attribute? Let's use the space substring selector: */
img[alt~="Insurance"]{}

/* Style an image based on the name of the image file itself? Also doable, even if you're image is this-image-shot-april-2-2014.png. The | is a hyphen substring selector: */
img[src|="-april-"]{}
div[class*="test"] {
    background: #000;
}
#include <stdio.h>
#include <string.h>

int hasEqualAB(const char* input) {
    int count = 0;

    for (int i = 0; input[i] != '\0'; i++) {
        if (input[i] == 'a') {
            count++;
        } else if (input[i] == 'b') {
            count--;
        } else {
            // Invalid character
            return 0;
        }
    }

    return count == 0;
}

int main() {
    char str[100];

    printf("Enter a string (only a and b): ");
    scanf("%s", str);

    if (hasEqualAB(str)) {
        printf("Accepted: Equal number of 'a' and 'b'\n");
    } else {
        printf("Rejected: Unequal number of 'a' and 'b'\n");
    }
return 0;
}
 #include <stdio.h>
#include <string.h>

int tempVar = 1;

void newTemp(char *temp) {
    sprintf(temp, "t%d", tempVar++);
}
void replace(char expr[][10], int *n, int i, char *temp) {
    strcpy(expr[i - 1], temp);
    for (int j = i + 2; j < *n; j++)
        strcpy(expr[j - 2], expr[j]);
    *n -= 2;
}
void generateTAC(char input[]) {
    char lhs[10], rhs[100];
    int n = 0;
    // Split into lhs and rhs
    sscanf(input, "%[^=]=%s", lhs, rhs);
    char expr[50][10], temp[10];
    // Tokenize RHS
    for (int i = 0; rhs[i]; i++) {
        char t[2] = {rhs[i], '\0'};
        strcpy(expr[n++], t);
    }
    // First handle * and /
    for (int i = 0; i < n; i++)
        if (!strcmp(expr[i], "*") || !strcmp(expr[i], "/")) {
            newTemp(temp);
            printf("%s = %s %s %s\n", temp, expr[i - 1], expr[i], expr[i + 1]);
            replace(expr, &n, i, temp);
            i = -1;
        }
    // Then handle + and -
    for (int i = 0; i < n; i++)
        if (!strcmp(expr[i], "+") || !strcmp(expr[i], "-")) {
            newTemp(temp);
            printf("%s = %s %s %s\n", temp, expr[i - 1], expr[i], expr[i + 1]);
            replace(expr, &n, i, temp);
            i = -1;
        }
    // Final assignment
    printf("%s = %s\n", lhs, expr[0]);
}
int main() {
    char expr[100];
    printf("Enter expression (e.g., a=b+c*d): ");
    scanf("%s", expr);
    generateTAC(expr);
    return 0;
}
Imagine a shopping platform where products never run out, browsing is lightning-fast, and checkout is as easy as a single click. Our Amazon Clone online store brings you an unmatched shopping experience with a wide range of products, smart recommendations, and smooth navigation. Whether you’re searching for the latest gadgets, fashion, or daily essentials, everything is just a tap away!
Why You’ll Like It?
 Infinite Choices – Browse an endless catalog of products.
 Fast & Easy Search – Find what you need instantly.
 Safe & Secure Payments – Shop with confidence.

Visit now >> https://www.beleaftechnologies.com/amazon-clone
Whatsapp :  +91 8056786622
Email id :  business@beleaftechnologies.com
Telegram : https://telegram.me/BeleafSoftTech 
<div class="rounded-box w-full overflow-hidden" style="aspect-ratio: 1920/1080;">
  <iframe 
    class="h-full w-full" 
    allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" 
    src="https://www.youtube.com/embed/bYznFmzL820?mute=0&amp;autoplay=1&amp;controls=0&amp;rel=0&amp;modestbranding=1&amp;loop=1&amp;playlist=bYznFmzL820" 
    title="Nexus Dashboard 2.0"> </iframe>
</div>
/js
jQuery(document).ready(function($) {
    $('.option-order ul').hide();

    // Toggle ul khi click vào option
    $('.option-order .option').on('click', function(e) {
        e.preventDefault();
        $(this).siblings('ul').slideToggle(200);
    });

    // Xử lý khi chọn li trong option-order
    $('.option-order ul li').on('click', function() {
        var selectedText = $(this).text();
        var order = $(this).data('order');
        var $option = $(this).closest('.option-order').find('.option');
        var $container = $(this).closest('.last-blog, .all-list-blog');
        var $listBlog = $container.find('.list-blog');
        var categorySlug = $('.list-cate .active').data('slug');

        $option.text(selectedText);
        $(this).parent().slideUp(200);

        var isLatest = $container.hasClass('last-blog');
        var args = {
            post_type: 'post',
            posts_per_page: isLatest ? 3 : 9,
            orderby: 'date',
            order: order,
            offset: (isLatest || order === 'DESC') ? (isLatest ? 0 : 3) : 0,
            category_name: categorySlug === 'all' ? '' : categorySlug
        };

        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: {
                action: 'load_posts_by_order',
                query_args: args,
                is_latest: isLatest
            },
            beforeSend: function() {
                $listBlog.addClass('loading'); // Thêm class loading
            },
            success: function(response) {
                $listBlog.removeClass('loading').html(response); // Xóa class và cập nhật
            }
        });
    });

    // Đóng ul khi click ngoài
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.option-order').length) {
            $('.option-order ul').slideUp(200);
        }
    });

    // Xử lý lọc theo category
    $('.list-cate ul li a').on('click', function(e) {
        e.preventDefault();
        $('.list-cate .active').removeClass('active');
        $(this).addClass('active');
        var categorySlug = $(this).data('slug');

        $('.last-blog, .all-list-blog').each(function() {
            var $container = $(this);
            var $listBlog = $container.find('.list-blog');
            var isLatest = $container.hasClass('last-blog');
            var order = $container.find('.option-order .option').text() === 'Newest' ? 'DESC' : 'ASC';

            var args = {
                post_type: 'post',
                posts_per_page: isLatest ? 3 : 9,
                orderby: 'date',
                order: order,
                offset: (isLatest || order === 'DESC') ? (isLatest ? 0 : 3) : 0,
                category_name: categorySlug === 'all' ? '' : categorySlug
            };

            $.ajax({
                url: '/wp-admin/admin-ajax.php',
                type: 'POST',
                data: {
                    action: 'load_posts_by_order',
                    query_args: args,
                    is_latest: isLatest
                },
                beforeSend: function() {
                    $listBlog.addClass('loading'); // Thêm class loading
                },
                success: function(response) {
                    $listBlog.removeClass('loading').html(response); // Xóa class và cập nhật
                }
            });
        });
    });

    // Xử lý load thêm bài viết cho All Blog List
    $('.btn-see-more').on('click', function(e) {
        e.preventDefault();
        var $listBlog = $('.all-list-blog .list-blog');
        var currentOffset = $listBlog.find('.box-blog').length;
        var order = $('.all-list-blog .option-order .option').text() === 'Newest' ? 'DESC' : 'ASC';
        var categorySlug = $('.list-cate .active').data('slug');

        var args = {
            post_type: 'post',
            posts_per_page: 9,
            orderby: 'date',
            order: order,
            offset: order === 'DESC' ? currentOffset + 3 : currentOffset,
            category_name: categorySlug === 'all' ? '' : categorySlug
        };

        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            data: {
                action: 'load_posts_by_order',
                query_args: args,
                is_latest: false
            },
            beforeSend: function() {
                $listBlog.addClass('loading'); // Thêm class loading
                $('.btn-see-more').text('Loading...');
            },
            success: function(response) {
                $listBlog.removeClass('loading'); // Xóa class loading
                if (response.trim()) {
                    $listBlog.append(response);
                    $('.btn-see-more').text('See more posts');
                } else {
                    $('.btn-see-more').text('No more posts');
                }
            }
        });
    });
});


/css loadding
.list-blog {
    position: relative;
}

.list-blog.loading::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7); /* Nền mờ */
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
}

.list-blog.loading::before {
    content: '';
    width: 40px;
    height: 40px;
    border: 4px solid #ccc;
    border-top: 4px solid #007bff; /* Màu vòng xoay */
    border-radius: 50%;
    animation: spin 1s linear infinite;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 11;
}

@keyframes spin {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}
# Example headings

## Sample Section

## This'll be a _Helpful_ Section About the Greek Letter Θ!
A heading containing characters not allowed in fragments, UTF-8 characters, two consecutive spaces between the first and second words, and formatting.

## This heading is not unique in the file

TEXT 1

## This heading is not unique in the file

TEXT 2

# Links to the example headings above

Link to the sample section: [Link Text](#sample-section).

Link to the helpful section: [Link Text](#thisll-be-a-helpful-section-about-the-greek-letter-Θ).

Link to the first non-unique section: [Link Text](#this-heading-is-not-unique-in-the-file).

Link to the second non-unique section: [Link Text](#this-heading-is-not-unique-in-the-file-1).
Some basic Git commands are:
```
git status
git add
git commit
```
Text that is not a quote

> Text that is a quote
//os
const os = require('os');

console.log('OS Platform:', os.platform());
console.log('CPU Architecture:', os.arch());
console.log('Free Memory:', os.freemem());
console.log('Total Memory:', os.totalmem());
console.log('Home Directory:', os.homedir());

//path

const path = require('path');

const filePath = '/user/local/app/index.html';

console.log('Base name:', path.basename(filePath));
console.log('Directory name:', path.dirname(filePath));
console.log('Extension:', path.extname(filePath));
console.log('Join path:', path.join(__dirname, 'public', 'index.html'));

//UTIL

const util = require('util');

// Format
const msg = util.format('%s has %d apples', 'John', 5);
console.log(msg);

// Example using promisify (convert callback to promise)
const fs = require('fs');
const readFile = util.promisify(fs.readFile);

readFile('sample.txt', 'utf8')
  .then(data => console.log(data))
  .catch(err => console.error(err));

//event 

const EventEmitter = require('events');

const emitter = new EventEmitter();

// Define event handler
emitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

// Trigger the event
emitter.emit('greet', 'Alice');
https://chatgpt.com/share/67f27ed9-2a24-800e-b87b-9fa317a9d773
Higher Order Function
function greet(name) {
  return function (message) {
    console.log(`${message}, ${name}`);
  };
}

const greetRoshini = greet("Roshini");
greetRoshini("Hello");


Callback & Callback Hell Example
function step1(callback) {
  setTimeout(() => {
    console.log("Step 1 done");
    callback();
  }, 1000);
}

function step2(callback) {
  setTimeout(() => {
    console.log("Step 2 done");
    callback();
  }, 1000);
}

function step3() {
  
  
   
  console.log("Step 3 done");
}

step1(() => {
  step2(() => {
    step3();
  });
});

XHR: Response
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onload = () => {
  const data = JSON.parse(xhr.responseText);
  console.log(data);
};
xhr.send();


Promise to Solve Callback Hell

function doStep(step) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(step);
      resolve();
      
      
    }, 1000);
  });
}

doStep("Step 1")
  .then(() => doStep("Step 2"))
  .then(() => doStep("Step 3"));



Promise Chaining & Async/Await

function task(msg, time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(msg);
      resolve();
    }, time);
  });
}

task("Start", 500)
  .then(() => task("Middle", 1000))
  .then(() => task("End", 500));
async function run() {
  await task("Start", 500);
  await task("Middle", 1000);
  await task("End", 500);
}

run();


Prototypal Inheritance and Classes 
function Person(name) {
  this.name = name;
}
Person.prototype.sayHi = function () {
  console.log("Hi, I'm " + this.name);
};

class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
  showGrade() {
    console.log(`${this.name}'s grade is ${this.grade}`);
  }
}

const s = new Student("Roshini", "A");
s.sayHi();
s.showGrade();

Object and Array Destructuring

const user = { name: "Roshini", age: 20 };
const { name, age } = user;
console.log(name, age);

const arr = [10, 20];
const [a, b] = arr;
console.log(a, b);



Modules
Steps:

Create math.js:

 
export function add(x, y) {
  return x + y;
}
Create main.js:

 
import { add } from "./math.js";
console.log(add(5, 3));
Add <script type="module" src="main.js"></script> in HTML


 Function Generators and Symbols
function* countUp() {
  yield 1;
  yield 2;
  yield 3;
}
let gen = countUp();
console.log(gen.next().value);

const sym1 = Symbol("id");
console.log(sym1 === Symbol("id")); // false

Closure

function outer() {
  let count = 0;
  return function () {
    count++;
    console.log("Count:", count);
  };
}
const counter = outer();
counter(); // 1
counter(); // 2





cd my-webapp
git init
git add .
git commit -m "Initial commit with 5 pages"


git remote add origin https://github.com/yourusername/my-webapp.git
git push -u origin main
git pull origin main  # Pull latest
git fetch             # Fetch without merge


git clone https://github.com/yourusername/my-webapp.git
cd my-webapp
echo "<footer>Footer info</footer>" >> about.html
git add .
git commit -m "Added footer"
git push

git checkout -b new-feature
# make changes
git commit -am "new feature"
git checkout main
git merge new-feature
git push


GitHub Pages
Go to GitHub repo → Settings → Pages

Select branch: main, folder: /root

Access your site at https://yourusername.github.io/my-webapp


FIREBASE_DB_URL=https://myfirebaseapp-65ada-default-rtdb.firebaseio.com/
MONGO_URI=mongodb+srv://chintumaligireddy143:fkTCfJ95ZeupKVps@cluster0.6d5ib6c.mongodb.net/
// a. Working with Higher Order Function in JavaScript
function higherOrderFunction(operation, a, b) {
    return operation(a, b);
}
 
function add(x, y) {
    return x + y;
}
 
console.log(higherOrderFunction(add, 5, 3)); // Output: 8
 
// b. Using Callback and Creating a Callback Hell Situation
function registerUser(callback) {
  setTimeout(() => {
    console.log("1. User registered");
    callback();
  }, 1000);
}

function sendWelcomeEmail(callback) {
  setTimeout(() => {
    console.log("2. Welcome email sent");
    callback();
  }, 1000);
}

function loginUser(callback) {
  setTimeout(() => {
    console.log("3. User logged in");
    callback();
  }, 1000);
}

function getUserData() {
  setTimeout(() => {
    console.log("4. Fetched user data");
  }, 1000);
}

// Nested callbacks (callback hell)
registerUser(() => {
  sendWelcomeEmail(() => {
    loginUser(() => {
      getUserData();
    });
  });
});

 
// c. Working with XHR : Response
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log("XHR Response:", JSON.parse(xhr.responseText));
    }
};
xhr.send();
 
// d. Dealing with Callback Hell Using Promise
function registerUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("1. User registered");
      resolve();
    }, 1000);
  });
}

function sendWelcomeEmail() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("2. Welcome email sent");
      resolve();
    }, 1000);
  });
}

function loginUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("3. User logged in");
      resolve();
    }, 1000);
  });
}

function getUserData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("4. Fetched user data");
      resolve();
    }, 1000);
  });
}

// Chaining Promises
registerUser()
  .then(sendWelcomeEmail)
  .then(loginUser)
  .then(getUserData)
  .catch((err) => {
    console.error("Error:", err);
  });
 
// e. Dealing with Promise Chaining and Async/Await
function registerUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("1. User registered");
      resolve();
    }, 1000);
  });
}

function sendWelcomeEmail() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("2. Welcome email sent");
      resolve();
    }, 1000);
  });
}

function loginUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("3. User logged in");
      resolve();
    }, 1000);
  });
}

function getUserData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("4. Fetched user data");
      resolve();
    }, 1000);
  });
}

// Using async/await
async function processUserFlow() {
  try {
    await registerUser();
    await sendWelcomeEmail();
    await loginUser();
    await getUserData();
    console.log("All steps completed successfully.");
  } catch (error) {
    console.error("An error occurred:", error);
  }
}

processUserFlow();
// a. Working with Prototypical Inheritance and Classes
function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  console.log(`${this.name} makes a noise.`);
};

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function () {
  console.log(`${this.name} barks.`);
};

const dog1 = new Dog("Buddy");
dog1.speak(); // Output: Buddy barks.

//classes

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog2 = new Dog("Max");
dog2.speak(); // Output: Max barks.

 
// b. Working with Object and Array Destructuring
const user = { name: 'Alice', age: 25, location: 'New York' };
const { name, age } = user;
console.log(`${name} is ${age} years old.`);
 
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(`First: ${first}, Second: ${second}, Rest: ${rest}`);
 
// c. Working with Modules
// In another file (mathUtils.js), create:
// export function add(a, b) { return a + b; }
// export function multiply(a, b) { return a * b; }
// Then import and use in this file:
// import { add, multiply } from './mathUtils.js';
 
// d. Working with Function Generators and Symbols
function* numberGenerator() {
    let num = 1;
    while (true) {
        yield num++;
    }
}
const gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
 
const uniqueID = Symbol('id');
const obj = { [uniqueID]: 12345 };
console.log(obj[uniqueID]);
 
// e. Working with Closures
function outerFunction() {
  let count = 0;

  function innerFunction() {
    count++;
    console.log(count);
  }

  return innerFunction;
}

const counter = outerFunction();
counter(); // 1
counter(); // 2
counter(); // 3
npm init -y
npm install express jsonwebtoken
npm init -y
npm install express mongoose jsonwebtoken bcryptjs dotenv
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const User = require('../models/User');
const router = express.Router();

function verifyToken(req, res, next) {
    const token = req.headers['authorization'];
    if (!token) return res.status(403).send('No token provided');
    jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
        if (err) return res.status(401).send('Invalid token');
        req.userId = decoded.id;
        next();
    });
}

router.post('/register', async (req, res) => {
    const hashedPassword = await bcrypt.hash(req.body.password, 8);
    const user = new User({ ...req.body, password: hashedPassword });
    await user.save();
    res.send('User registered');
});

router.post('/login', async (req, res) => {
    const user = await User.findOne({ email: req.body.email });
    if (!user) return res.status(404).send('User not found');

    const valid = await bcrypt.compare(req.body.password, user.password);
    if (!valid) return res.status(401).send('Wrong password');

    const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
    res.send({ token });
});

router.get('/dashboard', verifyToken, async (req, res) => {
    const user = await User.findById(req.userId, { password: 0 });
    res.send(user);
});

module.exports = router;
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
});

module.exports = mongoose.model('User', userSchema);
const express = require('express');
const mongoose = require('mongoose');
const userRoutes = require('./routes/userRoutes');
require('dotenv').config();

const app = express();
app.use(express.json());

mongoose.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => console.log("MongoDB connected"));

app.use('/api', userRoutes);

app.listen(5000, () => console.log('MongoDB Auth server running at http://localhost:5000'));
const express = require('express');
const authRoutes = require('./routes/authRoutes');

const app = express();
app.use(express.json());
app.use('/api', authRoutes);

app.listen(3000, () => console.log('Auth server running at http://localhost:3000'));
const express = require('express');
const jwt = require('jsonwebtoken');
const router = express.Router();

const users = [];

router.post('/register', (req, res) => {
    const user = req.body;
    users.push(user);
    res.send({ message: 'User registered' });
});

router.post('/login', (req, res) => {
    const { username, password } = req.body;
    const user = users.find(u => u.username === username && u.password === password);
    if (!user) return res.status(401).send('Invalid credentials');

    const token = jwt.sign({ username }, 'secretkey', { expiresIn: '1h' });
    res.send({ token });
});

router.get('/profile', verifyToken, (req, res) => {
    res.send({ message: 'Welcome to your profile!', user: req.user });
});

function verifyToken(req, res, next) {
    const token = req.headers['authorization'];
    if (!token) return res.status(403).send('No token provided');
    jwt.verify(token, 'secretkey', (err, decoded) => {
        if (err) return res.status(401).send('Invalid token');
        req.user = decoded;
        next();
    });
}

module.exports = router;
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <h3>Temperature Forecast Chart</h3>
  <input id="city" placeholder="Enter city">
  <button onclick="drawChart()">Get Forecast</button>
  <canvas id="tempChart" width="400" height="200"></canvas>

  <script>
    async function drawChart() {
      const city = document.getElementById("city").value;
      const key = "36f9af4e269fe80b4cda0e7e8af0809d"; // Replace with your OpenWeatherMap API key
      const res = await fetch(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${key}&units=metric`);
      const data = await res.json();

      const labels = [];
      const temps = [];

      data.list.forEach((item, i) => {
        if (i % 8 === 0) { // every 24 hours (8 x 3-hour slots)
          labels.push(item.dt_txt.split(" ")[0]);
          temps.push(item.main.temp);
        }
      });

      new Chart(document.getElementById("tempChart"), {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: 'Temperature (°C)',
            data: temps,
            backgroundColor: 'rgba(54, 162, 235, 0.6)'
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    }
  </script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
  <title>Weather Forecast</title>
</head>
<body>
  <h2>5-Day Forecast</h2>
  <input type="text" id="forecastCity" placeholder="Enter city name">
  <button onclick="getForecast()">Get Forecast</button>

  <table border="1" id="forecastTable">
    <tr><th>Date</th><th>Temperature (°C)</th></tr>
  </table>

  <script>
    async function getForecast() {
      const city = document.getElementById('forecastCity').value;
      const apiKey = '36f9af4e269fe80b4cda0e7e8af0809d';  // Replace with your OpenWeatherMap API key
      const url = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&units=metric`;

      const response = await fetch(url);
      const data = await response.json();

      const table = document.getElementById("forecastTable");
      table.innerHTML = `<tr><th>Date</th><th>Temperature (°C)</th></tr>`; // clear old rows

      data.list.forEach((item, index) => {
        if (index % 8 === 0) { // every 8th item = 24 hours
          const row = table.insertRow();
          row.innerHTML = `<td>${item.dt_txt.split(" ")[0]}</td>
                           <td>${item.main.temp}°C</td>`;
        }
      });
    }
  </script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
  <title>Weather Data</title>
</head>
<body>
  <h2>Weather Info</h2>
  <input type="text" id="city" placeholder="Enter city name">
  <button onclick="getWeather()">Get Weather</button>

  <table border="1" id="weatherTable">
    <tr><th>City</th><th>Min Temp</th><th>Max Temp</th><th>Humidity</th></tr>
  </table>

  
        <script>
  async function getWeather() {
    const city = document.getElementById('city').value.trim();
    const apiKey = '36f9af4e269fe80b4cda0e7e8af0809d'; // Make sure this is valid

    if (!city) {
      alert("Please enter a city name.");
      return;
    }

    const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

    try {
      const response = await fetch(url);
      const data = await response.json();
      if (response.ok) {
        const table = document.getElementById("weatherTable");
        const row = table.insertRow();
        row.innerHTML = `<td>${data.name}</td>
                         <td>${data.main.temp_min}°C</td>
                         <td>${data.main.temp_max}°C</td>
                         <td>${data.main.humidity}%</td>`;
      } else {
        alert(`Error: ${data.message}`);
      }
    } catch (error) {
      alert("Failed to fetch weather data. Please try again later.");
      console.error(error);
    }
  }
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
  <title>Fetch Example</title>
</head>
<body>
  <h2>User Data</h2>
  <table border="1" id="dataTable">
    <tr>
      <th>Name</th>
      <th>Email</th>
    </tr>
  </table>

  <script>
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => {
        const table = document.getElementById("dataTable");
        data.forEach(user => {
          const row = table.insertRow();
          row.innerHTML = `<td>${user.name}</td><td>${user.email}</td>`;
        });
      })
      .catch(err => console.log("Error:", err));
  </script>
</body>
</html>
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Express Server');
});

app.get('/html', (req, res) => {
    res.send('<h1>Hello from Express</h1>');
});

app.get('/json', (req, res) => {
    res.json({ message: 'Hello, Express!' });
});

app.listen(3000, () => {
    console.log('Express server running at http://localhost:3000/');
});
const http = require('http');
 
const server = http.createServer((req, res) => {
    if (req.url === '/html') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<h1>Hello, World! i am jashwanth reddy</h1>');
    } else if (req.url === '/json') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'Hello, World! this is jashwanth' }));
    } else {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Hello, World!');
    }
});
 
server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;

app.use(bodyParser.json());

let users = [
    { id: 1, name: "Alice", email: "alice@example.com" },
    { id: 2, name: "Bob", email: "bob@example.com" }
];

// CREATE
app.post('/users', (req, res) => {
    const user = req.body;
    user.id = users.length + 1;
    users.push(user);
    res.status(201).send(user);
});

// READ all users
app.get('/users', (req, res) => {
    res.send(users);
});

// READ single user
app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id == req.params.id);
    res.send(user || {});
});

// UPDATE
app.put('/users/:id', (req, res) => {
    const id = req.params.id;
    const index = users.findIndex(u => u.id == id);
    if (index !== -1) {
        users[index] = { ...users[index], ...req.body };
        res.send(users);
    } else {
        res.status(404).send({ error: "User not found" });
    }
});

// DELETE
app.delete('/users/:id', (req, res) => {
    const id = req.params.id;
    users = users.filter(u => u.id != id);
    res.send({ message: "User deleted" });
});

app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});
const express = require('express');
const axios = require('axios');
const app = express();

app.set('view engine', 'ejs');

app.get('/', async (req, res) => {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users');
    res.render('users', { users: response.data });
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});
<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>
    <h1>User List</h1>
    <table border="1" cellpadding="5">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <% users.forEach(user => { %>
            <tr>
                <td><%= user.id %></td>
                <td><%= user.name %></td>
                <td><%= user.email %></td>
            </tr>
        <% }) %>
    </table>
</body>
</html>
const express = require('express');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');
require('dotenv').config();
require('./services/firebaseService'); // Initialize Firebase

const app = express();
app.use(bodyParser.json());

app.use('/users', userRoutes);

app.listen(3000, () => {
  console.log('Firebase app running on http://localhost:3000');
});
const admin = require('firebase-admin');
const serviceAccount = require('../firebase-key.json'); // adjust path
require('dotenv').config(); // Make sure this line is included

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: process.env.FIREBASE_DB_URL // This must not be undefined
});

const db = admin.database();
const ref = db.ref('users');

module.exports = ref;
const express = require('express');
const router = express.Router();
const usersRef = require('../services/firebaseService');

// Add user
router.post('/', (req, res) => {
  const newUser = usersRef.push();
  newUser.set(req.body);
  res.send({ message: 'User added', id: newUser.key });
});

// Get users
router.get('/', (req, res) => {
  usersRef.once('value', snapshot => {
    res.send(snapshot.val());
  });
});

// Update user
router.put('/:id', (req, res) => {
  usersRef.child(req.params.id).update(req.body);
  res.send({ message: 'User updated' });
});

// Delete user
router.delete('/:id', (req, res) => {
  usersRef.child(req.params.id).remove();
  res.send({ message: 'User deleted' });
});

module.exports = router;
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const userRoutes = require('./routes/users');

dotenv.config(); // Load .env file

const app = express();
app.use(bodyParser.json());

// Connect to MongoDB using .env variable
mongoose.connect(process.env.MONGO_URI)
    .then(() => console.log("MongoDB connected"))
    .catch(err => console.log(err));

// Use user routes
app.use('/', userRoutes);

app.listen(5000, () => {
    console.log("Server started at http://localhost:5000");
});
star

Mon Apr 07 2025 14:21:53 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #not

star

Mon Apr 07 2025 14:20:11 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #not

star

Mon Apr 07 2025 14:18:54 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #not

star

Mon Apr 07 2025 14:18:03 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #list

star

Mon Apr 07 2025 14:16:20 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #empty

star

Mon Apr 07 2025 14:15:21 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #attribute

star

Mon Apr 07 2025 14:13:36 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:12:47 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:12:08 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:11:04 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:10:32 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 14:09:42 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector #attribute

star

Mon Apr 07 2025 14:08:27 GMT+0000 (Coordinated Universal Time)

@Sebhart #css #selector

star

Mon Apr 07 2025 13:39:12 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 12:57:20 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 12:13:50 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/amazon-clone

@raydensmith #amazon #clone #e-commerce

star

Mon Apr 07 2025 12:02:18 GMT+0000 (Coordinated Universal Time)

@Shahadat_Anik

star

Mon Apr 07 2025 10:19:55 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/crypto-leverage-trading-platform/

@CharleenStewar ##cryptoleveragetrading ##leveragetrading ##cryptotradingapp ##tradingplatform

star

Mon Apr 07 2025 09:51:20 GMT+0000 (Coordinated Universal Time)

@mamba

star

Mon Apr 07 2025 04:51:18 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#links

@Mido4477

star

Mon Apr 07 2025 04:50:00 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax

@Mido4477

star

Mon Apr 07 2025 04:49:49 GMT+0000 (Coordinated Universal Time) https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax

@Mido4477

star

Mon Apr 07 2025 02:06:50 GMT+0000 (Coordinated Universal Time)

@exam3

star

Mon Apr 07 2025 01:00:35 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 00:59:39 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 00:57:36 GMT+0000 (Coordinated Universal Time)

@sem

star

Mon Apr 07 2025 00:54:56 GMT+0000 (Coordinated Universal Time)

@sem

star

Sun Apr 06 2025 18:24:42 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:18:49 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:11:50 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:07:27 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:06:37 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:06:02 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:05:24 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 18:04:37 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:56:29 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:56:00 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:53:15 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:52:53 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:52:31 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:52:01 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:50:15 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:48:52 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:48:04 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:46:48 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:46:09 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:45:02 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:44:30 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:42:31 GMT+0000 (Coordinated Universal Time)

@exam3

star

Sun Apr 06 2025 17:40:45 GMT+0000 (Coordinated Universal Time)

@exam3

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension