Snippets Collections
class Solution
{
	public:
	//Function to find sum of weights of edges of the Minimum Spanning Tree.
    int spanningTree(int V, vector<vector<int>> adj[])
    {
        // code here
        vector<int> vis(V,0);
        vector<tuple<int,int,int>> mst;
        //wt,node,parent
        priority_queue<vector<int>,vector<vector<int>>, greater<vector<int>>> pq;
        
        pq.push({0,0,-1});
        int sum =0;
        
        while(!pq.empty()){
            auto it = pq.top();
            pq.pop();
            int node = it[1];
            int wt = it[0];
            int par = it[2];
            
            if(vis[node]==1) continue;
            vis[node]=1;
            sum+=wt;
            if(par!=-1){
                mst.push_back(make_tuple(wt,par,node));
            }
            for(auto it: adj[node]){
                int ch = it[0];
                int ch_w = it[1];
                if(!vis[ch]){
                    pq.push({ch_w, ch,node});
                }
            }
        }
        for(auto it: mst){
            int weight, u, v;
            tie(weight, u, v) = it;
            cout<<weight<<":"<<u<<"->"<<v<<endl;
        }
        return sum;
    }
};
class Solution {
  public:
    /*  Function to implement Bellman Ford
    *   edges: vector of vectors which represents the graph
    *   S: source vertex to start traversing graph with
    *   V: number of vertices
    */
    vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S) {
        // Code here
        //iterate through edges ond keep on updating the distance array. Iterate through all the edges for 
        //V-1 times
        vector<int> dis(V,1e8);
        dis[S]=0;
        for(int i=0;i<V-1;i++){
            
            for(int j =0;j<edges.size();j++){
                int u = edges[j][0];
                int v = edges[j][1];
                int w = edges[j][2];
                if(dis[u] != 1e8 && dis[u]+w<dis[v]){
                    dis[v]=dis[u]+w;
                }
            }
        }
        for(int i=0;i<1;i++){
            
            for(int j =0;j<edges.size();j++){
                int u = edges[j][0];
                int v = edges[j][1];
                int w = edges[j][2];
                if(dis[u] != 1e8 && dis[u]+w<dis[v]){
                    return {-1};
                }
            }
        }
        
        return dis;
    }
};
# Two Years Ago
![[<% moment(tp.date.now("YYYY-MM-DD")).subtract(2, 'years').format("YYYY-MM-DD") %> ]]

# One Year Ago
![[<% moment(tp.date.now("YYYY-MM-DD")).subtract(1, 'years').format("YYYY-MM-DD") %>]]
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:first/Login/login2.dart';
import 'package:first/Login/component/api_service.dart';

String SendPhone = "";
String OTP1 = "";
String userStatus2 = "";

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final TextInputFormatter phoneNumberFormatter =
      FilteringTextInputFormatter.allow(
    RegExp(r'^\d{0,11}'),
  );

  final _formKey = GlobalKey<FormState>();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();

  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      var name = _nameController.text;
      var phone = _phoneController.text;

      var jsonResponse = await ApiService.login(name, phone);
      if (jsonResponse != null) {
        var userStatus = jsonResponse['USER STATUS'];
        var otp = jsonResponse['otp'];
        OTP1 = otp;
        userStatus2 = userStatus;
        SendPhone = phone;
        print("otp");
        print(otp);
        if (userStatus == '0' || userStatus == '1') {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => Login2()),
          );
        } else {
          print('Unknown user status: $userStatus');
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(35.0),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                const Text(
                  'لطفا جهت ورود به برنامه، شماره تلفن خود را وارد نمایید',
                  textAlign: TextAlign.right,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 20),
                const SizedBox(height: 20),
                Directionality(
                  textDirection: TextDirection.rtl,
                  child: TextFormField(
                    controller: _phoneController,
                    textAlign: TextAlign.end,
                    decoration: const InputDecoration(
                      labelText: 'شماره تلفن',
                      border: OutlineInputBorder(),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue, width: 2.0),
                      ),
                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly,
                      phoneNumberFormatter,
                    ],
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'لطفا شماره تلفن خود را وارد کنید';
                      } else if (!RegExp(r'^09\d{9}$').hasMatch(value)) {
                        return 'شماره تلفن باید با 09 شروع شود و 11 رقم باشد';
                      }
                      return null;
                    },
                  ),
                ),
                const SizedBox(height: 20),
                ElevatedButton(
                  onPressed: _submitForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    padding: const EdgeInsets.symmetric(vertical: 16.0),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    textStyle: const TextStyle(
                      fontSize: 18,
                      color: Colors.white,
                    ),
                  ),
                  child: const Text('ادامه'),
                ),
                const SizedBox(height: 20),
                const Text(
                  'با ورود و استفاده از برنامه، شما با شرایط و قوانین موافقت می‌نمایید.',
                  textAlign: TextAlign.end,
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Main Page'),
      ),
      body: const Center(
        child: Text('Welcome to Main Page'),
      ),
    );
  }
}
int f(int ind,int buy, vector<int>& nums ,vector<vector<int>>& dp )
{
    if(ind==(nums.size()))
    return 0;
    if(dp[ind][buy]!=-1)
    return dp[ind][buy];
    int profit;
    if(buy)
    profit = max((-nums[ind]+f(ind+1,0,nums,dp)),(f(ind+1,1,nums,dp)));
    else
    profit = max((nums[ind]+f(ind+2,1,nums,dp)),(f(ind+1,0,nums,dp)));
    return dp[ind][buy]=profit;
}
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
         vector<vector<int>> dp(n,vector<int>(2,-1));
         return f(0,1,prices,dp);
        
    }
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { FlexLayoutModule } from '@angular/flex-layout';
import {jwtDecode} from 'jwt-decode';
 
@Component({
  selector: 'app-login',
  standalone: true,
  imports: [
    MaterialModule,
    ReactiveFormsModule,
    RouterLink,
    CommonModule,
    HttpClientModule,
    FlexLayoutModule   
  ],
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
 
  loginFormGroup: FormGroup;
  isLoading: boolean = false;
 
  constructor(
    private router: Router,
    private userService: UserService,
    private fb: FormBuilder,
    private snackBar: MatSnackBar
  ) { 
    this.loginFormGroup = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required],
    });
  }
 
  ngOnInit() {}
 
  async LoginUser() {
    if (this.loginFormGroup.valid) {
      this.isLoading = true;
  
      this.userService.LoginUser(this.loginFormGroup.value).subscribe({
        next: (result: any) => {
          if (result && result.token) {
            localStorage.setItem('User', JSON.stringify(result));
  
            // Decode the JWT token to extract user information
            const decodedToken: any = jwtDecode(result.token);
            console.log('Decoded Token:', decodedToken);
 
            const userId = decodedToken.userId;
            const userTypeID = decodedToken.User_Type_ID;
            console.log('User Type ID:', userTypeID);
            console.log('User Type ID:', userTypeID);
            
            
            this.loginFormGroup.reset();
            
            // Navigate based on user type
            if (userTypeID === "1") {  // Ensure userTypeID is compared as string
              this.router.navigateByUrl(`/OwnerHome/${userId}`);
            } else if (userTypeID === "2") {
              this.router.navigateByUrl(`/EmployeeHome/${userId}`);
            } else if (userTypeID === "3") {
              this.router.navigateByUrl(`/Home/${userId}`);
            } else {
              this.snackBar.open('Error: Invalid user type: Please register as an authorized user', 'Close', { duration: 5000 });
            }
          } else {
            this.snackBar.open('Login failed', 'Close', { duration: 5000 });
          }
        },
        error: () => {
          this.isLoading = false;
          this.snackBar.open('Login failed', 'Close', { duration: 5000 });
        },
        complete: () => {
          this.isLoading = false;
        }
      });
    }
  }
}
// Latest working register
[HttpPost]
[DisableRequestSizeLimit]
[Route("Register")]
public async Task<IActionResult> Register([FromForm] UserViewModel uvm)
{
    try
    {
        var formCollection = await Request.ReadFormAsync();
        var photo = formCollection.Files.FirstOrDefault();
 
        var user = await _userManager.FindByEmailAsync(uvm.Email);
        int lastUserID = _appDbContext.Users
                         .OrderByDescending(u => u.User_ID)
                         .Select(u => u.User_ID)
                         .FirstOrDefault();
 
        // Validate Phone Number Pattern
        var phoneNumberPattern = @"^\d{10}$";
 
        bool isValidPhoneNumber = Regex.IsMatch(uvm.PhoneNumber, phoneNumberPattern);
 
        if (!isValidPhoneNumber) return BadRequest("Enter valid 10-digit phone number.");
 
        // Validate South African ID number
        if (!IsValidSouthAfricanIDNumber(uvm.Id_Number, uvm.Date_of_Birth))
        {
            return BadRequest("Enter a valid South African ID number.");
        }
 
        if (user == null)
        {
            if (photo != null && photo.Length > 0)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await photo.CopyToAsync(memoryStream);
                    var fileBytes = memoryStream.ToArray();
                    string base64Image = Convert.ToBase64String(fileBytes);
 
                    user = new User
                    {
                        User_ID = lastUserID + 1,
                        Name = uvm.Name,
                        Surname = uvm.Surname,
                        UserName = uvm.Email,
                        Email = uvm.Email,
                        PasswordHash = _userManager.PasswordHasher.HashPassword(null, uvm.Password),
                        User_Status_ID = uvm.User_Status_ID,
                        User_Type_ID = uvm.User_Type_ID,
                        PhoneNumber = uvm.PhoneNumber,
                        Date_of_Birth = uvm.Date_of_Birth,
                        ID_Number = uvm.Id_Number,
                        Physical_Address = uvm.Physical_Address,
                        Photo = base64Image // Store the base64 string of the photo
                    };
 
                    IdentityResult result = await _userManager.CreateAsync(user);
 
                    if (result.Succeeded)
                    {
                        // Assign role based on User_Type_ID
                        string roleName = GetRoleNameByUserType(uvm.User_Type_ID);
                        if (!string.IsNullOrEmpty(roleName))
                        {
                            var roleResult = await _userManager.AddToRoleAsync(user, roleName);
                            if (!roleResult.Succeeded)
                            {
                                return BadRequest(new { Status = "Error", Errors = roleResult.Errors });
                            }
                        }
 
 
                        return Ok(new { Status = "Success", Message = "User created successfully!" });
                    }
                    else
                    {
                        return StatusCode(StatusCodes.Status500InternalServerError, result.Errors.FirstOrDefault()?.Description);
                    }
                }
            }
            else
            {
                return BadRequest("Photo is required.");
            }
        }
        else
        {
            return Forbid("Account already exists.");
        }
    }
    catch (DbUpdateException dbEx)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, dbEx.InnerException?.Message ?? "An error occurred while processing your request.");
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
    }
}
 
// Method to validate South African ID number
private bool IsValidSouthAfricanIDNumber(string idNumber, DateTime dateOfBirth)
{
    // Check if the ID number is exactly 13 digits long
    if (idNumber.Length != 13 || !long.TryParse(idNumber, out _))
    {
        return false;
    }
 
    // Validate date of birth (first six digits)
    string dateOfBirthPart = idNumber.Substring(0, 6);
    if (!DateTime.TryParseExact(dateOfBirthPart, "yyMMdd", null, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
    {
        return false;
    }
 
    // Check if the last two digits of the ID number match the last two digits of the year of birth
    if (parsedDate.Year % 100 != dateOfBirth.Year % 100)
    {
        return false;
    }
 
    // If it passes the length, date of birth, and year checks, it is considered valid
    return true;
}
 
 
private string GetRoleNameByUserType(int userTypeId)
{
    return userTypeId switch
    {
        1 => "Administrator",
        2 => "Employee",
        3 => "Member",
        _ => string.Empty,
    };
}

  
//untested login
[HttpPost]
[Route("Login")]
public async Task<ActionResult> Login(LoginViewModel lv)
{
    var user = await _userManager.FindByNameAsync(lv.Email);
 
    if (user != null && await _userManager.CheckPasswordAsync(user, lv.Password))
    {
        try
        {
            var principal = await _claimsPrincipalFactory.CreateAsync(user);
            return await GenerateJWTToken(user);
        }
        catch (Exception)
        {
 
            return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
        }
    }
    else
    {
        return NotFound("Incorrect email or password, Please Try Again");
    }
}
 
[HttpGet]
private async Task<ActionResult> GenerateJWTToken(User user)
{
    var role = await _userManager.GetRolesAsync(user);
    IdentityOptions _identityOptions = new IdentityOptions();
    // Create JWT Token
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.Email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
        // Add user ID claim
        new Claim("userId", user.Id.ToString()),
 
        new Claim("User_Type_ID", user.User_Type_ID.ToString()),
 
    };
 
    if (role.Count() > 0)
    {
        claims.Add(new Claim(_identityOptions.ClaimsIdentity.RoleClaimType, role.FirstOrDefault()));
    }
 
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
 
    var token = new JwtSecurityToken(
       issuer:  _configuration["Tokens:Issuer"],
       audience: _configuration["Tokens:Audience"],
       claims: claims,
       signingCredentials: credentials,
       expires: DateTime.UtcNow.AddHours(3)
    );
 
    return Created("", new
    {
        token = new JwtSecurityTokenHandler().WriteToken(token),
        user = user.UserName,
 
        userTypeId = user.User_Type_ID,
        // Include user ID in the response
        userId = user.Id
    });
}

//latest working editUser before base64
[HttpPut]
[Route("editUser/{id}")]
public async Task<IActionResult> EditUser(int id, UpdateUserViewModel uv)
{
    try
    {

        var user = await _userManager.FindByIdAsync(id.ToString());

        if (user == null)
        {
            return NotFound("User not found.");
        }

        user.Name = uv.Name;
        user.Surname = uv.Surname;
        user.Email = uv.Email;
        user.Physical_Address = uv.Physical_Address;
        user.PhoneNumber = uv.PhoneNumber;
        user.Photo = uv.Photo;

        // Update the user
        var result = await _userManager.UpdateAsync(user);

        if (result.Succeeded)
        {
            return Ok("User updated successfully.");
        }
        else
        {
            return BadRequest(result.Errors);
        }
    }
    catch (Exception)
    {

        return BadRequest("An Error Occured, Please Try Again");
    }
}

//latest working getUserById before base64
[HttpGet]
[Route("getUserById/{id}")]
public async Task<IActionResult> GetUserById(int id)
{

    try
    {
        var user = await _userManager.FindByIdAsync(id.ToString());

        if (user == null)
        {
            return NotFound("User not found.");
        }

        // Map User entity to UserViewModel or return the User entity directly
        var userViewModel = new UserViewModel
        {

            Name = user.Name,
            Surname = user.Surname,
            Email = user.Email,
            Physical_Address = user.Physical_Address,
            PhoneNumber = user.PhoneNumber,
            //Photo = user.Photo,
            Date_of_Birth = user.Date_of_Birth,
            User_Status_ID = user.User_Status_ID,
            User_Type_ID = user.User_Type_ID,
            Id_Number = user.ID_Number
        };

        return Ok(userViewModel);
    }
    catch (Exception)
    {

        return BadRequest("Try again");
    }
}
import math 

print(math.log10(10))
print(math.log10(50))
print(math.log10(100))
print(math.log10(200))
print(math.log10(1000))
class Solution
{
	public:
	//Function to find sum of weights of edges of the Minimum Spanning Tree.
    int spanningTree(int V, vector<vector<int>> adj[])
    {
        // code here
        vector<int> vis(V,0);
        vector<tuple<int,int,int>> mst;
        //wt,node,parent
        priority_queue<vector<int>,vector<vector<int>>, greater<vector<int>>> pq;
        
        pq.push({0,0,-1});
        int sum =0;
        
        while(!pq.empty()){
            auto it = pq.top();
            pq.pop();
            int node = it[1];
            int wt = it[0];
            int par = it[2];
            
            if(vis[node]==1) continue;
            vis[node]=1;
            sum+=wt;
            if(par!=-1){
                mst.push_back(make_tuple(wt,par,node));
            }
            for(auto it: adj[node]){
                int ch = it[0];
                int ch_w = it[1];
                if(!vis[ch]){
                    pq.push({ch_w, ch,node});
                }
            }
        }
        for(auto it: mst){
            int weight, u, v;
            tie(weight, u, v) = it;
            cout<<weight<<":"<<u<<"->"<<v<<endl;
        }
        return sum;
    }
};
int f(int ind,int buy,int t, vector<int>& nums, vector<vector<vector<int>>>& dp)
{
    if(ind==(nums.size()) || t==0)
    return 0;
    if(dp[ind][buy][t]!=-1)
    return dp[ind][buy][t];
    int profit;
    if(buy && t)
    profit = max((-nums[ind]+f(ind+1,0,t,nums,dp)),(f(ind+1,1,t,nums,dp)));
    else
    profit = max((nums[ind]+f(ind+1,1,t-1,nums,dp)),(f(ind+1,0,t,nums,dp)));
    return dp[ind][buy][t]=profit;
}
    int maxProfit(vector<int>& prices) {
         int n = prices.size();
     vector<vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(3, -1)));


         return f(0,1,2,prices,dp);
        
    }
int f(int ind,int buy, vector<int>& nums ,vector<vector<int>>& dp )
{
    if(ind==(nums.size()))
    return 0;
    if(dp[ind][buy]!=-1)
    return dp[ind][buy];
    int profit;
    if(buy)
    profit = max((-nums[ind]+f(ind+1,0,nums,dp)),(f(ind+1,1,nums,dp)));
    else
    profit = max((nums[ind]+f(ind+1,1,nums,dp)),(f(ind+1,0,nums,dp)));
    return dp[ind][buy]=profit;
}
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
         vector<vector<int>> dp(n,vector<int>(2,-1));
         return f(0,1,prices,dp);
        
    }
import { useState } from "react";
import "./App.css";

function Square({ value, onSquareClick }) {
  return (
    <button className="square" onClick={onSquareClick}>
      {value}
    </button>
  );
}

function Board({ xIsNext, squares, onPlay }) {
  function handleClick(i) {
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    const nextSquares = squares.slice();
    if (xIsNext) {
      nextSquares[i] = "X";
    } else {
      nextSquares[i] = "O";
    }
    onPlay(nextSquares);
  }

  const winner = calculateWinner(squares);
  let status;
  if (winner) {
    status = "Winner: " + winner;
  } else {
    status = "Next player: " + (xIsNext ? "X" : "O");
  }

  return (
    <>
      <div className="status">{status}</div>
      <div className="board-row">
        <Square value={squares[0]} onSquareClick={() => handleClick(0)} />
        <Square value={squares[1]} onSquareClick={() => handleClick(1)} />
        <Square value={squares[2]} onSquareClick={() => handleClick(2)} />
      </div>
      <div className="board-row">
        <Square value={squares[3]} onSquareClick={() => handleClick(3)} />
        <Square value={squares[4]} onSquareClick={() => handleClick(4)} />
        <Square value={squares[5]} onSquareClick={() => handleClick(5)} />
      </div>
      <div className="board-row">
        <Square value={squares[6]} onSquareClick={() => handleClick(6)} />
        <Square value={squares[7]} onSquareClick={() => handleClick(7)} />
        <Square value={squares[8]} onSquareClick={() => handleClick(8)} />
      </div>
    </>
  );
}

export default function Game() {
  const [history, setHistory] = useState([Array(9).fill(null)]);
  const [currentMove, setCurrentMove] = useState(0);
  const xIsNext = currentMove % 2 === 0;
  const currentSquares = history[currentMove];

  function handlePlay(nextSquares) {
    const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
    setHistory(nextHistory);
    setCurrentMove(nextHistory.length - 1);
  }

  function jumpTo(nextMove) {
    setCurrentMove(nextMove);
  }

  const moves = history.map((squares, move) => {
    let description;
    if (move > 0) {
      description = "Go to move #" + move;
    } else {
      description = "Go to game start";
    }
    return (
      <li key={move}>
        <button onClick={() => jumpTo(move)}>{description}</button>
      </li>
    );
  });

  return (
    <div className="game">
      <div className="game-board">
        <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
      </div>
      <div className="game-info">
        <ol>{moves}</ol>
      </div>
    </div>
  );
}

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}
#include <bits/stdc++.h>
using namespace std;


class Solution {
public:
	void shortest_distance(vector<vector<int>>&matrix) {
		int n = matrix.size();
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (matrix[i][j] == -1) {
					matrix[i][j] = 1e9;
				}
				if (i == j) matrix[i][j] = 0;
			}
		}

		for (int k = 0; k < n; k++) {
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					matrix[i][j] = min(matrix[i][j],
					                   matrix[i][k] + matrix[k][j]);
				}
			}
		}




		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (matrix[i][j] == 1e9) {
					matrix[i][j] = -1;
				}
			}
		}
	}
};
#include <iostream>
using namespace std;
int sqrt(int arr[], int n, int key) {
  int start = 0;
  int end = n - 1;
  int mid = start + (end - start) / 2;
  int ans = -1;
  while (start <= end) {
    int square = mid * mid;
    if (square == key) {
      return mid;
    } else if (square > key) {
      end = mid - 1;
    } else {
      start = mid + 1;
      ans = mid;
    }
    mid = start + (end - start) / 2;
  }
  return ans;
}
double precision(int n, int precision, int integer) {
  double factor = 1;
  double ans = integer;
  for (int i = 0; i < precision; i++) {
    factor = factor / 10;
    for (double j = ans; j * j < n; j += factor) {
      ans = j;
    }
  }
  return ans;
}
int main() {
  int n;
  cout << "enter the number :" << endl;
  cin >> n;
  int arr[n];
  for (int i = 0; i < n; i++) {
    arr[i] = (i + 1);
  }
  int squareRoot = sqrt(arr, n, n);
  double finalAns = precision(n, 3, squareRoot);
  cout << "square root of " << n << " is " << finalAns << endl;
  return 0;
}
#include <iostream>
using namespace std;
long long int binarySearch(int arr[],int n,int key) {
  int start = 0;
  int end = n-1;
  long long int mid = start + (end-start)/2;
  long long int ans = -1;
while (start <= end){
  long long int square = mid*mid;
  if (square == key) {
    return mid;
  }
  else if (square > key) {
    end = mid - 1;
  }
  else {
    start = mid + 1;
    ans = mid;
  }
  mid = start + (end-start)/2;
}
  return ans;
}
int main() {
  int n;
  cout << "enter the number :" << endl;
  cin >> n;
  int arr[n];
  for (int i = 0; i < n; i++) {
     arr[i] = (i+1);
  }
  int squareRoot = binarySearch(arr,n,n);
  cout << "square root of " << n << " is " << squareRoot << endl;
  return 0;
}
class Solution {
  public:
    /*  Function to implement Bellman Ford
    *   edges: vector of vectors which represents the graph
    *   S: source vertex to start traversing graph with
    *   V: number of vertices
    */
    vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S) {
        // Code here
        //iterate through edges ond keep on updating the distance array. Iterate through all the edges for 
        //V-1 times
        vector<int> dis(V,1e8);
        dis[S]=0;
        for(int i=0;i<V-1;i++){
            
            for(int j =0;j<edges.size();j++){
                int u = edges[j][0];
                int v = edges[j][1];
                int w = edges[j][2];
                if(dis[u] != 1e8 && dis[u]+w<dis[v]){
                    dis[v]=dis[u]+w;
                }
            }
        }
        for(int i=0;i<1;i++){
            
            for(int j =0;j<edges.size();j++){
                int u = edges[j][0];
                int v = edges[j][1];
                int w = edges[j][2];
                if(dis[u] != 1e8 && dis[u]+w<dis[v]){
                    return {-1};
                }
            }
        }
        
        return dis;
    }
};
// To change the add to cart button on the single product page
add_filter( 'woocommerce_product_single_add_to_cart_link', 'custom_single_add_to_cart_link', 10, 2 );
function custom_single_add_to_cart_link( $button, $product ) {
    $url = $product->get_permalink();
    $button_text = __( 'See Prices', 'woocommerce' );
    $button = '<a href="' . esc_url( $url ) . '" class="button single_add_to_cart_button"><img src="https://mejormovil.es/wp-content/themes/woodmart/images/amazon-icon.png?_t=1717658998" alt="Amazon Icon" style="vertical-align: middle; margin-right: 5px; width: 16px; height: 16px;" />' . esc_html( $button_text ) . '</a>';
    return $button;
}

// To change the add to cart button on the product archives (collection) page
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_loop_add_to_cart_link', 10, 2 );
function custom_loop_add_to_cart_link( $button, $product ) {
    $url = $product->get_permalink();
    $button_text = __( 'See Prices', 'woocommerce' );
    $button = '<a href="' . esc_url( $url ) . '" class="button add_to_cart_button"><img src="https://mejormovil.es/wp-content/themes/woodmart/images/amazon-icon.png?_t=1717658998" alt="Amazon Icon" style="vertical-align: middle; margin-right: 5px; width: 16px; height: 16px;" />' . esc_html( $button_text ) . '</a>';
    return $button;
}

element.style {
}
.tag-description {
    margin-bottom: 20px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    background: #333;
    text-align: center;
    min-height: 150px;
    margin: 60px auto 80px;
    padding-left: 50px;
    padding-right: 50px;
}

#single #comments.hosted .comment .large.comment-author, .title.large, .wpcf7 label.large {
    font-size: 30px;
    line-height: 1.2;
}

.getox {
	display:none
}
.btnText {
    /* Default button styles */
}

.btnText {
    /* Default button styles */
}

/* Media query for mobile devices */
@media screen and (max-width: 768px) {
    .btnText {
        width: 150px; /* Adjusted width for mobile view */
        height: 30px; /* Adjusted height for mobile view */
        font-size: 10px; /* Adjusted font size for mobile view */
        text-align: center; /* Center align the text */
        line-height: 18px; /* Vertically center the text */
        font-weight: bold; /* Make the text bold */
        /* Add any additional styles for mobile view */
    }
}

.wd-product .wd-entities-title {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
    height: 22px;
    font-size: inherit;
}
.wd-carousel-inner{
	height:auto;
}

.wd-product :is(.product-image-link,.hover-img) img {
    width: 100%;
	height:250px
}

.wd-product .wd-entities-title {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
    height: 22px;
    font-size: inherit;
}
.wd-carousel-inner{
	height:auto;
}

.wd-product :is(.product-image-link,.hover-img) img {
    width: auto;
	height:250px
}



/* Styling the language switch container */
.gt_languages {
  display: flex;
  gap: 10px;
  margin: 10px 0; /* Add margin for spacing if needed */
}

/* Styling each language link */
.gt_languages a {
  display: flex;
  align-items: center;
  text-decoration: none; /* Remove default underline */
  color: #333; /* Default text color */
  font-weight: bold; /* Make text bold */
  padding: 5px 10px; /* Add some padding */
  border-radius: 5px; /* Rounded corners */
  transition: background-color 0.3s; /* Smooth transition for hover effect */
}

/* Adding hover effect */
.gt_languages a:hover {
  background-color: #f0f0f0; /* Light gray background on hover */
}

/* Styling the current language link */
.gt_languages a.gt-current-lang {
  background-color: #dcdcdc; /* Different background for the current language */
}

/* Styling the language flags */
.gt_languages img {
  margin-right: 5px; /* Space between flag and text */
  width: 24px; /* Ensure consistent size for flags */
  height: 24px; /* Ensure consistent size for flags */
}


.wd-product.wd-hover-fw-button .wrap-price {
    display: none;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: var(--wd-prod-gap);
}





.wd-product .price {
    display: none;
}

.wd-single-price .price {
  display:none;  
	margin-bottom: 0;
    font-size: 155%;
    line-height: 1.2;
}


.product-image-link {
    pointer-events: none;
    cursor: default;
}


class Solution
{
	public:
	//Function to find the shortest distance of all the vertices
    //from the source vertex S.
    vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
    {
        // Code here
        //Dijkstra's algo
        //adj list, Create a dis array, intitialize with int_max, dis[src]=0,create a priority
        //queue or set where we'll store the dis and node, this priority queue/set would be sorted 
        // by the dis value and anlways the node with the smallest dis value will be at bottom,
        //we'll take out each one by one and then iterate to their adj nodes
        // and check if dis[curr]+wt<dis[child], if true then update the distance array
        vector<int> dis(V,INT_MAX);
        dis[S]=0;
        set<pair<int,int>> pq;
        pq.insert({0,S});
        while(!pq.empty()){
            auto it =*(pq.begin());
            int wt = it.first;
            int node = it.second;
            pq.erase(it);
            for(auto it:adj[node]){
                int ch = it[0];
                int edge =it[1];
                if(wt+edge<dis[ch]){
                    dis[ch]=wt+edge;
                    pq.insert({dis[ch],ch});
                }
            }
        }
        return dis;
        
        
    }
};
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class PostController extends Controller
{
    public function index()
    {
        $response = Http::get('https://jsonplaceholder.typicode.com/posts');
        $posts = $response->json();

        return view('posts.index', ['posts' => $posts]);
    }

    public function edit($id)
    {
        $response = Http::get('https://jsonplaceholder.typicode.com/posts/' . $id);
        $post = $response->json();

        return view('posts.edit', ['post' => $post]);
    }

    public function update(Request $request, $id)
    {
        // Simulates update logic for a real application (not supported by this API)
        $response = Http::put('https://jsonplaceholder.typicode.com/posts/' . $id, [
            'title' => $request->input('title'),
            'body' => $request->input('body'),
        ]);

        // Simulated response for successful or failed update
        if ($response->successful()) {
            return redirect()->route('posts.index')->with('success', 'Post updated successfully!');
        } else {
            return redirect()->route('posts.index')->with('error', 'Failed to update post. Please try again.');
        }
    }

    public function destroy($id)
    {
        // Simulates deletion logic for a real application (not supported by this API)
        $response = Http::delete('https://jsonplaceholder.typicode.com/posts/' . $id);

        // Simulated response for successful or failed deletion
        if ($response->successful()) {
            return redirect()->route('posts.index')->with('success', 'Post deleted successfully!');
        } else {
            return redirect()->route('posts.index')->with('error', 'Failed to delete post. Please try again.');
        }
    }
}
#include <iostream>
using namespace std;
int pivotSearch (int arr[],int n) {
  int start = 0;
  int end = n-1;
  int mid = start + (end-start)/2;
  while (start < end) {
    if (arr[mid] >= arr[0]) {
      start = mid + 1;
    }
    else {
      end = mid;
    }
    mid = start + (end-start)/2;
  }
  return end;
}
int binarySearch(int arr[],int n,int s,int e,int key) {
  int start = s;
  int end = e;
  int mid = start + (end-start)/2;
while (start <= end){
  if (arr[mid] == key) {
    return mid;
  }
  else if (arr[mid] > key) {
    end = mid - 1;
  }
  else {
    start = mid + 1;
  }
  mid = start + (end-start)/2;
}
  return -1;
}
int main() {
  int arr[6] = {3,8,10,0,1,2};
  int ans = pivotSearch(arr,6);
  cout << "the pivot is at : "<< ans << endl;
  if (2>=arr[ans]&&2<=arr[5]) {
    cout << "the element is present in the array at index     :" << binarySearch(arr,6,ans,5,2); 
  }
  else {
    cout << "the element is present in the array at index     :" << binarySearch(arr,6,0,ans-1,2);
  }
  return 0;
}
#include <iostream>
using namespace std;
int pivotSearch (int arr[],int n) {
  int start = 0;
  int end = n-1;
  int mid = start + (end-start)/2;
  while (start < end) {
    if (arr[mid] >= arr[0]) {
      start = mid + 1;
    }
    else {
      end = mid;
    }
    mid = start + (end-start)/2;
  }
  return end;
}
int main() {
  int arr[5] = {3,8,10,17,1};
  int ans = pivotSearch(arr,5);
  cout << "the pivot is : "<< ans;
  return 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Example</title>
</head>
<body>
  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <button type="button" onclick="handleFormSubmit()">Submit</button>
  </form>

  <script src="script.js"></script>
</body>
</html>



// the JS
// Function to get the value from the input field
function getValue(callback) {
  // Get the input field
  const nameInput = document.getElementById('name');
  // Get the value from the input field
  const nameValue = nameInput.value;
  // Pass the value to the callback function
  callback(nameValue);
}

// Callback function to process the value
function processValue(value) {
  console.log('Processing value...');
  console.log(`Value received: ${value}`);
  // You can add more logic here to process the value further
}

// Function to handle form submission
function handleFormSubmit() {
  getValue(processValue);
}
(function () {
  'use strict';

  function fetchData(callback) { // create the first (outer) function
    const data = 'get data from an API';
    setTimeout(() => {
      callback(data); // use the callback param as a function and pass in the data value
    }, 1000);
  }

  function displayData(data) { // create the inner function that takes in the callback as a param
    console.log('processing data');
    console.log(data);
  }

  fetchData(displayData); // finally call the outer function with the inner function as a value
})();
import { useState } from "react";

function MyButton() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return <button onClick={handleClick}>Clicked {count} {count === 1 ? "time" : "times"}</button>;
}

function App() {
  return <MyButton />;
}

export default App;
import "./App.css";

function MyButton() {
  return <button>MyButton</button>;
}

const products = [
  { title: "Cabbage", isFruit: false, id: 0 },
  { title: "Garlic", isFruit: false, id: 1 },
  { title: "Apple", isFruit: true, id: 2 },
];

function App() {
  const listitems = products.map((product) => (
    <li style={{ color: product.isFruit ? "red" : "green" }} key={product.id}>
      {product.title}
    </li>
  ));

  return (
    <div>
      <h1>Home</h1>
      <MyButton />
      <ul>{listitems}</ul>
    </div>
  );
}

export default App;
from collections import Counter

data = ['Java', 'Python', 'Java', 'C++', 'Python', 'PHP', 'C++', 'Java', 'PHP', 'Java', 'Python']

c = Counter(data)

print(c.most_common(3))
import tempfile

temp = tempfile.TemporaryFile('w+')
print(temp)

#write to the file
temp.write("Hello world,")
temp.write("\nWelcome to Pynerds.")

#read from the file
temp.seek(0)
for i in temp.read():
    print(i, end = '')

temp.close()
#Example with list
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(ascii(L.__repr__())) #same as print(L)

#Example with tuples
T = ("Pynerds", "Python", "Django", "Flask")
print(T.__repr__()) #same as print(T)

D = {1: "One", 2: "Two", 3: "Three"}

print(D.__repr__())#Same as print(D)
    Rigidbody m_Rigidbody;
    public float m_Speed = 5f;

    void Start()
    {
        //Fetch the Rigidbody from the GameObject with this script attached
        m_Rigidbody = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        //Store user input as a movement vector
        Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

        //Apply the movement vector to the current position, which is
        //multiplied by deltaTime and speed for a smooth MovePosition
        m_Rigidbody.MovePosition(transform.position + m_Input * Time.deltaTime * m_Speed);
    }
#include <iostream>
using namespace std;
int firstOcc(int arr[], int n, int key) {
  int start = 0;
  int end = n-1;
  int ans = -1;
  int mid = start + (end-start)/2;
  while (start <= end) {
    if (arr[mid] == key) {
      ans = mid;
      end = mid - 1;
    }
    else if (arr[mid] < key) {
      start = mid + 1;
    }
    else {
      end = mid - 1;
    } 
    mid = start + (end-start)/2;
  }
  return ans;
}
int lastOcc(int arr[], int n, int key) {
  int start = 0;
  int end = n-1;
  int ans = -1;
  int mid = start + (end-start)/2;
  while (start <= end) {
    if (arr[mid] == key) {
      ans = mid;
      start = mid + 1;
    }
    else if (arr[mid] < key) {
      start = mid + 1;
    }
    else {
      end = mid - 1;
    } 
    mid = start + (end-start)/2;
  }
  return ans;
}
int main() {
  int array[6] = {1,2,2,2,2,3};
  int first = firstOcc(array,6,2);
  cout << "first occurance of 2 is at index " << first << endl;
  int last = lastOcc(array,6,2);
  cout << "last occurance of 2 is at index " << last << endl;
  return 0;
}
void getNumberPattern(int n) {
    // Write your code here.
    for(int i=0;i<2*n-1;i++){
        for(int j=0;j<2*n-1;j++){
            int top=i;
            int left=j;
            int bottom=(2*n-2)-i;
            int right=(2*n-2)-j;
            cout<<n-min(min(top,left),min(right,bottom));
        }
        cout<<"\n";
    }
}
a , b = int(input()), int(input())
total_maximum = 0                    # сумма делителей
digit = 0                            # число с максимальной суммой делителей

for i in range(a, b + 1):             # цикл перебирающий все числа от a до b включительно
    maximum = 0                       # обнуление суммы делителей, для нового цикла
    for j in range(1, i + 1):         # проверяем все числа от 1 до числа не превышающего проверяемое
        if i % j == 0:                # проверка на деление без остатка
            maximum += j              # суммируем делители
        if maximum >= total_maximum:  # если сумма делителей больше max суммы делителей
            total_maximum = maximum   # записываем в переменную максимальную
            digit = j
print(digit, total_maximum)           # вывод 
  int f(int ind,vector<int>& nums,vector<int>& dp)
  {
      int one,two=INT_MAX;
      if(ind==0)return 0;
      if(dp[ind]!=-1)
      return dp[ind];
       one = f(ind-1,nums,dp)+abs(nums[ind]-nums[ind-1]);
      if(ind>1)
       two = f(ind-2,nums,dp)+abs(nums[ind]-nums[ind-2]);
      return dp[ind]=min(one,two);
  }
    int minimumEnergy(vector<int>& height, int n) {
        // Code here
        vector<int> dp(n,-1);
        return f(n-1,height,dp);
    }
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final TextInputFormatter phoneNumberFormatter =
      FilteringTextInputFormatter.allow(
    RegExp(r'^\d{0,11}'),
  );

  final _formKey = GlobalKey<FormState>();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      // Perform the login action
      print('Form is valid');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(35.0),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                const Text(
                  'لطفا جهت ورود به برنامه، شماره تلفن خود را وارد نمایید',
                  textAlign: TextAlign.right,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 20),
                Directionality(
                  textDirection: TextDirection.rtl,
                  child: TextFormField(
                    controller: _nameController,
                    textAlign: TextAlign.end,
                    decoration: const InputDecoration(
                      labelText: 'نام و نام خانوادگی',
                      border: OutlineInputBorder(),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue, width: 2.0),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'لطفا نام و نام خانوادگی خود را وارد کنید';
                      }
                      return null;
                    },
                  ),
                ),
                const SizedBox(height: 20),
                Directionality(
                  textDirection: TextDirection.rtl,
                  child: TextFormField(
                    controller: _phoneController,
                    textAlign: TextAlign.end,
                    decoration: const InputDecoration(
                      labelText: 'شماره تلفن',
                      border: OutlineInputBorder(),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue, width: 2.0),
                      ),
                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly,
                      phoneNumberFormatter,
                    ],
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'لطفا شماره تلفن خود را وارد کنید';
                      } else if (!RegExp(r'^09\d{9}$').hasMatch(value)) {
                        return 'شماره تلفن باید با 09 شروع شود و 11 رقم باشد';
                      }
                      return null;
                    },
                  ),
                ),
                const SizedBox(height: 20),
                ElevatedButton(
                  onPressed: _submitForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    padding: const EdgeInsets.symmetric(vertical: 16.0),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    textStyle: const TextStyle(
                      fontSize: 18,
                      color: Colors.white,
                    ),
                  ),
                  child: const Text('ادامه'),
                ),
                const SizedBox(height: 20),
                const Text(
                  'با ورود و استفاده از برنامه، شما با شرایط و قوانین موافقت می‌نمایید.',
                  textAlign: TextAlign.end,
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
import 'package:first/Login/component/butten_next.dart';
import 'package:first/Login/component/phone_textfield.dart';
import 'package:first/Login/component/user_textfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final _formKey = GlobalKey<FormState>();

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      // Perform the login action
      print('Form is valid');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(35.0),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                const Text(
                  'لطفا جهت ورود به برنامه، شماره تلفن خود را وارد نمایید',
                  textAlign: TextAlign.right,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 20),
                const UserNameTextField(),
                const SizedBox(height: 20),
                const PhoneNumberTextField(),
                const SizedBox(height: 20),
                GradientButton(
                  text: 'ادامه',
                  onPressed: _submitForm,
                ),
                const SizedBox(height: 20),
                const Text(
                  'با ورود و استفاده از برنامه، شما با شرایط و قوانین موافقت می‌نمایید',
                  textAlign: TextAlign.end,
                  style: TextStyle(
                      fontSize: 12, color: Color.fromARGB(255, 0, 0, 0)),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


btnclass
import 'package:flutter/material.dart';

class GradientButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  const GradientButton({
    Key? key,
    required this.text,
    required this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [
            Color.fromARGB(255, 24, 40, 219),
            Color.fromARGB(255, 25, 235, 2)
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(8.0),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2),
            spreadRadius: 1,
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          padding: const EdgeInsets.symmetric(vertical: 16.0),
          backgroundColor: Colors.transparent,
          shadowColor: Colors.transparent,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          textStyle: const TextStyle(
            fontSize: 18,
            color: Colors.white,
          ),
        ),
        child: Text(text),
      ),
    );
  }
}

Variable declarations begin with two dashes (-) and are given a name and a value like this: --variable-name: value;
                                             
To use a variable, put the variable name in parentheses with var in front of them like this: var(--variable-name). Whatever value you gave the variable will be applied to whatever property you use it on.

You should add a fallback value to a variable by putting it as the second value of where you use the variable like this: var(--variable-name, fallback-value). The property will use the fallback value when there's a problem with the variable. 

Variables are often declared in the :root selector. This is the highest level selector in CSS; putting your variables there will make them usable everywhere.

Gradients in CSS are a way to transition between colors across the distance of an element. They are applied to the background property and the syntax looks like this:

Example Code
gradient-type(
  color1,
  color2
);

Gradients can use as many colors as you want like this:

Example Code
gradient-type(
  color1,
  color2,
  color3
);

You can specify where you want a gradient transition to complete by adding it to the color like this:

Example Code
gradient-type(
  color1,
  color2 20%,
  color3
);

Gradient transitions often gradually change from one color to another. You can make the change a solid line like this:

Example Code
linear-gradient(
  var(--first-color) 0%,
  var(--first-color) 40%,
  var(--second-color) 40%,
  var(--second-color) 80%
);

You can specify another direction by adding it before your colors like this:

Example Code
gradient-type(
  direction,
  color1,
  color2
);

You can add multiple gradients to an element by separating them with a comma (,) like this:

Example Code
gradient1(
  colors
),
gradient2(
  colors
);
 int f(int ind,int wt, int w[],int v[],vector<vector<int>>& dp)
    {
        if(ind==0)
        {
            return (w[0]<=wt)?v[0]:0;
        }
        int pick,nonpick;
        if(dp[ind][wt]!=-1)
        return dp[ind][wt];
        nonpick = f(ind-1,wt,w,v,dp);
        pick = INT_MIN;
        if(wt>=w[ind])
        pick = v[ind] + f(ind-1,wt-w[ind],w,v,dp);
        
        return dp[ind][wt] = max(pick,nonpick);
    }
    int knapSack(int W, int wt[], int val[], int n) 
    { 
       // Your code here
       vector<vector<int>> dp(n + 1, vector<int>(W + 1, -1));
       return f(n-1,W,wt,val,dp);
    }
public class ListToArrayExample{  
public static void main(String args[]){  
 List<String> fruitList = new ArrayList<>();    
 fruitList.add("Mango");    
 fruitList.add("Banana");    
 fruitList.add("Apple");    
 fruitList.add("Strawberry");    
 //Converting ArrayList to Array  
 String[] array = fruitList.toArray(new String[fruitList.size()]);    
 System.out.println("Printing Array: "+Arrays.toString(array));  
 System.out.println("Printing List: "+fruitList);  
}  
}  
import java.util.*;  
public class ArrayToListExample{  
public static void main(String args[]){  
//Creating Array  
String[] array={"Java","Python","PHP","C++"};  
System.out.println("Printing Array: "+Arrays.toString(array));  
//Converting Array to List  
List<String> list=new ArrayList<String>();  
for(String lang:array){  
list.add(lang);  
}  
System.out.println("Printing List: "+list);  
  
}  
}  
Use the universal selector to add box-sizing: border-box; to your CSS. This ensures elements include padding and border in their specified width and height.

CSS positioning lets you set how you want an element to be positioned in the browser. It has a position property you can set to static, absolute, relative, sticky or fixed.

Once you set the position property of the element, you can move the element around by setting a pixel or a percentage value for one or more of the top, right, left, or bottom properties.

static is the default positioning for all elements. If you assign it to an element, you won't be able to move it around with top, right, left, or bottom.

When you use the relative value, the element is still positioned according to the normal flow of the document, but the top, left, bottom, and right values become active.

The next position property is absolute. When you use the absolute value for your position property, the element is taken out of the normal flow of the document, and then its position is determined by the top, right, bottom, and left properties.

fixed is a position property value that lets you make an element fixed to the page no matter where the user scrolls to on the page.

The last position property value is sticky. sticky positioning is a hybrid of relative and fixed positioning. It allows an element to stick to a specific position within its containing element or viewport, based on the scroll position.

The transform property allows you to modify the shape, position, and size of an element without changing the layout or affecting the surrounding elements. It has functions such as translate(), rotate(), scale(), skew(), and matrix().

z-index is a property you can use to define the order of overlapping HTML elements. Any element with a higher z-index will always be positioned over an element with a lower z-index.

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

There are four different combinators in CSS:

descendant selector (space)
child selector (>)
adjacent sibling selector (+)
general sibling selector (~)

The @media at-rule, also known as a media query, is used to conditionally apply CSS. Media queries are commonly used to apply CSS based on the viewport width using the max-width and min-width properties.

In the below example the padding is applied to the .card class when the viewport is 960px wide and below.

Example Code
@media (max-width: 960px) {
  .card {
    padding: 2rem;
  }
}

Logical operators can be used to construct more complex media queries. The and logical operator is used to query two media conditions.

For example, a media query that targets a display width between 500px and 1000px would be:

Example Code
@media (min-width: 500px) and (max-width: 1000px){

}

Setting the width of a block-level element will prevent it from stretching out to the edges of its container to the left and right. Then, you can set the left and right margins to auto to horizontally center that element within its container. The element will take up the width you specify, then the remaining space will be split evenly between the two margins.

The only problem occurs when the browser window is narrower than the width of your element. The browser resolves this by creating a horizontal scrollbar on the page. 

Using max-width instead of width in this situation will improve the browser's handling of small windows. 
You can use CSS pseudo selectors to change specific HTML elements.

The span[class~="sr-only"] selector will select any span element whose class includes sr-only.

The CSS clip property is used to define the visible portions of an element. 

The clip-path property determines the shape the clip property should take.

The :first-of-type pseudo-selector is used to target the first element that matches the selector.

The :last-of-type pseudo-selector does the exact opposite - it targets the last element that matches the selector.

The calc() function is a CSS function that allows you to calculate a value based on other values. For example, you can use it to calculate the width of the viewport minus the margin of an element:
.exampleClass {
  margin: 10px;
  width: calc(100% - 20px);
}

Adding position sticky moved the element into its own stack. To ensure your element does not get hidden by different stacks, add a z-index.

The :not() pseudo-selector is used to target all elements that do not match the selector.

The border-collapse property sets whether table borders should collapse into a single border or be separated as in standard HTML.

The [attribute="value"] selector targets any element that has an attribute with a specific value. 

The key difference between tr[class="total"] and tr.total is that the first will select tr elements where the only class is total. The second will select tr elements where the class includes total.

The :nth-of-type() pseudo-selector is used to target specific elements based on their order among siblings of the same type.

Vertically align the text to the top, horizontally align the text to the right.
	text-align: right;
	vertical-align: top;
background-color: #f0f0f0; /* sets the background color to a light gray */
font-family: Arial, sans-serif; /* sets the font to Arial or a similar sans-serif font */
  font-size: 18px; /* sets the font size to 18 pixels */
  font-style: italic; /* sets the font style to italic */
  color: #00698f; /* sets the text color to a dark blue */
  text-align: center; /* centers the text horizontally */
  text-decoration: underline; /* adds an underline to the text */
  text-indent: 20px; /* indents the text 20 pixels from the left */
}
```
Flexbox helps you design your webpage so that it looks good on any screen size.

The box-sizing property is used to set this behavior. By default, the content-box model is used. With this model, when an element has a specific width, that width is calculated based only on the element's content. Padding and border values get added to the total width, so the element grows to accommodate these values.

The border-box sizing model does the opposite of content-box. The total width of the element, including padding and border, will be the explicit width set. The content of the element will shrink to make room for the padding and border.

Flexbox is a one-dimensional CSS layout that can control the way items are spaced out and aligned within a container.

To use it, give an element a display property of flex. This will make the element a flex container. Any direct children of a flex container are called flex items.

Flexbox has a main and cross axis. The main axis is defined by the flex-direction property, which has four possible values:

row (default): horizontal axis with flex items from left to right
row-reverse: horizontal axis with flex items from right to left
column: vertical axis with flex items from top to bottom
column-reverse: vertical axis with flex items from bottom to top

The flex-wrap property determines how your flex items behave when the flex container is too small. Setting it to wrap will allow the items to wrap to the next row or column. nowrap (default) will prevent your items from wrapping and shrink them if needed.

The justify-content property determines how the items inside a flex container are positioned along the main axis, affecting their position and the space around them.

The align-items property positions the flex content along the cross axis. For example, with your flex-direction set to row (horizontal), your cross axis would be vertical.

The CSS object-fit property is used to specify how an <img> or <video> should be resized to fit its container.

This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible".

The gap CSS shorthand property sets the gaps, also known as gutters, between rows and columns. The gap property and its row-gap and column-gap sub-properties provide this functionality for flex, grid, and multi-column layout. You apply the property to the container element.

The ::after pseudo-element creates an element that is the last child of the selected element. You can use it to add an empty element after the last image. If you give it the same width as the images it will push the last image to the left when the gallery is in a two-column layout. Right now, it is in the center because you set justify-content: center on the flex container.
 for (const item of menu.entries()) {
    const [index, ...menuItem] = item;
    const startIndex = index + 1;
    console.log(`${startIndex}: ${menuItem}`);
  }
star

Sun Jun 23 2024 17:53:51 GMT+0000 (Coordinated Universal Time)

@utp #c++

star

Sun Jun 23 2024 17:53:06 GMT+0000 (Coordinated Universal Time)

@utp #c++

star

Sun Jun 23 2024 15:08:51 GMT+0000 (Coordinated Universal Time) https://www.reddit.com/r/ObsidianMD/comments/1bthjlp/what_plugins_could_i_use_to_organize_a_fiveyear/

@Enrico

star

Sun Jun 23 2024 14:39:26 GMT+0000 (Coordinated Universal Time)

@mehran

star

Sun Jun 23 2024 14:10:43 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sun Jun 23 2024 14:02:53 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sun Jun 23 2024 14:01:13 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sun Jun 23 2024 13:51:27 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/python-math-log10-function/

@pynerds #python

star

Sun Jun 23 2024 13:43:15 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/problems/minimum-spanning-tree/1

@Dragon14641 #c++

star

Sun Jun 23 2024 13:02:41 GMT+0000 (Coordinated Universal Time) Buy & Sell Stock II & III are important for Stock DP

@ayushg103 #c++

star

Sun Jun 23 2024 12:36:10 GMT+0000 (Coordinated Universal Time) https://hdtoday.tv/home

@wheter

star

Sun Jun 23 2024 12:22:13 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sun Jun 23 2024 11:21:34 GMT+0000 (Coordinated Universal Time) From my self

@Black_Shadow #react.js #+jsx

star

Sun Jun 23 2024 11:01:35 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/problems/implementing-floyd-warshall2042/1

@Dragon14641

star

Sun Jun 23 2024 10:39:23 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=6z2HK4o8qcU&list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA&index=14

@vishnu_jha #c++ #dsa

star

Sun Jun 23 2024 10:18:46 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=6z2HK4o8qcU&list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA&index=14

@vishnu_jha #c++ #dsa

star

Sun Jun 23 2024 10:07:22 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/problems/distance-from-the-source-bellman-ford-algorithm/1

@Dragon14641 #c++

star

Sun Jun 23 2024 09:52:57 GMT+0000 (Coordinated Universal Time)

@Promakers2611

star

Sun Jun 23 2024 09:52:20 GMT+0000 (Coordinated Universal Time)

@Promakers2611

star

Sun Jun 23 2024 09:51:29 GMT+0000 (Coordinated Universal Time)

@Promakers2611

star

Sun Jun 23 2024 09:49:42 GMT+0000 (Coordinated Universal Time)

@Promakers2611

star

Sun Jun 23 2024 09:16:50 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1

@Dragon14641

star

Sun Jun 23 2024 08:33:22 GMT+0000 (Coordinated Universal Time) https://laracoding.com/calling-an-external-api-with-laravel/

@Sifat_H

star

Sun Jun 23 2024 08:27:08 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=6z2HK4o8qcU&list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA&index=14

@vishnu_jha #c++ #dsa

star

Sun Jun 23 2024 07:49:57 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=6z2HK4o8qcU&list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA&index=14

@vishnu_jha #c++ #dsa

star

Sun Jun 23 2024 04:31:38 GMT+0000 (Coordinated Universal Time)

@davidmchale #callback #functions #forms

star

Sun Jun 23 2024 04:23:58 GMT+0000 (Coordinated Universal Time)

@davidmchale #callback #functions

star

Sat Jun 22 2024 20:23:25 GMT+0000 (Coordinated Universal Time) From my self

@Black_Shadow #react.js #+jsx

star

Sat Jun 22 2024 19:34:26 GMT+0000 (Coordinated Universal Time) From my self

@Black_Shadow #react.js #+jsx

star

Sat Jun 22 2024 18:55:00 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/python-collections-counter/

@pynerds #python

star

Sat Jun 22 2024 18:32:43 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/tempfile-module-in-python/

@pynerds #python

star

Sat Jun 22 2024 18:31:41 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/python-classes-repr-method/

@pynerds #python

star

Sat Jun 22 2024 16:01:43 GMT+0000 (Coordinated Universal Time) https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html

@gil

star

Sat Jun 22 2024 15:19:20 GMT+0000 (Coordinated Universal Time)

@vishnu_jha #c++

star

Sat Jun 22 2024 14:53:33 GMT+0000 (Coordinated Universal Time)

@Xeno_SSY #c++

star

Sat Jun 22 2024 14:41:20 GMT+0000 (Coordinated Universal Time) https://zazloo.ru/7-9-pokolenie-python/

@qwdixq

star

Sat Jun 22 2024 14:20:00 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sat Jun 22 2024 12:30:34 GMT+0000 (Coordinated Universal Time)

@mehran

star

Sat Jun 22 2024 12:30:00 GMT+0000 (Coordinated Universal Time)

@mehran

star

Sat Jun 22 2024 07:46:12 GMT+0000 (Coordinated Universal Time)

@NoFox420 #css

star

Sat Jun 22 2024 06:58:31 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sat Jun 22 2024 05:56:36 GMT+0000 (Coordinated Universal Time) undefined

@swatijaan

star

Sat Jun 22 2024 05:27:36 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/98ef9070-97c0-43e1-b062-8f76a88a78d2

@codeplugin

star

Sat Jun 22 2024 03:37:16 GMT+0000 (Coordinated Universal Time) https://www.javatpoint.com/java-list

@iyan #java

star

Sat Jun 22 2024 03:34:45 GMT+0000 (Coordinated Universal Time) https://www.javatpoint.com/java-list

@iyan #java

star

Sat Jun 22 2024 03:25:42 GMT+0000 (Coordinated Universal Time)

@NoFox420 #css

star

Sat Jun 22 2024 02:36:11 GMT+0000 (Coordinated Universal Time)

@NoFox420 #css

star

Sat Jun 22 2024 00:10:22 GMT+0000 (Coordinated Universal Time) Created

@MathewC84

star

Fri Jun 21 2024 22:47:49 GMT+0000 (Coordinated Universal Time)

@NoFox420 #css

star

Fri Jun 21 2024 22:34:10 GMT+0000 (Coordinated Universal Time)

@davidmchale #for #loop #index

Save snippets that work with our extensions

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