Wednesday, 8 November 2023

How to create model viewer for glb file to run in website.

 Below is the soure code to view glb file in website.


<!-- starts here-->
        <style> #mvdemo { width: 50%; height: 500px; } </style>
        <script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js"></script>
        <script nomodule src="https://unpkg.com/@google/model-viewer/dist/model-viewer-legacy.js"></script>        
        <model-viewer id="mvdemo" shadow-intensity="1" src="{{asset('TRY2.glb')}}" alt=""
        loading="eager" camera-controls touch-action="pan-y" auto-rotate poster=""></model-viewer>
        <!-- ends here -->

Wednesday, 16 August 2023

try and catch

 
use Log;

public function function_name(Request $request)
    {            
        try
        {
            $id= $request->oid;
            $data = Order::where('id',$id)->first();  
            if (!is_null($data)) {
                $result =  Order::where('id', $id)->update([
                    'status' => "Approved",
                    'approved_by' => auth()->user()->name,]);  
                    return redirect()->route('order-management')->withStatus('Status updated');   
            }else{                 
                    return redirect()->route('order-management')->withStatus('Record is not available.');   
            } 
        }
        catch (\Exception\Database\QueryException $e)
        {
           Log::info('Query: '.$e->getSql());
           Log::info('Query: Bindings: '.$e->getBindings());
           Log::info('Error: Code: '.$e->getCode());
           Log::info('Error: Message: '.$e->getMessage());  
           return redirect()->route('user-management')->withStatus('Internal Server Error.  Please try again later.');
        } 
    }

Wednesday, 12 July 2023

Laravel 10 setup with material ui and Laratrust.

 




Step1:  composer create-project laravel/laravel canpac

Step2:  cd canpac

Step3:  composer require laravel/ui

Step4:  php artisan ui bootstrap --auth 

Step5:  composer require laravel-frontend-presets/material-dashboard    

Step6:  php artisan ui material    

Step7:  composer dump-autoload 

Step8:  php artisan migrate 

Step9:  php artisan db:seed 

Step10: php artisan storage:link

Step11: php artisan serve

Step12: composer require santigarcor/laratrust

Step13: php artisan vendor:publish --tag=laratrust-assets --force

Step14: php artisan optimize:clear

Step15: php artisan laratrust:setup

Step16: composer dump-autoload

Step17: php artisan migrate

Step18: php artisan laratrust:seeder

Step19: php artisan vendor:publish --tag="laratrust-seeder"

Step20: composer dump-autoload

Step21: php artisan db:seed --class=LaratrustSeeder

Step22: php artisan serve

Step23: npm install

npm run dev

http://*****/laratrust/roles-assignment

******************************************************************

User Model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Contracts\Auth\CanResetPassword;
use Laratrust\Contracts\LaratrustUser;
use Laratrust\Traits\HasRolesAndPermissions;

class User extends Authenticatable implements LaratrustUser
{
    use HasApiTokens, HasFactory, Notifiable;
    use HasRolesAndPermissions;

Web.php

<?php


use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DashboardController;

use App\Http\Controllers\ProfileController;

use App\Http\Controllers\RegisterController;

use App\Http\Controllers\SessionsController;

  


Route::get('/', function () { return redirect('sign-in');})->middleware('guest');

Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth')->name('dashboard');

Route::get('sign-up', [RegisterController::class, 'create'])->middleware('guest')->name('register');

Route::post('sign-up', [RegisterController::class, 'store'])->middleware('guest');

Route::get('sign-in', [SessionsController::class, 'create'])->middleware('guest')->name('login');

Route::post('sign-in', [SessionsController::class, 'store'])->middleware('guest');

Route::post('verify', [SessionsController::class, 'show'])->middleware('guest');

Route::post('reset-password', [SessionsController::class, 'update'])->middleware('guest')->name('password.update');

Route::get('verify', function () { return view('sessions.password.verify'); })->middleware('guest')->name('verify'); 

Route::get('/reset-password/{token}', function ($token) { return view('sessions.password.reset', ['token' => $token]); })->middleware('guest')->name('password.reset');


Route::post('sign-out', [SessionsController::class, 'destroy'])->middleware('auth')->name('logout');

Route::get('profile', [ProfileController::class, 'create'])->middleware('auth')->name('profile');

Route::post('user-profile', [ProfileController::class, 'update'])->middleware('auth');


Route::group(['middleware' => 'auth'], function () { 

Route::get('billing', function () { return view('pages.billing'); })->name('billing');

Route::get('tables', function () { return view('pages.tables'); })->name('tables');

Route::get('rtl', function () { return view('pages.rtl'); })->name('rtl');

Route::get('virtual-reality', function () { return view('pages.virtual-reality'); })->name('virtual-reality');

Route::get('notifications', function () { return view('pages.notifications'); })->name('notifications');

Route::get('static-sign-in', function () { return view('pages.static-sign-in'); })->name('static-sign-in');

Route::get('static-sign-up', function () { return view('pages.static-sign-up'); })->name('static-sign-up');

Route::get('user-management', function () { return view('pages.laravel-examples.user-management');})->name('user-management');

Route::get('user-profile', function () { return view('pages.laravel-examples.user-profile');})->name('user-profile');

});


*********************************************************************************

Laratrust->layout.blade.php

<x-layout bodyClass="g-sidenav-show bg-gray-200">

    <x-navbars.sidebar activePage="roles-permissions"></x-navbars.sidebar>

    <div class="main-content position-relative max-height-vh-100 h-100 border-radius-lg ">

        <!-- Navbar -->

        <x-navbars.navs.auth titlePage="Roles and Permissions"></x-navbars.navs.auth>

        <!-- End Navbar -->

        <link href="{{ mix('laratrust.css', 'vendor/laratrust') }}" rel="stylesheet">

        <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer> </script>

        <div class="container-fluid py-4">

            <div class="row">

                <div class="col-12">

                    <div class="card my-4">

                        <div class="card-header p-0 position-relative mt-n4 mx-3 z-index-2">

                            <div class="bg-gradient-primary shadow-primary border-radius-lg pt-4 pb-3">

                                <div class="flex items-center justify-center h-16">

                                    <div class="flex items-center">

                                        <div class="flex items-baseline">

                                            <a href="{{config('laratrust.panel.go_back_route')}}" class="nav-button">←

                                                Go Back</a>

                                            <a href="{{ route('laratrust.roles-assignment.index') }}"

                                                class="ml-4 {{ request()->is('*roles-assignment*') ? 'nav-button-active' : 'nav-button' }}">

                                                Roles & Permissions Assignment

                                            </a>

                                            <a href="{{route('laratrust.roles.index')}}"

                                                class="ml-4 {{ request()->is('*roles') ? 'nav-button-active' : 'nav-button' }}">

                                                Roles

                                            </a>

                                            <a href="{{ route('laratrust.permissions.index') }}"

                                                class="ml-4 {{ request()->is('*permissions*') ? 'nav-button-active' : 'nav-button' }}">

                                                Permissions

                                            </a>

                                        </div>

                                    </div>

                                </div>

                            </div>

                        </div>


                        <div class="card-body p-3 pb-0">

                            @foreach (['error', 'warning', 'success'] as $msg)

                            @if(Session::has('laratrust-' . $msg))

                            <div class="alert alert-{{ $msg }} alert-dismissible text-white" role="alert">

                                <span class="text-sm">{{ Session::get('laratrust-' . $msg) }}</span>

                                <button type="button" class="btn-close text-lg py-3 opacity-10" data-bs-dismiss="alert"

                                    aria-label="Close"><span aria-hidden="true">&times;</span>

                                </button>

                            </div>

                            @endif

                            @endforeach

                        </div>


                        <div class="card-body px-0 pb-2">

                            @yield('content')

                        </div>

                    </div>

                </div>

            </div>

        </div>


        <x-footers.auth></x-footers.auth>

    </div>

    <x-plugins></x-plugins>

</x-layout>

**********************************************************

Laratrust->permission->index.blade.php

@extends('laratrust::panel.layout')

@section('title', 'Permissions')

@section('content')

@if (config('laratrust.panel.create_permissions'))

<div class=" me-3 my-3 text-end">

    <a href="{{route('laratrust.permissions.create')}}" class="btn bg-gradient-dark mb-0">+ New Permission</a>

</div>

@endif


<div class="table-responsive p-0">

    <table class="table align-items-center mb-0">

        <thead>

            <tr>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Id</th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Name/Code</th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Display Name</th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Description</th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7"></th>

            </tr>

        </thead>

        <tbody>

            @foreach ($permissions as $permission)

            <tr>

                <td>

                    <div class="d-flex px-2 py-1">

                        <div class="d-flex flex-column justify-content-center">

                            <p class="mb-0 text-sm">{{$permission->getKey()}}</p>

                        </div>

                    </div>

                </td>

                <td>

                    <div class="d-flex flex-column justify-content-center">

                        <h6 class="mb-0 text-sm">{{$permission->name}}</h6>

                    </div>

                </td>

                <td>

                    <div class="d-flex flex-column justify-content-center">

                        <h6 class="mb-0 text-sm">{{$permission->display_name}}</h6>

                    </div>

                </td>

                <td>

                    <p class="text-xs text-secondary mb-0">{{$permission->description}}</p>

                </td>

                <td class="align-middle">

                    <a rel="tooltip" class="btn btn-success btn-link" href="{{route('laratrust.permissions.edit', $permission->getKey())}}" data-original-title="" title="">

                        <i class="material-icons">edit</i>

                        <div class="ripple-container"></div>

                    </a>                    

                </td>

            </tr>

            @endforeach

        </tbody>

    </table>

</div>

{{ $permissions->links('laratrust::panel.pagination') }}

@endsection

*********************************************************************

Laratrust->Role->index.blade

@extends('laratrust::panel.layout')

@section('title', 'Roles')

@section('content')

@if (config('laratrust.panel.create_permissions'))

<div class=" me-3 my-3 text-end">

    <a href="{{route('laratrust.roles.create')}}" class="btn bg-gradient-dark mb-0">+ New Role</a>

</div>

@endif


<div class="table-responsive p-0">

    <table class="table align-items-center mb-0">

        <thead>

            <tr>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Id</th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Name/Code</th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Display Name</th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Description Permission

                </th>

                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7"></th>

            </tr>

        </thead>

        <tbody>

            @foreach ($roles as $role)

            <tr>

                <td>

                    <div class="d-flex px-2 py-1">

                        <div class="d-flex flex-column justify-content-center">

                            <p class="mb-0 text-sm">{{$role->getKey()}}</p>

                        </div>

                    </div>

                </td>

                <td>

                    <div class="d-flex flex-column justify-content-center">

                        <h6 class="mb-0 text-sm">{{$role->name}}</h6>

                    </div>

                </td>

                <td>

                    <div class="d-flex flex-column justify-content-center">

                        <h6 class="mb-0 text-sm">{{$role->display_name}}</h6>

                    </div>

                </td>

                <td>

                    <p class="text-xs text-secondary mb-0">

                        {{$role->description}} ({{$role->permissions_count}})</p>

                </td>


                <td class="justify-content-center" style="display:flex ">

                   

                        @if (\Laratrust\Helper::roleIsEditable($role))

                        <a rel="tooltip" class="btn btn-success btn-link"

                            href="{{route('laratrust.roles.edit', $role->getKey())}}">Edit</a> &nbsp;&nbsp;


                        <form action="{{route('laratrust.roles.destroy', $role->getKey())}}" method="POST"

                            onsubmit="return confirm('Are you sure you want to delete the record?');">

                            @method('DELETE')

                            @csrf

                            <button type="submit" class="btn btn-danger btn-link" data-original-title="" title="">

                                <i class="material-icons">close</i>

                                <div class="ripple-container"></div>

                            </button>

                        </form> 

                        @else

                        <a rel="tooltip" class="btn btn-success btn-link" href="{{route('laratrust.roles.show', $role->getKey())}}">Details</a>

                        @endif

                </td>

            </tr>

            @endforeach

        </tbody>

    </table>

</div> 

{{ $roles->links('laratrust::panel.pagination') }}

@endsection




Monday, 20 March 2023

How to install Apache2, Mysql, Phpmyadmin, Webmin and Jenkins

 Here I have listed the url for the above requirement.

1. Apache

     https://www.digitalocean.com/community/tutorials/how-to-install-the-apache-web-server-on-ubuntu-22-04

2. Mysql

     https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-20-04

3. ================================
# PHP-Installation on Server.
================================
apt-get install python-software-properties

add-apt-repository ppa:ondrej/php

apt-get install -y php8.0

apt install libapache2-mod-php8.0 php8.0-common php8.0-mysql php8.0-xml php8.0-xmlrpc php8.0-curl php8.0-gd php8.0-imagick php8.0-cli php8.0-dev php8.0-imap php8.0-mbstring php8.0-opcache php8.0-soap php8.0-zip php8.0-intl php8.0-mbstring -y

apt-get install -y php8.1

apt install libapache2-mod-php8.1 php8.1-common php8.1-mysql php8.1-xml php8.1-xmlrpc php8.1-curl php8.1-gd php8.1-imagick php8.1-cli php8.1-dev php8.1-imap php8.1-mbstring php8.1-opcache php8.1-soap php8.1-zip php8.1-intl php8.1-mbstring -y

4. Phpmyadmin

wget https://files.phpmyadmin.net/phpMyAdmin/5.2.0/phpMyAdmin-5.2.0-all-languages.zip  

   Download phpmyadmin from below link. Move to var/www/html and unzip. Rename to phpmyadmin

5. Webmin

     https://www.digitalocean.com/community/tutorials/how-to-install-webmin-on-ubuntu-20-04

    When problem occur for password check the below link   

      /usr/share/webmin/changepass.pl /etc/webmin root password

6. Jenkins

       https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-ubuntu-22-04

        https://www.programmerhat.com/failed-to-start-jenkins-continuous-integration-server/

        when  problem occurs use the below link. The error occurs for Java version.

        https://www.programmerhat.com/failed-to-start-jenkins-continuous-integration-server/

 7.   How To Add Swap Space on Ubuntu.

        https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-20-04


Wednesday, 22 February 2023

Get distance between address in kilometer

 <?php 

        $addressFrom = 'Bus Stand, 3MQQ+R3Q, Enasan, Gujarat 382330';
        $addressTo   = 'RAJKOT BUS PORT, bus port shop, 48, Kanak Rd, Karanpara, Rajkot, Gujarat 360001';
 ?>
<span>{{ getDistance($addressFrom, $addressTo, "K") }}</span>

*************************************************************

<?php
function getDistance($addressFrom, $addressTo, $unit = 'K')
{
    // Google API key
    $apiKey = 'xxxxxxxx';
    
    // Change address format
    $formattedAddrFrom    = str_replace(' ', '+', $addressFrom);
    $formattedAddrTo     = str_replace(' ', '+', $addressTo);
    
    // Geocoding API request with start address
    $geocodeFrom = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false&key='.$apiKey);
    $outputFrom = json_decode($geocodeFrom);
    if(!empty($outputFrom->error_message)){
        return $outputFrom->error_message;
    }
    
    // Geocoding API request with end address
    $geocodeTo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false&key='.$apiKey);
    $outputTo = json_decode($geocodeTo);
    if(!empty($outputTo->error_message)){
        return $outputTo->error_message;
    }
    
    // Get latitude and longitude from the geodata
    $latitudeFrom    = $outputFrom->results[0]->geometry->location->lat;
    $longitudeFrom    = $outputFrom->results[0]->geometry->location->lng;
    $latitudeTo        = $outputTo->results[0]->geometry->location->lat;
    $longitudeTo    = $outputTo->results[0]->geometry->location->lng;
    
    // Calculate distance between latitude and longitude
    $theta    = $longitudeFrom - $longitudeTo;
    $dist    = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
    $dist    = acos($dist);
    $dist    = rad2deg($dist);
    $miles    = $dist * 60 * 1.1515;
    
    // Convert unit and return distance
    $unit = strtoupper($unit);
    if($unit == "K"){
        return round($miles * 1.609344, 2).' km';
    }elseif($unit == "M"){
        return round($miles * 1609.344, 2).' meters';
    }else{
        return round($miles, 2).' miles';
    }
}
?> 

 

Tuesday, 21 February 2023

Google autosuggest address

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <!-- Fonts -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"
        integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"></script>
    <style> .pac-container.pac-logo { z-index: 9999; }  </style>
</head>
<body>
    <div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
        <div class="grid grid-cols-1 md:grid-cols-2">
            <div class="container mt-2">
                <div class="row">
                    <div class="col-md-6  m-auto">
                        <div class="card shadow">
                            <div class="card-body">
                                <!-- Trigger the modal with a button -->
                                <input type="text" name="currentlocation" id="currentlocation"
                                    class="form-control col-md-6" placeholder="Select Location" readonly
                                    data-toggle="modal" data-target="#myModal">
                                <!-- Modal -->
                                <div id="myModal" class="modal fade" role="dialog">
                                    <div class="modal-dialog col-md-5 modal-sm">

                                        <!-- Modal content-->
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close"
                                                    data-dismiss="modal">&times;</button>
                                                <h4 class="modal-title">Search Location</h4>
                                            </div>
                                            <div class="modal-body">
                                                <div class="card-body">
                                                    <div class="form-group">
                                                        <input type="text" name="autocomplete" id="autocomplete"
                                                            class="form-control" placeholder="Enter a city">
                                                    </div>
                                                    <div class="form-group" id="lat_area">
                                                        <label for="latitude"> Latitude </label>
                                                        <input type="text" name="latitude" id="latitude"
                                                            class="form-control">
                                                    </div>
                                                    <div class="form-group" id="long_area">
                                                        <label for="latitude"> Longitude </label>
                                                        <input type="text" name="longitude" id="longitude"
                                                            class="form-control">
                                                    </div>
                                                    <br>
                                                    <div id="ucurrentlocation">Use Current Location</div>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-default"
                                                    data-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
                integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
                crossorigin="anonymous"></script>
            <script
                src="https://maps.google.com/maps/api/js?key=xxxxx&libraries=places&callback=initAutocomplete"
                type="text/javascript"></script>
            <script src="address.js"></script>
        </div>
    </div>
    <script> $("#ucurrentlocation").click(function(event) { getLocation(); });

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            div.innerHTML = "The Browser Does not Support Geolocation";
        }
    }

    function showPosition(position) {
        var location = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," +
            position.coords.longitude + "&key=xxxxx"
        $.get(location, function(data) {
            $("#currentlocation").val(data.results[0].formatted_address);
        });
    }

    function showError(error) {
        if (error.PERMISSION_DENIED) {
            div.innerHTML = "The User have denied the request for Geolocation.";
        }
    }
    getLocation();
    </script>
</body>
</html>

*************************************************************

address.js            

$(document).ready(function () {
    $("#lat_area").addClass("d-none");
    $("#long_area").addClass("d-none");
});
google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
    var input = document.getElementById("autocomplete");
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.addListener("place_changed", function () {
        var place = autocomplete.getPlace();      
        $("#latitude").val(place.geometry["location"].lat());
        $("#longitude").val(place.geometry["location"].lng());
        // --------- show lat and long ---------------
        $("#lat_area").removeClass("d-none");
        $("#long_area").removeClass("d-none");
        var newadd =$("#autocomplete").val();
        $("#currentlocation").val(newadd);
        $(".close").click();
    });
}

Sunday, 19 February 2023

Create new scratch card.

 Html

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Scratch Card</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
    <div class="container">
      <div class="base">
        <h4>You Won</h4>
        <h3>$20</h3>
      </div>
      <canvas id="scratch" width="200" height="200"></canvas>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>


Scriptjs

let canvas = document.getElementById("scratch");
let context = canvas.getContext("2d");

const init = () => {
  let gradientColor = context.createLinearGradient(0, 0, 135, 135);
  gradientColor.addColorStop(0, "#c3a3f1");
  gradientColor.addColorStop(1, "#6414e9");
  context.fillStyle = gradientColor;
  context.fillRect(0, 0, 200, 200);
};

//initially mouse X and mouse Y positions are 0
let mouseX = 0;
let mouseY = 0;
let isDragged = false;

//Events for touch and mouse
let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmove",
    up: "touchend",
  },
};

let deviceType = "";

//Detech touch device
const isTouchDevice = () => {
  try {
    //We try to create TouchEvent. It would fail for desktops 
and throw error.
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

//Get left and top of canvas
let rectLeft = canvas.getBoundingClientRect().left;
let rectTop = canvas.getBoundingClientRect().top;

//Exact x and y position of mouse/touch
const getXY = (e) => {
  mouseX = (!isTouchDevice() ? e.pageX : e.touches[0].pageX) - rectLeft;
  mouseY = (!isTouchDevice() ? e.pageY : e.touches[0].pageY) - rectTop;
};

isTouchDevice();
//Start Scratch
canvas.addEventListener(events[deviceType].down, (event) => {
  isDragged = true;
  //Get x and y position
  getXY(event);
  scratch(mouseX, mouseY);
});

//mousemove/touchmove
canvas.addEventListener(events[deviceType].move, (event) => {
  if (!isTouchDevice()) {
    event.preventDefault();
  }
  if (isDragged) {
    getXY(event);
    scratch(mouseX, mouseY);
  }
});

//stop drawing
canvas.addEventListener(events[deviceType].up, () => {
  isDragged = false;
});

//If mouse leaves the square
canvas.addEventListener("mouseleave", () => {
  isDragged = false;
});

const scratch = (x, y) => {
  //destination-out draws new shapes behind the existing canvas content
  context.globalCompositeOperation = "destination-out";
  context.beginPath();
  //arc makes circle - x,y,radius,start angle,end angle
  context.arc(x, y, 12, 0, 2 * Math.PI);
  context.fill();
};

window.onload = init();


style.css

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
  body {
    height: 50vh;    
  }
  .container {
    width: 20em;
    height: 20em;
    background-color: #f5f5f5;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    border-radius: 0.6em;
  }
  .base,
  #scratch {
    height: 200px;
    width: 200px;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    text-align: center;
    cursor: pointer;
    border-radius: 1.3em;
  }
  .base {
    background-color: #ffffff;
    font-family: "Poppins", sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    box-shadow: 0 1.2em 2.5em rgba(17, 12, 99, 0.15);
  }
  .base h3 {
    font-weight: 600;
    font-size: 3.5em;
    color: #17013b;
  }
  .base h4 {
    font-weight: 400;
    color: #746e7e;
  }
  #scratch {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    user-select: none;
  }


Thursday, 16 February 2023

How to get the current longitude and latitude. using javascript?

<div id="location"></div>

<script>
    var div = document.getElementById("location");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            div.innerHTML = "The Browser Does not Support Geolocation";
        }
    }
    
    function showPosition(position) {
        div.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }
    
    function showError(error) {
        if (error.PERMISSION_DENIED) {
            div.innerHTML = "The User have denied the request for Geolocation.";
        }
    }
    getLocation();
</script>

Wednesday, 15 February 2023

URL encode

 URL  encode

 

 <?php

namespace App\Http\Controllers\API;
 
use Log; use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class EncodeController extends Controller
{       
    // UrlEncode
    public function urlencode(Request $request)
    {
        try            
        {  
            $myvar = DB::table('cl_master_category')
            ->select('cl_master_category.category_id', 'cl_master_category.category_name', 'cl_master_category.status', 'cl_master_category.color_code')
            ->get();
            
            $ciphering = "AES-256-CBC";    
            $encryption_key = env('ENCRYPTION_KEY');            
            $encryption_iv = env('ENCRYPTION_IV');
            
            $myencoding = openssl_encrypt($myvar, $ciphering,$encryption_key, 0, $encryption_iv);  
            
            return response()->json(['success' => true ,'encoded'=>$myencoding], 200);
           
        }
        catch (\Exception\Database\QueryException $e)
        {
            Log::info('Query: '.$e->getSql());
            Log::info('Query: Bindings: '.$e->getBindings());
            Log::info('Error: Code: '.$e->getCode());
            Log::info('Error: Message: '.$e->getMessage());

            return response()->json(['success' => false , 'message' => 'Database Server Error. Please try again later.'], 500);
        }
        catch (\Exception $e)
        {
            Log::info('Error: Code: '.$e->getCode());
            Log::info('Error: Message: '.$e->getMessage());

            return response()->json(['success' => true , 'message' => 'Internal Server Error. Please try again later.'], 500);
        }
    }
   
}


********************************************************************
Nextjs code

import React from "react";

import CryptoJS from "crypto-js";

const test = () => { 

  let keytext =  "25c6c7ff35b9979b151f2136cd13b0ff"

  let encrypted = "Nb7g0tuktmBmEwUbGrMabzMHlUTN/uyDPg5coE0AHTgmkvkxmwYxapvMu4IaZoCEXphDN+A+PfcMRGGdPso1vbKWJU9X1Yr+oh/eBRobD6hkG4BWJIxnVW79LSkK8WBfieMy05j2FxQH8GzXlPJ9KtcaMcxU2Zj8YERpko2Q8bpcWAlbQVDHXHRaYLMjoR7QvUz2OYqY3CNyLQgXnoc70q5JyAT+eC036Mx/zBnjA16HeVI5xI1MFQ4aFEddd58XwICngKZcuahG0tdUcZ8Z4XgZnmMzMrt+QeunhPg+IQGZhPhL4ZqH2CMYMy2TDtIqClRiAytjekMIcyJErYjVSYPnvGuBQqXiwW23QM69XWMvY0WFmZXXnKQPiwcRUSh3UgEPmbk6Dx023KnL6uw6Maq7/8BzaPzKCJO31gxyXk17NEh+by/59/UDaaLSKnB4fFRu1G/qa+Rg5n5l01XK2uNWITqKne3xWleACeMN652ZVhU1dWPwiWKkwI6hjbCg8m9UtRKw57rq3d6Jt/pN+SUdLJXbIjcTd9oxWlltSUDv4LlstWIlRIx9i6B+SEOMWtEvJvVfDn2DrBtxdo+02SH7ZjNhNi8CEFEHQybPxNBd2KNaiAWyIHgiqCZwmoCDjgPoQh2bWj33jPOVGvqPsCfuFfW10RieWK8yMtZHV2/W16DX3+j3Urt7Cb5o0KvG2+va3+YvTZ123c3a/+UkR+S2odrhEku041VUahIx15Zlhi80ffPn0ngX6E4wDa5QkKAL34kZbQJnZPnzD0P4QOHl34cpn5ZZVP8HsoWAXrAiTM033qG976w43Ld1ewxGG5VhSGRgNHj9CQ42l5+7GQ=="

  // let decrypted = "";

  let ivtext ="1234567891011121"

  

  const key = CryptoJS.enc.Utf8.parse(keytext);

  const iv = CryptoJS.enc.Utf8.parse(ivtext);  

  var decrypted = CryptoJS.AES.decrypt(encrypted, key, {

    iv: iv,

    mode: CryptoJS.mode.CBC,

  });

  text = CryptoJS.enc.Utf8.stringify(decrypted)

  console.log("decrypt", CryptoJS.enc.Utf8.stringify(decrypted));

  return (

    <>

      <div> {text}</div>

      {/ <div>encrypted Text : {encrypted}</div> /}

      {/ <div>Decrypted Text : {decrypted}</div> /}

    </>

  );

};

export default test;

 

 

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...