Copy files from a running docker container to your local machine.

You can use the docker cp command to copy files from a running container to your local machine. Here’s an example command:

docker cp container_name:/usr/local/etc/php ./config/php/
Replace container_name with the name of your container. This command will copy all the files and folders in the /usr/local/etc/php directory of the container to the ./config/php directory on your local machine.

Top 10 best programming language for 2023

Here are the top 10 best programming languages for 2023, based on various industry reports and surveys:

    1. Python: Python continues to be one of the most popular programming languages, due to its ease of use and versatility.
    2. JavaScript: JavaScript remains a dominant language for web development and is widely used for creating dynamic and interactive web pages.
    3. Java: Java is widely used for building enterprise applications and has a large community of developers.
    4. C++: C++ is a powerful, fast, and efficient language that is used in many areas such as game development, system programming, and more.
    5. C#: C# is widely used for developing Windows desktop applications and games, and has strong support from Microsoft.
    6. Swift: Swift is a fast and modern language used for developing iOS and macOS applications.
    7. Kotlin: Kotlin is a cross-platform language that can be used for developing Android apps, web apps, and more.
    8. Ruby: Ruby is a dynamic, open-source language that is widely used for building web applications.
    9. Go: Go is a fast and efficient language that is used for building scalable network services and large scale system software.
    10. TypeScript: TypeScript is a statically typed superset of JavaScript that is used for building large-scale applications.

It is important to note that the popularity of programming languages can change rapidly, and these rankings may not be the same in the future. The choice of programming language often depends on the specific project requirements and individual preferences.

This report given on below surveys report 

    1. TIOBE Index: The TIOBE Index is a monthly report that tracks the popularity of programming languages based on the number of search engine results.
    2. GitHub Octoverse: GitHub’s Octoverse report provides an overview of the most popular programming languages used on the platform.
    3. Redmonk Programming Language Rankings: Redmonk’s Programming Language Rankings are based on the number of Stack Overflow questions and GitHub projects related to a particular language.
    4. Stack Overflow Developer Survey: Stack Overflow’s annual Developer Survey is one of the largest surveys of developers, and it includes data on the most popular programming languages.
    5. Developer Survey by JetBrains: JetBrains conducts an annual developer survey that includes data on the popularity of programming languages.

React Js hello world using docker.

In this blog we will follow 2 steps. In first step we will install react js then we will create docker environment. Let proceed.

1st Step :

Once you have Node.js and npm installed, follow these steps to install React:

    1. Open your terminal or command prompt and navigate to the directory where you want to create your React project.
    2. Run the following command to create a new React project using the “create-react-app” tool:
npm create-react-app my-react-app
    1. Replace “my-react-app” with the name of your project.

Wait for the process to complete, then navigate into the project directory:

cd my-react-app
    1. To start the development server and run the application, run the following command:
npm start
  1. Open your web browser and go to http://localhost:3000. You should see the default React application running.2nd Step :

Now for docker env , first we will create 3 files

Dockerfile
docker-compose.yml
Makefile

Now make your Dockerfile like below

FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD [ "npm", "start" ]

You can add below code for docker-compose.yml file

version: "3"
services:
  app:
    container_name: react-app
    build: .
    ports:
      - "3000:3000"
    volumes:
      - ./:/app

You can add below code in makefile

# Define the image name
IMAGE_NAME = react-app

# Define the command to build the Docker image
build:
docker build -t $(IMAGE_NAME) .

# Define the command to run the Docker container
run:
docker-compose up

# Define the command to stop the Docker container
stop:
docker stop $(IMAGE_NAME)

Use below command to build container

Make run

Now you should see your react js app in your browser in 3000 port

http://localhost:3000/

Laravel Dynamodb connection

Here’s a basic example of how to connect to DynamoDB and retrieve data using the AWS SDK for PHP in Laravel:

composer require aws/aws-sdk-php

In your Laravel application, create an AWS service client for DynamoDB:Install the AWS SDK for PHP via Composer by running the following command:

use Aws\DynamoDb\DynamoDbClient;

$client = new DynamoDbClient([
    'region' => 'us-west-2',
    'version' => '2012-08-10',
    'credentials' => [
        'key'    => 'YOUR_AWS_ACCESS_KEY_ID',
        'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
    ],
]);

Use the client to retrieve data from your DynamoDB table:

use Aws\DynamoDb\Exception\DynamoDbException;

try {
    $result = $client->getItem([
        'TableName' => 'YOUR_TABLE_NAME',
        'Key' => [
            'KEY_NAME' => [
                'S' => 'KEY_VALUE',
            ],
        ],
    ]);
    print_r($result['Item']);
} catch (DynamoDbException $e) {
    echo "Unable to retrieve item:\n";
    echo $e->getMessage() . "\n";
}

This is just a basic example. You can refer to the official AWS SDK for PHP documentation for more information and options: https://docs.aws.amazon.com/en_us/sdk-for-php/v3/developer-guide/getting-started.html

 

Cakephp JWT implement in API

We will follow 4 steps to implement JWT token in API

    1. Install a package to encode and decode JWT token
    2. Create a public and a private key to verify and for encode JWT token.
    3. Change middleware.
    4. Update login function.Install a package to encode and decode JWT tokenWe will use below package
      Link : https://github.com/firebase/php-jwt
      To install this package you have to give below composer command

      composer require firebase/php-jwt

      Create a public and a private key to verify and for encode JWT token.

      To generate public and private key in project directory we give below commands

      # generate private key
      openssl genrsa -out config/jwt.key 1024
      # generate public key
      openssl rsa -in config/jwt.key -outform PEM -pubout -out config/jwt.pem

 Change middleware

 

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface

{

$service = newAuthenticationService();

$fields = [

IdentifierInterface::CREDENTIAL_USERNAME => 'email',

IdentifierInterface::CREDENTIAL_PASSWORD => 'password'

];

$service->loadIdentifier('Authentication.Password', [

'returnPayload' => false,

'fields' => $fields,

]);

$service->loadAuthenticator('Authentication.Form', [

    'fields' => $fields,

]);

if($request->getParam('prefix') === 'Api'){

  $service->loadIdentifier('Authentication.JwtSubject');

  $service->loadAuthenticator('Authentication.Jwt', [

     'secretKey' => file_get_contents(CONFIG .'/jwt.pem'),

    'algorithm' => 'RS256',

     'returnPayload' => false

    ]);

}else{

$service->setConfig([

'unauthenticatedRedirect' => Router::url('/login'),

'queryParam' => 'redirect',

]);

$service->loadAuthenticator('Authentication.Session');

}

return$service;

}

Changing login method :

 

public function login()

{

$result = $this->Authentication->getResult();

if( $result->isValid() )

{

$user = $result->getData();

$privateKey = file_get_contents(CONFIG .'/jwt.key');

$payload = [

'sub' => $user->id,

'exp' => time()+60

];

$user = [

'token' => JWT::encode($payload,$privateKey,'RS256'),

'userEnt' => $user

];

}else{

$this->response = $this->response->withStatus(401);

$user = [

'message' => 'invalid user'

];

}

$this->set('user',$user);

$this->viewBuilder()->setOption('serialize','user');

}

That’s it.

Laravel custom pagination

paginate-img

Custom pagination easy to create in laravel. Example we have a html like below

<div class="pager">
    <a href="#"><i class="fa-solid fa-chevron-left"></i><span>前へ</span></a>
    <a href="#" class="page-num">1</a>
    <a href="#" class="page-num">2</a>
    <a href="#" class="page-num">3</a>
    <a href="#" class="page-num">4</a>
    <span class="current page-num">5</span>
    <a href="#" class="page-num">6</a>
    <a href="#" class="page-num">7</a>
    <a href="#" class="page-num">8</a>
    <a href="#" class="page-num">9</a>
    <a href="#"><span>次へ</span><i class="fa-solid fa-chevron-right"></i></a>
</div>

Output will example like below with my custom css

paginate-img

For custom design you can follow below tutorial in w3schools.com

https://www.w3schools.com/w3css/w3css_pagination.asp

 

Now , for convert this pagination in laravel we can create blade file example in location resources/views/elements/pagination.blade.php

The pagination file will looks like below

@if ($paginator->hasPages())

    <div class="pager">

        {{-- Previous Page Link --}}

        @if ($paginator->onFirstPage())

        <a class="disabled" href="{{ $paginator->previousPageUrl() }}"><i class="fa-solid fa-chevron-left"></i><span>前へ</span></a>

        @else

            <a href="{{ $paginator->previousPageUrl() }}"><i class="fa-solid fa-chevron-left"></i><span>前へ</span></a>

        @endif

        {{-- Pagination Elements --}}

        @foreach ($elements as $element)

            {{-- "Three Dots" Separator --}}

            @if (is_string($element))

                <a class="disabled" aria-disabled="true"><span>{{ $element }}</span></a>

            @endif

            {{-- Array Of Links --}}

            @if (is_array($element))

                @foreach ($element as $page => $url)

                    @if ($page == $paginator->currentPage())

                        <a class="current page-num" href="{{ $url }}">{{ $page }}</a>

                    @else

                        <a class="page-num" href="{{ $url }}">{{ $page }}</a>

                    @endif

                @endforeach

            @endif

        @endforeach

        {{-- Next Page Link --}}

        @if ($paginator->hasMorePages())

            <a href="{{ $paginator->nextPageUrl() }}"><span>次へ</span><i class="fa-solid fa-chevron-right"></i></a>

        @else

            <a class="disabled" aria-disabled="true" href="{{ $paginator->nextPageUrl() }}"><span>次へ</span><i class="fa-solid fa-chevron-right"></i></a>

        @endif

    </div>

@endif

Now , In view file you can add your pagination like below

{{ $books->links('../elements/pagination') }}

Here books is your object which you have sent from controller.

Now your output should like

output image
Command for get laravel existing helper template

php artisan vendor:publish --tag=laravel-pagination

Set Background image in Flutter

If you use a Container as the body of the Scaffold, its size will be accordingly the size of its child, and usually that is not what you want when you try to add a background image to your app.

@override
Widget build(BuildContext context) {
  return new Scaffold(
    body: new Stack(
      children: <Widget>[
        new Container(
          decoration: new BoxDecoration(
            image: new DecorationImage(image: new AssetImage("images/background.jpg"), fit: BoxFit.cover,),
          ),
        ),
        new Center(
          child: new Text("Hello background"),
        )
      ],
    )
  );
}

Flutter create a circle Icon.

Today we are going to create a circle icon using flutter.

Circle Icon

For this example we will crate a state less widget in flutter.

import 'package:flutter/material.dart';

class CircleIcon extends StatelessWidget {

   finalIconDataicon;
   finaldoubleiconSize;
   finalVoidCallbackonPressed;

   constCircleIcon({
       Key? key,
       requiredthis.icon,
       this.iconSize = 25.0,
       requiredthis.onPressed,

   }) : super(key: key);

   @override

   Widgetbuild(BuildContextcontext) {

   return Container(
        margin: constEdgeInsets.all(8.0),
        decoration: BoxDecoration(
           color: Colors.grey[200],
           shape: BoxShape.circle
        ),

        child: IconButton(
          onPressed: onPressed,
          icon: Icon(icon),
          color: Colors.black,
          iconSize: iconSize,
       ),
    ); //container
  }
}

Here in this widget iconSize is optional and icon and event is required. We can use this widget like below

import ‘../widgets/circle_icon.dart’;

CircleIcon(
      icon: Icons.person_outline, 
      onPressed: () {  },
),

Cakephp create a simple API

This tutorial for cakephp version 4, here we will learn how we can create a simple API using cakephp.

Our goal is we will create an API to save category if doesn’t exist !

Very beginning we will create a resources route in cakephp. Here, you may ask what is the resource route ? Answer is resource route will accept all http VERBS. Example GET,POST,PUT,DELETE,PUT

Now let’s go in cakephp source in location config/routes.php Go to the end of the line and create a new route scope for your API. Example 

$routes->scope('/api', function (RouteBuilder $routes) {
   $routes->setExtensions(['json']);
   $routes->resources('Categories',[

       'path' => 'category',
       'prefix' => 'Api',
       'map' => [

           'addCategory' => [
               'action' => 'addCategory',
               'method' => 'POST',
               'path' => '/add-category'
           ],
       ]
   ]);
});

Here , You can see I have created a route for my categories controller where I have an action called addCategory

So, Let’s create a class in location src/Controller/Api
Note : Create a folder with name Api, because in route we have used prefix Api

Now your CategoriesController.php will looks like below.

 

<?php

namespace App\Controller\Api;
use App\Controller\AppController;
use Cake\Event\EventInterface;
use Cake\ORM\TableRegistry;

Class CategoriesController extends AppController 
{
   public function addCategory()
   {

       $this->request->allowMethod(['post']);
       $category = $this->Categories->patchEntity($this->Categories->newEmptyEntity(), $this->request->getData());
       $this->set('category',$this->Categories->findOrCreate(
                   ['name'=>$this->request->getData('name')],
                   function()use($category){
                       return $category;
                   }
               )
           )
       ;
       $this->viewBuilder()->setOption('serialize', ['category']);
    }
}

Don’t forget to create a model for categories ! You can use a simple bake command to create a model for categories table.

bin/cake bake model categories

So, We have done it ! Now let’s test in postman , you can test it postman using below URL

http://localhost/api/category/add-category.json

Set body name = your-category-name

Also send a post request !

Cakephp get last month summary report.

Example we have a table called transactions.Where transactions has 3 fields 

Id | amount | created 

We need to fetch last month’s summary by the created date. So, in cakephp we can write like below

public function report()

{
       $targetDate = FrozenTime::now()->modify('1 month ago');
       $query = $this->Transactions->find();
       $query
          ->select(
           [
               'created',
               'amount'=> $query->func()->sum('Transactions.amount')
           ]
       )
       ->where([
           'Transactions.created >=' => $targetDate->startOfMonth(),
           'Transactions.created <=' => $targetDate->endOfMonth()
       ])
       ->group('Transactions.created');
       $this->set("transactions",$this->paginate($query));
   }

Here I have used cakephp FrozenTime class.
So, top in our class we have to use

use Cake\I18n\FrozenTime;

In view you can write below foreach loop to print data.

<?php foreach ($transactions as $transaction): ?>
        <tr>
             <td><?= $transaction->created->format("Y-m-d") ?></td>
             <td><?= $transaction->amount ?></td>
        /tr>
 <?php endforeach; ?>