问:
Is there a way to put all external libraries into one folder?
For example, in the picture I have a 1.8 folder and a separate maven folder. Is there anyway that I can put the jsoup.jar in the maven folder into the 1.8 folder in Intellij? In other words, is there a way to have ALL my external libraries only in that 1.8 folder? Thanks!

答:
Do not manually manage the dependency in IDE when using a build tool like Maven or Gradle etc.

Regarding the two folders of libraries displayed in IntelliJ

<1.8> folder is from the JRE which is required to run any Java application.

Maven is generated based on the dependencies from the pom.xml.

Note: The folder displayed in IntelliJ is a logical representation not an actual folder in the filesystem.

Is there a way to put all external libraries into one folder?

Technically you can put all the dependency in a single folder and configure your IDE to load the libraries from that folder but in your case you don't need to  do that maven will take care of that.


来源: stackexchange

问:
angular-cli server - how to proxy API requests to another server?
With the angular-cli ng serve local dev server, it's serving all the static files from my project directory.

How can I proxy my AJAX calls to a different server?

答:
Cors-origin issue screenshot

Cors issue has been faced in my application. refer above screenshot. After adding proxy config issue has been resolved. my application url: localhost:4200 and requesting api url:"http://www.datasciencetoolkit.org/maps/api/geocode/json?sensor=false&address="

Api side no-cors permission allowed. And also I'm not able to change cors-issue in server side and I had to change only in angular(client side).

Steps to resolve:

create proxy.conf.json file inside src folder.

```<code>   {
      "/maps/*": {
        "target": "http://www.datasciencetoolkit.org",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true
      }
    }
</code>```

In Api request

```<code>this.http
      .get<GeoCode>('maps/api/geocode/json?sensor=false&address=' + cityName)
      .pipe(
        tap(cityResponse => this.responseCache.set(cityName, cityResponse))
      );
</code>```

Note: We have skip hostname name url in Api request, it will auto add while giving request. whenever changing proxy.conf.js we have to restart ng-serve, then only changes will update.

Config proxy in angular.json

```<code>"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TestProject:build",
            "proxyConfig": "src/proxy.conf.json"
          },
          "configurations": {
            "production": {
              "browserTarget": "TestProject:build:production"
            }
          }
        },
</code>```

After finishing these step restart ng-serve
Proxy working correctly as expect refer here

```<code>> WARNING in
> D:\angular\Divya_Actian_Assignment\src\environments\environment.prod.ts
> is part of the TypeScript compilation but it's unused. Add only entry
> points to the 'files' or 'include' properties in your tsconfig.
> ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** : Compiled
> successfully. [HPM] GET
> /maps/api/geocode/json?sensor=false&address=chennai ->
> http://www.datasciencetoolkit.org
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Cors-origin issue screenshot

Cors issue has been faced in my application. refer above screenshot. After adding proxy config issue has been resolved. my application url: localhost:4200 and requesting api url:"http://www.datasciencetoolkit.org/maps/api/geocode/json?sensor=false&address="

Api side no-cors permission allowed. And also I'm not able to change cors-issue in server side and I had to change only in angular(client side).

Steps to resolve:

create proxy.conf.json file inside src folder.

   {
      "/maps/*": {
        "target": "http://www.datasciencetoolkit.org",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true
      }
    }

In Api request

this.http
      .get<GeoCode>('maps/api/geocode/json?sensor=false&address=' + cityName)
      .pipe(
        tap(cityResponse => this.responseCache.set(cityName, cityResponse))
      );

Note: We have skip hostname name url in Api request, it will auto add while giving request. whenever changing proxy.conf.js we have to restart ng-serve, then only changes will update.

Config proxy in angular.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TestProject:build",
            "proxyConfig": "src/proxy.conf.json"
          },
          "configurations": {
            "production": {
              "browserTarget": "TestProject:build:production"
            }
          }
        },

After finishing these step restart ng-serve
Proxy working correctly as expect refer here

> WARNING in
> D:\angular\Divya_Actian_Assignment\src\environments\environment.prod.ts
> is part of the TypeScript compilation but it's unused. Add only entry
> points to the 'files' or 'include' properties in your tsconfig.
> ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** : Compiled
> successfully. [HPM] GET
> /maps/api/geocode/json?sensor=false&address=chennai ->
> http://www.datasciencetoolkit.org

ContentLicense: CC BY-SA 4.0


问:
How can I use multiple custom cursors for different purposes in CSS?
So, I have multiple cursors (e.g. default and pointer) and want to use them. I know how to implement them using this method:

```<code>cursor: url('default.cur'), default;
</code>```

How can I use my default.cur for only default and my pointer.cur for only pointer? There's most likely a way to do this, but I'm an idiot sometimes.

答:
Simple fix. Use the same method, but with different URLs to different cursors in different tags like so:

```<code>body {
    cursor: url('default.cur'), default;
}

a {
    cursor: url('pointer.cur'), pointer;
}
</code>```

The default cursor will work on the body, and the pointer will work over all the "a" tags.

Body:
So, I have multiple cursors (e.g. default and pointer) and want to use them. I know how to implement them using this method:

cursor: url('default.cur'), default;

How can I use my default.cur for only default and my pointer.cur for only pointer? There's most likely a way to do this, but I'm an idiot sometimes.

Body:
Simple fix. Use the same method, but with different URLs to different cursors in different tags like so:

body {
    cursor: url('default.cur'), default;
}

a {
    cursor: url('pointer.cur'), pointer;
}

The default cursor will work on the body, and the pointer will work over all the "a" tags.


问:
Why is a local variable declaration for "this" in decompiled constructor byte code?
The ASM 4.0 user guide describes the byte code for a default public constructor to be

```<code>ALOAD 0
INVOKESPECIAL java/lang/Object.<init> ()V
RETURN
</code>```

I wanted to replicate this, created my own class with a default public constructor, and decompiled it. The generated byte code for the constructor looks like the following though:

```<code>L0
 LINENUMBER 3 L0
 ALOAD 0
 INVOKESPECIAL java/lang/Object.<init> ()V
 RETURN
L1
 LOCALVARIABLE this Lcom/example/EmptyFixture; L0 L1 0
 MAXSTACK = 1
 MAXLOCALS = 1
</code>```

My understanding is that everything nested under label L0, which matched the user guide, is executed. There is unreachable code after the RETURN, nested under label L1, which is simply a local variable declaration of this with the type of the class.

What is the reason to include this variable declaration? What is it used for, especially since it looks like it is unreachable?

答:
The information after L1 is all descriptive; it is not code and cannot be executed, so its 'reachability' is meaningless. In other words, even if control flow somehow did reach L1, those lines would not be executed, and if they were put within code that is executed, in this case between L0 and L1, they still would not be executed.

Like the LINENUMBER directive, those lines specify debugging information that is in the classfile. Debugging information is included in the classfile to support debugging, and it is used by the debugger if you debug.

Body:
The ASM 4.0 user guide describes the byte code for a default public constructor to be

ALOAD 0
INVOKESPECIAL java/lang/Object.<init> ()V
RETURN

I wanted to replicate this, created my own class with a default public constructor, and decompiled it. The generated byte code for the constructor looks like the following though:

L0
 LINENUMBER 3 L0
 ALOAD 0
 INVOKESPECIAL java/lang/Object.<init> ()V
 RETURN
L1
 LOCALVARIABLE this Lcom/example/EmptyFixture; L0 L1 0
 MAXSTACK = 1
 MAXLOCALS = 1

My understanding is that everything nested under label L0, which matched the user guide, is executed. There is unreachable code after the RETURN, nested under label L1, which is simply a local variable declaration of this with the type of the class.

What is the reason to include this variable declaration? What is it used for, especially since it looks like it is unreachable?


问:
Cannot Save Data
I was to Try to save any Invoice Card on Database but it not saved

What's Wrong With my code, I was Try to search to solve this but it not solved

Always Blank to database,

The View Form & Post

The Controller

Use Boostrap 3 from AdminLte Template

```<code><?php

namespace App\Http\Controllers;

use App\Kwitansi;
use Illuminate\Http\Request;
use Haruncpi\LaravelIdGenerator\IdGenerator;

class KwitansiController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $kwitansi = Kwitansi::get();
        return view('user.formkwitansi', ['kwitansi' => $kwitansi]);
    }

    public function store(Request $request)
    {
        $kwitansi = new Kwitansi;

        $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
        $kwitansi->received = $request->received;
        $kwitansi->registration = $request->registration;
        $kwitansi->course = $request->course;
        $kwitansi->trasnportation = $request->trasnportation;
        $kwitansi->payment = $request->payment;
        $kwitansi->kota = $request->kota;
        $kwitansi->register_at = $request->register_at;

      $request->validate([
        'sum_rp' => 'required',
        'sum_text' => 'required',
      ]);

      $sum_rp = $request->registration + $request->course + $request->transportation;

      function penyebut($nilai) {
        $nilai = abs($nilai);
        $huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
        $temp = "";
        if ($nilai < 12) {
            $temp = " ". $huruf[$nilai];
        } else if ($nilai <20) {
            $temp = penyebut($nilai - 10). " belas";
        } else if ($nilai < 100) {
            $temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
        } else if ($nilai < 200) {
            $temp = " seratus" . penyebut($nilai - 100);
        } else if ($nilai < 1000) {
            $temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
        } else if ($nilai < 2000) {
            $temp = " seribu" . penyebut($nilai - 1000);
        } else if ($nilai < 1000000) {
            $temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
        } else if ($nilai < 1000000000) {
            $temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
        } else if ($nilai < 1000000000000) {
            $temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
        } else if ($nilai < 1000000000000000) {
            $temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
        }
        return $temp;
    }
    function terbilang($nilai) {
        if($nilai<0) {
            $hasil = "minus ". trim(penyebut($nilai));
        } else {
            $hasil = trim(penyebut($nilai));
        }
        return $hasil;
    }
    $sum_text = $request->sum_rp;

    $kwitansi->sum_rp = $sum_rp;
    $kwitansi->sum_text = terbilang($sum_text);

    $kwitansi->save();

    return redirect('kwitansi')->withSuccess('Added Succesfully');
    }
}
</code>```

The Blade View

Use Form and View in One Page

```<code>@extends('layouts.admin')

@section('title', 'Kwitansi')

@section('css')

<!-- DataTables -->
<link rel="stylesheet" href="{{ asset('adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.css') }}">
@section('js')
<!-- DataTables -->
<script src="{{ asset('adminlte/plugins/datatables/jquery.dataTables.js') }}"></script>
<script src="{{ asset('adminlte/plugins/datatables-bs4/js/dataTables.bootstrap4.js') }}"></script>
<script>
  $(function () {
    $("#example1").DataTable();
    $('#example2').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false,
    });
  });
</script>

@endsection

@section('content')

    <div class="row">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">DataTable User</h3>
              @if ($message = Session::get('success'))
              <div class="alert alert-success alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                  <h5><i class="icon fas fa-check"></i> Alert!</h5>
                  <p>{{ $message }}</p>
              </div>
              @endif
            </div>
            <!-- /.card-header -->
            <div class="card-body">
                <form action="{{ route('kwitansi.store') }}" method="POST" role="form" class="form-horizontal">
                    @csrf
                    <div class="form-group row">
                        <label for="name" class="control-label col-md-2">Terima Dari</label>
                        <div class="col-md-6">
                            <input type="text" name="received" class="form-control" placeholder="Received Form" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="registration" class="control-label col-md-2">Biaya Registrasi</label>
                        <div class="col-md-6">
                            <input type="text" name="registration" class="form-control" placeholder="Registration Fee" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="course" class="control-label col-md-2">Biaya Kursus</label>
                        <div class="col-md-6">
                            <input type="text" name="course" class="form-control" placeholder="Course Fee" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="trasnportation" class="control-label col-md-2">Biaya Transportasi</label>
                        <div class="col-md-6">
                            <input type="text" name="trasnportation" class="form-control" placeholder="Transportation Fee" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="payment" class="control-label col-md-2">Pembayaran Untuk</label>
                        <div class="col-md-6">
                            <input type="text" name="payment" class="form-control" placeholder="Payment Of" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="register_at" class="control-label col-md-2">Tanggal Registrasi</label>
                        <div class="col-md-6">
                            <input type="text" name="kota"class="form-control" value="Bandung" disabled hidden>
                            <input type="date" name="register_at"class="form-control">
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary" id="btnsubmit">Tambah Data</button>
                    <button type="reset" class="btn btn-warning" id="btncancel">Cancel</button>
                </form>
              <table id="example2" class="table table-bordered table-hover">
                <thead>
                <tr>
                  <th>No.</th>
                  <th>received</th>
                  <th>registration Fee</th>
                  <th>Course Fee</th>
                  <th>Transportation Fee</th>
                  <th>Grand Total</th>
                  <th>Payment of</th>
                  <th>Action</th>
                </tr>
                </thead>
                <tbody>
                @foreach($kwitansi as $k)
                <tr>
                  <td>{{ $k->id }}</td>
                  <td>{{ $k->received }}</td>
                  <td>{{ $k->registration }}</td>
                  <td>{{ $k->course }}</td>
                  <td>{{ $k->transportation }}</td>
                  <td>{{ $k->sum_rp }}</td>
                  <td>{{ $k->payment }}</td>
                  <td>
                    {{-- <a href="{{ route('user.edit', $u->id)}}" class="btn btn-sm btn-outline-warning"><i class="fas fa-edit"></i></a>
                    <a href="{{ route('user.show', $u->id)}}" class="btn btn-sm btn-outline-info"><i class="fas fa-file"></i></a>
                    <form action="{{ route('user.destroy', $u->id)}}" method="post">
                          @csrf
                          @method('DELETE')
                          <button class="btn btn-sm btn-outline-danger" type="submit"><i class="fas fa-trash-alt"></i></button>
                        </form> --}}
                  </td>
                </tr>
                @endforeach
                </tbody>
                <tfoot>
                <tr>
                    <th>No.</th>
                    <th>received</th>
                    <th>registration Fee</th>
                    <th>Course Fee</th>
                    <th>Transportation Fee</th>
                    <th>Grand Total</th>
                    <th>Payment of</th>
                    <th>Action</th>
                </tr>
                </tfoot>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->

@endsection
</code>```

I used form and view in one page are this is the problem

This is my model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Kwitansi extends Model
{
    // $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
    protected $table = 'kwitansis';
    protected $fillable = [
        'received',
        'registration',
        'course',
        'trasnportation',
        'sum_rp',
        'payment',
        'register_at',
    ];
    protected $primarykey = 'id';

    public $increment = false;

    protected $keyType = 'string';
}

```

答:
Remove these lines from your model:</p>

```<code>protected $primarykey = 'id';

public $increment = false;

protected $keyType = 'string';
</code>```

Title: Cannot Save Data

Body:
I was to Try to save any Invoice Card on Database but it not saved

What's Wrong With my code, I was Try to search to solve this but it not solved

Always Blank to database,

The View Form & Post

The Controller

Use Boostrap 3 from AdminLte Template

<?php

namespace App\Http\Controllers;

use App\Kwitansi;
use Illuminate\Http\Request;
use Haruncpi\LaravelIdGenerator\IdGenerator;

class KwitansiController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $kwitansi = Kwitansi::get();
        return view('user.formkwitansi', ['kwitansi' => $kwitansi]);
    }

    public function store(Request $request)
    {
        $kwitansi = new Kwitansi;

        $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
        $kwitansi->received = $request->received;
        $kwitansi->registration = $request->registration;
        $kwitansi->course = $request->course;
        $kwitansi->trasnportation = $request->trasnportation;
        $kwitansi->payment = $request->payment;
        $kwitansi->kota = $request->kota;
        $kwitansi->register_at = $request->register_at;

      $request->validate([
        'sum_rp' => 'required',
        'sum_text' => 'required',
      ]);

      $sum_rp = $request->registration + $request->course + $request->transportation;

      function penyebut($nilai) {
        $nilai = abs($nilai);
        $huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
        $temp = "";
        if ($nilai < 12) {
            $temp = " ". $huruf[$nilai];
        } else if ($nilai <20) {
            $temp = penyebut($nilai - 10). " belas";
        } else if ($nilai < 100) {
            $temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
        } else if ($nilai < 200) {
            $temp = " seratus" . penyebut($nilai - 100);
        } else if ($nilai < 1000) {
            $temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
        } else if ($nilai < 2000) {
            $temp = " seribu" . penyebut($nilai - 1000);
        } else if ($nilai < 1000000) {
            $temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
        } else if ($nilai < 1000000000) {
            $temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
        } else if ($nilai < 1000000000000) {
            $temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
        } else if ($nilai < 1000000000000000) {
            $temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
        }
        return $temp;
    }
    function terbilang($nilai) {
        if($nilai<0) {
            $hasil = "minus ". trim(penyebut($nilai));
        } else {
            $hasil = trim(penyebut($nilai));
        }
        return $hasil;
    }
    $sum_text = $request->sum_rp;

    $kwitansi->sum_rp = $sum_rp;
    $kwitansi->sum_text = terbilang($sum_text);

    $kwitansi->save();

    return redirect('kwitansi')->withSuccess('Added Succesfully');
    }
}

The Blade View

Use Form and View in One Page

@extends('layouts.admin')

@section('title', 'Kwitansi')

@section('css')

<link rel="stylesheet" href="{{ asset('adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.css') }}">
@section('js')

@endsection

@section('content')

DataTable User

              @if ($message = Session::get('success'))

                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

 Alert!

{{ $message }}

              @endif

                <form action="{{ route('kwitansi.store') }}" method="POST" role="form" class="form-horizontal">
                    @csrf

                        Terima Dari

                            <input type="text" name="received" class="form-control" placeholder="Received Form" />

                        Biaya Registrasi

                            <input type="text" name="registration" class="form-control" placeholder="Registration Fee" />

                        Biaya Kursus

                            <input type="text" name="course" class="form-control" placeholder="Course Fee" />

                        Biaya Transportasi

                            <input type="text" name="trasnportation" class="form-control" placeholder="Transportation Fee" />

                        Pembayaran Untuk

                            <input type="text" name="payment" class="form-control" placeholder="Payment Of" />

                        Tanggal Registrasi

                            <input type="text" name="kota"class="form-control" value="Bandung" disabled hidden>
                            <input type="date" name="register_at"class="form-control">

                    <button type="submit" class="btn btn-primary" id="btnsubmit">Tambah Data</button>
                    <button type="reset" class="btn btn-warning" id="btncancel">Cancel</button>
                </form>

                  No.
                  received
                  registration Fee
                  Course Fee
                  Transportation Fee
                  Grand Total
                  Payment of
                  Action

                @foreach($kwitansi as $k)

                  {{ $k->id }}
                  {{ $k->received }}
                  {{ $k->registration }}
                  {{ $k->course }}
                  {{ $k->transportation }}
                  {{ $k->sum_rp }}
                  {{ $k->payment }}

                    {{-- id)}}" class="btn btn-sm btn-outline-warning">
                    id)}}" class="btn btn-sm btn-outline-info">
                    <form action="{{ route('user.destroy', $u->id)}}" method="post">
                          @csrf
                          @method('DELETE')
                          <button class="btn btn-sm btn-outline-danger" type="submit"></button>
                        </form> --}}

                @endforeach

                    No.
                    received
                    registration Fee
                    Course Fee
                    Transportation Fee
                    Grand Total
                    Payment of
                    Action

@endsection

I used form and view in one page are this is the problem

This is my model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Kwitansi extends Model
{
    // $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
    protected $table = 'kwitansis';
    protected $fillable = [
        'received',
        'registration',
        'course',
        'trasnportation',
        'sum_rp',
        'payment',
        'register_at',
    ];
    protected $primarykey = 'id';

    public $increment = false;

    protected $keyType = 'string';
}

Body:
Remove these lines from your model:

protected $primarykey = 'id';

public $increment = false;

protected $keyType = 'string';


问:
Trying to create eks cluster using eksctl with ssh-access
While creating eks cluster using EKSCTL it is throwing error like error decoding SSH public key

Permission of pem file is 400

Command i am executing

eksctl create cluster --name=thirdekscluster --ssh-access --ssh-public-key=mysshkey.pem --nodegroup-name=standard-workers --node-type=t3.medium --nodes=3 --nodes-min=1 --nodes-max=4 --node-ami=auto

Error:

```<code>[ℹ]  using region ap-south-1
[ℹ]  setting availability zones to [ap-south-1a ap-south-1c ap-south-1b]
[ℹ]  subnets for ap-south-1a - public:xxxxx/19 private:xxxx/19
[ℹ]  subnets for ap-south-1c - public:xxxxx/19 private:xxxx/19
[ℹ]  subnets for ap-south-1b - public:xxxxx/19 private:xxxx/19
[ℹ]  nodegroup "standard-workers" will use "ami-01b6a163133c31994" [AmazonLinux2/1.12]
[✖]  computing fingerprint for key "mysshkey.pem":
error decoding SSH public key:

"-----BEGIN RSA PRIVATE KEY
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-----END RSA PRIVATE KEY-----"

err: illegal base64 data at input byte 0
</code>```

答: I used Bitvise Client Key Management to export in OpenSSH format. After that, eksctl worked!</p>

Body:
While creating eks cluster using EKSCTL it is throwing error like error decoding SSH public key

Permission of pem file is 400

Command i am executing

eksctl create cluster --name=thirdekscluster --ssh-access --ssh-public-key=mysshkey.pem --nodegroup-name=standard-workers --node-type=t3.medium --nodes=3 --nodes-min=1 --nodes-max=4 --node-ami=auto

Error:

[ℹ]  using region ap-south-1
[ℹ]  setting availability zones to [ap-south-1a ap-south-1c ap-south-1b]
[ℹ]  subnets for ap-south-1a - public:xxxxx/19 private:xxxx/19
[ℹ]  subnets for ap-south-1c - public:xxxxx/19 private:xxxx/19
[ℹ]  subnets for ap-south-1b - public:xxxxx/19 private:xxxx/19
[ℹ]  nodegroup "standard-workers" will use "ami-01b6a163133c31994" [AmazonLinux2/1.12]
[✖]  computing fingerprint for key "mysshkey.pem":
error decoding SSH public key:

"-----BEGIN RSA PRIVATE KEY
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-----END RSA PRIVATE KEY-----"

err: illegal base64 data at input byte 0


问:
iOS Keyboard - Capitalise 'done' button
I am using 'UIKeyboardTypeDefault' keyboard type for my UITextfields.

The done button for the keyboard appears in lowercase as 'done'.
Is there anyway to make this a capitalised as 'Done' ?

答:
We cannot set a custom text for the return key, we can only select from the available options (refer attached screenshot).
In order to set a custom text, for e.g capitalised 'done' button, you will have to create a custom keyboard. attached screenshot</p>

Title: iOS Keyboard - Capitalise 'done' button


问:
Search arrays then echo with conditionals?
I'm trying to do somthing like this:

```<code>  $random = array("apple","celery","banana");

  $define_fruits = array("apple","banana","pears","mango");
  $define_vegetables = array("celery","lettuce","carrots","cucumber");

  if($random contains only fruits){
    echo fruits;
  }elseif($random contains only vegetables){
    echo vegetables;
  }elseif($random contains both fruits and vegetables){
    echo both;
  }
</code>```

SOLVED:

```<code>$in_fruits = sizeof(array_intersect($random,$define_fruits));
$in_vegetables = sizeof(array_intersect($random,$define_vegetables));

      if($in_fruits >= 1 && $in_vegetables >= 1){
          echo "in_fruits and in_vegetables ";
        }elseif($in_fruits === 0 && $in_vegetables >= 1){
          echo "in_fruits ";
        }elseif($in_fruits >= 1 && $in_vegetables === 0){
          echo "in_fruits";
        }
</code>```

Progression:

```<code>$in_fruits = count(array_intersect($random,$define_fruits));
$in_vegetables = count(array_intersect($random,$define_vegetables));

if( $in_fruits ){
  if( $in_vegetables )
    echo "both";
  else
    echo "fruits";
}elseif( $in_vegetables ){
  echo "veggies";
}else{
  echo "neither ";
</code>```

答:
The simplest solution would be:</p>

```<code>if ( in_array($define_fruits, $random) && ! in_array($define_vegetables, $random) ) {
   // Only fruits
}elseif ( ! in_array($define_fruits, $random) && in_array($define_vegetables, $random) ) {
   // Only Vegetables
}elseif ( in_array($define_fruits, $random) && in_array($define_vegetables, $random) ) {
   // Both fruits and vegetables
}
</code>```

Body:
I'm trying to do somthing like this:

  $random = array("apple","celery","banana");

  $define_fruits = array("apple","banana","pears","mango");
  $define_vegetables = array("celery","lettuce","carrots","cucumber");

  if($random contains only fruits){
    echo fruits;
  }elseif($random contains only vegetables){
    echo vegetables;
  }elseif($random contains both fruits and vegetables){
    echo both;
  }

SOLVED:

$in_fruits = sizeof(array_intersect($random,$define_fruits));
$in_vegetables = sizeof(array_intersect($random,$define_vegetables));

      if($in_fruits >= 1 && $in_vegetables >= 1){
          echo "in_fruits and in_vegetables ";
        }elseif($in_fruits === 0 && $in_vegetables >= 1){
          echo "in_fruits ";
        }elseif($in_fruits >= 1 && $in_vegetables === 0){
          echo "in_fruits";
        }

Progression:

$in_fruits = count(array_intersect($random,$define_fruits));
$in_vegetables = count(array_intersect($random,$define_vegetables));

if( $in_fruits ){
  if( $in_vegetables )
    echo "both";
  else
    echo "fruits";
}elseif( $in_vegetables ){
  echo "veggies";
}else{
  echo "neither ";

Body:
The simplest solution would be:

if ( in_array($define_fruits, $random) && ! in_array($define_vegetables, $random) ) {
   // Only fruits
}elseif ( ! in_array($define_fruits, $random) && in_array($define_vegetables, $random) ) {
   // Only Vegetables
}elseif ( in_array($define_fruits, $random) && in_array($define_vegetables, $random) ) {
   // Both fruits and vegetables
}


问:
Angular 8 FormGroup async validation from API call

I need to validate Unique product title, except the current product
  id.

Please note that I need to validate FormGroup using async validation - API service call.

The function contains hardcoded value 2, please ignore it.

product-component.ts

```<code>ngOnInit() {
    this.productForm = this.fb.group({
      categoryId: ['', [Validators.required]],
      title: ['', [Validators.required]],
      description: [''],
      oldPrice: ['', [Validators.required, Validators.maxLength(10), Validators.pattern('^\\d+$')]],
      newPrice: ['', [Validators.required, Validators.maxLength(10), Validators.pattern('^\\d+$')]]
},
// {validators: ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)}
{asyncValidators: [ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)]}
);
</code>```

Validate class:

```<code>export class ValidateUniqueProductTitle {

public static checkProductTitle(productService: ProductService, productId) {
    return (group: AbstractControl): Observable<ValidationErrors | null> => {
        return productService.checkExisting(group.controls['title'].value, productId)
                            .pipe(
                                debounceTime(200),
                                distinctUntilChanged(),
                                take(1),
                                map((data: boolean) => {
                                    console.log('checkExisting api called', data);
                                    return data ?  {title_exists: true} : null;
                                })
                            );
        }
}
</code>```

Issue:

Validate class function is never called when I use this line:

{asyncValidators:[ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)]}

When I use this line, function gets called but API is not fired:

{validators: ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)}

答:
It was a silly mistake. Should have used FormGroup instead of Abstract Control type in return.

Validate class:

```<code>export class ValidateUniqueProductTitle {

  public static checkProductTitle(productService: ProductService, productId) {
       return (group: AbstractControl): Observable<ValidationErrors | null> => {
            return productService.checkExisting(group.controls['title'].value, productId)
                        .pipe(
                            debounceTime(200),
                            distinctUntilChanged(),
                            take(1),
                            map((data: boolean) => {
                                console.log('checkExisting api called', data);
                                return data ?  {title_exists: true} : null;
                            })
                        );
    }
}
</code>```

Also, it's important to note that:

Async validators are fired only when all sync validators return null.

I was expecting all validation errors (sync and async) to appear together, but that doesn't happen.

Body:
I need to validate Unique product title, except the current product
  id.

Please note that I need to validate FormGroup using async validation - API service call.

The function contains hardcoded value 2, please ignore it.

product-component.ts

ngOnInit() {
    this.productForm = this.fb.group({
      categoryId: ['', [Validators.required]],
      title: ['', [Validators.required]],
      description: [''],
      oldPrice: ['', [Validators.required, Validators.maxLength(10), Validators.pattern('^\\d+$')]],
      newPrice: ['', [Validators.required, Validators.maxLength(10), Validators.pattern('^\\d+$')]]
},
// {validators: ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)}
{asyncValidators: [ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)]}
);

Validate class:

export class ValidateUniqueProductTitle {

public static checkProductTitle(productService: ProductService, productId) {
    return (group: AbstractControl): Observable<ValidationErrors | null> => {
        return productService.checkExisting(group.controls['title'].value, productId)
                            .pipe(
                                debounceTime(200),
                                distinctUntilChanged(),
                                take(1),
                                map((data: boolean) => {
                                    console.log('checkExisting api called', data);
                                    return data ?  {title_exists: true} : null;
                                })
                            );
        }
}

Issue:

Validate class function is never called when I use this line:

{asyncValidators:[ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)]}

When I use this line, function gets called but API is not fired:

{validators: ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)}

Body:
It was a silly mistake. Should have used FormGroup instead of Abstract Control type in return.

Validate class:

export class ValidateUniqueProductTitle {

  public static checkProductTitle(productService: ProductService, productId) {
       return (group: AbstractControl): Observable<ValidationErrors | null> => {
            return productService.checkExisting(group.controls['title'].value, productId)
                        .pipe(
                            debounceTime(200),
                            distinctUntilChanged(),
                            take(1),
                            map((data: boolean) => {
                                console.log('checkExisting api called', data);
                                return data ?  {title_exists: true} : null;
                            })
                        );
    }
}

Also, it's important to note that:

Async validators are fired only when all sync validators return null.

I was expecting all validation errors (sync and async) to appear together, but that doesn't happen.


问:
Count previous 24 months rows based on condition from current row
How to count the previous 24 months from a current row based on principalreliefflag(It should be based on each row (each month with previous  24 months). So count principal flag(Y) from current row to previous 24 months.)?

Data I have:

Data I need:

Code:

```<code>       -------------------------------------------------------------------------
----Identify customers who are on principal relief more than one month
-------------------------------------------------------------------------

IF OBJECT_ID('tempdb..##PRappliedmorethan_once') IS NOT NULL
    DROP TABLE ##PRappliedmorethan_once
select *,
case when  PrincipalReliefFlag='Y'  then 1 else 0
                                      end  PR_applied_months

 into ##PRappliedmorethan_once
 from ##TL_details_dates2

 IF OBJECT_ID('tempdb..##PRappliedmorethan_once1') IS NOT NULL
    DROP TABLE ##PRappliedmorethan_once1
select *,
--Identify customers who have applied for principal relief within the past 12 months

sum(PR_applied_months) over    (partition by productitemcode, productcode
                                      order by dim_snapshotdate_key
                                      rows between  23 preceding and current row
                                     )
                                      abcd

 into ##PRappliedmorethan_once1
 from ##PRappliedmorethan_once
</code>```

It works but is there any better way?

答:
Try using the DATEDIFF() function to check the last 24 months e.g. :

```<code>SELECT COUNT(*) FROM YOUR_TABLE
WHERE DATEDIFF(month, current_row_date, date_to_be_compared) <= 24
</code>```

Body:
How to count the previous 24 months from a current row based on principalreliefflag(It should be based on each row (each month with previous  24 months). So count principal flag(Y) from current row to previous 24 months.)?

Data I have:

Data I need:

Code:

       -------------------------------------------------------------------------
----Identify customers who are on principal relief more than one month
-------------------------------------------------------------------------

IF OBJECT_ID('tempdb..##PRappliedmorethan_once') IS NOT NULL
    DROP TABLE ##PRappliedmorethan_once
select *,
case when  PrincipalReliefFlag='Y'  then 1 else 0
                                      end  PR_applied_months

 into ##PRappliedmorethan_once
 from ##TL_details_dates2

 IF OBJECT_ID('tempdb..##PRappliedmorethan_once1') IS NOT NULL
    DROP TABLE ##PRappliedmorethan_once1
select *,
--Identify customers who have applied for principal relief within the past 12 months

sum(PR_applied_months) over    (partition by productitemcode, productcode
                                      order by dim_snapshotdate_key
                                      rows between  23 preceding and current row
                                     )
                                      abcd

 into ##PRappliedmorethan_once1
 from ##PRappliedmorethan_once

It works but is there any better way?

Body:
Try using the DATEDIFF() function to check the last 24 months e.g. :

SELECT COUNT(*) FROM YOUR_TABLE
WHERE DATEDIFF(month, current_row_date, date_to_be_compared) <= 24


问:
Azure build Pipeline gets failed. Unable to find a dependent package
I am building the project through the Azure pipeline. The project is building locally but failing in the pipeline.
.

Error:- The type or namespace name 'CommonModules' could not be found (are you missing a using directive or an assembly reference?)

答:
Azure build Pipeline gets failed. Unable to find a dependent package

According to the error message:

```<code>'The type or namespace name 'CommonModules' could not be found'
</code>```

It seems that you just build the reference library instead of the solution file.

To resolve this issue, try to build the solution file .sln with Visual Studio build task:

Note: If it not help you, please share more info about this issue, like the project structure and the specific configuration of your visual studio build task.

Hope this helps.

Body:
Azure build Pipeline gets failed. Unable to find a dependent package

According to the error message:

'The type or namespace name 'CommonModules' could not be found'

It seems that you just build the reference library instead of the solution file.

To resolve this issue, try to build the solution file .sln with Visual Studio build task:

Note: If it not help you, please share more info about this issue, like the project structure and the specific configuration of your visual studio build task.

Hope this helps.


问:
Python Loop through excel file and and read each one by one using pandas read_excel function
I am trying to loop through an array that has the excel file name and then use that to read that excel using pandas read_excel. However i am unable to pass the path to read_excel(). Below is how my code looks.

```<code>import pandas as pd
from pathlib import Path

Moviedb = []

file_Name = ["/SG_JW_09-02-2020_1900_2009", "/SG_JW_09-02-2020_2010_2015", "/SG_JW_09-02-2020_2016_2017", "/SG_JW_09-02-2020_2018_2020", "/SG_JW_09-02-2020_2018_2020_1", "/SG_JW_09-02-2020_2018_2020_2"]

filecnt = 0
cnt = 0
for filename in file_Name:
    p = Path("D:/Python scripts/SG Title/SG/JW/03_02_2020" + filename)

    df = pd.read_excel(p)
    filecnt =  filecnt + 1
</code>```

I get the below error when i run this.

Error Image

Can someone help me with this?

答: Path("D:/Python scripts/SG Title/SG/JW/03_02_2020" + filename + ".xlsx")</p>

Body:
I am trying to loop through an array that has the excel file name and then use that to read that excel using pandas read_excel. However i am unable to pass the path to read_excel(). Below is how my code looks.

import pandas as pd
from pathlib import Path

Moviedb = []

file_Name = ["/SG_JW_09-02-2020_1900_2009", "/SG_JW_09-02-2020_2010_2015", "/SG_JW_09-02-2020_2016_2017", "/SG_JW_09-02-2020_2018_2020", "/SG_JW_09-02-2020_2018_2020_1", "/SG_JW_09-02-2020_2018_2020_2"]

filecnt = 0
cnt = 0
for filename in file_Name:
    p = Path("D:/Python scripts/SG Title/SG/JW/03_02_2020" + filename)

    df = pd.read_excel(p)
    filecnt =  filecnt + 1

I get the below error when i run this.

Error Image

Can someone help me with this?


问:
How To Delete All Records From Database All Tables
Can you guys help me solve my issue? How To Delete All Records From Database All Tables in a single click using Laravel ajax.
I have to delete all records from all tables, please help to solve my issue.

Thanks in advance

(https://i.stack.imgur.com/gu6Qg.png)

答:
You can make use of the truncate method, this works for Laravel 4 and 5:

```<code>MyModel::truncate();
</code>```

It will delete your all data for your single table.

```<code>php artisan migrate:refresh
</code>```

It will delete your all table's all data .it will refresh your all table's data

Body:
You can make use of the truncate method, this works for Laravel 4 and 5:

MyModel::truncate();

It will delete your all data for your single table.

php artisan migrate:refresh

It will delete your all table's all data .it will refresh your all table's data


问:
I am receiving could not find "htmlextra" reporter when i run it on my local (MAC OSX) neman html report generation
I am receiving below message, when i run newman run command with parameter -r htmlextra. Where i have already installed htmlextra using -g (globally). But when i create a newman .js file i am able to execute. Please advice what might have went wrong.

```<code>newman: could not find "htmlextra" reporter
ensure that the reporter is installed in the same directory as newman
please install reporter using npm
</code>```

Thanks in advance.

答:
If you have installed htmlextra reporter by npm install -g htmlextra then to generate report ideally you should use

newman run yourpostmancollection.json -r htmlextra --reporter-htmlextra-export pathToHtmlReportFile

after running this the report file should be generated on the given path

Body:
I am receiving below message, when i run newman run command with parameter -r htmlextra. Where i have already installed htmlextra using -g (globally). But when i create a newman .js file i am able to execute. Please advice what might have went wrong.

newman: could not find "htmlextra" reporter
ensure that the reporter is installed in the same directory as newman
please install reporter using npm

Thanks in advance.


问:
React native failed to launch emulator
While trying to test the android app am creating with React native, I run into this error

info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
```

I have the emulator(the AMD version) installed in the android studio.

How can I solve this problem

答: You can run the command adb devices to check if there is any device attached. It should list atleast one device for it to work

Title: React native failed to launch emulator

Body:
While trying to test the android app am creating with React native, I run into this error

info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.

I have the emulator(the AMD version) installed in the android studio.

How can I solve this problem


问:
C++ including a ".h" file, function duplication confusion
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).

Basically, my program was structured as follows:

The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).

Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc).  CalledByCurrent.h contains a class definition.

There was a non-class function defined in CalledByCurrent.cc called thisFunction().  thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function).  In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc.  However, when I did this, I got an error saying that the function was duplicated.  Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?

Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc.  However, when I did this, I found that Current.cc did not know what function I was talking about.  What the heck?  I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem.  Could you help me understand this behavior?  Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?

p.s - I apologize for how confusing this post is.  Please let me know if there's anything I can clear up.

答:
Here are some ideas:

You didn't put a header include guard in your header file.  If it's being included twice, you might get this sort of error.

The function's prototype (at the top) doesn't match its signature 100%.

You put the body of the function in the header file.

You have two functions of the same signature in two different source files, but they aren't marked static.

If you are using gcc (you didn't say what compiler you're using), you can use the -E switch to view the preprocessor output.  This includes expanding all #defines and including all #includes.

Each time something is expanded, it tells you what file and line it was in.  Using this you can see where thisFunction() is defined.


问:
Change from button to plain text
I've got a button. And this button when clicked, will produce popup. The problem is I don't want it to be a button, instead, I just want it to be a plain text. All the function will be the same.

Is there any way to get around this?

答:
The "See size chart" element is not a button, it is actually plain text with a button-like style. You need to change it's CSS rules

If you want it to be simple black text on white background, change this:

```<code>.yith-wcpsc-product-size-chart-button{
    background: #0f0f0f;
    border: none;
    border-radius: 0px;
    color: #ffffff;
    display: inline-block;
    padding: 3px 10px 3px 10px;
    text-decoration: none;
    margin: 5px 3px;
    cursor: pointer;
    box-shadow: 0px 2px 7px -2px #dddddd;
}
</code>```

to

```<code>.yith-wcpsc-product-size-chart-button {
    color: #000000;
    display: inline-block;
    cursor: pointer;
}
</code>```

and remove this

```<code>.yith-wcpsc-product-size-chart-button:hover {
    background: #3f3f3f;
}
</code>```

Title: Change from button to plain text

Body:
The "See size chart" element is not a button, it is actually plain text with a button-like style. You need to change it's CSS rules

If you want it to be simple black text on white background, change this:

.yith-wcpsc-product-size-chart-button{
    background: #0f0f0f;
    border: none;
    border-radius: 0px;
    color: #ffffff;
    display: inline-block;
    padding: 3px 10px 3px 10px;
    text-decoration: none;
    margin: 5px 3px;
    cursor: pointer;
    box-shadow: 0px 2px 7px -2px #dddddd;
}

to

.yith-wcpsc-product-size-chart-button {
    color: #000000;
    display: inline-block;
    cursor: pointer;
}

and remove this

.yith-wcpsc-product-size-chart-button:hover {
    background: #3f3f3f;
}


问:
Remove Element in ArrayList in loop
I need help. I tried to remove an element from an ArrayList.
I have two lists. One list from a file, the second list from the database.

I need to find the same elements to later remove them from the original list, and thus have a list with differences.

```<code>List<BinInternacionalMarcaDEL> listDiff = new ArrayList<BinInternacionalMarcaDEL>();

ListOriginal= binInternacionalRepositoryDEL.findAllByBin();

public  List<BinInternacionalMarcaDEL> Differences(List<BinInternacionalMarcaDEL> listA,
                                                   List<BinInternacionalMarcaDEL> listB) {
    try {
        for(BinInternacionalMarcaDEL elementA: listaA){
            for(BinInternacionalMarcaDEL elementB: listaB) {
                if(elementA.getNumRangoini().compareTo(elementB.getNumRangoini()) == 0 ){
                    listDiff.add(elementA);
                }
            }
        }
        ListOriginal.removeAll(listDiff);
    } catch (Exception e) {
        LOGGER.error(e.toString());
    }
</code>```

but this doesn't work.

答:
Java list remove and contains methods are implemented using equality of objects. This logic is implemented in hashCode and equal method in your class and all classes in Java inherit this attribute from the Object class.(to be honest ArrayList doesn't use hashCode in implementing remove and contains metheds but in java contract you should implement these two methods together). here when you are adding element to  listDiff you are defining your own equality which is based on equality of attribute numRangoini(using compateTo method) and when you request the list class to remove them from list(with removeAll method). removeAll remove them based on the equality of that two object. Since you haven't defined this logic in your own class.
this behaviour is inherited from object class which is based on strict equality. by default two object are equal if they reference the same object.

Solution: define the logic for equality in your own class in equal method. This method should return true if two object has the same attribute value numRangoini. don't forget to define hashCode as well. and here is the rule if two objects are equal they should return the same hashCode.

here is a simple implementation

```<code>@Override
public boolean equals(Object obj) {
    if(this == obj)
        return true;
    if(obj == null || obj.getClass()!= this.getClass())
        return false;
    BinInternacionalMarcaDEL  binInternacionalMarcaDEL  = (BinInternacionalMarcaDEL)obj;
    return (national.getNumRangoini().compareTo(this.getNumRangoini()) == 0);
}

@Override
public int hashCode() {
   return this.getNumRangoini().intValue();
}
</code>```

Title: Remove Element in ArrayList in loop

Body:
I need help. I tried to remove an element from an ArrayList.
I have two lists. One list from a file, the second list from the database.

I need to find the same elements to later remove them from the original list, and thus have a list with differences.

List<BinInternacionalMarcaDEL> listDiff = new ArrayList<BinInternacionalMarcaDEL>();

ListOriginal= binInternacionalRepositoryDEL.findAllByBin();

public  List<BinInternacionalMarcaDEL> Differences(List<BinInternacionalMarcaDEL> listA,
                                                   List<BinInternacionalMarcaDEL> listB) {
    try {
        for(BinInternacionalMarcaDEL elementA: listaA){
            for(BinInternacionalMarcaDEL elementB: listaB) {
                if(elementA.getNumRangoini().compareTo(elementB.getNumRangoini()) == 0 ){
                    listDiff.add(elementA);
                }
            }
        }
        ListOriginal.removeAll(listDiff);
    } catch (Exception e) {
        LOGGER.error(e.toString());
    }

but this doesn't work.

Body:
Java list remove and contains methods are implemented using equality of objects. This logic is implemented in hashCode and equal method in your class and all classes in Java inherit this attribute from the Object class.(to be honest ArrayList doesn't use hashCode in implementing remove and contains metheds but in java contract you should implement these two methods together). here when you are adding element to  listDiff you are defining your own equality which is based on equality of attribute numRangoini(using compateTo method) and when you request the list class to remove them from list(with removeAll method). removeAll remove them based on the equality of that two object. Since you haven't defined this logic in your own class.
this behaviour is inherited from object class which is based on strict equality. by default two object are equal if they reference the same object.

Solution: define the logic for equality in your own class in equal method. This method should return true if two object has the same attribute value numRangoini. don't forget to define hashCode as well. and here is the rule if two objects are equal they should return the same hashCode.

here is a simple implementation

@Override
public boolean equals(Object obj) {
    if(this == obj)
        return true;
    if(obj == null || obj.getClass()!= this.getClass())
        return false;
    BinInternacionalMarcaDEL  binInternacionalMarcaDEL  = (BinInternacionalMarcaDEL)obj;
    return (national.getNumRangoini().compareTo(this.getNumRangoini()) == 0);
}

@Override
public int hashCode() {
   return this.getNumRangoini().intValue();
}


问:
Can't find javascript source map to debug in chrome devtools
I'm using webpack in a .Net project to bundle my javascript files. I recently ran into a bug that I'd like to debug using chrome dev tools.

In my webpack config file, I added the following line to generate source maps.

```<code>devtool: 'source-map'
</code>```

After running npx webpack the following files were generated in my dist folder.

So I know for sure these files were generated. When I open up resources.entry.js in the chrome debugger, I see the following.

However, I can't seem to actually find the source map so that I can place a break point. I can't find it in the tree.

and I can't seem to do a ctrl + p to search for it like Chrome suggests.

What exactly do I need to do to be able to debug using my source javascript files?

Thank you.

答:
You need to manually add the source maps in dev-tools. Following are the steps.

Open DevTools

Open source tab

Open the minified JS file

Right-click in source code (editor) area

Select the option, "Add Source Maps"

Enter the name of the sourcemaps

Also, make sure you have sourcemaps enabled. (Check this: https://developers.google.com/web/tools/chrome-devtools/javascript/source-maps)

Update: Its available in chrome 85 as well.

Body:
I'm using webpack in a .Net project to bundle my javascript files. I recently ran into a bug that I'd like to debug using chrome dev tools.

In my webpack config file, I added the following line to generate source maps.

devtool: 'source-map'

After running npx webpack the following files were generated in my dist folder.

So I know for sure these files were generated. When I open up resources.entry.js in the chrome debugger, I see the following.

However, I can't seem to actually find the source map so that I can place a break point. I can't find it in the tree.

and I can't seem to do a ctrl + p to search for it like Chrome suggests.

What exactly do I need to do to be able to debug using my source javascript files?

Thank you.


问:
What's the use of "ostream &os"?
I just started learning C++, and I saw some function in C++ primer like that:

```<code>double total_receipt(ostream &os)const{...}
</code>```

then I try to find the address of cout by using this code: "cout << &cout << endl;"

and that's no difference between ostream &os and direct use cout.

So why not just use cout instead of ostream &os? Or maybe it's just a "good" habit?

答:
First notice:

cout is an object (check these docs)

ostream is a class (check these docs)

When you declare a method, you need to use the class names for the parameters, so if your class uses an "output stream" (that's what ostream means) then you declare your function like:

```<code>double total_receipt(ostream &os)
</code>```

You can't create the function like this:

```<code>double total_receipt(cout) // doesn't work
</code>```

Now, if your question is about what is the difference between declaring the total_receipt function  like this:

```<code>double total_receipt(ostream &os) {
    os << "hello world" << std::endl;
}
</code>```

or like this:

```<code>double total_receipt() {
    std::cout << "hello world" << std::endl;
}
</code>```

That's up to you. Usually, we use the first one as that allows to invoke the function with other things besides cout, like:

```<code>ofstream out_file("my_file.txt");
total_receipt(out_file);
</code>```

So, you can pass to that function any object of classes derived from ostream, like ofstream in the example. This means, your function can print to a file, besides printing to the terminal, so you add more functionality if you need it.

Title: What's the use of "ostream &os"?

Body:
I just started learning C++, and I saw some function in C++ primer like that:

double total_receipt(ostream &os)const{...}

then I try to find the address of cout by using this code: "cout << &cout << endl;"

and that's no difference between ostream &os and direct use cout.

So why not just use cout instead of ostream &os? Or maybe it's just a "good" habit?

Body:
First notice:

cout is an object (check these docs)

ostream is a class (check these docs)

When you declare a method, you need to use the class names for the parameters, so if your class uses an "output stream" (that's what ostream means) then you declare your function like:

double total_receipt(ostream &os)

You can't create the function like this:

double total_receipt(cout) // doesn't work

Now, if your question is about what is the difference between declaring the total_receipt function  like this:

double total_receipt(ostream &os) {
    os << "hello world" << std::endl;
}

or like this:

double total_receipt() {
    std::cout << "hello world" << std::endl;
}

That's up to you. Usually, we use the first one as that allows to invoke the function with other things besides cout, like:

ofstream out_file("my_file.txt");
total_receipt(out_file);

So, you can pass to that function any object of classes derived from ostream, like ofstream in the example. This means, your function can print to a file, besides printing to the terminal, so you add more functionality if you need it.


问:
No response after connecting from celery to redis via ssl
I'm following this tutorial, and adjusting the Celery-background related code to my project.

In my case I am operating in a Docker environment, and I have a secured site (i.e. https://localhost).
which requires secured ssl communication.

I adjusted the code for secure connection.

I had initial connection problems, which created log error messages, but I was able to solve - see here.

Now the log file is quite, but I think that I still have connection problems. As a result, at runtime, when triggerring a task, nothing happens.

What could be the reason for no connection in the secured case?

Should I expect a message if the keys are incorrect?
Is there a way to test the connection from celery/web containers to redis container from the command line?

答:
I was able to fix the problem by making changes to the configuration of the containers.

Specifically, I made the following changes:

In redis container:

followed this tutorial to add stunnel, and create certs for the redis container

used this git code to configure stunnel within a Docker container

In celery container:

 - elevated the log level to debug

I first tested that I can connect from my localhost to the redis docker container over ssl. This is described here

Then, I tested that I can connect from the celery container to the redis container over ssl.
The docker-compose file is:

```<code>version: '3'

services:
  web:
    restart: always
    build:
      context: ./web
      dockerfile: Dockerfile
    expose:
      - "8000"
    volumes:
      - /home/webServer/web:/home/flask/app/web
      - /home/webServer/redis/ssl:/etc/certs
      - data2:/home/flask/app/web/project/img
    command: /usr/local/bin/gunicorn -w 2 -t 3600 -b :8000 project:app
    depends_on:
      - postgres
    stdin_open: true
    tty: true

  nginx:
    restart: always
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /home/webServer/web:/home/flask/app/web
      - data2:/home/flask/app/web/project/img
    depends_on:
      - web

  postgres:
    restart: always
    build:
      context: ./postgresql
      dockerfile: Dockerfile
    volumes:
      - data1:/var/lib/postgresql/data
    expose:
      - "5432"

  redis:
    build:
      context: ./redis
      dockerfile: Dockerfile
    restart: always

    command: sh -c "stunnel /stunnel-redis-server.conf && /usr/local/bin/redis-server /etc/redis/redis.conf"
    expose:
      - '6380'
    ports:
     - "6380:6380"
    volumes:
      - /home/webServer/redis/ssl:/etc/certs
      - /home/webServer/redis/conf:/etc/redis

  celery:
    build:
      context: ./web
    command: watchmedo auto-restart --directory=./ --pattern=*.py --recursive -- celery worker -A project.celery  --loglevel=debug
    volumes:
      - /home/webServer/web:/home/flask/app/web
      - /home/webServer/redis/ssl:/etc/certs
      - data2:/home/flask/app/web/project/img
    depends_on:
      - redis

volumes:
  data1:
  data2:
</code>```

Other related files are:

files on the redis docker container: (the settings in these files are described here)

redis container Dockerfile

redis/conf/redis.conf

redis/stunnel-redis-server.conf

settings on the celery docker container:

```<code>cat web/project/flask_celery.py
...

key_file = '/etc/certs/localhost.key'
cert_file = '/etc/certs/private.pem'
ca_file = '/etc/certs/myCA.pem'
...

celery = Celery(app.import_name,
                backend=app.config['CELERY_RESULT_BACKEND'],
                broker=app.config['CELERY_BROKER_URL'],
                broker_use_ssl = {
                    'ssl_keyfile': key_file,
                    'ssl_certfile': cert_file,
                    'ssl_ca_certs': ca_file,
                    'ssl_cert_reqs': ssl.CERT_REQUIRED
                },
                redis_backend_use_ssl = {
                    'ssl_keyfile': key_file,
                    'ssl_certfile': cert_file,
                    'ssl_ca_certs': ca_file,
                    'ssl_cert_reqs': ssl.CERT_REQUIRED
                })

------------------

cat project/__init__.py
...
app.config['CELERY_BROKER_URL'] = 'rediss://webserver_redis_1:6380/0'
app.config['CELERY_RESULT_BACKEND'] = 'rediss://webserver_redis_1:6380/0'
</code>```

Body:
I was able to fix the problem by making changes to the configuration of the containers.

Specifically, I made the following changes:

In redis container:

followed this tutorial to add stunnel, and create certs for the redis container

used this git code to configure stunnel within a Docker container

In celery container:

 - elevated the log level to debug

I first tested that I can connect from my localhost to the redis docker container over ssl. This is described here

Then, I tested that I can connect from the celery container to the redis container over ssl.
The docker-compose file is:

version: '3'

services:
  web:
    restart: always
    build:
      context: ./web
      dockerfile: Dockerfile
    expose:
      - "8000"
    volumes:
      - /home/webServer/web:/home/flask/app/web
      - /home/webServer/redis/ssl:/etc/certs
      - data2:/home/flask/app/web/project/img
    command: /usr/local/bin/gunicorn -w 2 -t 3600 -b :8000 project:app
    depends_on:
      - postgres
    stdin_open: true
    tty: true

  nginx:
    restart: always
    build:
      context: ./nginx
      dockerfile: Dockerfile
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /home/webServer/web:/home/flask/app/web
      - data2:/home/flask/app/web/project/img
    depends_on:
      - web

  postgres:
    restart: always
    build:
      context: ./postgresql
      dockerfile: Dockerfile
    volumes:
      - data1:/var/lib/postgresql/data
    expose:
      - "5432"

  redis:
    build:
      context: ./redis
      dockerfile: Dockerfile
    restart: always

    command: sh -c "stunnel /stunnel-redis-server.conf && /usr/local/bin/redis-server /etc/redis/redis.conf"
    expose:
      - '6380'
    ports:
     - "6380:6380"
    volumes:
      - /home/webServer/redis/ssl:/etc/certs
      - /home/webServer/redis/conf:/etc/redis

  celery:
    build:
      context: ./web
    command: watchmedo auto-restart --directory=./ --pattern=*.py --recursive -- celery worker -A project.celery  --loglevel=debug
    volumes:
      - /home/webServer/web:/home/flask/app/web
      - /home/webServer/redis/ssl:/etc/certs
      - data2:/home/flask/app/web/project/img
    depends_on:
      - redis

volumes:
  data1:
  data2:

Other related files are:

files on the redis docker container: (the settings in these files are described here)

redis container Dockerfile

redis/conf/redis.conf

redis/stunnel-redis-server.conf

settings on the celery docker container:

cat web/project/flask_celery.py
...

key_file = '/etc/certs/localhost.key'
cert_file = '/etc/certs/private.pem'
ca_file = '/etc/certs/myCA.pem'
...

celery = Celery(app.import_name,
                backend=app.config['CELERY_RESULT_BACKEND'],
                broker=app.config['CELERY_BROKER_URL'],
                broker_use_ssl = {
                    'ssl_keyfile': key_file,
                    'ssl_certfile': cert_file,
                    'ssl_ca_certs': ca_file,
                    'ssl_cert_reqs': ssl.CERT_REQUIRED
                },
                redis_backend_use_ssl = {
                    'ssl_keyfile': key_file,
                    'ssl_certfile': cert_file,
                    'ssl_ca_certs': ca_file,
                    'ssl_cert_reqs': ssl.CERT_REQUIRED
                })

------------------

cat project/__init__.py
...
app.config['CELERY_BROKER_URL'] = 'rediss://webserver_redis_1:6380/0'
app.config['CELERY_RESULT_BACKEND'] = 'rediss://webserver_redis_1:6380/0'


问:
Match rows in a panda dataframe based on values in two columns
I have a pandas dataframe df with about half a million rows.
The columns are ['in','out'].
I need to find whether for each row i there is another row j that matches it. The condition for the match is:

```<code>df.in[i] == df.out[j]  and df.out[i] == df.in[j]
</code>```

I've implemented it as a for loop:

for i, row in df.iterrows():
    match_row = (d.out == row['in']) & (df.in == row['out'])
    if len(df[match_row].value) > 0:
        #do something
```
<p>As Nick Becker suggested, here is a small sample data:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'in':[10,20,30,40,50,60], 'out':[20,10,40,30,70,80]})
</code>```
```<code>    in  out
0   10  20
1   20  10
2   30  40
3   40  30
4   50  70
5   60  80
</code>```

I need to match row 0 with row 1 and row 2 with row 3.
I wonder if there is a more efficient way to do it without using a for loop.

[UPDATE]
Since there are some suggestions (thank you) on how to solve this problem, I'd like to post here what I expect to get. Here is the code and the output:

matches = []
for i, row in df.iterrows():
    match_row = (df['out'] == row['in']) & (df['in'] == row['out'])
    if len(df[match_row]) > 0:
        matches.append((i, df[match_row].index[0],row['in'], row['out'] ))
pd.DataFrame(matches, columns = ['row', 'match row', 'in','out'])
    row matching_row    in  out
0   0   1               10  20
1   1   0               20  10
2   2   3               30  40
3   3   2               40  30
```

I can do some clean up to remove duplication, but this is basically what I'm looking for. Is it an inherently sequential problem and there is nothing I can do about it?

答:
You can use merge in pandas to join the dataframe to itself. The default is an inner join. Does this help?

```<code>df.merge(df, left_on=["in", "out"], right_on=["out", "in"], suffixes=('_left', '_right'))
</code>```

Body:
I have a pandas dataframe df with about half a million rows.
The columns are ['in','out'].
I need to find whether for each row i there is another row j that matches it. The condition for the match is:

df.in[i] == df.out[j]  and df.out[i] == df.in[j]

I've implemented it as a for loop:

for i, row in df.iterrows():
    match_row = (d.out == row['in']) & (df.in == row['out'])
    if len(df[match_row].value) > 0:
        #do something

As Nick Becker suggested, here is a small sample data:

df = pd.DataFrame({'in':[10,20,30,40,50,60], 'out':[20,10,40,30,70,80]})

    in  out
0   10  20
1   20  10
2   30  40
3   40  30
4   50  70
5   60  80

I need to match row 0 with row 1 and row 2 with row 3.
I wonder if there is a more efficient way to do it without using a for loop.

[UPDATE]
Since there are some suggestions (thank you) on how to solve this problem, I'd like to post here what I expect to get. Here is the code and the output:

matches = []
for i, row in df.iterrows():
    match_row = (df['out'] == row['in']) & (df['in'] == row['out'])
    if len(df[match_row]) > 0:
        matches.append((i, df[match_row].index[0],row['in'], row['out'] ))
pd.DataFrame(matches, columns = ['row', 'match row', 'in','out'])
    row matching_row    in  out
0   0   1               10  20
1   1   0               20  10
2   2   3               30  40
3   3   2               40  30

I can do some clean up to remove duplication, but this is basically what I'm looking for. Is it an inherently sequential problem and there is nothing I can do about it?

Body:
You can use merge in pandas to join the dataframe to itself. The default is an inner join. Does this help?

df.merge(df, left_on=["in", "out"], right_on=["out", "in"], suffixes=('_left', '_right'))


问:
Banner rotating images. Each image when clicked sends to a different URL (vanilla javascript)
I've been given two examples of how to do this but neither is doing both things that I'm looking to do. My website should include:

Rotating Image Banner (3 images), that changes every few seconds

Each image should be clickable and redirect you to a different URL

In our recent lecture, the professor wrote this code on the board and said that this was how you did that. However, it's not working for me.

```<code><html>
 <head>
     <script language=JAVASCRIPT type=TEXT/JAVASCRIPT>
     //I'm not sure when to use '' or ""
     //I replaced some of the "picture.jpg" images with links to images. I'm not sure if I used the right syntax.
     adImages = new Array("https://i.picsum.photos/id/666/800/200.jpg",
                          "https://i.picsum.photos/id/420/800/200.jpg",
                          "https://i.picsum.photos/id/888/800/200.jpg");
 adURL = new Array("https://google.com","https://github.com","https://stackoverflow.com");
 thisAd = 0;
 //length of what?
 imgCt = adImages.length;

 function rotate()
 {
  if (document.images)
  {
    thisAd++;
    //Is it better practice to use "==="?
    if (thisAd == imgCt)
    {
      thisAd = 0;
    }
    document.adBanner.src=adImages[thisAd];
      setTimeout("rotate()", 2 * 1000);
  }
 }

 function newLocation()
 {
  document.location.href = adURL[thisAd];
 }
 </script>
 </head>
     //I don't understand what this is at all
     <body onload=rotate()>
         //Apparently <center> is obsolete?
         <center>
             <p><font size=4>Rotating Banner <font color=#ff0000>Assignment 6</font> Rotate Party -
             Udemy</font>
             </p>
         <a href="javascript:newLocation()"><IMG height=105 alt="Ad Banner"
         src="https://i.picsum.photos/id/666/800/200.jpg" width=610 name=adBanner></a>
         </center>
   </body>
  </html>
</code>```

Just a heads up. I've been posting my slides from class on Reddit the past couple of weeks and I've received a lot of comments about things being horribly out of date. If you can, please give me examples that are more modern or better practices than what you see me learning. You can find the conversations about my experience learning JavaScript in community college here if you're interested: https://www.reddit.com/user/gettupled/

The second example we were given was a YouTube video that gave the following example. However, it does not include the option of clicking the image and being sent to a URL. I'm not sure if it's common to post HTML, CSS and Javascript code in the body of a message so I'll just attach a codepen unless told otherwise. This code comes from Travesy Media.

https://codepen.io/vitalwheat/pen/QWbEyqN

Thanks everyone. This is my first post here. Hi.

答:
There are many way to implement this. Here is one of the way to do it.

working Demo

(function() {
  "use strict";

  const imageList = [
    "https://i.picsum.photos/id/666/800/200.jpg",
    "https://i.picsum.photos/id/420/800/200.jpg",
    "https://i.picsum.photos/id/888/800/200.jpg"
  ];

  const urlList = [
    "https://google.com",
    "https://github.com",
    "https://stackoverflow.com"
  ];

  function createRotatingBanner(rotationTime) {
    const $adsBanner = document.querySelector(".adBanner");
    let $bannerList;

    let currentBannerRendered = 0;

    function renderBanner() {
      Array.from($bannerList).forEach((banner, bannerIndex) => {
        banner.className = bannerIndex === currentBannerRendered ? "" : "hide";
      });
      currentBannerRendered = (currentBannerRendered+1)%$bannerList.length;
    }

    // creating Banner image and setting them to hide
    function createBanner() {
      const fragement = new DocumentFragment();

      imageList.forEach((image, index) => {
        const banner = document.createElement("img");
        banner.src = image;
        // wrapping image with anchor element
        const anchor = document.createElement("a");
        anchor.href = urlList[index];
        // hide all the banner
        anchor.className = "hide"
        anchor.appendChild(banner);
        fragement.appendChild(anchor);
      });
      const cloneFragement = [...fragement.children];
      $adsBanner.appendChild(fragement);
      return cloneFragement;
    }

    $bannerList = createBanner();
    renderBanner();

    setInterval(renderBanner, rotationTime);
  }

  createRotatingBanner(2000);
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
  display: none;
}</code>```

```

Body:
I've been given two examples of how to do this but neither is doing both things that I'm looking to do. My website should include:

Rotating Image Banner (3 images), that changes every few seconds

Each image should be clickable and redirect you to a different URL

In our recent lecture, the professor wrote this code on the board and said that this was how you did that. However, it's not working for me.

     //I don't understand what this is at all

         //Apparently  is obsolete?

Rotating Banner Assignment 6 Rotate Party -
             Udemy

Just a heads up. I've been posting my slides from class on Reddit the past couple of weeks and I've received a lot of comments about things being horribly out of date. If you can, please give me examples that are more modern or better practices than what you see me learning. You can find the conversations about my experience learning JavaScript in community college here if you're interested: https://www.reddit.com/user/gettupled/

The second example we were given was a YouTube video that gave the following example. However, it does not include the option of clicking the image and being sent to a URL. I'm not sure if it's common to post HTML, CSS and Javascript code in the body of a message so I'll just attach a codepen unless told otherwise. This code comes from Travesy Media.

https://codepen.io/vitalwheat/pen/QWbEyqN

Thanks everyone. This is my first post here. Hi.

Body:
There are many way to implement this. Here is one of the way to do it.

working Demo

(function() {
  "use strict";

  const imageList = [
    "https://i.picsum.photos/id/666/800/200.jpg",
    "https://i.picsum.photos/id/420/800/200.jpg",
    "https://i.picsum.photos/id/888/800/200.jpg"
  ];

  const urlList = [
    "https://google.com",
    "https://github.com",
    "https://stackoverflow.com"
  ];

  function createRotatingBanner(rotationTime) {
    const $adsBanner = document.querySelector(".adBanner");
    let $bannerList;

    let currentBannerRendered = 0;

    function renderBanner() {
      Array.from($bannerList).forEach((banner, bannerIndex) => {
        banner.className = bannerIndex === currentBannerRendered ? "" : "hide";
      });
      currentBannerRendered = (currentBannerRendered+1)%$bannerList.length;
    }

    // creating Banner image and setting them to hide
    function createBanner() {
      const fragement = new DocumentFragment();

      imageList.forEach((image, index) => {
        const banner = document.createElement("img");
        banner.src = image;
        // wrapping image with anchor element
        const anchor = document.createElement("a");
        anchor.href = urlList[index];
        // hide all the banner
        anchor.className = "hide"
        anchor.appendChild(banner);
        fragement.appendChild(anchor);
      });
      const cloneFragement = [...fragement.children];
      $adsBanner.appendChild(fragement);
      return cloneFragement;
    }

    $bannerList = createBanner();
    renderBanner();

    setInterval(renderBanner, rotationTime);
  }

  createRotatingBanner(2000);
})();

.hide {
  display: none;
}

<div class="adBanner"></div>


问:
WCF tracing add a filter
I would like to add a filter to my WCF tracing to either filter on an endpoint or on the content of the message.

It is not clear from what I have seen on how to do this. I am trying to do this in the web.config file.

Any ideas welcome.

Thanks
Ian

答:
Please try the below configuration, tracing the WCF activity.

```<code><system.diagnostics>
    <sources>
      <source name="System.ServiceModel" propagateActivity="true" switchValue="Information, ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.XmlWriterTraceListener" name="xmlLog" initializeData="myLogs.svclog"/>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
  <system.serviceModel>
    <diagnostics>
      <messageLogging logEntireMessage="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="false"/>
    </diagnostics>
  </system.serviceModel>
</code>```

You can custom your configuration referring to the below link.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging

https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/configuring-tracing

After we get the tracing file, We could use Microsoft Service Trace Viewer to filter the WCF activity.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/service-trace-viewer-tool-svctraceviewer-exe

https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/using-service-trace-viewer-for-viewing-correlated-traces-and-troubleshooting

Feel free to let me know if there is anything I can help with.

Title: WCF tracing add a filter

Body:
Please try the below configuration, tracing the WCF activity.

<system.diagnostics>
    <sources>
      <source name="System.ServiceModel" propagateActivity="true" switchValue="Information, ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.XmlWriterTraceListener" name="xmlLog" initializeData="myLogs.svclog"/>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
  <system.serviceModel>
    <diagnostics>
      <messageLogging logEntireMessage="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="false"/>
    </diagnostics>
  </system.serviceModel>

You can custom your configuration referring to the below link.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging

https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/configuring-tracing

After we get the tracing file, We could use Microsoft Service Trace Viewer to filter the WCF activity.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/service-trace-viewer-tool-svctraceviewer-exe

https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/using-service-trace-viewer-for-viewing-correlated-traces-and-troubleshooting

Feel free to let me know if there is anything I can help with.


问:
Compilation Error while iterating using Linq with multiple conditions
I am building a Linq query that does the following:

Iterate through each group

Check if the group contains at least one student with University= OPQ

Make sure that the same group doesn't have any Student= Adam.

Get the first item in each group of students that have University= OPQ.

Output

Emity (Group 2)

White (Group 5)

What I tried

```<code>    var results = StudentsList
        .GroupBy(x => x.GroupID)
        .Where(x=>x.Any(y=> y.University=="OPQ") && x.Any(y=> y.Student!="Adam" ))
        .Select(g =>
                {
                    var firstItem = g.Where(x=>x.University=="OPQ");
                    firstItem.IsQualified = true;

                    return firstItem;
                }).ToList();

    foreach(var item in results)
        Console.WriteLine("Group:" + item.GroupID + " Student:" + item.Student +  " IsQualified:" + item.IsQualified);
</code>```

I get an error:

Compilation error (line 56, col 22):
  'System.Collections.Generic.IEnumerable' does not
  contain a definition for 'IsQualified' and no extension method
  'IsQualified' accepting a first argument of type
  'System.Collections.Generic.IEnumerable' could be
  found (are you missing a using directive or an assembly reference?)

My Code

```<code>    List<StudentInfo> StudentsList = new List<StudentInfo>();

    // Group 1
    StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="John", University="abc", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="Jack", University="def", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Peter", University="abc", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", GroupID = 1, IsQualified=false} );

    // Group 2
    StudentsList.Add( new StudentInfo { Student="Donald", University="def", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", GroupID = 2, IsQualified=false} );

    // Group 3
    StudentsList.Add( new StudentInfo { Student="Adam", University="yub", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Saint", University="abc", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", GroupID = 3, IsQualified=false} );

    // Group 4
    StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", GroupID = 4, IsQualified=false} );

    // Group 5
    StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", GroupID = 5, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="White", University="OPQ", GroupID = 5, IsQualified=false} );

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}
}
</code>```

答:
Demo on dotnet fiddle

Firstly, You should make sure that the group does not contains any Student == "Adam"

Secondly, You should make sure that the group contains any least one University == "OPQ"

Finally, Get the first item of each group with University == "OPQ"

```<code>var results = StudentsList.GroupBy(x => x.GroupID)
                       .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
                       .Select(g =>
                                {
                                    var firstItem = g.First(x => x.University == "OPQ");
                                    firstItem.IsQualified = true;

                                    return firstItem;
                                }).ToList();
</code>```

Your error

x.Any(y=> y.Student!="Adam" ) should be !x.Any(y => y.Student =="Adam" )

var firstItem = g.Where(x=>x.University=="OPQ"); Should be var firstItem = g.First(x=>x.University=="OPQ")

Body:
I am building a Linq query that does the following:

Iterate through each group

Check if the group contains at least one student with University= OPQ

Make sure that the same group doesn't have any Student= Adam.

Get the first item in each group of students that have University= OPQ.

Output

Emity (Group 2)

White (Group 5)

What I tried

    var results = StudentsList
        .GroupBy(x => x.GroupID)
        .Where(x=>x.Any(y=> y.University=="OPQ") && x.Any(y=> y.Student!="Adam" ))
        .Select(g =>
                {
                    var firstItem = g.Where(x=>x.University=="OPQ");
                    firstItem.IsQualified = true;

                    return firstItem;
                }).ToList();

    foreach(var item in results)
        Console.WriteLine("Group:" + item.GroupID + " Student:" + item.Student +  " IsQualified:" + item.IsQualified);

I get an error:

Compilation error (line 56, col 22):
  'System.Collections.Generic.IEnumerable' does not
  contain a definition for 'IsQualified' and no extension method
  'IsQualified' accepting a first argument of type
  'System.Collections.Generic.IEnumerable' could be
  found (are you missing a using directive or an assembly reference?)

My Code

    List<StudentInfo> StudentsList = new List<StudentInfo>();

    // Group 1
    StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="John", University="abc", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="Jack", University="def", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Peter", University="abc", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", GroupID = 1, IsQualified=false} );

    // Group 2
    StudentsList.Add( new StudentInfo { Student="Donald", University="def", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", GroupID = 2, IsQualified=false} );

    // Group 3
    StudentsList.Add( new StudentInfo { Student="Adam", University="yub", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Saint", University="abc", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", GroupID = 3, IsQualified=false} );

    // Group 4
    StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", GroupID = 4, IsQualified=false} );

    // Group 5
    StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", GroupID = 5, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="White", University="OPQ", GroupID = 5, IsQualified=false} );

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}
}

Body:
Demo on dotnet fiddle

Firstly, You should make sure that the group does not contains any Student == "Adam"

Secondly, You should make sure that the group contains any least one University == "OPQ"

Finally, Get the first item of each group with University == "OPQ"

var results = StudentsList.GroupBy(x => x.GroupID)
                       .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
                       .Select(g =>
                                {
                                    var firstItem = g.First(x => x.University == "OPQ");
                                    firstItem.IsQualified = true;

                                    return firstItem;
                                }).ToList();

Your error

x.Any(y=> y.Student!="Adam" ) should be !x.Any(y => y.Student =="Adam" )

var firstItem = g.Where(x=>x.University=="OPQ"); Should be var firstItem = g.First(x=>x.University=="OPQ")