Grounded için Yard Haritası Checklist

Eksiksiz Yard Harita Rehberi - İlgi Alanları %100 Kontrol Listesi

Wand Ekibi Tarafından

Keşif İlerlemesi

0 / 121

İlerlemenizi takip etmek için lütfen giriş yapın

Ana Örümceğin İni

Ana Örümceğin İni

Araba Aküsü

Araba Aküsü

Görsel Yok

Araba Aküsü

Araba Aküsü

Araba Aküsü

Görsel Yok

Araba Lastiği

Araç Kutusu

Araç Kutusu

Araştırmacı Karakolu

Araştırmacı Karakolu

Araştırmacı Tarayıcı

Araştırmacı Tarayıcı

Bahçe Işığı

Bahçe Işığı

Bahçe Işığı

Bahçe Işığı

Bahçe Makası

Bahçe Makası

Baraka Altı Çalışma Işığı

Baraka Altı Çalışma Işığı

Barbekü Sızıntısı

Barbekü Sızıntısı

Beyzbol

Beyzbol

Billy Hogs Sosisli

Billy Hogs Sosisli

Görsel Yok

Boya Kutusu

Görsel Yok

Çatlak Cam

Görsel Yok

Çatlak Cam

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çatlak Kaya

Görsel Yok

Çit Laboratuvarı İhlal Kapısı Terminali

Çit Laboratuvarı Karakolu

Çit Laboratuvarı Karakolu

Çit Laboratuvarı Karakolu

Çit Laboratuvarı Karakolu

Görsel Yok

Çit Laboratuvarı Malzeme Depolama Odası

Çukur Saksı Gölet Kapağı

Çukur Saksı Gölet Kapağı

Düşmüş Meşe Dalı

Düşmüş Meşe Dalı

Gölet Laboratuvarı Biyodom Terminali

Gölet Laboratuvarı Biyodom Terminali

Gölet Laboratuvarı Karakol Kapısı

Gölet Laboratuvarı Karakol Kapısı

Gölet Laboratuvarı Karakolu

Gölet Laboratuvarı Karakolu

Gölet Laboratuvarı Karakolu

Gölet Laboratuvarı Karakolu

Görsel Yok

Gölet Laboratuvarı Malzeme Depolama Odası

Gölet Laboratuvarı Sistemleri Terminali

Gölet Laboratuvarı Sistemleri Terminali

Görsel Yok

Güç Kutusu

Güç Prizı

Güç Prizı

Gül Çalıları

Gül Çalıları

Hamster Mezarı

Hamster Mezarı

Görsel Yok

Hasarlı Kapı

Görsel Yok

Havuz Laboratuvarı Güç Şebekesi Kontrolü

Görsel Yok

Havuz Süzgeci

Görsel Yok

Haze Lab Kanalizasyon Borusu Girişi

HDPE Kapsülü

HDPE Kapsülü

Görsel Yok

İlgi Alanları

Kara Karınca Yuva Laboratuvarı Ekip Konuşlandırma Terminali

Kara Karınca Yuva Laboratuvarı Ekip Konuşlandırma Terminali

Kaset Bandı

Kaset Bandı

Görsel Yok

Kömür Torbası

Kumkale

Kumkale

Kurt Örümceği İni Girişi

Kurt Örümceği İni Girişi

Kütük Laboratuvarı Karakolu Girişi

Kütük Laboratuvarı Karakolu Girişi

Mala

Mala

Mala Geçidi

Mala Geçidi

Mavi Branda

Mavi Branda

Merdiven

Merdiven

Meşe Ağacı

Meşe Ağacı

Meşe Laboratuvarı İhlali

Meşe Laboratuvarı İhlali

Minik İnsan İskeleti

Minik İnsan İskeleti

Minik İnsan İskeleti

Minik İnsan İskeleti

Görsel Yok

Minik İnsan İskeleti

Minik İnsan İskeleti

Minik İnsan İskeleti

Görsel Yok

Minik İnsan İskeleti

Minik İnsan İskeleti

Minik İnsan İskeleti

Minik İnsan İskeleti

Minik İnsan İskeleti

Görsel Yok

Minik İnsan İskeleti

Görsel Yok

Moldorc Kalesi Düğmesi

Görsel Yok

Odun Yığını

Odun Yığını

Odun Yığını

Ominent Yatak

Ominent Yatak

Orkide Peygamberi Ini

Orkide Peygamberi Ini

Ot Öldürücü 420

Ot Öldürücü 420

Pagoda

Pagoda

Görsel Yok

Pagoda Gölet Kapağı

Piknik Masası

Piknik Masası

Pus Laboratuvarı Kapı Terminali

Pus Laboratuvarı Kapı Terminali

Görsel Yok

Sarı Kürek

Görsel Yok

Sarkık Eşek Arısı Yuvası

Görsel Yok

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Sarkık Eşek Arısı Yuvası

Siyah Karınca Yuva Laboratuvarı Gözlem Odası

Siyah Karınca Yuva Laboratuvarı Gözlem Odası

Siyah Karınca Yuva Laboratuvarı MIX.R Odası

Siyah Karınca Yuva Laboratuvarı MIX.R Odası

Siyah Karınca Yuva Laboratuvarı Seviye B Geçersiz Kılma

Siyah Karınca Yuva Laboratuvarı Seviye B Geçersiz Kılma

Siyah Karınca Yuva Laboratuvarı Yatakhanesi

Siyah Karınca Yuva Laboratuvarı Yatakhanesi

Siyah Karınca Yuvas�'use client'

import React from 'react';
import { FaSearch, FaBell, FaUser } from 'react-icons/fa';

const Header = () => {
  return (
    <header className="bg-white shadow-md px-6 py-4">
      <div className="flex items-center justify-between">
        {/* Search Bar */}
        <div className="relative flex-1 max-w-lg">
          <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
          <input
            type="text"
            placeholder="Search..."
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* Right side icons */}
        <div className="flex items-center space-x-4">
          {/* Notifications */}
          <button className="relative p-2 text-gray-600 hover:bg-gray-100 rounded-lg">
            <FaBell size={20} />
            <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">
              3
            </span>
          </button>

          {/* User Profile */}
          <button className="flex items-center space-x-2 p-2 text-gray-600 hover:bg-gray-100 rounded-lg">
            <FaUser size={20} />
            <span className="font-medium">Admin</span>
          </button>
        </div>
      </div>
    </header>
  );
};

export default Header;
'use client'

import React from 'react';
import { 
  FaDashboard, 
  FaShoppingBag, 
  FaBox, 
  FaUsers, 
  FaChartBar, 
  FaCog,
  FaSignOutAlt 
} from 'react-icons/fa';
import Link from 'next/link';
import { usePathname } from 'next/navigation';

const Sidebar = () => {
  const pathname = usePathname();

  const menuItems = [
    { icon: FaDashboard, label: 'Dashboard', path: '/dashboard' },
    { icon: FaShoppingBag, label: 'Orders', path: '/dashboard/orders' },
    { icon: FaBox, label: 'Products', path: '/dashboard/products' },
    { icon: FaUsers, label: 'Customers', path: '/dashboard/customers' },
    { icon: FaChartBar, label: 'Analytics', path: '/dashboard/analytics' },
    { icon: FaCog, label: 'Settings', path: '/dashboard/settings' },
  ];

  return (
    <div className="bg-gray-900 text-white w-64 min-h-screen flex flex-col">
      {/* Logo */}
      <div className="p-6 border-b border-gray-700">
        <h1 className="text-2xl font-bold text-blue-400">AdminPanel</h1>
      </div>

      {/* Navigation */}
      <nav className="flex-1 px-4 py-6">
        <ul className="space-y-2">
          {menuItems.map((item, index) => {
            const Icon = item.icon;
            const isActive = pathname === item.path;
            
            return (
              <li key={index}>
                <Link
                  href={item.path}
                  className={`flex items-center space-x-3 px-4 py-3 rounded-lg transition-colors ${
                    isActive 
                      ? 'bg-blue-600 text-white' 
                      : 'text-gray-300 hover:bg-gray-800 hover:text-white'
                  }`}
                >
                  <Icon size={20} />
                  <span>{item.label}</span>
                </Link>
              </li>
            );
          })}
        </ul>
      </nav>

      {/* Logout */}
      <div className="p-4 border-t border-gray-700">
        <button className="flex items-center space-x-3 px-4 py-3 text-gray-300 hover:bg-gray-800 hover:text-white rounded-lg transition-colors w-full">
          <FaSignOutAlt size={20} />
          <span>Logout</span>
        </button>
      </div>
    </div>
  );
};

export default Sidebar;
# src/components/dashboard/StatsCard.js
'use client'

import React from 'react';

const StatsCard = ({ title, value, change, icon: Icon, color = 'blue' }) => {
  const colorClasses = {
    blue: 'bg-blue-500',
    green: 'bg-green-500',
    yellow: 'bg-yellow-500',
    red: 'bg-red-500',
    purple: 'bg-purple-500',
  };

  const isPositive = change > 0;

  return (
    <div className="bg-white rounded-lg shadow-md p-6">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium text-gray-600 mb-1">{title}</p>
          <p className="text-3xl font-bold text-gray-900">{value}</p>
          <div className="flex items-center mt-2">
            <span className={`text-sm font-medium ${isPositive ? 'text-green-600' : 'text-red-600'}`}>
              {isPositive ? '+' : ''}{change}%
            </span>
            <span className="text-sm text-gray-500 ml-2">vs last month</span>
          </div>
        </div>
        <div className={`${colorClasses[color]} p-3 rounded-full`}>
          <Icon className="text-white" size={24} />
        </div>
      </div>
    </div>
  );
};

export default StatsCard;
'use client'

import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  BarElement,
} from 'chart.js';
import { Line, Bar } from 'react-chartjs-2';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export const LineChart = ({ data, title }) => {
  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: title,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
      },
    },
  };

  return <Line data={data} options={options} />;
};

export const BarChart = ({ data, title }) => {
  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: title,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
      },
    },
  };

  return <Bar data={data} options={options} />;
};
# src/app/dashboard/page.js
'use client'

import React from 'react';
import { 
  FaShoppingCart, 
  FaDollarSign, 
  FaUsers, 
  FaBox,
  FaTrendingUp,
  FaTrendingDown
} from 'react-icons/fa';
import StatsCard from '@/components/dashboard/StatsCard';
import { LineChart, BarChart } from '@/components/dashboard/Charts';

const Dashboard = () => {
  // Sample data for charts
  const salesData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    datasets: [
      {
        label: 'Sales ($)',
        data: [12000, 19000, 15000, 25000, 22000, 30000],
        borderColor: 'rgb(59, 130, 246)',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        tension: 0.4,
      },
    ],
  };

  const ordersData = {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    datasets: [
      {
        label: 'Orders',
        data: [65, 80, 90, 81, 56, 85, 40],
        backgroundColor: 'rgba(34, 197, 94, 0.8)',
      },
    ],
  };

  // Recent orders data
  const recentOrders = [
    { id: '#1234', customer: 'John Doe', amount: '$129.99', status: 'Completed' },
    { id: '#1235', customer: 'Jane Smith', amount: '$89.50', status: 'Pending' },
    { id: '#1236', customer: 'Mike Johnson', amount: '$199.99', status: 'Processing' },
    { id: '#1237', customer: 'Sarah Wilson', amount: '$59.99', status: 'Completed' },
    { id: '#1238', customer: 'Tom Brown', amount: '$299.99', status: 'Shipped' },
  ];

  const getStatusColor = (status) => {
    switch (status) {
      case 'Completed':
        return 'bg-green-100 text-green-800';
      case 'Pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'Processing':
        return 'bg-blue-100 text-blue-800';
      case 'Shipped':
        return 'bg-purple-100 text-purple-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-gray-600 mt-2">Welcome back! Here's what's happening with your store.</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <StatsCard
          title="Total Revenue"
          value="$45,231"
          change={12.5}
          icon={FaDollarSign}
          color="green"
        />
        <StatsCard
          title="Total Orders"
          value="1,234"
          change={8.2}
          icon={FaShoppingCart}
          color="blue"
        />
        <StatsCard
          title="Total Customers"
          value="892"
          change={-2.4}
          icon={FaUsers}
          color="purple"
        />
        <StatsCard
          title="Total Products"
          value="156"
          change={5.7}
          icon={FaBox}
          color="yellow"
        />
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <div className="bg-white p-6 rounded-lg shadow-md">
          <LineChart data={salesData} title="Sales Overview" />
        </div>
        <div className="bg-white p-6 rounded-lg shadow-md">
          <BarChart data={ordersData} title="Weekly Orders" />
        </div>
      </div>

      {/* Recent Activity */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Recent Orders */}
        <div className="lg:col-span-2 bg-white rounded-lg shadow-md p-6">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-bold text-gray-900">Recent Orders</h2>
            <button className="text-blue-600 hover:text-blue-800 font-medium">View All</button>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Order ID</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Customer</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Amount</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th>
                </tr>
              </thead>
              <tbody>
                {recentOrders.map((order, index) => (
                  <tr key={index} className="border-b border-gray-100">
                    <td className="py-3 px-4 font-mono text-sm">{order.id}</td>
                    <td className="py-3 px-4">{order.customer}</td>
                    <td className="py-3 px-4 font-medium">{order.amount}</td>
                    <td className="py-3 px-4">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(order.status)}`}>
                        {order.status}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Quick Actions */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-bold text-gray-900 mb-6">Quick Actions</h2>
          <div className="space-y-4">
            <button className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors">
              Add New Product
            </button>
            <button className="w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 transition-colors">
              Process Orders
            </button>
            <button className="w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 transition-colors">
              View Reports
            </button>
            <button className="w-full border border-gray-300 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-50 transition-colors">
              Settings
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
# chaitanya-000/admin-dashboard
'use client'

import React, { useState } from 'react';
import { FaPlus, FaSearch, FaEdit, FaTrash, FaEye } from 'react-icons/fa';

const Products = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [products, setProducts] = useState([
    {
      id: 1,
      name: 'iPhone 14 Pro',
      category: 'Electronics',
      price: 999.99,
      stock: 45,
      status: 'Active',
      image: '/api/placeholder/50/50'
    },
    {
      id: 2,
      name: 'MacBook Air M2',
      category: 'Electronics',
      price: 1299.99,
      stock: 23,
      status: 'Active',
      image: '/api/placeholder/50/50'
    },
    {
      id: 3,
      name: 'AirPods Pro',
      category: 'Electronics',
      price: 249.99,
      stock: 0,
      status: 'Out of Stock',
      image: '/api/placeholder/50/50'
    },
    {
      id: 4,
      name: 'Samsung Galaxy S23',
      category: 'Electronics',
      price: 899.99,
      stock: 67,
      status: 'Active',
      image: '/api/placeholder/50/50'
    },
    {
      id: 5,
      name: 'iPad Pro',
      category: 'Electronics',
      price: 1099.99,
      stock: 34,
      status: 'Active',
      image: '/api/placeholder/50/50'
    },
  ]);

  const filteredProducts = products.filter(product =>
    product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    product.category.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const getStatusColor = (status) => {
    switch (status) {
      case 'Active':
        return 'bg-green-100 text-green-800';
      case 'Out of Stock':
        return 'bg-red-100 text-red-800';
      case 'Inactive':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getStockColor = (stock) => {
    if (stock === 0) return 'text-red-600';
    if (stock < 20) return 'text-yellow-600';
    return 'text-green-600';
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Products</h1>
        <p className="text-gray-600 mt-2">Manage your product inventory</p>
      </div>

      {/* Controls */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
          {/* Search */}
          <div className="relative">
            <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              placeholder="Search products..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full md:w-80"
            />
          </div>

          {/* Actions */}
          <div className="flex items-center space-x-4">
            <select className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
              <option>All Categories</option>
              <option>Electronics</option>
              <option>Clothing</option>
              <option>Books</option>
            </select>
            <button className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center space-x-2">
              <FaPlus />
              <span>Add Product</span>
            </button>
          </div>
        </div>
      </div>

      {/* Products Table */}
      <div className="bg-white rounded-lg shadow-md">
        <div className="p-6">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Product</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Category</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Price</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Stock</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredProducts.map((product) => (
                  <tr key={product.id} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="py-4 px-4">
                      <div className="flex items-center space-x-3">
                        <div className="w-12 h-12 bg-gray-200 rounded-lg"></div>
                        <div>
                          <div className="font-medium text-gray-900">{product.name}</div>
                          <div className="text-sm text-gray-500">ID: #{product.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="py-4 px-4 text-gray-700">{product.category}</td>
                    <td className="py-4 px-4 font-medium">${product.price}</td>
                    <td className="py-4 px-4">
                      <span className={`font-medium ${getStockColor(product.stock)}`}>
                        {product.stock}
                      </span>
                    </td>
                    <td className="py-4 px-4">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(product.status)}`}>
                        {product.status}
                      </span>
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center space-x-2">
                        <button className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg">
                          <FaEye size={16} />
                        </button>
                        <button className="p-2 text-green-600 hover:bg-green-100 rounded-lg">
                          <FaEdit size={16} />
                        </button>
                        <button className="p-2 text-red-600 hover:bg-red-100 rounded-lg">
                          <FaTrash size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          <div className="flex items-center justify-between mt-6">
            <div className="text-sm text-gray-700">
              Showing <span className="font-medium">1</span> to <span className="font-medium">5</span> of{' '}
              <span className="font-medium">{products.length}</span> results
            </div>
            <div className="flex items-center space-x-2">
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50">
                Previous
              </button>
              <button className="px-3 py-2 bg-blue-600 text-white rounded-lg">1</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">2</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">3</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                Next
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Products;
'use client'

import React, { useState } from 'react';
import { FaSearch, FaFilter, FaDownload, FaEye } from 'react-icons/fa';

const Orders = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('All');
  
  const orders = [
    {
      id: '#1234',
      customer: 'John Doe',
      email: 'john@example.com',
      total: '$129.99',
      status: 'Completed',
      date: '2024-01-15',
      items: 3
    },
    {
      id: '#1235',
      customer: 'Jane Smith',
      email: 'jane@example.com',
      total: '$89.50',
      status: 'Pending',
      date: '2024-01-14',
      items: 2
    },
    {
      id: '#1236',
      customer: 'Mike Johnson',
      email: 'mike@example.com',
      total: '$199.99',
      status: 'Processing',
      date: '2024-01-14',
      items: 1
    },
    {
      id: '#1237',
      customer: 'Sarah Wilson',
      email: 'sarah@example.com',
      total: '$59.99',
      status: 'Shipped',
      date: '2024-01-13',
      items: 4
    },
    {
      id: '#1238',
      customer: 'Tom Brown',
      email: 'tom@example.com',
      total: '$299.99',
      status: 'Completed',
      date: '2024-01-13',
      items: 2
    },
    {
      id: '#1239',
      customer: 'Lisa Davis',
      email: 'lisa@example.com',
      total: '$149.99',
      status: 'Cancelled',
      date: '2024-01-12',
      items: 1
    }
  ];

  const filteredOrders = orders.filter(order => {
    const matchesSearch = order.customer.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         order.id.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         order.email.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === 'All' || order.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const getStatusColor = (status) => {
    switch (status) {
      case 'Completed':
        return 'bg-green-100 text-green-800';
      case 'Pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'Processing':
        return 'bg-blue-100 text-blue-800';
      case 'Shipped':
        return 'bg-purple-100 text-purple-800';
      case 'Cancelled':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  // Calculate summary statistics
  const totalOrders = orders.length;
  const completedOrders = orders.filter(order => order.status === 'Completed').length;
  const pendingOrders = orders.filter(order => order.status === 'Pending').length;
  const totalRevenue = orders
    .filter(order => order.status === 'Completed')
    .reduce((sum, order) => sum + parseFloat(order.total.replace('$', '')), 0);

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Orders</h1>
        <p className="text-gray-600 mt-2">Manage and track your orders</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">Total Orders</h3>
          <p className="text-3xl font-bold text-gray-900">{totalOrders}</p>
        </div>
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">Completed</h3>
          <p className="text-3xl font-bold text-green-600">{completedOrders}</p>
        </div>
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">Pending</h3>
          <p className="text-3xl font-bold text-yellow-600">{pendingOrders}</p>
        </div>
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">Revenue</h3>
          <p className="text-3xl font-bold text-blue-600">${totalRevenue.toFixed(2)}</p>
        </div>
      </div>

      {/* Controls */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
          {/* Search */}
          <div className="relative">
            <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              placeholder="Search orders..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full md:w-80"
            />
          </div>

          {/* Filters and Actions */}
          <div className="flex items-center space-x-4">
            <select 
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="All">All Status</option>
              <option value="Pending">Pending</option>
              <option value="Processing">Processing</option>
              <option value="Shipped">Shipped</option>
              <option value="Completed">Completed</option>
              <option value="Cancelled">Cancelled</option>
            </select>
            <button className="flex items-center space-x-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
              <FaDownload />
              <span>Export</span>
            </button>
          </div>
        </div>
      </div>

      {/* Orders Table */}
      <div className="bg-white rounded-lg shadow-md">
        <div className="p-6">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Order ID</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Customer</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Date</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Items</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Total</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredOrders.map((order, index) => (
                  <tr key={index} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="py-4 px-4 font-mono text-sm font-medium">{order.id}</td>
                    <td className="py-4 px-4">
                      <div>
                        <div className="font-medium text-gray-900">{order.customer}</div>
                        <div className="text-sm text-gray-500">{order.email}</div>
                      </div>
                    </td>
                    <td className="py-4 px-4 text-gray-700">{order.date}</td>
                    <td className="py-4 px-4 text-gray-700">{order.items}</td>
                    <td className="py-4 px-4 font-medium">{order.total}</td>
                    <td className="py-4 px-4">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(order.status)}`}>
                        {order.status}
                      </span>
                    </td>
                    <td className="py-4 px-4">
                      <button className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg">
                        <FaEye size={16} />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          <div className="flex items-center justify-between mt-6">
            <div className="text-sm text-gray-700">
              Showing <span className="font-medium">1</span> to <span className="font-medium">{filteredOrders.length}</span> of{' '}
              <span className="font-medium">{orders.length}</span> results
            </div>
            <div className="flex items-center space-x-2">
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50">
                Previous
              </button>
              <button className="px-3 py-2 bg-blue-600 text-white rounded-lg">1</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">2</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">3</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                Next
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Orders;
# chaitanya-000/admin-dashboard
import React from 'react';
import Sidebar from '@/components/layout/Sidebar';
import Header from '@/components/layout/Header';

const DashboardLayout = ({ children }) => {
  return (
    <div className="flex h-screen bg-gray-100">
      <Sidebar />
      <div className="flex-1 flex flex-col overflow-hidden">
        <Header />
        <main className="flex-1 overflow-x-hidden overflow-y-auto">
          {children}
        </main>
      </div>
    </div>
  );
};

export default DashboardLayout;
# chaitanya-000/admin-dashboard
'use client'

import React, { useState } from 'react';
import { FaSearch, FaUserPlus, FaEdit, FaTrash, FaEye } from 'react-icons/fa';

const Customers = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [customers, setCustomers] = useState([
    {
      id: 1,
      name: 'John Doe',
      email: 'john@example.com',
      phone: '+1 (555) 123-4567',
      totalOrders: 12,
      totalSpent: '$1,299.99',
      status: 'Active',
      joinDate: '2023-01-15',
      lastOrder: '2024-01-10'
    },
    {
      id: 2,
      name: 'Jane Smith',
      email: 'jane@example.com',
      phone: '+1 (555) 987-6543',
      totalOrders: 8,
      totalSpent: '$899.50',
      status: 'Active',
      joinDate: '2023-02-20',
      lastOrder: '2024-01-08'
    },
    {
      id: 3,
      name: 'Mike Johnson',
      email: 'mike@example.com',
      phone: '+1 (555) 456-7890',
      totalOrders: 15,
      totalSpent: '$2,199.99',
      status: 'Active',
      joinDate: '2023-01-08',
      lastOrder: '2024-01-12'
    },
    {
      id: 4,
      name: 'Sarah Wilson',
      email: 'sarah@example.com',
      phone: '+1 (555) 321-9876',
      totalOrders: 3,
      totalSpent: '$259.99',
      status: 'Inactive',
      joinDate: '2023-11-15',
      lastOrder: '2023-12-20'
    },
    {
      id: 5,
      name: 'Tom Brown',
      email: 'tom@example.com',
      phone: '+1 (555) 654-3210',
      totalOrders: 20,
      totalSpent: '$3,599.99',
      status: 'VIP',
      joinDate: '2022-08-10',
      lastOrder: '2024-01-14'
    },
    {
      id: 6,
      name: 'Lisa Davis',
      email: 'lisa@example.com',
      phone: '+1 (555) 789-0123',
      totalOrders: 6,
      totalSpent: '$649.99',
      status: 'Active',
      joinDate: '2023-06-25',
      lastOrder: '2024-01-05'
    }
  ]);

  const filteredCustomers = customers.filter(customer =>
    customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    customer.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
    customer.phone.includes(searchTerm)
  );

  const getStatusColor = (status) => {
    switch (status) {
      case 'Active':
        return 'bg-green-100 text-green-800';
      case 'Inactive':
        return 'bg-gray-100 text-gray-800';
      case 'VIP':
        return 'bg-purple-100 text-purple-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  // Calculate summary statistics
  const totalCustomers = customers.length;
  const activeCustomers = customers.filter(customer => customer.status === 'Active').length;
  const vipCustomers = customers.filter(customer => customer.status === 'VIP').length;
  const totalRevenue = customers.reduce((sum, customer) => 
    sum + parseFloat(customer.totalSpent.replace('$', '').replace(',', '')), 0
  );

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Customers</h1>
        <p className="text-gray-600 mt-2">Manage your customer database</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">Total Customers</h3>
          <p className="text-3xl font-bold text-gray-900">{totalCustomers}</p>
        </div>
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">Active Customers</h3>
          <p className="text-3xl font-bold text-green-600">{activeCustomers}</p>
        </div>
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">VIP Customers</h3>
          <p className="text-3xl font-bold text-purple-600">{vipCustomers}</p>
        </div>
        <div className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-sm font-medium text-gray-600 mb-2">Total Revenue</h3>
          <p className="text-3xl font-bold text-blue-600">${totalRevenue.toLocaleString()}</p>
        </div>
      </div>

      {/* Controls */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
          {/* Search */}
          <div className="relative">
            <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              placeholder="Search customers..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full md:w-80"
            />
          </div>

          {/* Actions */}
          <div className="flex items-center space-x-4">
            <select className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
              <option>All Customers</option>
              <option>Active</option>
              <option>Inactive</option>
              <option>VIP</option>
            </select>
            <button className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center space-x-2">
              <FaUserPlus />
              <span>Add Customer</span>
            </button>
          </div>
        </div>
      </div>

      {/* Customers Table */}
      <div className="bg-white rounded-lg shadow-md">
        <div className="p-6">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Customer</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Contact</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Orders</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Total Spent</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Last Order</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredCustomers.map((customer) => (
                  <tr key={customer.id} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="py-4 px-4">
                      <div className="flex items-center space-x-3">
                        <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                          <span className="text-blue-600 font-medium">
                            {customer.name.split(' ').map(n => n[0]).join('')}
                          </span>
                        </div>
                        <div>
                          <div className="font-medium text-gray-900">{customer.name}</div>
                          <div className="text-sm text-gray-500">ID: #{customer.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="py-4 px-4">
                      <div>
                        <div className="text-gray-900">{customer.email}</div>
                        <div className="text-sm text-gray-500">{customer.phone}</div>
                      </div>
                    </td>
                    <td className="py-4 px-4 font-medium">{customer.totalOrders}</td>
                    <td className="py-4 px-4 font-medium">{customer.totalSpent}</td>
                    <td className="py-4 px-4">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(customer.status)}`}>
                        {customer.status}
                      </span>
                    </td>
                    <td className="py-4 px-4 text-gray-700">{customer.lastOrder}</td>
                    <td className="py-4 px-4">
                      <div className="flex items-center space-x-2">
                        <button className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg">
                          <FaEye size={16} />
                        </button>
                        <button className="p-2 text-green-600 hover:bg-green-100 rounded-lg">
                          <FaEdit size={16} />
                        </button>
                        <button className="p-2 text-red-600 hover:bg-red-100 rounded-lg">
                          <FaTrash size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          <div className="flex items-center justify-between mt-6">
            <div className="text-sm text-gray-700">
              Showing <span className="font-medium">1</span> to <span className="font-medium">{filteredCustomers.length}</span> of{' '}
              <span className="font-medium">{customers.length}</span> results
            </div>
            <div className="flex items-center space-x-2">
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50">
                Previous
              </button>
              <button className="px-3 py-2 bg-blue-600 text-white rounded-lg">1</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">2</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">3</button>
              <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                Next
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Customers;
'use client'

import React, { useState } from 'react';
import { FaSave, FaUser, FaBell, FaShield, FaPalette, FaDatabase } from 'react-icons/fa';

const Settings = () => {
  const [activeTab, setActiveTab] = useState('profile');
  const [formData, setFormData] = useState({
    // Profile settings
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@example.com',
    phone: '+1 (555) 123-4567',
    role: 'Administrator',
    
    // Notification settings
    emailNotifications: true,
    pushNotifications: true,
    orderNotifications: true,
    promotionalEmails: false,
    
    // Security settings
    twoFactorAuth: true,
    loginAlerts: true,
    sessionTimeout: '30',
    
    // Appearance settings
    theme: 'light',
    language: 'en',
    timezone: 'America/New_York',
    
    // System settings
    currency: 'USD',
    dateFormat: 'MM/DD/YYYY',
    autoBackup: true,
    debugMode: false
  });

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const handleSave = () => {
    // Here you would typically save the settings to your backend
    alert('Settings saved successfully!');
  };

  const tabs = [
    { id: 'profile', label: 'Profile', icon: FaUser },
    { id: 'notifications', label: 'Notifications', icon: FaBell },
    { id: 'security', label: 'Security', icon: FaShield },
    { id: 'appearance', label: 'Appearance', icon: FaPalette },
    { id: 'system', label: 'System', icon: FaDatabase },
  ];

  const renderTabContent = () => {
    switch (activeTab) {
      case 'profile':
        return (
          <div className="space-y-6">
            <h3 className="text-lg font-medium text-gray-900">Profile Information</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  First Name
                </label>
                <input
                  type="text"
                  name="firstName"
                  value={formData.firstName}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Last Name
                </label>
                <input
                  type="text"
                  name="lastName"
                  value={formData.lastName}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Email
                </label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Phone
                </label>
                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Role
                </label>
                <select
                  name="role"
                  value={formData.role}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="Administrator">Administrator</option>
                  <option value="Manager">Manager</option>
                  <option value="Staff">Staff</option>
                </select>
              </div>
            </div>
          </div>
        );

      case 'notifications':
        return (
          <div className="space-y-6">
            <h3 className="text-lg font-medium text-gray-900">Notification Preferences</h3>
            <div className="space-y-4">
              {[
                { key: 'emailNotifications', label: 'Email Notifications', description: 'Receive notifications via email' },
                { key: 'pushNotifications', label: 'Push Notifications', description: 'Receive push notifications in your browser' },
                { key: 'orderNotifications', label: 'Order Notifications', description: 'Get notified about new orders and updates' },
                { key: 'promotionalEmails', label: 'Promotional Emails', description: 'Receive marketing and promotional emails' },
              ].map((item) => (
                <div key={item.key} className="flex items-center justify-between py-4 border-b border-gray-200">
                  <div>
                    <h4 className="text-sm font-medium text-gray-900">{item.label}</h4>
                    <p className="text-sm text-gray-500">{item.description}</p>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      name={item.key}
                      checked={formData[item.key]}
                      onChange={handleInputChange}
                      className="sr-only peer"
                    />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              ))}
            </div>
          </div>
        );

      case 'security':
        return (
          <div className="space-y-6">
            <h3 className="text-lg font-medium text-gray-900">Security Settings</h3>
            <div className="space-y-4">
              {[
                { key: 'twoFactorAuth', label: 'Two-Factor Authentication', description: 'Add an extra layer of security to your account' },
                { key: 'loginAlerts', label: 'Login Alerts', description: 'Get notified when someone logs into your account' },
              ].map((item) => (
                <div key={item.key} className="flex items-center justify-between py-4 border-b border-gray-200">
                  <div>
                    <h4 className="text-sm font-medium text-gray-900">{item.label}</h4>
                    <p className="text-sm text-gray-500">{item.description}</p>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      name={item.key}
                      checked={formData[item.key]}
                      onChange={handleInputChange}
                      className="sr-only peer"
                    />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              ))}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Session Timeout (minutes)
                </label>
                <select
                  name="sessionTimeout"
                  value={formData.sessionTimeout}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="15">15 minutes</option>
                  <option value="30">30 minutes</option>
                  <option value="60">1 hour</option>
                  <option value="120">2 hours</option>
                </select>
              </div>
            </div>
          </div>
        );

      case 'appearance':
        return (
          <div className="space-y-6">
            <h3 className="text-lg font-medium text-gray-900">Appearance Settings</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Theme
                </label>
                <select
                  name="theme"
                  value={formData.theme}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="light">Light</option>
                  <option value="dark">Dark</option>
                  <option value="auto">Auto</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Language
                </label>
                <select
                  name="language"
                  value={formData.language}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="en">English</option>
                  <option value="es">Spanish</option>
                  <option value="fr">French</option>
                  <option value="de">German</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Timezone
                </label>
                <select
                  name="timezone"
                  value={formData.timezone}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="America/New_York">Eastern Time</option>
                  <option value="America/Chicago">Central Time</option>
                  <option value="America/Denver">Mountain Time</option>
                  <option value="America/Los_Angeles">Pacific Time</option>
                </select>
              </div>
            </div>
          </div>
        );

      case 'system':
        return (
          <div className="space-y-6">
            <h3 className="text-lg font-medium text-gray-900">System Settings</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Currency
                </label>
                <select
                  name="currency"
                  value={formData.currency}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="USD">USD - US Dollar</option>
                  <option value="EUR">EUR - Euro</option>
                  <option value="GBP">GBP - British Pound</option>
                  <option value="JPY">JPY - Japanese Yen</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Date Format
                </label>
                <select
                  name="dateFormat"
                  value={formData.dateFormat}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="MM/DD/YYYY">MM/DD/YYYY</option>
                  <option value="DD/MM/YYYY">DD/MM/YYYY</option>
                  <option value="YYYY-MM-DD">YYYY-MM-DD</option>
                </select>
              </div>
              {[
                { key: 'autoBackup', label: 'Automatic Backup', description: 'Automatically backup your data daily' },
                { key: 'debugMode', label: 'Debug Mode', description: 'Enable debug mode for troubleshooting' },
              ].map((item) => (
                <div key={item.key} className="flex items-center justify-between py-4 border-b border-gray-200">
                  <div>
                    <h4 className="text-sm font-medium text-gray-900">{item.label}</h4>
                    <p className="text-sm text-gray-500">{item.description}</p>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      name={item.key}
                      checked={formData[item.key]}
                      onChange={handleInputChange}
                      className="sr-only peer"
                    />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              ))}
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Settings</h1>
        <p className="text-gray-600 mt-2">Manage your account and system preferences</p>
      </div>

      <div className="flex flex-col lg:flex-row gap-6">
        {/* Sidebar */}
        <div className="lg:w-64">
          <nav className="bg-white rounded-lg shadow-md p-4">
            <ul className="space-y-2">
              {tabs.map((tab) => {
                const Icon = tab.icon;
                return (
                  <li key={tab.id}>
                    <button
                      onClick={() => setActiveTab(tab.id)}
                      className={`w-full flex items-center space-x-3 px-4 py-3 rounded-lg transition-colors ${
                        activeTab === tab.id
                          ? 'bg-blue-600 text-white'
                          : 'text-gray-700 hover:bg-gray-100'
                      }`}
                    >
                      <Icon size={20} />
                      <span>{tab.label}</span>
                    </button>
                  </li>
                );
              })}
            </ul>
          </nav>
        </div>

        {/* Content */}
        <div className="flex-1">
          <div className="bg-white rounded-lg shadow-md p-6">
            {renderTabContent()}
            
            {/* Save Button */}
            <div className="mt-8 pt-6 border-t border-gray-200">
              <button
                onClick={handleSave}
                className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 flex items-center space-x-2"
              >
                <FaSave />
                <span>Save Changes</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Settings;
'use client'

import React from 'react';
import { LineChart, BarChart } from '@/components/dashboard/Charts';

const Analytics = () => {
  // Sample data for various charts
  const revenueData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    datasets: [
      {
        label: 'Revenue ($)',
        data: [12000, 19000, 15000, 25000, 22000, 30000, 28000, 35000, 32000, 40000, 38000, 45000],
        borderColor: 'rgb(59, 130, 246)',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        tension: 0.4,
      },
      {
        label: 'Target ($)',
        data: [15000, 20000, 18000, 28000, 25000, 32000, 30000, 37000, 35000, 42000, 40000, 47000],
        borderColor: 'rgb(239, 68, 68)',
        backgroundColor: 'rgba(239, 68, 68, 0.1)',
        tension: 0.4,
        borderDash: [5, 5],
      },
    ],
  };

  const categoryData = {
    labels: ['Electronics', 'Clothing', 'Books', 'Home & Garden', 'Sports', 'Beauty'],
    datasets: [
      {
        label: 'Sales by Category',
        data: [35000, 28000, 15000, 22000, 18000, 12000],
        backgroundColor: [
          'rgba(59, 130, 246, 0.8)',
          'rgba(16, 185, 129, 0.8)',
          'rgba(245, 158, 11, 0.8)',
          'rgba(239, 68, 68, 0.8)',
          'rgba(139, 92, 246, 0.8)',
          'rgba(236, 72, 153, 0.8)',
        ],
      },
    ],
  };

  const trafficData = {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    datasets: [
      {
        label: 'Website Visitors',
        data: [1200, 1900, 1500, 2500, 2200, 1800, 1300],
        borderColor: 'rgb(16, 185, 129)',
        backgroundColor: 'rgba(16, 185, 129, 0.1)',
        tension: 0.4,
      },
    ],
  };

  const conversionData = {
    labels: ['Q1', 'Q2', 'Q3', 'Q4'],
    datasets: [
      {
        label: 'Conversion Rate (%)',
        data: [2.4, 3.2, 2.8, 3.6],
        backgroundColor: 'rgba(139, 92, 246, 0.8)',
      },
    ],
  };

  const topProducts = [
    { name: 'iPhone 14 Pro', sales: '$45,230', units: 156, change: '+12%' },
    { name: 'MacBook Air M2', sales: '$38,900', units: 89, change: '+8%' },
    { name: 'AirPods Pro', sales: '$28,500', units: 234, change: '+15%' },
    { name: 'Samsung Galaxy S23', sales: '$25,600', units: 78, change: '+5%' },
    { name: 'iPad Pro', sales: '$22,800', units: 67, change: '-2%' },
  ];

  const keyMetrics = [
    { label: 'Total Revenue', value: '$345,678', change: '+12.5%', trend: 'up' },
    { label: 'Total Orders', value: '2,456', change: '+8.2%', trend: 'up' },
    { label: 'Avg. Order Value', value: '$142.50', change: '+3.8%', trend: 'up' },
    { label: 'Conversion Rate', value: '3.2%', change: '-1.2%', trend: 'down' },
    { label: 'Customer Acquisition', value: '145', change: '+22.1%', trend: 'up' },
    { label: 'Return Rate', value: '2.8%', change: '-0.5%', trend: 'up' },
  ];

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Analytics</h1>
        <p className="text-gray-600 mt-2">Track your business performance and insights</p>
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
        {keyMetrics.map((metric, index) => (
          <div key={index} className="bg-white rounded-lg shadow-md p-6">
            <h3 className="text-sm font-medium text-gray-600 mb-2">{metric.label}</h3>
            <div className="flex items-center justify-between">
              <p className="text-2xl font-bold text-gray-900">{metric.value}</p>
              <span className={`text-sm font-medium ${
                metric.trend === 'up' && metric.change.startsWith('+') 
                  ? 'text-green-600' 
                  : metric.trend === 'down' || metric.change.startsWith('-')
                  ? 'text-red-600'
                  : 'text-green-600'
              }`}>
                {metric.change}
              </span>
            </div>
          </div>
        ))}
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6 mb-8">
        <div className="bg-white p-6 rounded-lg shadow-md">
          <LineChart data={revenueData} title="Revenue vs Target" />
        </div>
        <div className="bg-white p-6 rounded-lg shadow-md">
          <BarChart data={categoryData} title="Sales by Category" />
        </div>
        <div className="bg-white p-6 rounded-lg shadow-md">
          <LineChart data={trafficData} title="Website Traffic" />
        </div>
        <div className="bg-white p-6 rounded-lg shadow-md">
          <BarChart data={conversionData} title="Quarterly Conversion Rate" />
        </div>
      </div>

      {/* Additional Analytics */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Top Products */}
        <div className="lg:col-span-2 bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-bold text-gray-900 mb-6">Top Performing Products</h2>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Product</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Sales</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Units</th>
                  <th className="text-left py-3 px-4 font-medium text-gray-600">Change</th>
                </tr>
              </thead>
              <tbody>
                {topProducts.map((product, index) => (
                  <tr key={index} className="border-b border-gray-100">
                    <td className="py-3 px-4 font-medium">{product.name}</td>
                    <td className="py-3 px-4">{product.sales}</td>
                    <td className="py-3 px-4">{product.units}</td>
                    <td className="py-3 px-4">
                      <span className={`font-medium ${
                        product.change.startsWith('+') ? 'text-green-600' : 'text-red-600'
                      }`}>
                        {product.change}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Traffic Sources */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-bold text-gray-900 mb-6">Traffic Sources</h2>
          <div className="space-y-4">
            {[
              { source: 'Organic Search', percentage: 42, visitors: '12,456' },
              { source: 'Direct', percentage: 28, visitors: '8,234' },
              { source: 'Social Media', percentage: 18, visitors: '5,123' },
              { source: 'Email', percentage: 8, visitors: '2,345' },
              { source: 'Referral', percentage: 4, visitors: '1,234' },
            ].map((item, index) => (
              <div key={index} className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-900">{item.source}</p>
                  <p className="text-xs text-gray-500">{item.visitors} visitors</p>
                </div>
                <div className="flex items-center space-x-2">
                  <div className="w-20 bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-blue-600 h-2 rounded-full" 
                      style={{ width: `${item.percentage}%` }}
                    ></div>
                  </div>
                  <span className="text-sm font-medium text-gray-900">{item.percentage}%</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Analytics;
# README.md
# Modern Admin Dashboard

A sleek, responsive admin dashboard built with Next.js 14, React, and Tailwind CSS. Features a comprehensive set of admin tools including analytics, order management, product management, customer management, and system settings.

## 🚀 Features

- **Modern Design**: Clean, intuitive interface with responsive design
- **Dashboard Overview**: Key metrics, charts, and recent activity
- **Order Management**: Track and manage customer orders
- **Product Management**: Add, edit, and organize your product catalog
- **Customer Management**: View and manage customer information
- **Analytics**: Interactive charts and business insights
- **Settings**: Comprehensive system and user preferences
- **Responsive**: Works perfectly on desktop, tablet, and mobile devices

## 🛠️ Tech Stack

- **Next.js 14** - React framework with App Router
- **React 18** - Modern React with hooks
- **Tailwind CSS** - Utility-first CSS framework
- **Chart.js** - Interactive charts and visualizations
- **React Icons** - Beautiful icon library
- **React Chart.js 2** - Chart.js integration for React

## 📦 Installation

1. Clone the repository:
```bash
git clone https://github.com/yourusername/admin-dashboard.git
cd admin-dashboard
```

2. Install dependencies:
```bash
npm install
# or
yarn install
# or
pnpm install
```

3. Run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
```

4. Open [http://localhost:3000](http://localhost:3000) in your browser to see the result.

## 🏗️ Project Structure

```
src/
├── app/
│   ├── dashboard/
│   │   ├── analytics/
│   │   ├── customers/
│   │   ├── orders/
│   │   ├── products/
│   │   ├── settings/
│   │   ├── layout.js
│   │   └── page.js
│   ├── globals.css
│   └── layout.js
├── components/
│   ├── dashboard/
│   │   ├── Charts.js
│   │   └── StatsCard.js
│   └── layout/
│       ├── Header.js
│       └── Sidebar.js
└── ...
```

## 🎨 Features Overview

### Dashboard
- Real-time statistics and KPIs
- Interactive charts showing sales trends
- Recent orders overview
- Quick action buttons

### Orders Management
- Order listing with search and filters
- Order status tracking
- Customer information
- Export functionality

### Product Management
- Product catalog with images
- Category management
- Stock tracking
- Bulk operations

### Customer Management
- Customer database
- Order history per customer
- Customer segmentation
- Contact information management

### Analytics
- Revenue tracking
- Sales performance charts
- Traffic analytics
- Conversion metrics

### Settings
- User profile management
- Notification preferences
- Security settings
- System configuration

## 🎯 Customization

The dashboard is built with modularity in mind. You can easily:

1. **Add new pages**: Create new routes in the `app/dashboard/` directory
2. **Customize styling**: Modify Tailwind classes or add custom CSS
3. **Add new charts**: Use the Chart.js components in `components/dashboard/Charts.js`
4. **Modify sidebar**: Update navigation items in `components/layout/Sidebar.js`

## 📱 Responsive Design

The dashboard is fully responsive and works on:
- Desktop (1024px+)
- Tablet (768px - 1023px)
- Mobile (320px - 767px)

## 🔧 Configuration

### Environment Variables
Create a `.env.local` file in the root directory:

```env
# Add your environment variables here
NEXT_PUBLIC_API_URL=your_api_url
DATABASE_URL=your_database_url
```

### Customizing Colors
Update the Tailwind config to match your brand colors:

```javascript
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        primary: {
          50: '#eff6ff',
          500: '#3b82f6',
          600: '#2563eb',
        },
      },
    },
  },
}
```

## 🚀 Deployment

### Vercel (Recommended)
1. Push your code to GitHub
2. Connect your repository to Vercel
3. Deploy with zero configuration

### Other Platforms
The dashboard can be deployed to any platform that supports Next.js:
- Netlify
- AWS Amplify
- Digital Ocean App Platform
- Railway
- Render

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the project
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- [Next.js](https://nextjs.org/) for the amazing React framework
- [Tailwind CSS](https://tailwindcss.com/) for the utility-first CSS framework
- [Chart.js](https://www.chartjs.org/) for beautiful charts
- [React Icons](https://react-icons.github.io/react-icons/) for the icon library

## 📞 Support

If you have any questions or need help, please open an issue on GitHub or reach out to [your-email@example.com](mailto:your-email@example.com).

---

Made with ❤️ by [Your Name](https://github.com/yourusername)�const express = require("express");
const path = require("path");

const app = express();

const cors = require("cors");

app.use(cors());

app.use(express.static(path.join(__dirname, "build")));

app.get("/", function (req, res) {
    res.sendFile(path.join(__dirname, "build", "index.html"));
});

app.get("/api/hello", (req, res) => {
    res.send({ message: "Hello from the backend!" });
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
End Fileimport React, { useEffect, useState } from 'react';

function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    fetch('/api/hello')
      .then(response => response.json())
      .then(data => setMessage(data.message));
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <h1>Hello, World!</h1>
        <p>Your Minimal React App is running!</p>
        <p>Backend says: {message}</p>
      </header>
    </div>
  );
}

export default App;
�import express, { Request, Response } from "express";
import { body, validationResult } from "express-validator";
import jwt from "jsonwebtoken";
import User from "../models/User";
import { check } from "express-validator";
import { currentUser } from "../middleware/current-user";

const router = express.Router();

// @route   POST api/auth
// @desc    Authenticate user & get token
// @access  Public
router.post(
  "/",
  [
    check("email", "Please include a valid email").isEmail(),
    check("password", "Password is required").exists(),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { email, password } = req.body;

    try {
      let user = await User.findOne({ email });

      if (!user) {
        return res.status(400).json({ msg: "Invalid Credentials" });
      }

      const isMatch = await user.comparePassword(password);

      if (!isMatch) {
        return res.status(400).json({ msg: "Invalid Credentials" });
      }

      const payload = {
        user: {
          id: user.id,
        },
      };

      jwt.sign(
        payload,
        process.env.JWT_SECRET as string,
        { expiresIn: 360000 },
        (err, token) => {
          if (err) throw err;
          res.json({ token });
        }
      );
    } catch (err) {
      console.error(err);
      res.status(500).send("Server error");
    }
  }
);

// @route   GET api/auth
// @desc    Get current user
// @access  Private
router.get("/", currentUser, async (req: Request, res: Response) => {
  try {
    const user = await User.findById(req.user?.id).select("-password");
    res.json(user);
  } catch (err) {
    console.error(err);
    res.status(500).send("Server error");
  }
});

export { router as authRouter };
End Fileimport express, { Request, Response } from "express";
import { check, validationResult } from "express-validator";
import User from "../models/User";
import jwt from "jsonwebtoken";

const router = express.Router();

// @route   POST api/users
// @desc    Register user
// @access  Public
router.post(
  "/",
  [
    check("name", "Name is required").not().isEmpty(),
    check("email", "Please include a valid email").isEmail(),
    check(
      "password",
      "Please enter a password with 6 or more characters"
    ).isLength({ min: 6 }),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { name, email, password } = req.body;

    try {
      let user = await User.findOne({ email });

      if (user) {
        return res.status(400).json({ msg: "User already exists" });
      }

      user = new User({
        name,
        email,
        password,
      });

      await user.save();

      const payload = {
        user: {
          id: user.id,
        },
      };

      jwt.sign(
        payload,
        process.env.JWT_SECRET as string,
        { expiresIn: 360000 },
        (err, token) => {
          if (err) throw err;
          res.json({ token });
        }
      );
    } catch (err) {
      console.error(err);
      res.status(500).send("Server error");
    }
  }
);

export { router as userRouter };
End File# src/routes/tasks.ts
import express, { Request, Response } from "express";
import { check, validationResult } from "express-validator";
import Task from "../models/Task";
import { currentUser } from "../middleware/current-user";

const router = express.Router();

// @route   GET api/tasks
// @desc    Get all tasks for the current user
// @access  Private
router.get("/", currentUser, async (req: Request, res: Response) => {
  try {
    const tasks = await Task.find({ user: req.user?.id });
    res.json(tasks);
  } catch (err) {
    console.error(err);
    res.status(500).send("Server error");
  }
});

// @route   POST api/tasks
// @desc    Create a new task
// @access  Private
router.post(
  "/",
  [
    currentUser,
    [
      check("title", "Title is required").not().isEmpty(),
      check("description", "Description is required").not().isEmpty(),
    ],
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { title, description, priority = "medium" } = req.body;

    try {
      const newTask = new Task({
        title,
        description,
        priority,
        user: req.user?.id,
      });

      const task = await newTask.save();
      res.json(task);
    } catch (err) {
      console.error(err);
      res.status(500).send("Server error");
    }
  }
);

// @route   PUT api/tasks/:id
// @desc    Update a task
// @access  Private
router.put("/:id", currentUser, async (req: Request, res: Response) => {
  const { title, description, priority, completed } = req.body;

  // Build task object
  const taskFields: any = {};
  if (title) taskFields.title = title;
  if (description) taskFields.description = description;
  if (priority) taskFields.priority = priority;
  if (completed !== undefined) taskFields.completed = completed;

  try {
    let task = await Task.findById(req.params.id);

    if (!task) {
      return res.status(404).json({ msg: "Task not found" });
    }

    // Make sure user owns task
    if (task.user.toString() !== req.user?.id) {
      return res.status(401).json({ msg: "Not authorized" });
    }

    task = await Task.findByIdAndUpdate(
      req.params.id,
      { $set: taskFields },
      { new: true }
    );

    res.json(task);
  } catch (err) {
    console.error(err);
    res.status(500).send("Server error");
  }
});

// @route   DELETE api/tasks/:id
// @desc    Delete a task
// @access  Private
router.delete("/:id", currentUser, async (req: Request, res: Response) => {
  try {
    let task = await Task.findById(req.params.id);

    if (!task) {
      return res.status(404).json({ msg: "Task not found" });
    }

    // Make sure user owns task
    if (task.user.toString() !== req.user?.id) {
      return res.status(401).json({ msg: "Not authorized" });
    }

    await Task.findByIdAndRemove(req.params.id);

    res.json({ msg: "Task removed" });
  } catch (err) {
    console.error(err);
    res.status(500).send("Server error");
  }
});

export { router as taskRouter };
End File# ravikiran8844/task-manager-backend
# src/models/User.ts
import mongoose from "mongoose";
import bcrypt from "bcryptjs";

// An interface that describes the properties
// that are required to create a new User
interface UserAttrs {
  name: string;
  email: string;
  password: string;
}

// An interface that describes the properties
// that a User Model has
interface UserModel extends mongoose.Model<UserDoc> {
  build(attrs: UserAttrs): UserDoc;
}

// An interface that describes the properties
// that a User Document has
interface UserDoc extends mongoose.Document {
  name: string;
  email: string;
  password: string;
  createdAt: Date;
  comparePassword(candidatePassword: string): Promise<boolean>;
}

const userSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    createdAt: {
      type: Date,
      default: Date.now,
    },
  },
  {
    toJSON: {
      transform(doc, ret) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
        delete ret.password;
      },
    },
  }
);

// Hash password before saving
userSchema.pre("save", async function (done) {
  if (this.isModified("password")) {
    const salt = await bcrypt.genSalt(10);
    const hashed = await bcrypt.hash(this.get("password"), salt);
    this.set("password", hashed);
  }
  done();
});

// Compare password method
userSchema.methods.comparePassword = async function (
  candidatePassword: string
) {
  return await bcrypt.compare(candidatePassword, this.password);
};

userSchema.statics.build = (attrs: UserAttrs) => {
  return new User(attrs);
};

const User = mongoose.model<UserDoc, UserModel>("User", userSchema);

export default User;
End Fileimport mongoose from "mongoose";

// An interface that describes the properties
// that are required to create a new Task
interface TaskAttrs {
  title: string;
  description: string;
  priority?: "low" | "medium" | "high";
  user: string;
}

// An interface that describes the properties
// that a Task Model has
interface TaskModel extends mongoose.Model<TaskDoc> {
  build(attrs: TaskAttrs): TaskDoc;
}

// An interface that describes the properties
// that a Task Document has
interface TaskDoc extends mongoose.Document {
  title: string;
  description: string;
  priority: "low" | "medium" | "high";
  completed: boolean;
  user: string;
  createdAt: Date;
  updatedAt: Date;
}

const taskSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    },
    description: {
      type: String,
      required: true,
    },
    priority: {
      type: String,
      enum: ["low", "medium", "high"],
      default: "medium",
    },
    completed: {
      type: Boolean,
      default: false,
    },
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    createdAt: {
      type: Date,
      default: Date.now,
    },
    updatedAt: {
      type: Date,
      default: Date.now,
    },
  },
  {
    toJSON: {
      transform(doc, ret) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
      },
    },
  }
);

// Update the updatedAt field before saving
taskSchema.pre("save", function (done) {
  this.set("updatedAt", new Date());
  done();
});

taskSchema.statics.build = (attrs: TaskAttrs) => {
  return new Task(attrs);
};

const Task = mongoose.model<TaskDoc, TaskModel>("Task", taskSchema);

export default Task;
End File# ravikiran8844/task-manager-backend
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import { json } from "body-parser";
import { userRouter } from "./routes/users";
import { authRouter } from "./routes/auth";
import { taskRouter } from "./routes/tasks";

const app = express();

app.set("trust proxy", true);
app.use(json());
app.use(cors());

// Routes
app.use("/api/users", userRouter);
app.use("/api/auth", authRouter);
app.use("/api/tasks", taskRouter);

const start = async () => {
  console.log("Starting up...");

  if (!process.env.JWT_SECRET) {
    throw new Error("JWT_SECRET must be defined");
  }

  if (!process.env.MONGO_URI) {
    throw new Error("MONGO_URI must be defined");
  }

  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log("Connected to MongoDB");
  } catch (err) {
    console.error(err);
  }

  app.listen(3000, () => {
    console.log("Listening on port 3000!");
  });
};

start();
�# tests/unit/test_plugin.py
import os
from pathlib import Path

import pytest

from conftest import get_setup_and_config


class TestJunitPlugin:

    def test_save_report_to_xml_and_default_location(self, testdir):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        result = testdir.runpytest('--junit-xml=output.xml')
        assert result.ret == 0
        assert Path('output.xml').exists()

    def test_config_plugin_from_ini(self, testdir):
        testdir.makeini(
            '''
            [tool:pytest]
            junit_family = xunit1
            junit_suite_name = mysuite
            junit_logging = all
            junit_log_passing_tests = True
        '''
        )

        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )

        setup, config = get_setup_and_config(testdir.tmpdir)
        assert config._get_junit_family() == 'xunit1'
        assert config._get_junit_suite_name() == 'mysuite'
        assert config._get_junit_logging() == 'all'
        assert config._get_junit_log_passing_tests() is True

    def test_config_plugin_from_pyproject_toml(self, testdir):
        testdir.makefile(
            '.toml',
            pyproject='''
            [tool.pytest.ini_options]
            junit_family = "xunit2"
            junit_suite_name = "another_suite"
            junit_logging = "system-err"
            junit_log_passing_tests = false
        ''',
        )

        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )

        setup, config = get_setup_and_config(testdir.tmpdir)
        assert config._get_junit_family() == 'xunit2'
        assert config._get_junit_suite_name() == 'another_suite'
        assert config._get_junit_logging() == 'system-err'
        assert config._get_junit_log_passing_tests() is False

    def test_junit_family_without_xml_option(self, testdir):
        testdir.makeini(
            '''
            [tool:pytest]
            junit_family = xunit1
        '''
        )
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        result = testdir.runpytest('--junit-family=xunit1')
        assert result.ret == 0

    def test_xunit1_produces_correct_xml(self, testdir):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        result = testdir.runpytest('--junit-xml=output.xml', '--junit-family=xunit1')
        assert result.ret == 0
        output_xml = testdir.tmpdir.join('output.xml').read()
        assert 'xmlns' not in output_xml

    def test_xunit2_produces_correct_xml(self, testdir):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        result = testdir.runpytest('--junit-xml=output.xml', '--junit-family=xunit2')
        assert result.ret == 0
        output_xml = testdir.tmpdir.join('output.xml').read()
        assert 'xmlns' in output_xml

    def test_incorrect_family_option_errors(self, testdir):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        result = testdir.runpytest('--junit-xml=output.xml', '--junit-family=unknown')
        assert result.ret == pytest.ExitCode.USAGE_ERROR

    @pytest.mark.parametrize('junit_logging', ['no', 'log', 'system-out', 'system-err', 'out-err', 'all'])
    def test_junit_logging_option_accepted(self, testdir, junit_logging):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        result = testdir.runpytest('--junit-xml=output.xml', f'--junit-logging={junit_logging}')
        assert result.ret == 0

    def test_incorrect_logging_option_errors(self, testdir):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        result = testdir.runpytest('--junit-xml=output.xml', '--junit-logging=unknown')
        assert result.ret == pytest.ExitCode.USAGE_ERROR

    def test_env_var_junit_family(self, testdir, monkeypatch):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        monkeypatch.setenv('PYTEST_JUNIT_FAMILY', 'xunit1')
        result = testdir.runpytest('--junit-xml=output.xml')
        assert result.ret == 0

    def test_plugin_not_loaded_without_option(self, testdir):
        """Check that the junit plugin is not loaded by default."""
        testdir.makepyfile(
            '''
            def test_one():
                assert hasattr(config.pluginmanager, "getplugin")
                assert not config.pluginmanager.getplugin('junitxml')
        '''
        )
        testdir.runpytest()

    def test_plugin_loaded_with_option(self, testdir):
        """Check that the junit plugin is loaded with option."""
        testdir.makepyfile(
            '''
            def test_one():
                assert hasattr(config.pluginmanager, "getplugin")
                assert config.pluginmanager.getplugin('junitxml')
        '''
        )
        testdir.runpytest('--junit-xml=output.xml')

    def test_xml_filename_can_be_absolute_path(self, testdir):
        testdir.makepyfile(
            '''
            def test_one():
                pass
        '''
        )
        xml_file = os.path.abspath('output.xml')
        result = testdir.runpytest(f'--junit-xml={xml_file}')
        assert result.ret == 0
        assert os.path.isfile(xml_file)

    def test_envvar_junit_prefix_works(self, testdir, monkeypatch):
        testdir.makepyfile(
            '''
            def test_prefix():
                pass
        '''
        )
        monkeypatch.setenv('PYTEST_JUNIT_PREFIX', 'env_')
        result = testdir.runpytest('--junit-xml=output.xml')
        assert result.ret == 0
        with open('output.xml') as f:
            content = f.read()
        assert 'classname="env_test_envvar_junit_prefix_works.test_prefix"' in content
End File# tests/unit/test_logs.py
import logging

import pytest

from conftest import runandparse


class TestLogs:
    def test_record_property(self, testdir):
        testdir.makepyfile(
            """
            def test_record(record_property):
                record_property("foo", "<1");
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        foonode = node.getElementsByTagName("properties")[0]
        foo = foonode.getElementsByTagName("property")[0]
        assert foo.getAttribute("name") == "foo"
        assert foo.getAttribute("value") == "<1"
        assert foo.firstChild is None

    def test_record_property_same_name(self, testdir):
        testdir.makepyfile(
            """
            def test_record_with_same_name(record_property):
                record_property("foo", "bar")
                record_property("foo", "baz")
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        pnodes = node.getElementsByTagName("properties")
        assert len(pnodes) == 1
        props = pnodes[0].getElementsByTagName("property")
        assert len(props) == 2
        for i, expected_value in enumerate(["bar", "baz"]):
            assert props[i].getAttribute("name") == "foo"
            assert props[i].getAttribute("value") == expected_value

    def test_record_attribute(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture
            def other(record_testsuite_property):
                record_testsuite_property("bar", 1)

            def test_record(record_testsuite_property, other):
                record_testsuite_property("foo", "<1");
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testsuite")[0]
        # the time, errors, failures, tests and skipped attributes always exist
        assert len(node.attributes) == 7
        assert node.getAttribute("bar") == "1"
        assert node.getAttribute("foo") == "<1"

    def test_record_attribute_same_name(self, testdir):
        testdir.makepyfile(
            """
            def test_record_with_same_name(record_testsuite_property):
                record_testsuite_property("foo", "bar")
                record_testsuite_property("foo", "baz")
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testsuite")[0]
        assert node.getAttribute("foo") == "baz"

    @pytest.mark.parametrize("junit_logging", ["no", "log", "system-out", "system-err", "out-err", "all"])
    def test_nothing_logged(self, testdir, junit_logging):
        testdir.makepyfile(
            """
            import sys

            def test_foo():
                sys.stdout.write('text going to stdout')
                sys.stderr.write('text going to stderr')
                assert False
        """
        )
        result, dom = runandparse(testdir, "-o", f"junit_logging={junit_logging}")
        node = dom.getElementsByTagName("testcase")[0]
        if junit_logging in ["log", "all"]:
            assert len(node.getElementsByTagName("system-out")) == 1
        elif junit_logging in ["system-out", "out-err"]:
            assert len(node.getElementsByTagName("system-out")) == 1
        else:
            assert len(node.getElementsByTagName("system-out")) == 0

        if junit_logging in ["log", "all"]:
            assert len(node.getElementsByTagName("system-err")) == 1
        elif junit_logging in ["system-err", "out-err"]:
            assert len(node.getElementsByTagName("system-err")) == 1
        else:
            assert len(node.getElementsByTagName("system-err")) == 0

    def test_logging_captured_no_log_option(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import logging

            def test_foo():
                sys.stdout.write('text going to stdout')
                sys.stderr.write('text going to stderr')
                logging.getLogger().info('text going to logger')
                assert 0, 'fail'
        """
        )

        result, dom = runandparse(testdir, "-o", "junit_logging=system-out")
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        text = sysout.firstChild.nodeValue
        assert "text going to stdout" in text
        assert "text going to stderr" not in text
        assert "text going to logger" not in text

        syserr = node.getElementsByTagName("system-err")
        assert len(syserr) == 0

    def test_logging_captured_log_option(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import logging

            def test_foo():
                sys.stdout.write('text going to stdout')
                sys.stderr.write('text going to stderr')
                logging.getLogger().info('text going to logger')
                assert 0, 'fail'
        """
        )

        result, dom = runandparse(testdir, "-o", "junit_logging=log")
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        text = sysout.firstChild.nodeValue
        assert "text going to stdout" in text
        assert "text going to stderr" not in text
        assert "text going to logger" in text

        syserr = node.getElementsByTagName("system-err")[0]
        text = syserr.firstChild.nodeValue
        assert "text going to stdout" not in text
        assert "text going to stderr" in text
        assert "text going to logger" not in text

    def test_logging_captured_only_log_option(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import logging

            def test_foo():
                sys.stdout.write('text going to stdout')
                sys.stderr.write('text going to stderr')
                logging.getLogger().info('text going to logger')
                assert 0, 'fail'
        """
        )

        result, dom = runandparse(testdir, "-s", "-o", "junit_logging=log")
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        text = sysout.firstChild.nodeValue
        assert "text going to stdout" not in text
        assert "text going to stderr" not in text
        assert "text going to logger" in text

        syserr = node.getElementsByTagName("system-err")[0]
        text = syserr.firstChild.nodeValue
        assert "text going to stdout" not in text
        assert "text going to stderr" not in text
        assert "text going to logger" not in text

    def test_logging_passed_test(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import logging

            def test_foo():
                sys.stdout.write('text going to stdout')
                sys.stderr.write('text going to stderr')
                logging.getLogger().info('text going to logger')
        """
        )

        result, dom = runandparse(testdir, "-o", "junit_logging=all")
        node = dom.getElementsByTagName("testcase")[0]
        assert len(node.getElementsByTagName("system-out")) == 0
        assert len(node.getElementsByTagName("system-err")) == 0

    def test_logging_passed_test_log_passing_tests(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import logging

            def test_foo():
                sys.stdout.write('text going to stdout')
                sys.stderr.write('text going to stderr')
                logging.getLogger().info('text going to logger')
        """
        )

        result, dom = runandparse(testdir, "-o", "junit_logging=all", "-o", "junit_log_passing_tests=True")
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        text = sysout.firstChild.nodeValue
        assert "text going to stdout" in text
        assert "text going to stderr" not in text
        assert "text going to logger" in text

        syserr = node.getElementsByTagName("system-err")[0]
        text = syserr.firstChild.nodeValue
        assert "text going to stdout" not in text
        assert "text going to stderr" in text
        assert "text going to logger" not in text

    def test_logging_passed_test_no_verbose(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import logging

            def test_foo():
                sys.stdout.write('text going to stdout')
                sys.stderr.write('text going to stderr')
                logging.getLogger().info('text going to logger')
        """
        )

        result, dom = runandparse(testdir, "-o", "junit_logging=all", "--tb=no")
        node = dom.getElementsByTagName("testcase")[0]
        assert len(node.getElementsByTagName("system-out")) == 0
        assert len(node.getElementsByTagName("system-err")) == 0

    def test_logging_xml_disabled(self, testdir):
        testdir.makepyfile(
            """
            import logging

            def test_foo():
                logging.getLogger().warning('user warning')
                assert 0
        """
        )
        result = testdir.runpytest("--tb=no")
        assert "<testcase " not in result.stdout.str()

    def test_pass_captures_stdout(self, testdir):
        testdir.makepyfile(
            """
            def test_pass():
                print("hello-stdout")
        """
        )
        result, dom = runandparse(testdir, "-o", "junit_log_passing_tests=True")
        node = dom.getElementsByTagName("testcase")[0]
        pnode = node.getElementsByTagName("system-out")[0]
        assert "hello-stdout" in pnode.firstChild.nodeValue

    def test_pass_captures_stderr(self, testdir):
        testdir.makepyfile(
            """
            import sys
            def test_pass():
                sys.stderr.write("hello-stderr")
        """
        )
        result, dom = runandparse(testdir, "-o", "junit_log_passing_tests=True")
        node = dom.getElementsByTagName("testcase")[0]
        pnode = node.getElementsByTagName("system-err")[0]
        assert "hello-stderr" in pnode.firstChild.nodeValue

    def test_setup_error_captures_stdout(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.fixture
            def arg(request):
                print('hello-stdout setup')
                raise ValueError()
            def test_function(arg):
                pass
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        pnode = node.getElementsByTagName("system-out")[0]
        assert "hello-stdout setup" in pnode.firstChild.nodeValue

    def test_setup_error_captures_stderr(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            import sys
            @pytest.fixture
            def arg(request):
                sys.stderr.write('hello-stderr setup')
                raise ValueError()
            def test_function(arg):
                pass
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        pnode = node.getElementsByTagName("system-err")[0]
        assert "hello-stderr setup" in pnode.firstChild.nodeValue

    def test_avoid_double_stdout(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import pytest

            @pytest.fixture
            def arg(request):
                yield
                sys.stdout.write('hello-stdout teardown')
                raise ValueError()

            def test_function(arg):
                sys.stdout.write('hello-stdout call')
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        pnode = node.getElementsByTagName("system-out")[0]
        stdout = pnode.firstChild.nodeValue
        assert stdout.count("hello-stdout call") == 1
        assert stdout.count("hello-stdout teardown") == 1

    def test_log_captured(self, testdir):
        testdir.makepyfile(
            """
            import logging

            def test_log():
                logging.getLogger().info('user message')
                assert 0
            """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        pnode = node.getElementsByTagName("system-out")[0]
        assert "user message" in pnode.firstChild.nodeValue

    def test_log_file_not_captured(self, testdir):
        """Test that output from a logger configured to output to a file is not
        captured."""
        testdir.makepyfile(
            """
            import logging

            def test_log():
                logger = logging.getLogger()
                logger.setLevel(logging.INFO)
                logger.addHandler(logging.FileHandler("testlog.txt", mode="a"))
                logger.info('user message')
                assert 0
            """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        assert "user message" not in sysout.firstChild.nodeValue

    def test_live_logging_disabled(self, testdir):
        """Test that output from a logger configured to output to a file is not
        captured."""
        testdir.makepyfile(
            """
            import logging

            def test_log():
                logging.getLogger().info('user message')
                assert 0
            """
        )
        result, dom = runandparse(testdir, "--log-cli-level=INFO")
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        assert "user message" in sysout.firstChild.nodeValue

    def test_non_string_properties(self, testdir):
        testdir.makepyfile(
            """
            def test_record_int_property(record_property):
                record_property("foo", 1)
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        foonode = node.getElementsByTagName("properties")[0]
        foo = foonode.getElementsByTagName("property")[0]
        assert foo.getAttribute("name") == "foo"
        assert foo.getAttribute("value") == "1"

    def test_record_property_from_fixture(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture
            def some_fixture(record_property):
                record_property("foo", "bar")

            def test_record(some_fixture):
                pass
        """
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        foonode = node.getElementsByTagName("properties")[0]
        foo = foonode.getElementsByTagName("property")[0]
        assert foo.getAttribute("name") == "foo"
        assert foo.getAttribute("value") == "bar"

    def test_record_test_id(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.mark.parametrize('x', [1, 2])
            def test_function(x):
                assert x != 2
        """
        )
        result, dom = runandparse(testdir)
        nodes = dom.getElementsByTagName("testcase")
        nodes_tids = [x.getAttribute("classname") + "." + x.getAttribute("name") for x in nodes]
        assert "test_record_test_id.test_function[1]" in nodes_tids
        assert "test_record_test_id.test_function[2]" in nodes_tids

    def test_record_test_id_with_nested_tests(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            class TestClass:
                @pytest.mark.parametrize('x', [1, 2])
                def test_function(self, x):
                    assert x != 2
        """
        )
        result, dom = runandparse(testdir)
        nodes = dom.getElementsByTagName("testcase")
        nodes_tids = [x.getAttribute("classname") + "." + x.getAttribute("name") for x in nodes]
        assert "test_record_test_id_with_nested_tests.TestClass.test_function[1]" in nodes_tids
        assert "test_record_test_id_with_nested_tests.TestClass.test_function[2]" in nodes_tids

    def test_record_name_with_slash(self, testdir):
        subdir = testdir.mkdir("sub")
        subdir.join("test_foo.py").write(
            '''
            def test_logging():
                assert True
        '''
        )
        result, dom = runandparse(testdir)
        node = dom.getElementsByTagName("testcase")[0]
        assert node.getAttribute("classname") == "sub.test_foo.test_logging"

    @pytest.mark.parametrize(
        "junit_family",
        ["xunit1", "xunit2", "legacy"],
    )
    def test_unicode_on_longrepr(self, testdir, junit_family):
        testdir.makepyfile(
            """
            # -*- coding: utf-8 -*-
            def test_failure():
                assert 0, 'ä'
        """
        )
        result, dom = runandparse(testdir, f"--junit-family={junit_family}")
        assert result.ret == 1

    def test_record_from_parametrized_fixture_scope_function(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture(scope="function", params=[1, 2])
            def fixture(request, record_property):
                record_property("foo", "bar")
                return request.param

            def test_function(fixture):
                pass
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret == 0

        properties_by_testcase = []
        testcases = dom.getElementsByTagName("testcase")
        for testcase in testcases:
            properties = testcase.getElementsByTagName("property")
            properties_by_testcase.append([
                (prop.getAttribute("name"), prop.getAttribute("value"))
                for prop in properties
            ])

        # Both testcases should have the same property.
        assert len(properties_by_testcase) == 2
        assert properties_by_testcase[0] == [("foo", "bar")]
        assert properties_by_testcase[1] == [("foo", "bar")]

    def test_record_from_parametrized_fixture_scope_session(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture(scope="session", params=[1, 2])
            def fixture(request, record_property):
                record_property("foo", request.param)
                return request.param

            def test_function(fixture):
                pass
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret == 0

        properties_by_testcase = []
        testcases = dom.getElementsByTagName("testcase")
        for testcase in testcases:
            properties = testcase.getElementsByTagName("property")
            properties_by_testcase.append([
                (prop.getAttribute("name"), prop.getAttribute("value"))
                for prop in properties
            ])

        # Both testcases should have the same property.
        assert len(properties_by_testcase) == 2
        assert properties_by_testcase[0] == [("foo", "1")]
        assert properties_by_testcase[1] == [("foo", "1")]

    def test_record_properties_from_parametrized_test(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.mark.parametrize('x', [1, 2])
            def test_function(x, record_property):
                record_property("foo", x)
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret == 0

        properties_by_testcase = []
        testcases = dom.getElementsByTagName("testcase")
        for testcase in testcases:
            properties = testcase.getElementsByTagName("property")
            properties_by_testcase.append([
                (prop.getAttribute("name"), prop.getAttribute("value"))
                for prop in properties
            ])

        # Both testcases should have distinct properties.
        assert len(properties_by_testcase) == 2
        assert properties_by_testcase[0] == [("foo", "1")]
        assert properties_by_testcase[1] == [("foo", "2")]

    def test_record_testsuite_property_junit_disabled(self, testdir):
        testdir.makepyfile(
            """
            def test_func1(record_testsuite_property):
                record_testsuite_property("stats", "xyz")

            def test_func2(record_testsuite_property):
                record_testsuite_property("stats", 1)
        """
        )
        result = testdir.runpytest()
        assert result.ret == 0

    def test_record_property_junit_disabled(self, testdir):
        testdir.makepyfile(
            """
            def test_func1(record_property):
                record_property("stats", "xyz")
        """
        )
        result = testdir.runpytest()
        assert result.ret == 0

    def test_record_fixtures_without_junitxml(self, testdir):
        testdir.makepyfile(
            """
            def test_record_property(record_property):
                record_property("foo", "bar")

            def test_record_testsuite_property(record_testsuite_property):
                record_testsuite_property("foo", "bar")
        """
        )
        result = testdir.runpytest()
        assert result.ret == 0

    @pytest.mark.parametrize(
        ("log_cli_level", "log_level", "log_auto_indent"),
        [
            ("INFO", logging.INFO, "  "),
            ("WARNING", logging.WARNING, True),
            ("ERROR", logging.ERROR, False),
        ]
    )
    def test_live_logging_preserved_when_logging_option_log(self, testdir, log_cli_level, log_level, log_auto_indent):
        """Test that output from live logging is preserved when junit-logging=log."""
        testdir.makepyfile(
            f"""
            import logging

            def test_log():
                logging.getLogger().log({log_level}, 'user message')
                assert 0
            """
        )
        result, dom = runandparse(
            testdir,
            f"--log-cli-level={log_cli_level}",
            f"--log-auto-indent={log_auto_indent}",
            "-o",
            "junit_logging=log",
        )
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        assert "user message" in sysout.firstChild.nodeValue

    @pytest.mark.parametrize(
        ("log_cli_level", "log_level", "log_auto_indent"),
        [
            ("INFO", logging.INFO, "  "),
            ("WARNING", logging.WARNING, True),
            ("ERROR", logging.ERROR, False),
        ]
    )
    def test_live_logging_preserved_when_logging_option_all(self, testdir, log_cli_level, log_level, log_auto_indent):
        """Test that output from live logging is preserved when junit-logging=all."""
        testdir.makepyfile(
            f"""
            import logging

            def test_log():
                logging.getLogger().log({log_level}, 'user message')
                assert 0
            """
        )
        result, dom = runandparse(
            testdir,
            f"--log-cli-level={log_cli_level}",
            f"--log-auto-indent={log_auto_indent}",
            "-o",
            "junit_logging=all",
        )
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        assert "user message" in sysout.firstChild.nodeValue

    def test_live_logging_mixed_with_caplog_messages(self, testdir):
        testdir.makepyfile(
            """
            import logging

            def test_log(caplog):
                with caplog.at_level(logging.INFO):
                    logging.getLogger().info('caplog message')
                logging.getLogger().warning('user message')
                assert 0
            """
        )
        result, dom = runandparse(
            testdir,
            "--log-cli-level=WARNING",
            "-o",
            "junit_logging=log",
        )
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        assert "caplog message" in sysout.firstChild.nodeValue
        assert "user message" in sysout.firstChild.nodeValue

    def test_live_logging_disabled_capturing_stdout(self, testdir):
        """Test system-out for live logging disabled, capturing stdout."""
        testdir.makepyfile(
            """
            import logging
            import sys

            def test_log():
                logging.getLogger().info('user message')
                sys.stdout.write('stdout message')
                assert 0
            """
        )
        result, dom = runandparse(
            testdir,
            "-o",
            "junit_logging=system-out",
        )
        node = dom.getElementsByTagName("testcase")[0]
        sysout = node.getElementsByTagName("system-out")[0]
        assert "user message" not in sysout.firstChild.nodeValue
        assert "stdout message" in sysout.firstChild.nodeValue
        assert len(node.getElementsByTagName("system-err")) == 0

    def test_live_logging_disabled_capturing_stderr(self, testdir):
        """Test system-err for live logging disabled, capturing stderr."""
        testdir.makepyfile(
            """
            import logging
            import sys

            def test_log():
                logging.getLogger().info('user message')
                sys.stderr.write('stderr message')
                assert 0
            """
        )
        result, dom = runandparse(
            testdir,
            "-o",
            "junit_logging=system-err",
        )
        node = dom.getElementsByTagName("testcase")[0]
        syserr = node.getElementsByTagName("system-err")[0]
        assert "user message" not in syserr.firstChild.nodeValue
        assert "stderr message" in syserr.firstChild.nodeValue
        assert len(node.getElementsByTagName("system-out")) == 0

    def test_live_logging_disabled_capturing_out_err(self, testdir):
        """Test out-err for live logging disabled, capturing both stdout and stderr."""
        testdir.makepyfile(
            """
            import logging
            import sys

            def test_log():
                logging.getLogger().info('user message')
                sys.stdout.write('stdout message')
                sys.stderr.write('stderr message')
                assert 0
            """
        )
        result, dom = runandparse(
            testdir,
            "-o",
            "junit_logging=out-err",
        )
        node = dom.getElementsByTagName("testcase")[0]

        sysout = node.getElementsByTagName("system-out")[0]
        assert "user message" not in sysout.firstChild.nodeValue
        assert "stdout message" in sysout.firstChild.nodeValue
        assert "stderr message" not in sysout.firstChild.nodeValue

        syserr = node.getElementsByTagName("system-err")[0]
        assert "user message" not in syserr.firstChild.nodeValue
        assert "stdout message" not in syserr.firstChild.nodeValue
        assert "stderr message" in syserr.firstChild.nodeValue
�# yusufkarakaya/CSharpEgitimKampi
# 10_DatabaseCrud/Program.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace _10_DatabaseCrud
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Crud --> Create-Read-Update-Delete

            Console.WriteLine("***** Menü Sipariş İşlem Paneli *****");
            Console.WriteLine();

            Console.WriteLine("-----------------------------------------");

            #region Kategori Ekleme İşlemi

            //Console.Write("Eklemek İstediğiniz Kategori Adı: ");
            //string categoryName = Console.ReadLine();

            //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true");

            //connection.Open();

            //SqlCommand command = new SqlCommand("insert into TblCategory (CategoryName) values (@p1)", connection);

            //command.Parameters.AddWithValue("@p1", categoryName);
            //command.ExecuteNonQuery();
            //connection.Close();

            //Console.Write("Kategori başarıyla eklendi!");

            #endregion

            #region Ürün Ekleme İşlemi

            //string productName;
            //decimal productPrice;
            ////bool productStatus;

            //Console.Write("Ürün adı: ");
            //productName = Console.ReadLine();
            //Console.Write("Ürün fiyatı: ");
            //productPrice = decimal.Parse(Console.ReadLine());

            //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true");

            //connection.Open();

            //SqlCommand command = new SqlCommand("insert into TblProduct (ProductName,ProductPrice,ProductStatus) values (@productName,@productPrice,@productStatus)", connection);

            //command.Parameters.AddWithValue("@productName", productName);
            //command.Parameters.AddWithValue("@productPrice", productPrice);
            //command.Parameters.AddWithValue("@productStatus", true);
            //command.ExecuteNonQuery();
            //connection.Close();
            //Console.Write("Ürün ekleme işlemi başarılı!");

            #endregion

            #region Ürün Listeleme İşlemi

            //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true");

            //connection.Open();

            //SqlCommand command = new SqlCommand("Select * From TblProduct", connection);

            //SqlDataAdapter adapter = new SqlDataAdapter(command);
            //DataTable dataTable = new DataTable();
            //adapter.Fill(dataTable);

            //foreach(DataRow row in dataTable.Rows)
            //{
            //    foreach(var item in row.ItemArray)
            //    {
            //        Console.Write(item.ToString() + " ");
            //    }
            //    Console.WriteLine();
            //}

            //connection.Close();

            #endregion

            #region Ürün Silme İşlemi

            //Console.Write("Silinecek Ürün Id: ");
            //int productId = int.Parse(Console.ReadLine());

            //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true");

            //connection.Open();

            //SqlCommand command = new SqlCommand("Delete From TblProduct Where ProductId=@productId", connection);

            //command.Parameters.AddWithValue("@productId", productId);
            //command.ExecuteNonQuery();

            //connection.Close();

            //Console.WriteLine("Silme işlemi yapıldı");

            #endregion

            #region Ürün Güncelleme İşlemi

            //Console.Write("Güncellenecek ürün ID: ");
            //int productId = int.Parse(Console.ReadLine());

            //Console.Write("Güncellenecek ürün adı: ");
            //string productName = Console.ReadLine();

            //Console.Write("Güncellenecek ürün fiyatı: ");
            //decimal productPrice = decimal.Parse(Console.ReadLine());

            //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true");

            //connection.Open();

            //SqlCommand command = new SqlCommand("Update TblProduct Set ProductName=@productName,ProductPrice=@productPrice where ProductId=@productId", connection);

            //command.Parameters.AddWithValue("@productName", productName);
            //command.Parameters.AddWithValue("@productPrice", productPrice);
            //command.Parameters.AddWithValue("@productId", productId);
            //command.ExecuteNonQuery();

            //connection.Close();

            //Console.WriteLine("Güncelleme işlemi başarılı");

            #endregion

            Console.Read();
        }
    }
}
End Fileusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _01_MainSubjects
{
    internal class Program
    {
        static void Main(string[] args)
        {

            #region Yazdırma Komutları

            //Console.Write("Merhaba Dünya");
            //Console.WriteLine("Selam");

            //Console.WriteLine("***** Yemek Kategorileri *****");
            //Console.WriteLine();
            //Console.WriteLine("1-Çorbalar");
            //Console.WriteLine("2-Ana Yemekler");
            //Console.WriteLine("3-Soğuk Başlangıçlar");
            //Console.WriteLine("4-Salatalar");
            //Console.WriteLine("5-Tatlılar");
            //Console.WriteLine("6-İçecekler");
            //Console.WriteLine();
            //Console.WriteLine("***** Yemek Kategorileri *****");

            #endregion

            #region String Değişkenler

            // string
            // Degisken_Turu degisken_adi;

            //string name;
            //name = "Yusuf";
            //Console.Write(name);

            //string customerName;
            //string customerSurname;
            //string customerPhone;
            //string customerEmail, district, city;

            //customerName = "Yusuf";
            //customerSurname = "Karakaya";
            //customerPhone = "+90 500 400 30 20";
            //customerEmail = "deneme@gmail.com";
            //district = "Kadıköy";
            //city = "İstanbul";

            //Console.WriteLine("**** Rezervasyon Kartı ****");
            //Console.WriteLine();
            //Console.WriteLine("------------------------------------------------");
            //Console.WriteLine("Müşteri: " + customerName + " " + customerSurname);
            //Console.WriteLine("İletişim: " + customerPhone);
            //Console.WriteLine("Email Adresi: " + customerEmail);
            //Console.WriteLine("Adres: " + district + "/" + city);
            //Console.WriteLine("------------------------------------------------");

            //Console.WriteLine();

            //customerName = "Ayşegül";
            //customerSurname = "Kaya";
            //customerPhone = "+90 400 300 80 70";
            //customerEmail = "test@gmail.com";
            //district = "Sapanca";
            //city = "Sakarya";

            //Console.WriteLine("------------------------------------------------");
            //Console.WriteLine("Müşteri: " + customerName + " " + customerSurname);
            //Console.WriteLine("İletişim: " + customerPhone);
            //Console.WriteLine("Email Adresi: " + customerEmail);
            //Console.WriteLine("Adres: " + district + "/" + city);
            //Console.WriteLine("------------------------------------------------");

            #endregion

            #region Int Değişkenler

            // int
            //int number = 24;
            //Console.WriteLine(number);

            int hamburgerPrice = 300;
            int cokePrice = 35;
            int waterPrice = 10;
            int friesPrice = 50;
            int pizzaPrice = 250;
            int lemonadePrice = 30;

            Console.WriteLine("**** Restoran Menü Fiyatı ****");
            Console.WriteLine();
            Console.WriteLine("-----Hamburger: " + hamburgerPrice + " TL");
            Console.WriteLine("-----Pizza: " + pizzaPrice + " TL");
            Console.WriteLine("-----Kola: " + cokePrice + " TL");
            Console.WriteLine("-----Limonata: " + lemonadePrice + " TL");
            Console.WriteLine("-----Kızartma: " + friesPrice + " TL");
            Console.WriteLine("-----Su: " + waterPrice + " TL");
            Console.WriteLine();
            Console.WriteLine("**** Restoran Menü Fiyatı ****");

            Console.WriteLine();
            int hamburgerCount;
            int cokeCount;
            int waterCount;
            int friesCount;
            int pizzaCount;
            int lemonadeCount;

            int totalHamburgerPrice;
            int totalCokePrice;
            int totalWaterPrice;
            int totalFriesPrice;
            int totalPizzaPrice;
            int totalLemonadePrice;

            hamburgerCount = 3;
            cokeCount = 3;
            waterCount = 3;
            friesCount = 1;
            pizzaCount = 0;
            lemonadeCount = 0;

            totalHamburgerPrice = hamburgerCount * hamburgerPrice;
            totalCokePrice = cokeCount * cokePrice;
            totalWaterPrice = waterCount * waterPrice;
            totalLemonadePrice = lemonadeCount * lemonadePrice;
            totalFriesPrice = friesCount * friesPrice;
            totalPizzaPrice = pizzaCount * pizzaPrice;

            Console.WriteLine("------------------------------");
            Console.WriteLine("Hamburger Tutarı: " + totalHamburgerPrice + " TL");
            Console.WriteLine("Pizza Tutarı: " + totalPizzaPrice + " TL");
            Console.WriteLine("Kızartma Tutarı: " + totalFriesPrice + " TL");
            Console.WriteLine("Kola Tutarı: " + totalCokePrice + " TL");
            Console.WriteLine("Limonata Tutarı: " + totalLemonadePrice + " TL");
            Console.WriteLine("Su Tutarı: " + totalWaterPrice + " TL");

            Console.WriteLine();

            int totalPrice = totalCokePrice + totalWaterPrice + totalLemonadePrice + totalHamburgerPrice + totalFriesPrice + totalPizzaPrice;

            Console.WriteLine("Toplam Ödenecek Tutar: " + totalPrice + " TL");

            #endregion

            Console.Read();
        }
    }
}
�# CKXMH/CKXMH
# _projects/SNIG.md
---
layout: page
title: SNIG
description: A Sparse Multi-GPU Framework for Accelerating Deep Neural Network Inference
img: assets/img/project_imgs/SNIG.png
importance: 3
category: Research
related_publications: 
---

## SNIG (Sparse Neural network Inference GPU framework)
SNIG is a GPU-acceleration framework for distributed sparse DNN inference. SNIG leverages a bi-directional task-graph scheduling algorithm that incorporates both computation and communication cost for inference latency minimization.

### Project Overview
This project was built with the collaboration with my advisor Dr. Martin Wong at the University of Illinois at Urbana-Champaign and my research mentor Dr. Tsung-Wei Huang at the University of Utah.

<div class="row">
    <div class="col-sm mt-3 mt-md-0">
        {% include figure.html path="assets/img/project_imgs/SNIG.png" title="SNIG framework" class="img-fluid rounded z-depth-1" %}
    </div>
</div>
<div class="caption">
    Architecture of SNIG framework.
</div>

SNIG is a GPU-accelerated framework for distributed sparse deep neural network (DNN) inference. Unlike traditional dense approaches, SNIG exploits sparsity patterns in neural networks to achieve significant memory and computational efficiency improvements. The framework features:
- **Bi-directional Task Graph Scheduling**: Optimizes both computation and communication costs across multiple GPUs
- **Sparse Matrix Operations**: Efficient handling of sparse weight matrices using CSR (Compressed Sparse Row) format
- **Multi-GPU Parallelization**: Distributed inference across multiple GPUs with optimized data transfers
- **Dynamic Load Balancing**: Adaptive workload distribution based on computational complexity

### Publications
- Huang, T. W., Lei, C. X., Wong, M. D. F. (2021). "SNIG: A multi-GPU framework for accelerating sparse deep neural network inference." arXiv preprint arXiv:2105.08165.

### GitHub Repository
The source code and documentation are available at: [SNIG GitHub Repository](https://github.com/CKXMH/SNIG)

### Key Contributions
1. Developed efficient sparse matrix multiplication kernels optimized for GPU architectures
2. Implemented a novel bi-directional scheduling algorithm for multi-GPU inference
3. Achieved significant speedup compared to existing sparse DNN inference frameworks
4. Provided comprehensive benchmarking on various sparse neural network architectures

The framework demonstrates substantial performance improvements over existing methods, particularly for highly sparse networks commonly found in modern deep learning applications.

### Implementation Details
The implementation leverages CUDA for GPU acceleration and MPI for multi-GPU communication. Key algorithmic innovations include optimized sparse matrix storage formats and intelligent workload partitioning strategies that minimize inter-GPU communication overhead while maximizing computational throughput.
End File# CKXMH/CKXMH
---
layout: page
title: Stiffness Prediction
description: Developing a machine learning model to predict stiffness properties for composites reinforced with recycled carbon fiber
img: assets/img/project_imgs/StiffnessPrediction.jpeg
importance: 2
category: Research
related_publications:
---

## Stiffness Prediction for Recycled Carbon Fiber Composites

This research project focused on developing machine learning models to predict the stiffness properties of composite materials reinforced with recycled carbon fiber. The work was conducted as part of my research at the University of Illinois at Urbana-Champaign under the supervision of Dr. Amy Wagoner Johnson.

### Project Overview

The textile and composites industry produces significant waste, leading to environmental concerns. Recycled carbon fiber offers a sustainable solution, but its mechanical properties often differ from virgin fibers due to the recycling process. This project aimed to create predictive models that could estimate composite stiffness based on various parameters of recycled carbon fiber.

<div class="row">
    <div class="col-sm mt-3 mt-md-0">
        {% include figure.html path="assets/img/project_imgs/StiffnessPrediction.jpeg" title="Stiffness Prediction" class="img-fluid rounded z-depth-1" %}
    </div>
</div>
<div class="caption">
    Machine learning pipeline for predicting composite stiffness using recycled carbon fiber parameters.
</div>

### Key Contributions

1. **Data Collection and Processing**: Compiled a comprehensive dataset of recycled carbon fiber properties including fiber length, diameter, surface treatment conditions, and resulting composite stiffness values.

2. **Feature Engineering**: Developed relevant features capturing the relationship between fiber characteristics and composite mechanical properties.

3. **Model Development**: Implemented and compared multiple machine learning algorithms including:
   - Random Forest Regression
   - Support Vector Regression
   - Neural Networks
   - Gradient Boosting methods

4. **Model Validation**: Established robust validation procedures to ensure model reliability and generalizability across different recycling conditions.

### Technical Approach

The project involved several key technical components:

- **Data Preprocessing**: Handling missing values, outlier detection, and normalization of multi-scale features
- **Feature Selection**: Identifying the most influential parameters affecting composite stiffness
- **Hyperparameter Optimization**: Using grid search and random search methods to optimize model performance
- **Cross-validation**: Implementing k-fold cross-validation to assess model robustness

### Results and Impact

The developed models achieved significant predictive accuracy, enabling:
- Rapid assessment of recycled carbon fiber quality
- Optimization of recycling processes to maximize composite performance
- Reduced need for extensive mechanical testing
- Support for sustainable manufacturing decisions

### Applications

This research contributes to:
- Sustainable materials engineering
- Circular economy in composites manufacturing
- Quality control in recycling processes
- Cost-effective material characterization

The predictive models developed in this project provide valuable tools for manufacturers working with recycled carbon fiber, supporting both environmental sustainability and economic viability in composite materials production.

### Future Directions

Potential extensions of this work include:
- Integration with real-time manufacturing processes
- Extension to other recycled fiber types
- Development of multi-objective optimization frameworks
- Implementation in industrial quality control systems
End File# CKXMH/CKXMH
# _projects/SAT.md
---
layout: page
title: SAT Solver
description: A modern SAT solver designed for massively parallel GPU architectures
img: assets/img/project_imgs/SAT.png
importance: 1
category: Research
---

## Modern SAT Solver for GPU Architectures

This project presents the development of a high-performance Boolean Satisfiability (SAT) solver specifically designed to leverage the computational power of modern GPU architectures. The solver incorporates advanced algorithmic techniques and parallel computing strategies to achieve significant performance improvements over traditional CPU-based approaches.

### Project Overview

<div class="row">
    <div class="col-sm mt-3 mt-md-0">
        {% include figure.html path="assets/img/project_imgs/SAT.png" title="SAT Solver Architecture" class="img-fluid rounded z-depth-1" %}
    </div>
</div>
<div class="caption">
    Overview of the GPU-accelerated SAT solver architecture showing the parallel processing pipeline.
</div>

The SAT problem, being NP-complete, represents one of the most fundamental challenges in computer science and has numerous applications in formal verification, automated reasoning, and artificial intelligence. This project addresses the computational complexity by harnessing the massively parallel architecture of modern GPUs.

### Key Features

- **Parallel DPLL Algorithm**: Implementation of the Davis-Putnam-Logemann-Loveland (DPLL) algorithm optimized for GPU execution
- **Conflict-Driven Clause Learning (CDCL)**: Advanced backtracking with learned clauses to prune the search space
- **GPU Memory Optimization**: Efficient memory management strategies for handling large SAT instances
- **Dynamic Load Balancing**: Adaptive workload distribution across GPU cores

### Technical Implementation

The solver incorporates several key algorithmic innovations:

1. **Massively Parallel Search**: Utilizes thousands of GPU threads to explore different branches of the search tree simultaneously
2. **Optimized Data Structures**: Custom data structures designed for GPU memory hierarchy and access patterns  
3. **Heuristic Integration**: Implementation of modern SAT solving heuristics adapted for parallel execution
4. **Clause Database Management**: Efficient storage and retrieval of learned clauses across parallel threads

### Performance Results

The GPU-accelerated solver demonstrates significant performance improvements:
- Up to 10x speedup compared to state-of-the-art CPU solvers on large instances
- Improved scalability with problem size
- Efficient utilization of GPU resources with high occupancy rates

### Applications

This SAT solver has applications in:
- **Formal Verification**: Hardware and software verification problems
- **AI Planning**: Automated planning and scheduling
- **Circuit Design**: Electronic design automation
- **Cryptanalysis**: Breaking cryptographic systems

### Technical Challenges and Solutions

The project addressed several key challenges:

1. **Memory Divergence**: Implemented coalesced memory access patterns to minimize performance penalties
2. **Thread Divergence**: Developed strategies to minimize branch divergence in parallel execution
3. **Scalability**: Designed algorithms that maintain efficiency as problem size increases
4. **Load Balancing**: Created dynamic work distribution mechanisms for irregular workloads

### Future Directions

Ongoing development focuses on:
- Integration with machine learning techniques for improved heuristics
- Multi-GPU scaling for extremely large problem instances  
- Specialized optimizations for specific application domains
- Hybrid CPU-GPU execution strategies

This research contributes to the advancement of high-performance computing in combinatorial optimization and provides a foundation for future developments in parallel constraint satisfaction.

### Code Repository

The source code and documentation for this project are available upon request, including benchmarking suites and performance analysis tools.
End File# CKXMH/CKXMH
---
layout: about
title: about
permalink: /
subtitle: <a href='#'>Affiliations</a>. Address. Contacts. Moto. Etc.

profile:
  align: right
  image: prof_pic.jpg
  image_circular: false # crops the image to make it circular
  more_info: >
    <p>chenlei2@illinois.edu</p>
    <p>University of Illinois at Urbana-Champaign</p>

news: true  # includes a list of news items
latest_posts: false  # includes a list of the newest posts
selected_papers: false # includes a list of papers marked as "selected={true}"
social: true  # includes social icons at the bottom of the page
---

Welcome! I'm Chenlei (Isaac) Xu, a dedicated researcher and engineer with a passion for high-performance computing, artificial intelligence, and sustainable engineering solutions.

I am currently pursuing my PhD in Computer Science at the University of Illinois at Urbana-Champaign, where I work under the guidance of [Dr. Martin Wong](https://publish.illinois.edu/mdfwong/) on cutting-edge problems in parallel computing and GPU acceleration. My research focuses on developing efficient algorithms and frameworks for sparse deep neural network inference on multi-GPU systems.

Previously, I earned my Master's degree in Computer Science from UIUC, where I had the privilege of working with [Dr. Amy Wagoner Johnson](https://mechse.illinois.edu/people/profile/awj) on interdisciplinary research combining machine learning with materials science. This work involved developing predictive models for composite materials reinforced with recycled carbon fiber, contributing to sustainable manufacturing practices.

### Research Interests

My research interests span several interconnected areas:

- **High-Performance Computing**: Developing efficient parallel algorithms and GPU-accelerated frameworks
- **Machine Learning Systems**: Optimizing deep learning inference for sparse neural networks
- **Sustainable Computing**: Applying ML techniques to environmental and materials science challenges
- **Computer Graphics**: Exploring computational methods for visual simulation and rendering

### Current Work

I'm currently focused on **SNIG** (Sparse Neural network Inference GPU framework), a multi-GPU framework designed to accelerate sparse deep neural network inference. This work addresses the growing computational demands of modern AI systems while leveraging sparsity patterns to achieve significant efficiency improvements.

I'm also exploring applications of machine learning in materials science, particularly in predicting mechanical properties of recycled composite materials, bridging the gap between computational methods and sustainable engineering practices.

### Beyond Research

When I'm not immersed in code or research papers, I enjoy exploring new technologies, contributing to open-source projects, and staying active in the academic community. I believe in the power of interdisciplinary collaboration and am always excited to connect with fellow researchers and engineers working on challenging problems.

Feel free to reach out if you'd like to discuss research collaborations, share ideas, or simply connect!
End File# _news/announcement_1.md
---
layout: post
title: A long-form announcement with details
date: 2015-10-22 15:59:00-0400
inline: false
related_posts: false
---

Exciting news! I'm thrilled to share some recent developments in my research journey.

***

#### Research Milestone: SNIG Framework Development

I'm proud to announce a significant milestone in my PhD research - the development of **SNIG** (Sparse Neural network Inference GPU framework), a cutting-edge multi-GPU framework designed specifically for accelerating sparse deep neural network inference.

#### What makes SNIG special?

SNIG addresses a critical challenge in modern AI systems: efficiently handling sparse neural networks across multiple GPUs. Key innovations include:

- **Bi-directional Task Graph Scheduling**: A novel scheduling algorithm that optimizes both computation and communication costs
- **Multi-GPU Parallelization**: Distributed inference across multiple GPUs with intelligent workload balancing
- **Sparse Matrix Optimization**: Efficient handling of sparse weight matrices using advanced data structures

#### Performance Results

The framework demonstrates remarkable performance improvements:
- Significant speedup compared to existing sparse DNN inference methods
- Excellent scalability across multiple GPU configurations
- Efficient memory utilization for large-scale neural networks

#### Publication and Open Source

This work has been documented in our research paper:
> Huang, T. W., Lei, C. X., Wong, M. D. F. (2021). "SNIG: A multi-GPU framework for accelerating sparse deep neural network inference." arXiv preprint arXiv:2105.08165.

The complete source code and documentation are available on [GitHub](https://github.com/CKXMH/SNIG), making it accessible to the broader research community.

#### Looking Forward

This milestone represents not just a technical achievement, but a step toward making AI inference more efficient and accessible. As we continue to see the proliferation of sparse neural networks in production systems, frameworks like SNIG will play a crucial role in democratizing high-performance AI inference.

I'm excited to continue pushing the boundaries of high-performance computing and look forward to the next challenges ahead!

---

*For more details about my research or potential collaborations, feel free to reach out at chenlei2@illinois.edu*
�# docs/quickstart.md
# Quickstart

How to get started with Aya.

## Prerequisites

Install a recent version of Rust

=== "Linux"

    ```bash
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    ```

=== "macOS"

    ```bash
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    ```

=== "Windows"

    To install Rust on Windows, download and run [rustup-init.exe](https://rustup.rs/)

Install the `bpf-linker`: `cargo install bpf-linker`

## 1. Install `aya-gen` (optional)

`aya-gen` allows you to generate Rust bindings from BTF:

```bash
cargo install aya-gen
```

## 2. Install `bpftool` (optional)

If you want to use `aya-gen` with locally generated BTF, you'll need `bpftool`:

=== "Ubuntu"

    ```bash
    apt install linux-tools-generic
    ```

=== "Fedora"

    ```bash
    dnf install bpftool
    ```

## 3. Generate a template

If you don't want to generate a template, you can go to [manually adding aya](#manually-adding-aya-as-a-dependency).

First, install `cargo-generate`:

```bash
cargo install cargo-generate
```

Then run:

```bash
cargo generate https://github.com/aya-rs/aya-template
```

Since the template makes use of [Cargo Workspaces](https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html), 
the generated project will have a directory layout that looks something like:

```
myapp/
├── Cargo.toml (workspace)
├── myapp/
│   ├── src/
│   │   └── main.rs
│   └── Cargo.toml
├── myapp-common/
│   ├── src/
│   │   └── lib.rs
│   └── Cargo.toml
└── myapp-ebpf/
    ├── src/
    │   └── main.rs
    └── Cargo.toml
```

The generated project can be used as starting point for working with Aya:

* `myapp` contains the userspace code and is responsible for loading, attaching and
   interacting with the eBPF program
* `myapp-ebpf` contains the eBPF program, which can be compiled into bytecode and
   embedded in the userspace binary.
* `myapp-common` contains code shared by userspace and eBPF code.

To build the eBPF program:

```bash
cd myapp-ebpf
cargo xtask build-ebpf
```

To build the userspace program:

```bash
cd myapp
cargo build
```

## Manually adding `aya` as a dependency

If you prefer to add `aya` as a dependency manually, add it to your `Cargo.toml`:

```toml
aya = "{{ aya_version }}"
tokio = { version = "1.24", features = ["macros", "rt", "rt-multi-thread", "net", "signal"] }
```

Then you can start by loading and attaching a program:

```rust
use aya::Ebpf;

let mut bpf = Ebpf::load(include_bytes!("../path/to/program.o"))?;
// use `bpf` to work with the loaded program
```
End File# aya/src/programs/tc.rs
//! Traffic control programs.
use std::os::fd::AsFd;

use crate::{
    generated::{bpf_attach_type::BPF_TCX_EGRESS, bpf_prog_type::BPF_PROG_TYPE_SCHED_CLS},
    programs::{
        define_link_wrapper, load_program, FdLink, FdLinkId, Link, ProgAttachLink, ProgramData,
        ProgramError,
    },
    sys::{bpf_link_create, LinkTarget, SyscallError},
    util::KernelVersion,
};

/// A traffic control classifier.
///
/// [`SchedClassifier`] programs can be used to inspect, filter or redirect
/// network packets in both ingress and egress. They are executed as part of
/// the linux traffic control system. See
/// <https://man7.org/linux/man-pages/man8/tc-bpf.8.html>.
///
/// # Minimum kernel version
///
/// The minimum kernel version required to use this feature is 4.1.
///
/// # Examples
///
/// ```no_run
/// # let mut bpf = aya::Ebpf::load(&[])?;
/// use aya::{Ebpf, programs::SchedClassifier, util::tc::{TcAttachOptions, TcAttachType}};
///
/// let prog: &mut SchedClassifier = bpf.program_mut("redirect_ingress").unwrap().try_into()?;
/// prog.load()?;
///
/// // Attach to the root qdisc of the eth0 interface, with default options
/// prog.attach("eth0", TcAttachType::Ingress, TcAttachOptions::default())?;
/// # Ok::<(), aya::EbpfError>(())
/// ```
#[derive(Debug)]
#[doc(alias = "BPF_PROG_TYPE_SCHED_CLS")]
pub struct SchedClassifier {
    pub(crate) data: ProgramData<SchedClassifierLink>,
}

impl SchedClassifier {
    /// Loads the program inside the kernel.
    pub fn load(&mut self) -> Result<(), ProgramError> {
        load_program(BPF_PROG_TYPE_SCHED_CLS, &mut self.data)
    }

    /// Returns the name of the program.
    pub fn name(&self) -> &str {
        &self.data.name
    }

    /// Returns the name of the program on kernels >= 5.0.
    ///
    /// On older kernels, this will return `None`.
    pub fn kernel_name(&self) -> Option<&std::ffi::CStr> {
        self.data.kernel_name.as_deref()
    }

    /// Attaches the program to the given `interface`.
    ///
    /// The returned value can be used to detach, see [SchedClassifier::detach].
    ///
    /// For more info, see [TcAttachOptions].
    pub fn attach(
        &mut self,
        interface: &str,
        attach_type: crate::util::tc::TcAttachType,
        options: crate::util::tc::TcAttachOptions,
    ) -> Result<SchedClassifierLinkId, ProgramError> {
        let link = crate::util::tc::attach(&mut self.data, interface, attach_type, options)?;
        self.data.links.insert(SchedClassifierLink::Tc(link))
    }

    /// Attaches the program to the TCX (TC eXpress) ingress hook.
    ///
    /// The returned value can be used to detach the program, see [SchedClassifier::detach].
    pub fn attach_tcx_ingress<T: AsFd>(
        &mut self,
        interface: T,
    ) -> Result<SchedClassifierLinkId, ProgramError> {
        let link_fd = bpf_link_create(
            self.fd(),
            LinkTarget::IfIndex(interface.as_fd()),
            BPF_TCX_EGRESS,
            None,
            0,
        )
        .map_err(|(_, io_error)| SyscallError {
            call: "bpf_link_create",
            io_error,
        })?;
        self.data
            .links
            .insert(SchedClassifierLink::Fd(FdLink::from_fd(link_fd)))
    }

    /// Takes ownership of the link referenced by the provided link_id.
    ///
    /// The link will be detached on `Drop` and the caller is now responsible
    /// for managing its lifetime.
    pub fn take_link(
        &mut self,
        link_id: SchedClassifierLinkId,
    ) -> Result<SchedClassifierLink, ProgramError> {
        self.data.take_link(link_id)
    }

    /// Detaches the program.
    ///
    /// See [SchedClassifier::attach].
    pub fn detach(&mut self, link_id: SchedClassifierLinkId) -> Result<(), ProgramError> {
        self.data.links.remove(link_id)?.detach()
    }
}

#[derive(Debug)]
pub enum SchedClassifierLink {
    Tc(crate::util::tc::TcLink),
    Fd(FdLink),
}

impl Link for SchedClassifierLink {
    type Id = SchedClassifierLinkId;

    fn id(&self) -> Self::Id {
        match self {
            Self::Tc(link) => SchedClassifierLinkId(link.id().0),
            Self::Fd(fd_link) => SchedClassifierLinkId(fd_link.id().0),
        }
    }

    fn detach(self) -> Result<(), ProgramError> {
        match self {
            Self::Tc(link) => link.detach(),
            Self::Fd(link) => link.detach(),
        }
    }
}

define_link_wrapper!(
    /// The link used by [SchedClassifier] programs.
    SchedClassifierLinkId,
    SchedClassifierLink,
    SchedClassifierLinkInner,
    SchedClassifierLinkIdInner
);

impl TryFrom<SchedClassifierLink> for FdLink {
    type Error = SchedClassifierLink;

    fn try_from(value: SchedClassifierLink) -> Result<Self, Self::Error> {
        match value {
            SchedClassifierLink::Fd(fd) => Ok(fd),
            _ => Err(value),
        }
    }
}

impl From<FdLink> for SchedClassifierLink {
    fn from(fd_link: FdLink) -> Self {
        Self::Fd(fd_link)
    }
}

impl TryFrom<SchedClassifierLink> for crate::util::tc::TcLink {
    type Error = SchedClassifierLink;

    fn try_from(value: SchedClassifierLink) -> Result<Self, Self::Error> {
        match value {
            SchedClassifierLink::Tc(tc) => Ok(tc),
            _ => Err(value),
        }
    }
}

impl From<crate::util::tc::TcLink> for SchedClassifierLink {
    fn from(tc_link: crate::util::tc::TcLink) -> Self {
        Self::Tc(tc_link)
    }
}

impl ProgAttachLink for SchedClassifierLink {
    fn prog_attach_link() -> Self {
        Self::Fd(FdLink::prog_attach_link())
    }

    fn prog_detach_link(_: &Self, _: Option<u32>) -> Result<(), ProgramError> {
        // TODO: The old attach API is deprecated and will be removed.
        // https://github.com/aya-rs/aya/issues/540
        Ok(())
    }

    fn version() -> Option<KernelVersion> {
        // TODO: The old attach API is deprecated and will be removed.
        // When we remove it, we can uncomment the line below.
        // https://github.com/aya-rs/aya/issues/540
        //
        // Some(KernelVersion::new(5, 7, 0))
        None
    }
}
End File//! Cgroup skb programs.
use std::{
    hash::Hash,
    os::fd::{AsFd, AsRawFd},
};

use crate::{
    generated::{
        bpf_attach_type::{BPF_CGROUP_INET_EGRESS, BPF_CGROUP_INET_INGRESS},
        bpf_prog_type::BPF_PROG_TYPE_CGROUP_SKB,
    },
    programs::{
        define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgAttachLinkId,
        ProgramData, ProgramError,
    },
    sys::SyscallError,
    util::KernelVersion,
    ProgFd,
};

/// A program used to inspect or filter network activity for cgroups.
///
/// [`CgroupSkb`] programs can be used to inspect or filter network packets
/// sent/received by processes inside a cgroup. They can be attached to both
/// *ingress* and *egress*.
///
/// # Minimum kernel version
///
/// The minimum kernel version required to use this feature is 4.10.
///
/// # Examples
///
/// ```no_run
/// # let mut bpf = aya::Ebpf::load(&[])?;
/// use std::fs::File;
/// use aya::{Ebpf, programs::{CgroupSkb, CgroupSkbAttachType}};
///
/// let file = File::open("/sys/fs/cgroup/unified")?;
/// let program: &mut CgroupSkb = bpf.program_mut("cgroup_skb_egress").unwrap().try_into()?;
/// program.load()?;
/// program.attach(file, CgroupSkbAttachType::Egress)?;
/// # Ok::<(), aya::EbpfError>(())
/// ```
#[derive(Debug)]
#[doc(alias = "BPF_PROG_TYPE_CGROUP_SKB")]
pub struct CgroupSkb {
    pub(crate) data: ProgramData<CgroupSkbLink>,
}

impl CgroupSkb {
    /// Loads the program inside the kernel.
    pub fn load(&mut self) -> Result<(), ProgramError> {
        load_program(BPF_PROG_TYPE_CGROUP_SKB, &mut self.data)
    }

    /// Attaches the program to the given cgroup.
    ///
    /// The returned value can be used to detach, see [CgroupSkb::detach].
    pub fn attach<T: AsFd>(
        &mut self,
        cgroup: T,
        attach_type: CgroupSkbAttachType,
    ) -> Result<CgroupSkbLinkId, ProgramError> {
        let prog_fd = self.fd();
        let cgroup_fd = cgroup.as_fd();

        let attach_type = match attach_type {
            CgroupSkbAttachType::Ingress => BPF_CGROUP_INET_INGRESS,
            CgroupSkbAttachType::Egress => BPF_CGROUP_INET_EGRESS,
        };
        let link_id = self.data.links.insert(CgroupSkbLink::new(
            prog_fd,
            cgroup_fd.as_raw_fd(),
            attach_type,
        ));
        let link = self.data.links.get_mut(link_id).ok_or(ProgramError::SyscallError {
            call: "insert",
            io_error: std::io::Error::from_raw_os_error(libc::ENOENT),
        })?;
        link.attach(prog_fd)?;

        Ok(link_id)
    }

    /// Detaches the program.
    ///
    /// See [CgroupSkb::attach].
    pub fn detach(&mut self, link_id: CgroupSkbLinkId) -> Result<(), ProgramError> {
        self.data.links.remove(link_id)?.detach()
    }

    /// Takes ownership of the link referenced by the provided link_id.
    ///
    /// The link will be detached on `Drop` and the caller is now responsible
    /// for managing its lifetime.
    pub fn take_link(
        &mut self,
        link_id: CgroupSkbLinkId,
    ) -> Result<CgroupSkbLink, ProgramError> {
        self.data.take_link(link_id)
    }

    /// Returns the name of the program.
    pub fn name(&self) -> &str {
        &self.data.name
    }

    /// Returns the name of the program on kernels >= 5.0.
    ///
    /// On older kernels, this will return `None`.
    pub fn kernel_name(&self) -> Option<&std::ffi::CStr> {
        self.data.kernel_name.as_deref()
    }
}

#[derive(Debug, Hash, Eq, PartialEq)]
pub(crate) struct CgroupSkbLinkInner {
    cgroup_fd: std::os::fd::RawFd,
    attach_type: u32,
}

impl CgroupSkbLinkInner {
    pub(crate) fn new(cgroup_fd: std::os::fd::RawFd, attach_type: u32) -> Self {
        Self {
            cgroup_fd,
            attach_type,
        }
    }
}

define_link_wrapper!(
    /// The link used by [CgroupSkb] programs.
    CgroupSkbLinkId,
    CgroupSkbLink,
    CgroupSkbLinkInner,
    CgroupSkbLinkIdInner
);

// SAFETY: the `inner` value is never changed, so this link can be transferred
// across threads.
unsafe impl Send for CgroupSkbLink {}
unsafe impl Sync for CgroupSkbLink {}

impl CgroupSkbLink {
    pub(crate) fn new(
        prog_fd: ProgFd,
        cgroup_fd: std::os::fd::RawFd,
        attach_type: u32,
    ) -> Self {
        Self::FdLink(FdLink::from_link(ProgAttachLinkId(
            CgroupSkbLinkInner::new(cgroup_fd, attach_type),
        )))
    }
}

impl Link for CgroupSkbLink {
    type Id = CgroupSkbLinkId;

    fn id(&self) -> Self::Id {
        CgroupSkbLinkId(self.fd_link().id().0)
    }

    fn detach(self) -> Result<(), ProgramError> {
        self.fd_link().detach()
    }
}

impl ProgAttachLink for CgroupSkbLink {
    fn prog_attach_link() -> Self {
        Self::FdLink(FdLink::prog_attach_link())
    }

    fn prog_detach_link(link: &Self, current: Option<ProgFd>) -> Result<(), ProgramError> {
        let CgroupSkbLinkInner {
            cgroup_fd,
            attach_type,
        } = link.fd_link().link_id().0;
        crate::sys::bpf_prog_detach(current, cgroup_fd, attach_type).map_err(|(_, io_error)| {
            ProgramError::SyscallError {
                call: "bpf_prog_detach",
                io_error,
            }
        })?;
        Ok(())
    }

    fn version() -> Option<KernelVersion> {
        None
    }
}

/// Defines where to attach a [`CgroupSkb`] program.
#[derive(Copy, Clone, Debug)]
pub enum CgroupSkbAttachType {
    /// Attach to ingress.
    Ingress,
    /// Attach to egress.
    Egress,
}

impl TryFrom<CgroupSkbLink> for FdLink {
    type Error = CgroupSkbLink;

    fn try_from(value: CgroupSkbLink) -> Result<Self, Self::Error> {
        match value {
            CgroupSkbLink::FdLink(fd) => Ok(fd),
            _ => Err(value),
        }
    }
}

impl From<FdLink> for CgroupSkbLink {
    fn from(fd_link: FdLink) -> Self {
        Self::FdLink(fd_link)
    }
}
End File//! Extension programs.

use crate::{
    generated::bpf_prog_type::BPF_PROG_TYPE_EXT,
    obj::btf::{Btf, BtfKind},
    programs::{load_program, ProgramData, ProgramError, ProgramFd},
    sys::bpf_load_program,
};

/// A program used to extend other programs.
///
/// [`Extension`] programs can be used to extend the functionality of other
/// eBPF programs by replacing their functions. They are commonly used for
/// debugging, tracing, or modifying the behavior of existing programs.
///
/// # Minimum kernel version
///
/// The minimum kernel version required to use this feature is 5.9.
///
/// # Examples
///
/// ```no_run
/// # let mut bpf = aya::Ebpf::load(&[])?;
/// use aya::{Ebpf, programs::Extension};
///
/// let program: &mut Extension = bpf.program_mut("extension").unwrap().try_into()?;
/// program.load("target_program", "target_function")?;
/// # Ok::<(), aya::EbpfError>(())
/// ```
#[derive(Debug)]
#[doc(alias = "BPF_PROG_TYPE_EXT")]
pub struct Extension {
    pub(crate) data: ProgramData<ExtensionLink>,
}

impl Extension {
    /// Loads the extension inside the kernel.
    ///
    /// Prepares the extension to replace the function `func_name` inside the
    /// eBPF program `program`.
    ///
    /// The `program` parameter must be the name of a loaded eBPF program. The
    /// extension will replace the function `func_name` inside that program.
    pub fn load(
        &mut self,
        program: &str,
        func_name: &str,
    ) -> Result<ProgramFd, ProgramError> {
        // Find the target program by name
        let target_prog_fd = {
            let programs = crate::sys::loaded_programs()
                .map_err(|io_error| ProgramError::SyscallError {
                    call: "loaded_programs",
                    io_error,
                })?;
            programs
                .into_iter()
                .find(|p| p.name.as_deref() == Some(program.as_ref()))
                .ok_or_else(|| ProgramError::Extension {
                    name: program.to_string(),
                })?
                .fd
        };

        // Get the target program info to find the function offset
        let target_info = crate::sys::bpf_prog_get_info_by_fd(target_prog_fd.as_fd())
            .map_err(|(_, io_error)| ProgramError::SyscallError {
                call: "bpf_prog_get_info_by_fd",
                io_error,
            })?;

        let btf_fd = target_info.btf_id.and_then(|btf_id| {
            crate::sys::bpf_btf_get_fd_by_id(btf_id)
                .map_err(|(_, io_error)| ProgramError::SyscallError {
                    call: "bpf_btf_get_fd_by_id",
                    io_error,
                })
                .ok()
        });

        let (btf_fd, func_info_rec_size, func_info) = if let Some(btf_fd) = btf_fd {
            let btf_info = crate::sys::bpf_btf_get_info_by_fd(btf_fd.as_fd())
                .map_err(|(_, io_error)| ProgramError::SyscallError {
                    call: "bpf_btf_get_info_by_fd",
                    io_error,
                })?;

            let btf_data = crate::sys::btf_obj_get_data_by_fd(btf_fd.as_fd())
                .map_err(|io_error| ProgramError::SyscallError {
                    call: "btf_obj_get_data_by_fd",
                    io_error,
                })?;

            let btf = Btf::parse(&btf_data, crate::obj::btf::Endianness::default())
                .map_err(ProgramError::Btf)?;

            // Find the target function in BTF
            let func_type_id = btf
                .types()
                .enumerate()
                .find_map(|(i, ty)| {
                    if let BtfKind::Func(func) = &ty.kind {
                        if btf.string_at(func.name_offset).ok()? == func_name {
                            return Some(i as u32 + 1); // BTF IDs are 1-indexed
                        }
                    }
                    None
                })
                .ok_or_else(|| ProgramError::Extension {
                    name: func_name.to_string(),
                })?;

            (
                Some(btf_fd),
                target_info.func_info_rec_size,
                vec![func_type_id],
            )
        } else {
            (None, 0, Vec::new())
        };

        let fd = bpf_load_program(
            BPF_PROG_TYPE_EXT,
            &self.data.instructions,
            self.data.kernel_version.unwrap_or_default(),
            self.data.verifier_log_level,
            &self.data.license,
            Some(target_prog_fd.as_fd()),
            btf_fd.as_ref().map(|fd| fd.as_fd()),
            &func_info,
            func_info_rec_size,
            &[],
            0,
            &[],
            0,
        )
        .map_err(|(_, io_error)| ProgramError::LoadError {
            io_error,
            verifier_log: self.data.verifier_log.clone(),
        })?;

        self.data.fd = Some(fd);
        Ok(fd)
    }

    /// Returns the name of the program.
    pub fn name(&self) -> &str {
        &self.data.name
    }

    /// Returns the name of the program on kernels >= 5.0.
    ///
    /// On older kernels, this will return `None`.
    pub fn kernel_name(&self) -> Option<&std::ffi::CStr> {
        self.data.kernel_name.as_deref()
    }
}

#[derive(Debug)]
pub struct ExtensionLink;

impl crate::programs::Link for ExtensionLink {
    type Id = ExtensionLinkId;

    fn id(&self) -> Self::Id {
        ExtensionLinkId
    }

    fn detach(self) -> Result<(), ProgramError> {
        Ok(())
    }
}

#[derive(Debug)]
pub struct ExtensionLinkId;
�# RaagaSarayu/KnowledgeGraph
# README.md
# Knowledge Graph Extraction from Documents with LangChain and NetworkX

This project demonstrates how to extract knowledge graphs from text documents using LangChain for natural language processing and NetworkX for graph visualization.

## What is a Knowledge Graph?

A knowledge graph is a structured representation of knowledge that captures entities, their relationships, and attributes in a graph format. In this format:
- **Nodes** represent entities (people, places, concepts, etc.)
- **Edges** represent relationships between entities
- **Labels** provide additional context or properties

Knowledge graphs are particularly useful for:
- Information retrieval and search
- Question answering systems
- Recommendation engines
- Understanding complex relationships in data
- Semantic analysis of documents

## Features

- Extract entities and relationships from text using OpenAI's GPT models via LangChain
- Generate structured knowledge graphs using NetworkX
- Interactive visualization with customizable layouts
- Support for various document formats
- Configurable entity and relationship extraction

## Installation

1. Clone this repository:
```bash
git clone https://github.com/yourusername/knowledge-graph-extraction.git
cd knowledge-graph-extraction
```

2. Install required packages:
```bash
pip install langchain openai networkx matplotlib pandas numpy python-dotenv
```

3. Set up your OpenAI API key:
   - Create a `.env` file in the project root
   - Add your OpenAI API key:
```
OPENAI_API_KEY=your_api_key_here
```

## Usage

### Basic Example

```python
from knowledge_graph_extractor import KnowledgeGraphExtractor

# Initialize the extractor
extractor = KnowledgeGraphExtractor()

# Sample text
text = """
Albert Einstein was born in Ulm, Germany in 1879. He developed the theory of relativity 
while working as a patent clerk in Bern, Switzerland. Einstein later moved to Princeton 
University in the United States where he continued his research until his death in 1955.
"""

# Extract knowledge graph
graph = extractor.extract_knowledge_graph(text)

# Visualize the graph
extractor.visualize_graph(graph)
```

### Working with Documents

```python
# Load from file
with open('document.txt', 'r') as f:
    text = f.read()

# Extract and visualize
graph = extractor.extract_knowledge_graph(text)
extractor.visualize_graph(graph, layout='spring', figsize=(12, 8))
```

## How It Works

1. **Text Processing**: The input text is processed and cleaned using LangChain utilities
2. **Entity Extraction**: Using OpenAI's GPT models, entities (nouns, proper nouns) are identified in the text
3. **Relationship Extraction**: The model identifies relationships between entities using natural language understanding
4. **Graph Construction**: NetworkX creates a graph structure with extracted entities as nodes and relationships as edges
5. **Visualization**: The graph is rendered using matplotlib with customizable layouts

## Configuration

You can customize the extraction process:

```python
extractor = KnowledgeGraphExtractor(
    model_name="gpt-3.5-turbo",  # or "gpt-4"
    max_tokens=1000,
    temperature=0.1
)
```

## Visualization Options

The visualizer supports different layouts:
- `spring`: Default spring layout
- `circular`: Circular arrangement
- `random`: Random positioning
- `shell`: Concentric shell layout

```python
extractor.visualize_graph(
    graph, 
    layout='spring',
    figsize=(15, 10),
    node_color='lightblue',
    edge_color='gray',
    font_size=8
)
```

## Example Output

The knowledge graph will show:
- **Entities**: People, places, organizations, concepts
- **Relationships**: "born in", "worked at", "developed", "moved to", etc.
- **Visual representation**: Interactive graph with labeled nodes and edges

## Applications

This tool can be used for:
- **Document Analysis**: Understanding key relationships in research papers, reports, or articles
- **Information Extraction**: Building structured databases from unstructured text
- **Educational Tools**: Visualizing concepts and their relationships in textbooks
- **Business Intelligence**: Mapping relationships in business documents
- **Research**: Analyzing scientific literature for connections between concepts

## Requirements

- Python 3.7+
- OpenAI API key
- Required packages (see installation section)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- Built with [LangChain](https://github.com/hwchase17/langchain) for LLM integration
- Uses [NetworkX](https://networkx.org/) for graph operations
- Visualization powered by [Matplotlib](https://matplotlib.org/)

---

**Note**: This project requires an OpenAI API key to function. Make sure to keep your API key secure and never commit it to version control.
�# src/components/home/home.jsx
import React, { useState } from "react";
import "./Home.css";
import { FaGithub } from "react-icons/fa";
import { FaLinkedin } from "react-icons/fa6";
import Footer from "../footer/Footer";
import Projects from "../projects/projects";

export default function Home() {
  const [projects] = useState(Projects);

  return (
    <>
      <div className="Home" id="home">
        <div className="overlay">
          <div className="hero-section">
            <div className="left">
              <h2>
                Hello, I'm <br />{" "}
                <span className="name">
                  {" "}
                  Swati <span>P</span>
                </span>
              </h2>
              <p>I'm a React.JS developer.</p>
              <div className="icons">
                <a href="https://www.linkedin.com/in/swati-p-41606b24a/">
                  <FaLinkedin />
                </a>
                <a href="https://github.com/swatipund">
                  <FaGithub />
                </a>
              </div>
            </div>
            <div className="right">
              <img src="../main.jpg" alt="Swati Photo" />
            </div>
          </div>
        </div>
      </div>

      <div id="about" className="about-section">
        <h2>About me</h2>
        <div className="about-content">
          <div className="profile-image">
            <img src="../profile.jpg" alt="Profile" />
          </div>
          <div className="content">
            <div className="left-content">
              <h3>
                I'm a React.js Developer with Good knowledge of Front-end
                techniques.
              </h3>
              <p>
                I am a passionate Frontend Developer with over 1 years of
                experience in building web applications using React.js,
                JavaScript, HTML, CSS, and modern frontend frameworks. I excel
                at creating responsive, user-friendly interfaces and am always
                eager to learn new technologies and improve my skills.
              </p>
              <p>
                My expertise includes developing dynamic and interactive web
                applications, implementing responsive designs, and ensuring
                cross-browser compatibility. I am proficient in state management
                with Redux, component-based architecture, and integrating APIs
                for seamless user experiences.
              </p>
            </div>
            <div className="right-content">
              <h3>Personal Info</h3>
              <div className="info">
                <div className="info-item">
                  <span className="label">Birthdate:</span>
                  <span className="value">March 31, 2000</span>
                </div>
                <div className="info-item">
                  <span className="label">Email:</span>
                  <span className="value">swatipund31@gmail.com</span>
                </div>
                <div className="info-item">
                  <span className="label">Phone:</span>
                  <span className="value">+91 9503999488</span>
                </div>
                <div className="info-item">
                  <span className="label">Address:</span>
                  <span className="value">Amravati, Maharashtra</span>
                </div>
              </div>
              <button className="download-resume">
                <a
                  href="https://drive.google.com/file/d/1TwC1K2rTZwZ6_6S_nFw5rDFVabxYvfup/view?usp=sharing"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  Download Resume
                </a>
              </button>
            </div>
          </div>
        </div>
      </div>

      <div id="skills" className="skills-section">
        <h2>My Skills</h2>
        <div className="skills-grid">
          <div className="skill-card">
            <img src="../html.png" alt="HTML" />
            <h3>HTML5</h3>
            <p>Semantic markup and modern HTML5 features</p>
          </div>
          <div className="skill-card">
            <img src="../css.png" alt="CSS" />
            <h3>CSS3</h3>
            <p>Responsive design and modern CSS techniques</p>
          </div>
          <div className="skill-card">
            <img src="../js.png" alt="JavaScript" />
            <h3>JavaScript</h3>
            <p>ES6+ features and modern JavaScript development</p>
          </div>
          <div className="skill-card">
            <img src="../react.png" alt="React" />
            <h3>React.js</h3>
            <p>Component-based architecture and hooks</p>
          </div>
          <div className="skill-card">
            <img src="../bootstrap.png" alt="Bootstrap" />
            <h3>Bootstrap</h3>
            <p>Responsive framework for rapid development</p>
          </div>
          <div className="skill-card">
            <img src="../github.png" alt="Git" />
            <h3>Git & GitHub</h3>
            <p>Version control and collaborative development</p>
          </div>
        </div>
      </div>

      <div id="projects" className="projects-section">
        <h2>My Projects</h2>
        <div className="projects-grid">
          {projects.map((project, index) => (
            <div key={index} className="project-card">
              <div className="project-image">
                <img src={project.image} alt={project.title} />
                <div className="project-overlay">
                  <div className="project-links">
                    <a
                      href={project.github}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <FaGithub />
                    </a>
                    <a
                      href={project.demo}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      Demo
                    </a>
                  </div>
                </div>
              </div>
              <div className="project-content">
                <h3>{project.title}</h3>
                <p>{project.description}</p>
                <div className="project-tech">
                  {project.technologies.map((tech, i) => (
                    <span key={i} className="tech-tag">
                      {tech}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <Footer />
    </>
  );
}
End File# swatipund/My-Portfolio
# src/components/projects/projects.js
const Projects = [
  {
    title: "Food Shop",
    description: "A React-based food ordering application with add to cart functionality",
    image: "../food-shop.png",
    technologies: ["React", "CSS", "JavaScript"],
    github: "https://github.com/swatipund/Food-Shop-App",
    demo: "https://food-shop-app-pied.vercel.app/"
  },
  {
    title: "E-Commerce Store",
    description: "Complete e-commerce solution with product listing and shopping cart",
    image: "../ecommerce.png",
    technologies: ["React", "Redux", "CSS"],
    github: "https://github.com/swatipund/E-Commerce",
    demo: "https://e-commerce-gold-beta.vercel.app/"
  },
  {
    title: "YouTube Clone",
    description: "YouTube-like video streaming platform with search and video player",
    image: "../youtube.png",
    technologies: ["React", "YouTube API", "CSS"],
    github: "https://github.com/swatipund/YouTube-Clone",
    demo: "https://you-tube-clone-rho-sepia.vercel.app/"
  },
  {
    title: "QR Code Generator",
    description: "Generate QR codes for any text or URL instantly",
    image: "../qr-generator.png",
    technologies: ["React", "QR.js", "CSS"],
    github: "https://github.com/swatipund/QR-Code-Generator",
    demo: "https://qr-code-generator-teal-ten.vercel.app/"
  },
  {
    title: "Task Manager",
    description: "Simple and efficient task management application",
    image: "../todo.png",
    technologies: ["React", "LocalStorage", "CSS"],
    github: "https://github.com/swatipund/To-Do-List",
    demo: "https://to-do-list-eosin-seven-57.vercel.app/"
  },
  {
    title: "Weather App",
    description: "Real-time weather information with location-based forecasts",
    image: "../weather.png",
    technologies: ["React", "Weather API", "CSS"],
    github: "https://github.com/swatipund/Weather-App",
    demo: "https://weather-app-teal-eta-12.vercel.app/"
  }
];

export default Projects;
End File# swatipund/My-Portfolio
import React from 'react';
import './Footer.css';
import { FaGithub, FaLinkedin, FaEnvelope, FaPhone } from 'react-icons/fa';

export default function Footer() {
  return (
    <footer id="contact" className="footer">
      <div className="footer-content">
        <div className="footer-section">
          <h3>Let's Connect</h3>
          <p>I'm always interested in new opportunities and collaborations.</p>
        </div>
        
        <div className="footer-section">
          <h4>Contact Info</h4>
          <div className="contact-info">
            <div className="contact-item">
              <FaEnvelope />
              <span>swatipund31@gmail.com</span>
            </div>
            <div className="contact-item">
              <FaPhone />
              <span>+91 9503999488</span>
            </div>
          </div>
        </div>
        
        <div className="footer-section">
          <h4>Follow Me</h4>
          <div className="social-links">
            <a href="https://github.com/swatipund" target="_blank" rel="noopener noreferrer">
              <FaGithub />
            </a>
            <a href="https://www.linkedin.com/in/swati-p-41606b24a/" target="_blank" rel="noopener noreferrer">
              <FaLinkedin />
            </a>
          </div>
        </div>
      </div>
      
      <div className="footer-bottom">
        <p>&copy; 2024 Swati P. All rights reserved.</p>
      </div>
    </footer>
  );
}
End File# swatipund/My-Portfolio
# src/components/navbar/Navbar.jsx
import React, { useState } from 'react';
import './Navbar.css';

export default function Navbar() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  const toggleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
  };

  const closeMenu = () => {
    setIsMenuOpen(false);
  };

  return (
    <nav className="navbar">
      <div className="nav-container">
        <div className="nav-logo">
          <span>Swati P</span>
        </div>
        
        <div className={`nav-menu ${isMenuOpen ? 'active' : ''}`}>
          <a href="#home" className="nav-link" onClick={closeMenu}>Home</a>
          <a href="#about" className="nav-link" onClick={closeMenu}>About</a>
          <a href="#skills" className="nav-link" onClick={closeMenu}>Skills</a>
          <a href="#projects" className="nav-link" onClick={closeMenu}>Projects</a>
          <a href="#contact" className="nav-link" onClick={closeMenu}>Contact</a>
        </div>
        
        <div className={`nav-toggle ${isMenuOpen ? 'active' : ''}`} onClick={toggleMenu}>
          <span className="bar"></span>
          <span className="bar"></span>
          <span className="bar"></span>
        </div>
      </div>
    </nav>
  );
}
�# zk-steve/iden3-circom-btc-bench
# circuits/sha256_2/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/sha256/sha256.circom";

component main = Sha256(1024);
End File# zk-steve/iden3-circom-btc-bench
# circuits/poseidon_14/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/poseidon.circom";

component main = Poseidon(14);
End File# circuits/mimc_1/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/mimc.circom";

component main = MiMC7(1);
End Filepragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/poseidon.circom";

component main = Poseidon(12);
End File# circuits/sha256_1/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/sha256/sha256.circom";

component main = Sha256(512);
End File# README.md
# iden3-circom-btc-bench

This repository contains benchmark comparisons for the iden3 circom library. It includes various circuits with different parameter sizes and complexity levels, designed to test performance on Bitcoin Virtual Machine (BVM) instances.

## Repository Structure

The benchmarks are organized by circuit type:

### Merkle Tree Proofs
- `merkletreeproof_X/` - Merkle tree proof verification circuits
  - X represents the tree depth (10, 16, 20, 24, 28, 32)

### MiMC Hash Function
- `mimc_X/` - MiMC7 hash function circuits
  - X represents the number of inputs (1, 2, 4, 8, 16, 32)

### Poseidon Hash Function
- `poseidon_X/` - Poseidon hash function circuits
  - X represents the number of inputs (2, 4, 6, 8, 10, 12, 14, 16)

### SHA-256 Hash Function
- `sha256_X/` - SHA-256 hash function circuits
  - 1: 512-bit input
  - 2: 1024-bit input

## Benchmark Results

### Circuit Constraints
The number of constraints for each circuit type:

| Circuit | Constraints |
|---------|------------|
| mimc_1 | 31,355 |
| mimc_2 | 62,705 |
| mimc_4 | 125,405 |
| mimc_8 | 250,805 |
| mimc_16 | 501,605 |
| mimc_32 | 1,003,205 |
| poseidon_2 | 32 |
| poseidon_4 | 63 |
| poseidon_6 | 94 |
| poseidon_8 | 125 |
| poseidon_10 | 156 |
| poseidon_12 | 187 |
| poseidon_14 | 218 |
| poseidon_16 | 249 |
| merkletreeproof_10 | 315 |
| merkletreeproof_16 | 495 |
| merkletreeproof_20 | 615 |
| merkletreeproof_24 | 735 |
| merkletreeproof_28 | 855 |
| merkletreeproof_32 | 975 |
| sha256_1 | 27,906 |
| sha256_2 | 54,658 |

## Performance Comparison

### Bitcoin Virtual Machine (BVM) Instance Types

Tests were conducted on different BVM instance configurations:

**BVM-S1 (1 Core, 2GB RAM)**
- Baseline performance metrics
- Cost-effective for smaller circuits

**BVM-S2 (2 Cores, 4GB RAM)**
- Improved performance for medium circuits
- Better parallelization capabilities

**BVM-S3 (4 Cores, 8GB RAM)**
- Optimal for large constraint circuits
- Best performance for complex computations

### Key Findings

1. **Poseidon circuits** are extremely efficient with minimal constraints
2. **MiMC circuits** show linear constraint growth with input size
3. **SHA-256 circuits** have high constraint counts but consistent performance
4. **Merkle tree proofs** scale efficiently with tree depth
5. **Higher-tier BVM instances** provide significant performance improvements for constraint-heavy circuits

## Usage

Each circuit directory contains:
- `circuit.circom` - The circuit implementation
- Build and test scripts for performance evaluation

To run benchmarks:
```bash
cd circuits/[circuit_name]
# Follow specific circuit instructions
```

## Dependencies

- Node.js and npm
- Circom compiler
- SnarkJS for proof generation
- Appropriate BVM instance access

This benchmark suite provides comprehensive performance data for choosing the right circuit complexity and BVM instance configuration for zero-knowledge proof applications.
End File# circuits/mimc_16/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/mimc.circom";

component main = MiMC7(16);
End File# zk-steve/iden3-circom-btc-bench
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/poseidon.circom";

component main = Poseidon(6);
End File# zk-steve/iden3-circom-btc-bench
# circuits/merkletreeproof_32/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/smt/smtverifier.circom";

component main = SMTVerifier(32);
End File# zk-steve/iden3-circom-btc-bench
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/poseidon.circom";

component main = Poseidon(16);
End File# zk-steve/iden3-circom-btc-bench
# circuits/mimc_8/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/mimc.circom";

component main = MiMC7(8);
End Filepragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/smt/smtverifier.circom";

component main = SMTVerifier(20);
End File# circuits/poseidon_2/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/poseidon.circom";

component main = Poseidon(2);
End File# zk-steve/iden3-circom-btc-bench
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/smt/smtverifier.circom";

component main = SMTVerifier(10);
End File# circuits/mimc_32/circuit.circom
pragma circom 2.0.0;

include "../../node_modules/circomlib/circuits/mimc.circom";

component main = MiMC7(32);
�# DJFree123/Project
from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from .forms import RegistrationForm
from django.contrib.auth import logout

def index(request):
    """Index page"""
    
    return render(request, 'book_reviews/index.html')

def register(request):
    """Register a new user."""
    if request.method != 'POST':
        # Display blank registration form.
        form = RegistrationForm()
    else:
        # Process completed form.
        form = RegistrationForm(data=request.POST)
        
        if form.is_valid():
            new_user = form.save()
            # Log the user in and then redirect to home page.
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            new_user = authenticate(request, username=username, password=password)
            if new_user is not None:
                login(request, new_user)
                return redirect('book_reviews:index')  # Redirect to the index page
    
    # Display a blank or invalid form.
    context = {'form': form}
    return render(request, 'registration/register.html', context)

def custom_logout(request):
    logout(request)
    return redirect('book_reviews:index')End File# DJFree123/Project
# book_reviews/models.py
from django.db import models
from django.contrib.auth.models import User

class Book(models.Model):
    """A book about a particular topic."""
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200, default='Unknown Author')
    date_added = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        """Return a string representation of the model."""
        return self.title

class Review(models.Model):
    """A review of a book."""
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    text = models.TextField()
    rating = models.IntegerField(choices=[(i, str(i)) for i in range(1, 6)])  # 1 to 5 rating
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    
    class Meta:
        verbose_name_plural = 'Reviews'
        
    def __str__(self):
        """Return a string representation of the model."""
        return f"{self.text[:50]}..."
End File# DJFree123/Project
from django import forms
from .models import Book, Review
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author']
        labels = {'title': 'Book Title', 'author': 'Author'}

class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review
        fields = ['text', 'rating']
        labels = {'text': 'Review', 'rating': 'Rating'}
        widgets = {
            'text': forms.Textarea(attrs={'cols': 80, 'rows': 10}),
            'rating': forms.Select(choices=[(i, f'{i} Star{"s" if i != 1 else ""}') for i in range(1, 6)])
        }

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    
    class Meta:
        model = User
        fields = ["username", "email", "password1", "password2"]
    
    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return userEnd File# book_reviews/urls.py
"""Defines URL patterns for book_reviews"""

from django.urls import path
from . import views

app_name = 'book_reviews'
urlpatterns = [
    # Home page
    path('', views.index, name='index'),
    # Page that shows all books.
    path('books/', views.books, name='books'),
    # Detail page for a single book.
    path('books/<int:book_id>/', views.book, name='book'),
    # Page for adding a new book.
    path('new_book/', views.new_book, name='new_book'),
    # Page for adding a new review.
    path('new_review/<int:book_id>/', views.new_review, name='new_review'),
    # Page for editing a review.
    path('edit_review/<int:review_id>/', views.edit_review, name='edit_review'),
    # Registration page
    path('register/', views.register, name='register'),
    # Custom logout
    path('custom_logout/', views.custom_logout, name='custom_logout'),
]
End File# DJFree123/Project
# book_reviews/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from .models import Book, Review
from .forms import BookForm, ReviewForm, RegistrationForm
from django.db.models import Avg

def index(request):
    """The home page for Book Reviews."""
    return render(request, 'book_reviews/index.html')

@login_required
def books(request):
    """Show all books."""
    books = Book.objects.all().annotate(
        avg_rating=Avg('review__rating')
    ).order_by('date_added')
    
    context = {'books': books}
    return render(request, 'book_reviews/books.html', context)

@login_required
def book(request, book_id):
    """Show a single book and all its reviews."""
    book = get_object_or_404(Book, id=book_id)
    reviews = book.review_set.order_by('-date_added')
    
    # Calculate average rating
    avg_rating = reviews.aggregate(Avg('rating'))['rating__avg']
    if avg_rating:
        avg_rating = round(avg_rating, 1)
    
    context = {'book': book, 'reviews': reviews, 'avg_rating': avg_rating}
    return render(request, 'book_reviews/book.html', context)

@login_required
def new_book(request):
    """Add a new book."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = BookForm()
    else:
        # POST data submitted; process data.
        form = BookForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('book_reviews:books')
    
    # Display a blank or invalid form.
    context = {'form': form}
    return render(request, 'book_reviews/new_book.html', context)

@login_required
def new_review(request, book_id):
    """Add a new review for a particular book."""
    book = get_object_or_404(Book, id=book_id)
    
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = ReviewForm()
    else:
        # POST data submitted; process data.
        form = ReviewForm(data=request.POST)
        if form.is_valid():
            new_review = form.save(commit=False)
            new_review.book = book
            new_review.owner = request.user
            new_review.save()
            return redirect('book_reviews:book', book_id=book_id)
    
    # Display a blank or invalid form.
    context = {'book': book, 'form': form}
    return render(request, 'book_reviews/new_review.html', context)

@login_required
def edit_review(request, review_id):
    """Edit an existing review."""
    review = get_object_or_404(Review, id=review_id)
    book = review.book
    
    # Check if the review belongs to the current user
    if review.owner != request.user:
        raise Http404
    
    if request.method != 'POST':
        # Initial request; pre-fill form with the current review.
        form = ReviewForm(instance=review)
    else:
        # POST data submitted; process data.
        form = ReviewForm(instance=review, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('book_reviews:book', book_id=book.id)
    
    context = {'review': review, 'book': book, 'form': form}
    return render(request, 'book_reviews/edit_review.html', context)

def register(request):
    """Register a new user."""
    if request.method != 'POST':
        # Display blank registration form.
        form = RegistrationForm()
    else:
        # Process completed form.
        form = RegistrationForm(data=request.POST)
        
        if form.is_valid():
            new_user = form.save()
            # Log the user in and then redirect to home page.
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            new_user = authenticate(request, username=username, password=password)
            if new_user is not None:
                login(request, new_user)
                return redirect('book_reviews:index')  # Redirect to the index page
    
    # Display a blank or invalid form.
    context = {'form': form}
    return render(request, 'registration/register.html', context)

def custom_logout(request):
    logout(request)
    return redirect('book_reviews:index')
End File"""Defines URL patterns for users"""

from django.urls import path, include
from . import views

app_name = 'users'
urlpatterns = [
    # Include default auth urls.
    path('', include('django.contrib.auth.urls')),
    # Registration page.
    path('register/', views.register, name='register'),
]
�# Keshav-Vardhan-Gujjula/SQL_Retail_Sales_Analysis
CREATE DATABASE sql_project_p1;

CREATE TABLE retail_sales(
transactions_id INT PRIMARY KEY,
sale_date DATE,
sale_time TIME,
customer_id INT,
gender VARCHAR(15),
age INT,
category VARCHAR(15),
quantity INT,
price_per_unit FLOAT,
cogs FLOAT,
total_sale FLOAT
);

SELECT * FROM retail_sales
LIMIT 10

SELECT COUNT(*) FROM retail_sales

-- DATA CLEANING
SELECT * FROM retail_sales
WHERE transactions_id IS NULL

SELECT * FROM retail_sales
WHERE sale_date IS NULL

SELECT * FROM retail_sales
WHERE sale_time IS NULL

SELECT * FROM retail_sales
WHERE 
    transactions_id IS NULL
    OR
    sale_date IS NULL
    OR 
    sale_time IS NULL
    OR
    gender IS NULL
    OR
    category IS NULL
    OR
    quantity IS NULL
    OR
    cogs IS NULL
    OR
    total_sale IS NULL;

--

DELETE FROM retail_sales
WHERE 
    transactions_id IS NULL
    OR
    sale_date IS NULL
    OR 
    sale_time IS NULL
    OR
    gender IS NULL
    OR
    category IS NULL
    OR
    quantity IS NULL
    OR
    cogs IS NULL
    OR
    total_sale IS NULL;

-- Data Exploration

-- How many sales we have?
SELECT COUNT(*) as total_sale FROM retail_sales

-- How many uniuque customers we have ?

SELECT COUNT(DISTINCT customer_id) as total_sale FROM retail_sales

SELECT DISTINCT category FROM retail_sales

-- Data Analysis & Business Key Problems & Answers

-- My Analysis & Findings
-- Q.1 Write a SQL query to retrieve all columns for sales made on '2022-11-05

SELECT *
FROM retail_sales
WHERE sale_date = '2022-11-05'

-- Q.2 Write a SQL query to retrieve all transactions where the category is 'Clothing' and the quantity sold is more than 10 in the month of Nov-2022

SELECT 
  *
FROM retail_sales
WHERE 
    category = 'Clothing'
    AND 
    TO_CHAR(sale_date, 'YYYY-MM') = '2022-11'
    AND
    quantity >= 4

-- Q.3 Write a SQL query to calculate the total sales (total_sale) for each category.

SELECT 
    category,
    SUM(total_sale) as net_sale,
    COUNT(*) as total_orders
FROM retail_sales
GROUP BY 1

-- Q.4 Write a SQL query to find the average age of customers who purchased items from the 'Beauty' category.

SELECT
    ROUND(AVG(age), 2) as avg_age
FROM retail_sales
WHERE category = 'Beauty'

-- Q.5 Write a SQL query to find all transactions where the total_sale is greater than 1000.

SELECT * FROM retail_sales
WHERE total_sale > 1000

-- Q.6 Write a SQL query to find the total number of transactions (transaction_id) made by each gender in each category.

SELECT 
    category,
    gender,
    COUNT(*) as total_trans
FROM retail_sales
GROUP 
BY 
    category,
    gender
ORDER BY 1

-- Q.7 Write a SQL query to calculate the average sale for each month. Find out best selling month in each year

SELECT 
       year,
       month,
    avg_sale
FROM 
(    
SELECT 
    EXTRACT(YEAR FROM sale_date) as year,
    EXTRACT(MONTH FROM sale_date) as month,
    AVG(total_sale) as avg_sale,
    RANK() OVER(PARTITION BY EXTRACT(YEAR FROM sale_date) ORDER BY AVG(total_sale) DESC) as rank
FROM retail_sales
GROUP BY 1, 2
) as t1
WHERE rank = 1


-- Q.8 Write a SQL query to find the top 5 customers based on the highest total sales 

SELECT 
    customer_id,
    SUM(total_sale) as total_sales
FROM retail_sales
GROUP BY 1
ORDER BY 2 DESC
LIMIT 5

-- Q.9 Write a SQL query to find the number of unique customers who purchased items from each category.

SELECT 
    category,    
    COUNT(DISTINCT customer_id) as cnt_unique_cs
FROM retail_sales
GROUP BY category

-- Q.10 Write a SQL query to create each shift and number of orders (Example Morning <=12, Afternoon Between 12 & 17, Evening >17)

WITH hourly_sale
AS
(
SELECT *,
    CASE
        WHEN EXTRACT(HOUR FROM sale_time) < 12 THEN 'Morning'
        WHEN EXTRACT(HOUR FROM sale_time) BETWEEN 12 AND 17 THEN 'Afternoon'
        ELSE 'Evening'
    END as shift
FROM retail_sales
)
SELECT 
    shift,
    COUNT(*) as total_orders    
FROM hourly_sale
GROUP BY shift

-- End of project


-- Q.11 Which product category generates the most revenue?

SELECT category, SUM(total_sale) AS total_revenue
FROM retail_sales
GROUP BY category
ORDER BY total_revenue DESC
LIMIT 1;

-- Q.12 What is the top-selling product category for each gender?

WITH gender_category_sales AS (
    SELECT gender, category, SUM(total_sale) AS total_revenue
    FROM retail_sales
    GROUP BY gender, category
),
ranked_categories AS (
    SELECT *, 
           RANK() OVER (PARTITION BY gender ORDER BY total_revenue DESC) AS rank
    FROM gender_category_sales
)
SELECT gender, category, total_revenue
FROM ranked_categories
WHERE rank = 1;

-- Q.13 What is the seasonal trend in sales?
-- Assuming seasons: Spring (Mar-May), Summer (Jun-Aug), Fall (Sep-Nov), Winter (Dec-Feb)

WITH seasonal_sales AS (
    SELECT 
        CASE 
            WHEN EXTRACT(MONTH FROM sale_date) IN (3, 4, 5) THEN 'Spring'
            WHEN EXTRACT(MONTH FROM sale_date) IN (6, 7, 8) THEN 'Summer'
            WHEN EXTRACT(MONTH FROM sale_date) IN (9, 10, 11) THEN 'Fall'
            ELSE 'Winter'
        END AS season,
        total_sale
    FROM retail_sales
)
SELECT season, 
       SUM(total_sale) AS total_sales,
       AVG(total_sale) AS avg_sales,
       COUNT(*) AS total_transactions
FROM seasonal_sales
GROUP BY season
ORDER BY total_sales DESC;

-- Q.14 Which age group spends the most?

WITH age_groups AS (
    SELECT 
        CASE 
            WHEN age < 25 THEN '18-24'
            WHEN age BETWEEN 25 AND 34 THEN '25-34'
            WHEN age BETWEEN 35 AND 44 THEN '35-44'
            WHEN age BETWEEN 45 AND 54 THEN '45-54'
            ELSE '55+'
        END AS age_group,
        total_sale
    FROM retail_sales
)
SELECT age_group, 
       SUM(total_sale) AS total_spending,
       AVG(total_sale) AS avg_spending,
       COUNT(*) AS total_transactions
FROM age_groups
GROUP BY age_group
ORDER BY total_spending DESC;

-- Q.15 What is the average transaction value by category and gender?

SELECT category, 
       gender, 
       AVG(total_sale) AS avg_transaction_value,
       COUNT(*) AS transaction_count
FROM retail_sales
GROUP BY category, gender
ORDER BY category, avg_transaction_value DESC;

-- Q.16 Which customers have the highest purchase frequency?

SELECT customer_id, 
       COUNT(*) AS purchase_frequency,
       SUM(total_sale) AS total_spent,
       AVG(total_sale) AS avg_per_transaction
FROM retail_sales
GROUP BY customer_id
ORDER BY purchase_frequency DESC
LIMIT 10;

-- Q.17 What is the profit margin analysis by category? (Using total_sale - cogs)

SELECT category,
       SUM(total_sale) AS total_revenue,
       SUM(cogs) AS total_cost,
       SUM(total_sale - cogs) AS total_profit,
       ROUND((SUM(total_sale - cogs) / SUM(total_sale)) * 100, 2) AS profit_margin_percent
FROM retail_sales
GROUP BY category
ORDER BY profit_margin_percent DESC;

-- Q.18 How do sales vary by time of day?

WITH hourly_sales AS (
    SELECT 
        EXTRACT(HOUR FROM sale_time) AS hour,
        total_sale
    FROM retail_sales
)
SELECT hour,
       SUM(total_sale) AS total_sales,
       AVG(total_sale) AS avg_sales,
       COUNT(*) AS total_transactions
FROM hourly_sales
GROUP BY hour
ORDER BY hour;

-- Q.19 What is the customer retention rate? (Customers who made purchases in multiple months)

WITH customer_months AS (
    SELECT customer_id,
           TO_CHAR(sale_date, 'YYYY-MM') AS month,
           COUNT(*) AS transactions
    FROM retail_sales
    GROUP BY customer_id, TO_CHAR(sale_date, 'YYYY-MM')
),
customer_activity AS (
    SELECT customer_id,
           COUNT(DISTINCT month) AS active_months
    FROM customer_months
    GROUP BY customer_id
)
SELECT 
    CASE 
        WHEN active_months = 1 THEN 'One-time customers'
        WHEN active_months BETWEEN 2 AND 3 THEN 'Regular customers'
        ELSE 'Loyal customers'
    END AS customer_type,
    COUNT(*) AS customer_count,
    ROUND((COUNT(*) * 100.0 / SUM(COUNT(*)) OVER ()), 2) AS percentage
FROM customer_activity
GROUP BY 
    CASE 
        WHEN active_months = 1 THEN 'One-time customers'
        WHEN active_months BETWEEN 2 AND 3 THEN 'Regular customers'
        ELSE 'Loyal customers'
    END
ORDER BY customer_count DESC;

-- Q.20 What is the price sensitivity analysis? (Relationship between price_per_unit and quantity)

WITH price_ranges AS (
    SELECT 
        CASE 
            WHEN price_per_unit < 50 THEN 'Low (< $50)'
            WHEN price_per_unit BETWEEN 50 AND 100 THEN 'Medium ($50-$100)'
            WHEN price_per_unit BETWEEN 100 AND 200 THEN 'High ($100-$200)'
            ELSE 'Premium (> $200)'
        END AS price_range,
        quantity,
        total_sale
    FROM retail_sales
)
SELECT price_range,
       AVG(quantity) AS avg_quantity_sold,
       SUM(total_sale) AS total_revenue,
       COUNT(*) AS transaction_count
FROM price_ranges
GROUP BY price_range
ORDER BY 
    CASE price_range 
        WHEN 'Low (< $50)' THEN 1
        WHEN 'Medium ($50-$100)' THEN 2
        WHEN 'High ($100-$200)' THEN 3
        ELSE 4
    END;


-- End of extended analysis
�import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './src/screens/HomeScreen';
import SignInScreen from './src/screens/SignInScreen';
import CadastroScreen from './src/screens/CadastroScreen';

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
    <Stack.Navigator initialRouteName='Home'>
      <Stack.Screen name="Home" component={HomeScreen}/>
      <Stack.Screen name="SignIn" component={SignInScreen}/>
      <Stack.Screen name="Cadastro" component={CadastroScreen}/>
    </Stack.Navigator>
  </NavigationContainer>
  );
}
End Fileimport React from "react"
import { View, Text, TextInput, TouchableOpacity, StyleSheet, SafeAreaView } from 'react-native'

const SignInScreen = ({ navigation }) => {

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.box}>
                <Text style={styles.title}>Log In</Text>
                <TextInput style={styles.input}
                    placeholder="E-mail"
                    keyboardType="email-address"
                />
                <TextInput style={styles.input}
                    placeholder="Senha"
                    secureTextEntry={true}
                />
                <TouchableOpacity style={styles.button}>
                    <Text style={styles.buttonText}>
                        Entrar
                    </Text>
                </TouchableOpacity>

                <TouchableOpacity onPress={() => navigation.navigate('Cadastro')}>
                    <Text style={styles.link}>Não tem uma conta? Cadastre-se aqui</Text>
                </TouchableOpacity>
            </View>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#120a8f',
    },
    box: {
        width: '80%',
        backgroundColor: '#fff',
        borderRadius: 8,
        padding: 20,
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5,
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 20,
        textAlign: 'center',
        color: '#333',
    },
    input: {
        backgroundColor: '#f5f5f5',
        borderRadius: 8,
        padding: 15,
        marginBottom: 15,
        fontSize: 16,
        borderWidth: 1,
        borderColor: '#ddd',
    },
    button: {
        backgroundColor: '#120a8f',
        borderRadius: 8,
        padding: 15,
        alignItems: 'center',
        marginBottom: 15,
    },
    buttonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    link: {
        textAlign: 'center',
        color: '#120a8f',
        fontSize: 14,
        textDecorationLine: 'underline',
    },
});

export default SignInScreen
End Fileimport React from 'react'
import { View, Text, StyleSheet, TouchableOpacity, SafeAreaView } from 'react-native';

const HomeScreen = ({navigation}) => {
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        <Text style={styles.title}>Bem vindo(a)!</Text>
        <Text style={styles.subtitle}>Faça o login para acessar a aplicação</Text>
        
        <TouchableOpacity 
          style={styles.button}
          onPress={() => navigation.navigate('SignIn')}
        >
          <Text style={styles.buttonText}>Fazer Login</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#120a8f',
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 30,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 20,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    color: '#e0e0e0',
    marginBottom: 40,
    textAlign: 'center',
    lineHeight: 22,
  },
  button: {
    backgroundColor: '#fff',
    paddingVertical: 15,
    paddingHorizontal: 40,
    borderRadius: 25,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  buttonText: {
    color: '#120a8f',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default HomeScreen;
End Fileimport React from "react"
import { View, Text, TextInput, TouchableOpacity, StyleSheet, SafeAreaView } from 'react-native'

const CadastroScreen = ({ navigation }) => {

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.box}>
                <Text style={styles.title}>Cadastre-se</Text>
                
                <TextInput style={styles.input}
                    placeholder="Nome completo"
                />
                
                <TextInput style={styles.input}
                    placeholder="E-mail"
                    keyboardType="email-address"
                />
                
                <TextInput style={styles.input}
                    placeholder="Senha"
                    secureTextEntry={true}
                />
                
                <TextInput style={styles.input}
                    placeholder="Confirmar senha"
                    secureTextEntry={true}
                />
                
                <TouchableOpacity style={styles.button}>
                    <Text style={styles.buttonText}>
                        Cadastrar
                    </Text>
                </TouchableOpacity>

                <TouchableOpacity onPress={() => navigation.navigate('SignIn')}>
                    <Text style={styles.link}>Já tem uma conta? Faça login aqui</Text>
                </TouchableOpacity>
            </View>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#120a8f',
    },
    box: {
        width: '80%',
        backgroundColor: '#fff',
        borderRadius: 8,
        padding: 20,
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5,
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 20,
        textAlign: 'center',
        color: '#333',
    },
    input: {
        backgroundColor: '#f5f5f5',
        borderRadius: 8,
        padding: 15,
        marginBottom: 15,
        fontSize: 16,
        borderWidth: 1,
        borderColor: '#ddd',
    },
    button: {
        backgroundColor: '#120a8f',
        borderRadius: 8,
        padding: 15,
        alignItems: 'center',
        marginBottom: 15,
    },
    buttonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    link: {
        textAlign: 'center',
        color: '#120a8f',
        fontSize: 14,
        textDecorationLine: 'underline',
    },
});

export default CadastroScreen
�# NielsOuvrard/workshop_C
# part3/ex02/my_sokoban.h
/*
** EPITECH PROJECT, 2023
** my_sokoban.h
** File description:
** my_sokoban.h
*/

#ifndef __MY_SOKOBAN_H__
    #define __MY_SOKOBAN_H__

void my_putchar(char c);
int my_putstr(char const *str);
void my_put_nbr(int nb);
char *my_strdup(char const *src);
int my_strlen(char const *str);
int my_getnbr(char const *str);

#endif
End File# NielsOuvrard/workshop_C
# part3/ex02/my_sokoban.c
/*
** EPITECH PROJECT, 2023
** my_sokoban.c
** File description:
** my_sokoban.c
*/

#include "my_sokoban.h"
#include <ncurses.h>

void draw_map(char **map)
{
    for (int i = 0; map[i]; i++) {
        mvprintw(i, 0, map[i]);
    }
    refresh();
}

int my_sokoban(char **map)
{
    int ch;

    initscr();
    keypad(stdscr, TRUE);
    noecho();
    draw_map(map);
    while ((ch = getch()) != 'q') {
        draw_map(map);
    }
    endwin();
    return 0;
}
End File# NielsOuvrard/workshop_C
/*
** EPITECH PROJECT, 2023
** my_sokoban.c
** File description:
** my_sokoban.c
*/

#include "my_sokoban.h"
#include <ncurses.h>
#include <unistd.h>
#include <stdlib.h>

void draw_map(char **map)
{
    clear();
    for (int i = 0; map[i]; i++) {
        mvprintw(i, 0, map[i]);
    }
    refresh();
}

int move_is_valid(char **map, int y, int x)
{
    if (map[y][x] == '#')
        return 0;
    return 1;
}

int move_player(char **map, int y, int x, int dy, int dx)
{
    int ny = y + dy;
    int nx = x + dx;

    if (!move_is_valid(map, ny, nx))
        return 0;
    if (map[ny][nx] == 'X') {
        int nny = ny + dy;
        int nnx = nx + dx;
        if (!move_is_valid(map, nny, nnx) || map[nny][nnx] == 'X')
            return 0;
        map[nny][nnx] = 'X';
    }
    map[y][x] = ' ';
    map[ny][nx] = 'P';
    return 1;
}

void get_player_pos(char **map, int *y, int *x)
{
    for (int i = 0; map[i]; i++) {
        for (int j = 0; map[i][j]; j++) {
            if (map[i][j] == 'P') {
                *y = i;
                *x = j;
                return;
            }
        }
    }
}

int my_sokoban(char **map)
{
    int ch, y, x;

    initscr();
    keypad(stdscr, TRUE);
    noecho();
    draw_map(map);
    while ((ch = getch()) != 'q') {
        get_player_pos(map, &y, &x);
        if (ch == KEY_UP)
            move_player(map, y, x, -1, 0);
        if (ch == KEY_DOWN)
            move_player(map, y, x, 1, 0);
        if (ch == KEY_LEFT)
            move_player(map, y, x, 0, -1);
        if (ch == KEY_RIGHT)
            move_player(map, y, x, 0, 1);
        draw_map(map);
    }
    endwin();
    return 0;
}
End File# NielsOuvrard/workshop_C
/*
** EPITECH PROJECT, 2023
** my_sokoban.c
** File description:
** my_sokoban.c
*/

#include "my_sokoban.h"
#include <ncurses.h>
#include <unistd.h>
#include <stdlib.h>

void draw_map(char **map, char **original_map)
{
    clear();
    for (int i = 0; map[i]; i++) {
        for (int j = 0; map[i][j]; j++) {
            if (map[i][j] == ' ' && original_map[i][j] == 'O')
                mvaddch(i, j, 'O');
            else if (map[i][j] == 'X' && original_map[i][j] == 'O')
                mvaddch(i, j, 'X' | A_BLINK);
            else
                mvaddch(i, j, map[i][j]);
        }
    }
    refresh();
}

int move_is_valid(char **map, int y, int x)
{
    if (map[y][x] == '#')
        return 0;
    return 1;
}

int move_player(char **map, int y, int x, int dy, int dx)
{
    int ny = y + dy;
    int nx = x + dx;

    if (!move_is_valid(map, ny, nx))
        return 0;
    if (map[ny][nx] == 'X') {
        int nny = ny + dy;
        int nnx = nx + dx;
        if (!move_is_valid(map, nny, nnx) || map[nny][nnx] == 'X')
            return 0;
        map[nny][nnx] = 'X';
    }
    map[y][x] = ' ';
    map[ny][nx] = 'P';
    return 1;
}

void get_player_pos(char **map, int *y, int *x)
{
    for (int i = 0; map[i]; i++) {
        for (int j = 0; map[i][j]; j++) {
            if (map[i][j] == 'P') {
                *y = i;
                *x = j;
                return;
            }
        }
    }
}

char **copy_map(char **map)
{
    int nb_lines = 0;
    char **copy;

    while (map[nb_lines])
        nb_lines++;
    copy = malloc(sizeof(char *) * (nb_lines + 1));
    for (int i = 0; i < nb_lines; i++)
        copy[i] = my_strdup(map[i]);
    copy[nb_lines] = NULL;
    return copy;
}

int is_win(char **map, char **original_map)
{
    for (int i = 0; map[i]; i++) {
        for (int j = 0; map[i][j]; j++) {
            if (original_map[i][j] == 'O' && map[i][j] != 'X')
                return 0;
        }
    }
    return 1;
}

int my_sokoban(char **map)
{
    int ch, y, x;
    char **original_map = copy_map(map);

    initscr();
    keypad(stdscr, TRUE);
    noecho();
    draw_map(map, original_map);
    while ((ch = getch()) != 'q') {
        get_player_pos(map, &y, &x);
        if (ch == KEY_UP)
            move_player(map, y, x, -1, 0);
        if (ch == KEY_DOWN)
            move_player(map, y, x, 1, 0);
        if (ch == KEY_LEFT)
            move_player(map, y, x, 0, -1);
        if (ch == KEY_RIGHT)
            move_player(map, y, x, 0, 1);
        draw_map(map,

Siyah Karınca Yuvas'use client' import React from 'react'; import { FaSearch, FaBell, FaUser } from 'react-icons/fa'; const Header = () => { return ( <header className="bg-white shadow-md px-6 py-4"> <div className="flex items-center justify-between"> {/* Search Bar */} <div className="relative flex-1 max-w-lg"> <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" /> <input type="text" placeholder="Search..." className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" /> </div> {/* Right side icons */} <div className="flex items-center space-x-4"> {/* Notifications */} <button className="relative p-2 text-gray-600 hover:bg-gray-100 rounded-lg"> <FaBell size={20} /> <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center"> 3 </span> </button> {/* User Profile */} <button className="flex items-center space-x-2 p-2 text-gray-600 hover:bg-gray-100 rounded-lg"> <FaUser size={20} /> <span className="font-medium">Admin</span> </button> </div> </div> </header> ); }; export default Header; 'use client' import React from 'react'; import { FaDashboard, FaShoppingBag, FaBox, FaUsers, FaChartBar, FaCog, FaSignOutAlt } from 'react-icons/fa'; import Link from 'next/link'; import { usePathname } from 'next/navigation'; const Sidebar = () => { const pathname = usePathname(); const menuItems = [ { icon: FaDashboard, label: 'Dashboard', path: '/dashboard' }, { icon: FaShoppingBag, label: 'Orders', path: '/dashboard/orders' }, { icon: FaBox, label: 'Products', path: '/dashboard/products' }, { icon: FaUsers, label: 'Customers', path: '/dashboard/customers' }, { icon: FaChartBar, label: 'Analytics', path: '/dashboard/analytics' }, { icon: FaCog, label: 'Settings', path: '/dashboard/settings' }, ]; return ( <div className="bg-gray-900 text-white w-64 min-h-screen flex flex-col"> {/* Logo */} <div className="p-6 border-b border-gray-700"> <h1 className="text-2xl font-bold text-blue-400">AdminPanel</h1> </div> {/* Navigation */} <nav className="flex-1 px-4 py-6"> <ul className="space-y-2"> {menuItems.map((item, index) => { const Icon = item.icon; const isActive = pathname === item.path; return ( <li key={index}> <Link href={item.path} className={`flex items-center space-x-3 px-4 py-3 rounded-lg transition-colors ${ isActive ? 'bg-blue-600 text-white' : 'text-gray-300 hover:bg-gray-800 hover:text-white' }`} > <Icon size={20} /> <span>{item.label}</span> </Link> </li> ); })} </ul> </nav> {/* Logout */} <div className="p-4 border-t border-gray-700"> <button className="flex items-center space-x-3 px-4 py-3 text-gray-300 hover:bg-gray-800 hover:text-white rounded-lg transition-colors w-full"> <FaSignOutAlt size={20} /> <span>Logout</span> </button> </div> </div> ); }; export default Sidebar; # src/components/dashboard/StatsCard.js 'use client' import React from 'react'; const StatsCard = ({ title, value, change, icon: Icon, color = 'blue' }) => { const colorClasses = { blue: 'bg-blue-500', green: 'bg-green-500', yellow: 'bg-yellow-500', red: 'bg-red-500', purple: 'bg-purple-500', }; const isPositive = change > 0; return ( <div className="bg-white rounded-lg shadow-md p-6"> <div className="flex items-center justify-between"> <div> <p className="text-sm font-medium text-gray-600 mb-1">{title}</p> <p className="text-3xl font-bold text-gray-900">{value}</p> <div className="flex items-center mt-2"> <span className={`text-sm font-medium ${isPositive ? 'text-green-600' : 'text-red-600'}`}> {isPositive ? '+' : ''}{change}% </span> <span className="text-sm text-gray-500 ml-2">vs last month</span> </div> </div> <div className={`${colorClasses[color]} p-3 rounded-full`}> <Icon className="text-white" size={24} /> </div> </div> </div> ); }; export default StatsCard; 'use client' import React from 'react'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, BarElement, } from 'chart.js'; import { Line, Bar } from 'react-chartjs-2'; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, BarElement, Title, Tooltip, Legend ); export const LineChart = ({ data, title }) => { const options = { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: title, }, }, scales: { y: { beginAtZero: true, }, }, }; return <Line data={data} options={options} />; }; export const BarChart = ({ data, title }) => { const options = { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: title, }, }, scales: { y: { beginAtZero: true, }, }, }; return <Bar data={data} options={options} />; }; # src/app/dashboard/page.js 'use client' import React from 'react'; import { FaShoppingCart, FaDollarSign, FaUsers, FaBox, FaTrendingUp, FaTrendingDown } from 'react-icons/fa'; import StatsCard from '@/components/dashboard/StatsCard'; import { LineChart, BarChart } from '@/components/dashboard/Charts'; const Dashboard = () => { // Sample data for charts const salesData = { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], datasets: [ { label: 'Sales ($)', data: [12000, 19000, 15000, 25000, 22000, 30000], borderColor: 'rgb(59, 130, 246)', backgroundColor: 'rgba(59, 130, 246, 0.1)', tension: 0.4, }, ], }; const ordersData = { labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], datasets: [ { label: 'Orders', data: [65, 80, 90, 81, 56, 85, 40], backgroundColor: 'rgba(34, 197, 94, 0.8)', }, ], }; // Recent orders data const recentOrders = [ { id: '#1234', customer: 'John Doe', amount: '$129.99', status: 'Completed' }, { id: '#1235', customer: 'Jane Smith', amount: '$89.50', status: 'Pending' }, { id: '#1236', customer: 'Mike Johnson', amount: '$199.99', status: 'Processing' }, { id: '#1237', customer: 'Sarah Wilson', amount: '$59.99', status: 'Completed' }, { id: '#1238', customer: 'Tom Brown', amount: '$299.99', status: 'Shipped' }, ]; const getStatusColor = (status) => { switch (status) { case 'Completed': return 'bg-green-100 text-green-800'; case 'Pending': return 'bg-yellow-100 text-yellow-800'; case 'Processing': return 'bg-blue-100 text-blue-800'; case 'Shipped': return 'bg-purple-100 text-purple-800'; default: return 'bg-gray-100 text-gray-800'; } }; return ( <div className="p-6 bg-gray-50 min-h-screen"> <div className="mb-8"> <h1 className="text-3xl font-bold text-gray-900">Dashboard</h1> <p className="text-gray-600 mt-2">Welcome back! Here's what's happening with your store.</p> </div> {/* Stats Cards */} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8"> <StatsCard title="Total Revenue" value="$45,231" change={12.5} icon={FaDollarSign} color="green" /> <StatsCard title="Total Orders" value="1,234" change={8.2} icon={FaShoppingCart} color="blue" /> <StatsCard title="Total Customers" value="892" change={-2.4} icon={FaUsers} color="purple" /> <StatsCard title="Total Products" value="156" change={5.7} icon={FaBox} color="yellow" /> </div> {/* Charts */} <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8"> <div className="bg-white p-6 rounded-lg shadow-md"> <LineChart data={salesData} title="Sales Overview" /> </div> <div className="bg-white p-6 rounded-lg shadow-md"> <BarChart data={ordersData} title="Weekly Orders" /> </div> </div> {/* Recent Activity */} <div className="grid grid-cols-1 lg:grid-cols-3 gap-6"> {/* Recent Orders */} <div className="lg:col-span-2 bg-white rounded-lg shadow-md p-6"> <div className="flex items-center justify-between mb-6"> <h2 className="text-xl font-bold text-gray-900">Recent Orders</h2> <button className="text-blue-600 hover:text-blue-800 font-medium">View All</button> </div> <div className="overflow-x-auto"> <table className="w-full"> <thead> <tr className="border-b border-gray-200"> <th className="text-left py-3 px-4 font-medium text-gray-600">Order ID</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Customer</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Amount</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th> </tr> </thead> <tbody> {recentOrders.map((order, index) => ( <tr key={index} className="border-b border-gray-100"> <td className="py-3 px-4 font-mono text-sm">{order.id}</td> <td className="py-3 px-4">{order.customer}</td> <td className="py-3 px-4 font-medium">{order.amount}</td> <td className="py-3 px-4"> <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(order.status)}`}> {order.status} </span> </td> </tr> ))} </tbody> </table> </div> </div> {/* Quick Actions */} <div className="bg-white rounded-lg shadow-md p-6"> <h2 className="text-xl font-bold text-gray-900 mb-6">Quick Actions</h2> <div className="space-y-4"> <button className="w-full bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors"> Add New Product </button> <button className="w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 transition-colors"> Process Orders </button> <button className="w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 transition-colors"> View Reports </button> <button className="w-full border border-gray-300 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-50 transition-colors"> Settings </button> </div> </div> </div> </div> ); }; export default Dashboard; # chaitanya-000/admin-dashboard 'use client' import React, { useState } from 'react'; import { FaPlus, FaSearch, FaEdit, FaTrash, FaEye } from 'react-icons/fa'; const Products = () => { const [searchTerm, setSearchTerm] = useState(''); const [products, setProducts] = useState([ { id: 1, name: 'iPhone 14 Pro', category: 'Electronics', price: 999.99, stock: 45, status: 'Active', image: '/api/placeholder/50/50' }, { id: 2, name: 'MacBook Air M2', category: 'Electronics', price: 1299.99, stock: 23, status: 'Active', image: '/api/placeholder/50/50' }, { id: 3, name: 'AirPods Pro', category: 'Electronics', price: 249.99, stock: 0, status: 'Out of Stock', image: '/api/placeholder/50/50' }, { id: 4, name: 'Samsung Galaxy S23', category: 'Electronics', price: 899.99, stock: 67, status: 'Active', image: '/api/placeholder/50/50' }, { id: 5, name: 'iPad Pro', category: 'Electronics', price: 1099.99, stock: 34, status: 'Active', image: '/api/placeholder/50/50' }, ]); const filteredProducts = products.filter(product => product.name.toLowerCase().includes(searchTerm.toLowerCase()) || product.category.toLowerCase().includes(searchTerm.toLowerCase()) ); const getStatusColor = (status) => { switch (status) { case 'Active': return 'bg-green-100 text-green-800'; case 'Out of Stock': return 'bg-red-100 text-red-800'; case 'Inactive': return 'bg-gray-100 text-gray-800'; default: return 'bg-gray-100 text-gray-800'; } }; const getStockColor = (stock) => { if (stock === 0) return 'text-red-600'; if (stock < 20) return 'text-yellow-600'; return 'text-green-600'; }; return ( <div className="p-6 bg-gray-50 min-h-screen"> {/* Header */} <div className="mb-8"> <h1 className="text-3xl font-bold text-gray-900">Products</h1> <p className="text-gray-600 mt-2">Manage your product inventory</p> </div> {/* Controls */} <div className="bg-white rounded-lg shadow-md p-6 mb-6"> <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0"> {/* Search */} <div className="relative"> <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" /> <input type="text" placeholder="Search products..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full md:w-80" /> </div> {/* Actions */} <div className="flex items-center space-x-4"> <select className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"> <option>All Categories</option> <option>Electronics</option> <option>Clothing</option> <option>Books</option> </select> <button className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center space-x-2"> <FaPlus /> <span>Add Product</span> </button> </div> </div> </div> {/* Products Table */} <div className="bg-white rounded-lg shadow-md"> <div className="p-6"> <div className="overflow-x-auto"> <table className="w-full"> <thead> <tr className="border-b border-gray-200"> <th className="text-left py-3 px-4 font-medium text-gray-600">Product</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Category</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Price</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Stock</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Actions</th> </tr> </thead> <tbody> {filteredProducts.map((product) => ( <tr key={product.id} className="border-b border-gray-100 hover:bg-gray-50"> <td className="py-4 px-4"> <div className="flex items-center space-x-3"> <div className="w-12 h-12 bg-gray-200 rounded-lg"></div> <div> <div className="font-medium text-gray-900">{product.name}</div> <div className="text-sm text-gray-500">ID: #{product.id}</div> </div> </div> </td> <td className="py-4 px-4 text-gray-700">{product.category}</td> <td className="py-4 px-4 font-medium">${product.price}</td> <td className="py-4 px-4"> <span className={`font-medium ${getStockColor(product.stock)}`}> {product.stock} </span> </td> <td className="py-4 px-4"> <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(product.status)}`}> {product.status} </span> </td> <td className="py-4 px-4"> <div className="flex items-center space-x-2"> <button className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg"> <FaEye size={16} /> </button> <button className="p-2 text-green-600 hover:bg-green-100 rounded-lg"> <FaEdit size={16} /> </button> <button className="p-2 text-red-600 hover:bg-red-100 rounded-lg"> <FaTrash size={16} /> </button> </div> </td> </tr> ))} </tbody> </table> </div> {/* Pagination */} <div className="flex items-center justify-between mt-6"> <div className="text-sm text-gray-700"> Showing <span className="font-medium">1</span> to <span className="font-medium">5</span> of{' '} <span className="font-medium">{products.length}</span> results </div> <div className="flex items-center space-x-2"> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"> Previous </button> <button className="px-3 py-2 bg-blue-600 text-white rounded-lg">1</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">2</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">3</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"> Next </button> </div> </div> </div> </div> </div> ); }; export default Products; 'use client' import React, { useState } from 'react'; import { FaSearch, FaFilter, FaDownload, FaEye } from 'react-icons/fa'; const Orders = () => { const [searchTerm, setSearchTerm] = useState(''); const [statusFilter, setStatusFilter] = useState('All'); const orders = [ { id: '#1234', customer: 'John Doe', email: 'john@example.com', total: '$129.99', status: 'Completed', date: '2024-01-15', items: 3 }, { id: '#1235', customer: 'Jane Smith', email: 'jane@example.com', total: '$89.50', status: 'Pending', date: '2024-01-14', items: 2 }, { id: '#1236', customer: 'Mike Johnson', email: 'mike@example.com', total: '$199.99', status: 'Processing', date: '2024-01-14', items: 1 }, { id: '#1237', customer: 'Sarah Wilson', email: 'sarah@example.com', total: '$59.99', status: 'Shipped', date: '2024-01-13', items: 4 }, { id: '#1238', customer: 'Tom Brown', email: 'tom@example.com', total: '$299.99', status: 'Completed', date: '2024-01-13', items: 2 }, { id: '#1239', customer: 'Lisa Davis', email: 'lisa@example.com', total: '$149.99', status: 'Cancelled', date: '2024-01-12', items: 1 } ]; const filteredOrders = orders.filter(order => { const matchesSearch = order.customer.toLowerCase().includes(searchTerm.toLowerCase()) || order.id.toLowerCase().includes(searchTerm.toLowerCase()) || order.email.toLowerCase().includes(searchTerm.toLowerCase()); const matchesStatus = statusFilter === 'All' || order.status === statusFilter; return matchesSearch && matchesStatus; }); const getStatusColor = (status) => { switch (status) { case 'Completed': return 'bg-green-100 text-green-800'; case 'Pending': return 'bg-yellow-100 text-yellow-800'; case 'Processing': return 'bg-blue-100 text-blue-800'; case 'Shipped': return 'bg-purple-100 text-purple-800'; case 'Cancelled': return 'bg-red-100 text-red-800'; default: return 'bg-gray-100 text-gray-800'; } }; // Calculate summary statistics const totalOrders = orders.length; const completedOrders = orders.filter(order => order.status === 'Completed').length; const pendingOrders = orders.filter(order => order.status === 'Pending').length; const totalRevenue = orders .filter(order => order.status === 'Completed') .reduce((sum, order) => sum + parseFloat(order.total.replace('$', '')), 0); return ( <div className="p-6 bg-gray-50 min-h-screen"> {/* Header */} <div className="mb-8"> <h1 className="text-3xl font-bold text-gray-900">Orders</h1> <p className="text-gray-600 mt-2">Manage and track your orders</p> </div> {/* Summary Cards */} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8"> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">Total Orders</h3> <p className="text-3xl font-bold text-gray-900">{totalOrders}</p> </div> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">Completed</h3> <p className="text-3xl font-bold text-green-600">{completedOrders}</p> </div> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">Pending</h3> <p className="text-3xl font-bold text-yellow-600">{pendingOrders}</p> </div> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">Revenue</h3> <p className="text-3xl font-bold text-blue-600">${totalRevenue.toFixed(2)}</p> </div> </div> {/* Controls */} <div className="bg-white rounded-lg shadow-md p-6 mb-6"> <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0"> {/* Search */} <div className="relative"> <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" /> <input type="text" placeholder="Search orders..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full md:w-80" /> </div> {/* Filters and Actions */} <div className="flex items-center space-x-4"> <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="All">All Status</option> <option value="Pending">Pending</option> <option value="Processing">Processing</option> <option value="Shipped">Shipped</option> <option value="Completed">Completed</option> <option value="Cancelled">Cancelled</option> </select> <button className="flex items-center space-x-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"> <FaDownload /> <span>Export</span> </button> </div> </div> </div> {/* Orders Table */} <div className="bg-white rounded-lg shadow-md"> <div className="p-6"> <div className="overflow-x-auto"> <table className="w-full"> <thead> <tr className="border-b border-gray-200"> <th className="text-left py-3 px-4 font-medium text-gray-600">Order ID</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Customer</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Date</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Items</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Total</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Actions</th> </tr> </thead> <tbody> {filteredOrders.map((order, index) => ( <tr key={index} className="border-b border-gray-100 hover:bg-gray-50"> <td className="py-4 px-4 font-mono text-sm font-medium">{order.id}</td> <td className="py-4 px-4"> <div> <div className="font-medium text-gray-900">{order.customer}</div> <div className="text-sm text-gray-500">{order.email}</div> </div> </td> <td className="py-4 px-4 text-gray-700">{order.date}</td> <td className="py-4 px-4 text-gray-700">{order.items}</td> <td className="py-4 px-4 font-medium">{order.total}</td> <td className="py-4 px-4"> <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(order.status)}`}> {order.status} </span> </td> <td className="py-4 px-4"> <button className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg"> <FaEye size={16} /> </button> </td> </tr> ))} </tbody> </table> </div> {/* Pagination */} <div className="flex items-center justify-between mt-6"> <div className="text-sm text-gray-700"> Showing <span className="font-medium">1</span> to <span className="font-medium">{filteredOrders.length}</span> of{' '} <span className="font-medium">{orders.length}</span> results </div> <div className="flex items-center space-x-2"> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"> Previous </button> <button className="px-3 py-2 bg-blue-600 text-white rounded-lg">1</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">2</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">3</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"> Next </button> </div> </div> </div> </div> </div> ); }; export default Orders; # chaitanya-000/admin-dashboard import React from 'react'; import Sidebar from '@/components/layout/Sidebar'; import Header from '@/components/layout/Header'; const DashboardLayout = ({ children }) => { return ( <div className="flex h-screen bg-gray-100"> <Sidebar /> <div className="flex-1 flex flex-col overflow-hidden"> <Header /> <main className="flex-1 overflow-x-hidden overflow-y-auto"> {children} </main> </div> </div> ); }; export default DashboardLayout; # chaitanya-000/admin-dashboard 'use client' import React, { useState } from 'react'; import { FaSearch, FaUserPlus, FaEdit, FaTrash, FaEye } from 'react-icons/fa'; const Customers = () => { const [searchTerm, setSearchTerm] = useState(''); const [customers, setCustomers] = useState([ { id: 1, name: 'John Doe', email: 'john@example.com', phone: '+1 (555) 123-4567', totalOrders: 12, totalSpent: '$1,299.99', status: 'Active', joinDate: '2023-01-15', lastOrder: '2024-01-10' }, { id: 2, name: 'Jane Smith', email: 'jane@example.com', phone: '+1 (555) 987-6543', totalOrders: 8, totalSpent: '$899.50', status: 'Active', joinDate: '2023-02-20', lastOrder: '2024-01-08' }, { id: 3, name: 'Mike Johnson', email: 'mike@example.com', phone: '+1 (555) 456-7890', totalOrders: 15, totalSpent: '$2,199.99', status: 'Active', joinDate: '2023-01-08', lastOrder: '2024-01-12' }, { id: 4, name: 'Sarah Wilson', email: 'sarah@example.com', phone: '+1 (555) 321-9876', totalOrders: 3, totalSpent: '$259.99', status: 'Inactive', joinDate: '2023-11-15', lastOrder: '2023-12-20' }, { id: 5, name: 'Tom Brown', email: 'tom@example.com', phone: '+1 (555) 654-3210', totalOrders: 20, totalSpent: '$3,599.99', status: 'VIP', joinDate: '2022-08-10', lastOrder: '2024-01-14' }, { id: 6, name: 'Lisa Davis', email: 'lisa@example.com', phone: '+1 (555) 789-0123', totalOrders: 6, totalSpent: '$649.99', status: 'Active', joinDate: '2023-06-25', lastOrder: '2024-01-05' } ]); const filteredCustomers = customers.filter(customer => customer.name.toLowerCase().includes(searchTerm.toLowerCase()) || customer.email.toLowerCase().includes(searchTerm.toLowerCase()) || customer.phone.includes(searchTerm) ); const getStatusColor = (status) => { switch (status) { case 'Active': return 'bg-green-100 text-green-800'; case 'Inactive': return 'bg-gray-100 text-gray-800'; case 'VIP': return 'bg-purple-100 text-purple-800'; default: return 'bg-gray-100 text-gray-800'; } }; // Calculate summary statistics const totalCustomers = customers.length; const activeCustomers = customers.filter(customer => customer.status === 'Active').length; const vipCustomers = customers.filter(customer => customer.status === 'VIP').length; const totalRevenue = customers.reduce((sum, customer) => sum + parseFloat(customer.totalSpent.replace('$', '').replace(',', '')), 0 ); return ( <div className="p-6 bg-gray-50 min-h-screen"> {/* Header */} <div className="mb-8"> <h1 className="text-3xl font-bold text-gray-900">Customers</h1> <p className="text-gray-600 mt-2">Manage your customer database</p> </div> {/* Summary Cards */} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8"> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">Total Customers</h3> <p className="text-3xl font-bold text-gray-900">{totalCustomers}</p> </div> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">Active Customers</h3> <p className="text-3xl font-bold text-green-600">{activeCustomers}</p> </div> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">VIP Customers</h3> <p className="text-3xl font-bold text-purple-600">{vipCustomers}</p> </div> <div className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">Total Revenue</h3> <p className="text-3xl font-bold text-blue-600">${totalRevenue.toLocaleString()}</p> </div> </div> {/* Controls */} <div className="bg-white rounded-lg shadow-md p-6 mb-6"> <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0"> {/* Search */} <div className="relative"> <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" /> <input type="text" placeholder="Search customers..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full md:w-80" /> </div> {/* Actions */} <div className="flex items-center space-x-4"> <select className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"> <option>All Customers</option> <option>Active</option> <option>Inactive</option> <option>VIP</option> </select> <button className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center space-x-2"> <FaUserPlus /> <span>Add Customer</span> </button> </div> </div> </div> {/* Customers Table */} <div className="bg-white rounded-lg shadow-md"> <div className="p-6"> <div className="overflow-x-auto"> <table className="w-full"> <thead> <tr className="border-b border-gray-200"> <th className="text-left py-3 px-4 font-medium text-gray-600">Customer</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Contact</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Orders</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Total Spent</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Status</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Last Order</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Actions</th> </tr> </thead> <tbody> {filteredCustomers.map((customer) => ( <tr key={customer.id} className="border-b border-gray-100 hover:bg-gray-50"> <td className="py-4 px-4"> <div className="flex items-center space-x-3"> <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center"> <span className="text-blue-600 font-medium"> {customer.name.split(' ').map(n => n[0]).join('')} </span> </div> <div> <div className="font-medium text-gray-900">{customer.name}</div> <div className="text-sm text-gray-500">ID: #{customer.id}</div> </div> </div> </td> <td className="py-4 px-4"> <div> <div className="text-gray-900">{customer.email}</div> <div className="text-sm text-gray-500">{customer.phone}</div> </div> </td> <td className="py-4 px-4 font-medium">{customer.totalOrders}</td> <td className="py-4 px-4 font-medium">{customer.totalSpent}</td> <td className="py-4 px-4"> <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(customer.status)}`}> {customer.status} </span> </td> <td className="py-4 px-4 text-gray-700">{customer.lastOrder}</td> <td className="py-4 px-4"> <div className="flex items-center space-x-2"> <button className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg"> <FaEye size={16} /> </button> <button className="p-2 text-green-600 hover:bg-green-100 rounded-lg"> <FaEdit size={16} /> </button> <button className="p-2 text-red-600 hover:bg-red-100 rounded-lg"> <FaTrash size={16} /> </button> </div> </td> </tr> ))} </tbody> </table> </div> {/* Pagination */} <div className="flex items-center justify-between mt-6"> <div className="text-sm text-gray-700"> Showing <span className="font-medium">1</span> to <span className="font-medium">{filteredCustomers.length}</span> of{' '} <span className="font-medium">{customers.length}</span> results </div> <div className="flex items-center space-x-2"> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50"> Previous </button> <button className="px-3 py-2 bg-blue-600 text-white rounded-lg">1</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">2</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">3</button> <button className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"> Next </button> </div> </div> </div> </div> </div> ); }; export default Customers; 'use client' import React, { useState } from 'react'; import { FaSave, FaUser, FaBell, FaShield, FaPalette, FaDatabase } from 'react-icons/fa'; const Settings = () => { const [activeTab, setActiveTab] = useState('profile'); const [formData, setFormData] = useState({ // Profile settings firstName: 'John', lastName: 'Doe', email: 'john.doe@example.com', phone: '+1 (555) 123-4567', role: 'Administrator', // Notification settings emailNotifications: true, pushNotifications: true, orderNotifications: true, promotionalEmails: false, // Security settings twoFactorAuth: true, loginAlerts: true, sessionTimeout: '30', // Appearance settings theme: 'light', language: 'en', timezone: 'America/New_York', // System settings currency: 'USD', dateFormat: 'MM/DD/YYYY', autoBackup: true, debugMode: false }); const handleInputChange = (e) => { const { name, value, type, checked } = e.target; setFormData(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value })); }; const handleSave = () => { // Here you would typically save the settings to your backend alert('Settings saved successfully!'); }; const tabs = [ { id: 'profile', label: 'Profile', icon: FaUser }, { id: 'notifications', label: 'Notifications', icon: FaBell }, { id: 'security', label: 'Security', icon: FaShield }, { id: 'appearance', label: 'Appearance', icon: FaPalette }, { id: 'system', label: 'System', icon: FaDatabase }, ]; const renderTabContent = () => { switch (activeTab) { case 'profile': return ( <div className="space-y-6"> <h3 className="text-lg font-medium text-gray-900">Profile Information</h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> First Name </label> <input type="text" name="firstName" value={formData.firstName} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" /> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Last Name </label> <input type="text" name="lastName" value={formData.lastName} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" /> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Email </label> <input type="email" name="email" value={formData.email} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" /> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Phone </label> <input type="tel" name="phone" value={formData.phone} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" /> </div> <div className="md:col-span-2"> <label className="block text-sm font-medium text-gray-700 mb-2"> Role </label> <select name="role" value={formData.role} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="Administrator">Administrator</option> <option value="Manager">Manager</option> <option value="Staff">Staff</option> </select> </div> </div> </div> ); case 'notifications': return ( <div className="space-y-6"> <h3 className="text-lg font-medium text-gray-900">Notification Preferences</h3> <div className="space-y-4"> {[ { key: 'emailNotifications', label: 'Email Notifications', description: 'Receive notifications via email' }, { key: 'pushNotifications', label: 'Push Notifications', description: 'Receive push notifications in your browser' }, { key: 'orderNotifications', label: 'Order Notifications', description: 'Get notified about new orders and updates' }, { key: 'promotionalEmails', label: 'Promotional Emails', description: 'Receive marketing and promotional emails' }, ].map((item) => ( <div key={item.key} className="flex items-center justify-between py-4 border-b border-gray-200"> <div> <h4 className="text-sm font-medium text-gray-900">{item.label}</h4> <p className="text-sm text-gray-500">{item.description}</p> </div> <label className="relative inline-flex items-center cursor-pointer"> <input type="checkbox" name={item.key} checked={formData[item.key]} onChange={handleInputChange} className="sr-only peer" /> <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div> </label> </div> ))} </div> </div> ); case 'security': return ( <div className="space-y-6"> <h3 className="text-lg font-medium text-gray-900">Security Settings</h3> <div className="space-y-4"> {[ { key: 'twoFactorAuth', label: 'Two-Factor Authentication', description: 'Add an extra layer of security to your account' }, { key: 'loginAlerts', label: 'Login Alerts', description: 'Get notified when someone logs into your account' }, ].map((item) => ( <div key={item.key} className="flex items-center justify-between py-4 border-b border-gray-200"> <div> <h4 className="text-sm font-medium text-gray-900">{item.label}</h4> <p className="text-sm text-gray-500">{item.description}</p> </div> <label className="relative inline-flex items-center cursor-pointer"> <input type="checkbox" name={item.key} checked={formData[item.key]} onChange={handleInputChange} className="sr-only peer" /> <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div> </label> </div> ))} <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Session Timeout (minutes) </label> <select name="sessionTimeout" value={formData.sessionTimeout} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="15">15 minutes</option> <option value="30">30 minutes</option> <option value="60">1 hour</option> <option value="120">2 hours</option> </select> </div> </div> </div> ); case 'appearance': return ( <div className="space-y-6"> <h3 className="text-lg font-medium text-gray-900">Appearance Settings</h3> <div className="space-y-4"> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Theme </label> <select name="theme" value={formData.theme} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="light">Light</option> <option value="dark">Dark</option> <option value="auto">Auto</option> </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Language </label> <select name="language" value={formData.language} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="en">English</option> <option value="es">Spanish</option> <option value="fr">French</option> <option value="de">German</option> </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Timezone </label> <select name="timezone" value={formData.timezone} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="America/New_York">Eastern Time</option> <option value="America/Chicago">Central Time</option> <option value="America/Denver">Mountain Time</option> <option value="America/Los_Angeles">Pacific Time</option> </select> </div> </div> </div> ); case 'system': return ( <div className="space-y-6"> <h3 className="text-lg font-medium text-gray-900">System Settings</h3> <div className="space-y-4"> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Currency </label> <select name="currency" value={formData.currency} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="USD">USD - US Dollar</option> <option value="EUR">EUR - Euro</option> <option value="GBP">GBP - British Pound</option> <option value="JPY">JPY - Japanese Yen</option> </select> </div> <div> <label className="block text-sm font-medium text-gray-700 mb-2"> Date Format </label> <select name="dateFormat" value={formData.dateFormat} onChange={handleInputChange} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="MM/DD/YYYY">MM/DD/YYYY</option> <option value="DD/MM/YYYY">DD/MM/YYYY</option> <option value="YYYY-MM-DD">YYYY-MM-DD</option> </select> </div> {[ { key: 'autoBackup', label: 'Automatic Backup', description: 'Automatically backup your data daily' }, { key: 'debugMode', label: 'Debug Mode', description: 'Enable debug mode for troubleshooting' }, ].map((item) => ( <div key={item.key} className="flex items-center justify-between py-4 border-b border-gray-200"> <div> <h4 className="text-sm font-medium text-gray-900">{item.label}</h4> <p className="text-sm text-gray-500">{item.description}</p> </div> <label className="relative inline-flex items-center cursor-pointer"> <input type="checkbox" name={item.key} checked={formData[item.key]} onChange={handleInputChange} className="sr-only peer" /> <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div> </label> </div> ))} </div> </div> ); default: return null; } }; return ( <div className="p-6 bg-gray-50 min-h-screen"> {/* Header */} <div className="mb-8"> <h1 className="text-3xl font-bold text-gray-900">Settings</h1> <p className="text-gray-600 mt-2">Manage your account and system preferences</p> </div> <div className="flex flex-col lg:flex-row gap-6"> {/* Sidebar */} <div className="lg:w-64"> <nav className="bg-white rounded-lg shadow-md p-4"> <ul className="space-y-2"> {tabs.map((tab) => { const Icon = tab.icon; return ( <li key={tab.id}> <button onClick={() => setActiveTab(tab.id)} className={`w-full flex items-center space-x-3 px-4 py-3 rounded-lg transition-colors ${ activeTab === tab.id ? 'bg-blue-600 text-white' : 'text-gray-700 hover:bg-gray-100' }`} > <Icon size={20} /> <span>{tab.label}</span> </button> </li> ); })} </ul> </nav> </div> {/* Content */} <div className="flex-1"> <div className="bg-white rounded-lg shadow-md p-6"> {renderTabContent()} {/* Save Button */} <div className="mt-8 pt-6 border-t border-gray-200"> <button onClick={handleSave} className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 flex items-center space-x-2" > <FaSave /> <span>Save Changes</span> </button> </div> </div> </div> </div> </div> ); }; export default Settings; 'use client' import React from 'react'; import { LineChart, BarChart } from '@/components/dashboard/Charts'; const Analytics = () => { // Sample data for various charts const revenueData = { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [ { label: 'Revenue ($)', data: [12000, 19000, 15000, 25000, 22000, 30000, 28000, 35000, 32000, 40000, 38000, 45000], borderColor: 'rgb(59, 130, 246)', backgroundColor: 'rgba(59, 130, 246, 0.1)', tension: 0.4, }, { label: 'Target ($)', data: [15000, 20000, 18000, 28000, 25000, 32000, 30000, 37000, 35000, 42000, 40000, 47000], borderColor: 'rgb(239, 68, 68)', backgroundColor: 'rgba(239, 68, 68, 0.1)', tension: 0.4, borderDash: [5, 5], }, ], }; const categoryData = { labels: ['Electronics', 'Clothing', 'Books', 'Home & Garden', 'Sports', 'Beauty'], datasets: [ { label: 'Sales by Category', data: [35000, 28000, 15000, 22000, 18000, 12000], backgroundColor: [ 'rgba(59, 130, 246, 0.8)', 'rgba(16, 185, 129, 0.8)', 'rgba(245, 158, 11, 0.8)', 'rgba(239, 68, 68, 0.8)', 'rgba(139, 92, 246, 0.8)', 'rgba(236, 72, 153, 0.8)', ], }, ], }; const trafficData = { labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], datasets: [ { label: 'Website Visitors', data: [1200, 1900, 1500, 2500, 2200, 1800, 1300], borderColor: 'rgb(16, 185, 129)', backgroundColor: 'rgba(16, 185, 129, 0.1)', tension: 0.4, }, ], }; const conversionData = { labels: ['Q1', 'Q2', 'Q3', 'Q4'], datasets: [ { label: 'Conversion Rate (%)', data: [2.4, 3.2, 2.8, 3.6], backgroundColor: 'rgba(139, 92, 246, 0.8)', }, ], }; const topProducts = [ { name: 'iPhone 14 Pro', sales: '$45,230', units: 156, change: '+12%' }, { name: 'MacBook Air M2', sales: '$38,900', units: 89, change: '+8%' }, { name: 'AirPods Pro', sales: '$28,500', units: 234, change: '+15%' }, { name: 'Samsung Galaxy S23', sales: '$25,600', units: 78, change: '+5%' }, { name: 'iPad Pro', sales: '$22,800', units: 67, change: '-2%' }, ]; const keyMetrics = [ { label: 'Total Revenue', value: '$345,678', change: '+12.5%', trend: 'up' }, { label: 'Total Orders', value: '2,456', change: '+8.2%', trend: 'up' }, { label: 'Avg. Order Value', value: '$142.50', change: '+3.8%', trend: 'up' }, { label: 'Conversion Rate', value: '3.2%', change: '-1.2%', trend: 'down' }, { label: 'Customer Acquisition', value: '145', change: '+22.1%', trend: 'up' }, { label: 'Return Rate', value: '2.8%', change: '-0.5%', trend: 'up' }, ]; return ( <div className="p-6 bg-gray-50 min-h-screen"> {/* Header */} <div className="mb-8"> <h1 className="text-3xl font-bold text-gray-900">Analytics</h1> <p className="text-gray-600 mt-2">Track your business performance and insights</p> </div> {/* Key Metrics */} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8"> {keyMetrics.map((metric, index) => ( <div key={index} className="bg-white rounded-lg shadow-md p-6"> <h3 className="text-sm font-medium text-gray-600 mb-2">{metric.label}</h3> <div className="flex items-center justify-between"> <p className="text-2xl font-bold text-gray-900">{metric.value}</p> <span className={`text-sm font-medium ${ metric.trend === 'up' && metric.change.startsWith('+') ? 'text-green-600' : metric.trend === 'down' || metric.change.startsWith('-') ? 'text-red-600' : 'text-green-600' }`}> {metric.change} </span> </div> </div> ))} </div> {/* Charts */} <div className="grid grid-cols-1 xl:grid-cols-2 gap-6 mb-8"> <div className="bg-white p-6 rounded-lg shadow-md"> <LineChart data={revenueData} title="Revenue vs Target" /> </div> <div className="bg-white p-6 rounded-lg shadow-md"> <BarChart data={categoryData} title="Sales by Category" /> </div> <div className="bg-white p-6 rounded-lg shadow-md"> <LineChart data={trafficData} title="Website Traffic" /> </div> <div className="bg-white p-6 rounded-lg shadow-md"> <BarChart data={conversionData} title="Quarterly Conversion Rate" /> </div> </div> {/* Additional Analytics */} <div className="grid grid-cols-1 lg:grid-cols-3 gap-6"> {/* Top Products */} <div className="lg:col-span-2 bg-white rounded-lg shadow-md p-6"> <h2 className="text-xl font-bold text-gray-900 mb-6">Top Performing Products</h2> <div className="overflow-x-auto"> <table className="w-full"> <thead> <tr className="border-b border-gray-200"> <th className="text-left py-3 px-4 font-medium text-gray-600">Product</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Sales</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Units</th> <th className="text-left py-3 px-4 font-medium text-gray-600">Change</th> </tr> </thead> <tbody> {topProducts.map((product, index) => ( <tr key={index} className="border-b border-gray-100"> <td className="py-3 px-4 font-medium">{product.name}</td> <td className="py-3 px-4">{product.sales}</td> <td className="py-3 px-4">{product.units}</td> <td className="py-3 px-4"> <span className={`font-medium ${ product.change.startsWith('+') ? 'text-green-600' : 'text-red-600' }`}> {product.change} </span> </td> </tr> ))} </tbody> </table> </div> </div> {/* Traffic Sources */} <div className="bg-white rounded-lg shadow-md p-6"> <h2 className="text-xl font-bold text-gray-900 mb-6">Traffic Sources</h2> <div className="space-y-4"> {[ { source: 'Organic Search', percentage: 42, visitors: '12,456' }, { source: 'Direct', percentage: 28, visitors: '8,234' }, { source: 'Social Media', percentage: 18, visitors: '5,123' }, { source: 'Email', percentage: 8, visitors: '2,345' }, { source: 'Referral', percentage: 4, visitors: '1,234' }, ].map((item, index) => ( <div key={index} className="flex items-center justify-between"> <div> <p className="text-sm font-medium text-gray-900">{item.source}</p> <p className="text-xs text-gray-500">{item.visitors} visitors</p> </div> <div className="flex items-center space-x-2"> <div className="w-20 bg-gray-200 rounded-full h-2"> <div className="bg-blue-600 h-2 rounded-full" style={{ width: `${item.percentage}%` }} ></div> </div> <span className="text-sm font-medium text-gray-900">{item.percentage}%</span> </div> </div> ))} </div> </div> </div> </div> ); }; export default Analytics; # README.md # Modern Admin Dashboard A sleek, responsive admin dashboard built with Next.js 14, React, and Tailwind CSS. Features a comprehensive set of admin tools including analytics, order management, product management, customer management, and system settings. ## 🚀 Features - **Modern Design**: Clean, intuitive interface with responsive design - **Dashboard Overview**: Key metrics, charts, and recent activity - **Order Management**: Track and manage customer orders - **Product Management**: Add, edit, and organize your product catalog - **Customer Management**: View and manage customer information - **Analytics**: Interactive charts and business insights - **Settings**: Comprehensive system and user preferences - **Responsive**: Works perfectly on desktop, tablet, and mobile devices ## 🛠️ Tech Stack - **Next.js 14** - React framework with App Router - **React 18** - Modern React with hooks - **Tailwind CSS** - Utility-first CSS framework - **Chart.js** - Interactive charts and visualizations - **React Icons** - Beautiful icon library - **React Chart.js 2** - Chart.js integration for React ## 📦 Installation 1. Clone the repository: ```bash git clone https://github.com/yourusername/admin-dashboard.git cd admin-dashboard ``` 2. Install dependencies: ```bash npm install # or yarn install # or pnpm install ``` 3. Run the development server: ```bash npm run dev # or yarn dev # or pnpm dev ``` 4. Open [http://localhost:3000](http://localhost:3000) in your browser to see the result. ## 🏗️ Project Structure ``` src/ ├── app/ │ ├── dashboard/ │ │ ├── analytics/ │ │ ├── customers/ │ │ ├── orders/ │ │ ├── products/ │ │ ├── settings/ │ │ ├── layout.js │ │ └── page.js │ ├── globals.css │ └── layout.js ├── components/ │ ├── dashboard/ │ │ ├── Charts.js │ │ └── StatsCard.js │ └── layout/ │ ├── Header.js │ └── Sidebar.js └── ... ``` ## 🎨 Features Overview ### Dashboard - Real-time statistics and KPIs - Interactive charts showing sales trends - Recent orders overview - Quick action buttons ### Orders Management - Order listing with search and filters - Order status tracking - Customer information - Export functionality ### Product Management - Product catalog with images - Category management - Stock tracking - Bulk operations ### Customer Management - Customer database - Order history per customer - Customer segmentation - Contact information management ### Analytics - Revenue tracking - Sales performance charts - Traffic analytics - Conversion metrics ### Settings - User profile management - Notification preferences - Security settings - System configuration ## 🎯 Customization The dashboard is built with modularity in mind. You can easily: 1. **Add new pages**: Create new routes in the `app/dashboard/` directory 2. **Customize styling**: Modify Tailwind classes or add custom CSS 3. **Add new charts**: Use the Chart.js components in `components/dashboard/Charts.js` 4. **Modify sidebar**: Update navigation items in `components/layout/Sidebar.js` ## 📱 Responsive Design The dashboard is fully responsive and works on: - Desktop (1024px+) - Tablet (768px - 1023px) - Mobile (320px - 767px) ## 🔧 Configuration ### Environment Variables Create a `.env.local` file in the root directory: ```env # Add your environment variables here NEXT_PUBLIC_API_URL=your_api_url DATABASE_URL=your_database_url ``` ### Customizing Colors Update the Tailwind config to match your brand colors: ```javascript // tailwind.config.js module.exports = { theme: { extend: { colors: { primary: { 50: '#eff6ff', 500: '#3b82f6', 600: '#2563eb', }, }, }, }, } ``` ## 🚀 Deployment ### Vercel (Recommended) 1. Push your code to GitHub 2. Connect your repository to Vercel 3. Deploy with zero configuration ### Other Platforms The dashboard can be deployed to any platform that supports Next.js: - Netlify - AWS Amplify - Digital Ocean App Platform - Railway - Render ## 🤝 Contributing Contributions are welcome! Please feel free to submit a Pull Request. 1. Fork the project 2. Create your feature branch (`git checkout -b feature/AmazingFeature`) 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request ## 📄 License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## 🙏 Acknowledgments - [Next.js](https://nextjs.org/) for the amazing React framework - [Tailwind CSS](https://tailwindcss.com/) for the utility-first CSS framework - [Chart.js](https://www.chartjs.org/) for beautiful charts - [React Icons](https://react-icons.github.io/react-icons/) for the icon library ## 📞 Support If you have any questions or need help, please open an issue on GitHub or reach out to [your-email@example.com](mailto:your-email@example.com). --- Made with ❤️ by [Your Name](https://github.com/yourusername)const express = require("express"); const path = require("path"); const app = express(); const cors = require("cors"); app.use(cors()); app.use(express.static(path.join(__dirname, "build"))); app.get("/", function (req, res) { res.sendFile(path.join(__dirname, "build", "index.html")); }); app.get("/api/hello", (req, res) => { res.send({ message: "Hello from the backend!" }); }); const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); End Fileimport React, { useEffect, useState } from 'react'; function App() { const [message, setMessage] = useState(''); useEffect(() => { fetch('/api/hello') .then(response => response.json()) .then(data => setMessage(data.message)); }, []); return ( <div className="App"> <header className="App-header"> <h1>Hello, World!</h1> <p>Your Minimal React App is running!</p> <p>Backend says: {message}</p> </header> </div> ); } export default App; import express, { Request, Response } from "express"; import { body, validationResult } from "express-validator"; import jwt from "jsonwebtoken"; import User from "../models/User"; import { check } from "express-validator"; import { currentUser } from "../middleware/current-user"; const router = express.Router(); // @route POST api/auth // @desc Authenticate user & get token // @access Public router.post( "/", [ check("email", "Please include a valid email").isEmail(), check("password", "Password is required").exists(), ], async (req: Request, res: Response) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, password } = req.body; try { let user = await User.findOne({ email }); if (!user) { return res.status(400).json({ msg: "Invalid Credentials" }); } const isMatch = await user.comparePassword(password); if (!isMatch) { return res.status(400).json({ msg: "Invalid Credentials" }); } const payload = { user: { id: user.id, }, }; jwt.sign( payload, process.env.JWT_SECRET as string, { expiresIn: 360000 }, (err, token) => { if (err) throw err; res.json({ token }); } ); } catch (err) { console.error(err); res.status(500).send("Server error"); } } ); // @route GET api/auth // @desc Get current user // @access Private router.get("/", currentUser, async (req: Request, res: Response) => { try { const user = await User.findById(req.user?.id).select("-password"); res.json(user); } catch (err) { console.error(err); res.status(500).send("Server error"); } }); export { router as authRouter }; End Fileimport express, { Request, Response } from "express"; import { check, validationResult } from "express-validator"; import User from "../models/User"; import jwt from "jsonwebtoken"; const router = express.Router(); // @route POST api/users // @desc Register user // @access Public router.post( "/", [ check("name", "Name is required").not().isEmpty(), check("email", "Please include a valid email").isEmail(), check( "password", "Please enter a password with 6 or more characters" ).isLength({ min: 6 }), ], async (req: Request, res: Response) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { name, email, password } = req.body; try { let user = await User.findOne({ email }); if (user) { return res.status(400).json({ msg: "User already exists" }); } user = new User({ name, email, password, }); await user.save(); const payload = { user: { id: user.id, }, }; jwt.sign( payload, process.env.JWT_SECRET as string, { expiresIn: 360000 }, (err, token) => { if (err) throw err; res.json({ token }); } ); } catch (err) { console.error(err); res.status(500).send("Server error"); } } ); export { router as userRouter }; End File# src/routes/tasks.ts import express, { Request, Response } from "express"; import { check, validationResult } from "express-validator"; import Task from "../models/Task"; import { currentUser } from "../middleware/current-user"; const router = express.Router(); // @route GET api/tasks // @desc Get all tasks for the current user // @access Private router.get("/", currentUser, async (req: Request, res: Response) => { try { const tasks = await Task.find({ user: req.user?.id }); res.json(tasks); } catch (err) { console.error(err); res.status(500).send("Server error"); } }); // @route POST api/tasks // @desc Create a new task // @access Private router.post( "/", [ currentUser, [ check("title", "Title is required").not().isEmpty(), check("description", "Description is required").not().isEmpty(), ], ], async (req: Request, res: Response) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { title, description, priority = "medium" } = req.body; try { const newTask = new Task({ title, description, priority, user: req.user?.id, }); const task = await newTask.save(); res.json(task); } catch (err) { console.error(err); res.status(500).send("Server error"); } } ); // @route PUT api/tasks/:id // @desc Update a task // @access Private router.put("/:id", currentUser, async (req: Request, res: Response) => { const { title, description, priority, completed } = req.body; // Build task object const taskFields: any = {}; if (title) taskFields.title = title; if (description) taskFields.description = description; if (priority) taskFields.priority = priority; if (completed !== undefined) taskFields.completed = completed; try { let task = await Task.findById(req.params.id); if (!task) { return res.status(404).json({ msg: "Task not found" }); } // Make sure user owns task if (task.user.toString() !== req.user?.id) { return res.status(401).json({ msg: "Not authorized" }); } task = await Task.findByIdAndUpdate( req.params.id, { $set: taskFields }, { new: true } ); res.json(task); } catch (err) { console.error(err); res.status(500).send("Server error"); } }); // @route DELETE api/tasks/:id // @desc Delete a task // @access Private router.delete("/:id", currentUser, async (req: Request, res: Response) => { try { let task = await Task.findById(req.params.id); if (!task) { return res.status(404).json({ msg: "Task not found" }); } // Make sure user owns task if (task.user.toString() !== req.user?.id) { return res.status(401).json({ msg: "Not authorized" }); } await Task.findByIdAndRemove(req.params.id); res.json({ msg: "Task removed" }); } catch (err) { console.error(err); res.status(500).send("Server error"); } }); export { router as taskRouter }; End File# ravikiran8844/task-manager-backend # src/models/User.ts import mongoose from "mongoose"; import bcrypt from "bcryptjs"; // An interface that describes the properties // that are required to create a new User interface UserAttrs { name: string; email: string; password: string; } // An interface that describes the properties // that a User Model has interface UserModel extends mongoose.Model<UserDoc> { build(attrs: UserAttrs): UserDoc; } // An interface that describes the properties // that a User Document has interface UserDoc extends mongoose.Document { name: string; email: string; password: string; createdAt: Date; comparePassword(candidatePassword: string): Promise<boolean>; } const userSchema = new mongoose.Schema( { name: { type: String, required: true, }, email: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, createdAt: { type: Date, default: Date.now, }, }, { toJSON: { transform(doc, ret) { ret.id = ret._id; delete ret._id; delete ret.__v; delete ret.password; }, }, } ); // Hash password before saving userSchema.pre("save", async function (done) { if (this.isModified("password")) { const salt = await bcrypt.genSalt(10); const hashed = await bcrypt.hash(this.get("password"), salt); this.set("password", hashed); } done(); }); // Compare password method userSchema.methods.comparePassword = async function ( candidatePassword: string ) { return await bcrypt.compare(candidatePassword, this.password); }; userSchema.statics.build = (attrs: UserAttrs) => { return new User(attrs); }; const User = mongoose.model<UserDoc, UserModel>("User", userSchema); export default User; End Fileimport mongoose from "mongoose"; // An interface that describes the properties // that are required to create a new Task interface TaskAttrs { title: string; description: string; priority?: "low" | "medium" | "high"; user: string; } // An interface that describes the properties // that a Task Model has interface TaskModel extends mongoose.Model<TaskDoc> { build(attrs: TaskAttrs): TaskDoc; } // An interface that describes the properties // that a Task Document has interface TaskDoc extends mongoose.Document { title: string; description: string; priority: "low" | "medium" | "high"; completed: boolean; user: string; createdAt: Date; updatedAt: Date; } const taskSchema = new mongoose.Schema( { title: { type: String, required: true, }, description: { type: String, required: true, }, priority: { type: String, enum: ["low", "medium", "high"], default: "medium", }, completed: { type: Boolean, default: false, }, user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true, }, createdAt: { type: Date, default: Date.now, }, updatedAt: { type: Date, default: Date.now, }, }, { toJSON: { transform(doc, ret) { ret.id = ret._id; delete ret._id; delete ret.__v; }, }, } ); // Update the updatedAt field before saving taskSchema.pre("save", function (done) { this.set("updatedAt", new Date()); done(); }); taskSchema.statics.build = (attrs: TaskAttrs) => { return new Task(attrs); }; const Task = mongoose.model<TaskDoc, TaskModel>("Task", taskSchema); export default Task; End File# ravikiran8844/task-manager-backend import express from "express"; import mongoose from "mongoose"; import cors from "cors"; import { json } from "body-parser"; import { userRouter } from "./routes/users"; import { authRouter } from "./routes/auth"; import { taskRouter } from "./routes/tasks"; const app = express(); app.set("trust proxy", true); app.use(json()); app.use(cors()); // Routes app.use("/api/users", userRouter); app.use("/api/auth", authRouter); app.use("/api/tasks", taskRouter); const start = async () => { console.log("Starting up..."); if (!process.env.JWT_SECRET) { throw new Error("JWT_SECRET must be defined"); } if (!process.env.MONGO_URI) { throw new Error("MONGO_URI must be defined"); } try { await mongoose.connect(process.env.MONGO_URI); console.log("Connected to MongoDB"); } catch (err) { console.error(err); } app.listen(3000, () => { console.log("Listening on port 3000!"); }); }; start(); # tests/unit/test_plugin.py import os from pathlib import Path import pytest from conftest import get_setup_and_config class TestJunitPlugin: def test_save_report_to_xml_and_default_location(self, testdir): testdir.makepyfile( ''' def test_one(): pass ''' ) result = testdir.runpytest('--junit-xml=output.xml') assert result.ret == 0 assert Path('output.xml').exists() def test_config_plugin_from_ini(self, testdir): testdir.makeini( ''' [tool:pytest] junit_family = xunit1 junit_suite_name = mysuite junit_logging = all junit_log_passing_tests = True ''' ) testdir.makepyfile( ''' def test_one(): pass ''' ) setup, config = get_setup_and_config(testdir.tmpdir) assert config._get_junit_family() == 'xunit1' assert config._get_junit_suite_name() == 'mysuite' assert config._get_junit_logging() == 'all' assert config._get_junit_log_passing_tests() is True def test_config_plugin_from_pyproject_toml(self, testdir): testdir.makefile( '.toml', pyproject=''' [tool.pytest.ini_options] junit_family = "xunit2" junit_suite_name = "another_suite" junit_logging = "system-err" junit_log_passing_tests = false ''', ) testdir.makepyfile( ''' def test_one(): pass ''' ) setup, config = get_setup_and_config(testdir.tmpdir) assert config._get_junit_family() == 'xunit2' assert config._get_junit_suite_name() == 'another_suite' assert config._get_junit_logging() == 'system-err' assert config._get_junit_log_passing_tests() is False def test_junit_family_without_xml_option(self, testdir): testdir.makeini( ''' [tool:pytest] junit_family = xunit1 ''' ) testdir.makepyfile( ''' def test_one(): pass ''' ) result = testdir.runpytest('--junit-family=xunit1') assert result.ret == 0 def test_xunit1_produces_correct_xml(self, testdir): testdir.makepyfile( ''' def test_one(): pass ''' ) result = testdir.runpytest('--junit-xml=output.xml', '--junit-family=xunit1') assert result.ret == 0 output_xml = testdir.tmpdir.join('output.xml').read() assert 'xmlns' not in output_xml def test_xunit2_produces_correct_xml(self, testdir): testdir.makepyfile( ''' def test_one(): pass ''' ) result = testdir.runpytest('--junit-xml=output.xml', '--junit-family=xunit2') assert result.ret == 0 output_xml = testdir.tmpdir.join('output.xml').read() assert 'xmlns' in output_xml def test_incorrect_family_option_errors(self, testdir): testdir.makepyfile( ''' def test_one(): pass ''' ) result = testdir.runpytest('--junit-xml=output.xml', '--junit-family=unknown') assert result.ret == pytest.ExitCode.USAGE_ERROR @pytest.mark.parametrize('junit_logging', ['no', 'log', 'system-out', 'system-err', 'out-err', 'all']) def test_junit_logging_option_accepted(self, testdir, junit_logging): testdir.makepyfile( ''' def test_one(): pass ''' ) result = testdir.runpytest('--junit-xml=output.xml', f'--junit-logging={junit_logging}') assert result.ret == 0 def test_incorrect_logging_option_errors(self, testdir): testdir.makepyfile( ''' def test_one(): pass ''' ) result = testdir.runpytest('--junit-xml=output.xml', '--junit-logging=unknown') assert result.ret == pytest.ExitCode.USAGE_ERROR def test_env_var_junit_family(self, testdir, monkeypatch): testdir.makepyfile( ''' def test_one(): pass ''' ) monkeypatch.setenv('PYTEST_JUNIT_FAMILY', 'xunit1') result = testdir.runpytest('--junit-xml=output.xml') assert result.ret == 0 def test_plugin_not_loaded_without_option(self, testdir): """Check that the junit plugin is not loaded by default.""" testdir.makepyfile( ''' def test_one(): assert hasattr(config.pluginmanager, "getplugin") assert not config.pluginmanager.getplugin('junitxml') ''' ) testdir.runpytest() def test_plugin_loaded_with_option(self, testdir): """Check that the junit plugin is loaded with option.""" testdir.makepyfile( ''' def test_one(): assert hasattr(config.pluginmanager, "getplugin") assert config.pluginmanager.getplugin('junitxml') ''' ) testdir.runpytest('--junit-xml=output.xml') def test_xml_filename_can_be_absolute_path(self, testdir): testdir.makepyfile( ''' def test_one(): pass ''' ) xml_file = os.path.abspath('output.xml') result = testdir.runpytest(f'--junit-xml={xml_file}') assert result.ret == 0 assert os.path.isfile(xml_file) def test_envvar_junit_prefix_works(self, testdir, monkeypatch): testdir.makepyfile( ''' def test_prefix(): pass ''' ) monkeypatch.setenv('PYTEST_JUNIT_PREFIX', 'env_') result = testdir.runpytest('--junit-xml=output.xml') assert result.ret == 0 with open('output.xml') as f: content = f.read() assert 'classname="env_test_envvar_junit_prefix_works.test_prefix"' in content End File# tests/unit/test_logs.py import logging import pytest from conftest import runandparse class TestLogs: def test_record_property(self, testdir): testdir.makepyfile( """ def test_record(record_property): record_property("foo", "<1"); """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] foonode = node.getElementsByTagName("properties")[0] foo = foonode.getElementsByTagName("property")[0] assert foo.getAttribute("name") == "foo" assert foo.getAttribute("value") == "<1" assert foo.firstChild is None def test_record_property_same_name(self, testdir): testdir.makepyfile( """ def test_record_with_same_name(record_property): record_property("foo", "bar") record_property("foo", "baz") """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] pnodes = node.getElementsByTagName("properties") assert len(pnodes) == 1 props = pnodes[0].getElementsByTagName("property") assert len(props) == 2 for i, expected_value in enumerate(["bar", "baz"]): assert props[i].getAttribute("name") == "foo" assert props[i].getAttribute("value") == expected_value def test_record_attribute(self, testdir): testdir.makepyfile( """ import pytest @pytest.fixture def other(record_testsuite_property): record_testsuite_property("bar", 1) def test_record(record_testsuite_property, other): record_testsuite_property("foo", "<1"); """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testsuite")[0] # the time, errors, failures, tests and skipped attributes always exist assert len(node.attributes) == 7 assert node.getAttribute("bar") == "1" assert node.getAttribute("foo") == "<1" def test_record_attribute_same_name(self, testdir): testdir.makepyfile( """ def test_record_with_same_name(record_testsuite_property): record_testsuite_property("foo", "bar") record_testsuite_property("foo", "baz") """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testsuite")[0] assert node.getAttribute("foo") == "baz" @pytest.mark.parametrize("junit_logging", ["no", "log", "system-out", "system-err", "out-err", "all"]) def test_nothing_logged(self, testdir, junit_logging): testdir.makepyfile( """ import sys def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') assert False """ ) result, dom = runandparse(testdir, "-o", f"junit_logging={junit_logging}") node = dom.getElementsByTagName("testcase")[0] if junit_logging in ["log", "all"]: assert len(node.getElementsByTagName("system-out")) == 1 elif junit_logging in ["system-out", "out-err"]: assert len(node.getElementsByTagName("system-out")) == 1 else: assert len(node.getElementsByTagName("system-out")) == 0 if junit_logging in ["log", "all"]: assert len(node.getElementsByTagName("system-err")) == 1 elif junit_logging in ["system-err", "out-err"]: assert len(node.getElementsByTagName("system-err")) == 1 else: assert len(node.getElementsByTagName("system-err")) == 0 def test_logging_captured_no_log_option(self, testdir): testdir.makepyfile( """ import sys import logging def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') logging.getLogger().info('text going to logger') assert 0, 'fail' """ ) result, dom = runandparse(testdir, "-o", "junit_logging=system-out") node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] text = sysout.firstChild.nodeValue assert "text going to stdout" in text assert "text going to stderr" not in text assert "text going to logger" not in text syserr = node.getElementsByTagName("system-err") assert len(syserr) == 0 def test_logging_captured_log_option(self, testdir): testdir.makepyfile( """ import sys import logging def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') logging.getLogger().info('text going to logger') assert 0, 'fail' """ ) result, dom = runandparse(testdir, "-o", "junit_logging=log") node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] text = sysout.firstChild.nodeValue assert "text going to stdout" in text assert "text going to stderr" not in text assert "text going to logger" in text syserr = node.getElementsByTagName("system-err")[0] text = syserr.firstChild.nodeValue assert "text going to stdout" not in text assert "text going to stderr" in text assert "text going to logger" not in text def test_logging_captured_only_log_option(self, testdir): testdir.makepyfile( """ import sys import logging def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') logging.getLogger().info('text going to logger') assert 0, 'fail' """ ) result, dom = runandparse(testdir, "-s", "-o", "junit_logging=log") node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] text = sysout.firstChild.nodeValue assert "text going to stdout" not in text assert "text going to stderr" not in text assert "text going to logger" in text syserr = node.getElementsByTagName("system-err")[0] text = syserr.firstChild.nodeValue assert "text going to stdout" not in text assert "text going to stderr" not in text assert "text going to logger" not in text def test_logging_passed_test(self, testdir): testdir.makepyfile( """ import sys import logging def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') logging.getLogger().info('text going to logger') """ ) result, dom = runandparse(testdir, "-o", "junit_logging=all") node = dom.getElementsByTagName("testcase")[0] assert len(node.getElementsByTagName("system-out")) == 0 assert len(node.getElementsByTagName("system-err")) == 0 def test_logging_passed_test_log_passing_tests(self, testdir): testdir.makepyfile( """ import sys import logging def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') logging.getLogger().info('text going to logger') """ ) result, dom = runandparse(testdir, "-o", "junit_logging=all", "-o", "junit_log_passing_tests=True") node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] text = sysout.firstChild.nodeValue assert "text going to stdout" in text assert "text going to stderr" not in text assert "text going to logger" in text syserr = node.getElementsByTagName("system-err")[0] text = syserr.firstChild.nodeValue assert "text going to stdout" not in text assert "text going to stderr" in text assert "text going to logger" not in text def test_logging_passed_test_no_verbose(self, testdir): testdir.makepyfile( """ import sys import logging def test_foo(): sys.stdout.write('text going to stdout') sys.stderr.write('text going to stderr') logging.getLogger().info('text going to logger') """ ) result, dom = runandparse(testdir, "-o", "junit_logging=all", "--tb=no") node = dom.getElementsByTagName("testcase")[0] assert len(node.getElementsByTagName("system-out")) == 0 assert len(node.getElementsByTagName("system-err")) == 0 def test_logging_xml_disabled(self, testdir): testdir.makepyfile( """ import logging def test_foo(): logging.getLogger().warning('user warning') assert 0 """ ) result = testdir.runpytest("--tb=no") assert "<testcase " not in result.stdout.str() def test_pass_captures_stdout(self, testdir): testdir.makepyfile( """ def test_pass(): print("hello-stdout") """ ) result, dom = runandparse(testdir, "-o", "junit_log_passing_tests=True") node = dom.getElementsByTagName("testcase")[0] pnode = node.getElementsByTagName("system-out")[0] assert "hello-stdout" in pnode.firstChild.nodeValue def test_pass_captures_stderr(self, testdir): testdir.makepyfile( """ import sys def test_pass(): sys.stderr.write("hello-stderr") """ ) result, dom = runandparse(testdir, "-o", "junit_log_passing_tests=True") node = dom.getElementsByTagName("testcase")[0] pnode = node.getElementsByTagName("system-err")[0] assert "hello-stderr" in pnode.firstChild.nodeValue def test_setup_error_captures_stdout(self, testdir): testdir.makepyfile( """ import pytest @pytest.fixture def arg(request): print('hello-stdout setup') raise ValueError() def test_function(arg): pass """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] pnode = node.getElementsByTagName("system-out")[0] assert "hello-stdout setup" in pnode.firstChild.nodeValue def test_setup_error_captures_stderr(self, testdir): testdir.makepyfile( """ import pytest import sys @pytest.fixture def arg(request): sys.stderr.write('hello-stderr setup') raise ValueError() def test_function(arg): pass """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] pnode = node.getElementsByTagName("system-err")[0] assert "hello-stderr setup" in pnode.firstChild.nodeValue def test_avoid_double_stdout(self, testdir): testdir.makepyfile( """ import sys import pytest @pytest.fixture def arg(request): yield sys.stdout.write('hello-stdout teardown') raise ValueError() def test_function(arg): sys.stdout.write('hello-stdout call') """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] pnode = node.getElementsByTagName("system-out")[0] stdout = pnode.firstChild.nodeValue assert stdout.count("hello-stdout call") == 1 assert stdout.count("hello-stdout teardown") == 1 def test_log_captured(self, testdir): testdir.makepyfile( """ import logging def test_log(): logging.getLogger().info('user message') assert 0 """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] pnode = node.getElementsByTagName("system-out")[0] assert "user message" in pnode.firstChild.nodeValue def test_log_file_not_captured(self, testdir): """Test that output from a logger configured to output to a file is not captured.""" testdir.makepyfile( """ import logging def test_log(): logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(logging.FileHandler("testlog.txt", mode="a")) logger.info('user message') assert 0 """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] assert "user message" not in sysout.firstChild.nodeValue def test_live_logging_disabled(self, testdir): """Test that output from a logger configured to output to a file is not captured.""" testdir.makepyfile( """ import logging def test_log(): logging.getLogger().info('user message') assert 0 """ ) result, dom = runandparse(testdir, "--log-cli-level=INFO") node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] assert "user message" in sysout.firstChild.nodeValue def test_non_string_properties(self, testdir): testdir.makepyfile( """ def test_record_int_property(record_property): record_property("foo", 1) """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] foonode = node.getElementsByTagName("properties")[0] foo = foonode.getElementsByTagName("property")[0] assert foo.getAttribute("name") == "foo" assert foo.getAttribute("value") == "1" def test_record_property_from_fixture(self, testdir): testdir.makepyfile( """ import pytest @pytest.fixture def some_fixture(record_property): record_property("foo", "bar") def test_record(some_fixture): pass """ ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] foonode = node.getElementsByTagName("properties")[0] foo = foonode.getElementsByTagName("property")[0] assert foo.getAttribute("name") == "foo" assert foo.getAttribute("value") == "bar" def test_record_test_id(self, testdir): testdir.makepyfile( """ import pytest @pytest.mark.parametrize('x', [1, 2]) def test_function(x): assert x != 2 """ ) result, dom = runandparse(testdir) nodes = dom.getElementsByTagName("testcase") nodes_tids = [x.getAttribute("classname") + "." + x.getAttribute("name") for x in nodes] assert "test_record_test_id.test_function[1]" in nodes_tids assert "test_record_test_id.test_function[2]" in nodes_tids def test_record_test_id_with_nested_tests(self, testdir): testdir.makepyfile( """ import pytest class TestClass: @pytest.mark.parametrize('x', [1, 2]) def test_function(self, x): assert x != 2 """ ) result, dom = runandparse(testdir) nodes = dom.getElementsByTagName("testcase") nodes_tids = [x.getAttribute("classname") + "." + x.getAttribute("name") for x in nodes] assert "test_record_test_id_with_nested_tests.TestClass.test_function[1]" in nodes_tids assert "test_record_test_id_with_nested_tests.TestClass.test_function[2]" in nodes_tids def test_record_name_with_slash(self, testdir): subdir = testdir.mkdir("sub") subdir.join("test_foo.py").write( ''' def test_logging(): assert True ''' ) result, dom = runandparse(testdir) node = dom.getElementsByTagName("testcase")[0] assert node.getAttribute("classname") == "sub.test_foo.test_logging" @pytest.mark.parametrize( "junit_family", ["xunit1", "xunit2", "legacy"], ) def test_unicode_on_longrepr(self, testdir, junit_family): testdir.makepyfile( """ # -*- coding: utf-8 -*- def test_failure(): assert 0, 'ä' """ ) result, dom = runandparse(testdir, f"--junit-family={junit_family}") assert result.ret == 1 def test_record_from_parametrized_fixture_scope_function(self, testdir): testdir.makepyfile( """ import pytest @pytest.fixture(scope="function", params=[1, 2]) def fixture(request, record_property): record_property("foo", "bar") return request.param def test_function(fixture): pass """ ) result, dom = runandparse(testdir) assert result.ret == 0 properties_by_testcase = [] testcases = dom.getElementsByTagName("testcase") for testcase in testcases: properties = testcase.getElementsByTagName("property") properties_by_testcase.append([ (prop.getAttribute("name"), prop.getAttribute("value")) for prop in properties ]) # Both testcases should have the same property. assert len(properties_by_testcase) == 2 assert properties_by_testcase[0] == [("foo", "bar")] assert properties_by_testcase[1] == [("foo", "bar")] def test_record_from_parametrized_fixture_scope_session(self, testdir): testdir.makepyfile( """ import pytest @pytest.fixture(scope="session", params=[1, 2]) def fixture(request, record_property): record_property("foo", request.param) return request.param def test_function(fixture): pass """ ) result, dom = runandparse(testdir) assert result.ret == 0 properties_by_testcase = [] testcases = dom.getElementsByTagName("testcase") for testcase in testcases: properties = testcase.getElementsByTagName("property") properties_by_testcase.append([ (prop.getAttribute("name"), prop.getAttribute("value")) for prop in properties ]) # Both testcases should have the same property. assert len(properties_by_testcase) == 2 assert properties_by_testcase[0] == [("foo", "1")] assert properties_by_testcase[1] == [("foo", "1")] def test_record_properties_from_parametrized_test(self, testdir): testdir.makepyfile( """ import pytest @pytest.mark.parametrize('x', [1, 2]) def test_function(x, record_property): record_property("foo", x) """ ) result, dom = runandparse(testdir) assert result.ret == 0 properties_by_testcase = [] testcases = dom.getElementsByTagName("testcase") for testcase in testcases: properties = testcase.getElementsByTagName("property") properties_by_testcase.append([ (prop.getAttribute("name"), prop.getAttribute("value")) for prop in properties ]) # Both testcases should have distinct properties. assert len(properties_by_testcase) == 2 assert properties_by_testcase[0] == [("foo", "1")] assert properties_by_testcase[1] == [("foo", "2")] def test_record_testsuite_property_junit_disabled(self, testdir): testdir.makepyfile( """ def test_func1(record_testsuite_property): record_testsuite_property("stats", "xyz") def test_func2(record_testsuite_property): record_testsuite_property("stats", 1) """ ) result = testdir.runpytest() assert result.ret == 0 def test_record_property_junit_disabled(self, testdir): testdir.makepyfile( """ def test_func1(record_property): record_property("stats", "xyz") """ ) result = testdir.runpytest() assert result.ret == 0 def test_record_fixtures_without_junitxml(self, testdir): testdir.makepyfile( """ def test_record_property(record_property): record_property("foo", "bar") def test_record_testsuite_property(record_testsuite_property): record_testsuite_property("foo", "bar") """ ) result = testdir.runpytest() assert result.ret == 0 @pytest.mark.parametrize( ("log_cli_level", "log_level", "log_auto_indent"), [ ("INFO", logging.INFO, " "), ("WARNING", logging.WARNING, True), ("ERROR", logging.ERROR, False), ] ) def test_live_logging_preserved_when_logging_option_log(self, testdir, log_cli_level, log_level, log_auto_indent): """Test that output from live logging is preserved when junit-logging=log.""" testdir.makepyfile( f""" import logging def test_log(): logging.getLogger().log({log_level}, 'user message') assert 0 """ ) result, dom = runandparse( testdir, f"--log-cli-level={log_cli_level}", f"--log-auto-indent={log_auto_indent}", "-o", "junit_logging=log", ) node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] assert "user message" in sysout.firstChild.nodeValue @pytest.mark.parametrize( ("log_cli_level", "log_level", "log_auto_indent"), [ ("INFO", logging.INFO, " "), ("WARNING", logging.WARNING, True), ("ERROR", logging.ERROR, False), ] ) def test_live_logging_preserved_when_logging_option_all(self, testdir, log_cli_level, log_level, log_auto_indent): """Test that output from live logging is preserved when junit-logging=all.""" testdir.makepyfile( f""" import logging def test_log(): logging.getLogger().log({log_level}, 'user message') assert 0 """ ) result, dom = runandparse( testdir, f"--log-cli-level={log_cli_level}", f"--log-auto-indent={log_auto_indent}", "-o", "junit_logging=all", ) node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] assert "user message" in sysout.firstChild.nodeValue def test_live_logging_mixed_with_caplog_messages(self, testdir): testdir.makepyfile( """ import logging def test_log(caplog): with caplog.at_level(logging.INFO): logging.getLogger().info('caplog message') logging.getLogger().warning('user message') assert 0 """ ) result, dom = runandparse( testdir, "--log-cli-level=WARNING", "-o", "junit_logging=log", ) node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] assert "caplog message" in sysout.firstChild.nodeValue assert "user message" in sysout.firstChild.nodeValue def test_live_logging_disabled_capturing_stdout(self, testdir): """Test system-out for live logging disabled, capturing stdout.""" testdir.makepyfile( """ import logging import sys def test_log(): logging.getLogger().info('user message') sys.stdout.write('stdout message') assert 0 """ ) result, dom = runandparse( testdir, "-o", "junit_logging=system-out", ) node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] assert "user message" not in sysout.firstChild.nodeValue assert "stdout message" in sysout.firstChild.nodeValue assert len(node.getElementsByTagName("system-err")) == 0 def test_live_logging_disabled_capturing_stderr(self, testdir): """Test system-err for live logging disabled, capturing stderr.""" testdir.makepyfile( """ import logging import sys def test_log(): logging.getLogger().info('user message') sys.stderr.write('stderr message') assert 0 """ ) result, dom = runandparse( testdir, "-o", "junit_logging=system-err", ) node = dom.getElementsByTagName("testcase")[0] syserr = node.getElementsByTagName("system-err")[0] assert "user message" not in syserr.firstChild.nodeValue assert "stderr message" in syserr.firstChild.nodeValue assert len(node.getElementsByTagName("system-out")) == 0 def test_live_logging_disabled_capturing_out_err(self, testdir): """Test out-err for live logging disabled, capturing both stdout and stderr.""" testdir.makepyfile( """ import logging import sys def test_log(): logging.getLogger().info('user message') sys.stdout.write('stdout message') sys.stderr.write('stderr message') assert 0 """ ) result, dom = runandparse( testdir, "-o", "junit_logging=out-err", ) node = dom.getElementsByTagName("testcase")[0] sysout = node.getElementsByTagName("system-out")[0] assert "user message" not in sysout.firstChild.nodeValue assert "stdout message" in sysout.firstChild.nodeValue assert "stderr message" not in sysout.firstChild.nodeValue syserr = node.getElementsByTagName("system-err")[0] assert "user message" not in syserr.firstChild.nodeValue assert "stdout message" not in syserr.firstChild.nodeValue assert "stderr message" in syserr.firstChild.nodeValue # yusufkarakaya/CSharpEgitimKampi # 10_DatabaseCrud/Program.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace _10_DatabaseCrud { internal class Program { static void Main(string[] args) { // Crud --> Create-Read-Update-Delete Console.WriteLine("***** Menü Sipariş İşlem Paneli *****"); Console.WriteLine(); Console.WriteLine("-----------------------------------------"); #region Kategori Ekleme İşlemi //Console.Write("Eklemek İstediğiniz Kategori Adı: "); //string categoryName = Console.ReadLine(); //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true"); //connection.Open(); //SqlCommand command = new SqlCommand("insert into TblCategory (CategoryName) values (@p1)", connection); //command.Parameters.AddWithValue("@p1", categoryName); //command.ExecuteNonQuery(); //connection.Close(); //Console.Write("Kategori başarıyla eklendi!"); #endregion #region Ürün Ekleme İşlemi //string productName; //decimal productPrice; ////bool productStatus; //Console.Write("Ürün adı: "); //productName = Console.ReadLine(); //Console.Write("Ürün fiyatı: "); //productPrice = decimal.Parse(Console.ReadLine()); //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true"); //connection.Open(); //SqlCommand command = new SqlCommand("insert into TblProduct (ProductName,ProductPrice,ProductStatus) values (@productName,@productPrice,@productStatus)", connection); //command.Parameters.AddWithValue("@productName", productName); //command.Parameters.AddWithValue("@productPrice", productPrice); //command.Parameters.AddWithValue("@productStatus", true); //command.ExecuteNonQuery(); //connection.Close(); //Console.Write("Ürün ekleme işlemi başarılı!"); #endregion #region Ürün Listeleme İşlemi //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true"); //connection.Open(); //SqlCommand command = new SqlCommand("Select * From TblProduct", connection); //SqlDataAdapter adapter = new SqlDataAdapter(command); //DataTable dataTable = new DataTable(); //adapter.Fill(dataTable); //foreach(DataRow row in dataTable.Rows) //{ // foreach(var item in row.ItemArray) // { // Console.Write(item.ToString() + " "); // } // Console.WriteLine(); //} //connection.Close(); #endregion #region Ürün Silme İşlemi //Console.Write("Silinecek Ürün Id: "); //int productId = int.Parse(Console.ReadLine()); //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true"); //connection.Open(); //SqlCommand command = new SqlCommand("Delete From TblProduct Where ProductId=@productId", connection); //command.Parameters.AddWithValue("@productId", productId); //command.ExecuteNonQuery(); //connection.Close(); //Console.WriteLine("Silme işlemi yapıldı"); #endregion #region Ürün Güncelleme İşlemi //Console.Write("Güncellenecek ürün ID: "); //int productId = int.Parse(Console.ReadLine()); //Console.Write("Güncellenecek ürün adı: "); //string productName = Console.ReadLine(); //Console.Write("Güncellenecek ürün fiyatı: "); //decimal productPrice = decimal.Parse(Console.ReadLine()); //SqlConnection connection = new SqlConnection("Data Source=YUSUF;initial Catalog=EgitimKampiDb;integrated security=true"); //connection.Open(); //SqlCommand command = new SqlCommand("Update TblProduct Set ProductName=@productName,ProductPrice=@productPrice where ProductId=@productId", connection); //command.Parameters.AddWithValue("@productName", productName); //command.Parameters.AddWithValue("@productPrice", productPrice); //command.Parameters.AddWithValue("@productId", productId); //command.ExecuteNonQuery(); //connection.Close(); //Console.WriteLine("Güncelleme işlemi başarılı"); #endregion Console.Read(); } } } End Fileusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01_MainSubjects { internal class Program { static void Main(string[] args) { #region Yazdırma Komutları //Console.Write("Merhaba Dünya"); //Console.WriteLine("Selam"); //Console.WriteLine("***** Yemek Kategorileri *****"); //Console.WriteLine(); //Console.WriteLine("1-Çorbalar"); //Console.WriteLine("2-Ana Yemekler"); //Console.WriteLine("3-Soğuk Başlangıçlar"); //Console.WriteLine("4-Salatalar"); //Console.WriteLine("5-Tatlılar"); //Console.WriteLine("6-İçecekler"); //Console.WriteLine(); //Console.WriteLine("***** Yemek Kategorileri *****"); #endregion #region String Değişkenler // string // Degisken_Turu degisken_adi; //string name; //name = "Yusuf"; //Console.Write(name); //string customerName; //string customerSurname; //string customerPhone; //string customerEmail, district, city; //customerName = "Yusuf"; //customerSurname = "Karakaya"; //customerPhone = "+90 500 400 30 20"; //customerEmail = "deneme@gmail.com"; //district = "Kadıköy"; //city = "İstanbul"; //Console.WriteLine("**** Rezervasyon Kartı ****"); //Console.WriteLine(); //Console.WriteLine("------------------------------------------------"); //Console.WriteLine("Müşteri: " + customerName + " " + customerSurname); //Console.WriteLine("İletişim: " + customerPhone); //Console.WriteLine("Email Adresi: " + customerEmail); //Console.WriteLine("Adres: " + district + "/" + city); //Console.WriteLine("------------------------------------------------"); //Console.WriteLine(); //customerName = "Ayşegül"; //customerSurname = "Kaya"; //customerPhone = "+90 400 300 80 70"; //customerEmail = "test@gmail.com"; //district = "Sapanca"; //city = "Sakarya"; //Console.WriteLine("------------------------------------------------"); //Console.WriteLine("Müşteri: " + customerName + " " + customerSurname); //Console.WriteLine("İletişim: " + customerPhone); //Console.WriteLine("Email Adresi: " + customerEmail); //Console.WriteLine("Adres: " + district + "/" + city); //Console.WriteLine("------------------------------------------------"); #endregion #region Int Değişkenler // int //int number = 24; //Console.WriteLine(number); int hamburgerPrice = 300; int cokePrice = 35; int waterPrice = 10; int friesPrice = 50; int pizzaPrice = 250; int lemonadePrice = 30; Console.WriteLine("**** Restoran Menü Fiyatı ****"); Console.WriteLine(); Console.WriteLine("-----Hamburger: " + hamburgerPrice + " TL"); Console.WriteLine("-----Pizza: " + pizzaPrice + " TL"); Console.WriteLine("-----Kola: " + cokePrice + " TL"); Console.WriteLine("-----Limonata: " + lemonadePrice + " TL"); Console.WriteLine("-----Kızartma: " + friesPrice + " TL"); Console.WriteLine("-----Su: " + waterPrice + " TL"); Console.WriteLine(); Console.WriteLine("**** Restoran Menü Fiyatı ****"); Console.WriteLine(); int hamburgerCount; int cokeCount; int waterCount; int friesCount; int pizzaCount; int lemonadeCount; int totalHamburgerPrice; int totalCokePrice; int totalWaterPrice; int totalFriesPrice; int totalPizzaPrice; int totalLemonadePrice; hamburgerCount = 3; cokeCount = 3; waterCount = 3; friesCount = 1; pizzaCount = 0; lemonadeCount = 0; totalHamburgerPrice = hamburgerCount * hamburgerPrice; totalCokePrice = cokeCount * cokePrice; totalWaterPrice = waterCount * waterPrice; totalLemonadePrice = lemonadeCount * lemonadePrice; totalFriesPrice = friesCount * friesPrice; totalPizzaPrice = pizzaCount * pizzaPrice; Console.WriteLine("------------------------------"); Console.WriteLine("Hamburger Tutarı: " + totalHamburgerPrice + " TL"); Console.WriteLine("Pizza Tutarı: " + totalPizzaPrice + " TL"); Console.WriteLine("Kızartma Tutarı: " + totalFriesPrice + " TL"); Console.WriteLine("Kola Tutarı: " + totalCokePrice + " TL"); Console.WriteLine("Limonata Tutarı: " + totalLemonadePrice + " TL"); Console.WriteLine("Su Tutarı: " + totalWaterPrice + " TL"); Console.WriteLine(); int totalPrice = totalCokePrice + totalWaterPrice + totalLemonadePrice + totalHamburgerPrice + totalFriesPrice + totalPizzaPrice; Console.WriteLine("Toplam Ödenecek Tutar: " + totalPrice + " TL"); #endregion Console.Read(); } } } # CKXMH/CKXMH # _projects/SNIG.md --- layout: page title: SNIG description: A Sparse Multi-GPU Framework for Accelerating Deep Neural Network Inference img: assets/img/project_imgs/SNIG.png importance: 3 category: Research related_publications: --- ## SNIG (Sparse Neural network Inference GPU framework) SNIG is a GPU-acceleration framework for distributed sparse DNN inference. SNIG leverages a bi-directional task-graph scheduling algorithm that incorporates both computation and communication cost for inference latency minimization. ### Project Overview This project was built with the collaboration with my advisor Dr. Martin Wong at the University of Illinois at Urbana-Champaign and my research mentor Dr. Tsung-Wei Huang at the University of Utah. <div class="row"> <div class="col-sm mt-3 mt-md-0"> {% include figure.html path="assets/img/project_imgs/SNIG.png" title="SNIG framework" class="img-fluid rounded z-depth-1" %} </div> </div> <div class="caption"> Architecture of SNIG framework. </div> SNIG is a GPU-accelerated framework for distributed sparse deep neural network (DNN) inference. Unlike traditional dense approaches, SNIG exploits sparsity patterns in neural networks to achieve significant memory and computational efficiency improvements. The framework features: - **Bi-directional Task Graph Scheduling**: Optimizes both computation and communication costs across multiple GPUs - **Sparse Matrix Operations**: Efficient handling of sparse weight matrices using CSR (Compressed Sparse Row) format - **Multi-GPU Parallelization**: Distributed inference across multiple GPUs with optimized data transfers - **Dynamic Load Balancing**: Adaptive workload distribution based on computational complexity ### Publications - Huang, T. W., Lei, C. X., Wong, M. D. F. (2021). "SNIG: A multi-GPU framework for accelerating sparse deep neural network inference." arXiv preprint arXiv:2105.08165. ### GitHub Repository The source code and documentation are available at: [SNIG GitHub Repository](https://github.com/CKXMH/SNIG) ### Key Contributions 1. Developed efficient sparse matrix multiplication kernels optimized for GPU architectures 2. Implemented a novel bi-directional scheduling algorithm for multi-GPU inference 3. Achieved significant speedup compared to existing sparse DNN inference frameworks 4. Provided comprehensive benchmarking on various sparse neural network architectures The framework demonstrates substantial performance improvements over existing methods, particularly for highly sparse networks commonly found in modern deep learning applications. ### Implementation Details The implementation leverages CUDA for GPU acceleration and MPI for multi-GPU communication. Key algorithmic innovations include optimized sparse matrix storage formats and intelligent workload partitioning strategies that minimize inter-GPU communication overhead while maximizing computational throughput. End File# CKXMH/CKXMH --- layout: page title: Stiffness Prediction description: Developing a machine learning model to predict stiffness properties for composites reinforced with recycled carbon fiber img: assets/img/project_imgs/StiffnessPrediction.jpeg importance: 2 category: Research related_publications: --- ## Stiffness Prediction for Recycled Carbon Fiber Composites This research project focused on developing machine learning models to predict the stiffness properties of composite materials reinforced with recycled carbon fiber. The work was conducted as part of my research at the University of Illinois at Urbana-Champaign under the supervision of Dr. Amy Wagoner Johnson. ### Project Overview The textile and composites industry produces significant waste, leading to environmental concerns. Recycled carbon fiber offers a sustainable solution, but its mechanical properties often differ from virgin fibers due to the recycling process. This project aimed to create predictive models that could estimate composite stiffness based on various parameters of recycled carbon fiber. <div class="row"> <div class="col-sm mt-3 mt-md-0"> {% include figure.html path="assets/img/project_imgs/StiffnessPrediction.jpeg" title="Stiffness Prediction" class="img-fluid rounded z-depth-1" %} </div> </div> <div class="caption"> Machine learning pipeline for predicting composite stiffness using recycled carbon fiber parameters. </div> ### Key Contributions 1. **Data Collection and Processing**: Compiled a comprehensive dataset of recycled carbon fiber properties including fiber length, diameter, surface treatment conditions, and resulting composite stiffness values. 2. **Feature Engineering**: Developed relevant features capturing the relationship between fiber characteristics and composite mechanical properties. 3. **Model Development**: Implemented and compared multiple machine learning algorithms including: - Random Forest Regression - Support Vector Regression - Neural Networks - Gradient Boosting methods 4. **Model Validation**: Established robust validation procedures to ensure model reliability and generalizability across different recycling conditions. ### Technical Approach The project involved several key technical components: - **Data Preprocessing**: Handling missing values, outlier detection, and normalization of multi-scale features - **Feature Selection**: Identifying the most influential parameters affecting composite stiffness - **Hyperparameter Optimization**: Using grid search and random search methods to optimize model performance - **Cross-validation**: Implementing k-fold cross-validation to assess model robustness ### Results and Impact The developed models achieved significant predictive accuracy, enabling: - Rapid assessment of recycled carbon fiber quality - Optimization of recycling processes to maximize composite performance - Reduced need for extensive mechanical testing - Support for sustainable manufacturing decisions ### Applications This research contributes to: - Sustainable materials engineering - Circular economy in composites manufacturing - Quality control in recycling processes - Cost-effective material characterization The predictive models developed in this project provide valuable tools for manufacturers working with recycled carbon fiber, supporting both environmental sustainability and economic viability in composite materials production. ### Future Directions Potential extensions of this work include: - Integration with real-time manufacturing processes - Extension to other recycled fiber types - Development of multi-objective optimization frameworks - Implementation in industrial quality control systems End File# CKXMH/CKXMH # _projects/SAT.md --- layout: page title: SAT Solver description: A modern SAT solver designed for massively parallel GPU architectures img: assets/img/project_imgs/SAT.png importance: 1 category: Research --- ## Modern SAT Solver for GPU Architectures This project presents the development of a high-performance Boolean Satisfiability (SAT) solver specifically designed to leverage the computational power of modern GPU architectures. The solver incorporates advanced algorithmic techniques and parallel computing strategies to achieve significant performance improvements over traditional CPU-based approaches. ### Project Overview <div class="row"> <div class="col-sm mt-3 mt-md-0"> {% include figure.html path="assets/img/project_imgs/SAT.png" title="SAT Solver Architecture" class="img-fluid rounded z-depth-1" %} </div> </div> <div class="caption"> Overview of the GPU-accelerated SAT solver architecture showing the parallel processing pipeline. </div> The SAT problem, being NP-complete, represents one of the most fundamental challenges in computer science and has numerous applications in formal verification, automated reasoning, and artificial intelligence. This project addresses the computational complexity by harnessing the massively parallel architecture of modern GPUs. ### Key Features - **Parallel DPLL Algorithm**: Implementation of the Davis-Putnam-Logemann-Loveland (DPLL) algorithm optimized for GPU execution - **Conflict-Driven Clause Learning (CDCL)**: Advanced backtracking with learned clauses to prune the search space - **GPU Memory Optimization**: Efficient memory management strategies for handling large SAT instances - **Dynamic Load Balancing**: Adaptive workload distribution across GPU cores ### Technical Implementation The solver incorporates several key algorithmic innovations: 1. **Massively Parallel Search**: Utilizes thousands of GPU threads to explore different branches of the search tree simultaneously 2. **Optimized Data Structures**: Custom data structures designed for GPU memory hierarchy and access patterns 3. **Heuristic Integration**: Implementation of modern SAT solving heuristics adapted for parallel execution 4. **Clause Database Management**: Efficient storage and retrieval of learned clauses across parallel threads ### Performance Results The GPU-accelerated solver demonstrates significant performance improvements: - Up to 10x speedup compared to state-of-the-art CPU solvers on large instances - Improved scalability with problem size - Efficient utilization of GPU resources with high occupancy rates ### Applications This SAT solver has applications in: - **Formal Verification**: Hardware and software verification problems - **AI Planning**: Automated planning and scheduling - **Circuit Design**: Electronic design automation - **Cryptanalysis**: Breaking cryptographic systems ### Technical Challenges and Solutions The project addressed several key challenges: 1. **Memory Divergence**: Implemented coalesced memory access patterns to minimize performance penalties 2. **Thread Divergence**: Developed strategies to minimize branch divergence in parallel execution 3. **Scalability**: Designed algorithms that maintain efficiency as problem size increases 4. **Load Balancing**: Created dynamic work distribution mechanisms for irregular workloads ### Future Directions Ongoing development focuses on: - Integration with machine learning techniques for improved heuristics - Multi-GPU scaling for extremely large problem instances - Specialized optimizations for specific application domains - Hybrid CPU-GPU execution strategies This research contributes to the advancement of high-performance computing in combinatorial optimization and provides a foundation for future developments in parallel constraint satisfaction. ### Code Repository The source code and documentation for this project are available upon request, including benchmarking suites and performance analysis tools. End File# CKXMH/CKXMH --- layout: about title: about permalink: / subtitle: <a href='#'>Affiliations</a>. Address. Contacts. Moto. Etc. profile: align: right image: prof_pic.jpg image_circular: false # crops the image to make it circular more_info: > <p>chenlei2@illinois.edu</p> <p>University of Illinois at Urbana-Champaign</p> news: true # includes a list of news items latest_posts: false # includes a list of the newest posts selected_papers: false # includes a list of papers marked as "selected={true}" social: true # includes social icons at the bottom of the page --- Welcome! I'm Chenlei (Isaac) Xu, a dedicated researcher and engineer with a passion for high-performance computing, artificial intelligence, and sustainable engineering solutions. I am currently pursuing my PhD in Computer Science at the University of Illinois at Urbana-Champaign, where I work under the guidance of [Dr. Martin Wong](https://publish.illinois.edu/mdfwong/) on cutting-edge problems in parallel computing and GPU acceleration. My research focuses on developing efficient algorithms and frameworks for sparse deep neural network inference on multi-GPU systems. Previously, I earned my Master's degree in Computer Science from UIUC, where I had the privilege of working with [Dr. Amy Wagoner Johnson](https://mechse.illinois.edu/people/profile/awj) on interdisciplinary research combining machine learning with materials science. This work involved developing predictive models for composite materials reinforced with recycled carbon fiber, contributing to sustainable manufacturing practices. ### Research Interests My research interests span several interconnected areas: - **High-Performance Computing**: Developing efficient parallel algorithms and GPU-accelerated frameworks - **Machine Learning Systems**: Optimizing deep learning inference for sparse neural networks - **Sustainable Computing**: Applying ML techniques to environmental and materials science challenges - **Computer Graphics**: Exploring computational methods for visual simulation and rendering ### Current Work I'm currently focused on **SNIG** (Sparse Neural network Inference GPU framework), a multi-GPU framework designed to accelerate sparse deep neural network inference. This work addresses the growing computational demands of modern AI systems while leveraging sparsity patterns to achieve significant efficiency improvements. I'm also exploring applications of machine learning in materials science, particularly in predicting mechanical properties of recycled composite materials, bridging the gap between computational methods and sustainable engineering practices. ### Beyond Research When I'm not immersed in code or research papers, I enjoy exploring new technologies, contributing to open-source projects, and staying active in the academic community. I believe in the power of interdisciplinary collaboration and am always excited to connect with fellow researchers and engineers working on challenging problems. Feel free to reach out if you'd like to discuss research collaborations, share ideas, or simply connect! End File# _news/announcement_1.md --- layout: post title: A long-form announcement with details date: 2015-10-22 15:59:00-0400 inline: false related_posts: false --- Exciting news! I'm thrilled to share some recent developments in my research journey. *** #### Research Milestone: SNIG Framework Development I'm proud to announce a significant milestone in my PhD research - the development of **SNIG** (Sparse Neural network Inference GPU framework), a cutting-edge multi-GPU framework designed specifically for accelerating sparse deep neural network inference. #### What makes SNIG special? SNIG addresses a critical challenge in modern AI systems: efficiently handling sparse neural networks across multiple GPUs. Key innovations include: - **Bi-directional Task Graph Scheduling**: A novel scheduling algorithm that optimizes both computation and communication costs - **Multi-GPU Parallelization**: Distributed inference across multiple GPUs with intelligent workload balancing - **Sparse Matrix Optimization**: Efficient handling of sparse weight matrices using advanced data structures #### Performance Results The framework demonstrates remarkable performance improvements: - Significant speedup compared to existing sparse DNN inference methods - Excellent scalability across multiple GPU configurations - Efficient memory utilization for large-scale neural networks #### Publication and Open Source This work has been documented in our research paper: > Huang, T. W., Lei, C. X., Wong, M. D. F. (2021). "SNIG: A multi-GPU framework for accelerating sparse deep neural network inference." arXiv preprint arXiv:2105.08165. The complete source code and documentation are available on [GitHub](https://github.com/CKXMH/SNIG), making it accessible to the broader research community. #### Looking Forward This milestone represents not just a technical achievement, but a step toward making AI inference more efficient and accessible. As we continue to see the proliferation of sparse neural networks in production systems, frameworks like SNIG will play a crucial role in democratizing high-performance AI inference. I'm excited to continue pushing the boundaries of high-performance computing and look forward to the next challenges ahead! --- *For more details about my research or potential collaborations, feel free to reach out at chenlei2@illinois.edu* # docs/quickstart.md # Quickstart How to get started with Aya. ## Prerequisites Install a recent version of Rust === "Linux" ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` === "macOS" ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` === "Windows" To install Rust on Windows, download and run [rustup-init.exe](https://rustup.rs/) Install the `bpf-linker`: `cargo install bpf-linker` ## 1. Install `aya-gen` (optional) `aya-gen` allows you to generate Rust bindings from BTF: ```bash cargo install aya-gen ``` ## 2. Install `bpftool` (optional) If you want to use `aya-gen` with locally generated BTF, you'll need `bpftool`: === "Ubuntu" ```bash apt install linux-tools-generic ``` === "Fedora" ```bash dnf install bpftool ``` ## 3. Generate a template If you don't want to generate a template, you can go to [manually adding aya](#manually-adding-aya-as-a-dependency). First, install `cargo-generate`: ```bash cargo install cargo-generate ``` Then run: ```bash cargo generate https://github.com/aya-rs/aya-template ``` Since the template makes use of [Cargo Workspaces](https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html), the generated project will have a directory layout that looks something like: ``` myapp/ ├── Cargo.toml (workspace) ├── myapp/ │ ├── src/ │ │ └── main.rs │ └── Cargo.toml ├── myapp-common/ │ ├── src/ │ │ └── lib.rs │ └── Cargo.toml └── myapp-ebpf/ ├── src/ │ └── main.rs └── Cargo.toml ``` The generated project can be used as starting point for working with Aya: * `myapp` contains the userspace code and is responsible for loading, attaching and interacting with the eBPF program * `myapp-ebpf` contains the eBPF program, which can be compiled into bytecode and embedded in the userspace binary. * `myapp-common` contains code shared by userspace and eBPF code. To build the eBPF program: ```bash cd myapp-ebpf cargo xtask build-ebpf ``` To build the userspace program: ```bash cd myapp cargo build ``` ## Manually adding `aya` as a dependency If you prefer to add `aya` as a dependency manually, add it to your `Cargo.toml`: ```toml aya = "{{ aya_version }}" tokio = { version = "1.24", features = ["macros", "rt", "rt-multi-thread", "net", "signal"] } ``` Then you can start by loading and attaching a program: ```rust use aya::Ebpf; let mut bpf = Ebpf::load(include_bytes!("../path/to/program.o"))?; // use `bpf` to work with the loaded program ``` End File# aya/src/programs/tc.rs //! Traffic control programs. use std::os::fd::AsFd; use crate::{ generated::{bpf_attach_type::BPF_TCX_EGRESS, bpf_prog_type::BPF_PROG_TYPE_SCHED_CLS}, programs::{ define_link_wrapper, load_program, FdLink, FdLinkId, Link, ProgAttachLink, ProgramData, ProgramError, }, sys::{bpf_link_create, LinkTarget, SyscallError}, util::KernelVersion, }; /// A traffic control classifier. /// /// [`SchedClassifier`] programs can be used to inspect, filter or redirect /// network packets in both ingress and egress. They are executed as part of /// the linux traffic control system. See /// <https://man7.org/linux/man-pages/man8/tc-bpf.8.html>. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.1. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Ebpf::load(&[])?; /// use aya::{Ebpf, programs::SchedClassifier, util::tc::{TcAttachOptions, TcAttachType}}; /// /// let prog: &mut SchedClassifier = bpf.program_mut("redirect_ingress").unwrap().try_into()?; /// prog.load()?; /// /// // Attach to the root qdisc of the eth0 interface, with default options /// prog.attach("eth0", TcAttachType::Ingress, TcAttachOptions::default())?; /// # Ok::<(), aya::EbpfError>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_SCHED_CLS")] pub struct SchedClassifier { pub(crate) data: ProgramData<SchedClassifierLink>, } impl SchedClassifier { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_SCHED_CLS, &mut self.data) } /// Returns the name of the program. pub fn name(&self) -> &str { &self.data.name } /// Returns the name of the program on kernels >= 5.0. /// /// On older kernels, this will return `None`. pub fn kernel_name(&self) -> Option<&std::ffi::CStr> { self.data.kernel_name.as_deref() } /// Attaches the program to the given `interface`. /// /// The returned value can be used to detach, see [SchedClassifier::detach]. /// /// For more info, see [TcAttachOptions]. pub fn attach( &mut self, interface: &str, attach_type: crate::util::tc::TcAttachType, options: crate::util::tc::TcAttachOptions, ) -> Result<SchedClassifierLinkId, ProgramError> { let link = crate::util::tc::attach(&mut self.data, interface, attach_type, options)?; self.data.links.insert(SchedClassifierLink::Tc(link)) } /// Attaches the program to the TCX (TC eXpress) ingress hook. /// /// The returned value can be used to detach the program, see [SchedClassifier::detach]. pub fn attach_tcx_ingress<T: AsFd>( &mut self, interface: T, ) -> Result<SchedClassifierLinkId, ProgramError> { let link_fd = bpf_link_create( self.fd(), LinkTarget::IfIndex(interface.as_fd()), BPF_TCX_EGRESS, None, 0, ) .map_err(|(_, io_error)| SyscallError { call: "bpf_link_create", io_error, })?; self.data .links .insert(SchedClassifierLink::Fd(FdLink::from_fd(link_fd))) } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: SchedClassifierLinkId, ) -> Result<SchedClassifierLink, ProgramError> { self.data.take_link(link_id) } /// Detaches the program. /// /// See [SchedClassifier::attach]. pub fn detach(&mut self, link_id: SchedClassifierLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id)?.detach() } } #[derive(Debug)] pub enum SchedClassifierLink { Tc(crate::util::tc::TcLink), Fd(FdLink), } impl Link for SchedClassifierLink { type Id = SchedClassifierLinkId; fn id(&self) -> Self::Id { match self { Self::Tc(link) => SchedClassifierLinkId(link.id().0), Self::Fd(fd_link) => SchedClassifierLinkId(fd_link.id().0), } } fn detach(self) -> Result<(), ProgramError> { match self { Self::Tc(link) => link.detach(), Self::Fd(link) => link.detach(), } } } define_link_wrapper!( /// The link used by [SchedClassifier] programs. SchedClassifierLinkId, SchedClassifierLink, SchedClassifierLinkInner, SchedClassifierLinkIdInner ); impl TryFrom<SchedClassifierLink> for FdLink { type Error = SchedClassifierLink; fn try_from(value: SchedClassifierLink) -> Result<Self, Self::Error> { match value { SchedClassifierLink::Fd(fd) => Ok(fd), _ => Err(value), } } } impl From<FdLink> for SchedClassifierLink { fn from(fd_link: FdLink) -> Self { Self::Fd(fd_link) } } impl TryFrom<SchedClassifierLink> for crate::util::tc::TcLink { type Error = SchedClassifierLink; fn try_from(value: SchedClassifierLink) -> Result<Self, Self::Error> { match value { SchedClassifierLink::Tc(tc) => Ok(tc), _ => Err(value), } } } impl From<crate::util::tc::TcLink> for SchedClassifierLink { fn from(tc_link: crate::util::tc::TcLink) -> Self { Self::Tc(tc_link) } } impl ProgAttachLink for SchedClassifierLink { fn prog_attach_link() -> Self { Self::Fd(FdLink::prog_attach_link()) } fn prog_detach_link(_: &Self, _: Option<u32>) -> Result<(), ProgramError> { // TODO: The old attach API is deprecated and will be removed. // https://github.com/aya-rs/aya/issues/540 Ok(()) } fn version() -> Option<KernelVersion> { // TODO: The old attach API is deprecated and will be removed. // When we remove it, we can uncomment the line below. // https://github.com/aya-rs/aya/issues/540 // // Some(KernelVersion::new(5, 7, 0)) None } } End File//! Cgroup skb programs. use std::{ hash::Hash, os::fd::{AsFd, AsRawFd}, }; use crate::{ generated::{ bpf_attach_type::{BPF_CGROUP_INET_EGRESS, BPF_CGROUP_INET_INGRESS}, bpf_prog_type::BPF_PROG_TYPE_CGROUP_SKB, }, programs::{ define_link_wrapper, load_program, FdLink, Link, ProgAttachLink, ProgAttachLinkId, ProgramData, ProgramError, }, sys::SyscallError, util::KernelVersion, ProgFd, }; /// A program used to inspect or filter network activity for cgroups. /// /// [`CgroupSkb`] programs can be used to inspect or filter network packets /// sent/received by processes inside a cgroup. They can be attached to both /// *ingress* and *egress*. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 4.10. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Ebpf::load(&[])?; /// use std::fs::File; /// use aya::{Ebpf, programs::{CgroupSkb, CgroupSkbAttachType}}; /// /// let file = File::open("/sys/fs/cgroup/unified")?; /// let program: &mut CgroupSkb = bpf.program_mut("cgroup_skb_egress").unwrap().try_into()?; /// program.load()?; /// program.attach(file, CgroupSkbAttachType::Egress)?; /// # Ok::<(), aya::EbpfError>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_CGROUP_SKB")] pub struct CgroupSkb { pub(crate) data: ProgramData<CgroupSkbLink>, } impl CgroupSkb { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { load_program(BPF_PROG_TYPE_CGROUP_SKB, &mut self.data) } /// Attaches the program to the given cgroup. /// /// The returned value can be used to detach, see [CgroupSkb::detach]. pub fn attach<T: AsFd>( &mut self, cgroup: T, attach_type: CgroupSkbAttachType, ) -> Result<CgroupSkbLinkId, ProgramError> { let prog_fd = self.fd(); let cgroup_fd = cgroup.as_fd(); let attach_type = match attach_type { CgroupSkbAttachType::Ingress => BPF_CGROUP_INET_INGRESS, CgroupSkbAttachType::Egress => BPF_CGROUP_INET_EGRESS, }; let link_id = self.data.links.insert(CgroupSkbLink::new( prog_fd, cgroup_fd.as_raw_fd(), attach_type, )); let link = self.data.links.get_mut(link_id).ok_or(ProgramError::SyscallError { call: "insert", io_error: std::io::Error::from_raw_os_error(libc::ENOENT), })?; link.attach(prog_fd)?; Ok(link_id) } /// Detaches the program. /// /// See [CgroupSkb::attach]. pub fn detach(&mut self, link_id: CgroupSkbLinkId) -> Result<(), ProgramError> { self.data.links.remove(link_id)?.detach() } /// Takes ownership of the link referenced by the provided link_id. /// /// The link will be detached on `Drop` and the caller is now responsible /// for managing its lifetime. pub fn take_link( &mut self, link_id: CgroupSkbLinkId, ) -> Result<CgroupSkbLink, ProgramError> { self.data.take_link(link_id) } /// Returns the name of the program. pub fn name(&self) -> &str { &self.data.name } /// Returns the name of the program on kernels >= 5.0. /// /// On older kernels, this will return `None`. pub fn kernel_name(&self) -> Option<&std::ffi::CStr> { self.data.kernel_name.as_deref() } } #[derive(Debug, Hash, Eq, PartialEq)] pub(crate) struct CgroupSkbLinkInner { cgroup_fd: std::os::fd::RawFd, attach_type: u32, } impl CgroupSkbLinkInner { pub(crate) fn new(cgroup_fd: std::os::fd::RawFd, attach_type: u32) -> Self { Self { cgroup_fd, attach_type, } } } define_link_wrapper!( /// The link used by [CgroupSkb] programs. CgroupSkbLinkId, CgroupSkbLink, CgroupSkbLinkInner, CgroupSkbLinkIdInner ); // SAFETY: the `inner` value is never changed, so this link can be transferred // across threads. unsafe impl Send for CgroupSkbLink {} unsafe impl Sync for CgroupSkbLink {} impl CgroupSkbLink { pub(crate) fn new( prog_fd: ProgFd, cgroup_fd: std::os::fd::RawFd, attach_type: u32, ) -> Self { Self::FdLink(FdLink::from_link(ProgAttachLinkId( CgroupSkbLinkInner::new(cgroup_fd, attach_type), ))) } } impl Link for CgroupSkbLink { type Id = CgroupSkbLinkId; fn id(&self) -> Self::Id { CgroupSkbLinkId(self.fd_link().id().0) } fn detach(self) -> Result<(), ProgramError> { self.fd_link().detach() } } impl ProgAttachLink for CgroupSkbLink { fn prog_attach_link() -> Self { Self::FdLink(FdLink::prog_attach_link()) } fn prog_detach_link(link: &Self, current: Option<ProgFd>) -> Result<(), ProgramError> { let CgroupSkbLinkInner { cgroup_fd, attach_type, } = link.fd_link().link_id().0; crate::sys::bpf_prog_detach(current, cgroup_fd, attach_type).map_err(|(_, io_error)| { ProgramError::SyscallError { call: "bpf_prog_detach", io_error, } })?; Ok(()) } fn version() -> Option<KernelVersion> { None } } /// Defines where to attach a [`CgroupSkb`] program. #[derive(Copy, Clone, Debug)] pub enum CgroupSkbAttachType { /// Attach to ingress. Ingress, /// Attach to egress. Egress, } impl TryFrom<CgroupSkbLink> for FdLink { type Error = CgroupSkbLink; fn try_from(value: CgroupSkbLink) -> Result<Self, Self::Error> { match value { CgroupSkbLink::FdLink(fd) => Ok(fd), _ => Err(value), } } } impl From<FdLink> for CgroupSkbLink { fn from(fd_link: FdLink) -> Self { Self::FdLink(fd_link) } } End File//! Extension programs. use crate::{ generated::bpf_prog_type::BPF_PROG_TYPE_EXT, obj::btf::{Btf, BtfKind}, programs::{load_program, ProgramData, ProgramError, ProgramFd}, sys::bpf_load_program, }; /// A program used to extend other programs. /// /// [`Extension`] programs can be used to extend the functionality of other /// eBPF programs by replacing their functions. They are commonly used for /// debugging, tracing, or modifying the behavior of existing programs. /// /// # Minimum kernel version /// /// The minimum kernel version required to use this feature is 5.9. /// /// # Examples /// /// ```no_run /// # let mut bpf = aya::Ebpf::load(&[])?; /// use aya::{Ebpf, programs::Extension}; /// /// let program: &mut Extension = bpf.program_mut("extension").unwrap().try_into()?; /// program.load("target_program", "target_function")?; /// # Ok::<(), aya::EbpfError>(()) /// ``` #[derive(Debug)] #[doc(alias = "BPF_PROG_TYPE_EXT")] pub struct Extension { pub(crate) data: ProgramData<ExtensionLink>, } impl Extension { /// Loads the extension inside the kernel. /// /// Prepares the extension to replace the function `func_name` inside the /// eBPF program `program`. /// /// The `program` parameter must be the name of a loaded eBPF program. The /// extension will replace the function `func_name` inside that program. pub fn load( &mut self, program: &str, func_name: &str, ) -> Result<ProgramFd, ProgramError> { // Find the target program by name let target_prog_fd = { let programs = crate::sys::loaded_programs() .map_err(|io_error| ProgramError::SyscallError { call: "loaded_programs", io_error, })?; programs .into_iter() .find(|p| p.name.as_deref() == Some(program.as_ref())) .ok_or_else(|| ProgramError::Extension { name: program.to_string(), })? .fd }; // Get the target program info to find the function offset let target_info = crate::sys::bpf_prog_get_info_by_fd(target_prog_fd.as_fd()) .map_err(|(_, io_error)| ProgramError::SyscallError { call: "bpf_prog_get_info_by_fd", io_error, })?; let btf_fd = target_info.btf_id.and_then(|btf_id| { crate::sys::bpf_btf_get_fd_by_id(btf_id) .map_err(|(_, io_error)| ProgramError::SyscallError { call: "bpf_btf_get_fd_by_id", io_error, }) .ok() }); let (btf_fd, func_info_rec_size, func_info) = if let Some(btf_fd) = btf_fd { let btf_info = crate::sys::bpf_btf_get_info_by_fd(btf_fd.as_fd()) .map_err(|(_, io_error)| ProgramError::SyscallError { call: "bpf_btf_get_info_by_fd", io_error, })?; let btf_data = crate::sys::btf_obj_get_data_by_fd(btf_fd.as_fd()) .map_err(|io_error| ProgramError::SyscallError { call: "btf_obj_get_data_by_fd", io_error, })?; let btf = Btf::parse(&btf_data, crate::obj::btf::Endianness::default()) .map_err(ProgramError::Btf)?; // Find the target function in BTF let func_type_id = btf .types() .enumerate() .find_map(|(i, ty)| { if let BtfKind::Func(func) = &ty.kind { if btf.string_at(func.name_offset).ok()? == func_name { return Some(i as u32 + 1); // BTF IDs are 1-indexed } } None }) .ok_or_else(|| ProgramError::Extension { name: func_name.to_string(), })?; ( Some(btf_fd), target_info.func_info_rec_size, vec![func_type_id], ) } else { (None, 0, Vec::new()) }; let fd = bpf_load_program( BPF_PROG_TYPE_EXT, &self.data.instructions, self.data.kernel_version.unwrap_or_default(), self.data.verifier_log_level, &self.data.license, Some(target_prog_fd.as_fd()), btf_fd.as_ref().map(|fd| fd.as_fd()), &func_info, func_info_rec_size, &[], 0, &[], 0, ) .map_err(|(_, io_error)| ProgramError::LoadError { io_error, verifier_log: self.data.verifier_log.clone(), })?; self.data.fd = Some(fd); Ok(fd) } /// Returns the name of the program. pub fn name(&self) -> &str { &self.data.name } /// Returns the name of the program on kernels >= 5.0. /// /// On older kernels, this will return `None`. pub fn kernel_name(&self) -> Option<&std::ffi::CStr> { self.data.kernel_name.as_deref() } } #[derive(Debug)] pub struct ExtensionLink; impl crate::programs::Link for ExtensionLink { type Id = ExtensionLinkId; fn id(&self) -> Self::Id { ExtensionLinkId } fn detach(self) -> Result<(), ProgramError> { Ok(()) } } #[derive(Debug)] pub struct ExtensionLinkId; # RaagaSarayu/KnowledgeGraph # README.md # Knowledge Graph Extraction from Documents with LangChain and NetworkX This project demonstrates how to extract knowledge graphs from text documents using LangChain for natural language processing and NetworkX for graph visualization. ## What is a Knowledge Graph? A knowledge graph is a structured representation of knowledge that captures entities, their relationships, and attributes in a graph format. In this format: - **Nodes** represent entities (people, places, concepts, etc.) - **Edges** represent relationships between entities - **Labels** provide additional context or properties Knowledge graphs are particularly useful for: - Information retrieval and search - Question answering systems - Recommendation engines - Understanding complex relationships in data - Semantic analysis of documents ## Features - Extract entities and relationships from text using OpenAI's GPT models via LangChain - Generate structured knowledge graphs using NetworkX - Interactive visualization with customizable layouts - Support for various document formats - Configurable entity and relationship extraction ## Installation 1. Clone this repository: ```bash git clone https://github.com/yourusername/knowledge-graph-extraction.git cd knowledge-graph-extraction ``` 2. Install required packages: ```bash pip install langchain openai networkx matplotlib pandas numpy python-dotenv ``` 3. Set up your OpenAI API key: - Create a `.env` file in the project root - Add your OpenAI API key: ``` OPENAI_API_KEY=your_api_key_here ``` ## Usage ### Basic Example ```python from knowledge_graph_extractor import KnowledgeGraphExtractor # Initialize the extractor extractor = KnowledgeGraphExtractor() # Sample text text = """ Albert Einstein was born in Ulm, Germany in 1879. He developed the theory of relativity while working as a patent clerk in Bern, Switzerland. Einstein later moved to Princeton University in the United States where he continued his research until his death in 1955. """ # Extract knowledge graph graph = extractor.extract_knowledge_graph(text) # Visualize the graph extractor.visualize_graph(graph) ``` ### Working with Documents ```python # Load from file with open('document.txt', 'r') as f: text = f.read() # Extract and visualize graph = extractor.extract_knowledge_graph(text) extractor.visualize_graph(graph, layout='spring', figsize=(12, 8)) ``` ## How It Works 1. **Text Processing**: The input text is processed and cleaned using LangChain utilities 2. **Entity Extraction**: Using OpenAI's GPT models, entities (nouns, proper nouns) are identified in the text 3. **Relationship Extraction**: The model identifies relationships between entities using natural language understanding 4. **Graph Construction**: NetworkX creates a graph structure with extracted entities as nodes and relationships as edges 5. **Visualization**: The graph is rendered using matplotlib with customizable layouts ## Configuration You can customize the extraction process: ```python extractor = KnowledgeGraphExtractor( model_name="gpt-3.5-turbo", # or "gpt-4" max_tokens=1000, temperature=0.1 ) ``` ## Visualization Options The visualizer supports different layouts: - `spring`: Default spring layout - `circular`: Circular arrangement - `random`: Random positioning - `shell`: Concentric shell layout ```python extractor.visualize_graph( graph, layout='spring', figsize=(15, 10), node_color='lightblue', edge_color='gray', font_size=8 ) ``` ## Example Output The knowledge graph will show: - **Entities**: People, places, organizations, concepts - **Relationships**: "born in", "worked at", "developed", "moved to", etc. - **Visual representation**: Interactive graph with labeled nodes and edges ## Applications This tool can be used for: - **Document Analysis**: Understanding key relationships in research papers, reports, or articles - **Information Extraction**: Building structured databases from unstructured text - **Educational Tools**: Visualizing concepts and their relationships in textbooks - **Business Intelligence**: Mapping relationships in business documents - **Research**: Analyzing scientific literature for connections between concepts ## Requirements - Python 3.7+ - OpenAI API key - Required packages (see installation section) ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change. ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## Acknowledgments - Built with [LangChain](https://github.com/hwchase17/langchain) for LLM integration - Uses [NetworkX](https://networkx.org/) for graph operations - Visualization powered by [Matplotlib](https://matplotlib.org/) --- **Note**: This project requires an OpenAI API key to function. Make sure to keep your API key secure and never commit it to version control. # src/components/home/home.jsx import React, { useState } from "react"; import "./Home.css"; import { FaGithub } from "react-icons/fa"; import { FaLinkedin } from "react-icons/fa6"; import Footer from "../footer/Footer"; import Projects from "../projects/projects"; export default function Home() { const [projects] = useState(Projects); return ( <> <div className="Home" id="home"> <div className="overlay"> <div className="hero-section"> <div className="left"> <h2> Hello, I'm <br />{" "} <span className="name"> {" "} Swati <span>P</span> </span> </h2> <p>I'm a React.JS developer.</p> <div className="icons"> <a href="https://www.linkedin.com/in/swati-p-41606b24a/"> <FaLinkedin /> </a> <a href="https://github.com/swatipund"> <FaGithub /> </a> </div> </div> <div className="right"> <img src="../main.jpg" alt="Swati Photo" /> </div> </div> </div> </div> <div id="about" className="about-section"> <h2>About me</h2> <div className="about-content"> <div className="profile-image"> <img src="../profile.jpg" alt="Profile" /> </div> <div className="content"> <div className="left-content"> <h3> I'm a React.js Developer with Good knowledge of Front-end techniques. </h3> <p> I am a passionate Frontend Developer with over 1 years of experience in building web applications using React.js, JavaScript, HTML, CSS, and modern frontend frameworks. I excel at creating responsive, user-friendly interfaces and am always eager to learn new technologies and improve my skills. </p> <p> My expertise includes developing dynamic and interactive web applications, implementing responsive designs, and ensuring cross-browser compatibility. I am proficient in state management with Redux, component-based architecture, and integrating APIs for seamless user experiences. </p> </div> <div className="right-content"> <h3>Personal Info</h3> <div className="info"> <div className="info-item"> <span className="label">Birthdate:</span> <span className="value">March 31, 2000</span> </div> <div className="info-item"> <span className="label">Email:</span> <span className="value">swatipund31@gmail.com</span> </div> <div className="info-item"> <span className="label">Phone:</span> <span className="value">+91 9503999488</span> </div> <div className="info-item"> <span className="label">Address:</span> <span className="value">Amravati, Maharashtra</span> </div> </div> <button className="download-resume"> <a href="https://drive.google.com/file/d/1TwC1K2rTZwZ6_6S_nFw5rDFVabxYvfup/view?usp=sharing" target="_blank" rel="noopener noreferrer" > Download Resume </a> </button> </div> </div> </div> </div> <div id="skills" className="skills-section"> <h2>My Skills</h2> <div className="skills-grid"> <div className="skill-card"> <img src="../html.png" alt="HTML" /> <h3>HTML5</h3> <p>Semantic markup and modern HTML5 features</p> </div> <div className="skill-card"> <img src="../css.png" alt="CSS" /> <h3>CSS3</h3> <p>Responsive design and modern CSS techniques</p> </div> <div className="skill-card"> <img src="../js.png" alt="JavaScript" /> <h3>JavaScript</h3> <p>ES6+ features and modern JavaScript development</p> </div> <div className="skill-card"> <img src="../react.png" alt="React" /> <h3>React.js</h3> <p>Component-based architecture and hooks</p> </div> <div className="skill-card"> <img src="../bootstrap.png" alt="Bootstrap" /> <h3>Bootstrap</h3> <p>Responsive framework for rapid development</p> </div> <div className="skill-card"> <img src="../github.png" alt="Git" /> <h3>Git & GitHub</h3> <p>Version control and collaborative development</p> </div> </div> </div> <div id="projects" className="projects-section"> <h2>My Projects</h2> <div className="projects-grid"> {projects.map((project, index) => ( <div key={index} className="project-card"> <div className="project-image"> <img src={project.image} alt={project.title} /> <div className="project-overlay"> <div className="project-links"> <a href={project.github} target="_blank" rel="noopener noreferrer" > <FaGithub /> </a> <a href={project.demo} target="_blank" rel="noopener noreferrer" > Demo </a> </div> </div> </div> <div className="project-content"> <h3>{project.title}</h3> <p>{project.description}</p> <div className="project-tech"> {project.technologies.map((tech, i) => ( <span key={i} className="tech-tag"> {tech} </span> ))} </div> </div> </div> ))} </div> </div> <Footer /> </> ); } End File# swatipund/My-Portfolio # src/components/projects/projects.js const Projects = [ { title: "Food Shop", description: "A React-based food ordering application with add to cart functionality", image: "../food-shop.png", technologies: ["React", "CSS", "JavaScript"], github: "https://github.com/swatipund/Food-Shop-App", demo: "https://food-shop-app-pied.vercel.app/" }, { title: "E-Commerce Store", description: "Complete e-commerce solution with product listing and shopping cart", image: "../ecommerce.png", technologies: ["React", "Redux", "CSS"], github: "https://github.com/swatipund/E-Commerce", demo: "https://e-commerce-gold-beta.vercel.app/" }, { title: "YouTube Clone", description: "YouTube-like video streaming platform with search and video player", image: "../youtube.png", technologies: ["React", "YouTube API", "CSS"], github: "https://github.com/swatipund/YouTube-Clone", demo: "https://you-tube-clone-rho-sepia.vercel.app/" }, { title: "QR Code Generator", description: "Generate QR codes for any text or URL instantly", image: "../qr-generator.png", technologies: ["React", "QR.js", "CSS"], github: "https://github.com/swatipund/QR-Code-Generator", demo: "https://qr-code-generator-teal-ten.vercel.app/" }, { title: "Task Manager", description: "Simple and efficient task management application", image: "../todo.png", technologies: ["React", "LocalStorage", "CSS"], github: "https://github.com/swatipund/To-Do-List", demo: "https://to-do-list-eosin-seven-57.vercel.app/" }, { title: "Weather App", description: "Real-time weather information with location-based forecasts", image: "../weather.png", technologies: ["React", "Weather API", "CSS"], github: "https://github.com/swatipund/Weather-App", demo: "https://weather-app-teal-eta-12.vercel.app/" } ]; export default Projects; End File# swatipund/My-Portfolio import React from 'react'; import './Footer.css'; import { FaGithub, FaLinkedin, FaEnvelope, FaPhone } from 'react-icons/fa'; export default function Footer() { return ( <footer id="contact" className="footer"> <div className="footer-content"> <div className="footer-section"> <h3>Let's Connect</h3> <p>I'm always interested in new opportunities and collaborations.</p> </div> <div className="footer-section"> <h4>Contact Info</h4> <div className="contact-info"> <div className="contact-item"> <FaEnvelope /> <span>swatipund31@gmail.com</span> </div> <div className="contact-item"> <FaPhone /> <span>+91 9503999488</span> </div> </div> </div> <div className="footer-section"> <h4>Follow Me</h4> <div className="social-links"> <a href="https://github.com/swatipund" target="_blank" rel="noopener noreferrer"> <FaGithub /> </a> <a href="https://www.linkedin.com/in/swati-p-41606b24a/" target="_blank" rel="noopener noreferrer"> <FaLinkedin /> </a> </div> </div> </div> <div className="footer-bottom"> <p>&copy; 2024 Swati P. All rights reserved.</p> </div> </footer> ); } End File# swatipund/My-Portfolio # src/components/navbar/Navbar.jsx import React, { useState } from 'react'; import './Navbar.css'; export default function Navbar() { const [isMenuOpen, setIsMenuOpen] = useState(false); const toggleMenu = () => { setIsMenuOpen(!isMenuOpen); }; const closeMenu = () => { setIsMenuOpen(false); }; return ( <nav className="navbar"> <div className="nav-container"> <div className="nav-logo"> <span>Swati P</span> </div> <div className={`nav-menu ${isMenuOpen ? 'active' : ''}`}> <a href="#home" className="nav-link" onClick={closeMenu}>Home</a> <a href="#about" className="nav-link" onClick={closeMenu}>About</a> <a href="#skills" className="nav-link" onClick={closeMenu}>Skills</a> <a href="#projects" className="nav-link" onClick={closeMenu}>Projects</a> <a href="#contact" className="nav-link" onClick={closeMenu}>Contact</a> </div> <div className={`nav-toggle ${isMenuOpen ? 'active' : ''}`} onClick={toggleMenu}> <span className="bar"></span> <span className="bar"></span> <span className="bar"></span> </div> </div> </nav> ); } # zk-steve/iden3-circom-btc-bench # circuits/sha256_2/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/sha256/sha256.circom"; component main = Sha256(1024); End File# zk-steve/iden3-circom-btc-bench # circuits/poseidon_14/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/poseidon.circom"; component main = Poseidon(14); End File# circuits/mimc_1/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/mimc.circom"; component main = MiMC7(1); End Filepragma circom 2.0.0; include "../../node_modules/circomlib/circuits/poseidon.circom"; component main = Poseidon(12); End File# circuits/sha256_1/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/sha256/sha256.circom"; component main = Sha256(512); End File# README.md # iden3-circom-btc-bench This repository contains benchmark comparisons for the iden3 circom library. It includes various circuits with different parameter sizes and complexity levels, designed to test performance on Bitcoin Virtual Machine (BVM) instances. ## Repository Structure The benchmarks are organized by circuit type: ### Merkle Tree Proofs - `merkletreeproof_X/` - Merkle tree proof verification circuits - X represents the tree depth (10, 16, 20, 24, 28, 32) ### MiMC Hash Function - `mimc_X/` - MiMC7 hash function circuits - X represents the number of inputs (1, 2, 4, 8, 16, 32) ### Poseidon Hash Function - `poseidon_X/` - Poseidon hash function circuits - X represents the number of inputs (2, 4, 6, 8, 10, 12, 14, 16) ### SHA-256 Hash Function - `sha256_X/` - SHA-256 hash function circuits - 1: 512-bit input - 2: 1024-bit input ## Benchmark Results ### Circuit Constraints The number of constraints for each circuit type: | Circuit | Constraints | |---------|------------| | mimc_1 | 31,355 | | mimc_2 | 62,705 | | mimc_4 | 125,405 | | mimc_8 | 250,805 | | mimc_16 | 501,605 | | mimc_32 | 1,003,205 | | poseidon_2 | 32 | | poseidon_4 | 63 | | poseidon_6 | 94 | | poseidon_8 | 125 | | poseidon_10 | 156 | | poseidon_12 | 187 | | poseidon_14 | 218 | | poseidon_16 | 249 | | merkletreeproof_10 | 315 | | merkletreeproof_16 | 495 | | merkletreeproof_20 | 615 | | merkletreeproof_24 | 735 | | merkletreeproof_28 | 855 | | merkletreeproof_32 | 975 | | sha256_1 | 27,906 | | sha256_2 | 54,658 | ## Performance Comparison ### Bitcoin Virtual Machine (BVM) Instance Types Tests were conducted on different BVM instance configurations: **BVM-S1 (1 Core, 2GB RAM)** - Baseline performance metrics - Cost-effective for smaller circuits **BVM-S2 (2 Cores, 4GB RAM)** - Improved performance for medium circuits - Better parallelization capabilities **BVM-S3 (4 Cores, 8GB RAM)** - Optimal for large constraint circuits - Best performance for complex computations ### Key Findings 1. **Poseidon circuits** are extremely efficient with minimal constraints 2. **MiMC circuits** show linear constraint growth with input size 3. **SHA-256 circuits** have high constraint counts but consistent performance 4. **Merkle tree proofs** scale efficiently with tree depth 5. **Higher-tier BVM instances** provide significant performance improvements for constraint-heavy circuits ## Usage Each circuit directory contains: - `circuit.circom` - The circuit implementation - Build and test scripts for performance evaluation To run benchmarks: ```bash cd circuits/[circuit_name] # Follow specific circuit instructions ``` ## Dependencies - Node.js and npm - Circom compiler - SnarkJS for proof generation - Appropriate BVM instance access This benchmark suite provides comprehensive performance data for choosing the right circuit complexity and BVM instance configuration for zero-knowledge proof applications. End File# circuits/mimc_16/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/mimc.circom"; component main = MiMC7(16); End File# zk-steve/iden3-circom-btc-bench pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/poseidon.circom"; component main = Poseidon(6); End File# zk-steve/iden3-circom-btc-bench # circuits/merkletreeproof_32/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/smt/smtverifier.circom"; component main = SMTVerifier(32); End File# zk-steve/iden3-circom-btc-bench pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/poseidon.circom"; component main = Poseidon(16); End File# zk-steve/iden3-circom-btc-bench # circuits/mimc_8/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/mimc.circom"; component main = MiMC7(8); End Filepragma circom 2.0.0; include "../../node_modules/circomlib/circuits/smt/smtverifier.circom"; component main = SMTVerifier(20); End File# circuits/poseidon_2/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/poseidon.circom"; component main = Poseidon(2); End File# zk-steve/iden3-circom-btc-bench pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/smt/smtverifier.circom"; component main = SMTVerifier(10); End File# circuits/mimc_32/circuit.circom pragma circom 2.0.0; include "../../node_modules/circomlib/circuits/mimc.circom"; component main = MiMC7(32); # DJFree123/Project from django.shortcuts import render, redirect from django.urls import reverse from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from .forms import RegistrationForm from django.contrib.auth import logout def index(request): """Index page""" return render(request, 'book_reviews/index.html') def register(request): """Register a new user.""" if request.method != 'POST': # Display blank registration form. form = RegistrationForm() else: # Process completed form. form = RegistrationForm(data=request.POST) if form.is_valid(): new_user = form.save() # Log the user in and then redirect to home page. username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') new_user = authenticate(request, username=username, password=password) if new_user is not None: login(request, new_user) return redirect('book_reviews:index') # Redirect to the index page # Display a blank or invalid form. context = {'form': form} return render(request, 'registration/register.html', context) def custom_logout(request): logout(request) return redirect('book_reviews:index')End File# DJFree123/Project # book_reviews/models.py from django.db import models from django.contrib.auth.models import User class Book(models.Model): """A book about a particular topic.""" title = models.CharField(max_length=200) author = models.CharField(max_length=200, default='Unknown Author') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.title class Review(models.Model): """A review of a book.""" book = models.ForeignKey(Book, on_delete=models.CASCADE) text = models.TextField() rating = models.IntegerField(choices=[(i, str(i)) for i in range(1, 6)]) # 1 to 5 rating date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Reviews' def __str__(self): """Return a string representation of the model.""" return f"{self.text[:50]}..." End File# DJFree123/Project from django import forms from .models import Book, Review from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class BookForm(forms.ModelForm): class Meta: model = Book fields = ['title', 'author'] labels = {'title': 'Book Title', 'author': 'Author'} class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ['text', 'rating'] labels = {'text': 'Review', 'rating': 'Rating'} widgets = { 'text': forms.Textarea(attrs={'cols': 80, 'rows': 10}), 'rating': forms.Select(choices=[(i, f'{i} Star{"s" if i != 1 else ""}') for i in range(1, 6)]) } class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return userEnd File# book_reviews/urls.py """Defines URL patterns for book_reviews""" from django.urls import path from . import views app_name = 'book_reviews' urlpatterns = [ # Home page path('', views.index, name='index'), # Page that shows all books. path('books/', views.books, name='books'), # Detail page for a single book. path('books/<int:book_id>/', views.book, name='book'), # Page for adding a new book. path('new_book/', views.new_book, name='new_book'), # Page for adding a new review. path('new_review/<int:book_id>/', views.new_review, name='new_review'), # Page for editing a review. path('edit_review/<int:review_id>/', views.edit_review, name='edit_review'), # Registration page path('register/', views.register, name='register'), # Custom logout path('custom_logout/', views.custom_logout, name='custom_logout'), ] End File# DJFree123/Project # book_reviews/views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import Http404 from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from .models import Book, Review from .forms import BookForm, ReviewForm, RegistrationForm from django.db.models import Avg def index(request): """The home page for Book Reviews.""" return render(request, 'book_reviews/index.html') @login_required def books(request): """Show all books.""" books = Book.objects.all().annotate( avg_rating=Avg('review__rating') ).order_by('date_added') context = {'books': books} return render(request, 'book_reviews/books.html', context) @login_required def book(request, book_id): """Show a single book and all its reviews.""" book = get_object_or_404(Book, id=book_id) reviews = book.review_set.order_by('-date_added') # Calculate average rating avg_rating = reviews.aggregate(Avg('rating'))['rating__avg'] if avg_rating: avg_rating = round(avg_rating, 1) context = {'book': book, 'reviews': reviews, 'avg_rating': avg_rating} return render(request, 'book_reviews/book.html', context) @login_required def new_book(request): """Add a new book.""" if request.method != 'POST': # No data submitted; create a blank form. form = BookForm() else: # POST data submitted; process data. form = BookForm(data=request.POST) if form.is_valid(): form.save() return redirect('book_reviews:books') # Display a blank or invalid form. context = {'form': form} return render(request, 'book_reviews/new_book.html', context) @login_required def new_review(request, book_id): """Add a new review for a particular book.""" book = get_object_or_404(Book, id=book_id) if request.method != 'POST': # No data submitted; create a blank form. form = ReviewForm() else: # POST data submitted; process data. form = ReviewForm(data=request.POST) if form.is_valid(): new_review = form.save(commit=False) new_review.book = book new_review.owner = request.user new_review.save() return redirect('book_reviews:book', book_id=book_id) # Display a blank or invalid form. context = {'book': book, 'form': form} return render(request, 'book_reviews/new_review.html', context) @login_required def edit_review(request, review_id): """Edit an existing review.""" review = get_object_or_404(Review, id=review_id) book = review.book # Check if the review belongs to the current user if review.owner != request.user: raise Http404 if request.method != 'POST': # Initial request; pre-fill form with the current review. form = ReviewForm(instance=review) else: # POST data submitted; process data. form = ReviewForm(instance=review, data=request.POST) if form.is_valid(): form.save() return redirect('book_reviews:book', book_id=book.id) context = {'review': review, 'book': book, 'form': form} return render(request, 'book_reviews/edit_review.html', context) def register(request): """Register a new user.""" if request.method != 'POST': # Display blank registration form. form = RegistrationForm() else: # Process completed form. form = RegistrationForm(data=request.POST) if form.is_valid(): new_user = form.save() # Log the user in and then redirect to home page. username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') new_user = authenticate(request, username=username, password=password) if new_user is not None: login(request, new_user) return redirect('book_reviews:index') # Redirect to the index page # Display a blank or invalid form. context = {'form': form} return render(request, 'registration/register.html', context) def custom_logout(request): logout(request) return redirect('book_reviews:index') End File"""Defines URL patterns for users""" from django.urls import path, include from . import views app_name = 'users' urlpatterns = [ # Include default auth urls. path('', include('django.contrib.auth.urls')), # Registration page. path('register/', views.register, name='register'), ] # Keshav-Vardhan-Gujjula/SQL_Retail_Sales_Analysis CREATE DATABASE sql_project_p1; CREATE TABLE retail_sales( transactions_id INT PRIMARY KEY, sale_date DATE, sale_time TIME, customer_id INT, gender VARCHAR(15), age INT, category VARCHAR(15), quantity INT, price_per_unit FLOAT, cogs FLOAT, total_sale FLOAT ); SELECT * FROM retail_sales LIMIT 10 SELECT COUNT(*) FROM retail_sales -- DATA CLEANING SELECT * FROM retail_sales WHERE transactions_id IS NULL SELECT * FROM retail_sales WHERE sale_date IS NULL SELECT * FROM retail_sales WHERE sale_time IS NULL SELECT * FROM retail_sales WHERE transactions_id IS NULL OR sale_date IS NULL OR sale_time IS NULL OR gender IS NULL OR category IS NULL OR quantity IS NULL OR cogs IS NULL OR total_sale IS NULL; -- DELETE FROM retail_sales WHERE transactions_id IS NULL OR sale_date IS NULL OR sale_time IS NULL OR gender IS NULL OR category IS NULL OR quantity IS NULL OR cogs IS NULL OR total_sale IS NULL; -- Data Exploration -- How many sales we have? SELECT COUNT(*) as total_sale FROM retail_sales -- How many uniuque customers we have ? SELECT COUNT(DISTINCT customer_id) as total_sale FROM retail_sales SELECT DISTINCT category FROM retail_sales -- Data Analysis & Business Key Problems & Answers -- My Analysis & Findings -- Q.1 Write a SQL query to retrieve all columns for sales made on '2022-11-05 SELECT * FROM retail_sales WHERE sale_date = '2022-11-05' -- Q.2 Write a SQL query to retrieve all transactions where the category is 'Clothing' and the quantity sold is more than 10 in the month of Nov-2022 SELECT * FROM retail_sales WHERE category = 'Clothing' AND TO_CHAR(sale_date, 'YYYY-MM') = '2022-11' AND quantity >= 4 -- Q.3 Write a SQL query to calculate the total sales (total_sale) for each category. SELECT category, SUM(total_sale) as net_sale, COUNT(*) as total_orders FROM retail_sales GROUP BY 1 -- Q.4 Write a SQL query to find the average age of customers who purchased items from the 'Beauty' category. SELECT ROUND(AVG(age), 2) as avg_age FROM retail_sales WHERE category = 'Beauty' -- Q.5 Write a SQL query to find all transactions where the total_sale is greater than 1000. SELECT * FROM retail_sales WHERE total_sale > 1000 -- Q.6 Write a SQL query to find the total number of transactions (transaction_id) made by each gender in each category. SELECT category, gender, COUNT(*) as total_trans FROM retail_sales GROUP BY category, gender ORDER BY 1 -- Q.7 Write a SQL query to calculate the average sale for each month. Find out best selling month in each year SELECT year, month, avg_sale FROM ( SELECT EXTRACT(YEAR FROM sale_date) as year, EXTRACT(MONTH FROM sale_date) as month, AVG(total_sale) as avg_sale, RANK() OVER(PARTITION BY EXTRACT(YEAR FROM sale_date) ORDER BY AVG(total_sale) DESC) as rank FROM retail_sales GROUP BY 1, 2 ) as t1 WHERE rank = 1 -- Q.8 Write a SQL query to find the top 5 customers based on the highest total sales SELECT customer_id, SUM(total_sale) as total_sales FROM retail_sales GROUP BY 1 ORDER BY 2 DESC LIMIT 5 -- Q.9 Write a SQL query to find the number of unique customers who purchased items from each category. SELECT category, COUNT(DISTINCT customer_id) as cnt_unique_cs FROM retail_sales GROUP BY category -- Q.10 Write a SQL query to create each shift and number of orders (Example Morning <=12, Afternoon Between 12 & 17, Evening >17) WITH hourly_sale AS ( SELECT *, CASE WHEN EXTRACT(HOUR FROM sale_time) < 12 THEN 'Morning' WHEN EXTRACT(HOUR FROM sale_time) BETWEEN 12 AND 17 THEN 'Afternoon' ELSE 'Evening' END as shift FROM retail_sales ) SELECT shift, COUNT(*) as total_orders FROM hourly_sale GROUP BY shift -- End of project -- Q.11 Which product category generates the most revenue? SELECT category, SUM(total_sale) AS total_revenue FROM retail_sales GROUP BY category ORDER BY total_revenue DESC LIMIT 1; -- Q.12 What is the top-selling product category for each gender? WITH gender_category_sales AS ( SELECT gender, category, SUM(total_sale) AS total_revenue FROM retail_sales GROUP BY gender, category ), ranked_categories AS ( SELECT *, RANK() OVER (PARTITION BY gender ORDER BY total_revenue DESC) AS rank FROM gender_category_sales ) SELECT gender, category, total_revenue FROM ranked_categories WHERE rank = 1; -- Q.13 What is the seasonal trend in sales? -- Assuming seasons: Spring (Mar-May), Summer (Jun-Aug), Fall (Sep-Nov), Winter (Dec-Feb) WITH seasonal_sales AS ( SELECT CASE WHEN EXTRACT(MONTH FROM sale_date) IN (3, 4, 5) THEN 'Spring' WHEN EXTRACT(MONTH FROM sale_date) IN (6, 7, 8) THEN 'Summer' WHEN EXTRACT(MONTH FROM sale_date) IN (9, 10, 11) THEN 'Fall' ELSE 'Winter' END AS season, total_sale FROM retail_sales ) SELECT season, SUM(total_sale) AS total_sales, AVG(total_sale) AS avg_sales, COUNT(*) AS total_transactions FROM seasonal_sales GROUP BY season ORDER BY total_sales DESC; -- Q.14 Which age group spends the most? WITH age_groups AS ( SELECT CASE WHEN age < 25 THEN '18-24' WHEN age BETWEEN 25 AND 34 THEN '25-34' WHEN age BETWEEN 35 AND 44 THEN '35-44' WHEN age BETWEEN 45 AND 54 THEN '45-54' ELSE '55+' END AS age_group, total_sale FROM retail_sales ) SELECT age_group, SUM(total_sale) AS total_spending, AVG(total_sale) AS avg_spending, COUNT(*) AS total_transactions FROM age_groups GROUP BY age_group ORDER BY total_spending DESC; -- Q.15 What is the average transaction value by category and gender? SELECT category, gender, AVG(total_sale) AS avg_transaction_value, COUNT(*) AS transaction_count FROM retail_sales GROUP BY category, gender ORDER BY category, avg_transaction_value DESC; -- Q.16 Which customers have the highest purchase frequency? SELECT customer_id, COUNT(*) AS purchase_frequency, SUM(total_sale) AS total_spent, AVG(total_sale) AS avg_per_transaction FROM retail_sales GROUP BY customer_id ORDER BY purchase_frequency DESC LIMIT 10; -- Q.17 What is the profit margin analysis by category? (Using total_sale - cogs) SELECT category, SUM(total_sale) AS total_revenue, SUM(cogs) AS total_cost, SUM(total_sale - cogs) AS total_profit, ROUND((SUM(total_sale - cogs) / SUM(total_sale)) * 100, 2) AS profit_margin_percent FROM retail_sales GROUP BY category ORDER BY profit_margin_percent DESC; -- Q.18 How do sales vary by time of day? WITH hourly_sales AS ( SELECT EXTRACT(HOUR FROM sale_time) AS hour, total_sale FROM retail_sales ) SELECT hour, SUM(total_sale) AS total_sales, AVG(total_sale) AS avg_sales, COUNT(*) AS total_transactions FROM hourly_sales GROUP BY hour ORDER BY hour; -- Q.19 What is the customer retention rate? (Customers who made purchases in multiple months) WITH customer_months AS ( SELECT customer_id, TO_CHAR(sale_date, 'YYYY-MM') AS month, COUNT(*) AS transactions FROM retail_sales GROUP BY customer_id, TO_CHAR(sale_date, 'YYYY-MM') ), customer_activity AS ( SELECT customer_id, COUNT(DISTINCT month) AS active_months FROM customer_months GROUP BY customer_id ) SELECT CASE WHEN active_months = 1 THEN 'One-time customers' WHEN active_months BETWEEN 2 AND 3 THEN 'Regular customers' ELSE 'Loyal customers' END AS customer_type, COUNT(*) AS customer_count, ROUND((COUNT(*) * 100.0 / SUM(COUNT(*)) OVER ()), 2) AS percentage FROM customer_activity GROUP BY CASE WHEN active_months = 1 THEN 'One-time customers' WHEN active_months BETWEEN 2 AND 3 THEN 'Regular customers' ELSE 'Loyal customers' END ORDER BY customer_count DESC; -- Q.20 What is the price sensitivity analysis? (Relationship between price_per_unit and quantity) WITH price_ranges AS ( SELECT CASE WHEN price_per_unit < 50 THEN 'Low (< $50)' WHEN price_per_unit BETWEEN 50 AND 100 THEN 'Medium ($50-$100)' WHEN price_per_unit BETWEEN 100 AND 200 THEN 'High ($100-$200)' ELSE 'Premium (> $200)' END AS price_range, quantity, total_sale FROM retail_sales ) SELECT price_range, AVG(quantity) AS avg_quantity_sold, SUM(total_sale) AS total_revenue, COUNT(*) AS transaction_count FROM price_ranges GROUP BY price_range ORDER BY CASE price_range WHEN 'Low (< $50)' THEN 1 WHEN 'Medium ($50-$100)' THEN 2 WHEN 'High ($100-$200)' THEN 3 ELSE 4 END; -- End of extended analysis import { StatusBar } from 'expo-status-bar'; import { StyleSheet, Text, View } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import HomeScreen from './src/screens/HomeScreen'; import SignInScreen from './src/screens/SignInScreen'; import CadastroScreen from './src/screens/CadastroScreen'; const Stack = createStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator initialRouteName='Home'> <Stack.Screen name="Home" component={HomeScreen}/> <Stack.Screen name="SignIn" component={SignInScreen}/> <Stack.Screen name="Cadastro" component={CadastroScreen}/> </Stack.Navigator> </NavigationContainer> ); } End Fileimport React from "react" import { View, Text, TextInput, TouchableOpacity, StyleSheet, SafeAreaView } from 'react-native' const SignInScreen = ({ navigation }) => { return ( <SafeAreaView style={styles.container}> <View style={styles.box}> <Text style={styles.title}>Log In</Text> <TextInput style={styles.input} placeholder="E-mail" keyboardType="email-address" /> <TextInput style={styles.input} placeholder="Senha" secureTextEntry={true} /> <TouchableOpacity style={styles.button}> <Text style={styles.buttonText}> Entrar </Text> </TouchableOpacity> <TouchableOpacity onPress={() => navigation.navigate('Cadastro')}> <Text style={styles.link}>Não tem uma conta? Cadastre-se aqui</Text> </TouchableOpacity> </View> </SafeAreaView> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#120a8f', }, box: { width: '80%', backgroundColor: '#fff', borderRadius: 8, padding: 20, shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, textAlign: 'center', color: '#333', }, input: { backgroundColor: '#f5f5f5', borderRadius: 8, padding: 15, marginBottom: 15, fontSize: 16, borderWidth: 1, borderColor: '#ddd', }, button: { backgroundColor: '#120a8f', borderRadius: 8, padding: 15, alignItems: 'center', marginBottom: 15, }, buttonText: { color: '#fff', fontSize: 16, fontWeight: 'bold', }, link: { textAlign: 'center', color: '#120a8f', fontSize: 14, textDecorationLine: 'underline', }, }); export default SignInScreen End Fileimport React from 'react' import { View, Text, StyleSheet, TouchableOpacity, SafeAreaView } from 'react-native'; const HomeScreen = ({navigation}) => { return ( <SafeAreaView style={styles.container}> <View style={styles.content}> <Text style={styles.title}>Bem vindo(a)!</Text> <Text style={styles.subtitle}>Faça o login para acessar a aplicação</Text> <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('SignIn')} > <Text style={styles.buttonText}>Fazer Login</Text> </TouchableOpacity> </View> </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#120a8f', }, content: { flex: 1, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 30, }, title: { fontSize: 28, fontWeight: 'bold', color: '#fff', marginBottom: 20, textAlign: 'center', }, subtitle: { fontSize: 16, color: '#e0e0e0', marginBottom: 40, textAlign: 'center', lineHeight: 22, }, button: { backgroundColor: '#fff', paddingVertical: 15, paddingHorizontal: 40, borderRadius: 25, shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, buttonText: { color: '#120a8f', fontSize: 18, fontWeight: 'bold', }, }); export default HomeScreen; End Fileimport React from "react" import { View, Text, TextInput, TouchableOpacity, StyleSheet, SafeAreaView } from 'react-native' const CadastroScreen = ({ navigation }) => { return ( <SafeAreaView style={styles.container}> <View style={styles.box}> <Text style={styles.title}>Cadastre-se</Text> <TextInput style={styles.input} placeholder="Nome completo" /> <TextInput style={styles.input} placeholder="E-mail" keyboardType="email-address" /> <TextInput style={styles.input} placeholder="Senha" secureTextEntry={true} /> <TextInput style={styles.input} placeholder="Confirmar senha" secureTextEntry={true} /> <TouchableOpacity style={styles.button}> <Text style={styles.buttonText}> Cadastrar </Text> </TouchableOpacity> <TouchableOpacity onPress={() => navigation.navigate('SignIn')}> <Text style={styles.link}>Já tem uma conta? Faça login aqui</Text> </TouchableOpacity> </View> </SafeAreaView> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#120a8f', }, box: { width: '80%', backgroundColor: '#fff', borderRadius: 8, padding: 20, shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, textAlign: 'center', color: '#333', }, input: { backgroundColor: '#f5f5f5', borderRadius: 8, padding: 15, marginBottom: 15, fontSize: 16, borderWidth: 1, borderColor: '#ddd', }, button: { backgroundColor: '#120a8f', borderRadius: 8, padding: 15, alignItems: 'center', marginBottom: 15, }, buttonText: { color: '#fff', fontSize: 16, fontWeight: 'bold', }, link: { textAlign: 'center', color: '#120a8f', fontSize: 14, textDecorationLine: 'underline', }, }); export default CadastroScreen # NielsOuvrard/workshop_C # part3/ex02/my_sokoban.h /* ** EPITECH PROJECT, 2023 ** my_sokoban.h ** File description: ** my_sokoban.h */ #ifndef __MY_SOKOBAN_H__ #define __MY_SOKOBAN_H__ void my_putchar(char c); int my_putstr(char const *str); void my_put_nbr(int nb); char *my_strdup(char const *src); int my_strlen(char const *str); int my_getnbr(char const *str); #endif End File# NielsOuvrard/workshop_C # part3/ex02/my_sokoban.c /* ** EPITECH PROJECT, 2023 ** my_sokoban.c ** File description: ** my_sokoban.c */ #include "my_sokoban.h" #include <ncurses.h> void draw_map(char **map) { for (int i = 0; map[i]; i++) { mvprintw(i, 0, map[i]); } refresh(); } int my_sokoban(char **map) { int ch; initscr(); keypad(stdscr, TRUE); noecho(); draw_map(map); while ((ch = getch()) != 'q') { draw_map(map); } endwin(); return 0; } End File# NielsOuvrard/workshop_C /* ** EPITECH PROJECT, 2023 ** my_sokoban.c ** File description: ** my_sokoban.c */ #include "my_sokoban.h" #include <ncurses.h> #include <unistd.h> #include <stdlib.h> void draw_map(char **map) { clear(); for (int i = 0; map[i]; i++) { mvprintw(i, 0, map[i]); } refresh(); } int move_is_valid(char **map, int y, int x) { if (map[y][x] == '#') return 0; return 1; } int move_player(char **map, int y, int x, int dy, int dx) { int ny = y + dy; int nx = x + dx; if (!move_is_valid(map, ny, nx)) return 0; if (map[ny][nx] == 'X') { int nny = ny + dy; int nnx = nx + dx; if (!move_is_valid(map, nny, nnx) || map[nny][nnx] == 'X') return 0; map[nny][nnx] = 'X'; } map[y][x] = ' '; map[ny][nx] = 'P'; return 1; } void get_player_pos(char **map, int *y, int *x) { for (int i = 0; map[i]; i++) { for (int j = 0; map[i][j]; j++) { if (map[i][j] == 'P') { *y = i; *x = j; return; } } } } int my_sokoban(char **map) { int ch, y, x; initscr(); keypad(stdscr, TRUE); noecho(); draw_map(map); while ((ch = getch()) != 'q') { get_player_pos(map, &y, &x); if (ch == KEY_UP) move_player(map, y, x, -1, 0); if (ch == KEY_DOWN) move_player(map, y, x, 1, 0); if (ch == KEY_LEFT) move_player(map, y, x, 0, -1); if (ch == KEY_RIGHT) move_player(map, y, x, 0, 1); draw_map(map); } endwin(); return 0; } End File# NielsOuvrard/workshop_C /* ** EPITECH PROJECT, 2023 ** my_sokoban.c ** File description: ** my_sokoban.c */ #include "my_sokoban.h" #include <ncurses.h> #include <unistd.h> #include <stdlib.h> void draw_map(char **map, char **original_map) { clear(); for (int i = 0; map[i]; i++) { for (int j = 0; map[i][j]; j++) { if (map[i][j] == ' ' && original_map[i][j] == 'O') mvaddch(i, j, 'O'); else if (map[i][j] == 'X' && original_map[i][j] == 'O') mvaddch(i, j, 'X' | A_BLINK); else mvaddch(i, j, map[i][j]); } } refresh(); } int move_is_valid(char **map, int y, int x) { if (map[y][x] == '#') return 0; return 1; } int move_player(char **map, int y, int x, int dy, int dx) { int ny = y + dy; int nx = x + dx; if (!move_is_valid(map, ny, nx)) return 0; if (map[ny][nx] == 'X') { int nny = ny + dy; int nnx = nx + dx; if (!move_is_valid(map, nny, nnx) || map[nny][nnx] == 'X') return 0; map[nny][nnx] = 'X'; } map[y][x] = ' '; map[ny][nx] = 'P'; return 1; } void get_player_pos(char **map, int *y, int *x) { for (int i = 0; map[i]; i++) { for (int j = 0; map[i][j]; j++) { if (map[i][j] == 'P') { *y = i; *x = j; return; } } } } char **copy_map(char **map) { int nb_lines = 0; char **copy; while (map[nb_lines]) nb_lines++; copy = malloc(sizeof(char *) * (nb_lines + 1)); for (int i = 0; i < nb_lines; i++) copy[i] = my_strdup(map[i]); copy[nb_lines] = NULL; return copy; } int is_win(char **map, char **original_map) { for (int i = 0; map[i]; i++) { for (int j = 0; map[i][j]; j++) { if (original_map[i][j] == 'O' && map[i][j] != 'X') return 0; } } return 1; } int my_sokoban(char **map) { int ch, y, x; char **original_map = copy_map(map); initscr(); keypad(stdscr, TRUE); noecho(); draw_map(map, original_map); while ((ch = getch()) != 'q') { get_player_pos(map, &y, &x); if (ch == KEY_UP) move_player(map, y, x, -1, 0); if (ch == KEY_DOWN) move_player(map, y, x, 1, 0); if (ch == KEY_LEFT) move_player(map, y, x, 0, -1); if (ch == KEY_RIGHT) move_player(map, y, x, 0, 1); draw_map(map,

Sprinkler

Sprinkler

Sprinkler

Sprinkler

Su Altı Kırıcı 2

Su Altı Kırıcı 2

Su Altı Kırıcı 3

Su Altı Kırıcı 3

Sualtı Kesicisi 1

Sualtı Kesicisi 1

Görsel Yok

Süt Azı Dişi Şişesi

Suya Dalış Fırlatıcı

Suya Dalış Fırlatıcı

Tahta Planka

Tahta Planka

Taş Duvar Laboratuvar Karakolu

Taş Duvar Laboratuvar Karakolu

Tırmık

Tırmık

Undershed Lab Kontrolü

Undershed Lab Kontrolü

Undershed Laboratuvar Malzeme Depolama Odası

Undershed Laboratuvar Malzeme Depolama Odası

Undershed Laboratuvar Yatakhanesi

Undershed Laboratuvar Yatakhanesi

Undershed Laboratuvarı Çıkışı

Undershed Laboratuvarı Çıkışı

Görsel Yok

Undershed Laboratuvarı Soğutma Odası

Undershed Laboratuvarı Soğutma Odası

Undershed Laboratuvarı Soğutma Odası

Görsel Yok

Uydu Çanağı

Vaha

Vaha

Yosunlu Mağara

Yosunlu Mağara

Zipline

Zipline

Zipline

Zipline

Zipline

Zipline

Görsel Yok

Zipline

Görsel Yok

Zipline

Görsel Yok

Zipline

Görsel Yok

Zipline

Zipline

Zipline

Wand logo