フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

Pandasのメソッドについて

はじめに

  • 気分転換にたまにはPythonを触ってみる。

Pandasのメソッド

以下は、Pandasの機能だが、もっとあるはず・・・。

やりたいこと  メソッド
列名を抽出する df.columns
最初の2行を選択します df.iloc [2]
最初の2列を選択します df.iloc [:、2]
名前で列を選択 df.loc [:、["col1"、 "col2"]]
ランダム番号を選択します。行の df.sample(n = 10)
ランダムな行の一部を選択します df.sample(frac = 0.2)
変数の名前を変更します df.rename()
インデックスとして列を選択する df.set_index()
行または列の削除 df.drop()
値の並べ替え df.sort_values()
変数のグループ化 df.groupby()
フィルタリング df.query()
不足している値を見つける df.isnull()
不足している値を削除する df.dropna()
重複を削除する df.drop_duplicates()
ダミーの作成 pd.get_dummies()
ランキング df.rank()
累計 df.cumsum()
分位数 df.quantile()
数値変数の選択 df.select_dtypes()
2つのデータフレームを連結する pd.concat()
共通変数に基づいてマージ pd.merge()

変数タイプを知る

  • dataFrameName.dtypesコマンドを使用して、データフレームに格納されている変数のタイプの情報を抽出できる。

データ型の変更

  • astype()メソッドで型を変換(キャスト)することができる

一部の行のみを表示するには

  • デフォルトでは、head()は最初の5行を表示する。特定の行数を確認したい場合は、括弧内にそれを記載できます。  同様に、tail()関数はデフォルトで最後の5行を表示します。

カテゴリ変数を定義する

  • Rのfactors()関数と同様に、「category」dtypeを使用してPythonにカテゴリ変数を含めることができます。

Laravel 問い合わせフォームを作成する①

はじめに

  • laravelで問い合わせフォームを開発する

モデルの作成

  • モデルを作成する
php artisan make:model ContactForm -m

マイグレーション(テーブルの作成)

  • /database/migrations/YYYY_MM_DD_HHMMSS_create_contact_forms_table.phpファイルを下記のように修正し問い合わせテーブルのフィールドを追加する
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactFormsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contact_forms', function (Blueprint $table) {
            $table->id();
            $table->string('name', 20);
            $table->string('email', 255);
            $table->longText('url')->nullable();
            $table->boolean('sex');
            $table->tinyInteger('age');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contact_forms');
    }
}

readouble.com

  • テーブルを作成する
$ php artisan migrate
  • テーブルが作成されていることを確認する
mysql> desc contact_forms;
+-------------+---------------------+------+-----+---------+----------------+
| Field       | Type                | Null | Key | Default | Extra          |
+-------------+---------------------+------+-----+---------+----------------+
| id          | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| name        | varchar(20)         | NO   |     | NULL    |                |
| email       | varchar(255)        | NO   |     | NULL    |                |
| url         | longtext            | YES  |     | NULL    |                |
| sex         | tinyint(1)          | NO   |     | NULL    |                |
| age         | tinyint(4)          | NO   |     | NULL    |                |
| description | text                | NO   |     | NULL    |                |
| created_at  | timestamp           | YES  |     | NULL    |                |
| updated_at  | timestamp           | YES  |     | NULL    |                |
+-------------+---------------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)
  • 作成したテーブルにカラムを追加する場合、table名にフィールドを追加したいカラム名を指定する
php artisan make:migration add_title_to_contact_forms_table --table=contact_forms
  • /database/migrations/YYYY_MM_DD_HHMMSS_add_title_to_contact_forms_table.phpファイルを下記のように修正する
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactFormsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contact_forms', function (Blueprint $table) {
            $table->id();
            $table->string('name', 20);
            $table->string('email', 255);
            $table->longText('url')->nullable();
            $table->boolean('sex');
            $table->tinyInteger('age');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contact_forms');
    }
}
  • 既存テーブルにカラムを追加する
$ php artisan migrate
  • migrateのステータスを確認することができる。migrate:rollbackで1つ前のマイグレーションされた状態に戻すことができる
$ php artisan migrate:status
+------+----------------------------------------------------+-------+
| Ran? | Migration                                          | Batch |
+------+----------------------------------------------------+-------+
| Yes  | 2020_10_14_232814_create_contact_forms_table       | 1     |
| Yes  | 2020_10_14_235306_add_title_to_contact_forms_table | 2     |
+------+----------------------------------------------------+-------+
  • カラムが追加されていることを確認する
mysql> desc contact_forms;
+-------------+---------------------+------+-----+---------+----------------+
| Field       | Type                | Null | Key | Default | Extra          |
+-------------+---------------------+------+-----+---------+----------------+
| id          | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| name        | varchar(20)         | NO   |     | NULL    |                |
| email       | varchar(255)        | NO   |     | NULL    |                |
| url         | longtext            | YES  |     | NULL    |                |
| sex         | tinyint(1)          | NO   |     | NULL    |                |
| age         | tinyint(4)          | NO   |     | NULL    |                |
| description | text                | NO   |     | NULL    |                |
| subject     | varchar(50)         | NO   |     | NULL    |                |
| created_at  | timestamp           | YES  |     | NULL    |                |
| updated_at  | timestamp           | YES  |     | NULL    |                |
+-------------+---------------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)

Laravel フロントエンド

はじめに

  • 前回、laravel/uiをインストールすることができたので、実際にlaravel/uiを利用してみる
$ composer require laravel/ui

ログイン/ユーザー登録スカフォールドを生成

$ php artisan ui vue --auth
$ npm install
$ npm run watch
  • laravel/uiのエラーメッセージを日本語にしたい場合、下記のgithubからダウンロードし、ダウンロードしたファイルを「resources/lang/ja」フォルダに格納する github.com

コントローラ

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Facades\DB;

class TestController extends Controller
{
    public function index(){
        $categories = Category::all();
        return view('tests.test', compact('categories'));
    }
}

View(blade)

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>Laravel</title>

        <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div class="alert alert-primary" role="alert">
            BootStrapのアラート
        </div>
        <h3>カテゴリ一覧</h3>

        @foreach($categories as $category)

            {{$category->id}}<br>
            {{$category->name}}<br>

        @endforeach
        <div id="app">
            <example-component></example-component>
            <p>@{{ message }}</p>
        </div>
    <script src="{{ asset('js/app.js') }}"></script>
    </body>
</html>

Vuejs

  • 基本的にデフォルトに設定された状態のままです
/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
    data: {
        message: 'こんにちは!!!'
    },
});

実行結果

f:id:PX-WING:20201014005826p:plain

Laravel コレクション/クエリビルダなど

コレクション

  • データベースからデータ取得時はコレクション型になっている。 Eloquentクエリの結果は、常にCollectionインスタンスを返します。
  • メソッドチェーンで記述が可能である
  • コレクション型専用の関数多が多数ある。 all /chunk / get / pluck / whereln / toArrayなど

readouble.com

クエリビルダ

  • Select,where,groupbyなどSQLに近い構文がある
  • DB::table(テーブル名)->他のテーブルなど
  • クエリビルダはアプリケーションをSQLインジェクション攻撃から守るために、PDOパラメーターによるバインディングを使用します。 バインドする文字列をクリーンにしてから渡す必要はありません。

readouble.com

  • クエリビルダを利用する際は下記を指定する
use Illuminate\Support\Facades\DB;
  • 下記の実行結果はほぼ同じ値が取得できる
  $user  = User::find(1);
  $user = DB::table('users')->first()->get();
  • 直接SQLを記述したい場合、DB::rawを利用してSQLを記述することができる
$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

Note: rawメソッドはクエリを文字列として挿入するため、SQLインジェクション脆弱性を生まないように十分気をつけてください。

Facade(ファサード

  • 既存のクラスを複数組み合わせて使う手順を、「窓口」となるクラスを作ってシンプルに利用できるようにするパターンです。 www.techscore.com readouble.com

‐ config/app.phpファサードが指定されている

    'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

    ],

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Arr' => Illuminate\Support\Arr::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,
        'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
        'Bus' => Illuminate\Support\Facades\Bus::class,
        'Cache' => Illuminate\Support\Facades\Cache::class,
        'Config' => Illuminate\Support\Facades\Config::class,
        'Cookie' => Illuminate\Support\Facades\Cookie::class,
        'Crypt' => Illuminate\Support\Facades\Crypt::class,
        'DB' => Illuminate\Support\Facades\DB::class,
        'Eloquent' => Illuminate\Database\Eloquent\Model::class,
        'Event' => Illuminate\Support\Facades\Event::class,
        'File' => Illuminate\Support\Facades\File::class,
        'Gate' => Illuminate\Support\Facades\Gate::class,
        'Hash' => Illuminate\Support\Facades\Hash::class,
        'Http' => Illuminate\Support\Facades\Http::class,
        'Lang' => Illuminate\Support\Facades\Lang::class,
        'Log' => Illuminate\Support\Facades\Log::class,
        'Mail' => Illuminate\Support\Facades\Mail::class,
        'Notification' => Illuminate\Support\Facades\Notification::class,
        'Password' => Illuminate\Support\Facades\Password::class,
        'Queue' => Illuminate\Support\Facades\Queue::class,
        'Redirect' => Illuminate\Support\Facades\Redirect::class,
        'Redis' => Illuminate\Support\Facades\Redis::class,
        'Request' => Illuminate\Support\Facades\Request::class,
        'Response' => Illuminate\Support\Facades\Response::class,
        'Route' => Illuminate\Support\Facades\Route::class,
        'Schema' => Illuminate\Support\Facades\Schema::class,
        'Session' => Illuminate\Support\Facades\Session::class,
        'Storage' => Illuminate\Support\Facades\Storage::class,
        'Str' => Illuminate\Support\Str::class,
        'URL' => Illuminate\Support\Facades\URL::class,
        'Validator' => Illuminate\Support\Facades\Validator::class,
        'View' => Illuminate\Support\Facades\View::class,

    ],

DI依存やサービスコンテナ

ITエキスパートのための問題解決メディア - @IT

Laravelワカンネ(゚⊿゚)から「完全に理解した()」までステップアップ - Qiita

composer install時にメモリ不足エラーが発生したのでインスタンスタイプの変更して解決した

はじめに

  • composerでインストール時にメモリ不足で落ちる。スワップ領域を追加しても対応できなかったので、EC2インスタンスタイプを変更する
$ composer require laravel/ui
Using version ^3.0 for laravel/ui
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
PHP Fatal error:  Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52

Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.

インスタンスタイプ変更

‐ 「アクション」→「インスタンスの設定」→「インスタンスタイプの変更」を選択する f:id:PX-WING:20201013081314p:plain

  • [t2.micro]から [t2.medium]に変更する f:id:PX-WING:20201013081824p:plain

  • 簡単にインスタンスタイプの変更が完了した f:id:PX-WING:20201013082056p:plain

php.iniの設定

  • PHPのメモリリミットの設定の確認をする。defaultの128mbになっていることを確認する
$ php -r "echo ini_get('memory_limit').PHP_EOL;"
128MB
  • 「-1」にすることでメモリの利用制限を無制限にする
$ sudo vi /etc/php.ini
memory_limit = -1  ; 

composeを再度インストール

  • 依存関係のせいでインストールできなかったので不要なlibraryは削除する
composer remove kris/laravel-form-builder

‐ 無事インストールすることができた

$ composer require laravel/ui
Using version ^3.0 for laravel/ui
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: encore/laravel-admin
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: fruitcake/laravel-cors
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
77 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

Laravel 便利なヘルパ関数

はじめに

  • Laravelには、便利なグローバルヘルパー関数がたくさん付属しています。 開発がはるかに簡単になるヘルパをいくつかピックアップしました。

ヘルパ関数

array_flatten()

  • array_flatten関数は、多次元配列を単一レベルの配列に平坦化します。
$ array = [ 'name' => 'John' 、 'tools' => [ 'Laravel' 、 'Recipes' ] ] ;

$ flattened = array_flatten ($ array );

// ['John'、 'Laravel'、 'Recipes']

一部の値に別の配列が含まれている可能性があるすべての配列値を収集する必要がある場合は、非常に役立ちます。ここでは、すべての値のリストを含む新しい配列を取得することに集中しています。それは魅力のように機能します!

array_forget()

  • array_forget関数は、「ドット」表記を使用して、深くネストされた配列から特定のキーと値のペアを削除します。
$ array = [ 'users' => [ 'managers' => [ 'name' => 'John' ] ] ] ;

array_forget ($ array 、 'users.managers' );

// ['users' => []]

これは、配列要素を削除するためのネイティブPHP関数であるunset()関数のより良いバージョンです。

array_get()

  • 「ドット」表記を使用して、深くネストされた配列から値を取得します。
$ array = [ 'users' => [ 'managers' => [ 'name' => 'John' ] ] ] ;

$ price = array_get ($ array 、 'products.desk.price' );

// 100

array_only()

  • 配列内に使用したくないキーがたくさんあると想像してみてください。実際のところ、10個のキーのうち、2つだけを使用して、すぐに新しい配列を作成する必要があります。各アイテムを調べてarray_forget()する代わりに、必要なアイテムを選択するだけで済みます。array_only関数は、指定された配列から指定されたキーと値のペアのみを返します。
$ array = [ 'name' => 'John' 、 'type' => 'user' 、 'age' => 44 ] ;

$ lice = array_only ($ array 、 [ 'name' 、 'age' ] );

// ['name' => 'John'、 'age' => 44]

array_prepend()

  • array_pushを使用し、配列をプリペンディングする代わりに逆にする必要があった頻度。array_prepend関数は、アイテムを配列の先頭にプッシュします。
$ array = [ 'one' 、 'two' 、 'three' 、 'four' ] ;

$ array = array_prepend ($ array 、 'zero' );

// ['zero'、 'one'、 'two'、 'three'、 'four']
  • キー/値に対しても機能するのは素晴らしいことです。必要に応じて、値に使用するキーを指定できます。
$ array = [ 'price' => 100 ] ;

$ array = array_prepend ($ array 、 'Desk' 、 'name' );

// ['name' => 'Desk'、 'price' => 100]

array_sort_recursive()

  • 多くの場合、すべてを同時に並べ替える必要があるネストされた配列を取得します。はい、各配列をループして並べ替える簡単な関数を作成できますが、次の関数があるのはなぜですか。array_sort_recursive関数は、sort関数を使用して配列を再帰的にソートします。
$array = [
    ['Roman', 'Taylor', 'Li'],
    ['PHP', 'Ruby', 'JavaScript'],
];

$sorted = array_sort_recursive($array);

/*
    [
        ['Li', 'Roman', 'Taylor'],
        ['JavaScript', 'PHP', 'Ruby'],
    ]
*/

array_wrap()

  • 単一の文字列の結果を、要素が1つだけの配列に変換したい場合があります。コードを1行に減らすことができるのは常に良いことです。array_wrap関数は、指定された値を配列にラップします。指定された値がすでに配列である場合、変更されません。
$string = 'Success';

$array = array_wrap($string);

// ['Success']
If the given value is null, an empty array will be returned:

$nothing = null;

$array = array_wrap($nothing);

// []

public_path()

  • アプリケーションアイコン、svgイメージ、cssリソースなど、アプリ内で静的に使用されるパブリックファイルをパブリックフォルダーに配置する必要があります。 public_path関数は、完全修飾パスをパブリックディレクトリに戻します。public_path関数を使用して、パブリックディレクトリ内の特定のファイルへの完全修飾パスを生成することもできます。
$ path = public_path ();

$ path = public_path ('css / app.css' );

optional関数

  • どんな引数も指定でき、そのオブジェクトのプロパティへアクセスするか、メソッドを呼び出せます。 指定したオブジェクトがnullだった場合、エラーを発生させる代わりに、プロパティとメソッドはnullを返します。
  • 下記の例だとUserモデルにtestというプロパティがないのにエラーが発生しない。 Rubyでいう&.の処理と同じ
$user  = User::find(1);
optional($user)->test

実行結果はnullが返ってくる

dump関数

  • 指定した変数をダンプします。ddと違う点は処理が停止しないで変数をダンプできる
$user  = User::find(1);
dump($user);

コレクション

  • Illuminate\Support\Collectionクラスは配列データを操作するための、書きやすく使いやすいラッパーです。以下の例をご覧ください。配列から新しいコレクションインスタンスを作成するためにcollectヘルパを使用し、各要素に対しstrtoupperを実行し、それから空の要素を削除しています。
 $collection = collect(['taylor', 'abigail', null])->map(function ($name) {
   return strtoupper($name);
 })->reject(function ($name) {
   return empty($name);
 });
 dd($collection);

Laravelでnpm run devでエラーが発生する

はじめに

  • laravelでvuejsを利用する際にエラーが発生したので下記の手順で解決した

エラーの内容

  • npm run devを実行する下記のエラーメッセージが表示される
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT

下記の手順で実行する

rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
npm install
npm run dev