Notification script.jss
let notifications = [];
let notificationCount = 0;
document.getElementById(‘notificationIcon’).onclick = function() {
const dropdown = document.getElementById(‘notificationDropdown’);
dropdown.style.display = dropdown.style.display === ‘block’ ? ‘none’ : ‘block’;
};
document.getElementById(‘clearNotifications’).onclick = function() {
notifications = [];
notificationCount = 0;
updateNotificationDisplay();
};
function addNotification(message) {
notifications.push(message);
notificationCount++;
updateNotificationDisplay();
}
function updateNotificationDisplay() {
const countElement = document.getElementById(‘notificationCount’);
const listElement = document.getElementById(‘notificationList’);
countElement.textContent = notificationCount;
listElement.innerHTML = notifications.map(notification => ${notification}
).join(”);
}
// Example notifications
setTimeout(() => addNotification(‘New message from John’), 1000);
setTimeout(() => addNotification(‘Your order has been shipped’), 3000);
setTimeout(() => addNotification(‘New comment on your post’), 5000);
Notification Types+style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
header {
background: #007bff;
color: white;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
position: relative;
}
.notification-icon {
cursor: pointer;
position: relative;
}
.notification-count {
position: absolute;
top: -5px;
right: -10px;
background: red;
color: white;
border-radius: 50%;
padding: 3px 6px;
font-size: 12px;
}
.notification-dropdown {
display: none;
position: absolute;
right: 0;
background: white;
border: 1px solid #ccc;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
z-index: 10;
width: 250px;
}
.notification-dropdown div {
padding: 10px;
border-bottom: 1px solid #eee;
}
.notification-dropdown div:last-child {
border-bottom: none;
}
.notification-dropdown button {
width: 100%;
padding: 10px;
background: #ff4d4d;
color: white;
border: none;
cursor: pointer;
border-radius: 0 0 5px 5px;
}
Notification+Types script.jss
let notifications = [];
let notificationCount = 0;
document.getElementById(‘notificationIcon’).onclick = function() {
const dropdown = document.getElementById(‘notificationDropdown’);
dropdown.style.display = dropdown.style.display === ‘block’ ? ‘none’ : ‘block’;
};
document.getElementById(‘clearNotifications’).onclick = function() {
notifications = [];
notificationCount = 0;
updateNotificationDisplay();
};
function addNotification(type, message) {
const notification = ${type}: ${message};
notifications.push(notification);
notificationCount++;
updateNotificationDisplay();
}
function updateNotificationDisplay() {
const countElement = document.getElementById(‘notificationCount’);
const listElement = document.getElementById(‘notificationList’);
countElement.textContent = notificationCount;
listElement.innerHTML = notifications.map(notification => ${notification}
).join(”);
}
// Example notifications
setTimeout(() => addNotification(‘Like’, ‘Alice liked your post’), 1000);
setTimeout(() => addNotification(‘Comment’, ‘Bob commented on your photo’), 3000);
setTimeout(() => addNotification(‘Follower’, ‘Charlie started following you’), 5000);
setTimeout(() => addNotification(‘Message’, ‘You have a new message from Dave’), 7000);
Privacy controls and immunity HTML
Privacy Controls
Privacy Settings
Allow others to see my profile
Immunity Groups
Create Immunity Group
Privacy controls and immunity style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
header {
background: #007bff;
color: white;
padding: 10px 20px;
text-align: center;
}
section {
margin: 20px 0;
padding: 15px;
background: white;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 15px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
.group-item {
margin-top: 10px;
padding: 10px;
background: #e9ecef;
border-radius: 5px;
}
privacy controls and immunity script.js
document.getElementById(‘createGroup’).onclick = function() {
const groupName = prompt(“Enter the name of your immunity group:”);
if (groupName) {
addGroup(groupName);
}
};
function addGroup(name) {
const groupsContainer = document.getElementById(‘groupsContainer’);
const groupDiv = document.createElement(‘div’);
groupDiv.className = ‘group-item’;
groupDiv.textContent = name;
groupsContainer.appendChild(groupDiv);
}
// Handle visibility toggle
document.getElementById(‘visibilityToggle’).onclick = function() {
const isVisible = this.checked;
const status = isVisible ? “Your profile is now visible.” : “Your profile is now hidden.”;
alert(status);
};
interactive groups style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
header {
background: #007bff;
color: white;
padding: 10px 20px;
text-align: center;
}
section {
margin: 20px 0;
padding: 15px;
background: white;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type=”text”] {
padding: 10px;
width: calc(100% – 22px);
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 15px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
.group-item {
margin-top: 10px;
padding: 10px;
background: #e9ecef;
border-radius: 5px;
display: flex;
justify-content: space-between;
align-items: center;
}
interactive groups script.jss
document.getElementById(‘createGroupButton’).onclick = function() {
const groupName = document.getElementById(‘groupNameInput’).value.trim();
if (groupName) {
addGroup(groupName);
document.getElementById(‘groupNameInput’).value = ”; // Clear input
} else {
alert(“Please enter a group name.”);
}
};
function addGroup(name) {
const groupsContainer = document.getElementById(‘groupsContainer’);
const groupDiv = document.createElement(‘div’);
groupDiv.className = ‘group-item’;
groupDiv.innerHTML = ${name} Join
;
groupsContainer.appendChild(groupDiv);
}
function joinGroup(name) {
alert(You have joined the group: ${name});
}
Integrate real data from API
Analytics Dashboard
Performance Metrics
Access Analytics
Your Performance Metrics
document.getElementById(‘accessAnalytics’).addEventListener(‘click’, async function() {
// Clear previous data and messages
document.getElementById(‘metricsData’).innerHTML = ”;
document.getElementById(‘errorMessage’).innerHTML = ”;
document.getElementById(‘analyticsContainer’).style.display = ‘none’;
try {
// Fetch data from the API (replace with your actual API URL)
const response = await fetch(‘https://api.example.com/user/metrics’);
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
const metrics = await response.json();
// Display the metrics
document.getElementById(‘metricsData’).innerHTML = <br/> <strong>Views:</strong> ${metrics.views}<br><br/> <strong>Clicks:</strong> ${metrics.clicks}<br><br/> <strong>Conversion Rate:</strong> ${metrics.conversionRate}%<br/>
;
// Show the analytics container
document.getElementById(‘analyticsContainer’).style.display = ‘block’;
} catch (error) {
// Display an error message if the fetch fails
document.getElementById(‘errorMessage’).innerText = ‘Failed to load metrics: ‘ + error.message;
}
});
Source code for analytics dashboard
Review Section
Leave Your Feedback
Rating:
1 Star
2 Stars
3 Stars
4 Stars
5 Stars
Write Your Review:
Submit Review
Recent Reviews
document.getElementById(‘submitReview’).addEventListener(‘click’, function() {
const rating = document.getElementById(‘rating’).value;
const reviewText = document.getElementById(‘reviewText’).value;
const reviewsContainer = document.getElementById(‘reviews’);
if (reviewText.trim() !== “”) {
const reviewDiv = document.createElement(‘div’);
reviewDiv.className = ‘review’;
reviewDiv.innerHTML = Rating: ${rating} Stars
${reviewText};
reviewsContainer.appendChild(reviewDiv);
// Clear the input fields
document.getElementById(‘reviewText’).value = ”;
document.getElementById(‘rating’).value = ‘1’;
} else {
alert(‘Please enter a review.’);
}
});
Integrate real data from API
Analytics Dashboard
Performance Metrics
Access Analytics
Your Performance Metrics
document.getElementById(‘accessAnalytics’).addEventListener(‘click’, async function() {
// Clear previous data and messages
document.getElementById(‘metricsData’).innerHTML = ”;
document.getElementById(‘errorMessage’).innerHTML = ”;
document.getElementById(‘analyticsContainer’).style.display = ‘none’;
try {
// Fetch data from the API (replace with your actual API URL)
const response = await fetch(‘https://api.example.com/user/metrics’);
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
const metrics = await response.json();
// Display the metrics
document.getElementById(‘metricsData’).innerHTML = <br/> <strong>Views:</strong> ${metrics.views}<br><br/> <strong>Clicks:</strong> ${metrics.clicks}<br><br/> <strong>Conversion Rate:</strong> ${metrics.conversionRate}%<br/>
;
// Show the analytics container
document.getElementById(‘analyticsContainer’).style.display = ‘block’;
} catch (error) {
// Display an error message if the fetch fails
document.getElementById(‘errorMessage’).innerText = ‘Failed to load metrics: ‘ + error.message;
}
});
integrate Chart chart.js
Analytics Dashboard
Performance Metrics
Access Analytics
Your Performance Metrics
document.getElementById(‘accessAnalytics’).addEventListener(‘click’, async function() {
// Clear previous data and messages
document.getElementById(‘metricsData’).innerHTML = ”;
document.getElementById(‘errorMessage’).innerHTML = ”;
document.getElementById(‘analyticsContainer’).style.display = ‘none’;
try {
// Fetch data from the API (replace with your actual API URL)
const response = await fetch(‘https://api.example.com/user/metrics’);
if (!response.ok) {
throw new Error(‘Network response was not ok’);
}
const metrics = await response.json();
// Display the metrics
document.getElementById(‘metricsData’).innerHTML = <br/> <strong>Views:</strong> ${metrics.views}<br><br/> <strong>Clicks:</strong> ${metrics.clicks}<br><br/> <strong>Conversion Rate:</strong> ${metrics.conversionRate}%<br/>
;
// Show the analytics container
document.getElementById(‘analyticsContainer’).style.display = ‘block’;
// Prepare data for the chart
const chartData = {
labels: [‘Views’, ‘Clicks’],
datasets: [{
label: ‘User Metrics’,
data: [metrics.views, metrics.clicks],
backgroundColor: [‘rgba(75, 192, 192, 0.2)’, ‘rgba(255, 99, 132, 0.2)’],
borderColor: [‘rgba(75, 192, 192, 1)’, ‘rgba(255, 99, 132, 1)’],
borderWidth: 1
}]
};
// Create the chart
const ctx = document.getElementById(‘metricsChart’).getContext(‘2d’);
new Chart(ctx, {
type: ‘bar’,
data: chartData,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
} catch (error) {
/
Display an error message if the fetch fails
document.getElementById(‘errorMessage’).innerText = ‘Failed to load metrics: ‘ + error.message;
}
});
ecommerce style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: white;
padding: 15px 0;
}
nav ul {
list-style-type: none;
padding: 0;
}
nav ul li {
display: inline;
margin: 0 15px;
}
nav ul li a {
color: white;
text-decoration: none;
}
.product-list {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
margin: 20px;
}
.product {
border: 1px solid #ccc;
border-radius: 5px;
padding: 15px;
margin: 10px;
width: 200px;
text-align: center;
}
.product button {
background-color: #28a745;
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
ecommerce script.js
const products = [
{ id: 1, name: ‘Product 1’, price: 29.99 },
{ id: 2, name: ‘Product 2’, price: 39.99 },
{ id: 3, name: ‘Product 3’, price: 49.99 },
];
function displayProducts() {
const productList = document.getElementById(‘productList’);
products.forEach(product => {
const productDiv = document.createElement(‘div’);
productDiv.className = ‘product’;
productDiv.innerHTML = ${product.name} Price: $${product.price.toFixed(2)} Buy Now
;
productList.appendChild(productDiv);
});
}
function addToCart(productId) {
const product = products.find(p => p.id === productId);
alert(Added ${product.name} to cart!);
}
window.onload = displayProducts;
style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: white;
padding: 15px 0;
text-align: center;
}
upload-section {
padding: 20px;
}
preview {
margin-top: 20px;
}
.preview-item {
margin: 10px;
display: inline-block;
}
img, video {
max-width: 200px;
max-height: 200px;
margin-bottom: 10px;
}
Script.js
document.getElementById(‘uploadButton’).addEventListener(‘click’, function() {
const fileInput = document.getElementById(‘fileInput’);
const files = fileInput.files;
const preview = document.getElementById(‘preview’);
preview.innerHTML = ”; // Clear previous previews
for (let i = 0; i < files.length; i++) {
const file = files[i];
const reader = new FileReader();
reader.onload = function(event) {
const previewItem = document.createElement(‘div’);
previewItem.className = ‘preview-item’;
if (file.type.startsWith(‘image/’)) {
const img = document.createElement(‘img’);
img.src = event.target.result;
previewItem.appendChild(img);
} else if (file.type.startsWith(‘video/’)) {
const video = document.createElement(‘video’);
video.src = event.target.result;
video.controls = true;
previewItem.appendChild(video);
} else if (file.type.startsWith(‘audio/’)) {
const audio = document.createElement(‘audio’);
audio.src = event.target.result;
audio.controls = true;
previewItem.appendChild(audio);
}
preview.appendChild(previewItem);
};
reader.readAsDataURL(file);
}
});
Source code for API integration HTML
API Integration Settings
Manage API Integrations
Add Integration
Current Integrations
© 2024 API Manager
style.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: white;
padding: 15px 0;
text-align: center;
}
settings-section {
padding: 20px;
}
form {
margin-bottom: 20px;
}
input {
margin: 5px;
padding: 10px;
width: 200px;
}
button {
padding: 10px;
}
.integration-item {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
display: flex;
justify-content: space-between;
}
.delete-button {
background-color: #dc3545;
color: white;
border: none;
padding: 5px;
cursor: pointer;
}
script.jss
let integrations = [];
document.getElementById(‘apiForm’).addEventListener(‘submit’, function(event) {
event.preventDefault();
const apiName = document.getElementById(‘apiName’).value;
const apiEndpoint = document.getElementById(‘apiEndpoint’).value;
const apiKey = document.getElementById(‘apiKey’).value;
const newIntegration = { name: apiName, endpoint: apiEndpoint, key: apiKey };
integrations.push(newIntegration);
document.getElementById(‘apiForm’).reset();
displayIntegrations();
});
function displayIntegrations() {
const integrationList = document.getElementById(‘integrationList’);
integrationList.innerHTML = ”;
integrations.forEach((integration, index) => {
const integrationItem = document.createElement(‘div’);
integrationItem.className = ‘integration-item’;
integrationItem.innerHTML = ${integration.name} Endpoint: ${integration.endpoint} Key: ${integration.key} Delete
;
integrationList.appendChild(integrationItem);
});
}
function deleteIntegration(index) {
integrations.splice(index, 1);
displayIntegrations();
}
Content Moderation Tools1
import React from ‘react’;
const Post = ({ post }) => {
const handleReport = () => {
fetch(‘/api/report’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({ postId: post.id }),
})
.then(response => {
if (response.ok) {
alert(‘Post reported successfully!’);
}
})
.catch(err => console.error(‘Error reporting post:’, err));
};
return (
{post.title}
{post.content}
Report
);
};
export default Post;
2
const express = require(‘express’);
const router = express.Router();
// Mock database
let reportedPosts = [];
router.post(‘/report’, (req, res) => {
const { postId } = req.body;
reportedPosts.push(postId);
console.log(Post ${postId} reported.);
res.status(200).send(‘Post reported successfully’);
});
module.exports = router;
3
router.get(‘/admin/reports’, (req, res) => {
// In a real app, you would fetch from a database
res.json(reportedPosts);
});
4
router.delete(‘/admin/reports/:postId’, (req, res) => {
const postId = req.params.postId;
reportedPosts = reportedPosts.filter(id => id !== postId);
console.log(Post ${postId} deleted.);
res.status(204).send();
});
5
import nltk
from nltk.corpus import stopwords
nltk.download(‘stopwords’)
def is_content_acceptable(content):
stop_words = set(stopwords.words(‘english’))
offensive_words = {‘badword1’, ‘badword2’} # Add your offensive words here
words = content.lower().split()
for word in words:
if word in offensive_words:
return False
return True
6
const mongoose = require(‘mongoose’);
const reportSchema = new mongoose.Schema({
postId: String,
reportedAt: { type: Date, default: Date.now },
});
const Report = mongoose.model(‘Report’, reportSchema);
router.post(‘/report’, async (req, res) => {
const { postId } = req.body;
const report = new Report({ postId });
await report.save();
res.status(200).send(‘Post reported successfully’);
});
user authentication role mngt 1
const bcrypt = require(‘bcrypt’);
const User = require(‘./models/User’); // Assume you have a User model
router.post(‘/register’, async (req, res) => {
const { username, password, role } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ username, password: hashedPassword, role });
await newUser.save();
res.status(201).send(‘User registered successfully’);
});
Dashboard for admin to view reports2
router.get(‘/admin/dashboard’, async (req, res) => {
const reports = await Report.find().populate(‘postId’);
res.render(‘adminDashboard’, { reports });
});
content filtering 3
router.post(‘/submit’, (req, res) => {
const { content } = req.body;
const flagged = [‘badword1’, ‘badword2’].some(word => content.includes(word));
if (flagged) {
// Flag the content for review
const report = new Report({ postId: content.id });
report.save();
return res.status(400).send(‘Content flagged for moderation.’);
}
// Save content to database
res.status(201).send(‘Content submitted successfully.’);
});
Manual 4
router.post(‘/moderate/:reportId’, async (req, res) => {
const { action } = req.body; // ‘approve’ or ‘reject’
const report = await Report.findById(req.params.reportId);
if (action === ‘approve’) {
// Code to approve content
// e.g., update the post status in the database
} else {
// Code to reject content (delete or flag)
}
await report.remove(); // Remove the report after action
res.status(200).send(‘Moderation action completed.’);
});
Feedback 5
router.post(‘/appeal/:reportId’, async (req, res) => {
const { reason } = req.body;
const appeal = new Appeal({ reportId: req.params.reportId, reason });
await appeal.save();
res.status(200).send(‘Appeal submitted successfully.’);
});
Logging6
const Log = require(‘./models/Log’);
router.post(‘/moderate/:reportId’, async (req, res) => {
const action = req.body.action;
// Perform moderation action here…
const logEntry = new Log({
reportId: req.params.reportId,
action,
performedAt: new Date(),
userId: req.user.id, // Assuming you have user authentication
});
await logEntry.save();
res.status(200).send(‘Action logged and completed.’);
});
More details1
const mongoose = require(‘mongoose’);
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
role: { type: String, enum: [‘user’, ‘moderator’, ‘admin’], default: ‘user’ },
});
const User = mongoose.model(‘User’, userSchema);
module.exports = User;
JWT
const jwt = require(‘jsonwebtoken’);
router.post(‘/register’, async (req, res) => {
const { username, password, role } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ username, password: hashedPassword, role });
await newUser.save();
res.status(201).send(‘User registered successfully’);
});
router.post(‘/login’, async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (user && await bcrypt.compare(password, user.password)) {
const token = jwt.sign({ id: user._id, role: user.role }, ‘your_secret_key’);
return res.json({ token });
}
res.status(401).send(‘Invalid credentials’);
});
2 Admin dashboard
router.get(‘/admin/dashboard’, async (req, res) => {
if (req.user.role !== ‘admin’) {
return res.status(403).send(‘Access denied’);
}
const reports = await Report.find().populate(‘postId’); // Assume postId is a reference
res.render(‘adminDashboard’, { reports });
});
http://router.post
Automated
const offensiveWords = [‘badword1’, ‘badword2’]; // Add more as needed
router.post(‘/submit’, (req, res) => {
const { content } = req.body;
const flagged = offensiveWords.some(word => content.includes(word));
if (flagged) {
const report = new Report({ postId: content.id }); // Link to the actual post
report.save();
return res.status(400).send(‘Content flagged for moderation.’);
}
// Save valid content
const newPost = new Post({ content });
newPost.save();
res.status(201).send(‘Content submitted successfully.’);
});
4 Manual
router.post(‘/moderate/:reportId’, async (req, res) => {
const { action } = req.body;
const report = await Report.findById(req.params.reportId);
if (!report) return res.status(404).send(‘Report not found.’);
if (action === ‘approve’) {
// Logic to approve content
await Post.findByIdAndUpdate(report.postId, { status: ‘approved’ });
} else {
// Logic to reject content
await Post.findByIdAndDelete(report.postId);
}
await report.remove(); // Remove the report
res.status(200).send(‘Moderation action completed.’);
});
5 Feedback Loop
const appealSchema = new mongoose.Schema({
reportId: { type: mongoose.Schema.Types.ObjectId, ref: ‘Report’ },
reason: String,
userId: { type: mongoose.Schema.Types.ObjectId, ref: ‘User’ },
submittedAt: { type: Date, default: Date.now },
});
const Appeal = mongoose.model(‘Appeal’, appealSchema);
Appeal endpoint
router.post(‘/appeal/:reportId’, async (req, res) => {
const { reason } = req.body;
const appeal = new Appeal({ reportId: req.params.reportId, reason, userId: req.user.id });
await appeal.save();
res.status(200).send(‘Appeal submitted successfully.’);
});
6Logging
const logSchema = new mongoose.Schema({
reportId: { type: mongoose.Schema.Types.ObjectId, ref: ‘Report’ },
action: String,
performedAt: { type: Date, default: Date.now },
userId: { type: mongoose.Schema.Types.ObjectId, ref: ‘User’ },
});
const Log = mongoose.model(‘Log’, logSchema);
6 Logging Actions
router.post(‘/moderate/:reportId’, async (req, res) => {
const action = req.body.action;
// Perform moderation action…
const logEntry = new Log({
reportId: req.params.reportId,
action,
performedAt: new Date(),
userId: req.user.id,
});
await logEntry.save();
res.status(200).send(‘Action logged and completed.’);
});
1Further Customization
const rolesPermissions = {
user: [‘submit’],
moderator: [‘submit’, ‘viewReports’, ‘approve’],
admin: [‘submit’, ‘viewReports’, ‘approve’, ‘delete’, ‘manageUsers’],
};
// Middleware to check permissions
function checkPermission(action) {
return (req, res, next) => {
const userRole = req.user.role; // Assume role is set in user object
if (rolesPermissions[userRole].includes(action)) {
return next();
}
return res.status(403).send(‘Permission denied’);
};
}
// Usage
router.get(‘/admin/dashboard’, checkPermission(‘viewReports’), async (req, res) => {
// Fetch and display reports
});
2Advance
from transformers import pipeline
Load sentiment-analysis model
classifier = pipeline(‘text-classification’, model=’your-model’)
def is_content_offensive(content):
result = classifier(content)
return result[0][‘label’] == ‘OFFENSIVE’
3Bulk
router.post(‘/bulk-report’, async (req, res) => {
const { postIds } = req.body; // Array of post IDs
const reports = postIds.map(id => new Report({ postId: id }));
await Report.insertMany(reports);
res.status(200).send(‘Posts reported successfully.’);
});
4 Detailed
router.get(‘/admin/appeals’, async (req, res) => {
const appeals = await Appeal.find().populate(‘reportId’);
res.render(‘appealsDashboard’, { appeals });
});
// Admin can approve or deny appeals
router.post(‘/admin/appeals/:appealId’, async (req, res) => {
const { action } = req.body;
const appeal = await Appeal.findById(req.params.appealId);
if (action === ‘approve’) {
// Logic to reverse moderation action
}
await appeal.remove();
res.status(200).send(‘Appeal processed.’);
});
5 Notification 1
const notificationSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: ‘User’ },
message: String,
read: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now },
});
const Notification = mongoose.model(‘Notification’, notificationSchema);
Notification 2
async function sendNotification(userId, message) {
const notification = new Notification({ userId, message });
await notification.save();
}
// Example usage after moderation
sendNotification(postOwnerId, ‘Your post was flagged for moderation.’);
6 Analytics
router.get(‘/admin/analytics’, async (req, res) => {
const reportCount = await Report.countDocuments();
const appealCount = await Appeal.countDocuments();
const activeUsers = await User.countDocuments({ active: true });
res.json({ reportCount, appealCount, activeUsers });
});
7 Feedback
const feedbackSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: ‘User’ },
content: String,
createdAt: { type: Date, default: Date.now },
});
const Feedback = mongoose.model(‘Feedback’, feedbackSchema);
Feedback 2
router.post(‘/feedback’, async (req, res) => {
const { content } = req.body;
const feedback = new Feedback({ userId: req.user.id, content });
await feedback.save();
res.status(200).send(‘Feedback submitted successfully.’);
});
8.International
const i18n = require(‘i18n’);
i18n.configure({
locales: [‘en’, ‘es’, ‘fr’],
directory: __dirname + ‘/locales’,
});
app.use(i18n.init);
// Usage in routes
router.get(‘/some-route’, (req, res) => {
res.send(req.(‘welcome’)); // ‘welcome’ is a key in your locale files
});
search engine option 1
Search engine : set up, project structure:
pip install Flask
/search_engine
app.py
templates/
index.html
app.py Backend
from flask import Flask, render_template, request
app = Flask(name)
Mock function to simulate search
def search(query, option):
Replace with actual search logic or API calls
return [f”{option} result for ‘{query}'”]
@app.route(‘/’)
def home():
return render_template(‘index.html’)
@app.route(‘/search’, methods=[‘POST’])
def perform_search():
query = request.form[‘query’]
option = request.form[‘option’]
results = search(query, option)
return render_template(‘index.html’, results=results, query=query, option=option)
if name == ‘main‘:
app.run(debug=True)
Index.html Frontend
Search Engine
Search Engine
Websites
Images
Videos
Shopping
News
Books
Short Videos
Maps
Flights
Finance
Search
{% if results %}
Results for “{{ query }}” in “{{ option }}”
{% for result in results %}
{{ result }}
{% endfor %}
{% endif %}
Running the application
python app.py
Open your web browser and go to http://127.0.0.1:5000/. You can enter a query and select a search option.
Search Engine Option 2
pip install Flask requests
Backend(app.py)
from flask import Flask, request, render_template
import requests
app = Flask(name)
Replace with actual API keys and endpoints
API_KEYS = {
“images”: “YOUR_IMAGE_API_KEY”,
“videos”: “YOUR_VIDEO_API_KEY”,
Add other API keys as needed
}
@app.route(‘/’)
def home():
return render_template(‘index.html’)
@app.route(‘/search’, methods=[‘POST’])
def search():
query = request.form[‘query’]
category = request.form[‘category’]
results = []
if category == ‘images’:
results = fetch_images(query)
elif category == ‘videos’:
results = fetch_videos(query)
Add other categories as needed
return render_template(‘results.html’, results=results)
def fetch_images(query):
Example API request for images
response = requests.get(f”https://api.example.com/images?query={query}&key={API_KEYS[‘images’]}”)
return response.json().get(‘results’, [])
def fetch_videos(query):
Example API request for videos
response = requests.get(f”https://api.example.com/videos?query={query}&key={API_KEYS[‘videos’]}”)
return response.json().get(‘results’, [])
if name == ‘main‘:
app.run(debug=True)
FRONTEND:(templates/index.html)
Search Engine
Search Engine
Web
Images
Videos
Shopping
News
Books
Short Videos
Maps
Flights
Finance
Search
Results Page(templates/result.html)
Search Results
Search Results
{% for result in results %}
{{ result }}
{% endfor %}
Back to Search
Running
python app.py
API
Images API
def fetch_images(query):
url = f”https://api.unsplash.com/search/photos?query={query}&client_id={API_KEYS[‘images’]}”
response = requests.get(url)
return response.json().get(‘results’, [])
Videos API
def fetch_videos(query):
url = f”https://www.googleapis.com/youtube/v3/search?part=snippet&q={query}&key={API_KEYS[‘videos’]}”
response = requests.get(url)
return response.json().get(‘items’, [])
End point:https://www.googleapis.com/youtube/v3/search
Shopping
def fetch_shopping(query):
Implementation depends on your access method
Use requests to connect to the API
pass # Implement your API logic here
API: Amazon Product Advertising API
Endpoint: Use Amazon’s Product Search APIs (requires signing up for an account)
News API
def fetch_news(query):
url = f”https://newsapi.org/v2/everything?q={query}&apiKey={API_KEYS[‘news’]}”
response = requests.get(url)
return response.json().get(‘articles’, [])
Endpoint:https://newsapi.org/v2/everything
Google Books API
def fetch_books(query):
url = f”https://www.googleapis.com/books/v1/volumes?q={query}”
response = requests.get(url)
return response.json().get(‘items’, [])
https://www.googleapis.com/books/v1/volumes
Short Videos API
API:TIKTOK API
def fetch_short_videos(query):
Placeholder for short video API integration
pass # Implement your API logic here
Maps
API: Google MAPS API
https://maps.googleapis.com/maps/api/place/textsearch/json
def fetch_maps(query):
url = f”https://maps.googleapis.com/maps/api/place/textsearch/json?query={query}&key={API_KEYS[‘maps’]}”
response = requests.get(url)
return response.json().get(‘results’, [])
Flights
API:Skyscanner API
def fetch_flights(query):
Placeholder for flight API integration
pass # Implement your API logic here
Finance
API:Alpha vantage or Yahoo Finance
def fetch_finance(query):
url = f”https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={query}&apikey={API_KEYS[‘finance’]}”
response = requests.get(url)
return response.json().get(‘Time Series (Daily)’, [])
html structure with all 30 features
Community Platform
News Feed
User posted something…
User Profiles
User Name
Community Groups
Group Name
Marketplace
Item for sale
Event Management
Upcoming Event
Messaging System
Chat message…
Live Video Streaming
Live Stream Here
Stories
Story content…
Analytics Dashboard
Data visualization…
© 2024 Community Platform. All rights reserve
html 2 remaining ones
Discover Content
Article Title
Brief description of the content…
Read More
User Reactions
User reacted to: Post Title
👍 Like
❤ Love
😢 Sad
Comments
User123: Great post!
Post
Polls and Surveys
What’s your favorite color?
Red
Blue
Green
Live Reporting
Live Update: Event Name
Details of the live update…
Interactive Content
Interactive Quiz
Question: What is 2 + 2?
3
4
4
5
Location Tagging
Tag your location:
Tag
Shopping
Product Name
Price: $XX
Add to Cart
Customize Your Content
Choose a theme:
Light
Dark
Apply
Curation
Curated Content Title
Description of curated content…
View
Group Chat
User1: Hello!
Send
Broadcast Lists
List Name
Send Message
Archived Content
Archived Item Title
Summary of the archived content…
View Archived Content
style.css
main {
padding: 20px;
background-color: #f4f4f4;
}
section {
margin-bottom: 30px;
padding: 15px;
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
h2 {
font-size: 24px;
margin-bottom: 10px;
}
h3 {
font-size: 20px;
}
button {
margin-top: 5px;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
input[type=”text”] {
padding: 10px;
width: calc(100% – 22px);
margin-top: 5px;
}
Script.js
document.addEventListener(‘DOMContentLoaded’, function() {
// Example of handling comments
const commentButton = document.querySelector(‘button:contains(“Post”)’);
commentButton.addEventListener(‘click’, function() {
const commentInput = document.querySelector(‘input[type=”text”]’);
const commentSection = document.getElementById(‘comments’);
if (commentInput.value) {
const newComment = document.createElement(‘div’);
newComment.classList.add(‘comment’);
newComment.innerHTML = You: ${commentInput.value}
;
commentSection.appendChild(newComment);
commentInput.value = ”; // Clear input field
}
});
// Poll functionality
const pollButtons = document.querySelectorAll(‘#polls button’);
pollButtons.forEach(button => {
button.addEventListener(‘click’, function() {
alert(You voted for: ${button.textContent});
});
});
// Location tagging functionality
const locationButton = document.querySelector(‘#location-tagging button’);
locationButton.addEventListener(‘click’, function() {
const locationInput = document.querySelector(‘#location-tagging input’);
alert(Location tagged: ${locationInput.value});
});
// More event listeners for other features…
});
Search
React
Reel
React
Videos
React
News
React for all
what’s app set up
pip install Flask
Create flask
from flask import Flask, render_template, request, redirect
app = Flask(name)
@app.route(‘/’, methods=[‘GET’, ‘POST’])
def home():
if request.method == ‘POST’:
phone_number = request.form[‘phone_number’]
return redirect(f’https://wa.me/{phone_number}’)
return render_template(‘index.html’)
if name == ‘main‘:
app.run(debug=True)
Html form
WhatsApp Chat
Chat with WhatsApp Number
Enter WhatsApp Number:
Chat
Run
python app.py
Access application
http://127.0.0.1:5000/
Youtube video display html
YouTube Video Search
YouTube Video Search
Search
Javascript for API
const apiKey = ‘YOUR_YOUTUBE_API_KEY’; // Replace with your API key
document.getElementById(‘search-button’).addEventListener(‘click’, () => {
const query = document.getElementById(‘search-query’).value;
searchYouTube(query);
});
function searchYouTube(query) {
const url = https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=${encodeURIComponent(query)}&key=${apiKey};
fetch(url)
.then(response => response.json())
.then(data => displayVideos(data.items))
.catch(error => console.error(‘Error fetching data:’, error));
}
function displayVideos(videos) {
const container = document.getElementById(‘video-container’);
container.innerHTML = ”; // Clear previous results
videos.forEach(video => {const videoId = video.id.videoId;
const title = video.snippet.title;
const videoElement = document.createElement(‘div’);
videoElement.innerHTML = ${title}
;
container.appendChild(videoElement);
});
}
pip install transformers torch
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer
Load pre-trained model and tokenizer from Hugging Face
model_name = ‘gpt2’ # You can use other models like ‘gpt2-medium’, ‘gpt2-large’, ‘gpt2-xl’
model = GPT2LMHeadModel.from_pretrained(model_name)
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
Ensure that the model is in evaluation mode
model.eval()
def chat_with_gpt2(input_text):
Encode the input text and return tensor representation
inputs = tokenizer.encode(input_text + tokenizer.eos_token, return_tensors=’pt’)
Ensure that the model is on the correct device (GPU or CPU)
device = ‘cuda’ if torch.cuda.is_available() else ‘cpu’
model.to(device)
inputs = inputs.to(device)
Generate a response using the GPT-2 model
with torch.no_grad():
outputs = model.generate(inputs, max_length=100, num_return_sequences=1, no_repeat_ngram_size=2, pad_token_id=tokenizer.eos_token_id)
Decode the generated response back to text
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return response
if name == “main“:
print(“ChatGPT-like Bot: Type ‘exit’ to end the conversation.”)
while True:
Get user input
user_input = input(“You: “)
if user_input.lower() == ‘exit’:
break
Get response from GPT-2 model
response = chat_with_gpt2(user_input)
Print the response
print(f”Bot: {response}”)
pip install Flask
from flask import Flask, request, jsonify
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer
Initialize Flask app
app = Flask(name)
Load model and tokenizer
model_name = ‘gpt2’
model = GPT2LMHeadModel.from_pretrained(model_name)
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model.eval()
device = ‘cuda’ if torch.cuda.is_available() else ‘cpu’
model.to(device)
def chat_with_gpt2(input_text):
inputs = tokenizer.encode(input_text + tokenizer.eos_token, return_tensors=’pt’).to(device)
with torch.no_grad():
outputs = model.generate(inputs, max_length=100, num_return_sequences=1, no_repeat_ngram_size=2, pad_token_id=tokenizer.eos_token_id)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
@app.route(‘/chat’, methods=[‘POST’])
def chat():
user_input = request.json.get(‘message’)
response = chat_with_gpt2(user_input)
return jsonify({“response”: response})
if name == “main“:
app.run(debug=True)
pip install datasets
from transformers import GPT2Tokenizer, GPT2LMHeadModel, Trainer, TrainingArguments
from datasets import load_dataset
Load the pre-trained model and tokenizer
model_name = “gpt2”
model = GPT2LMHeadModel.from_pretrained(model_name)
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
Load your dataset
dataset = load_dataset(‘path_to_your_dataset’)
Tokenize the dataset
def tokenize_function(examples):
return tokenizer(examples[“text”], return_tensors=”pt”, padding=True, truncation=True)
Tokenize the data
tokenized_datasets = dataset.map(tokenize_function, batched=True)
Training arguments
training_args = TrainingArguments(
output_dir=’./results’,
evaluation_strategy=”epoch”,
learning_rate=2e-5,
per_device_train_batch_size=4,
per_device_eval_batch_size=4,
num_train_epochs=3,
weight_decay=0.01,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets[“train”],
eval_dataset=tokenized_datasets[“test”],
)
trainer.train()
pip install openai
import openai
Set up your API key
openai.api_key = ‘your-api-key-here’
def chat_with_gpt3(prompt):
response = openai.Completion.create(
engine=”text-davinci-003″, # Use “text-davinci-003” for GPT-3 (latest version)
prompt=prompt,
max_tokens=150, # Adjust the response length
n=1,
stop=None,
temperature=0.7, # Controls randomness
)
return response.choices[0].text.strip()
if name == “main“:
print(“ChatGPT-like Bot with GPT-3: Type ‘exit’ to end the conversation.”)
while True:
user_input = input(“You: “)
if user_input.lower() == ‘exit’:
break
response = chat_with_gpt3(user_input)
print(f”Bot: {response}”)
from flask import Flask, request, jsonify
import openai
openai.api_key = ‘your-api-key-here’
app = Flask(name)
def chat
from flask import Flask, request, jsonify
import openai
openai.api_key = ‘your-api-key-here’
app = Flask(name)
def chat_with_gpt3(prompt):
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=150,
n=1,
stop=None,
temperature=0.7,
)
return response.choices[0].text.strip()
@app.route(‘/chat’, methods=[‘POST’])
def chat():
user_input = request.json.get(‘message’)
response = chat_with_gpt3(user_input)
return jsonify({“response”: response})
if name == ‘main‘:
app.run(debug=True)
Chatbot Interface
Send
async function sendMessage() {
const userInput = document.getElementById(‘userInput’).value;
if (userInput === ”) return;
const chatbox = document.getElementById(‘chatbox’);
chatbox.innerHTML +=
You: ${userInput};
// Send request to Flask API
const response = await fetch(‘/chat’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ message: userInput })
});
const data = await response.json();
chatbox.innerHTML +=
Bot: ${data.response};
document.getElementById(‘userInput’).value = ”;
}
user_memory = {}
def update_memory(user_id, user_input):
Example: store the user’s name
if “my name is” in user_input.lower():
name = user_input.split(“is”)[-1].strip()
user_memory[user_id] = {“name”: name}
return f”Nice to meet you, {name}!”
return “Got it!”
def get_user_name(user_id):
return user_memory.get(user_id, {}).get(“name”, “Guest”)
def chat_with_context(user_id, user_input):
conversation_history = memory.get(user_id, [])
conversation_history.append(f”You: {user_input}”)
prompt = “\n”.join(conversation_history) # Build the conversation context
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=150,
temperature=0.7
)
reply = response.choices[0].text.strip()
conversation_history.append(f”Bot: {reply}”)
memory[user_id] = conversation_history # Save the context
return reply
def chat_in_multilingual(user_input):
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=user_input,
max_tokens=150,
temperature=0.7
)
return response.choices[0].text.strip()
def chat_in_multilingual(user_input):
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=user_input,
max_tokens=150,
temperature=0.7
)
return response.choices[0].text.strip()
import speech_recognition as sr
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print(“Listening…”)
audio = recognizer.listen(source)
text = recognizer.recognize_google(audio)
print(“You said:”, text)
from gtts import gTTS
import os
def text_to_speech(response):
tts = gTTS(text=response, lang=’en’)
tts.save(“response.mp3”)
os.system(“mpg321 response.mp3”)
from gtts import gTTS
import os
def text_to_speech(response):
tts = gTTS(text=response, lang=’en’)
tts.save(“response.mp3”)
os.system(“mpg321 response.mp3”)
pip install vaderSentiment
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
def analyze_sentiment(user_input):
analyzer = SentimentIntensityAnalyzer()
sentiment_score = analyzer.polarity_scores(user_input)
if sentiment_score[‘compound’] >= 0.05:
return “positive”
elif sentiment_score[‘compound’] return “negative”
else:
return “neutral”
docker build -t chatbot-app .
docker run -d -p 5000:5000 chatbot-app
Simple in-memory conversation history for each user
conversation_memory = {}
def get_conversation_history(user_id):
return conversation_memory.get(user_id, [])
def save_conversation_history(user_id, user_input, bot_response):
if user_id not in conversation_memory:
conversation_memory[user_id] = []
conversation_memory[user_id].append(f”You: {user_input}”)
conversation_memory[user_id].append(f”Bot: {bot_response}”)
def chat_with_memory(user_id, user_input):
history = get_conversation_history(user_id)
prompt = “\n”.join(history) + “\nYou: ” + user_input + “\nBot:”
Call the model with the complete conversation history
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=150,
temperature=0.7
)
bot_response = response.choices[0].text.strip()
save_conversation_history(user_id, user_input, bot_response)
return bot_response
def summarize_conversation(conversation):
Summarization with a model like BART or T5
summary = openai.Completion.create(
engine=”text-davinci-003″,
prompt=f”Summarize the following conversation:\n{conversation}”,
max_tokens=150,
temperature=0.5
)
return summary.choices[0].text.strip()
def chat_with_summarization(user_id, user_input):
history = get_conversation_history(user_id)
conversation = “\n”.join(history) + “\nYou: ” + user_input
if len(conversation.split()) > 200: # If the conversation is too long
conversation = summarize_conversation(conversation)
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=conversation + “\nBot:”,
max_tokens=150,
temperature=0.7
)
bot_response = response.choices[0].text.strip()
save_conversation_history(user_id, user_input, bot_response)
return bot_response
from transformers import DialoGPTTokenizer, DialoGPTForConditionalGeneration
Load pre-trained DialoGPT model
tokenizer = DialoGPTTokenizer.from_pretrained(“microsoft/DialoGPT-medium”)
model = DialoGPTForConditionalGeneration.from_pretrained(“microsoft/DialoGPT-medium”)
def chat_with_dialogue_model(user_input):
Encode user input and generate response
new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors=”pt”)
Generate a response
bot_output = model.generate(new_user_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id, no_repeat_ngram_size=2)
bot_response = tokenizer.decode(bot_output[:, new_user_input_ids.shape[-1]:][0], skip_special_tokens=True)
return bot_response
import requests
def get_weather(city):
api_key = “your_openweather_api_key”
url = f”http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}”
response = requests.get(url).json()
if response.get(“weather”):
return f”The weather in {city} is {response[‘weather’][0][‘description’]}.”
else:
return “Sorry, I couldn’t fetch the weather details.”
def get_news(query=”Technology”):
api_key = “your_newsapi_key”
url = f”https://newsapi.org/v2/top-headlines?category={query}&apiKey={api_key}”
response = requests.get(url).json()
articles = response.get(“articles”, [])
if articles:
headlines = “\n”.join([f”{article[‘title’]} – {article[‘source’][‘name’]}” for article in articles[:5]])
return headlines
else:
return “Sorry, I couldn’t fetch the latest news.”
pip install Flask-JWT-Extended
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
app = Flask(name)
app.config[“JWT_SECRET_KEY”] = “your_secret_key”
jwt = JWTManager(app)
Route to log in and get token
@app.route(“/login”, methods=[“POST”])
def login():
username = request.json.get(“username”, None)
if username:
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200
return jsonify({“message”: “Missing username”}), 400
Secure chat route
@app.route(“/chat”, methods=[“POST”])
@jwt_required()
def chat():
current_user = get_jwt_identity()
user_input = request.json.get(“message”)
response = chat_with_memory(current_user, user_input) # Use context for the user
return jsonify({“response”: response}), 200
if name == “main“:
app.run(debug=True)
import logging
logging.basicConfig(filename=’chatbot_logs.log’, level=logging.INFO)
def log_interaction(user_id, user_input, bot_response):
logging.info(f”User ID: {user_id} | User Input: {user_input} | Bot Response: {bot_response}”)
html
Interactive Search Engine
Search
Toggle Results
Css
/* styles.css */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}
.search-container {
display: flex;
justify-content: center;
padding: 20px;
background-color: #fff;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
searchInput {
padding: 10px;
font-size: 16px;
width: 300px;
border: 1px solid #ddd;
border-radius: 4px;
}
searchButton {
padding: 10px 20px;
font-size: 16px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 4px;
margin-left: 10px;
cursor: pointer;
}
searchButton:hover {
background-color: #0056b3;
}
.results-container {
padding: 20px;
margin-top: 20px;
background-color: #fff;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
max-height: 500px;
overflow: auto;
}
.result-item {
margin-bottom: 15px;
padding: 10px;
background-color: #f9f9f9;
border-radius: 5px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.toggle-btn {
display: block;
width: 200px;
margin: 20px auto;
padding: 10px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.toggle-btn:hover {
background-color: #0056b3;
}
Javascript
// script.js
document.getElementById(‘searchButton’).addEventListener(‘click’, performSearch);
document.getElementById(‘toggleButton’).addEventListener(‘click’, toggleResults);
function performSearch() {
const query = document.getElementById(‘searchInput’).value;
const resultsContainer = document.getElementById(‘resultsContainer’);
// Clear previous results
resultsContainer.innerHTML = ”;
if (query) {
// Simulate some search results
for (let i = 1; i const resultItem = document.createElement(‘div’);
resultItem.classList.add(‘result-item’);
resultItem.innerHTML = Result ${i} for: ${query};
resultsContainer.appendChild(resultItem);
}
} else {
resultsContainer.innerHTML = ‘
No search term entered.
‘;
}
}
function toggleResults() {
const resultsContainer = document.getElementById(‘resultsContainer’);
const toggleButton = document.getElementById(‘toggleButton’);
if (resultsContainer.style.maxHeight === ‘0px’ || resultsContainer.style.maxHeight === ”) {
resultsContainer.style.maxHeight = ‘500px’;
toggleButton.innerText = ‘Fold Results’;
} else {
resultsContainer.style.maxHeight = ‘0px’;
toggleButton.innerText = ‘Show Results’;
}
}
Ai
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer, AdamW
from data_preprocessing.tokenizer import load_data
Load model and tokenizer
model = GPT2LMHeadModel.from_pretrained(‘gpt2’)
tokenizer = GPT2Tokenizer.from_pretrained(‘gpt2’)
Load data
train_data = load_data(‘data/processed/train_data.txt’)
Define optimizer
optimizer = AdamW(model.parameters(), lr=1e-5)
Training loop
for epoch in range(10):
model.train()
for batch in train_data:
optimizer.zero_grad()
inputs = tokenizer(batch, return_tensors=”pt”, padding=True, truncation=True)
outputs = model(**inputs, labels=inputs[‘input_ids’])
loss = outputs.loss
loss.backward()
optimizer.step()
print(f”Epoch {epoch} Loss: {loss.item()}”)
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer
Load the trained model and tokenizer
model = GPT2LMHeadModel.from_pretrained(‘path_to_trained_model’)
tokenizer = GPT2Tokenizer.from_pretrained(‘gpt2’)
def generate_response(prompt):
inputs = tokenizer(prompt, return_tensors=”pt”)
outputs = model.generate(inputs[‘input_ids’], max_length=100)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return response
if name == “main“:
user_input = input(“Ask a question: “)
print(generate_response(user_input))
from fastapi import FastAPI
from model_inference.generate_response import generate_response
app = FastAPI()
@app.get(“/generate/”)
def get_response(prompt: str):
response = generate_response(prompt)
return {“response”: response}
1
1.1
npx react-native init WhatsAppClone
cd WhatsAppClone
npm install react-navigation react-navigation-stack react-native-gesture-handler react-native-reanimated react-native-screens
npm install socket.io-client axios
1.2
import React, { useState } from ‘react’;
import { View, TextInput, Button, Text, StyleSheet } from ‘react-native’;
import axios from ‘axios’;
const LoginScreen = ({ navigation }) => {
const [phone, setPhone] = useState(”);
const [password, setPassword] = useState(”);
const login = async () => {
try {
const response = await axios.post(‘http:///login’, { phone, password });
if (response.data.success) {
navigation.navigate(‘ChatList’);
}
} catch (error) {
console.error(error);
}
};
return (
placeholder=”Phone”
value={phone}
onChangeText={setPhone}
style={styles.input}
/>
placeholder=”Password”
value={password}
onChangeText={setPassword}
style={styles.input}
secureTextEntry
/>
navigation.navigate(‘Signup’)}>Don’t have an account? Sign up
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: ‘center’, alignItems: ‘center’ },
input: { width: 200, height: 40, borderWidth: 1, margin: 10, padding: 10 },
});
export default LoginScreen;
1.3 Chat screen
import React, { useState, useEffect } from ‘react’;
import { View, TextInput, Button, Text, FlatList, StyleSheet } from ‘react-native’;
import io from ‘socket.io-client’;
import axios from ‘axios’;
const ChatScreen = ({ route }) => {
const { userId } = route.params; // Get user id from route params
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState(”);
const socket = io(‘http://’); // Your backend URL here
useEffect(() => {
socket.emit(‘join_room’, userId);
socket.on(‘receive_message’, (message) => {
setMessages((prevMessages) => […prevMessages, message]);
});
return () => {
socket.disconnect();
};
}, []);
const sendMessage = () => {
socket.emit(‘send_message’, { userId, message });
setMessage(”);
};
return (
data={messages}
renderItem={({ item }) => {item.text}}
keyExtractor={(item, index) => index.toString()}
/>
placeholder=”Type a message”
value={message}
onChangeText={setMessage}
style={styles.input}
/>
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: ‘flex-end’ },
input: { width: ‘100%’, height: 40, borderWidth: 1, margin: 10, padding: 10 },
});
export default ChatScreen;
2
mkdir backend
cd backend
npm init -y
npm install express socket.io mongoose body-parser jsonwebtoken bcryptjs dotenv
2.2
const express = require(‘express’);
const http = require(‘http’);
const socketIo = require(‘socket.io’);
const mongoose = require(‘mongoose’);
const cors = require(‘cors’);
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect(‘mongodb://localhost/whatsappclone’, { useNewUrlParser: true, useUnifiedTopology: true });
// User Schema and Model
const userSchema = new mongoose.Schema({
phone: String,
password: String,
});
const User = mongoose.model(‘User’, userSchema);
// Message Schema and Model
const messageSchema = new mongoose.Schema({
text: String,
userId: String,
timestamp: { type: Date, default: Date.now },
});
const Message = mongoose.model(‘Message’, messageSchema);
// Handle user authentication (signup/login)
app.post(‘/signup’, async (req, res) => {
const { phone, password } = req.body;
const user = new User({ phone, password });
await user.save();
res.status(201).send({ success: true });
});
app.post(‘/login’, async (req, res) => {
const { phone, password } = req.body;
const user = await User.findOne({ phone, password });
if (user) {
res.send({ success: true });
} else {
res.send({ success: false, message: ‘Invalid credentials’ });
}
});
// Real-time messaging using Socket.IO
io.on(‘connection’, (socket) => {
console.log(‘a user connected’);
socket.on(‘join_room’, (userId) => {
socket.join(userId);
console.log(User ${userId} joined the room);
});
socket.on(‘send_message’, async (data) => {
const { userId, message } = data;
const newMessage = new Message({ userId, text: message });
await newMessage.save();
io.to(userId).emit(‘receive_message’, newMessage); // Send message to the room
});
socket.on(‘disconnect’, () => {
console.log(‘user disconnected’);
});
});
server.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});
3
2.
npm install @react-native-firebase/app @react-native-firebase/messaging
3.
import messaging from ‘@react-native-firebase/messaging’;
// Request permission to send notifications
const requestUserPermission = async () => {
const authStatus = await messaging.requestPermission();
const isAuthStatusAuthorized = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (isAuthStatusAuthorized) {
const token = await messaging.getToken();
console.log(‘FCM Token:’, token);
}
};
useEffect(() => {
requestUserPermission();
}, []);
2.1
pip install openai requests
2.2
import openai
openai.api_key = ‘your-api-key-here’
3.
import openai
Set your OpenAI API key
openai.api_key = ‘your-api-key-here’
def generate_image(prompt):
try:
Call the DALL·E 2 API to generate the image
response = openai.Image.create(
prompt=prompt, # Text description for image generation
n=1, # Number of images to generate
size=”1024×1024″ # Image size (other options: 256×256, 512×512)
)
Get the URL of the generated image
image_url = response[‘data’][0][‘url’]
return image_url
except Exception as e:
return f”Error generating image: {str(e)}”
Example usage
prompt = “a futuristic city with flying cars at sunset”
image_url = generate_image(prompt)
print(f”Generated Image URL: {image_url}”)
4.
import openai
Set your OpenAI API key
openai.api_key = ‘your-api-key-here’
def generate_image(prompt):
try:
Call the DALL·E 2 API to generate the image
response = openai.Image.create(
prompt=prompt, # Text description for image generation
n=1, # Number of images to generate
size=”1024×1024″ # Image size (other options: 256×256, 512×512)
)
Get the URL of the generated image
image_url = response[‘data’][0][‘url’]
return image_url
except Exception as e:
return f”Error generating image: {str(e)}”
Example usage
prompt = “a futuristic city with flying cars at sunset”
image_url = generate_image(prompt)
print(f”Generated Image URL: {image_url}”)
5,2,
prompt = f”Write a {tone} email based on the following details: {details}”
5.4.
def categorize_input(user_input):
if “email” in user_input:
return ’email’
elif “essay” in user_input:
return ‘essay’
elif “blog” in user_input:
return ‘blog post’
Add more categories as needed
else:
return ‘general writing’
6.
import React, { useState } from ‘react’;
function WriteAssistant() {
const [taskType, setTaskType] = useState(”);
const [details, setDetails] = useState(”);
const [generatedContent, setGeneratedContent] = useState(”);
const handleGenerate = async () => {
const response = await fetch(‘/api/write-assistant’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ taskType, details }),
});
const data = await response.json();
setGeneratedContent(data.generatedText);
};
return (
Help Me Write
Task Type:
setTaskType(e.target.value)} />
Details:
setDetails(e.target.value)} />
Generate
{generatedContent && (
Generated Text
{generatedContent}
)}
);
}
export default WriteAssistant;
2.3.
pip install openai
4.
import openai
openai.api_key = ‘your-api-key-here’
3.
import openai
Set OpenAI API key
openai.api_key = ‘your-api-key-here’
def get_advice(topic, details):
“””
Function to generate advice based on the user’s input.
topic: (str) The category of advice (e.g., ‘career’, ‘health’, ‘relationships’).
details: (str) The user’s specific question or situation.
“””
Create a customized prompt based on the topic
prompt = “”
if topic == ‘career’:
prompt = f”Provide career advice for someone facing the following situation: {details}”
elif topic == ‘health’:
prompt = f”Give health and wellness advice for the following situation: {details}”
elif topic == ‘relationships’:
prompt = f”Provide relationship advice for someone experiencing the following issue:
{details}”
elif topic == ‘financial’:
prompt = f”Offer financial advice based on this scenario: {details}”
elif topic == ‘personal development’:
prompt = f”Give advice on personal development for someone in this situation: {details}”
elif topic == ‘productivity’:
prompt = f”Provide productivity advice for someone struggling with the following challenge: {details}”
else:
return “Sorry, I don’t have advice for that topic.”
try:
Call OpenAI’s API to generate the advice
response = openai.Completion.create(
engine=”text-davinci-003″, # You can use a different engine like GPT-4
prompt=prompt,
max_tokens=200, # Limit the length of the response
temperature=0.7, # Adjust creativity (0 to 1)
top_p=1,
n=1,
stop=None
)
Extract the generated text from the response
advice = response[‘choices’][0][‘text’].strip()
return advice
except Exception as e:
return f”Error generating advice: {str(e)}”
Example usage
topic = “career”
details = “I’m struggling to find a job after college. What should I do?”
advice = get_advice(topic, details)
print(advice)
4.
import openai
Set OpenAI API key
openai.api_key = ‘your-api-key-here’
def get_advice(topic, details):
“””
Function to generate advice based on the user’s input.
topic: (str) The category of advice (e.g., ‘career’, ‘health’, ‘relationships’).
details: (str) The user’s specific question or situation.
“””
Create a customized prompt based on the topic
prompt = “”
if topic == ‘career’:
prompt = f”Provide career advice for someone facing the following situation: {details}”
elif topic == ‘health’:
prompt = f”Give health and wellness advice for the following situation: {details}”
elif topic == ‘relationships’:
prompt = f”Provide relationship advice for someone experiencing the following issue: {details}”
elif topic == ‘financial’:
prompt = f”Offer financial advice based on this scenario: {details}”
elif topic == ‘personal development’:
prompt = f”Give advice on personal development for someone in this situation: {details}”
elif topic == ‘productivity’:
prompt = f”Provide productivity advice for someone struggling with the following challenge: {details}”
else:
return “Sorry, I don’t have advice for that topic.”
try:
Call OpenAI’s API to generate the advice
response = openai.Completion.create(
engine=”text-davinci-003″, # You can use a different engine like GPT-4
prompt=prompt,
max_tokens=200, # Limit the length of the response
temperature=0.7, # Adjust creativity (0 to 1)
top_p=1,
n=1,
stop=None
)
Extract the generated text from the response
advice = response[‘choices’][0][‘text’].strip()
return advice
except Exception as e:
return f”Error generating advice: {str(e)}”
Example usage
topic = “career”
details = “I’m struggling to find a job after college. What should I do?”
advice = get_advice(topic, details)
print(advice)
5.import React, { useState } from ‘react’;
function GetAdvice() {
const [topic, setTopic] = useState(”);
const [details, setDetails] = useState(”);
const [advice, setAdvice] = useState(”);
const handleGetAdvice = async () => {
const response = await fetch(‘/api/get-advice’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ topic, details }),
});
const data = await response.json();
setAdvice(data.advice);
};
return (
Need Advice? Ask Me!
Topic:
type=”text”
value={topic}
onChange={(e) => setTopic(e.target.value)}
placeholder=”e.g., career, health, relationships”
/>
Details:
value={details}
onChange={(e) => setDetails(e.target.value)}
placeholder=”Tell me more about the situation”
/>
Get Advice
{advice && (
Advice:
{advice}
)}
);
}
export default GetAdvice;
2.2
pip install openai
2.3
import openai
openai.api_key = ‘your-api-key-here’
3.
import openai
Set up OpenAI API key
openai.api_key = ‘your-api-key-here’
def summarize_text(text):
“””
Function to summarize a given text using OpenAI’s GPT-4 model.
text: (str) The content to be summarized.
Returns:
str: The summary of the text.
“””
prompt = f”Please summarize the following text:\n\n{text}\n\nSummary:”
try:
Make a request to the OpenAI API
response = openai.Completion.create(engine=”text-davinci-003″, # Or use GPT-4 if available
prompt=prompt,
max_tokens=150, # Limit the length of the summary (adjust as needed)
temperature=0.5, # Balance between creativity and focus (lower is more focused)
top_p=1,
n=1,
stop=None
)
)
Extract and return the summary from the response
summary = response[‘choices’][0][‘text’].strip()
return summary
except Exception as e:
return f”Error summarizing the text: {str(e)}”
Example usage
input_text = “””
Artificial intelligence (AI) is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans and animals. Leading AI textbooks define the field as the study of “intelligent agents”: any device that perceives its environment and takes actions that maximize its chance of successfully achieving its goals. Colloquially, the term “artificial intelligence” is often used to describe machines (or computers) that mimic “cognitive” functions that humans associate with the human mind, such as “learning” and “problem-solving”.
“””
summary = summarize_text(input_text)
print(“Summary:”, summary)
4.1
import React, { useState } from ‘react’;
function SummarizeText() {
const [inputText, setInputText] = useState(”);
const [summary, setSummary] = useState(”);
const handleSummarize = async () => {
const response = await fetch(‘/api/summarize’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ text: inputText }),
});
const data = await response.json();
setSummary(data.summary);
};
return (
Summarize Text
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder=”Paste your text here”
rows=”8″
cols=”50″
/>
Summarize
{summary && (
Summary:
{summary}
)}
);
}
export default SummarizeText;
4.2
from flask import Flask, request, jsonify
from summarize import summarize_text # The summarization function we created earlier
app = Flask(name)
@app.route(‘/api/summarize’, methods=[‘POST’])
def summarize():
data = request.get_json()
text = data.get(‘text’, ”)
summary = summarize_text(text)
return jsonify({‘summary’: summary})
if name == ‘main‘:
app.run(debug=True)
Integrate code tool
2.3.
pip install openai
2.4.
import openai
openai.api_key = ‘your-api-key-here’
3.
import openai
Set up OpenAI API key
openai.api_key = ‘your-api-key-here’
def generate_code(prompt, language=’python’):
“””
Function to generate code based on the user’s prompt using OpenAI’s GPT-4.
prompt: (str) The code prompt (e.g., ‘Create a function that checks if a number is prime’).
language: (str) The programming language for the generated code (‘python’, ‘javascript’, etc.)
Returns:
str: The generated code.
Customize prompt based on the language
if language == ‘python’:
prompt = f”Write a Python function for this task: {prompt}”
elif language == ‘javascript’:
prompt = f”Write a JavaScript function for this task: {prompt}”
elif language == ‘java’:
prompt = f”Write a Java method for this task: {prompt}”
else:
prompt = f”Write a function in {language} for this task: {prompt}”
try:
Call the OpenAI API to generate the code
response = openai.Completion.create(
engine=”text-davinci-003″, # GPT-3 engine (use GPT-4 if available)
prompt=prompt,
max_tokens=200, # Limit the length of the response
temperature=0.7, # Control randomness (0.7 is a balanced value)
top_p=1,
n=1,
stop=None
)
Extract and return the generated code from the response
generated_code = response[‘choices’][0][‘text’].strip()
return generated_code
except Exception as e:
return f”Error generating code: {str(e)}”
Example usage
prompt = “Create a function that checks if a number is prime”
language = ‘python’
generated_code = generate_code(prompt, language)
print(“Generated Code:\n”, generated_code)
4.1
def debug_code(code_snippet):
“””
Function to debug a code snippet using OpenAI’s GPT-4.
code_snippet: (str) The code that needs to be debugged.
Returns:
str: The debugging suggestions or fixes.
“””
prompt = f”Debug the following code and suggest improvements or fixes:\n{code_snippet}”
try:
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=150,
temperature=0.3, # Lower temperature for more focused responses
top_p=1,
n=1,
stop=None
)
Return the response from GPT-4 (debugging advice)
debug_suggestions = response[‘choices’][0][‘text’].strip()
return debug_suggestions
except Exception as e:
return f”Error debugging code: {str(e)}”
Example usage
code_snippet = “””
def check_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
“””
debug_suggestions = debug_code(code_snippet)
print(“Debugging Suggestions:\n”, debug_suggestions)
4.2
def explain_code(code_snippet):
“””
Function to explain a code snippet using OpenAI’s GPT-4.
code_snippet: (str) The code to be explained.
Returns:
str: Explanation of the code.
“””
prompt = f”Explain the following code in simple terms:\n{code_snippet}”
try:
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=200,
temperature=0.5,
top_p=1,
n=1,
stop=None
)
Return the explanation of the code
explanation = response[‘choices’][0][‘text’].strip()
return explanation
except Exception as e:
return f”Error explaining code: {str(e)}”
Example usage
code_snippet = “””
def add_numbers(a, b):
return a + b
“””
explanation = explain_code(code_snippet)
print(“Code Explanation:\n”, explanation)
4.2
def explain_code(code_snippet):
“””
Function to explain a code snippet using OpenAI’s GPT-4.
code_snippet: (str) The code to be explained.
Returns:
str: Explanation of the code.
“””
prompt = f”Explain the following code in simple terms:\n{code_snippet}”
try:
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=200,
temperature=0.5,
top_p=1,
n=1,
stop=None
)
Return the explanation of the code
explanation = response[‘choices’][0][‘text’].strip()
return explanation
except Exception as e:
return f”Error explaining code: {str(e)}”
Example usage
code_snippet = “””
def add_numbers(a, b):
return a + b
“””
explanation = explain_code(code_snippet)
print(“Code Explanation:\n”, explanation)
4.3 next page
4.3
def translate_code(code_snippet, from_language, to_language):
“””
Function to translate code from one language to another using OpenAI’s GPT-4.
code_snippet: (str) The code to be translated.
from_language: (str) The language the code is currently written in (e.g., ‘python’).
to_language: (str) The language to translate the code into (e.g., ‘javascript’).
Returns:
str: The translated code.
“””
prompt = f”Translate the following {from_language} code to {to_language}:\n{code_snippet}”
try:
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=200,
temperature=0.6,
top_p=1,
n=1,
stop=None
)
Return the translated code
translated_code = response[‘choices’][0][‘text’].strip()
return translated_code
except Exception as e:
return f”Error translating code: {str(e)}”
Example usage
python_code = “””
def greet(name):
print(f’Hello, {name}!’)
“””
translated_code = translate_code(python_code, ‘python’, ‘javascript’)
print(“Translated Code:\n”, translated_code)
)
Return the translated code
translated_code = response[‘choices’][0][‘text’].strip()
return translated_code
except Exception as e:
return f”Error translating code: {str(e)}”
Example usage
python_code = “””
def greet(name):
print(f’Hello, {name}!’)
“””
translated_code = translate_code(python_code, ‘python’, ‘javascript’)
print(“Translated Code:\n”, translated_code)
Brainstorm
2.3.
pip install openai
2.4.
import openai
openai.api_key = ‘your-api-key-here’
3.
import openai
openai.api_key = ‘your-api-key-here’
Output
Brainstormed Ideas:
- Launch a zero-waste packaging service for e-commerce businesses.
- Create an app that helps users reduce their carbon footprint by tracking daily activities.
- Develop a sustainable fashion brand using recycled materials.
- Start a community garden initiative that grows organic food for local restaurants.
- Create an online marketplace for eco-friendly products from small artisans.
4.1
def brainstorm_with_categories(prompt, categories, num_ideas=5):
“””
Function to generate brainstorming ideas with specific categories.
prompt: (str) The prompt or challenge for brainstorming.
categories: (list) List of categories for ideas (e.g., [‘business’, ‘product’, ‘service’]).
num_ideas: (int) Number of ideas to generate.
Returns:
dict: A dictionary of ideas categorized by the specified categories.
“””
formatted_prompt = f”Brainstorm {num_ideas} ideas for {prompt}. Categorize ideas under the following categories: {‘, ‘.join(categories)}”
try:
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=formatted_prompt,
max_tokens=250,
temperature=0.8,
top_p=1,
n=1,
stop=None
)
ideas = response[‘choices’][0][‘text’].strip().split(‘\n’)
categorized_ideas = {category: [] for category in categories}
for idea in ideas:
Assuming each idea is categorized in some way by the model
for category in categories:
if category.lower() in idea.lower():
categorized_ideas[category].append(idea)
return categorized_ideas
except Exception as e:
return f”Error generating categorized brainstorming ideas: {str(e)}”
Example usage
categories = [‘business’, ‘product’, ‘service’]
prompt = “innovative startup ideas”
categorized_ideas = brainstorm_with_categories(prompt, categories, num_ideas=5)
for category, ideas in categorized_ideas.items():
print(f”\n{category.capitalize()} Ideas:”)
for idea in ideas:
print(f”- {idea}”)
4.2
def refine_idea(idea):
“””
Refines a specific idea and provides more details.
idea: (str) The idea to be refined.
Returns:
str: A refined version of the idea with more details and considerations.
“””
prompt = f”Refine this idea by providing more details and making it more actionable: {idea}”
try:
response = openai.Completion.create(
engine=”text-davinci-003″,
prompt=prompt,
max_tokens=150,
temperature=0.6,
top_p=1,
n=1,
stop=None
)
refined_idea = response[‘choices’][0][‘text’].strip()
return refined_idea
except Exception as e:
return f”Error refining idea: {str(e)}”
Example usage
idea = “Create an app for sustainable transportation.”
refined_idea = refine_idea(idea)
print(“Refined Idea:”, refined_idea)
5.
import React, { useState } from ‘react’;
function BrainstormTool() {
const [prompt, setPrompt] = useState(”);
const [ideas, setIdeas] = useState([]);
const [loading, setLoading] = useState(false);
const handleBrainstorm = async () => {
setLoading(true);
const response = await fetch(‘/api/brainstorm’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ prompt, num_ideas: 5 }),
});
const data = await response.json();
setIdeas(data.ideas);
setLoading(false);
};
return (
Brainstorming Tool
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder=”Enter your brainstorming prompt”
rows=”4″
cols=”50″
/>
{loading ? ‘Loading…’ : ‘Generate Ideas’}
{ideas.length > 0 && (
Generated Ideas:
{ideas.map((idea, index) => (
{idea}
))}
)}
);
}
export default BrainstormTool;
Make a plan
1.
import spacy
nlp = spacy.load(‘en_core_web_sm’)
text = “Help me make a study plan for my exam in two weeks.”
doc = nlp(text)
for ent in doc.ents:
print(ent.text, ent.label_)
3.
from google.oauth2 import service_account
from googleapiclient.discovery import build
Set up the Calendar API client
credentials = service_account.Credentials.from_service_account_file(
‘credentials.json’, scopes=[‘https://www.googleapis.com/auth/calendar’]
)
service = build(‘calendar’, ‘v3’, credentials=credentials)
Create an event for a study session
event = {
‘summary’: ‘Study Session for Math’,
‘start’: {‘dateTime’: ‘2024-12-21T09:00:00’, ‘timeZone’: ‘America/Los_Angeles’},
‘end’: {‘dateTime’: ‘2024-12-21T12:00:00’, ‘timeZone’: ‘America/Los_Angeles’}
}
service.events().insert(calendarId=’primary’, body=event).execute()
5.
def create_study_plan(goal, time_frame, available_hours, subjects):
plan = []
Break down the plan based on the goal and time frame
days = time_frame # e.g., 14 days for 2 weeks
tasks_per_day = len(subjects) # Assuming 1 task per subject per day
hours_per_task = available_hours / tasks_per_day
for day in range(1, days + 1):
daily_plan = []
for subject in subjects:
daily_plan.append(f”{subject} – {hours_per_task} hours”)
plan.append(f”Day {day}: ” + “, “.join(daily_plan))
return plan
Example Usage
goal = “Study for exams”
time_frame = 14 # Days
available_hours = 3 # Hours per day
subjects = [“Math”, “Physics”, “History”]
study_plan = create_study_plan(goal, time_frame, available_hours, subjects)
Output the plan
for day_plan in study_plan:
print(day_plan)
Drop-down
Html
Search Results Dropdown
Toggle Results
Css
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.search-container {
display: flex;
align-items: center;
margin-bottom: 10px;
}
searchBox {
padding: 8px;
margin-right: 10px;
width: 200px;
}
toggleBtn {
padding: 8px 15px;
}
dropdown-container {
display: none;
margin-top: 10px;
border: 1px solid #ccc;
max-width: 250px;
border-radius: 4px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
resultsList {
list-style-type: none;
padding: 0;
margin: 0;
}
resultsList li {
padding: 8px;
border-bottom: 1px solid #ddd;
}
resultsList li:last-child {
border-bottom: none;
}
resultsList li:hover {
background-color: #f0f0f0;
}
Javascript
let results = [
“Apple”,
“Banana”,
“Orange”,
“Grapes”,
“Mango”,
“Pineapple”,
“Watermelon”
];
function searchResults() {
const query = document.getElementById(“searchBox”).value.toLowerCase();
const resultsList = document.getElementById(“resultsList”);
resultsList.innerHTML = ”; // Clear previous results
if (query.length > 0) {
let filteredResults = results.filter(item => item.toLowerCase().includes(query));
filteredResults.forEach(result => {
let li = document.createElement(‘li’);
li.textContent = result;
resultsList.appendChild(li);
});
}
}
function toggleDropdown() {
const dropdownContainer = document.getElementById(“dropdownContainer”);
const currentDisplay = dropdownContainer.style.display;
// Toggle dropdown visibility
if (currentDisplay === “none” || currentDisplay === “”) {
dropdownContainer.style.display = “block”;
} else {
dropdownContainer.style.display = “none”;
}
}
What’s app like msg service
1.1
mkdir chat-app
cd chat-app
npm init -y
npm install express socket.io mongoose jsonwebtoken bcryptjs
1.2
const express = require(‘express’);
const socketIo = require(‘socket.io’);
const http = require(‘http’);
const mongoose = require(‘mongoose’);
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// MongoDB connection
mongoose.connect(‘mongodb://localhost/chatapp’, { useNewUrlParser: true, useUnifiedTopology: true });
const UserSchema = new mongoose.Schema({
username: String,
phoneNumber: String,
profilePic: String,
status: String,
});
const MessageSchema = new mongoose.Schema({
from: String,
to: String,
message: String,
timestamp: Date,
});
const User = mongoose.model(‘User’, UserSchema);
const Message = mongoose.model(‘Message’, MessageSchema);
io.on(‘connection’, (socket) => {
console.log(‘A user connected’);
// Handle incoming messages
socket.on(‘message’, async (msg) => {
const message = new Message({
from: msg.from,
to: msg.to,
message: msg.message,
timestamp: new Date(),
});
await message.save();
io.emit(‘newMessage’, msg);
});
socket.on(‘disconnect’, () => {
console.log(‘User disconnected’);
});
});
app.listen(5000, () => {
console.log(‘Server running on port 5000’);
});
2.1
npx create-react-app chat-frontend
cd chat-frontend
npm install socket.io-client
2.2
import React, { useState, useEffect } from ‘react’;
import { io } from ‘socket.io-client’;
const socket = io(‘http://localhost:5000’);
const Chat = () => {
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState(”);
const [user, setUser] = useState(‘User1’); // Example user
useEffect(() => {
socket.on(‘newMessage’, (msg) => {
setMessages((prevMessages) => […prevMessages, msg]);
});
}, []);
const sendMessage = () => {
socket.emit(‘message’, { from: user, to: ‘User2’, message });
setMessage(”);
};
return (
{messages.map((msg, index) => (
{msg.from}: {msg.message}
))}
type=”text”
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
Send
);
};
export default Chat;
3.1
const uploadFile = (file) => {
const formData = new FormData();
formData.append(‘file’, file);
fetch(‘https://your-storage-api.com/upload’, {
method: ‘POST’,
body: formData,
})
.then(response => response.json())
.then(data => {
console.log(‘File uploaded:’, data);
})
.catch(error => {
console.error(‘Error:’, error);
});
};
1.1
const express = require(‘express’);
const socketIo = require(‘socket.io’);
const http = require(‘http’);
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
let onlineUsers = {}; // Track online users
// When a user connects
io.on(‘connection’, socket => {
console.log(‘A user connected: ‘ + socket.id);
// Store the user connection status
socket.on(‘register’, (userId) => {
onlineUsers[userId] = socket.id;
console.log(User ${userId} is online);
});
// Handle incoming messages
socket.on(‘sendMessage’, (data) => {
const { to, from, message } = data;
if (onlineUsers[to]) {
io.to(onlineUsers[to]).emit(‘receiveMessage’, { from, message { from, message });
}
});
// Disconnecting user
socket.on(‘disconnect’, () => {
for (let user in onlineUsers) {
if (onlineUsers[user] === socket.id) {
delete onlineUsers[user];
console.log(User ${user} disconnected);
}
}
});
});
server.listen(5000, () => {
console.log(‘Server running on port 5000’);
});
1.2
import React, { useState, useEffect } from ‘react’;
import { io } from ‘socket.io-client’;
const socket = io(‘http://localhost:5000’); // Backend URL
const Chat = () => {
const [message, setMessage] = useState(”);
const [messages, setMessages] = useState([]);
const [userId] = useState(‘user1’); // Assume static user ID for now
useEffect(() => {
socket.emit(‘register’, userId); // Register user when connecting to socket
socket.on(‘receiveMessage’, (data) => {
setMessages((prevMessages) => […prevMessages, data]);
});
return () => {
socket.disconnect();
};
}, [userId]);
const sendMessage = () => {
if (message.trim()) {
socket.emit(‘sendMessage’, { from: userId, to: ‘user2’, message });
setMessages((prevMessages) => […prevMessages, { from: userId, message }]);
setMessage(”);
}
};
return (
{messages.map((msg, idx) => (
{msg.from}: {msg.message}
))}
type=”text”
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
Send
);
};
export default Chat;
3.1
if (‘Notification’ in window && ‘serviceWorker’ in navigator) {
navigator.serviceWorker.register(‘/service-worker.js’)
.then(registration => {
Notification.requestPermission(permission => {
if (permission === “granted”) {
registration.showNotification(‘New message’, {
body: ‘You have received a new message!’,
icon: ‘icon.png’,
});
}
});
});
}
Backend
const admin = require(‘firebase-admin’);
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
// Send notification
const message = {
notification: {
title: ‘New Message!’,
body: ‘You have a new message.’,
},
token: recipientToken, // This is the device token to send the push notification to
};
admin.messaging().send(message)
.then(response => {
console.log(‘Successfully sent message:’, response);
})
.catch(error => {
console.log(‘Error sending message:’, error);
});
2.1
const twilio = require(‘twilio’);
const client = new twilio(‘your_account_sid’, ‘your_auth_token’);
client.messages.create({
body: ‘Your OTP code is 123456’,
from: ‘+1234567890’, // Twilio number
to: ‘+0987654321’, // User’s phone number
})
.then(message => console.log(message.sid));
2.2
const jwt = require(‘jsonwebtoken’);
const bcrypt = require(‘bcryptjs’);
const User = require(‘./models/User’); // Assume you have a User model
// Register user
app.post(‘/signup’, async (req, res) => {
const { username, password, phone } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ username, password: hashedPassword, phone });
await newUser.save();
res.status(201).json({ message: ‘User created’ });
});
// Login user and issue JWT token
app.post(‘/login’, async (req, res) => {
const { phone, password } = req.body;
const user = await User.findOne({ phone });
if (!user) return res.status(400).json({ message: ‘User not found’ });
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) return res.status(400).json({ message: ‘Invalid credentials’ });
const token = jwt.sign({ userId: user._id }, ‘your_jwt_secret’);
res.json({ token });
});
2.3
const GroupSchema = new mongoose.Schema({
name: String,
members: [S
4.2
// Client-side (React)
const startCall = () => {
// Set up the peer connection, handle media streams
const peerConnection = new RTCPeerConnection();
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
// Display local video
document.getElementById(‘local-video’).srcObject = stream;
// Add local stream to peer connection
stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
});
};
5.1
const multer = require(‘multer’);
const upload = multer({ dest: ‘uploads/’ });
app.post(‘/upload’, upload.single(‘file’), (req, res) => {
console.log(req.file);
// Store file to cloud storage and return URL
res.json({ fileUrl: ‘path_to_file’ });
});
1.2
const crypto = require(‘crypto’);
// Generate RSA Keys (done once for each user)
const { publicKey, privateKey } = crypto.generateKeyPairSync(‘rsa’, {
modulusLength: 2048,
});
// Encrypt message with recipient’s public key
function encryptMessage(message, publicKey) {
const buffer = Buffer.from(message, ‘utf-8’);
const encryptedMessage = crypto.publicEncrypt(publicKey, buffer);
return encryptedMessage.toString(‘base64’);
}
// Decrypt message with recipient’s private key
function decryptMessage(encryptedMessage, privateKey) {
const buffer = Buffer.from(encryptedMessage, ‘base64’);
const decryptedMessage = crypto.privateDecrypt(privateKey, buffer);
return decryptedMessage.toString(‘utf-8’);
}
4.
socket.on(‘typing’, (userId, conversationId) => {
socket.broadcast.emit(‘showTyping’, { userId, conversationId });
});
4.
const [isTyping, setIsTyping] = useState(false);
const handleTyping = (e) => {
setIsTyping(true);
socket.emit(‘typing’, userId, conversationId);
};
useEffect(() => {
socket.on(‘showTyping’, (data) => {
if (data.conversationId === conversationId) {
// Show “User is typing…” indicator
}
});
}, [conversationId]);
1.
const AWS = require(‘aws-sdk’);
const s3 = new AWS.S3();
const uploadFileToS3 = (file, userId) => {
const params = {
Bucket: ‘your-bucket-name’,
Key: ${userId}/${Date.now()}-${file.originalname},
Body: file.buffer,
ContentType: file.mimetype,
};
return s3.upload(params).promise();
};
1.
const sharp = require(‘sharp’);
const compressImage = (inputPath, outputPath) => {
sharp(inputPath)
.resize(800) // Resize to 800px width
.jpeg({ quality: 80 }) // Compress JPEG
.toFile(outputPath);
};
ffmpeg -i input.mp4 -vcodec libx264 -acodec aac -strict -2 output.mp4
2.
const { Client } = require(‘@elastic/elasticsearch’);
const client = new Client({ node: ‘http://localhost:9200’ });
async function indexMessage(message) {
await client.index({
index: ‘messages’,
body: {
userId: message.userId,
conversationId: message.conversationId,
text: message.text,
timestamp: message.timestamp,
}
});
}
async function searchMessages(query) {
const { body } = await client.search({
index: ‘messages’,
body: {
query: {
match: { text: query },
},
},
});
return body.hits.hits;
}
Js
db.messages.createIndex({ text: “text” });
db.messages.find({ $text: { $search: “hello” } });
3.
// Open IndexedDB
const request = indexedDB.open(“chatDatabase”, 1);
request.onupgradeneeded = function (e) {
const db = e.target.result;
if (!db.objectStoreNames.contains(“messages”)) {
db.createObjectStore(“messages”, { keyPath: “messageId” });
}
};
function saveMessageLocally(message) {
const db = request.result;
const transaction = db.transaction(“messages”, “readwrite”);
const store = transaction.objectStore(“messages”);
store.put(message);
}
function syncMessages() {
// Sync local messages with server when online
// For example, send saved messages to the server via API calls
}
4.
const Sentry = require(‘@sentry/node’);
Sentry.init({ dsn: ‘your_sentry_dsn’ });
// Capture errors in your app
app.get(‘/some-endpoint’, function mainHandler(req, res) {
throw new Error(‘Something went wrong!’);
});
5.
function checkAdminRole(req, res, next) {
if (req.user.role === ‘admin’) {
return next();
}
res.status(403).send(‘Forbidden’);
}
1.
const axios = require(‘axios’);
async function sendPushNotification(token, message) {
const fcmUrl = ‘https://fcm.googleapis.com/fcm/send’;
const headers = {
‘Authorization’: key=YOUR_SERVER_KEY,
‘Content-Type’: ‘application/json’
};
const body = {
to: token,
notification: {
title: ‘New Message’,
body: message,
sound: ‘default’
}
};
try {
const response = await axios.post(fcmUrl, body, { headers });
console.log(response.data);
} catch (error) {
console.error(‘Error sending push notification:’, error);
}
}
2.
const io = require(‘socket.io’)(server, {
perMessageDeflate: {
threshold: 1024, // Messages larger than 1KB will be compressed
}
});
Js
// Join a room (conversation) for a user
socket.join(conversationId);
// Emit to everyone in the room
io.to(conversationId).emit(‘newMessage’, message);
Js
// On the recipient’s side, emit event back to the sender to acknowledge receipt
socket.emit(‘messageReceived’, { messageId, userId });
Js
const redis = require(‘redis’);
const subscriber = redis.createClient();
const publisher = redis.createClient();
// On message send, publish to Redis
publisher.publish(‘newMessageChannel’, JSON.stringify(message));
// On each server, subscribe to the channel
subscriber.on(‘message’, (channel, message) => {
if (channel === ‘newMessageChannel’) {
// Broadcast message to clients
io.emit(‘newMessage’, JSON.parse(message));
}
});
3.
const crypto = require(‘crypto’);
const secretKey = ‘your-secret-key’;
// Compute HMAC (SHA256) for message integrity
function createHMAC(message) {
return crypto.createHmac(‘sha256’, secretKey)
.update(message)
.digest(‘hex’);
}
1.
const dialogflow = require(‘@google-cloud/dialogflow’);
const projectId = ‘your-project-id’;
const sessionClient = new dialogflow.SessionsClient();
async function detectIntent(sessionId, query) {
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: ‘en’,
},
},
};
const responses = await sessionClient.detectIntent(request);
return responses[0].queryResult.fulfillmentText;
}
Js
const smartReply = require(‘@google-cloud/smartreply’);
const client = new smartReply.SmartReplyClient();
async function getSmartReplies(text) {
const [response] = await client.detectIntent({ text });
return response.replies; // Returns smart reply suggestions
}
2.
const passport = require(‘passport’);
const GoogleStrategy = require(‘passport-google-oauth20’).Strategy;
passport.use(new GoogleStrategy({
clientID: ‘your-google-client-id’,
clientSecret: ‘your-google-client-secret’,
callbackURL: ‘http://localhost:3000/auth/google/callback’,
},
(token, tokenSecret, profile, done) => {
return done(null, profile);
}
));
app.get(‘/auth/google’,
passport.authenticate(‘google’, { scope: [‘profile’, ’email’] }));
app.get(‘/auth/google/callback’,
passport.authenticate(‘google’, { failureRedirect: ‘/’ }),
(req, res) => {
res.redirect(‘/profile’);
});
);
2.js
const speakeasy = require(‘speakeasy’);
// Generate a secret for 2FA
const secret = speakeasy.generateSecret();
// Verify the OTP entered by the user
const isValid = speakeasy.totp.verify({
secret: userSecret,
encoding: ‘base32’,
token: userToken
});
3.
const sodium = require(‘libsodium-wrappers’);
async function encryptMessage(plaintext, publicKey) {
await sodium.ready;
const encryptedMessage = sodium.crypto_box_seal(plaintext, publicKey);
return encryptedMessage;
}
4.
const socket = io();
// Document editing updates
socket.emit(‘documentUpdate’, { userId, content });
socket.on(‘documentUpdate’, (data) => {
updateDocumentContent(data);
});
6.
exports.handler = async (event) => {
const message = event.body.message;
// Process the message (e.g., store in database, send push notification)
return {
statusCode: 200,
body: JSON.stringify({ message: “Message received successfully” }),
};
};
What’s app integrate pH no
1.1
// Firebase initialization
import firebase from “firebase/app”;
import “firebase/auth”;
// Initialize Firebase app
const firebaseConfig = {
apiKey: “YOUR_API_KEY”,
authDomain: “YOUR_AUTH_DOMAIN”,
projectId: “YOUR_PROJECT_ID”,
storageBucket: “YOUR_STORAGE_BUCKET”,
messagingSenderId: “YOUR_MESSAGING_SENDER_ID”,
appId: “YOUR_APP_ID”,
};
// Initialize Firebase
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
} else {
firebase.app(); // if already initialized
}
// Phone number authentication
const phoneNumber = “+1234567890”; // Get the phone number from the input field
const appVerifier = window.recaptchaVerifier; // ReCAPTCHA verifier
firebase.auth()
.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(confirmationResult => {
const verificationCode = window.prompt(“Enter the OTP”);
return confirmationResult.confirm(verificationCode);
})
.then(userCredential => {
console.log(“User is authenticated”, userCredential);
})
.catch(error => {
console.error(“Error during authentication”, error);
});
2.
// Set up the server-side Socket.IO in Node.js
const io = require(“socket.io”)(httpServer); // httpServer is your Express server
io.on(“connection”, (socket) => {
console.log(“User connected: ” + socket.id);
// Handle incoming messages
socket.on(“send_message”, (messageData) => {
const { recipientPhoneNumber, message } = messageData;
// Broadcast the message to the recipient (by their phone number)
socket.broadcast.emit(“receive_message”, { sender: socket.id, message });
});
socket.on(“disconnect”, () => {
console.log(“User disconnected”);
});
});
2.frontend
import io from “socket.io-client”;
import { useState, useEffect } from “react”;
// Connect to the backend socket server
const socket = io(“http://localhost:4000”);
const MessagingApp = () => {
const [message, setMessage] = useState(“”);
const [messages, setMessages] = useState([]);
const [phoneNumber, setPhoneNumber] = useState(“”);
useEffect(() => {
socket.on(“receive_message”, (data) => {
setMessages((prevMessages) => […prevMessages, data]);
});
return () => {
socket.off(“receive_message”);
};
}, []);
const sendMessage = () => {
socket.emit(“send_message”, {
recipientPhoneNumber: phoneNumber,
message: message,
});
setMessages((prevMessages) => […prevMessages, { message }]);
setMessage(“”); // Clear the input field
};
return (
type=”text”
placeholder=”Enter recipient phone number”
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
/>
placeholder=”Type a message”
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
Send Message
{messages.map((msg, index) => (
{msg.message}
))}
);
};
export default MessagingApp;
3.1
npm install twilio
3.2
const twilio = require(“twilio”);
// Twilio credentials
const accountSid = ‘YOUR_ACCOUNT_SID’;
const authToken = ‘YOUR_AUTH_TOKEN’;
const client = new twilio(accountSid, authToken);
// Send an SMS message
client.messages
.create({
body: ‘Hello from your messaging app!’,
from: ‘+1234567890’, // Your Twilio number
to: ‘+1987654321’, // Recipient phone number
})
.then((message) => console.log(message.sid))
.catch((error) => console.error(error));
2.
const axios = require(‘axios’);
const sendWhatsAppMessage = async (to, message) => {
const url = ‘https://graph.facebook.com/v13.0/YOUR_PHONE_NUMBER_ID/messages’;
const token = ‘YOUR_ACCESS_TOKEN’;
const data = {
messaging_product: ‘whatsapp’,
to: to,
text: { body: message },
};
try {
const response = await axios.post(url, data, {
headers: {
‘Authorization’: Bearer ${token},
‘Content-Type’: ‘application/json’,
},
});
console.log(response.data);
} catch (error) {
console.error(error);
}
};
sendWhatsAppMessage(‘+1987654321’, ‘Hello, this is a message via WhatsApp!’);
5.
const mongoose = require(‘mongoose’);
// Message schema
const messageSchema = new mongoose.Schema({
sender: String,
recipient: String,
message: String,
timestamp: { type: Date, default: Date.now },
});
// Model
const Message = mongoose.model(‘Message’, messageSchema);
// Save a message
const saveMessage = async (sender, recipient, message) => {
const new
Search engine
1.1
mkdir search_engine
cd search_engine
2.
python3 -m venv venv
source venv/bin/activate # On Windows use venv\Scripts\activate
3.
pip install flask requests
2.
from flask import Flask, render_template, request
import requests
import json
app = Flask(name)
Set up your API keys and search engines
GOOGLE_API_KEY = ‘your_google_api_key’
GOOGLE_CX = ‘your_custom_search_engine_id’
NEWS_API_KEY = ‘your_news_api_key’
Google Search API function
def google_search(query, search_type=’web’):
url = f”https://www.googleapis.com/customsearch/v1?q={query}&cx={GOOGLE_CX}&key={GOOGLE_API_KEY}”
if search_type == ‘image’:
url += “&searchType=image”
elif search_type == ‘video’:
url += “&searchType=video”
response = requests.get(url)
return response.json()
News API function
def get_news(query):
url = f”https://newsapi.org/v2/everything?q={query}&apiKey={NEWS_API_KEY}”
response = requests.get(url)
return response.json()
@app.route(“/”, methods=[“GET”, “POST”])
def index():
if request.method == “POST”:
query = request.form[‘query’]
category = request.form.get(‘category’)
Handle different categories of search
if category == ‘images’:
results = google_search(query, search_type=’image’)
items = results.get(‘items’, [])
return render_template(‘index.html’, query=query, category=category, items=items)
elif category == ‘news’:
results = get_news(query)
articles = results.get(‘articles’, [])
return render_template(‘index.html’, query=query, category=category, items=articles)
Add other categories (maps, shopping, etc.) similarly
else:
results = google_search(query, search_type=’web’)
items = results.get(‘items’, [])
return render_template(‘index.html’, query=query, category=’web’, items=items)
return render_template(“index.html”, query=None)
if name == “main“:
app.run(debug=True)
3.
Search Engine
Search Engine
Search Query:
Category:
All
Images
News
Videos
Search
{% if items %}
Results for “{{ query }}” in category “{{ category }}”
{% for item in items %}
{{ item.title }}
{% if category == ‘images’ %}
{% elif category == ‘news’ %}
{{ item.description }}
{% endif %}
{% endfor %}
{% elif query %}
No results found.
{% endif %}
4.1
python app.py
Then
def google_search(query, search_type=’web’):
url = f”https://www.googleapis.com/customsearch/v1?q={query}&cx={GOOGLE_CX}&key={GOOGLE_API_KEY}”
if search_type == ‘image’:
url += “&searchType=image”
elif search_type == ‘video’:
url += “&searchType=video”
elif search_type == ‘news’:
url += “&filter=false” # Allow news results in the search
response = requests.get(url)
return response.json()
Then
def get_news(query):
url = f”https://newsapi.org/v2/everything?q={query}&apiKey={NEWS_API_KEY}”
response = requests.get(url)
return response.json()
def get_map_results(query):
maps_api_key = ‘your_google_maps_api_key’
url = f”https://maps.googleapis.com/maps/api/place/textsearch/json?query={query}&key={maps_api_key}”
response = requests.get(url)
return response.json()
def get_youtube_results(query):
youtube_api_key = ‘your_youtube_api_key’
url = f”https://www.googleapis.com/youtube/v3/search?part=snippet&q={query}&key={youtube_api_key}”
response = requests.get(url)
return response.json()
Note: Amazon’s API requires OAuth authentication and is more complex
You can refer to their documentation for setup: https://affiliate-program.amazon.com/
Books API
def get_books(query):
url = f”https://www.googleapis.com/books/v1/volumes?q={query}”
response = requests.get(url)
return response.json()
Backend Flask
Backend Flask
from flask import Flask, render_template, request
import requests
import json
app = Flask(name)
API keys (replace with your keys)
GOOGLE_API_KEY = ‘your_google_api_key’
GOOGLE_CX = ‘your_custom_search_engine_id’
NEWS_API_KEY = ‘your_news_api_key’
YOUTUBE_API_KEY = ‘your_youtube_api_key’
MAPS_API_KEY = ‘your_google_maps_api_key’
Search functions for various categories
def google_search(query, search_type=’web’):
url = f”https://www.googleapis.com/customsearch/v1?q={query}&cx={GOOGLE_CX}&key={GOOGLE_API_KEY}”
if search_type == ‘image’:
url += “&searchType=image”
elif search_type == ‘video’:
url += “&searchType=video”
response = requests.get(url)
return response.json()
def get_news(query):
url = f”https://newsapi.org/v2/everything?q={query}&apiKey={NEWS_API_KEY}”
response = requests.get(url)
return response.json()
def get_map_results(query):
url = f”https://maps.googleapis.com/maps/api/place/textsearch/json?query={query}&key={MAPS_API_KEY}”
response = requests.get(url)
return response.json()
def get_youtube_results(query):
url = f”https://www.googleapis.com/youtube/v3/search?part=snippet&q={query}&key={YOUTUBE_API_KEY}”
response = requests.get(url)
return response.json()
def get_books(query):
url = f”https://www.googleapis.com/books/v1/volumes?q={query}”
response = requests.get(url)
return response.json()
@app.route(“/”, methods=[“GET”, “POST”])
def index():
if request.method == “POST”:
query = request.form[‘query’]
category = request.form.get(‘category’)
if category == ‘images’:
results = google_search(query, search_type=’image’)
items = results.get(‘items’, [])
elif category == ‘news’:
results = get_news(query)
items = results.get(‘articles’, [])
elif category == ‘maps’:
results = get_map_results(query)
items = results.get(‘results’, [])
elif category == ‘videos’:
results = get_youtube_results(query)
items = results.get(‘items’, [])
elif category == ‘books’:
results = get_books(query)
items = results.get(‘items’, [])
else: # Default to web search
results = google_search(query, search_type=’web’)
items = results.get(‘items’, [])
return render_template(‘index.html’, query=query, category=category, items=items)
return render_template(“index.html”, query=None)
if name == “main“:
app.run(debug=True)
2 Frontend
Front end flask
Multi-Category Search Engine
Multi-Category Search Engine
Search Query:
Category:
All
Images
News
Maps
Videos
Books
Search
{% if items %}
Results for “{{ query }}” in category “{{ category }}”
{% for item in items %}
{% if category == ‘images’ %}
{{ item.title }}
{% elif category == ‘news’ %}
{{ item.title }}
{{ item.description }}
{% elif category == ‘maps’ %}
{{ item.name }}
{{ item.formatted_address }}
{% elif category == ‘videos’ %}
{{ item.snippet.title }}
{% elif category == ‘books’ %}
{{ item.volumeInfo.title }}
{{ item.volumeInfo.description }}
{% endif %}
{% endfor %}
{% elif query %}
No results found.
{% endif %}
Errorhandling
def safe_request(url):
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for 4xx/5xx responses
return response.json()
except requests.exceptions.RequestException as e:
print(f”Error with API request: {e}”)
return {}
Search filters
Search Engine with Filters
Search Engine
All
Images
Videos
Shopping
Maps
News
Books
Finance
Travels
Search
function performSearch(event) {
event.preventDefault(); // Prevent form submission
// Get the search query and filter type
const query = document.getElementById(“search-query”).value;
const filterType = document.getElementById(“search-type”).value;
// Construct the search URL based on the selected filter
let searchURL = https://www.google.com/search?q=${encodeURIComponent(query)};
switch (filterType) {
case “images”:
searchURL += “&tbm=isch”; // Image search
break;
case “videos”:
searchURL += “&tbm=vid”; // Video search
break;
case “shopping”:
searchURL += “&tbm=shop”; // Shopping search
break;
case “maps”:
searchURL += “&tbm=map”; // Map search
break;
case “news”:
searchURL += “&tbm=nws”; // News search
break;
case “books”:
searchURL += “&tbm=bks”; // Books search
break;
case “finance”:
searchURL += “&tbm=fin”; // Finance search
break;
case “travels”:
searchURL += “&tbm=travel”; // Travel search
break;
default:
break; // All (no filter applied)
}
// Redirect to the generated search URL
window.location.href = searchURL;
}
Search filters
Search Engine with Filters
Search Engine
Search
All
Images
Videos
Shopping
Maps
News
Books
Finance
Travels
// Show the filter options when the search button is clicked
function showFilters() {
const query = document.getElementById(“search-query”).value;
if (query.trim()) {
document.getElementById(“filters-container”).style.display = ‘block’;
}
}
// Perform search based on selected filter
function performSearch(filterType) {
const query = document.getElementById(“search-query”).value;
let searchURL = https://www.google.com/search?q=${encodeURIComponent(query)};
switch (filterType) {
case “images”:
searchURL += “&tbm=isch”; // Image search
break;
case “videos”:
searchURL += “&tbm=vid”; // Video search
break;
case “shopping”:
searchURL += “&tbm=shop”; // Shopping search
break;
case “maps”:
searchURL += “&tbm=map”; // Map search
break;
case “news”:
searchURL += “&tbm=nws”; // News search
break;
case “books”:
searchURL += “&tbm=bks”; // Books
search
break;
case “finance”:
searchURL += “&tbm=fin”; // Finance search
break;
case “travels”:
searchURL += “&tbm=travel”; // Travel search
break;
default:
break; // All (no filter applied)
}
// Redirect to the generated search URL
window.location.href = searchURL;
}
Search filters
Search Engine with Filters
Search Engine
Search
All
Images
Videos
Shopping
Maps
News
Books
Finance
Travels
// Show the filter options when the search button is clicked
function showFilters() {
const query = document.getElementById(“search-query”).value;
if (query.trim()) {
document.getElementById(“filters-container”).style.display = ‘block’;
}
}
// Perform search based on selected filter
function performSearch(filterType) {
const query = document.getElementById(“search-query”).value;
let searchURL = https://www.google.com/search?q=${encodeURIComponent(query)};
switch (filterType) {
case “images”:
searchURL += “&tbm=isch”; // Image search
break;
case “videos”:
searchURL += “&tbm=vid”; // Video search
break;
case “shopping”:
searchURL += “&tbm=shop”; // Shopping search
break;
case “maps”:
searchURL += “&tbm=map”; // Map search
break;
case “news”:
searchURL += “&tbm=nws”; // News search
break;
case “books”:
searchURL += “&tbm=bks”; // Books search
break;
case “finance”:
searchURL += “&tbm=fin”; // Finance search
break;
case “travels”:
searchURL += “&tbm=travel”; // Travel search
break;
default:
break; // All (no filter applied)
}
// Redirect to the generated search URL
window.location.href = searchURL;
}
Mobile responsive
1.html
Responsive Website
Welcome to My Website
This is a simple responsive layout.
Article 1
This is a sample article with some text.
Article 2
This is another article with some more content.
© 2024 My Website
2.css
Responsive Website
Welcome to My Website
This is a simple responsive layout.
Article 1
This is a sample article with some text.
Article 2
This is another article with some more content.
© 2024 My Website
/* Reset some basic styles for better cross-browser consistency */
{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
/* Make sure the website is responsive / meta[name=”viewport”] { width: device-width, initial-scale: 1.0; } / General Layout / header { background-color: #333; color: white; padding: 1rem; } header nav ul { list-style: none; text-align: center; } header nav ul li { display: inline; margin: 0 10px; } header nav ul li a { color: white; text-decoration: none; font-weight: bold; } .hero { background-color: #f4f4f4; padding: 50px 0; text-align: center; } .hero h1 { font-size: 3rem; } .content { display: flex; flex-wrap: wrap; justify-content: space-around; padding: 20px; } article { flex: 1 1 300px; margin: 20px; background: #f9f9f9; padding: 20px; border: 1px solid #ddd; border-radius: 8px; } footer { background-color: #333; color: white; text-align: center; padding: 10px; } / Media Queries for Responsiveness / @media screen and (max-width: 768px) { .hero h1 { font-size: 2rem; } .content { flex-direction: column; align-items: center; } header nav ul { text-align: left; padding-left: 20px; } header nav ul li { display: block; margin: 5px 0; } } @media screen and (max-width: 480px) { .hero h1 { font-size: 1.5rem; } .content article { margin: 10px; padding: 15px; } } Key 1. 2. .content { display: flex; flex-wrap: wrap; justify-content: space-around; } 3. @media screen and (max-width: 768px) { / Adjustments for tablet devices / } @media screen and (max-width: 480px) { / Adjustments for mobile devices */
}
4.
.hero h1 {
font-size: 3rem;
}
@media screen and (max-width: 768px) {
.hero h1 {
font-size: 2rem;
}
}
@media screen and (max-width: 480px) {
.hero h1 {
font-size: 1.5rem;
}
}
Register and login
1.
CREATE DATABASE user_system;
USE user_system;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2.
Sign up.html
Sign Up
Sign Up
Sign Up
Login.html
Login
Login
Login
3.
Style.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.form-container {
width: 300px;
margin: 100px auto;
padding: 20px;
background-color: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
form input {
width: 100%;
padding: 10px;
margin: 10px 0;
box-sizing: border-box;
}
form button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
form button:hover {
background-color: #45a049;
}
3.PHP
db.php
$servername = “localhost”;
$username = “root”; // your MySQL username
$password = “”; // your MySQL password
$dbname = “user_system”; // your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
?>
Signup.php
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$username = $_POST[‘username’];
$email = $_POST[’email’];
$password = $_POST[‘password’];
$confirm_password = $_POST[‘confirm_password’];
// Password validation
if ($password !== $confirm_password) {
die(“Passwords do not match.”);
}
// Hash the password for security
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
// Insert user into database
$sql = “INSERT INTO users (username, password, email) VALUES (‘$username’, ‘$hashed_password’, ‘$email’)”;
if ($conn->query($sql) === TRUE) {
echo “New record created successfully. Login here”;
} else {
echo “Error: ” . $sql . “
” . $conn->error;
}
}
?>
Login.php
session_start();
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$username = $_POST[‘username’];
$password = $_POST[‘password’];
// Query the database for the user
$sql = “SELECT * FROM users WHERE username = ‘$username’ LIMIT 1”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
// Verify the password
if (password_verify($password, $row[‘password’])) {
// Start a session for the user
$_SESSION[‘user_id’] = $row[‘id’];
$_SESSION[‘username’] = $row[‘username’];
header(‘Location: dashboard.php’); // Redirect to a dashboard or user area
} else {
echo “Invalid username or password.”;
}
} else {
echo “Invalid username or password.”;
}
}
?>
Dashboard.php
session_start();
if (!isset($_SESSION[‘user_id’])) {
header(‘Location: login.html’); // Redirect if the user is not logged in
exit();
}
echo “Welcome, ” . $_SESSION[‘username’] . “!”;
?>
3.
Style.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.form-container {
width: 300px;
margin: 100px auto;
padding: 20px;
background-color: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
form input {
width: 100%;
padding: 10px;
margin: 10px 0;
box-sizing: border-box;
}
form button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
form button:hover {
background-color: #45a049;
}
3.PHP
db.php
$servername = “localhost”;
$username = “root”; // your MySQL username
$password = “”; // your MySQL password
$dbname = “user_system”; // your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
?>
Signup.php
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$username = $_POST[‘username’];
$email = $_POST[’email’];
$password = $_POST[‘password’];
$confirm_password = $_POST[‘confirm_password’];
// Password validation
if ($password !== $confirm_password) {
die(“Passwords do not match.”);
}
// Hash the password for security
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
// Insert user into database
$sql = “INSERT INTO users (username, password, email) VALUES (‘$username’, ‘$hashed_password’, ‘$email’)”;
if ($conn->query($sql) === TRUE) {
echo “New record created successfully. Login here”;
} else {
echo “Error: ” . $sql . “
” . $conn->error;
}
}
?>
Login.php
session_start();
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$username = $_POST[‘username’];
$password = $_POST[‘password’];
// Query the database for the user
$sql = “SELECT * FROM users WHERE username = ‘$username’ LIMIT 1”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
// Verify the password
if (password_verify($password, $row[‘password’])) {
// Start a session for the user
$_SESSION[‘user_id’] = $row[‘id’];
$_SESSION[‘username’] = $row[‘username’];
header(‘Location: dashboard.php’); // Redirect to a dashboard or user area
} else {
echo “Invalid username or password.”;
}
} else {
echo “Invalid username or password.”;
}
}
?>
Dashboard.php
session_start();
if (!isset($_SESSION[‘user_id’])) {
header(‘Location: login.html’); // Redirect if the user is not logged in
exit();
}
echo “Welcome, ” . $_SESSION[‘username’] . “!”;
?>
Phone no
1.
CREATE DATABASE user_system;
USE user_system;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
phone_number VARCHAR(15) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2.
Sign up
Sign Up
Sign Up
Sign Up
login.html
Login
Login
Login
style.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.form-container {
width: 300px;
margin: 100px auto;
padding: 20px;
background-color: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
Form input {
width: 100%;
padding: 10px;
margin: 10px 0;
box-sizing: border-box;
}
form button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
form button:hover {
background-color: #45a049;
}
3.PHP
db.php
$servername = “localhost”;
$username = “root”; // your MySQL username
$password = “”; // your MySQL password
$dbname = “user_system”; // your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
?>
Signup.php
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$username = $_POST[‘username’];
$email = $_POST[’email’];
$password = $_POST[‘password’];
$confirm_password = $_POST[‘confirm_password’];
// Password validation
if ($password !== $confirm_password) {
die(“Passwords do not match.”);
}
// Hash the password for security
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
// Insert user into database
$sql = “INSERT INTO users (username, password, email) VALUES (‘$username’, ‘$hashed_password’, ‘$email’)”;
if ($conn->query($sql) === TRUE) {
echo “New record created successfully. Login here”;
} else {
echo “Error: ” . $sql . “
” . $conn->error;
}
}
?>
Login.php
session_start();
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$username = $_POST[‘username’];
$password = $_POST[‘password’];
// Query the database for the user
$sql = “SELECT * FROM users WHERE username = ‘$username’ LIMIT 1”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
// Verify the password
if (password_verify($password, $row[‘password’])) {
// Start a session for the user
$_SESSION[‘user_id’] = $row[‘id’];
$_SESSION[‘username’] = $row[‘username’];
header(‘Location: dashboard.php’); // Redirect to a dashboard or user area
} else {
echo “Invalid username or password.”;
}
} else {
echo “Invalid username or password.”;
}
}
?>
Dashboard.php
session_start();
if (!isset($_SESSION[‘user_id’])) {
header(‘Location: login.html’); // Redirect if the user is not logged in
exit();
}
echo “Welcome, ” . $_SESSION[‘username’] . “!”;
?>
Phone no
1.
CREATE DATABASE user_system;
USE user_system;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
phone_number VARCHAR(15) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2.
Sign up
Sign Up
Sign Up
Sign Up
login.html
Login
Login
Login
style.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.form-container {
width: 300px;
margin: 100px auto;
padding: 20px;
background-color: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
form input {
width: 100%;
padding: 10px;
margin: 10px 0;
box-sizing: border-box;
}
form button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
form button:hover {
background-color: #45a049;
}
3.
db.php
$servername = “localhost”;
$username = “root”; // your MySQL username
$password = “”; // your MySQL password
$dbname = “user_system”; // your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
?>
signup.php
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$phone_number = $_POST[‘phone_number’];
$password = $_POST[‘password’];
$confirm_password = $_POST[‘confirm_password’];
// Validate password match
if ($password !== $confirm_password) {
die(“Passwords do not match.”);
}
// Check if phone number is already registered
$sql = “SELECT * FROM users WHERE phone_number = ‘$phone_number'”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
die(“This phone number is already registered.”);
}
// Hash the password for security
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
// Insert new user into the database
$sql = “INSERT INTO users (phone_number, password) VALUES (‘$phone_number’, ‘$hashed_password’)”;
if ($conn->query($sql) === TRUE) {
echo “New account created successfully. Login here”;
} else {
echo “Error: ” . $sql . “
” . $conn->error;
}
}
?>
login.php
session_start();
include(‘db.php’);
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$phone_number = $_POST[‘phone_number’];
$password = $_POST[‘password’];
// Query the database for the user
$sql = “SELECT * FROM users WHERE phone_number = ‘$phone_number’ LIMIT 1”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
// Verify the password
if (password_verify($password, $row[‘password’])) {
// Start a session for the user
$_SESSION[‘user_id’] = $row[‘id’];
$_SESSION[‘phone_number’] = $row[‘phone_number’];
header(‘Location: dashboard.php’); // Redirect to a dashboard or user area
} else {
echo “Invalid phone number or password.”;
}
} else {
echo “Invalid phone number or password.”;
}
}
?>
4.Dashboard.php
session_start();
if (!isset($_SESSION[‘user_id’])) {
header(‘Location: login.html’); // Redirect if the user is not logged in
exit();
}
echo “Welcome, ” . $_SESSION[‘phone_number’] . “!”;
?>
1.
Login
function handleLogin(event) {
event.preventDefault();
// Dummy login check
const username = document.getElementById(‘username’).value;
const password = document.getElementById(‘password’).value;
if (username === ‘user’ && password === ‘pass’) {
// Redirect to homepage after successful login
window.location.href = ‘index.html’; // or homepage URL
} else {
alert(‘Invalid credentials’);
}
}
2.
const express = require(‘express’);
const session = require(‘express-session’);
const app = express();
// Middlewares
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: ‘your-secret-key’,
resave: false,
saveUninitialized: true
}));
// Login Route
// Login Route
app.post(‘/login’, (req, res) => {
const { username, password } = req.body;
// Dummy login check
if (username === ‘user’ && password === ‘pass’) {
req.session.user = username; // Save user in session
res.redirect(‘/’); // Redirect to homepage (index)
} else {
res.send(‘Invalid credentials’);
}
});
// Homepage Route (Redirects to index page if logged in)
app.get(‘/’, (req, res) => {
if (req.session.user) {
res.send(‘Welcome to the homepage!’);
} else {
res.redirect(‘/login’);
}
});
// Login Page (Simple form)
app.get(‘/login’, (req, res) => {
res.send( Login
);
});
app.listen(3000, () => {
console.log(‘Server running on http://localhost:3000’);
});
3.
from flask import Flask, render_template, redirect, request, session
app = Flask(name)
app.secret_key = ‘your-secret-key’
@app.route(‘/’)
def home():
if ‘user’ in session:
return “Welcome to the homepage!”
return redirect(‘/login’)
@app.route(‘/login’, methods=[‘GET’, ‘POST’])
def login():
if request.method == ‘POST’:
username = request.form[‘username’]
password = request.form[‘password’]
Dummy login check
if username == ‘user’ and password == ‘pass’:
session[‘user’] = username
return redirect(‘/’) # Redirect to homepage after login
return ‘Invalid credentials’
return ”’
Login
”’
if name == ‘main‘:
app.run(debug=True)
4.
import { useState } from ‘react’;
import { useNavigate } from ‘react-router-dom’;
function LoginForm() {
const [username, setUsername] = useState(”);
const [password, setPassword] = useState(”);
const navigate = useNavigate();
const handleLogin = async (event) => {
event.preventDefault();
// Dummy login logic
if (username === ‘user’ && password === ‘pass’) {
// Redirect to homepage after login
navigate(‘/home’); // This can be the path to your homepage
} else {
alert(‘Invalid credentials’);
}
};
return (
type=”text”
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder=”Username”
required
/>
type=”password”
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder=”Password”
required
/>
Login
);
}
export default LoginForm;
Routing config
import { BrowserRouter as Router, Route, Routes } from ‘react-router-dom’;
import LoginForm from ‘./LoginForm’;
import HomePage from ‘./HomePage’;
function App() {
return (
} />
} />
);
}
export default App;
Php
session_start();
// Check login
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$username = $_POST[‘username’];
$password = $_POST[‘password’];
// Dummy login check
if ($username == ‘user’ && $password == ‘pass’) {
$_SESSION[‘user’] = $username;
header(‘Location: index.php’); // Redirect to homepage
exit;
} else {
echo ‘Invalid credentials’;
}
}
?>
Login
6.
Login
export default {
data() {
return {
username: ”,
password: ”
};
},
methods: {
handleLogin() {
// Dummy login check
if (this.username === ‘user’ && this.password === ‘pass’) {
// Store user info (could use Vuex or localStorage)
localStorage.setItem(‘user’, this.username);
// Redirect to homepage
this.$router.push({ name: ‘Home’ });
} else {
alert(‘Invalid credentials’);
}
}
}
};
2.VRC
import { createRouter, createWebHistory } from ‘vue-router’;
import HomePage from ‘./components/HomePage.vue’;
import LoginPage from ‘./components/LoginPage.vue’;
const routes = [
{ path: ‘/’, name: ‘Home’, component: HomePage },
{ path: ‘/login’, name: ‘Login’, component: LoginPage }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
Homepage compo
Welcome to the Homepage!
You are logged in!
7.Angular
import { Component } from ‘@angular/core’;
import { Router } from ‘@angular/router’;
import { FormBuilder, FormGroup, Validators } from ‘@angular/forms’;
@Component({
selector: ‘app-login’,
templateUrl: ‘./login.component.html’
})
export class LoginComponent {
loginForm: FormGroup;
constructor(private fb: FormBuilder, private router: Router) {
this.loginForm = this.fb.group({
username: [”, Validators.required],
password: [”, Validators.required]
});
}
onSubmit() {
const { username, password } = this.loginForm.value;
// Dummy login check
if (username === ‘user’ && password === ‘pass’) {
localStorage.setItem(‘user’, username);
this.router.navigate([‘/home’]); // Redirect to homepage
} else {
alert(‘Invalid credentials’);
}
}
}
LCH
Login
ARC
import { NgModule } from ‘@angular/core’;
import { RouterModule, Routes } from ‘@angular/router’;
import { HomeComponent } from ‘./home/home.component’;
import { LoginComponent } from ‘./login/login.component’;
const routes: Routes = [
{ path: ”, component: HomeComponent },
{ path: ‘login’, component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
8.
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
def login_view(request):
if request.method == ‘POST’:
username = request.POST[‘username’]
password = request.POST[‘password’]
Authenticate the user
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect(‘home’) # Redirect to homepage after successful login
else:
return render(request, ‘login.html’, {‘error’: ‘Invalid credentials’})
return render(request, ‘login.html’)
DVH
from django.shortcuts import render
def home_view(request):
if request.user.is_authenticated:
return render(request, ‘home.html’)
else:
return redirect(‘login’) # Redirect to login if not authenticated
URL
from django.urls import path
from . import views
urlpatterns = [
path(‘login/’, views.login_view, name=’login’),
path(‘home/’, views.home_view, name=’home’),
]
Django
{% csrf_token %}
Login
9.
9.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task Login(string username, string password)
{
// Dummy login check
if (username == “user” && password == “pass”)
{
var claims = new List
{
new Claim(ClaimTypes.Name, username)
};
var identity = new ClaimsIdentity(claims, “login”);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);
return RedirectToAction(“Home”, “Home”);
}
ViewBag.ErrorMessage = “Invalid credentials!”;
return View();
}
}
HC
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task Login(string username, string password)
{
// Dummy login check
if (username == “user” && password == “pass”)
{
var claims = new List
{
new Claim(ClaimTypes.Name, username)
};
var identity = new ClaimsIdentity(claims, “login”);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);
return RedirectToAction(“Home”, “Home”);
}
ViewBag.ErrorMessage = “Invalid credentials!”;
return View();
}
}
LV
Login
@if(ViewBag.ErrorMessage != null)
{
@ViewBag.ErrorMessage
}
HV
Welcome to the Homepage!
You are logged in!
10.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class LoginController {
@GetMapping(“/login”)
public String loginPage() {
return “login”; // Return login view
}
@PostMapping(“/login”)
public String login(String username, String password) {
if (“user”.equals(username) && “pass”.equals(password)) {
return “redirect:/home”; // Redirect to homepage after successful login
}
return “login”; // Return to login page if invalid credentials
}
@GetMapping(“/home”)
public String homePage() {
return “home”; // Return homepage view
}
}
LV
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(“/login”, “/”).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(“/login”)
.defaultSuccessUrl(“/home”, true)
.permitAll();
}
}
LV
Login
HV
Welcome to the Homepage!
You are logged in!
10.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class LoginController {
@GetMapping(“/login”)
public String loginPage() {
return “login”; // Return login view
}
@PostMapping(“/login”)
public String login(String username, String password) {
if (“user”.equals(username) && “pass”.equals(password)) {
return “redirect:/home”; // Redirect to homepage after successful login
}
return “login”; // Return to login page if invalid credentials
}
@GetMapping(“/home”)
public String homePage() {
return “home”; // Return homepage view
}
}
LV
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(“/login”, “/”).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(“/login”)
.defaultSuccessUrl(“/home”, true)
.permitAll();
}
}
LV
Login
HV
Welcome to the Homepage!
You are logged in!
Google voice search
1.
🎙
2.
// Check if the browser supports Web Speech API
const voiceSearchBtn = document.getElementById(‘voice-search-btn’);
const searchBox = document.getElementById(‘search-box’);
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = ‘en-US’; // Set language for recognition
// Event listener to start voice recognition on button click
voiceSearchBtn.addEventListener(‘click’, () => {
recognition.start(); // Start listening for voice input
});
// When speech is detected, put the text into the search box
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
searchBox.value = transcript; // Set the text in search box
};
// Handle errors during speech recognition
recognition.onerror = (event) => {
console.error(‘Speech recognition error:’, event.error);
};
3.
// Optional: Trigger the search when Enter key is pressed
searchBox.addEventListener(‘keypress’, (event) => {
if (event.key === ‘Enter’) {
performSearch(searchBox.value);
}
});
// Function to perform the search
function performSearch(query) {
// Here you would trigger your search logic (e.g., redirect to search results page)
console.log(‘Searching for:’, query);
// Example: window.location.href = /search?q=${query};
}
4.
.search-container {
position: relative;
display: flex;
align-items: center;
}
search-box {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc
border-radius: 4px;
}
voice-search-btn {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
margin-left: 10px;
}
More 1.
🎙
Listening…
Update:
const microphoneStatus = document.getElementById(‘microphone-status’);
// Start voice recognition with feedback
voiceSearchBtn.addEventListener(‘click’, () => {
recognition.start(); // Start listening for voice input
microphoneStatus.style.display = ‘inline’; // Show “Listening…” status
voiceSearchBtn.disabled = true; // Optionally disable the button during recognition
});
// When recognition is finished, hide “Listening…” status
recognition.onend = () => {
microphoneStatus.style.display = ‘none’; // Hide listening status
voiceSearchBtn.disabled = false; // Enable the button again
};
// Handle results
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
searchBox.value = transcript; // Set the text in the search box
performSearch(transcript); // Optionally perform search immediately
};
2.
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
searchBox.value = transcript; // Set the text in search box
performSearch(transcript); // Automatically trigger the search
};
3.
recognition.onerror = (event) => {
console.error(‘Speech recognition error:’, event.error);
alert(“Sorry, there was an issue with voice recognition. Please try again.”);
microphoneStatus.style.display = ‘none’;
voiceSearchBtn.disabled = false;
};
recognition.onnomatch = () => {
alert(“Sorry, I couldn’t understand that. Please try again.”);
microphoneStatus.style.display = ‘none’;
voiceSearchBtn.disabled = false;
};
4.
English (US)
Spanish (Spain)
French (France)
German
Then,
const languageSelector = document.getElementById(‘language-selector’);
// Update language when user selects a different language
languageSelector.addEventListener(‘change’, (event) => {
recognition.lang = event.target.value;
console.log(‘Language changed to:’, event.target.value);
});
5.
function speak(message) {
const speech = new SpeechSynthesisUtterance(message);
window.speechSynthesis.speak(speech);
}
// Use this function to provide verbal feedback
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
searchBox.value = transcript;
performSearch(transcript);
speak(‘Searching for ‘ + transcript); // Let the user know that search is in progress
};
6.6.
if (!(‘SpeechRecognition’ in window || ‘webkitSpeechRecognition’ in window)) {
alert(“Sorry, your browser does not support voice recognition.”);
voiceSearchBtn.style.display = ‘none’; // Hide voice search button if not supported
} else {
// Initialize recognition only if supported
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
// The rest of your voice recognition logic
}
Example
Voice Search Example
🎙
Listening…
English (US)
Spanish (Spain)
French (France)
German
if (!(‘SpeechRecognition’ in window || ‘webkitSpeechRecognition’ in window)) {
alert(“Sorry, your browser does not support voice recognition.”);
document.getElementById(‘voice-search-btn’).style.display = ‘none’;
} else {
const voiceSearchBtn = document.getElementById(‘voice-search-btn’);
const searchBox = document.getElementById(‘search-box’);
const microphoneStatus = document.getElementById(‘microphone-status’);
const languageSelector = document.getElementById(‘language-selector’);
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = ‘en-US’; // Default language
// Handle language change
languageSelector.addEventListener(‘change’, (event) => {
recognition.lang = event.target.value;
});
// Start recognition when button is clicked
voiceSearchBtn.addEventListener(‘click’, () => {
recognition.start();
microphoneStatus.style.display = ‘inline’;
voiceSearchBtn.disabled = true;
});
recognition.onend = () => {
microphoneStatus.style.display = ‘none’;
voiceSearchBtn.disabled = false;
};
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
searchBox.value = transcript;
performSearch(transcript);
speak(‘Searching for ‘ + transcript);
};
recognition.onerror = (event) => {
console.error(‘Error occurred during recognition:’, event.error);
alert(“Sorry, there was an issue with voice recognition. Please try again.”);
};
function performSearch(query) {
console.log(‘Searching for:’, query);
// Here you can trigger a search action or redirect to a results page
}
function speak(message) {
const speech = new SpeechSynthesisUtterance(message);
window.speechSynthesis.speak(speech);
}
}
Youtube code
YouTube Clone
YouClone Upload
- Home
Trending
Subscriptions
Library
History
Recommended
Video Title
Channel Name
100K views · 2 days ago
News homepage design
nav a {
color: white;
text-decoration: none;
}
.container {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 1rem;
padding: 1rem;
}
.post {
background: white;
padding: 1rem;
border-radius: 8px;
box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
.media {
margin-top: 0.5rem;
}
.media img, .media video, .media audio {
width: 100%;
border-radius: 8px;
}
aside {
background: white;
padding: 1rem;
border-radius: 8px;
box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
GlobalNewsShare
HomeTrendingCategoriesUploadProfile
Breaking: Local Election Results
Today, the city concluded its local elections with a record voter turnout. Citizens have chosen…
Tech Update: AI in 2025
The latest developments in artificial intelligence have opened new doors in medicine, education, and finance…

Recommended News
Index.html
NewsShare – Home
NewsShare
Breaking News: Global Summit 2025
By Jane Doe | May 7, 2025

The Global Summit brings together leaders to discuss the future of AI and sustainability…
New Tech Unveiled in Berlin
By TechDaily | May 6, 2025

Today, leading tech firms showcased their latest innovations in Berlin…
© 2025 NewsShare. All rights reserved.
Css
body {
font-family: Arial, sans-serif;
margin: 0;
background-color: #f4f4f4;
}
header {
background-color: #333;
color: white;
padding: 1em;
}
header h1 {
display: inline-block;
margin: 0;
}
nav {
float: right;
}
nav a {
color: white;
margin-left: 20px;
text-decoration: none;
}
.content {
padding: 20px;
}
.news-post {
background: white;
margin-bottom: 20px;
padding: 20px;
border-radius: 5px;
}
.media-img, .media-video, .media-audio {
max-width: 100%;
margin-top: 10px;
}
footer {
background-color: #333;
color: white;
text-align: center;
padding: 1em;
margin-top: 20px;
}
Youtube homepage
YouTube Clone
YouTube Search
UploadNotificationsProfile
- Home
- Trending
- Subscriptions
- Library
Video Title
Channel Name
1M views • 1 day ago
Css
- {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, sans-serif;
}
body {
display: flex;
flex-direction: column;
}
header {
height: 60px;
background-color: #fff;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
border-bottom: 1px solid #ddd;
}
.logo {
font-size: 24px;
font-weight: bold;
color: red;
}
.search-bar input {
padding: 6px;
width: 300px;
}
.search-bar button {
padding: 6px 10px;
}
.user-actions span {
margin-left: 15px;
cursor: pointer;
}
aside {
width: 200px;
background-color: #f9f9f9;
padding-top: 20px;
height: calc(100vh – 60px);
position: fixed;
top: 60px;
left: 0;
border-right: 1px solid #ddd;
}
aside ul {
list-style: none;
}
aside li {
padding: 10px 20px;
cursor: pointer;
}
main {
margin-left: 200px;
padding: 20px;
background-color: #f1f1f1;
min-height: calc(100vh – 60px);
}
.videos {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.video {
background-color: #fff;
border-radius: 5px;
width: 300px;
overflow: hidden;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.video img {
width: 100%;
height: auto;
}
.video-info {
padding: 10px;
}
News sharing platform
Spaceview – News Platform
Spaceview
Breaking News: Major Update in Global Markets
Text Article
This is a sample news article with plain text content explaining the latest trends.
Image News
Captured moment from the recent event held in Berlin.
Video Report
Exclusive footage from the ground report in California.
Audio Broadcast
Listen to the daily morning briefing by our reporters. © 2025 Spaceview News | All rights reserved
News sharing platform
Spaceview – News Platform
SpaceviewHomeCategoriesUploadAboutLogin
Featured Story: Global Climate Update
Watch our exclusive report from the frontlines of change.
Text Post
Today’s article highlights the economic shifts in Europe.
Image Post
Scene from the protest in Berlin this afternoon.
Video Report
Exclusive footage from the wildfire zones.
Audio Briefing
Listen to the top headlines for today.
© 2025 Spaceview News | All rights reserved
Css
body {
margin: 0;
font-family: sans-serif;
background: #f2f2f2;
}
header {
background: #1a1a1a;
color: white;
display: flex;
justify-content: space-between;
padding: 1rem 2rem;
align-items: center;
}
header .logo {
font-size: 1.5rem;
font-weight: bold;
}
header nav a {
color: white;
margin-left: 1rem;
text-decoration: none;
}
.hero {
background: #333 url(‘https://via.placeholder.com/1200×400’) center/cover no-repeat;
color: white;
text-align: center;
padding: 4rem 2rem;
text-shadow: 1px 1px 4px #000;
}
.feed {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
padding: 2rem;
}
.card {
background: white;
padding: 1rem;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.05);
}
.card img,
.card video,
.card audio {
width: 100%;
margin-bottom: 0.5rem;
border-radius: 4px;
}
footer {
background: #1a1a1a;
color: white;
text-align: center;
padding: 1rem;
}
First 15 Transactions of our company in Machapucchre Bank Nepal, Our Company Bank account in Machapuchhre Bank , You can deposit in this account from anywhere in Nepal through laptop mobile or visiting your nearest Machapuchhre Bank.
My License, Passport, , Citizenship, USA VISA Photo, USA FULL SCHOLARSHIP I-20
My High School Certificate: XAVIER ACADEMY, LAZIMPAT

My Bachelor Degree Certificate in Himalayan College Of Engineering, Kathmandu, Nepal.




News Sharing Site, TheSpaceView Designs, Youtube Designs, Rough and Final designs and all completed rough work is listed below:

YOUTUBE DESIGN OF PAGES
THESPACEVIEW LOGO FINAL
TheSpaceView Project Details













SPACEVIEW PROJECT DETAILS WITH FUNDING REQUIREMENT, EXPENSES AND DETAILS














Details Of Alibaba Project In Nepal



Sample Photo Of Site Registration For Godaddy
CHINA,USA,FRANCE,UNITEDKINGDOM,AUSTRALIA,JAPAN,CANADA,GERMANY,INDIA-Site Registration Charges from www.godaddy.com-USA Company

RAJKUMARBHAUMIK+MOUMITAMANNABHAUMIK+MARRIAGE+CERTIFICATE
ALL PAYMENT METHODS FROM WORLDWIDE(Esp:Nepal, India, UAE,China,India, USA,UK,Germany, Canada) TO SURYAIMPORT COMPANY

1.PAYONEER TO PAYONEER FROM ANY COUNTRY Esp:Nepal, India, UAE,China,India, USA,UK,Germany, Canada [WILL BE DEPOSITED TO INDIAN LOCAL BANK AND NEPAL LOCAL BANK AS WELL IE:FIRST IT WILL BE DEPOSITED IN US BANK THEN NEPAL LOCAL BANK AND INDIAN LOCAL BANK]
US Bank Account
Beneficiary name: RAJ BHAUMIK
Bank name: First Century Bank
Bank Address: 1731 N Elm St Commerce Ga 30529 USA
Routing (ABA): 061120084
Account No: 4012873877478
Account Type: CHECKING

3.PAYPAL
4.SBI NEPAL to SBI INDIA BANK REMITTANCE
Payment through RTGS SBI
India Bank Account Details
- A/c Name: Rajkumar Bhunia
- IFSC code: SBIN0002020
- AC no: 43625613656
- Bank name: State Bank of India (SBI Bank)
- Swift Code: SBININBB839
5.WIRE Transfer to INDIA Bank UPI
6.SBI UPI ID:7478089895@sbi Other UPI No:9635822964@axl
7.For Razorpay Payments ID:
8.PAN No:GEYPB3893C Esewa Id:9860256292 and 9851000209
YOU CAN USE ANY OF SCANNER FOR PAYMENT METHODS: PHONE PE Scanner, SBI Bank Scanner, Allahabad Bank Scanner, UPI QR, PayTm UPI, GooglePay






MY PRAY TO GODDESS MANAKAMANA. KRISHNA , SARASWOTI MAA!

SOME OF RECENT TRANSACTIONS IN OUR COMPANY FROM NEPAL AND WORLDWIDE:PHOTOS AND PROOF OF TRANSACTIONS

































The Temple or God I,CEO, Suryaimport, Alibaba in Nepal and TheSpaceview ,Mr.Raj Kumar Bhaumik, worship or call whenever I need god help or in confusion or trouble: Mata Manakamana

My Dad and Mom in Baharampur, Kolkata Puja!

My wife:Moumita(right side), her sister: Moupiya(between) and her neighbour and sister of Moupiya: Sorry dont know her name!

People who are close and special to me and help me for my success, to be owner of this company and organization.
1.My Talented and Beautiful Wife: Ms.Moumita Manna Bhaumik [Simply: Queen and Miss Universe] (Company Owner, Founder and Chairman of Suryaimport Company , Alibaba In Nepal Project As well As TheSpaceView Company and All Suryaimport Stores Around UAE, UK,Canada ,USA ,Germany)

2.Mr.Sulav Kumar Shrestha [ Half (50%) Owner Of Suryaimport Online Store in Nepal ]

3.Mr.Binod Krishna Shrestha

4.Mr.Moti Krishna Shrestha
5.Mr.Sundar Lal Shrestha
6.Ms.Reenu Shrestha
7.Mr.Niranjan Bhaumik
8.Mr.Krishna Ghimire
9.Mr.Centos Rijal
10.Ms.Suraksha Neupane
11.Mr.Rajan Poudel
12.Mr.Arpan Dahal
13.Mr.Shekhar Acharya
14.Mr.Suray Sir (Siddhartha Shishu Niketan)
15.Ms.Urisha Joshi and all family members
16.Ms.Pranisha Shrestha and all family members
17.Mr.Sudin Shrestha
18.Mr.Narayan Gopal Risal and family
19.Mr.Sambhu Bista
20.Mr.Rimesh Bahadur Rajbhandari
21.Ms.Prarthana Koirala
22.Mr.Roshan Shrestha and Mr.Bishal Shrestha