问:
Angular Material table matSort not working
I'm having troubles with my table

I fetch data and then pass it to my table

Here is my code:

html

```<code><div class="mainContainer">
  <div class="mat-elevation-z8 content">

  <mat-table
    class="mat-elevation-z3 productsTable"
    matSort
    mat-table
    [dataSource]="productsDataForTable">

    <ng-container matColumnDef="title">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Title
      </mat-header-cell>
      <mat-cell *matCellDef="let row">
        {{row.name.en}}
      </mat-cell>
    </ng-container>

  <ng-container matColumnDef="image">
      <mat-header-cell *matHeaderCellDef>
        Image
      </mat-header-cell>
      <mat-cell *matCellDef="let prod; let i = index" >
        <img class="prodThumbnail" src={{prodsThumbnails[i]}} alt="Product thumbnail">
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="description">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Description
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.description.en}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Weight
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.weight + ' ' + prod.weightUnit}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="SKU">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        SKU
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.sku}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="price">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Price
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        $ {{prod.prices[0].unitPrice}} {{prod.prices[0].currency}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="category">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Category
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.category}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Status
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.status}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="actions">
      <mat-header-cell *matHeaderCellDef>
        Actions
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        <mat-icon class="actionOnProductButton" (click)="openProductDetailsDialog(prod)">create</mat-icon>
        <mat-icon class="actionOnProductButton" (click)="openDeleteProductDialog(prod)">delete</mat-icon>
      </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="tableHeaders"></mat-header-row>
    <mat-row
      class="table-rows"
      *matRowDef="let row; columns: tableHeaders;">

    </mat-row>

  </mat-table>

  </div>
</div>
</code>```

TS

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Catalog } from '../../catalog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ProductsService } from '../../products.service';
import { EnvironmentConfigService } from 'src/app/manufacturer/environment-config.service';

@Component({
  selector: 'app-catalog-details',
  templateUrl: './catalog-details.component.html',
  styleUrls: ['./catalog-details.component.scss']
})
export class CatalogDetailsComponent implements OnInit {

  catalogID: string;
  productsFetched: any;

  // For product thumbnail in table
  prodsThumbnails = [];

  // Data for products table
  productsDataForTable: MatTableDataSource<[]>;
  tableHeaders = [
    'image',
    'title',
    'description',
    'weight',
    'SKU',
    'price',
    'category',
    'status',
    'actions'
  ];

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor(
    private envService: EnvironmentConfigService,
    private prodsService: ProductsService,
    private snackBar: MatSnackBar,
    public dialog: MatDialog,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private catService: CatalogsService
  ) { }

  ngOnInit(): void {
    this.route.params.subscribe((params: Params) => {
      this.getProducts(params.id);
    });
  }

  getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
      this.productsDataForTable = new MatTableDataSource(prods);
      this.productsDataForTable.sort = this.sort;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
    });
  }

}
</code>```

The table was with *ngIf and i read that a matTable shouldn't has that because the @ViewChild(MatSort, {static: true}) sort: MatSort would be undefined so i erased an *ngIf that I was actually using but I still cant achieve the sorting.

I tried matPagination feature too without success, I suppose it is due to the same error.

I'll appreciate any help

答:
I found out what was wrong:

What you define in matColumnDef should actually match the object properties of the objects that will be displayed on each row.

So I did populate my objects before passing data to table

Body:
I'm having troubles with my table

I fetch data and then pass it to my table

Here is my code:

html

  <mat-table
    class="mat-elevation-z3 productsTable"
    matSort
    mat-table
    [dataSource]="productsDataForTable">

    <ng-container matColumnDef="title">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Title
      </mat-header-cell>
      <mat-cell *matCellDef="let row">
        {{row.name.en}}
      </mat-cell>
    </ng-container>

  <ng-container matColumnDef="image">
      <mat-header-cell *matHeaderCellDef>
        Image
      </mat-header-cell>
      <mat-cell *matCellDef="let prod; let i = index" >

      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="description">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Description
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.description.en}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Weight
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.weight + ' ' + prod.weightUnit}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="SKU">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        SKU
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.sku}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="price">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Price
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        $ {{prod.prices[0].unitPrice}} {{prod.prices[0].currency}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="category">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Category
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.category}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Status
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.status}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="actions">
      <mat-header-cell *matHeaderCellDef>
        Actions
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        <mat-icon class="actionOnProductButton" (click)="openProductDetailsDialog(prod)">create</mat-icon>
        <mat-icon class="actionOnProductButton" (click)="openDeleteProductDialog(prod)">delete</mat-icon>
      </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="tableHeaders"></mat-header-row>
    <mat-row
      class="table-rows"
      *matRowDef="let row; columns: tableHeaders;">

    </mat-row>

  </mat-table>

TS

import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Catalog } from '../../catalog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ProductsService } from '../../products.service';
import { EnvironmentConfigService } from 'src/app/manufacturer/environment-config.service';

@Component({
  selector: 'app-catalog-details',
  templateUrl: './catalog-details.component.html',
  styleUrls: ['./catalog-details.component.scss']
})
export class CatalogDetailsComponent implements OnInit {

  catalogID: string;
  productsFetched: any;

  // For product thumbnail in table
  prodsThumbnails = [];

  // Data for products table
  productsDataForTable: MatTableDataSource<[]>;
  tableHeaders = [
    'image',
    'title',
    'description',
    'weight',
    'SKU',
    'price',
    'category',
    'status',
    'actions'
  ];

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor(
    private envService: EnvironmentConfigService,
    private prodsService: ProductsService,
    private snackBar: MatSnackBar,
    public dialog: MatDialog,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private catService: CatalogsService
  ) { }

  ngOnInit(): void {
    this.route.params.subscribe((params: Params) => {
      this.getProducts(params.id);
    });
  }

  getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
      this.productsDataForTable = new MatTableDataSource(prods);
      this.productsDataForTable.sort = this.sort;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
    });
  }

}

The table was with *ngIf and i read that a matTable shouldn't has that because the @ViewChild(MatSort, {static: true}) sort: MatSort would be undefined so i erased an *ngIf that I was actually using but I still cant achieve the sorting.

I tried matPagination feature too without success, I suppose it is due to the same error.

I'll appreciate any help


来源: stackexchange

问:
solr 8.4.1 search ignore duplicate phrase
We are using Solr 8.4.1 to search the products from documents. I want exact phrase to come on top, but I also want if same phrase is repeated many times in document then it should only be counted once. Right now those keywords having same phrase multiple times in document comes on top because they're getting a higher score.

Please see the result below given i am searching for "pipes". Seven results found, but prod_id:297720 named my pipes pipes have a different score from  prod_id:3064.

As per our need both should have the same score. I want to ignore the repeated phrase found in the documents.

We are using similarity class <similarity class="solr.BM25SimilarityFactory"/>

Searching field schema given below as

```<code><field name="product_related_kword" type="text_general" indexed="true" stored="true" />
</code>```

And the result is:

```<code>{
  "responseHeader":{
    "status":0,
    "QTime":222,
    "params":{
      "q":"product_related_kword:pipes",
      "fl":"product_name,score,product_related_kword,prod_id,member_classified_slno,member_id",
      "start":"0",
      "rows":"100",
      "debugQuery":"on"}},
  "response":{"numFound":7,"start":0,"maxScore":2.7593598,"docs":[
      {
        "prod_id":297720,
        "product_name":"my pipes pipes",
        "member_classified_slno":123457327,
        "member_id":"11111327",
        "product_related_kword":"my pipes pipes 00",
        "score":2.7593598},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457560,
        "member_id":"11119579",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457544,
        "member_id":"11113186",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457546,
        "member_id":"11113636",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457551,
        "member_id":"11119238",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457553,
        "member_id":"785565531",
        "product_related_kword":"pipes 00",
        "score":2.5436506
       }
    ]
  },
</code>```

答:
Add the following filter to your index analyzer.

```<code><filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</code>```

This will remove the duplicate tokens from the stream. If you have synonyms then add this after Synonym Filter for better results.

Check RemoveDuplicatesTokenFilterFactory on the following page

https://lucene.apache.org/solr/guide/8_4/filter-descriptions.html

ContentLicense: CC BY-SA 4.0

Body:
We are using Solr 8.4.1 to search the products from documents. I want exact phrase to come on top, but I also want if same phrase is repeated many times in document then it should only be counted once. Right now those keywords having same phrase multiple times in document comes on top because they're getting a higher score.

Please see the result below given i am searching for "pipes". Seven results found, but prod_id:297720 named my pipes pipes have a different score from  prod_id:3064.

As per our need both should have the same score. I want to ignore the repeated phrase found in the documents.

We are using similarity class <similarity class="solr.BM25SimilarityFactory"/>

Searching field schema given below as

<field name="product_related_kword" type="text_general" indexed="true" stored="true" />

And the result is:

{
  "responseHeader":{
    "status":0,
    "QTime":222,
    "params":{
      "q":"product_related_kword:pipes",
      "fl":"product_name,score,product_related_kword,prod_id,member_classified_slno,member_id",
      "start":"0",
      "rows":"100",
      "debugQuery":"on"}},
  "response":{"numFound":7,"start":0,"maxScore":2.7593598,"docs":[
      {
        "prod_id":297720,
        "product_name":"my pipes pipes",
        "member_classified_slno":123457327,
        "member_id":"11111327",
        "product_related_kword":"my pipes pipes 00",
        "score":2.7593598},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457560,
        "member_id":"11119579",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457544,
        "member_id":"11113186",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457546,
        "member_id":"11113636",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457551,
        "member_id":"11119238",
        "product_related_kword":"pipes 00",
        "score":2.5436506},
      {
        "prod_id":3064,
        "product_name":"pipes",
        "member_classified_slno":123457553,
        "member_id":"785565531",
        "product_related_kword":"pipes 00",
        "score":2.5436506
       }
    ]
  },

Body:
Add the following filter to your index analyzer.

<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>

This will remove the duplicate tokens from the stream. If you have synonyms then add this after Synonym Filter for better results.

Check RemoveDuplicatesTokenFilterFactory on the following page

https://lucene.apache.org/solr/guide/8_4/filter-descriptions.html


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答:
The machine word size depends on the architecture, but also how the operating system is running the application.

In Windows x64 for example an application can be run either as a 64 bit application (having a 64 bit mahine word), or as a 32 bit application (having a 32 bit machine word). So the size of a machine word can differ even on the same machine.

The term WORD has different meaning depending on how it's used. It can either mean a machine word, or a type with a specific size. In x86 assembly language WORD, DOUBLEWORD (DWORD) and QUADWORD (QWORD) are used for 2, 4 and 8 byte sizes, regardless of the machine word size.

OwnerDisplayName: mixedpickles

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Guffa

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Guffa


问:
Does using assembly compiled in older version of .NET framework affects whole performance?
Lets imagine that we have two assemblies:

Foo.Logic (compiled on .NET 2.0 framework)

Foo.Application (compiled on .NET 4.0 framework) that have reference and uses compiled Foo.Logic.

Does it have impact on Foo.Application performance (or have any other drawbacks)?

答:
In the situation you described in the question, everything will Just Work™ without any problems.

A .NET 4.0 application will load a .NET 2.0 library directly into the .NET 4.0 runtime environment. It will not use side-by-side execution unless you explicitly ask it to. There's a lot of misinformation or unclear statements made about this around the web, so be careful in evaluating what you read.

I finally came across this article, which confirms what Jon Skeet says in his answer. In particular, the article explains (emphasis added):

In-Proc SxS does not solve the compatibility problems faced by library developers. Any libraries directly loaded by an application--either via a direct reference or an Assembly.Load--will continue to load directly into the runtime and AppDomain of the application loading it. This means that if an application is recompiled to run against the .NET Framework 4 runtime and still has dependent assemblies built against .NET 2.0, those dependents will load on the .NET 4 runtime as well. Therefore, we still recommend testing your libraries against all version[s] of the framework you wish to support. This is one of the reasons we have continued to maintain our high level of backward compatibility.

But if you're interested in even more of the nitty-gritty details, it's worth mentioning that one of the new features introduced with version 4.0 of the CLR is the ability to run multiple versions of the runtime at the same time from in a single process. This is called "In Process Side-by-Side Execution" (or "Inproc SxS" if you're very cool), and is a very powerful tool. You can read more about it here on the CLR team's blog.

Here are some pretty pictures for demonstration purposes:

Note the "layer-cake" model that was used to build the .NET 3.0 and 3.5 releases on top of .NET 2.0. That means that they'll all run side-by-side without any problems. But the isolation of the other versions will create a problem.

However, as mentioned above, .NET 4.0 solves this problem with Side-by-Side Execution:

Of course, this is mostly applicable to situations involving COM and interop with external applications like Outlook, but it's still a very cool feature.

But either way, you shouldn't see any problems whatsoever with this approach, either with compatibility, performance, or whatever else.


问:
Can two actors both required for a usecase be the same person?
I have been presented with the following use case diagram.

The given question was "How many people are required for the Use Case?".

I was taught, that Actors are used to model certain roles in the domain and that a "real" person can take multiple roles.

Going strictly by that definition, a single person with both roles should be enough, but I am not sure whether I am missing something, since intuitively there should be a reason, why there are two actors present.
Can a single "real" person be enough here?

答:
Yes this is possible.

For instance imagine a system allowing to trace bugs in a software, the actors can be

user : person adding a new bug report in the system to signal the problem

corrector : person correcting the bug

In case the bug detected in intern by the persons developing the software are traced a same person of that team can have the two roles

In my forum when a user requests to register I manually accept or not the registration to reject spammers

be sure to test I played the role of both a user and the administrator

Etc, there are lot of cases like that


问:
"xsi:type" attribute is changed to "type" c# xml document
I'm using XMLDocument to create a XML file, but when i set an attribute to an element called "xsi:type" in the .xml generated file this attribute is changed to just "type".

This is the output that i'm expecting:

```<code><ODX xsi:type="VALUE" />
</code>```

This is my code

```<code>using System.Xml;
        public static void xml_test()
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            XmlElement ODX = doc.CreateElement("ODX");
            ODX.SetAttribute("xsi:type", "VALUE");
            doc.AppendChild(ODX);
            doc.Save("C:\\Users\\dev\\Pictures\\DocParser\\DocParser\\xml_question_test.xml");
        }
</code>```

This is content of the xml_question_test.xml output file that i get,:

```<code><ODX type="VALUE" />
</code>```

Notice how change the name of the attribute from "xsi:type" to "type", i tried to set the name of the attribute as literal with @ before the string but it didn't work... i haven't found anything useful...

答:
Since you are adding xs, you need to specify the namespace which it represents.

```<code>public static void xml_test()
    {
        XmlDocument doc = new XmlDocument();
        XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        XmlElement ODX = doc.CreateElement("ODX");
        var attr = doc.CreateAttribute("xs:type", "http://www.w3.org/2001/XMLSchema");
        attr.Value = "VALUE";
        ODX.Attributes.Append(attr);
        doc.AppendChild(ODX);
        doc.Save("C:\\xml_question_test.xml");
    }
</code>```

You can read more here about XML namespaces: https://www.w3schools.com/xml/xml_namespaces.asp

Body:
I'm using XMLDocument to create a XML file, but when i set an attribute to an element called "xsi:type" in the .xml generated file this attribute is changed to just "type".

This is the output that i'm expecting:

<ODX xsi:type="VALUE" />

This is my code

using System.Xml;
        public static void xml_test()
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            XmlElement ODX = doc.CreateElement("ODX");
            ODX.SetAttribute("xsi:type", "VALUE");
            doc.AppendChild(ODX);
            doc.Save("C:\\Users\\dev\\Pictures\\DocParser\\DocParser\\xml_question_test.xml");
        }

This is content of the xml_question_test.xml output file that i get,:

<ODX type="VALUE" />

Notice how change the name of the attribute from "xsi:type" to "type", i tried to set the name of the attribute as literal with @ before the string but it didn't work... i haven't found anything useful...

Body:
Since you are adding xs, you need to specify the namespace which it represents.

public static void xml_test()
    {
        XmlDocument doc = new XmlDocument();
        XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        XmlElement ODX = doc.CreateElement("ODX");
        var attr = doc.CreateAttribute("xs:type", "http://www.w3.org/2001/XMLSchema");
        attr.Value = "VALUE";
        ODX.Attributes.Append(attr);
        doc.AppendChild(ODX);
        doc.Save("C:\\xml_question_test.xml");
    }

You can read more here about XML namespaces: https://www.w3schools.com/xml/xml_namespaces.asp


问:
Class Not Found in PHP Laravel 6.x when another class extends
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

```<code><?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}
</code>```

Class myUser: extension is fine.

```<code><?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}
</code>```

Class oauth: extension returns myContext class not found.

```<code><?php
namespace config\models;

class oauth extends myContext {
    private $user;
}
</code>```

Instantiate the class - returns class not found.

```<code><?php

use config\models\myContext as context;

$cont = new context();
</code>```

答: have you add autoload for config/ folder in composer.json. Laravel only default autoload for app/

Body:
I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.

However, another child class that is located in same directory could extend class A successfully.

In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.

Please help me on this.
Thanks in an advance.

Parent class: myContext

<?php
namespace config\models;

class myContext {
    public static $conn;
    ...
}

Class myUser: extension is fine.

<?php
namespace config\models;

class myUser extends myContext {
   private $name;
   ...
}

Class oauth: extension returns myContext class not found.

<?php
namespace config\models;

class oauth extends myContext {
    private $user;
}

Instantiate the class - returns class not found.

<?php

use config\models\myContext as context;

$cont = new context();


问:
How do I idiomatically convert a bool to an Option or Result in Rust?
It seems there is no way of such one-line conversion using std.

I do not like this kind of verbosity:

match my_bool {
    true => Ok(()),
    false => Err(MyError::False),
}
```
<p>I would like to use a one-liner, for example:</p>
<pre class="lang-rust prettyprint-override"><code>let my_bool = true;
let my_option = my_bool.to_option(MyObject{}); // true => MyObject{}, false => None
let my_result = my_bool.to_result(MyObject{}, MyError{}); // true => MyObject{}, false => MyError{}
</code>```

What is the shortest piece of code for doing that?

答:
bool.then_some() does this:

let my_bool = true;
let my_option = my_bool.then_some(MyObject{});
let my_result = my_bool.then_some(MyObject{}).ok_or(MyError{});
```

At the time of writing, this is still part of the experimental bool_to_option feature.

Update: As of Rust 1.62, this feature has been stabilized.

Body:
It seems there is no way of such one-line conversion using std.

I do not like this kind of verbosity:

match my_bool {
    true => Ok(()),
    false => Err(MyError::False),
}

I would like to use a one-liner, for example:

let my_bool = true;
let my_option = my_bool.to_option(MyObject{}); // true => MyObject{}, false => None
let my_result = my_bool.to_result(MyObject{}, MyError{}); // true => MyObject{}, false => MyError{}

What is the shortest piece of code for doing that?

Body:
bool.then_some() does this:

let my_bool = true;
let my_option = my_bool.then_some(MyObject{});
let my_result = my_bool.then_some(MyObject{}).ok_or(MyError{});

At the time of writing, this is still part of the experimental bool_to_option feature.

Update: As of Rust 1.62, this feature has been stabilized.


问:
Python Prepared Statements. Problems with SELECT IN
I'm having an issue with a prepared statement in Python I can't solve so far.

The Query, which should be execute is e.g.:

```<code> SELECT md5 FROM software WHERE software_id IN (1, 2, 4)
</code>```

So I tried to execute a Query like this:

```<code>software_id_string = "(2, 3, 4)"
cursor.execute("SELECT md5 FROM software WHERE software_id IN %s",
                software_id_string)
</code>```

The Problem is that there are '' added to the string --> '(2, 3, 4)', so that the Query will be:

```<code>SELECT md5 FROM software WHERE software_id IN ''(2, 3, 4)''
</code>```

I've also tried to rebuild the Script like this:

```<code>software_id_string = " 1 OR software_id = 2"
cursor.execute("SELECT md5 FROm software WHERE software_id = %s",
              software_id_string)
</code>```

This works only for the first id, which will be submitted (in this case 1), because the OR-part won't be interpeted as an SQL Statement...

Is there any possibility to fix the issues with the prepared statements?

答:
You need one placeholder for each item in your parameter list.

You can use string operations to get that part done:

Create one %s for each parameter, and

Join those together with a comma.

In the next step you can pass your two arguments to execute() as recommended in the DB-API documentation.

```<code>software_id_string = (1,2,4)
qry = '''SELECT md5
           FROM software
          WHERE software_id IN (%s)''' % ','.join(['%s']*len(software_id_string))
# // 'SELECT md5 FROM software WHERE software_id IN (%s,%s,%s)'
cursor.execute(qry, software_id_string)
</code>```

Body:
I'm having an issue with a prepared statement in Python I can't solve so far.

The Query, which should be execute is e.g.:

 SELECT md5 FROM software WHERE software_id IN (1, 2, 4)

So I tried to execute a Query like this:

software_id_string = "(2, 3, 4)"
cursor.execute("SELECT md5 FROM software WHERE software_id IN %s",
                software_id_string)

The Problem is that there are '' added to the string --> '(2, 3, 4)', so that the Query will be:

SELECT md5 FROM software WHERE software_id IN ''(2, 3, 4)''

I've also tried to rebuild the Script like this:

software_id_string = " 1 OR software_id = 2"
cursor.execute("SELECT md5 FROm software WHERE software_id = %s",
              software_id_string)

This works only for the first id, which will be submitted (in this case 1), because the OR-part won't be interpeted as an SQL Statement...

Is there any possibility to fix the issues with the prepared statements?

Body:
You need one placeholder for each item in your parameter list.

You can use string operations to get that part done:

Create one %s for each parameter, and

Join those together with a comma.

In the next step you can pass your two arguments to execute() as recommended in the DB-API documentation.

software_id_string = (1,2,4)
qry = '''SELECT md5
           FROM software
          WHERE software_id IN (%s)''' % ','.join(['%s']*len(software_id_string))
# // 'SELECT md5 FROM software WHERE software_id IN (%s,%s,%s)'
cursor.execute(qry, software_id_string)


问:
Resolved [org.springframework.beans.TypeMismatchException String : Failed to convert value of type 'java.lang.String' to required type
So I am building a site where someone puts a post and people can make comments to the post and people can make comments to those comments -- nested comments, if you will. Post creation: works, the initials responses/comments: works, but for some reason when I fill out the form add the nested comment, I get this error:

```<code>WARN 52874 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'codes.optiko.oc.model.Comment'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Adding my comment to a response'; nested exception is java.lang.NumberFormatException: For input string: "Addingmycommenttoaresponse"]
</code>```

The following is my bean/model:

```<code>package codes.optiko.oc.model;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(name = "comments")
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(nullable = false, columnDefinition = "text")
    private String comment;

//  foreign key: many comments to one user
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

//    foreign key: many comments to one response
    @ManyToOne
    @JoinColumn(name = "response_id")
    private Response response;

//    time stamps are sql-oriented
    @Column
    @CreationTimestamp
    private Timestamp createDate;

    @Column
    @UpdateTimestamp
    private Timestamp updateDate;

//************** CONSTRUCTORS ********************

//    empty constructor
    public Comment(){
    }

    public Comment(long id){
        this.id = id;
    }

    public Comment(long id, String comment){
        this.id = id;
        this.comment = comment;
    }

    public Comment(long id, String comment, User user){
        this.id = id;
        this.comment = comment;
        this.user = user;
    }

    public Comment(long id, String comment, User user, Response response){
        this.id = id;
        this.comment = comment;
        this.user = user;
        this.response = response;
    }

    public Comment(long id, String comment, User user, Response response, Timestamp createDate){
        this.id = id;
        this.comment = comment;
        this.user = user;
        this.response = response;
        this.createDate = createDate;
    }

    public Comment(long id, String comment, User user, Response response, Timestamp createDate, Timestamp updateDate){
        this.id = id;
        this.comment = comment;
        this.user = user;
        this.response = response;
        this.createDate = createDate;
        this.updateDate = updateDate;
    }

//************** GETTERS and SETTERS ********************

//    getters and setters
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getBody() {
        return comment;
    }

    public void setBody(String body) {
        this.comment = comment;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Timestamp getDate() {
        return createDate;
    }

    public void setDate(Timestamp date) {
        this.createDate = createDate;
    }

    public Timestamp getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Timestamp updateDate) {
        this.updateDate = updateDate;
    }

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }

    public Timestamp getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }
}

</code>```

The following is my controller (creating the comment):

```<code>@PostMapping("/posts/{post_id}/response/{response_id}/create-comment")
    public String createResponse(@PathVariable long post_id, @PathVariable long response_id, @ModelAttribute Comment comment) {
        Response response = responseRepo.getOne(response_id);
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        comment.setResponse(response);
        comment.setUser(user);
        comment.setCreateDate(new Timestamp(System.currentTimeMillis()));

        commentRepo.save(comment);

        return "redirect:/posts/" + post_id;
    }
</code>```

The following is my controller (For displaying a single post -- where people can add comments):

```<code>@GetMapping("/posts/{id}")
    public String viewPost(@PathVariable long id, Model model) {
        model.addAttribute("post", postRepo.getPostById(id));
        model.addAttribute("responses", responseRepo.findByPostId(id));
        model.addAttribute("response", new Response());
        model.addAttribute("comments", commentRepo.findByResponseId(id));
        model.addAttribute("comment", new Comment());
        return "posts/show";
    }
</code>```

The following is my view:

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

<head th:replace="partials/partials :: head ('Show Question')"></head>

<body>
<nav th:replace="partials/partials :: navbar"></nav>

<div class="container">
    <h2 th:text="${post.title}"></h2>
    <p style="padding-left: 2rem;" th:utext="${post.description}"></p>
    <p style="padding-left: 2rem;" th:text="${post.updateDate}"></p>
    <p style="padding-left: 2rem;" th:text="${post.user.username}"></p>

    <div th:unless="${#lists.isEmpty(responses)}">
        <h3>Responses:</h3>
        <!-- Display video responses -->
        <div class="post-div mb-3" th:each="res : ${responses}">
            <p th:text="'Posted by: ' + ${post.user.username}"></p>
            <div class="video-responsive" th:utext="${res.video}"></div>

            <!-- Display comments for video responses -->
            <div th:unless="${#lists.isEmpty(comments)}">
                <div class="post-div mb-3" th:each="com : ${comments}">
                    <p th:text="${com.comment}"></p>
                </div>
            </div>

            <!-- Add a comment -->
            <div sec:authorize="isAuthenticated()">
                <button class="add-comment btn btn-primary">Add a Comment</button>
                <form th:action="@{|/posts/${post.id}/response/${res.id}/create-comment|}" th:method="post" th:object="${comment}" class="comment-form">
                    <div class="form-group">
                        <label for="comment">Comment:</label>
                        <textarea class="form-control" id="comment" th:field="*{comment}"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit Comment</button>
                </form>
            </div>
            <div sec:authorize="!isAuthenticated()">
                <p class="font-weight-bold">Please <a href="/login">log in</a> or <a href="/register">register</a> to add a comment.</p>
            </div>
        </div>
    </div>

    <!-- Add a video response -->
    <div sec:authorize="isAuthenticated()">
        <button class="add-video-response btn btn-primary">Add a Video Response</button>
        <form th:action="@{|/posts/${post.id}/create-response|}" th:method="post" th:object="${response}" class="video-response-form">
            <div class="form-group">
                <label for="video">Video Embed URL:<br><span class="small">(YouTube, Vimeo, DailyMotion, etc...)</span></label>
                <textarea class="form-control" id="video" th:field="*{video}"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit Video Response</button>
        </form>
    </div>
    <div sec:authorize="!isAuthenticated()">
        <p class="font-weight-bold">Please <a href="/login">log in</a> or <a href="/register">register</a> to add a video response.</p>
    </div>
</div>

<standard_scripts th:replace="partials/partials :: footer">
</standard_scripts>
</body>
</html>
</code>```

I tried having it print out to the console whatever is sent to the controller when they submit, but it seems like it errors out before even doing anything. I have been trying to figure this out for hours now, and have exhausted all of what I know to try and resolve the issue.

Thank you in advanced!

答:
Note: Solution found in comments. Reposting as answer so it can be marked as solution

Change the name of the Field Comment#comment. There is most likely a mixup in the html where it sends the comment string back to the function instead of the Comment object

Body:
So I am building a site where someone puts a post and people can make comments to the post and people can make comments to those comments -- nested comments, if you will. Post creation: works, the initials responses/comments: works, but for some reason when I fill out the form add the nested comment, I get this error:

WARN 52874 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'codes.optiko.oc.model.Comment'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Adding my comment to a response'; nested exception is java.lang.NumberFormatException: For input string: "Addingmycommenttoaresponse"]

The following is my bean/model:

package codes.optiko.oc.model;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(name = "comments")
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(nullable = false, columnDefinition = "text")
    private String comment;

//  foreign key: many comments to one user
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

//    foreign key: many comments to one response
    @ManyToOne
    @JoinColumn(name = "response_id")
    private Response response;

//    time stamps are sql-oriented
    @Column
    @CreationTimestamp
    private Timestamp createDate;

    @Column
    @UpdateTimestamp
    private Timestamp updateDate;

//************** CONSTRUCTORS ********************

//    empty constructor
    public Comment(){
    }

    public Comment(long id){
        this.id = id;
    }

    public Comment(long id, String comment){
        this.id = id;
        this.comment = comment;
    }

    public Comment(long id, String comment, User user){
        this.id = id;
        this.comment = comment;
        this.user = user;
    }

    public Comment(long id, String comment, User user, Response response){
        this.id = id;
        this.comment = comment;
        this.user = user;
        this.response = response;
    }

    public Comment(long id, String comment, User user, Response response, Timestamp createDate){
        this.id = id;
        this.comment = comment;
        this.user = user;
        this.response = response;
        this.createDate = createDate;
    }

    public Comment(long id, String comment, User user, Response response, Timestamp createDate, Timestamp updateDate){
        this.id = id;
        this.comment = comment;
        this.user = user;
        this.response = response;
        this.createDate = createDate;
        this.updateDate = updateDate;
    }

//************** GETTERS and SETTERS ********************

//    getters and setters
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getBody() {
        return comment;
    }

    public void setBody(String body) {
        this.comment = comment;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Timestamp getDate() {
        return createDate;
    }

    public void setDate(Timestamp date) {
        this.createDate = createDate;
    }

    public Timestamp getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Timestamp updateDate) {
        this.updateDate = updateDate;
    }

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }

    public Timestamp getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }
}

The following is my controller (creating the comment):

@PostMapping("/posts/{post_id}/response/{response_id}/create-comment")
    public String createResponse(@PathVariable long post_id, @PathVariable long response_id, @ModelAttribute Comment comment) {
        Response response = responseRepo.getOne(response_id);
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        comment.setResponse(response);
        comment.setUser(user);
        comment.setCreateDate(new Timestamp(System.currentTimeMillis()));

        commentRepo.save(comment);

        return "redirect:/posts/" + post_id;
    }

The following is my controller (For displaying a single post -- where people can add comments):

@GetMapping("/posts/{id}")
    public String viewPost(@PathVariable long id, Model model) {
        model.addAttribute("post", postRepo.getPostById(id));
        model.addAttribute("responses", responseRepo.findByPostId(id));
        model.addAttribute("response", new Response());
        model.addAttribute("comments", commentRepo.findByResponseId(id));
        model.addAttribute("comment", new Comment());
        return "posts/show";
    }

The following is my view:

<!DOCTYPE html>

Responses:

                <button class="add-comment btn btn-primary">Add a Comment</button>
                <form th:action="@{|/posts/${post.id}/response/${res.id}/create-comment|}" th:method="post" th:object="${comment}" class="comment-form">

                        Comment:
                        <textarea class="form-control" id="comment" th:field="*{comment}"></textarea>

                    <button type="submit" class="btn btn-primary">Submit Comment</button>
                </form>

Please log in or register to add a comment.

        <button class="add-video-response btn btn-primary">Add a Video Response</button>
        <form th:action="@{|/posts/${post.id}/create-response|}" th:method="post" th:object="${response}" class="video-response-form">

                Video Embed URL:
(YouTube, Vimeo, DailyMotion, etc...)
                <textarea class="form-control" id="video" th:field="*{video}"></textarea>

            <button type="submit" class="btn btn-primary">Submit Video Response</button>
        </form>

Please log in or register to add a video response.

<standard_scripts th:replace="partials/partials :: footer">
</standard_scripts>

I tried having it print out to the console whatever is sent to the controller when they submit, but it seems like it errors out before even doing anything. I have been trying to figure this out for hours now, and have exhausted all of what I know to try and resolve the issue.

Thank you in advanced!


问:
How to embed youtube livestream chat
I'm trying to embed a youtube livestream chat onto a webpage on my website,

```<code><iframe allowfullscreen="" frameborder="0" height="270" src="https://www.youtube.com/live_chat?v=hHW1oY26kxQ&embed_domain=localhost" width="480"></iframe>
</code>```

I'm trying this, but the chat doesn't show up at all, if tried doing embeded domain using a real domain I own, but that doesn't work either.

答:
I'm not sure if you got this working in the end? We have managed to get it working on our site using this iframe, hope it helps you:

```<code><iframe src="https://www.youtube.com/live_chat?v=YourVidCodeHere&embed_domain=www.YourDomainHere.com"width="100%" height="600"></iframe>
</code>```

I hope that helps:) PS it doesn't work on mobile (YouTube said they have removed this feature from mobile), but it does work on desktop and tab.

Best wishes.

Title: How to embed youtube livestream chat

Body:
I'm trying to embed a youtube livestream chat onto a webpage on my website,

I'm trying this, but the chat doesn't show up at all, if tried doing embeded domain using a real domain I own, but that doesn't work either.

Body:
I'm not sure if you got this working in the end? We have managed to get it working on our site using this iframe, hope it helps you:

<iframe src="https://www.youtube.com/live_chat?v=YourVidCodeHere&embed_domain=www.YourDomainHere.com"width="100%" height="600"></iframe>

I hope that helps:) PS it doesn't work on mobile (YouTube said they have removed this feature from mobile), but it does work on desktop and tab.

Best wishes.


问:
Entry name 'AndroidManifest.xml' collided (Build failed after updating the android gradle plugin to 3.6.0)
I have recently updated the Android Studio from 3.5(stable) to 3.6(stable).

Then I saw the plugin update was also available, so I have updated the version of "com.android.tools.build:gradle" from 3.5.0 to 3.6.0 and also updated the gradle version to 5.6.4.

Now the problem starts when I try to build the project; it fails with message Entry name 'AndroidManifest.xml' collided

答:
According to the issue this happens when a JAR dependency contains an AndroidManifest.xml file.

For my project, the cause was this old dependency:

```<code>androidTestImplementation 'com.google.android:android-test:4.1.1.4'
</code>```

Which had a dependency on com.google.android:android:4.1.1.4 which had an AndroidManifest.xml in the JAR.

How I found it

I searched in $HOME\.gradle\caches\modules-2\files-2.1 for all .jar files containing an AndroidManifest.xml (I used Total Commander)

Then I cross referenced the results with the dependencies of my app.
To get the dependency tree use the Gradle tool window to run the Tasks/android/androidDependencies gradle task.

Body:
According to the issue this happens when a JAR dependency contains an AndroidManifest.xml file.

For my project, the cause was this old dependency:

androidTestImplementation 'com.google.android:android-test:4.1.1.4'

Which had a dependency on com.google.android:android:4.1.1.4 which had an AndroidManifest.xml in the JAR.

How I found it

I searched in $HOME\.gradle\caches\modules-2\files-2.1 for all .jar files containing an AndroidManifest.xml (I used Total Commander)

Then I cross referenced the results with the dependencies of my app.
To get the dependency tree use the Gradle tool window to run the Tasks/android/androidDependencies gradle task.


问:
function for the sum of all even numbers
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

```<code>function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")
</code>```

答:
The below code help you with minimum loops

function sumEven(s) {
  return s
    .split("")
    .filter(x => x % 2 === 0)
    .reduce((acc, val) => acc + Number(val), 0);
}

console.log(sumEven("112,sf34,4)-k)"));```

Body:
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")


问:
Connect over SSH using a .pem file
I would like to know how to connect over SSH using a .pem file to any server.

Currently I'm executing the following command:

```<code>ssh user@mydomain.example
</code>```

What option should I use?

答:
You can connect to a AWS ec-2 instance using the following commands.

```<code>chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip
</code>```

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

```<code>ssh -i mykey.pem ubuntu@your-ip
</code>```

Title: Connect over SSH using a .pem file

Body:
I would like to know how to connect over SSH using a .pem file to any server.

Currently I'm executing the following command:

ssh user@mydomain.example

What option should I use?

Body:
You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip


问:
How return type annotation change behavior of scala mixin in Twitter's Effective Scala
I have a very hard time understanding the following explanation from Twitter's Effective Scala https://twitter.github.io/effectivescala/:

While Scala allows these to be omitted, such annotations provide good documentation: this is especially important for public methods. Where a method is not exposed and its return type obvious, omit them. This is especially important when instantiating objects with mixins as the scala compiler creates singleton types for these. For example, make in:

```<code>trait Service
def make() = new Service {
  def getId = 123
}
</code>```

does not have a return type of Service; the compiler creates the refinement type Object with Service{def getId: Int}. Instead use an explicit annotation:

```<code>def make(): Service = new Service{}
</code>```

Now the author is free to mix in more traits without changing the public type of make, making it easier to manage backwards compatibility.

I am trying to understand how return type annotation here helps development with backward compatibility. Can anyone demonstrate with a concrete code example?

Thank you.

答:
It's actually really simple:

If you explicitly annotate the return type, the return type will forever what you said it would be.

If you don't annotate the return type, the return type will be inferred to whatever the type of the right-hand-side may be now.

So, whenever the type of the right-hand-side changes, in the first case, the return type will stay the same, in the second case, the return type will change, and thus (potentially) break existing users.

In this particular case, as mentioned, the return types in the first and second example are actually not the same:

def make(): Service = new Service {
  def getId = 123
}
```

<p>The return type of <code>make()</code> is <code>Service</code>.</p>

<pre class="lang-scala prettyprint-override"><code>def make() = new Service {
  def getId = 123
}
</code>```

The return type of make() is Object with Service.

If you now make a small change to your method, like e.g. extracting that method into a common trait:

trait IdGetter {
  def getId = 123
}
```

<p>and Refactoring your code to use that trait:</p>

<pre class="lang-scala prettyprint-override"><code>def make(): Service = new Service with IdGetter {}
</code>```

Now, in this case, the return type is still Service.

But in this case:

def make() = new Service with IdGetter {}
```

The return type is now Object with Service with IdGetter.

So, the return type has changed due to something which should have been a simple Extract Method Refactoring that is completely invisible to the user, but actually breaks downstream dependencies.

Body:
I have a very hard time understanding the following explanation from Twitter's Effective Scala https://twitter.github.io/effectivescala/:

While Scala allows these to be omitted, such annotations provide good documentation: this is especially important for public methods. Where a method is not exposed and its return type obvious, omit them. This is especially important when instantiating objects with mixins as the scala compiler creates singleton types for these. For example, make in:

trait Service
def make() = new Service {
  def getId = 123
}

does not have a return type of Service; the compiler creates the refinement type Object with Service{def getId: Int}. Instead use an explicit annotation:

def make(): Service = new Service{}

Now the author is free to mix in more traits without changing the public type of make, making it easier to manage backwards compatibility.

I am trying to understand how return type annotation here helps development with backward compatibility. Can anyone demonstrate with a concrete code example?

Thank you.

Body:
It's actually really simple:

If you explicitly annotate the return type, the return type will forever what you said it would be.

If you don't annotate the return type, the return type will be inferred to whatever the type of the right-hand-side may be now.

So, whenever the type of the right-hand-side changes, in the first case, the return type will stay the same, in the second case, the return type will change, and thus (potentially) break existing users.

In this particular case, as mentioned, the return types in the first and second example are actually not the same:

def make(): Service = new Service {
  def getId = 123
}

The return type of make() is Service.

def make() = new Service {
  def getId = 123
}

The return type of make() is Object with Service.

If you now make a small change to your method, like e.g. extracting that method into a common trait:

trait IdGetter {
  def getId = 123
}

and Refactoring your code to use that trait:

def make(): Service = new Service with IdGetter {}

Now, in this case, the return type is still Service.

But in this case:

def make() = new Service with IdGetter {}

The return type is now Object with Service with IdGetter.

So, the return type has changed due to something which should have been a simple Extract Method Refactoring that is completely invisible to the user, but actually breaks downstream dependencies.


问:
how to trace who has deleted Kubernetes PVC , deployment and POD's
Wonder if there is anyway to trace who has deleted the PVC , deployment or POD's .
I am running with issue where 2 of my Couchbase cluster(deployed in Onprem K8s cluster) with 3 nodes in each of them got deleted from 2 separate namespaces .

We are working in distributed framework with multiple people has access to same namespaces . curious if there is anyway to trace how this got deleted and wiped off database cluster.
the couchbase operator stay intact with POD in CrashLoopBackoff and not running state and no PVC , no deployment , no cluster found .

thanks

答:
You can use Auditing

Kubernetes auditing provides a security-relevant chronological set of records documenting the sequence of activities that have affected system by individual users, administrators or other components of the system. It allows cluster administrator to answer the following questions:

what happened?

when did it happen?

who initiated it?

on what did it happen?

where was it observed?

from where was it initiated?

to where was it going?


问:
( ! ) Parse error: syntax error, unexpected '[', expecting ')' in wamp
have this linecode

```<code>$panel_setting = new Setting();

$panel_setting = $panel_setting->where(["admin_id"=> $admin->id])->one();
</code>```

the php version on my local wamp server is 5.3.10  but when i run it on my local server then it gives this error

( ! ) Parse error: syntax error, unexpected '[', expecting ')'

I don't know how to solve it, please help.

答:
If I am correct [] syntax for arrays is available from php 5.4 and you have version 5.3.10.

Maybe you should write as this:

```<code>$panel_setting = $panel_setting->where(array("admin_id" => $admin->id))->one();
</code>```

Body:
have this linecode

$panel_setting = new Setting();

$panel_setting = $panel_setting->where(["admin_id"=> $admin->id])->one();

the php version on my local wamp server is 5.3.10  but when i run it on my local server then it gives this error

( ! ) Parse error: syntax error, unexpected '[', expecting ')'

I don't know how to solve it, please help.

Body:
If I am correct [] syntax for arrays is available from php 5.4 and you have version 5.3.10.

Maybe you should write as this:

$panel_setting = $panel_setting->where(array("admin_id" => $admin->id))->one();


问:
Pine tradingview: one time if until new event
I "made" my first Tradingview script, based on copying other public scripts. I can figure out most of it, except the last part. I am wondering whether it is possible to add an if-statement once, until an other specific event has taken place.

In the printscreen below I have an example. In my script I have a colored trendline and candles. I want to enter a short when trendline is red and candle is black (first green circle). But the series plot again bar color changes from white to black (red circles). I want to add alert only the first time (green circle) until a new event has taken place; when the trendline changes color (purple circle).

Chart example

```<code>BBperiod          = input(defval = 19,     title = "BB Period",    type = input.integer, minval       = 1)
BBdeviations      = input(defval = 1.00,     title = "BB Deviations",    type = input.float, minval = 0.1, step=0.05)
UseATRfilter      = input(defval = true, title = "ATR Filter",  type = input.bool)
ATRperiod         = input(defval = 7,     title = "ATR Period",    type = input.integer, minval = 1)

BBUpper=sma (close,BBperiod)+stdev(close, BBperiod)*BBdeviations
BBLower=sma (close,BBperiod)-stdev(close, BBperiod)*BBdeviations
//
TrendLine = 0.0
iTrend = 0.0
buy = 0.0
sell = 0.0
//
BBSignal = close>BBUpper? 1 : close<BBLower? -1 : 0
//
if BBSignal == 1 and UseATRfilter == 1
TrendLine:=low-atr(ATRperiod)
if TrendLine<TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 1
TrendLine:=high+atr(ATRperiod)
if TrendLine>TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 1
TrendLine:=TrendLine[1]
//
if BBSignal == 1 and UseATRfilter == 0
TrendLine:=low
if TrendLine<TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 0
TrendLine:=high
if TrendLine>TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 0
TrendLine:=TrendLine[1]
//
iTrend:=iTrend[1]
if TrendLine>TrendLine[1]
iTrend:=1
if TrendLine<TrendLine[1]
iTrend:=-1
//
buy:=iTrend[1]==-1 and iTrend==1 ? 1 : na
sell:=iTrend[1]==1 and iTrend==-1? 1 : na
//
plot(TrendLine, color=iTrend > 0?color.blue:color.red         ,style=plot.style_line,linewidth=2,transp=0,title="Trend Line")

//BarcolorT1
length = input(title="Length", type=input.integer, defval=50)
src_=input(close, title="Source", type=input.source)
mult=input(6.0, title="Mult")
barc=input(true, title="Use barcolor?")
plots=input(false, title="Show plots?")

r(src, n)=>
s = 0.0
for i = 0 to n-1
    s := s + ((n-(i*2+1))/2)*src[i]
x=s/(n*(n+1))
x

l=sma(low, length)
h=sma(high, length)
lr= l+mult*r(low, length)
hr= h+mult*r(high, length)

trend=0
trend:=src_ > lr and src_ > hr ? 1 : src_ < lr and src_ < hr ? -1 : trend[1]

long=0
short=0
long:= trend==1 and src_>h ? 1 : trend==-1 ? -1 : long[1]
short:= trend==-1 and src_<l ? 1 : trend==1 ? -1 : short[1]

barcolor(barc? (long>0? color.green : short>0? color.black : trend>0? color.white: trend<0 ?     color.white : color.blue) : na)

//plot shape
data = short!=short[1] and short==1 and iTrend < 0
plotshape(data, style=shape.xcross)
</code>```

答:
You can achieve your goal with an extra flag that will be activated and deactivated on required events. Here is the code:

```<code>var active = false

// Activation
active := active or data

// Deactivation
if nz(iTrend[1]) <= 0 and iTrend > 0
    active := false

activated = not nz(active[1], false) and active

plotshape(activated, style=shape.triangledown, color=color.red, size=size.small, location=location.belowbar)
</code>```

Add it to the end of your script and it will show red triangles when the trend line is red and bar color changes from white to black for the first time.

Body:
I "made" my first Tradingview script, based on copying other public scripts. I can figure out most of it, except the last part. I am wondering whether it is possible to add an if-statement once, until an other specific event has taken place.

In the printscreen below I have an example. In my script I have a colored trendline and candles. I want to enter a short when trendline is red and candle is black (first green circle). But the series plot again bar color changes from white to black (red circles). I want to add alert only the first time (green circle) until a new event has taken place; when the trendline changes color (purple circle).

Chart example

BBperiod          = input(defval = 19,     title = "BB Period",    type = input.integer, minval       = 1)
BBdeviations      = input(defval = 1.00,     title = "BB Deviations",    type = input.float, minval = 0.1, step=0.05)
UseATRfilter      = input(defval = true, title = "ATR Filter",  type = input.bool)
ATRperiod         = input(defval = 7,     title = "ATR Period",    type = input.integer, minval = 1)

BBUpper=sma (close,BBperiod)+stdev(close, BBperiod)*BBdeviations
BBLower=sma (close,BBperiod)-stdev(close, BBperiod)*BBdeviations
//
TrendLine = 0.0
iTrend = 0.0
buy = 0.0
sell = 0.0
//
BBSignal = close>BBUpper? 1 : close<BBLower? -1 : 0
//
if BBSignal == 1 and UseATRfilter == 1
TrendLine:=low-atr(ATRperiod)
if TrendLine<TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 1
TrendLine:=high+atr(ATRperiod)
if TrendLine>TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 1
TrendLine:=TrendLine[1]
//
if BBSignal == 1 and UseATRfilter == 0
TrendLine:=low
if TrendLine<TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 0
TrendLine:=high
if TrendLine>TrendLine[1]
    TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 0
TrendLine:=TrendLine[1]
//
iTrend:=iTrend[1]
if TrendLine>TrendLine[1]
iTrend:=1
if TrendLine<TrendLine[1]
iTrend:=-1
//
buy:=iTrend[1]==-1 and iTrend==1 ? 1 : na
sell:=iTrend[1]==1 and iTrend==-1? 1 : na
//
plot(TrendLine, color=iTrend > 0?color.blue:color.red         ,style=plot.style_line,linewidth=2,transp=0,title="Trend Line")

//BarcolorT1
length = input(title="Length", type=input.integer, defval=50)
src_=input(close, title="Source", type=input.source)
mult=input(6.0, title="Mult")
barc=input(true, title="Use barcolor?")
plots=input(false, title="Show plots?")

r(src, n)=>
s = 0.0
for i = 0 to n-1
    s := s + ((n-(i*2+1))/2)*src[i]
x=s/(n*(n+1))
x

l=sma(low, length)
h=sma(high, length)
lr= l+mult*r(low, length)
hr= h+mult*r(high, length)

trend=0
trend:=src_ > lr and src_ > hr ? 1 : src_ < lr and src_
h ? 1 : trend==-1 ? -1 : long[1]
short:= trend==-1 and src_<l ? 1 : trend==1 ? -1 : short[1]

barcolor(barc? (long>0? color.green : short>0? color.black : trend>0? color.white: trend<0 ?     color.white : color.blue) : na)

//plot shape
data = short!=short[1] and short==1 and iTrend < 0
plotshape(data, style=shape.xcross)

Body:
You can achieve your goal with an extra flag that will be activated and deactivated on required events. Here is the code:

var active = false

// Activation
active := active or data

// Deactivation
if nz(iTrend[1]) <= 0 and iTrend > 0
    active := false

activated = not nz(active[1], false) and active

plotshape(activated, style=shape.triangledown, color=color.red, size=size.small, location=location.belowbar)

Add it to the end of your script and it will show red triangles when the trend line is red and bar color changes from white to black for the first time.


问:
Error when check out code from SVN server
I have SVN server to control source code version

I can checkout my code when I use TortoiseSVN or use command line.

Here is some information:

SVN server

Checkout code by using TortoiseSVN in Windows

Chechout code by using commandline in Ubuntu (Web server)

I use this command

```<code>root@controller1:/var/www/onecloud# svn co --force --username hoang --password gcsvn123 http://203.162.141.79/onecloud /var/www/onecloud
</code>```

Then I write PHP code to update version auto (don't use TortoiseSVN or use command line).

```<code>error_reporting(-1);
ini_set('display_errors', 'On');
$result= exec('svn co --force --username hoang --password gcsvn123 http://203.162.141.79/onecloud /var/www/onecloud 2>&1',$out);
print_r($out);
</code>```

But when I run my code, it show this error:

```<code>Array ( [0] => svn: E155004: Run 'svn cleanup' to remove locks (type 'svn help cleanup' for details) [1] => svn: E155004: Working copy '/var/www/onecloud' locked [2] => svn: E200031: sqlite[S8]: attempt to write a readonly database [3] => svn: E200031: Additional errors: [4] => svn: E200031: sqlite[S8]: attempt to write a readonly database )
</code>```

I have run command line svn cleanup, but it seem doesn't work.

Not:

```<code>My SVN server is 203.162.141.79
My web server is 203.162.141.26
</code>```

答:
I found directory .svn in my code after checkout.

When I use these two commands:

```<code>chmod -R 777 .svn/
chown www-data:www-data .svn/
</code>```

it works.

Body:
I have SVN server to control source code version

I can checkout my code when I use TortoiseSVN or use command line.

Here is some information:

SVN server

Checkout code by using TortoiseSVN in Windows

Chechout code by using commandline in Ubuntu (Web server)

I use this command

root@controller1:/var/www/onecloud# svn co --force --username hoang --password gcsvn123 http://203.162.141.79/onecloud /var/www/onecloud

Then I write PHP code to update version auto (don't use TortoiseSVN or use command line).

error_reporting(-1);
ini_set('display_errors', 'On');
$result= exec('svn co --force --username hoang --password gcsvn123 http://203.162.141.79/onecloud /var/www/onecloud 2>&1',$out);
print_r($out);

But when I run my code, it show this error:

Array ( [0] => svn: E155004: Run 'svn cleanup' to remove locks (type 'svn help cleanup' for details) [1] => svn: E155004: Working copy '/var/www/onecloud' locked [2] => svn: E200031: sqlite[S8]: attempt to write a readonly database [3] => svn: E200031: Additional errors: [4] => svn: E200031: sqlite[S8]: attempt to write a readonly database )

I have run command line svn cleanup, but it seem doesn't work.

Not:

My SVN server is 203.162.141.79
My web server is 203.162.141.26

Body:
I found directory .svn in my code after checkout.

When I use these two commands:

chmod -R 777 .svn/
chown www-data:www-data .svn/

it works.


问:
Azure service bus topic can use for private message
In contrast with Azure Service Bus Queues that allow us to deliver one-to-one, Azure Service Bus Topics allow us to deliver messages one-to-many. This means that we can deliver the same message to multiple clients that are called subscribers. This messaging system is basically an ESB system (Enterprise Service Bus), allowing to have a “publish/subscribe” communication.

I have multiple clients and i have created topic for each client. Whenever server send message to client, it just put message into client topic. Is it possible if i create single topic and multiple subscriber so that every client just listen only its message?

答:
Is it possible if i create single topic and multiple subscriber so
  that every client just listen only its message?

It is certainly possible to do so. What you have to do is configure topic filtering rules so that each subscription gets the message based on the filter criteria defined for them. You can learn more about the filtering rules here: https://learn.microsoft.com/en-us/azure/service-bus-messaging/topic-filters.

From this link:

Subscribers can define which messages they want to receive from a
  topic. These messages are specified in the form of one or more named
  subscription rules. Each rule consists of a condition that selects
  particular messages and an action that annotates the selected message.
  For each matching rule condition, the subscription produces a copy of
  the message, which may be differently annotated for each matching
  rule.


问:
Perl - Convert IPv4 address to hexadecimal
I'm trying to write a perl script that asks user to input their ipv4 address and convert it into hexadecimals.
For example, user enters "130.130.68.1" which will return "0x82.0x82.0x44.0x01". How can i do this?</p>

答:
0x82.0x82.0x44.0x01:

```<code>my $hex =
   join ".",
      map { sprintf "0x%02X", $_ }
         split /\./,
            $ip;
</code>```

or

```<code>my $hex = $ip =~ s/[^.]+/ sprintf "0x%02X", $& /reg;
</code>```

That said, 0x82.0x82.0x44.0x01 is a really weird way of writing 8282260116, the 32-bit number 130.130.68.1 represents.

0x82824401:

```<code>use Socket qw( inet_aton );

my $hex = '0x' . unpack('H*', inet_aton('130.130.68.1'));
</code>```

0x82.82.44.01:

```<code>use Socket qw( inet_aton );

my $hex = '0x' . join('.', unpack('(H2)*', inet_aton('130.130.68.1')));
</code>```

Both of these also with domain names.

Body:
0x82.0x82.0x44.0x01:

my $hex =
   join ".",
      map { sprintf "0x%02X", $_ }
         split /\./,
            $ip;

or

my $hex = $ip =~ s/[^.]+/ sprintf "0x%02X", $& /reg;

That said, 0x82.0x82.0x44.0x01 is a really weird way of writing 8282260116, the 32-bit number 130.130.68.1 represents.

0x82824401:

use Socket qw( inet_aton );

my $hex = '0x' . unpack('H*', inet_aton('130.130.68.1'));

0x82.82.44.01:

use Socket qw( inet_aton );

my $hex = '0x' . join('.', unpack('(H2)*', inet_aton('130.130.68.1')));

Both of these also with domain names.


问:
VS code runs python with no errors only if started from conda terminal
One of the projects that I work on in Python is pretty big and uses a lot of libraries.
I started developing it in Spyder then switched to VS Code.
I also use conda environment.

The problem is with VS Code only: when I open VS Code itself and try to run the project - I get all kinds of import errors.

However, if I open the conda terminal first and just type "code" in it and execute it - the VS Code opens, I can select my project and everything runs just fine, no errors.

In both cases the environment is the same, I did the Ctrl+Shift+P to select it, plus it shows as selected in the bottom left corner anyway. It's the default env.

How can I fix this so I don't have to start VS Code from conda terminal each time?

答:
I found what the problem was so I'll just leave it here in case it may happen to someone else.

My VS Code was using Powershell as the default shell, even though the input was right with the correct conda env selected (the base in my case), even with running

```<code>conda activate base
</code>```

command to ensure it, it would still somehow mess up and complain about missing imports

So the solution was to set the default shell in VSC to regular Windows cmd.exe - that was the only needed change

Body:
I found what the problem was so I'll just leave it here in case it may happen to someone else.

My VS Code was using Powershell as the default shell, even though the input was right with the correct conda env selected (the base in my case), even with running

conda activate base

command to ensure it, it would still somehow mess up and complain about missing imports

So the solution was to set the default shell in VSC to regular Windows cmd.exe - that was the only needed change


问:
Deploy VueJS App in a sub-directory or sub-path
I’m experiencing problems deploying a Vue JS app built using the Webpack CLi to work.

If uploaded in a root directory everything renders fine, but inside a subfolder, all the links break.

I want deploy VueJS App to this url :
https://event.domain.net/webinar

I have added publicPath in vue.config.js :

```<code>var path = require(‘path’)
module.exports = {
   publicPath: ‘./’
}
</code>```

But only the css and js folders point to the path /webinar.

For assets, fonts and others still point to the subdomain https://event.domain.net.

CSS and JS point to path /webinar

Asset, fonts still point to subdomain https://event.domain.net/

Console

答:
use value of publicPath as /webinar that should work.

More details are here https://cli.vuejs.org/config/#publicpath

you can configure publicPath even based on environment.

Body:
I’m experiencing problems deploying a Vue JS app built using the Webpack CLi to work.

If uploaded in a root directory everything renders fine, but inside a subfolder, all the links break.

I want deploy VueJS App to this url :
https://event.domain.net/webinar

I have added publicPath in vue.config.js :

var path = require(‘path’)
module.exports = {
   publicPath: ‘./’
}

But only the css and js folders point to the path /webinar.

For assets, fonts and others still point to the subdomain https://event.domain.net.

CSS and JS point to path /webinar

Asset, fonts still point to subdomain https://event.domain.net/

Console


问:
Error when trying to run RandomForestClassifier with Pipieline and GridSearch
I am trying to run a RandomForest Classifier using Pipeline, GridSerach and CV

I am getting an error when I fit the data. I am not sure how to fix it.
I found a similar Question with the solution https://stackoverflow.com/a/34890246/9592484 but didn't work for me

Will appreciate any help on this.

My code is:

```<code> column_trans = make_column_transformer((OneHotEncoder(), ['CategoricalData']),
 remainder='passthrough')
 RF = RandomForestClassifier()
 pipe = make_pipeline(column_trans, RF)

 # Set grid search params
 grid_params = [{'randomforestclassifier_criterion': ['gini', 'entropy'],
 'randomforestclassifier_min_samples_leaf': [5,10,20,30,50,80,100],
 'randomforestclassifier_max_depth': [3,4,6,8,10],
 'randomforestclassifier_min_samples_split': [2,4,6,8,10]}]

 # Construct grid search
 gs = GridSearchCV(estimator = pipe,
 param_grid = grid_params,
 scoring='accuracy',
 cv=5)

 gs.fit(train_features, train_target)  ----This is where I get an error

ValueError: Invalid parameter randomforestclassifier_criterion for estimator Pipeline(steps=[('columntransformer',
             ColumnTransformer(remainder='passthrough',
                               transformers=[('onehotencoder',
                                              OneHotEncoder(),
                                              ['saleschanneltypeid'])])),
            ('randomforestclassifier', RandomForestClassifier())]). Check the list of available parameters with `estimator.get_params().keys()`.
</code>```

答:
The make_pipeline utility function derives step names from transformer/estimator class names. For example, the RandomForestClassifier is mapped to randomforestclassifier step.

Please adjust your grid search parameter prefixes acordingly (ie. from RF to randomforestclassifier). For example, RF__criterion should become randomforestclassifier__criterion.

Body:
I am trying to run a RandomForest Classifier using Pipeline, GridSerach and CV

I am getting an error when I fit the data. I am not sure how to fix it.
I found a similar Question with the solution https://stackoverflow.com/a/34890246/9592484 but didn't work for me

Will appreciate any help on this.

My code is:

 column_trans = make_column_transformer((OneHotEncoder(), ['CategoricalData']),
 remainder='passthrough')
 RF = RandomForestClassifier()
 pipe = make_pipeline(column_trans, RF)

 # Set grid search params
 grid_params = [{'randomforestclassifier_criterion': ['gini', 'entropy'],
 'randomforestclassifier_min_samples_leaf': [5,10,20,30,50,80,100],
 'randomforestclassifier_max_depth': [3,4,6,8,10],
 'randomforestclassifier_min_samples_split': [2,4,6,8,10]}]

 # Construct grid search
 gs = GridSearchCV(estimator = pipe,
 param_grid = grid_params,
 scoring='accuracy',
 cv=5)

 gs.fit(train_features, train_target)  ----This is where I get an error

ValueError: Invalid parameter randomforestclassifier_criterion for estimator Pipeline(steps=[('columntransformer',
             ColumnTransformer(remainder='passthrough',
                               transformers=[('onehotencoder',
                                              OneHotEncoder(),
                                              ['saleschanneltypeid'])])),
            ('randomforestclassifier', RandomForestClassifier())]). Check the list of available parameters with `estimator.get_params().keys()`.


问:
Parent - Child relation Child ID
I have the following classes

```<code>public class Order
{
    public int OrderID {get;set;}
    /*...
    Some other properties
    ...*/
    public ICollection<OrderDetail> Details {get;set;}
}

public class OrderDetail
{
    public int OrderID {get;set;}
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OrderDetailID {get;set;}
    /*...
    Some other properties
    ...*/

    public Order Order {get;set;}
}
</code>```

I have also specified the relation in the OnModelCreation like below:

```<code>modelBuilder.Entity<OrderDetail>().HasKey(detail => new { detail.OrderID, detail.OrderDetailID});
modelBuilder.Entity<OrderDetail>().HasOne(detail => detail.Order)
                                            .WithMany(order => order.Details)
                                            .HasForeignKey(detail => detail.OrderID).OnDelete(DeleteBehavior.Cascade);
</code>```

Everything works without any errors.

My problem is that in this case when I create an order with details the OrderDetailID is incremented for all the details and I am getting the below in the database.

```
OrderID OrderDetailID ....
17      19              3   15.0000 15.0000 EA
17      20              3   15.0000 15.0000 EA
18      21              1   25.0000 0.0000  EA
18      22              1   25.0000 0.0000  EA
```

I understand that the way OrderDetailID works is corresponding to the configuration in my code. But my problem is that I need to get the following picture in the database:

```
OrderID OrderDetailID ....
17      1               3   15.0000 15.0000 EA
17      2               3   15.0000 15.0000 EA
18      1               1   25.0000 0.0000  EA
18      2               1   25.0000 0.0000  EA
```

In other words I need the OrderDetailID to be reset to 1 for every new order.

I can't find any configuration option in Entity Framework to get this to work in the way that I need.

Thank you in advance.

答:
After long reviews I ended up adding the below script to the Migration.

```<code>migrationBuilder.Sql(@"CREATE OR ALTER TRIGGER [DetailLineNbr] ON Details AFTER INSERT AS
                        BEGIN
                        declare @minLineNbr int;
                        declare @maxExistingLineNbr int;
                        SET @minLineNbr = (SELECT MIN(DetailID) FROM inserted);
                        SET @maxExistingLineNbr = ISNULL((SELECT MAX(LineNbr) FROM Details WHERE Details.OrderID in (select inserted.OrderID from inserted) AND Details.DetailID not in (select inserted.DetailID from inserted)),0);
                        UPDATE Details
                        SET LineNbr = Details.DetailID - @minLineNbr + @maxExistingLineNbr + 1
                        WHERE Details.OrderID in (select inserted.OrderID from inserted) AND Details.DetailID in (select inserted.DetailID from inserted)
                        END");
</code>```

The solution suggested by David Edel works only for single line inserts.
Unfortunately, in my case almost all inserts where multiple line inserts.

Title: Parent - Child relation Child ID

Body:
I have the following classes

public class Order
{
    public int OrderID {get;set;}
    /*...
    Some other properties
    ...*/
    public ICollection<OrderDetail> Details {get;set;}
}

public class OrderDetail
{
    public int OrderID {get;set;}
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OrderDetailID {get;set;}
    /*...
    Some other properties
    ...*/

    public Order Order {get;set;}
}

I have also specified the relation in the OnModelCreation like below:

modelBuilder.Entity<OrderDetail>().HasKey(detail => new { detail.OrderID, detail.OrderDetailID});
modelBuilder.Entity<OrderDetail>().HasOne(detail => detail.Order)
                                            .WithMany(order => order.Details)
                                            .HasForeignKey(detail => detail.OrderID).OnDelete(DeleteBehavior.Cascade);

Everything works without any errors.

My problem is that in this case when I create an order with details the OrderDetailID is incremented for all the details and I am getting the below in the database.

OrderID OrderDetailID ....
17      19              3   15.0000 15.0000 EA
17      20              3   15.0000 15.0000 EA
18      21              1   25.0000 0.0000  EA
18      22              1   25.0000 0.0000  EA

I understand that the way OrderDetailID works is corresponding to the configuration in my code. But my problem is that I need to get the following picture in the database:

OrderID OrderDetailID ....
17      1               3   15.0000 15.0000 EA
17      2               3   15.0000 15.0000 EA
18      1               1   25.0000 0.0000  EA
18      2               1   25.0000 0.0000  EA

In other words I need the OrderDetailID to be reset to 1 for every new order.

I can't find any configuration option in Entity Framework to get this to work in the way that I need.

Thank you in advance.

Body:
After long reviews I ended up adding the below script to the Migration.

migrationBuilder.Sql(@"CREATE OR ALTER TRIGGER [DetailLineNbr] ON Details AFTER INSERT AS
                        BEGIN
                        declare @minLineNbr int;
                        declare @maxExistingLineNbr int;
                        SET @minLineNbr = (SELECT MIN(DetailID) FROM inserted);
                        SET @maxExistingLineNbr = ISNULL((SELECT MAX(LineNbr) FROM Details WHERE Details.OrderID in (select inserted.OrderID from inserted) AND Details.DetailID not in (select inserted.DetailID from inserted)),0);
                        UPDATE Details
                        SET LineNbr = Details.DetailID - @minLineNbr + @maxExistingLineNbr + 1
                        WHERE Details.OrderID in (select inserted.OrderID from inserted) AND Details.DetailID in (select inserted.DetailID from inserted)
                        END");

The solution suggested by David Edel works only for single line inserts.
Unfortunately, in my case almost all inserts where multiple line inserts.


问:
What is 'Currying'?
I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)</p>

答:
Currying is one of the higher-order functions of Java Script.

Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.

Confused?

Let see an example,

function add(a,b)
    {
        return a+b;
    }
add(5,6);
```

<p>This is similar to the following currying function,</p>

<pre class="lang-js prettyprint-override"><code>function add(a)
    {
        return function(b){
            return a+b;
        }
    }
var curryAdd = add(5);
curryAdd(6);
</code>```

So what does this code means?

Now read the definition again,

Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.

Still, Confused?
Let me explain in deep!

When you call this function,

var curryAdd = add(5);
```

<p>It will return you a function like this,</p>

<pre class="lang-js prettyprint-override"><code>curryAdd=function(y){return 5+y;}
</code>```

So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script.
So come back to the currying,

This line will pass the second argument to the curryAdd function.

curryAdd(6);
```

<p>which in turns results,</p>

<pre class="lang-js prettyprint-override"><code>curryAdd=function(6){return 5+6;}
// Which results in 11
</code>```

Hope you understand the usage of currying here.
So, Coming to the advantages,

Why Currying?

It makes use of code reusability.
Less code, Less Error.
You may ask how it is less code?

I can prove it with ECMA script 6 new feature arrow functions.

Yes! ECMA 6, provide us with the wonderful feature called arrow functions,

function add(a)
    {
        return function(b){
            return a+b;
        }
    }
```

<p>With the help of the arrow function, we can write the above function as follows,</p>

<pre class="lang-js prettyprint-override"><code>x=>y=>x+y
</code>```

Cool right?

So, Less Code and Fewer bugs!!

With the help of these higher-order function one can easily develop a bug-free code.

I challenge you!

Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.

Thanks, Have a nice day!

OwnerDisplayName: Ben

Title: What is 'Currying'?

LastEditorDisplayName: Turbulent Intellect

Body:
Currying is one of the higher-order functions of Java Script.

Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.

Confused?

Let see an example,

function add(a,b)
    {
        return a+b;
    }
add(5,6);

This is similar to the following currying function,

function add(a)
    {
        return function(b){
            return a+b;
        }
    }
var curryAdd = add(5);
curryAdd(6);

So what does this code means?

Now read the definition again,

Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.

Still, Confused?
Let me explain in deep!

When you call this function,

var curryAdd = add(5);

It will return you a function like this,

curryAdd=function(y){return 5+y;}

So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script.
So come back to the currying,

This line will pass the second argument to the curryAdd function.

curryAdd(6);

which in turns results,

curryAdd=function(6){return 5+6;}
// Which results in 11

Hope you understand the usage of currying here.
So, Coming to the advantages,

Why Currying?

It makes use of code reusability.
Less code, Less Error.
You may ask how it is less code?

I can prove it with ECMA script 6 new feature arrow functions.

Yes! ECMA 6, provide us with the wonderful feature called arrow functions,

function add(a)
    {
        return function(b){
            return a+b;
        }
    }

With the help of the arrow function, we can write the above function as follows,

x=>y=>x+y

Cool right?

So, Less Code and Fewer bugs!!

With the help of these higher-order function one can easily develop a bug-free code.

I challenge you!

Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.

Thanks, Have a nice day!


问:
MS Build dual assemblies for x86 and x64 builds and TeamCity
I've recently had a few issues when trying to run SQLLite powered in-memory repository mock (Repository pattern) with Fluent Nhibernate. When I ran the tests against a (TeamCity) build agent on Windows Server 2008 the tests were failing with unable to load System.Data.SQLite exceptions.

After some fiddling I remembered there was a x64 version of System.Data.SQLite in the downloaded SqlLite binaries. Dropping that next to unit tested assembly and running tests through NUnit UI worked and no longer threw any exceptions.

My question is: is it possible to tell the build something like: when compiling on x64 system, reference the binary from folder B and when on x86 system, from folder A? So a conditional reference include?

The only other option I can think of right now is to limit TeamCity build agents to be x64 and use a command line script build step to overwrite assembly in bin\Release folder in between build finishing ant unit tests running. Development environments are all x86 so that's the root of the issue.

Writing this there is one other option - but a messy one - modify the project file after svn build source is downloaded and before the build runs using a script.

答:
References can be made conditional in your project file (I'm making up the details of the references below).</p>

```<code><Reference
  Include="SQLLite"
  Condition="'$(Platform)' == 'x64'">
  <HintPath>PathTo/x64/SqlLite.dll"</HintPath>
</Reference>
<Reference
  Include="SQLLite"
  Condition="'$(Platform)' == 'Win32'">
  <HintPath>PathTo/Win32/SqlLite.dll"</HintPath>
</Reference>
</code>```

Body:
References can be made conditional in your project file (I'm making up the details of the references below).

<Reference
  Include="SQLLite"
  Condition="'$(Platform)' == 'x64'">
  <HintPath>PathTo/x64/SqlLite.dll"</HintPath>
</Reference>
<Reference
  Include="SQLLite"
  Condition="'$(Platform)' == 'Win32'">
  <HintPath>PathTo/Win32/SqlLite.dll"</HintPath>
</Reference>


问:
Changing individual image sources with jQuery
I need to change the image sources of multiple individual images on a site containing many. They do not have IDs I could use to identify each individual image, which is why I need to make the changes based on the current source each image has.

I have not managed to find a working solution to this.

The html looks like this:

```<code><img class="card-image" alt="" src="www.url.com/12987237857.an-individual-photo.jpg">
</code>```

Ive found and tried many variations of this but have not found a way to make this change only a specific img src:

```<code>  $('.card-image').attr('src', $('.card-image').attr('src').replace('original', 'new'));
</code>```

I have done something similar before with hrefs and this worked perfectly:

```<code> $('a[href$="partOfOldURL"]').attr('href', 'newURL');
</code>```

Could someone help me out? Thank you in advance!

答:
I suggest using the jQuery.each function.

$(document).ready(function(){
  $('.card-image').each(function(){
    $(this).attr('src', $(this).attr('src').replace('original', 'new'));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="card-image" alt="" src="https://via.placeholder.com/150?text=original+1234">
<img class="card-image" alt="" src="https://via.placeholder.com/150?text=original+5678"></code>```

Body:
I need to change the image sources of multiple individual images on a site containing many. They do not have IDs I could use to identify each individual image, which is why I need to make the changes based on the current source each image has.

I have not managed to find a working solution to this.

The html looks like this:

Ive found and tried many variations of this but have not found a way to make this change only a specific img src:

  $('.card-image').attr('src', $('.card-image').attr('src').replace('original', 'new'));

I have done something similar before with hrefs and this worked perfectly:

 $('a[href$="partOfOldURL"]').attr('href', 'newURL');

Could someone help me out? Thank you in advance!

Body:
I suggest using the jQuery.each function.

$(document).ready(function(){
  $('.card-image').each(function(){
    $(this).attr('src', $(this).attr('src').replace('original', 'new'));
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="card-image" alt="" src="https://via.placeholder.com/150?text=original+1234">
<img class="card-image" alt="" src="https://via.placeholder.com/150?text=original+5678">