问:
How to read data set that have lists
In the dataset I'm working on,
some columns are containing List of dictionaries

below is an example of a column describes genres of a movie

The problem is when I use pd.read_csv() this column datatype will be string not list which makes data preprocessing harder.

how can i read these columns as list not a string?

答:
Use parameter 'converters' to decide special column's type in function 'pd.read_csv'. It's like:

df = pd.read_csv('filename.csv', converters={'Code':str})
```

It will force column 'Code' to be readed as type string.
Maybe it will help you, but I just have a experience about type transform from 'float' to 'str',so I can't guarantee it works.

Title: How to read data set that have lists

Body:
Use parameter 'converters' to decide special column's type in function 'pd.read_csv'. It's like:

df = pd.read_csv('filename.csv', converters={'Code':str})

It will force column 'Code' to be readed as type string.
Maybe it will help you, but I just have a experience about type transform from 'float' to 'str',so I can't guarantee it works.


来源: stackexchange

问:
Angular Service not a global singleton
I was under the impression that a Angular Service is a Singleton, but have recently discovered, or atleast it seems, that the service is only a singleton to the instance of the component and the component's children.

Consider the following code:

```<code>const CACHE_REFRESH_INTERVAL = 1800000; //30 minutes
const CACHE_SIZE = 1;

const COMPANY_CACHE_KEY = 'company_cache_key';

@Injectable({
  providedIn: "root"
})
export class CompanyService {

  private companyCache: Map<string, Observable<any>> = new Map();

  constructor(private httpClient: HttpClient) { }

  public getAllCompanies(): Observable<CompanyViewModel[]> {
    if (!this.companyCache[COMPANY_CACHE_KEY]) {
      const timer$ = timer(0, CACHE_REFRESH_INTERVAL);
      this.companyCache[COMPANY_CACHE_KEY] = timer$.pipe(
        switchMap(_ => this.getAllCompaniesHttpRequest()),
        shareReplay(CACHE_SIZE),
        refCount(),
        catchError(err => this.companyCache[COMPANY_CACHE_KEY] = undefined) //prevents storing error in cache
      );
    }
    return this.companyCache[COMPANY_CACHE_KEY];
  }

  private getAllCompaniesHttpRequest(): Observable<CompanyViewModel[]> {
    return this.httpClient.get<CompanyViewModel[]>(environment.endpoints.company.getAllCompanies());
  }
}
</code>```

Let's say, ComponentA gets this service injected through the component's instructor.  When ComponentA calls the CompanyService.getAllCompanies() method, the results will be stored in companyCache.  Now the user navigates to a new URL, ComponentA get destroyed, as well as the instance of the service.  Navigate back to ComponentA, and a new instance of the service is injected, and companyCache is once again empty.

Is my assumption correct?  Can I make a service a singleton accross the entire application?

答:
Services are a singleton at the level of the app.

Take this simple stackblitz demo

I have a trivial service that sets a random number from the constructor.

```<code>@Injectable({
  providedIn: 'root'
})
export class Service {
  constructor() {
    this.rnd = Math.random();
  }

  private rnd: number;

  getRand(): number {
    return this.rnd;
  }
}
</code>```

I have a component structure like this with the service being injected into 2 "child" components (not actual children, but that's the pattern of navigation I have set up):

```<code>|- home

|- component a
|--  inject service

|- component b
|--  inject service
</code>```

When navigating from home to component a, it will display the random number that was set in the constructor of the service.

When I navigate back to home (check the console to see that component a was destroyed), and then navigate to component b, it will display the random number that was set in the constructor of the service.

For the lifetime of the app, the random number remains the same. To me this proves that even when a service isn't "in scope", it is still in memory.

Not to mention that the docs talk about this on the very first line:

A singleton service is a service for which only one instance exists in an app.

ContentLicense: CC BY-SA 4.0

Title: Angular Service not a global singleton

Body:
I was under the impression that a Angular Service is a Singleton, but have recently discovered, or atleast it seems, that the service is only a singleton to the instance of the component and the component's children.

Consider the following code:

const CACHE_REFRESH_INTERVAL = 1800000; //30 minutes
const CACHE_SIZE = 1;

const COMPANY_CACHE_KEY = 'company_cache_key';

@Injectable({
  providedIn: "root"
})
export class CompanyService {

  private companyCache: Map<string, Observable<any>> = new Map();

  constructor(private httpClient: HttpClient) { }

  public getAllCompanies(): Observable<CompanyViewModel[]> {
    if (!this.companyCache[COMPANY_CACHE_KEY]) {
      const timer$ = timer(0, CACHE_REFRESH_INTERVAL);
      this.companyCache[COMPANY_CACHE_KEY] = timer$.pipe(
        switchMap(_ => this.getAllCompaniesHttpRequest()),
        shareReplay(CACHE_SIZE),
        refCount(),
        catchError(err => this.companyCache[COMPANY_CACHE_KEY] = undefined) //prevents storing error in cache
      );
    }
    return this.companyCache[COMPANY_CACHE_KEY];
  }

  private getAllCompaniesHttpRequest(): Observable<CompanyViewModel[]> {
    return this.httpClient.get<CompanyViewModel[]>(environment.endpoints.company.getAllCompanies());
  }
}

Let's say, ComponentA gets this service injected through the component's instructor.  When ComponentA calls the CompanyService.getAllCompanies() method, the results will be stored in companyCache.  Now the user navigates to a new URL, ComponentA get destroyed, as well as the instance of the service.  Navigate back to ComponentA, and a new instance of the service is injected, and companyCache is once again empty.

Is my assumption correct?  Can I make a service a singleton accross the entire application?

Body:
Services are a singleton at the level of the app.

Take this simple stackblitz demo

I have a trivial service that sets a random number from the constructor.

@Injectable({
  providedIn: 'root'
})
export class Service {
  constructor() {
    this.rnd = Math.random();
  }

  private rnd: number;

  getRand(): number {
    return this.rnd;
  }
}

I have a component structure like this with the service being injected into 2 "child" components (not actual children, but that's the pattern of navigation I have set up):

|- home

|- component a
|--  inject service

|- component b
|--  inject service

When navigating from home to component a, it will display the random number that was set in the constructor of the service.

When I navigate back to home (check the console to see that component a was destroyed), and then navigate to component b, it will display the random number that was set in the constructor of the service.

For the lifetime of the app, the random number remains the same. To me this proves that even when a service isn't "in scope", it is still in memory.

Not to mention that the docs talk about this on the very first line:

A singleton service is a service for which only one instance exists in an app.


问:
GCP: Vision API: Getting certification error
I am using GCP Vision API since almost last 3 years and till few days before it was working correctly.
But since last couple of days, I started getting below error.

```<code>sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

Not sure why its failing. Need help to resolve it. Have valid Billing account and OAuth credentials json.

```<code>AnnotateImageRequest request = new AnnotateImageRequest()
                .setImage(new Image().encodeContent(image))
                .setFeatures(ImmutableList.of(new Feature().setType("LOGO_DETECTION").setMaxResults(MAX_RESULTS),
                                            new Feature().setType("IMAGE_PROPERTIES").setMaxResults(MAX_RESULTS),
                                            new Feature().setType("TEXT_DETECTION").setMaxResults(MAX_RESULTS)));
        Vision.Images.Annotate annotate = vision.images()
                .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request)));

        BatchAnnotateImagesResponse batchResponse = annotate.execute();
</code>```

Getting above mentioned error on last line.

答:
The error is one related to SSL. It means that Java tried to open an SSL connection but was unable to find a chain of certificates validating the Google server's certificate. This isn't a Cloud Vision specific issue.

Google manages its own certificate authority for Google websites and services. The necessary root certificates you need to trust to access Google services can be retrieved from
https://pki.goog/roots.pem

Can you ensure that all of those root certificates are installed in your certificate truststore?

Does the issue occur if you call other Google APIs in the same way you're calling the Cloud Vision API?

Are your devices behind any proxies or firewalls that might interfere with establishing SSL connections? Are there any personal firewalls, network equipment, or software that might be blocking this traffic? In particular, port 443 must be enabled for SSL-encrypted traffic.

Can you reproduce the issue on other devices? Or on devices connected to different networks?

Is the system clock on the requesting computer set properly? If the clock is off, the computer may mistakenly think that a certificate is expired or invalid.

Can you use the Google API Explorer to verify that the Cloud Vision API is working for members of your domain?
For example, anyone in your domain with Cloud Vision turned should be able to follow this link https://cloud.google.com/vision/docs/drag-and-drop, and test the API.

Body:
I am using GCP Vision API since almost last 3 years and till few days before it was working correctly.
But since last couple of days, I started getting below error.

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Not sure why its failing. Need help to resolve it. Have valid Billing account and OAuth credentials json.

AnnotateImageRequest request = new AnnotateImageRequest()
                .setImage(new Image().encodeContent(image))
                .setFeatures(ImmutableList.of(new Feature().setType("LOGO_DETECTION").setMaxResults(MAX_RESULTS),
                                            new Feature().setType("IMAGE_PROPERTIES").setMaxResults(MAX_RESULTS),
                                            new Feature().setType("TEXT_DETECTION").setMaxResults(MAX_RESULTS)));
        Vision.Images.Annotate annotate = vision.images()
                .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request)));

        BatchAnnotateImagesResponse batchResponse = annotate.execute();

Getting above mentioned error on last line.


问:
Find matching questions from all records
I've a library of questions and answers and building an API in NodeJS which allows to search for answers based on the question passed as input. Following is my goal:

Split the question by space

Tokenize it and remove stopwords

Query database for records where question contains one or more words from the tokenized array

Ideally sort in descending order total number of matches in the question. For eg: If the question A contains 'module' and 'solution' and question B contains only 'solution', then question A should be shown before question B

I've been able to achieve 1 to 3, using the below code:

```<code>let question = req.query.question;
let arrQuestions = question.split(" ");
let tokenizedQuestion = stopwords.removeStopwords(arrQuestions);

let whereClause = tokenizedQuestion.join("%' OR answer LIKE '%");
whereClause = " answer LIKE '%" + whereClause + "%' ";

let query = "SELECT * FROM tbl_libraries WHERE " + whereClause;
</code>```

I'm not able to figure out how to achieve 4. Can somebody provide pointers?

Thanks!

答:
I ended up using Full Text Search. Following is the stored procedure I created to enable searching:

```<code>DROP PROCEDURE IF EXISTS SP_Search $$
CREATE PROCEDURE `SP_Search`(IN QuestionToSearch TEXT, IN TagsToSearch TEXT, IN CollectionsToSearch TEXT, IN ReturnRecordsFromIndex INT, IN TotalRecordsToReturn INT)
BEGIN
    SET @MainQuery = CONCAT("SELECT *, MATCH(question, answer_content) AGAINST (", CONCAT("'", QuestionToSearch, "'"), " IN NATURAL LANGUAGE MODE) AS score ");
    SET @MainQuery = CONCAT(@MainQuery, " FROM tbl_libraries ");
    SET @MainQuery = CONCAT(@MainQuery, " WHERE MATCH(question, answer_content) AGAINST (", CONCAT("'", QuestionToSearch, "'"), " IN NATURAL LANGUAGE MODE) ");

    IF F_IsNullOrEmpty(TagsToSearch) AND NOT F_IsNullOrEmpty(CollectionsToSearch) THEN
        SET @MainQuery = CONCAT(@MainQuery, " AND collections LIKE '%", CollectionsToSearch, "%' ");
    ELSEIF F_IsNullOrEmpty(CollectionsToSearch) AND NOT F_IsNullOrEmpty(TagsToSearch) THEN
        SET @MainQuery = CONCAT(@MainQuery, " AND tags LIKE '", TagsToSearch, "' ");
    ELSEIF NOT F_IsNullOrEmpty(TagsToSearch) AND NOT F_IsNullOrEmpty(CollectionsToSearch) THEN
        SET @MainQuery = CONCAT(@MainQuery, " AND tags LIKE '", TagsToSearch, "' AND collections LIKE '", CollectionsToSearch, "' ");
    END IF;

    SET @MainQuery = CONCAT(@MainQuery, " ORDER BY score DESC ");
    SET @MainQuery = CONCAT(@MainQuery, " LIMIT ", ReturnRecordsFromIndex, ", ", TotalRecordsToReturn);

    PREPARE SqlQuery FROM @MainQuery;
    EXECUTE SqlQuery;
END $$
DELIMITER ;
</code>```

This uses a custom function I created F_IsNullOrEmpty, which is as shown below for completion:

```<code>CREATE FUNCTION F_IsNullOrEmpty(ValueToCheck VARCHAR(256)) RETURNS BOOL
DETERMINISTIC
BEGIN
    IF((ValueToCheck IS NULL) OR (LENGTH(ValueToCheck) = 0) OR (ValueToCheck = 'null')) THEN
        Return True;
    ELSE
        Return False;
    END IF;
END;
</code>```

Body:
I've a library of questions and answers and building an API in NodeJS which allows to search for answers based on the question passed as input. Following is my goal:

Split the question by space

Tokenize it and remove stopwords

Query database for records where question contains one or more words from the tokenized array

Ideally sort in descending order total number of matches in the question. For eg: If the question A contains 'module' and 'solution' and question B contains only 'solution', then question A should be shown before question B

I've been able to achieve 1 to 3, using the below code:

let question = req.query.question;
let arrQuestions = question.split(" ");
let tokenizedQuestion = stopwords.removeStopwords(arrQuestions);

let whereClause = tokenizedQuestion.join("%' OR answer LIKE '%");
whereClause = " answer LIKE '%" + whereClause + "%' ";

let query = "SELECT * FROM tbl_libraries WHERE " + whereClause;

I'm not able to figure out how to achieve 4. Can somebody provide pointers?

Thanks!

Body:
I ended up using Full Text Search. Following is the stored procedure I created to enable searching:

DROP PROCEDURE IF EXISTS SP_Search $$
CREATE PROCEDURE `SP_Search`(IN QuestionToSearch TEXT, IN TagsToSearch TEXT, IN CollectionsToSearch TEXT, IN ReturnRecordsFromIndex INT, IN TotalRecordsToReturn INT)
BEGIN
    SET @MainQuery = CONCAT("SELECT *, MATCH(question, answer_content) AGAINST (", CONCAT("'", QuestionToSearch, "'"), " IN NATURAL LANGUAGE MODE) AS score ");
    SET @MainQuery = CONCAT(@MainQuery, " FROM tbl_libraries ");
    SET @MainQuery = CONCAT(@MainQuery, " WHERE MATCH(question, answer_content) AGAINST (", CONCAT("'", QuestionToSearch, "'"), " IN NATURAL LANGUAGE MODE) ");

    IF F_IsNullOrEmpty(TagsToSearch) AND NOT F_IsNullOrEmpty(CollectionsToSearch) THEN
        SET @MainQuery = CONCAT(@MainQuery, " AND collections LIKE '%", CollectionsToSearch, "%' ");
    ELSEIF F_IsNullOrEmpty(CollectionsToSearch) AND NOT F_IsNullOrEmpty(TagsToSearch) THEN
        SET @MainQuery = CONCAT(@MainQuery, " AND tags LIKE '", TagsToSearch, "' ");
    ELSEIF NOT F_IsNullOrEmpty(TagsToSearch) AND NOT F_IsNullOrEmpty(CollectionsToSearch) THEN
        SET @MainQuery = CONCAT(@MainQuery, " AND tags LIKE '", TagsToSearch, "' AND collections LIKE '", CollectionsToSearch, "' ");
    END IF;

    SET @MainQuery = CONCAT(@MainQuery, " ORDER BY score DESC ");
    SET @MainQuery = CONCAT(@MainQuery, " LIMIT ", ReturnRecordsFromIndex, ", ", TotalRecordsToReturn);

    PREPARE SqlQuery FROM @MainQuery;
    EXECUTE SqlQuery;
END $$
DELIMITER ;

This uses a custom function I created F_IsNullOrEmpty, which is as shown below for completion:

CREATE FUNCTION F_IsNullOrEmpty(ValueToCheck VARCHAR(256)) RETURNS BOOL
DETERMINISTIC
BEGIN
    IF((ValueToCheck IS NULL) OR (LENGTH(ValueToCheck) = 0) OR (ValueToCheck = 'null')) THEN
        Return True;
    ELSE
        Return False;
    END IF;
END;


问:
react manage query string called data
I don't know how to manage query string to react.

I made component class and it is composed of 3 other components.
It is not show data first time. Users have to select or click but
ton.

It is work well.

But I received a new feature. ;(

When users connect my site who copied url, the page has to show data immediately.

So I added query string. But I don't know when I call function.

I installed query-string.

I tried to use 'shouldComponentUpdate' function, but it was not work.

```<code>shouldComponentUpdate(nextProps, nextState) {
 if (this.props.location.search.ids !== nextProps.location.search.ids) {

      // call some function....
    }
    return true;
}
</code>```

for example,
Users connect localhost:3000/my/home

It's ok.

But users connect localhost:3000/my/home?ids=1

It's not ok.

Summary.
I want to show data immediately when user connect to the site by query-string.

答:
I added componentDidMount and call myfunction.

```<code>  componentDidMount(){
    const query = queryString.parse(this.props.location.search);
    if(query.ids !== 'undefined'){
      let slice_ids = [];
      slice_ids = query.ids.split(',');
      if(slice_ids.length > 0){
        this.myfunction(1);
      }
    }
  }
</code>```

Users can access the url.
Thanks @gnujoow

Title: react manage query string called data

Body:
I don't know how to manage query string to react.

I made component class and it is composed of 3 other components.
It is not show data first time. Users have to select or click but
ton.

It is work well.

But I received a new feature. ;(

When users connect my site who copied url, the page has to show data immediately.

So I added query string. But I don't know when I call function.

I installed query-string.

I tried to use 'shouldComponentUpdate' function, but it was not work.

shouldComponentUpdate(nextProps, nextState) {
 if (this.props.location.search.ids !== nextProps.location.search.ids) {

      // call some function....
    }
    return true;
}

for example,
Users connect localhost:3000/my/home

It's ok.

But users connect localhost:3000/my/home?ids=1

It's not ok.

Summary.
I want to show data immediately when user connect to the site by query-string.

Body:
I added componentDidMount and call myfunction.

  componentDidMount(){
    const query = queryString.parse(this.props.location.search);
    if(query.ids !== 'undefined'){
      let slice_ids = [];
      slice_ids = query.ids.split(',');
      if(slice_ids.length > 0){
        this.myfunction(1);
      }
    }
  }

Users can access the url.
Thanks @gnujoow


问:
Failed to unmarshal nested yaml
Yaml input:

```<code>Tasks:
 - task:
    name: 123
    retry: 5
    next: 123
 - task:
    name: 123
    retry: 5
    next: 123
</code>```

code:

```<code>package main

import (
    "fmt"
    "io/ioutil"
    "os"

    "gopkg.in/yaml.v2"
)

type Tasks []struct {
    Task Task `yaml:"task"`
}

type Task struct {
    Name  string `yaml:"name"`
    Retry int    `yaml:"retry"`
    Next  string `yaml:"next"`
}

func main() {
    var w Tasks
    wfyaml, _ := os.Open(".yaml")
    byteValue, _ := ioutil.ReadAll(wfyaml)
    yaml.Unmarshal(byteValue, &w)
    fmt.Printf("%+v\n", w)
}
</code>```

Output:[]

I cannot figure out what's the cause of the issue. I have checked what I can.

答:
You missed the top layer (Tasks) in your struct (playground):

```<code>package main

import (
    "fmt"

    "gopkg.in/yaml.v2"
)

const yamlStr = `Tasks:
 - task:
    name: 123
    retry: 5
    next: 123
 - task:
    name: 123
    retry: 5
    next: 123`

type File struct {
    Tasks Tasks `yaml:"Tasks"`
}

type Tasks []struct {
    Task Task `yaml:"task"`
}

type Task struct {
    Name  string `yaml:"name"`
    Retry int    `yaml:"retry"`
    Next  string `yaml:"next"`
}

func main() {
    var w File
    yaml.Unmarshal([]byte(yamlStr), &w)
    fmt.Printf("%+v\n", w)
}
</code>```

Title: Failed to unmarshal nested yaml

Body:
Yaml input:

Tasks:
 - task:
    name: 123
    retry: 5
    next: 123
 - task:
    name: 123
    retry: 5
    next: 123

code:

package main

import (
    "fmt"
    "io/ioutil"
    "os"

    "gopkg.in/yaml.v2"
)

type Tasks []struct {
    Task Task `yaml:"task"`
}

type Task struct {
    Name  string `yaml:"name"`
    Retry int    `yaml:"retry"`
    Next  string `yaml:"next"`
}

func main() {
    var w Tasks
    wfyaml, _ := os.Open(".yaml")
    byteValue, _ := ioutil.ReadAll(wfyaml)
    yaml.Unmarshal(byteValue, &w)
    fmt.Printf("%+v\n", w)
}

Output:[]

I cannot figure out what's the cause of the issue. I have checked what I can.

Body:
You missed the top layer (Tasks) in your struct (playground):

package main

import (
    "fmt"

    "gopkg.in/yaml.v2"
)

const yamlStr = `Tasks:
 - task:
    name: 123
    retry: 5
    next: 123
 - task:
    name: 123
    retry: 5
    next: 123`

type File struct {
    Tasks Tasks `yaml:"Tasks"`
}

type Tasks []struct {
    Task Task `yaml:"task"`
}

type Task struct {
    Name  string `yaml:"name"`
    Retry int    `yaml:"retry"`
    Next  string `yaml:"next"`
}

func main() {
    var w File
    yaml.Unmarshal([]byte(yamlStr), &w)
    fmt.Printf("%+v\n", w)
}


问:
ionic 4: <ion-reorder> not working as expected
i'm working with ionic 4 angular 7. I'm using <ion-reorder> to reorder list.  Drag n Drop works for the first time fine but when I release the click, item got stuck. After first reorder everything freezes. And I'm unable to attempt reorder for the second time.

Here my .html file

```<code><ion-list lines="none">
      <ion-reorder-group disabled="false">
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>
              <img src="../assets/images/5.jpg">
            </ion-thumbnail>
            <div class="pl-2">
              <h5 no-margin>Multan</h5>
              <p no-margin>Historical place...</p>
            </div>
            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>
              <img src="../assets/images/5.jpg">
            </ion-thumbnail>
            <div class="pl-2">
              <h5 no-margin>Multan</h5>
              <p no-margin>Historical place...</p>
            </div>
            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>
              <img src="../assets/images/5.jpg">
            </ion-thumbnail>
            <div class="pl-2">
              <h5 no-margin>Multan</h5>
              <p no-margin>Historical place...</p>
            </div>
            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>
              <img src="../assets/images/5.jpg">
            </ion-thumbnail>
            <div class="pl-2">
              <h5 no-margin>Multan</h5>
              <p no-margin>Historical place...</p>
            </div>
            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
      </ion-reorder-group>
    </ion-list>
</code>```

When I drag n Drop Item. It get stuck when I drop it. After this, everything freezes.

Any Help...?

I'm using

Ionic: 4.10.2
Angular: 7.3.0

答:
The key here is to complete the event and you have to do it manually. So the ionItemReorder event callback is a must. So something as simple as this should do the trick:

Typescript :

```<code>    public onItemReorder({ detail }) {
       detail.complete(true);
    }
</code>```

HTML :

<ion-reorder-group (ionItemReorder)="onItemReorder($event)" [disabled]="false">

Body:
i'm working with ionic 4 angular 7. I'm using <ion-reorder> to reorder list.  Drag n Drop works for the first time fine but when I release the click, item got stuck. After first reorder everything freezes. And I'm unable to attempt reorder for the second time.

Here my .html file

<ion-list lines="none">
      <ion-reorder-group disabled="false">
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>

            </ion-thumbnail>

Multan

Historical place...

            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>

            </ion-thumbnail>

Multan

Historical place...

            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>

            </ion-thumbnail>

Multan

Historical place...

            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
        <ion-reorder>
          <ion-item>
            <ion-thumbnail no-margin item-start>

            </ion-thumbnail>

Multan

Historical place...

            <ion-buttons slot="end">
              <ion-button>
                <ion-icon slot="icon-only" name="close"></ion-icon>
              </ion-button>
            </ion-buttons>
          </ion-item>
        </ion-reorder>
      </ion-reorder-group>
    </ion-list>

When I drag n Drop Item. It get stuck when I drop it. After this, everything freezes.

Any Help...?

I'm using

Ionic: 4.10.2
Angular: 7.3.0

Body:
The key here is to complete the event and you have to do it manually. So the ionItemReorder event callback is a must. So something as simple as this should do the trick:

Typescript :

    public onItemReorder({ detail }) {
       detail.complete(true);
    }

HTML :

<ion-reorder-group (ionItemReorder)="onItemReorder($event)" [disabled]="false">


问:
Entity Framework - How to check if table exists?
I'm using the Entity Framework with Code First approach. The base class DbContext has functions to create and delete the database as well as to check for its existence.

I want to check if a special table (entity) is existing or not. Is it possible with an framework implementation or do I need to write custom methods? If I need to write my own implementation, what would be the most generic approach to do that?

Thanks for any help.

答:
In EF Core, I have added the TableExists method as a extension method for the DbContext class. Here is my solution using Dapper.

```<code>using System.Linq;
using Dapper;
using Microsoft.EntityFrameworkCore;

public static class DbContextsExtensions
{
    public static bool TableExists(this DbContext dbContext, string tableName)
    {
        var sqlQ = $"SELECT COUNT(*) as Count FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}'";

        var conn = dbContext.Database.GetDbConnection();
        {
            if (conn != null)
            {
                // Query - method extension provided by Dapper library
                var count = conn.Query<int>(sqlQ).FirstOrDefault();

                return (count > 0);
            }
        }
        return false;
    }
}
</code>```

And here is an usage example:

```<code>if(context != null && context.TableExists("AppSettings"))
{
   // do something;
}
</code>```

Hope this help other people.

ContentLicense: CC BY-SA 3.0

Body:
In EF Core, I have added the TableExists method as a extension method for the DbContext class. Here is my solution using Dapper.

using System.Linq;
using Dapper;
using Microsoft.EntityFrameworkCore;

public static class DbContextsExtensions
{
    public static bool TableExists(this DbContext dbContext, string tableName)
    {
        var sqlQ = $"SELECT COUNT(*) as Count FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}'";

        var conn = dbContext.Database.GetDbConnection();
        {
            if (conn != null)
            {
                // Query - method extension provided by Dapper library
                var count = conn.Query<int>(sqlQ).FirstOrDefault();

                return (count > 0);
            }
        }
        return false;
    }
}

And here is an usage example:

if(context != null && context.TableExists("AppSettings"))
{
   // do something;
}

Hope this help other people.


问:
select same data from different db in same select statement
hi i want to select multiple db from linq in same select statement

```<code>// gets specific information from Cabinet table
var chassi = (from a in db.Cabinets
              from b in db.Commodities
              from e in db.sArticleNumbers

              where
                  kjopKollonne.Contains(e.ArtNum) &&
                  a.ArticleNumberID == e.ID &&
                  a.ArticleNumberID == b.ArticleNumberID

              select new {
                  ArtNum = e.ArtNum,
                  Price = b.Price,
                  ModelName = a.ModelName,
                           }).ToList();

// gets specific information from cpu table
 var cpu = (from a in db.cpu
            from b in db.Commodities
            from e in db.sArticleNumbers

            where
                kjopKollonne.Contains(e.ArtNum) &&
                a.ArticleNumberID == e.ID &&
                a.ArticleNumberID == b.ArticleNumberID

            select new {
                ArtNum = e.ArtNum,
                Price = b.Price,
                ModelName = a.ModelName,
            }).ToList();

// Joins CPU and chassi information to one output
            var query1 = (from a in chassi
                          from b in cpu

            select new {
                ArtNum = a.ArtNum and b.ArtNum, <-- problem
                Price = a.Price,
                ModelName = a.ModelName,
            }).ToList();
</code>```

If any one has a different approach to solving it, thanks for posting it.

答: It sounds like you're looking for the Union (removes duplicates) or Concat (keeps duplicates) methods.

Body:
hi i want to select multiple db from linq in same select statement

// gets specific information from Cabinet table
var chassi = (from a in db.Cabinets
              from b in db.Commodities
              from e in db.sArticleNumbers

              where
                  kjopKollonne.Contains(e.ArtNum) &&
                  a.ArticleNumberID == e.ID &&
                  a.ArticleNumberID == b.ArticleNumberID

              select new {
                  ArtNum = e.ArtNum,
                  Price = b.Price,
                  ModelName = a.ModelName,
                           }).ToList();

// gets specific information from cpu table
 var cpu = (from a in db.cpu
            from b in db.Commodities
            from e in db.sArticleNumbers

            where
                kjopKollonne.Contains(e.ArtNum) &&
                a.ArticleNumberID == e.ID &&
                a.ArticleNumberID == b.ArticleNumberID

            select new {
                ArtNum = e.ArtNum,
                Price = b.Price,
                ModelName = a.ModelName,
            }).ToList();

// Joins CPU and chassi information to one output
            var query1 = (from a in chassi
                          from b in cpu

            select new {
                ArtNum = a.ArtNum and b.ArtNum, <-- problem
                Price = a.Price,
                ModelName = a.ModelName,
            }).ToList();

If any one has a different approach to solving it, thanks for posting it.


问:
Update a json file from Angular
I am using a json file to populate data on UI in angular. Is there any way I can make changes to this file from UI.
I should be able to do a put/post request to update contents of this file.

Any help would be appreciated.

I use this structure as a datasource to populate on UI, I want to edit this json data through angular.

```<code>"events"    : {
    "rows": [
      {
        "id"        : 1,
        "resourceId": "a",
        "name"      : "Meeting #1",
       "startDate" : "2018-02-07 11:00",
        "endDate"   : "2018-02-07 14:00",
        "eventType" : "Meeting",
        "eventColor": "blue"
        }]}
</code>```

答:
You can do this with json-server !

How I set this up

In terminal:

```<code>npm i -D @angular-builders/custom-webpack json-server
ng config projects.<project>.architect.build.builder @angular-builders/custom-webpack:browser
ng config projects.<project>.architect.build.options.customWebpackConfig.path custom-webpack.config.js
ng config projects.<project>.architect.serve.builder @angular-builders/custom-webpack:dev-server
ng config projects.<project>.architect.serve.options.customWebpackConfig.path custom-webpack.config.js
</code>```

This installs the packages needed and modifies angular.json so we can run the json server in tandem when we run ng serve

Then we need to make two files in the root of project:

db.json

custom-webpack.config.js

in custom-webpack.config we put

```<code>const json = require('json-server');

module.exports = {
  devServer: {
    before: function(app) {
      app.use('/api', json.router('db.json'));
    }
  }
};
</code>```

In db.json we can put our endpoints, in this case

```<code>{
    "users": []
}
</code>```

Now we can use this in our service

```<code>const API = '/api/users/';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  constructor(private http: HttpClient) {}

  get(id: number) {
    return this.http.get(API + id);
  }

  post(user: any) {
    return this.http.post(API, user);
  }
}
</code>```

Do a post and checkout db.json.

json-server docs: https://www.npmjs.com/package/json-server

Title: Update a json file from Angular

Body:
I am using a json file to populate data on UI in angular. Is there any way I can make changes to this file from UI.
I should be able to do a put/post request to update contents of this file.

Any help would be appreciated.

I use this structure as a datasource to populate on UI, I want to edit this json data through angular.

"events"    : {
    "rows": [
      {
        "id"        : 1,
        "resourceId": "a",
        "name"      : "Meeting #1",
       "startDate" : "2018-02-07 11:00",
        "endDate"   : "2018-02-07 14:00",
        "eventType" : "Meeting",
        "eventColor": "blue"
        }]}

Body:
You can do this with json-server !

How I set this up

In terminal:

npm i -D @angular-builders/custom-webpack json-server
ng config projects.<project>.architect.build.builder @angular-builders/custom-webpack:browser
ng config projects.<project>.architect.build.options.customWebpackConfig.path custom-webpack.config.js
ng config projects.<project>.architect.serve.builder @angular-builders/custom-webpack:dev-server
ng config projects.<project>.architect.serve.options.customWebpackConfig.path custom-webpack.config.js

This installs the packages needed and modifies angular.json so we can run the json server in tandem when we run ng serve

Then we need to make two files in the root of project:

db.json

custom-webpack.config.js

in custom-webpack.config we put

const json = require('json-server');

module.exports = {
  devServer: {
    before: function(app) {
      app.use('/api', json.router('db.json'));
    }
  }
};

In db.json we can put our endpoints, in this case

{
    "users": []
}

Now we can use this in our service

const API = '/api/users/';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  constructor(private http: HttpClient) {}

  get(id: number) {
    return this.http.get(API + id);
  }

  post(user: any) {
    return this.http.post(API, user);
  }
}

Do a post and checkout db.json.

json-server docs: https://www.npmjs.com/package/json-server


问:
Change WooCommerce text string "Order #" to "Internet Order #"
Seems like it should be simple, but I can't figure out how to change the strings "Order #" in emails or "Order Number" in Thank You page.

I want both to read "Web Order #" and "Web Order Number" respectively.

I have tried:

add_filter( 'gettext', 'translate_woocommerce_strings', 999, 3 );

function translate_woocommerce_strings( $translated, $untranslated, $domain ) {
   if ( ! is_admin() && 'woocommerce' === $domain ) {
      switch ( $translated) {
         case 'Order' :
            $translated = 'Web Order';
            break;
      }
   }
   return $translated;
 }
```

答:
For the thankyou page you can apply the same as the example above for the e-mails,
on the following line you will find what you are looking for

https://github.com/woocommerce/woocommerce/blob/3.8.0/templates/checkout/thankyou.php#L45

This template can be overridden by copying it to yourtheme/woocommerce/checkout/thankyou.php.


问:
In Cytoscape.js, using HTML in node labels, how can I handle events on a certain DOM element in the HTML label?
I'm using Cytoscape.js with the cytoscape-node-html-label extension to draw a complex HTML node. My goal is to show a tooltip when the user hovers over a certain area in this HTML node. However, I can't seem to access the mouse events at all. I can listen for mouse events over the whole node by using Cytoscapes functionality:

```<code>cy.on('mouseover', 'node', function(evt){
   var node = evt.target;
});
</code>```

But trying to use regular jQuery events on an HTML element inside the node label (they have unique ids) does not work. The event does not fire. I guess it's because this HTML is somehow drawn in the canvas and the extension does not implement this functionality. I tried:

```<code>$('#' + id_of_elem).hover(function(evt){
   ...
});
</code>```

The extension offers an option to enable pointer events but it does not change anything. I configure the extension like this:

```<code>cy.nodeHtmlLabel([{
        query: '.machineNode',
        valign: 'center',
        halign: 'center',
        valignBox: 'center',
        halignBox: 'center',
        tpl: function(data) {
            return [HTML code here];
        }
      }
    ], {
      enablePointerEvents: true
    });
</code>```

Does anyone have an idea how to accomplish my goal? Alternative ideas are welcome. Do you think there is a way to implement the events?

答:
I believe that you can achieve what you want with other cytoscape extensions. Here is a runnable code that plots a simple graph of 2 nodes and 1 edge. Cytoscape-popper, popper, and tippy extensions are used to produce pop-up HTML (text + button) when 'mouse-over' event is fired. The button can be clicked to run a javascript code. It also has a tooltip text when the mouse pointer hovers over it.

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    style: [
      {
        selector: "node",
        style: {
          content: "data(id)"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle"
        }
      },
      {
        selector: 'node.game_mkr',
        style: {
          shape: 'octagon',
          width: 25,
          height: 25,
          'background-color': 'magenta',
          label: 'Game Marker',
          'font-size': 14,
          'text-background-color': 'white',
          'text-background-padding': '2px',
          'text-background-opacity': 0.85,

        }
      }
    ],

    elements: {
      nodes: [
        {
          data: {
            id: "a",
            text: "For gaming"
          },
          classes: "game_mkr"
        },
        {
          data: {
            id: "b",
            text: "For work"
          }
        }
      ],
      edges: [
        {
          data: {
            id: "ab",
            source: "a",
            target: "b",
            text: "Sample edge"
          }
        }
      ],

    },

    layout: {
      name: "grid"
    }
  }));

  function makePopper(ele) {
    let ref = ele.popperRef(); // used only for positioning

    ele.tippy = tippy(ref, {
      // tippy options:
      content: () => {
        let contentdiv = document.createElement("div");
        let ctent = "ID: ";
        ctent += ""+ele.id()+"";
        ctent += "
<button type='button' onclick='alert(\"Hello.\")' title='"+ ele.data().text +"'>Click Me!</button>";
        contentdiv.innerHTML = ctent;

        return contentdiv;
      },
      arrow: true,
      allowHTML: true,
      interactive: true,
      duration: [100, 1000],
      trigger: "manual" //when use program to handle
    });
  }

  cy.ready(function() {
    cy.elements().forEach(function(ele) {
      makePopper(ele);
    });
  });

  cy.elements().unbind("mouseover");
  cy.elements().bind("mouseover", event => event.target.tippy.show());

  cy.elements().unbind("mouseout");
  cy.elements().bind("mouseout", event => event.target.tippy.hide());

//  cy.elements().unbind("click");
//  cy.elements().bind("click", event => {event.target.tippy.show()});

//let insta = event.target.tippy;
//console.log(insta)

//  cy.elements().unbind("mouseover");
//  cy.elements().bind("mouseover", event => event.target.tippy.hide());

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}</code>```

  <link rel="stylesheet" href="https://unpkg.com/tippy.js@4.0.1/index.css" />

```

Body:
I'm using Cytoscape.js with the cytoscape-node-html-label extension to draw a complex HTML node. My goal is to show a tooltip when the user hovers over a certain area in this HTML node. However, I can't seem to access the mouse events at all. I can listen for mouse events over the whole node by using Cytoscapes functionality:

cy.on('mouseover', 'node', function(evt){
   var node = evt.target;
});

But trying to use regular jQuery events on an HTML element inside the node label (they have unique ids) does not work. The event does not fire. I guess it's because this HTML is somehow drawn in the canvas and the extension does not implement this functionality. I tried:

$('#' + id_of_elem).hover(function(evt){
   ...
});

The extension offers an option to enable pointer events but it does not change anything. I configure the extension like this:

cy.nodeHtmlLabel([{
        query: '.machineNode',
        valign: 'center',
        halign: 'center',
        valignBox: 'center',
        halignBox: 'center',
        tpl: function(data) {
            return [HTML code here];
        }
      }
    ], {
      enablePointerEvents: true
    });

Does anyone have an idea how to accomplish my goal? Alternative ideas are welcome. Do you think there is a way to implement the events?

Body:
I believe that you can achieve what you want with other cytoscape extensions. Here is a runnable code that plots a simple graph of 2 nodes and 1 edge. Cytoscape-popper, popper, and tippy extensions are used to produce pop-up HTML (text + button) when 'mouse-over' event is fired. The button can be clicked to run a javascript code. It also has a tooltip text when the mouse pointer hovers over it.

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),
    style: [
      {
        selector: "node",
        style: {
          content: "data(id)"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle"
        }
      },
      {
        selector: 'node.game_mkr',
        style: {
          shape: 'octagon',
          width: 25,
          height: 25,
          'background-color': 'magenta',
          label: 'Game Marker',
          'font-size': 14,
          'text-background-color': 'white',
          'text-background-padding': '2px',
          'text-background-opacity': 0.85,

        }
      }
    ],

    elements: {
      nodes: [
        {
          data: {
            id: "a",
            text: "For gaming"
          },
          classes: "game_mkr"
        },
        {
          data: {
            id: "b",
            text: "For work"
          }
        }
      ],
      edges: [
        {
          data: {
            id: "ab",
            source: "a",
            target: "b",
            text: "Sample edge"
          }
        }
      ],

    },

    layout: {
      name: "grid"
    }
  }));

  function makePopper(ele) {
    let ref = ele.popperRef(); // used only for positioning

    ele.tippy = tippy(ref, {
      // tippy options:
      content: () => {
        let contentdiv = document.createElement("div");
        let ctent = "<strong>ID: </strong>";
        ctent += "<b>"+ele.id()+"</b>";
        ctent += "<br/><button type='button' onclick='alert(\"Hello.\")' title='"+ ele.data().text +"'>Click Me!</button>";
        contentdiv.innerHTML = ctent;

        return contentdiv;
      },
      arrow: true,
      allowHTML: true,
      interactive: true,
      duration: [100, 1000],
      trigger: "manual" //when use program to handle
    });
  }

  cy.ready(function() {
    cy.elements().forEach(function(ele) {
      makePopper(ele);
    });
  });

  cy.elements().unbind("mouseover");
  cy.elements().bind("mouseover", event => event.target.tippy.show());

  cy.elements().unbind("mouseout");
  cy.elements().bind("mouseout", event => event.target.tippy.hide());

//  cy.elements().unbind("click");
//  cy.elements().bind("click", event => {event.target.tippy.show()});

//let insta = event.target.tippy;
//console.log(insta)

//  cy.elements().unbind("mouseover");
//  cy.elements().bind("mouseover", event => event.target.tippy.hide());

});

body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
}

<head>

  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
  <script src="https://unpkg.com/popper.js@1.14.7/dist/umd/popper.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/cytoscape-popper@1.0.4/cytoscape-popper.min.js"></script>
  <script src="https://unpkg.com/tippy.js@4.0.1/umd/index.all.min.js"></script>

  <link rel="stylesheet" href="https://unpkg.com/tippy.js@4.0.1/index.css" />
</head>

<body>
  <div id="cy"></div>
</body>


问:
How to draw circle on the MAP using GMAP.NET in C#
I am using GMAP.NET in c#. I am able to display the map on the form,  now i am trying to draw a CIRCLE mouse by clicking on a certian point, keeping the left mouse button and dragging the mouse upto specific place. Once the circle is drawn I want to get its radius in miles from the center point which I am sure GMAP is capable of doing it. I am using Opentstreet maps.

I am just unable to achive this functionly, anybody who has played with GMAP control kindly share your experience with some code which will work.

Thanks

答:
My code draws arcs and inherits from GMapMarker too. The arc sweeps from point A to point B with the pivot point at C. Where point A and B are coincidental, a circle will be drawn.</p>

```<code>    public class CustomArc : GMapMarker, ISerializable {
    [NonSerialized]
    public Pen pen;

    private int radius = 20;
    private int pen_width = 2;

    private float start = 0.0f;
    private float sweep = 0.0f;

    private GPoint ptA;
    private GPoint ptB;
    private GPoint ptC;
    private List<PointF> points;

    private static Logger logger = LogManager.GetCurrentClassLogger();

    public CustomArc(GPoint ptA, GPoint ptB, GPoint ptC, PointLatLng geo) : base(geo) {
        this.ptA = ptA;
        this.ptB = ptB;
        this.ptC = ptC;
        initialise();
    }

    private void initialise() {
        this.pen = new Pen(Brushes.White, this.pen_width);
        this.radius = (int)UIMaths.distance(ptC, ptA);

        this.points = new List<PointF>();

        if (ptA == ptB) {
            this.sweep = 360.0f;
        } else {
            // Calculate the radius
            this.sweep = (float)UIMaths.sweepAngleDeg(ptA, ptB, ptC);
        }
        this.start = (float)UIMaths.startAngle(ptC, ptB);
        Size = new Size(2 * radius, 2 * radius);
        Offset = new Point(-Size.Width / 2, -Size.Height / 2);

        Console.Out.WriteLine("Radius {0}, Start {1:0.0}, Sweep {2:0.0}", radius, start, sweep);
    }

    public override void OnRender(Graphics g) {
        try {
            Rectangle rect = new Rectangle(LocalPosition.X, LocalPosition.Y, Size.Width, Size.Height);
            g.DrawArc(pen, rect, start, sweep);

        } catch (ArgumentException ex) {
            logger.Error(ex.Message);
        }
    }

    public sealed override void Dispose() {
        if (pen != null) {
            pen.Dispose();
            pen = null;
        }

        base.Dispose();
    }

    #region ISerializable Members

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
        base.GetObjectData(info, context);
    }

    protected CustomArc(SerializationInfo info, StreamingContext context)
     : base(info, context) {
    }
    #endregion

}
</code>```

Body:
My code draws arcs and inherits from GMapMarker too. The arc sweeps from point A to point B with the pivot point at C. Where point A and B are coincidental, a circle will be drawn.

    public class CustomArc : GMapMarker, ISerializable {
    [NonSerialized]
    public Pen pen;

    private int radius = 20;
    private int pen_width = 2;

    private float start = 0.0f;
    private float sweep = 0.0f;

    private GPoint ptA;
    private GPoint ptB;
    private GPoint ptC;
    private List<PointF> points;

    private static Logger logger = LogManager.GetCurrentClassLogger();

    public CustomArc(GPoint ptA, GPoint ptB, GPoint ptC, PointLatLng geo) : base(geo) {
        this.ptA = ptA;
        this.ptB = ptB;
        this.ptC = ptC;
        initialise();
    }

    private void initialise() {
        this.pen = new Pen(Brushes.White, this.pen_width);
        this.radius = (int)UIMaths.distance(ptC, ptA);

        this.points = new List<PointF>();

        if (ptA == ptB) {
            this.sweep = 360.0f;
        } else {
            // Calculate the radius
            this.sweep = (float)UIMaths.sweepAngleDeg(ptA, ptB, ptC);
        }
        this.start = (float)UIMaths.startAngle(ptC, ptB);
        Size = new Size(2 * radius, 2 * radius);
        Offset = new Point(-Size.Width / 2, -Size.Height / 2);

        Console.Out.WriteLine("Radius {0}, Start {1:0.0}, Sweep {2:0.0}", radius, start, sweep);
    }

    public override void OnRender(Graphics g) {
        try {
            Rectangle rect = new Rectangle(LocalPosition.X, LocalPosition.Y, Size.Width, Size.Height);
            g.DrawArc(pen, rect, start, sweep);

        } catch (ArgumentException ex) {
            logger.Error(ex.Message);
        }
    }

    public sealed override void Dispose() {
        if (pen != null) {
            pen.Dispose();
            pen = null;
        }

        base.Dispose();
    }

    #region ISerializable Members

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
        base.GetObjectData(info, context);
    }

    protected CustomArc(SerializationInfo info, StreamingContext context)
     : base(info, context) {
    }
    #endregion

}


问:
Publishing xunit test results in Azure Devops fails with "No Result Found to Publish"
I want to publish xunit test results in an Azure Devops release pipeline using the "Publish test results" task Version 1.* and 2.*.

Although xunit test file is present and has content - I checked with ls and cat commands in the pipepline I get an error message like this:

```<code>2020-02-13T08:23:10.9093662Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9092530Z and Completed Date: 2020-02-13T08:23:10.9092530Z
2020-02-13T08:23:10.9144214Z No Result Found to Publish '/home/vsts/work/r1/a/report/report.xml'.
2020-02-13T08:23:10.9149123Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9148260Z and Completed Date: 2020-02-13T08:23:10.9148260Z
2020-02-13T08:23:10.9149993Z No Result Found to Publish '/home/vsts/work/r1/a/report/report1.xml'.
</code>```

The two files report1.xml and report2.xml get discovered properly but Azure DevOps says No Result Found to Publishand hesitates to publish them.

答:
If you're using dotnet test task in this way:

You may need to set VSTest instead of Xunit in Publish Test Result Task:

I met same message like yours and then resolve it by changing Xunit to VSTest. I think you may encounter similar issue.

In addition:

And as I know, built-in tasks such as Visual Studio Test task and Dot NetCore CLI task automatically publish test results to the pipeline, so you actually don't need a separate Publish Test Results task in the pipeline. See this for more details.

E.g： Dotnet test task by default will generate and publish test results:

Hope it makes some help :)

Body:
I want to publish xunit test results in an Azure Devops release pipeline using the "Publish test results" task Version 1.* and 2.*.

Although xunit test file is present and has content - I checked with ls and cat commands in the pipepline I get an error message like this:

2020-02-13T08:23:10.9093662Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9092530Z and Completed Date: 2020-02-13T08:23:10.9092530Z
2020-02-13T08:23:10.9144214Z No Result Found to Publish '/home/vsts/work/r1/a/report/report.xml'.
2020-02-13T08:23:10.9149123Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9148260Z and Completed Date: 2020-02-13T08:23:10.9148260Z
2020-02-13T08:23:10.9149993Z No Result Found to Publish '/home/vsts/work/r1/a/report/report1.xml'.

The two files report1.xml and report2.xml get discovered properly but Azure DevOps says No Result Found to Publishand hesitates to publish them.


问:
Consume SOAP service using Quarkus
My project requirement is to consume a SOAP service and I am trying to use Quarkus for this purpose. What are the quarkus dependecies hwould I use to acheive this? Is there any sample application I can refer to?

In Spring we can use org.springframework.ws.client.core.support.WebServiceGatewaySupport is there anything similiar in Quarkus.

答:
There is no SOAP client extension at the moment in Quarkus.

There is some discussion to include a CXF extension here : https://github.com/quarkusio/quarkus/issues/4005, you can join the discussion.

A PR is open (not yet finished) for SOAP WS support via CXF but not for SOAP client: https://github.com/quarkusio/quarkus/pull/5538

If you didn't plan to deploy to GraalVM (Quarkus can be deployed both in standard JVM mode and on GraalVM/SubstrateVM as a native application) you can still use any Java library with Quarkus but you will not have any integration with Quarkus itself. So using the CXF Client should works fine in JVM mode : https://cxf.apache.org/docs/how-do-i-develop-a-client.html

Title: Consume SOAP service using Quarkus


问:
How do I sort my File (highscores) with python?
I'm currently working on a dice game for my computer science coursework. I'm on the last bit of it which requires me to sort my highscores into a text file. This is what I have so far

```<code>player1=input("input") ##Temporary inputs (these values are got from the actual code)
player1score=int(input("input"))

highscore = open("Scores.txt", "r")
whowon=("{0}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("\n")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()
highscores.sort()
highscores.reverse()

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]

top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))

highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()

</code>```

Basically, in the document, it sorts them into order but it disregards the amount of place holders it has. For example:

```<code>8
7
6943734
5
</code>```

It would only sort it depending on the first place holder. And i dont know how to fix it. Obviously 6943734 should be at the top.

Thanks.

答:
Replace:

```<code>highscores.sort()
highscores.reverse()
</code>```

with

```<code>highscores = [ x.rstrip() for x in highscores ]
highscores.sort(reverse=True, key=int)
</code>```

The first line removes newline characters from your strings, so they can be converted to integers using int() function, the second - sorts in descending order according to int value.
BTW, this part:

```<code>top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))
</code>```

can be shortened to:

```<code>top = '\n'.join(highscores[0:5])
</code>```

(here you need to add newlines back before writing your highscores to a file).

Body:
I'm currently working on a dice game for my computer science coursework. I'm on the last bit of it which requires me to sort my highscores into a text file. This is what I have so far

player1=input("input") ##Temporary inputs (these values are got from the actual code)
player1score=int(input("input"))

highscore = open("Scores.txt", "r")
whowon=("{0}".format(player1score,player1))
highscores = highscore.readlines()
highscore.close()
highscore = open("Scores.txt", "a")
highscore.write(whowon)
highscore.write("\n")
highscore.close()
highscore = open("Scores.txt", "r")
highscores = highscore.readlines()
highscores.sort()
highscores.reverse()

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]

top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))

highscore.close()

highscore=open("Scores.txt", "w")
highscore.write(top)
highscore.close()

Basically, in the document, it sorts them into order but it disregards the amount of place holders it has. For example:

8
7
6943734
5

It would only sort it depending on the first place holder. And i dont know how to fix it. Obviously 6943734 should be at the top.

Thanks.

Body:
Replace:

highscores.sort()
highscores.reverse()

with

highscores = [ x.rstrip() for x in highscores ]
highscores.sort(reverse=True, key=int)

The first line removes newline characters from your strings, so they can be converted to integers using int() function, the second - sorts in descending order according to int value.
BTW, this part:

top1=highscores[0]
top2=highscores[1]
top3=highscores[2]
top4=highscores[3]
top5=highscores[4]
top=("{0}{1}{2}{3}{4}".format(top1, top2, top3, top4, top5))

can be shortened to:

top = '\n'.join(highscores[0:5])

(here you need to add newlines back before writing your highscores to a file).


问:
Jquery Datatable gives error when recreating datatable: TypeError: t[c] is undefined
I have a function that creates a datatable. On page load the datatable is created and drawn. Now, when I have a form submit to make a search on a table, I call the same function. First I make an instance of the datatable, I call the clear function then I call the function to recreate it.

Here is how I create  the datatable for the first time, which works just fine:

```<code>    $(window).load(function () {

        var table = UpdateTableCompany(null, null);
        .....
</code>```

Here is the function which manages the datatable:

```<code>    function UpdateTableCompany(val, search_field)
{
    $('#tablePubDev').DataTable().clear();
    var table = $('#tablePubDev').DataTable({
        destroy: true,
        searching: false,
        "lengthMenu": [[5, 10, 15, -1], [5, 10, 15, "All"]],
        "pageLength": 5,
        "columnDefs": [
            {
                "render": function (data, type, row) {

                    var text = '<div class="form-group">' +
                            '<div class="checkbox-nice center" style="cursor: default; height:100px;">' +
                            '<img  src="/application/assets/img/pub_devs/logos/' + row['c']['logo'] + '" style="max-height:100%; max-width: 100%;"/>' +
                            '</div>' +
                            '<div class="checkbox-nice text-center" style="cursor: default">' +
                            '<strong >Id: ' + pad(data, 11) + '</strong>' +
                            '</label>' +
                            '</div>' +
                            '</div>';

                    return text;
                },
                "targets": 0,
            },
            {
                "render": function (data, type, row) {

                    var text = '<div class="form-group">' +
                            '<div class="checkbox-nice center" style="cursor: default; height:100px;"><p class="center" style="font-size: 150%; font-weight: bold;">' +
                            row['c']['descr'] +
                            '</p></div>' +
                            '</div>';

                    return text;
                },
                "targets": 1,
            },
            {
                "render": function (data, type, row) {

                    var add_text1 = '';
                    var checked1 = '';
                    var add_text2 = '';
                    var checked2 = '';

                    if (data != null && data > 0) {

                        checked1 += 'checked="checked"';
                    } else
                        add_text1 += 'buttonDisabled ';

                    if (row['c']['developer'] != null && row['c']['developer'] > 0) {

                        checked2 += 'checked="checked"';
                    } else
                        add_text2 += 'buttonDisabled ';

                    var text = '<div class="form-group">' +
                            '<div class="checkbox-nice ' + add_text1 + '" style="cursor: default">' +
                            '<input type="checkbox" ' + checked1 + ' disabled="disabled" id="checkbox-1">' +
                            '<label for="checkbox-1">' +
                            'Publisher ' +
                            '</label>' +
                            '</div>' +
                            '<div class="checkbox-nice ' + add_text2 + '" style="cursor: default">' +
                            '<input type="checkbox" id="checkbox-2" ' + checked2 + ' disabled="disabled">' +
                            '<label for="checkbox-2">' +
                            'Developer' +
                            '</label>' +
                            '</div>' +
                            '</div>';

                    return text;
                },
                "targets": 3,
            },
            {
                "render": function (data, type, row) {
                    var text = '<td style="width: 20%;">' +
                            //'<a href="#" class="table-link">' +
                            //'<span class="fa-stack">' +
                            //'<i class="fa fa-square fa-stack-2x"></i>' +
                            //'<i class="fa fa-search-plus fa-stack-1x fa-inverse"></i>' +
                            //'</span>' +
                            //'</a>' +
                            '<a href="#" class="table-link updatePubDev" data-modal="modal-11">' +
                            '<span class="fa-stack">' +
                            '<i class="fa fa-square fa-stack-2x"></i>' +
                            '<i class="fa fa-pencil fa-stack-1x fa-inverse"></i>' +
                            '</span>' +
                            '</a>' +
                            '<span class="fa-stack table-link danger deletePubDev">' +
                            '<i class="fa fa-square fa-stack-2x"></i>' +
                            '<i class="fa fa-trash-o fa-stack-1x fa-inverse"></i>' +
                            '</span>' +
                            '</td>';

                    return text;
                },
                "targets": 4,
            }
        ],
        "columns": [
            {"data": "c.idpubdev", "name": "c.idpubdev"},
            {"data": "c.descr", "name": "c.descr"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.publisher", "name": "c.publisher"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.developer", "name": "c.developer", "visible": false, "searchable": false},
            {"data": "c.logo", "name": "c.logo", "visible": false, "searchable": false},

        ],
        "order": [[0, false], [1, 'asc'], [2, 'asc'], [3, 'asc']],

        "displayLength": 3,
        serverSide: true,
        "ajax":
                {
                    "url": "/pubdev/search/",
                    "type": "POST",
                    "data": function (d) {
                        if (val)
                            d.val = val;
                        if (search_field)
                            d.search_field = search_field;
                    }

                },
        error: function (request, status, error) {
            alert('Unable to update table contents');
            console.log(request);
            console.log(status);
            console.log(error);
        },

    });

    return table;
}
</code>```

Here instead is the submit of the form which executes the search function:

```<code> $("#search_form").submit(function (e) {
            e.preventDefault();

            var search_key = $.trim($('#val').val());
            var search_field = 'c.descr like ';

            table = $('#tablePubDev').DataTable();

            table.clear();

            table = UpdateTableCompany(search_field, search_key);

        });
</code>```

I am currently using the minified format of jquery version v1.10.2
The version of datatable is 1.10.4

This is the error I get in the console

I tried an experiment: I did not load the datatable in document ready, so I made a search submit to load the datatable , and it worked! Of course if I do a second search then the same error occurs, so the problem has to do with the recreation of datatable. All the back end code (php) works correctly and gives the desired results.

Here is the table in html

                                        Company
                                        Name
                                        Listed Games
                                        Type
                                        Actions

```
</div>
</div>
</p>

<p>I have tried using the unminified version of datatable (v 1.10.12) and I got still and error but now it says his:</p>

<blockquote>
  <p>TypeError: headerCells[i] is undefined</p>

```headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !==...
```
</blockquote>

```    // Clone the table header and footer - we can't use the header / footer
        // from the cloned table, since if scrolling is active, the table's
        // real header and footer are contained in different table tags
        tmpTable.find('thead, tfoot').remove();
        tmpTable
            .append( $(oSettings.nTHead).clone() )
            .append( $(oSettings.nTFoot).clone() );

        // Remove any assigned widths from the footer (from scrolling)
        tmpTable.find('tfoot th, tfoot td').css('width', '');

        // Apply custom sizing to the cloned header
        **headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0]** ); <-- This is where the error occurs <--

        for ( i=0 ; i<visibleColumns.length ; i++ ) {
            column = columns[ visibleColumns[i] ];

            headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
                _fnStringToCss( column.sWidthOrig ) :
                '';

            // For scrollX we need to force the column width otherwise the
            // browser will collapse it. If this width is smaller than the
            // width the column requires, then it will have no effect
            if ( column.sWidthOrig && scrollX ) {
                $( headerCells[i] ).append( $('
').css( {
                    width: column.sWidthOrig,
                    margin: 0,
                    padding: 0,
                    border: 0,
                    height: 1
                } ) );
            }
        }

        // Find the widest cell for each column and put it
```

<p>UPDATE:</p>

<p>I think I know why this is happening, although I still need to find a fix for this. It just so happens that When I define my columns in the Datatable instantiation:</p>

```   "columns": [
            {"data": "c.idpubdev", "name": "c.idpubdev"},
            {"data": "c.descr", "name": "c.descr"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.publisher", "name": "c.publisher"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.developer", "name": "c.developer", "visible": false, "searchable": false},
            {"data": "c.logo", "name": "c.logo", "visible": false, "searchable": false},
```

<p>These need to be exactly as many as the table headers that I included in my html page</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>                            <thead>
                                    <tr>
                                        <th>Company</th>
                                        <th>Name</th>
                                        <th><span>Listed Games</th>
                                        <th>Type</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead></code>```

In this case I have 5 table headers and 7  data column definitions (two have visible = false). When I used them in an older project, all I had to do was set the "visible" property to false so that they wouldn't be mapped to a table header, but here it doesn't seem to work... Why do you think that would happen? I sthere a way to work around it?

答: Sometimes this error can be occurred due to difference in no of columns of in thead and datatable columns.</p>

Body:
I have a function that creates a datatable. On page load the datatable is created and drawn. Now, when I have a form submit to make a search on a table, I call the same function. First I make an instance of the datatable, I call the clear function then I call the function to recreate it.

Here is how I create  the datatable for the first time, which works just fine:

    $(window).load(function () {

        var table = UpdateTableCompany(null, null);
        .....

Here is the function which manages the datatable:

    function UpdateTableCompany(val, search_field)
{
    $('#tablePubDev').DataTable().clear();
    var table = $('#tablePubDev').DataTable({
        destroy: true,
        searching: false,
        "lengthMenu": [[5, 10, 15, -1], [5, 10, 15, "All"]],
        "pageLength": 5,
        "columnDefs": [
            {
                "render": function (data, type, row) {

                    var text = '
' +
                            '
' +
                            '' +
                            '
' +
                            '
' +
                            'Id: ' + pad(data, 11) + '' +
                            '' +
                            '
' +
                            '
';

                    return text;
                },
                "targets": 0,
            },
            {
                "render": function (data, type, row) {

                    var text = '
' +
                            '

' +
                            row['c']['descr'] +
                            '

' +
                            '
';

                    return text;
                },
                "targets": 1,
            },
            {
                "render": function (data, type, row) {

                    var add_text1 = '';
                    var checked1 = '';
                    var add_text2 = '';
                    var checked2 = '';

                    if (data != null && data > 0) {

                        checked1 += 'checked="checked"';
                    } else
                        add_text1 += 'buttonDisabled ';

                    if (row['c']['developer'] != null && row['c']['developer'] > 0) {

                        checked2 += 'checked="checked"';
                    } else
                        add_text2 += 'buttonDisabled ';

                    var text = '
' +
                            '
' +
                            '<input type="checkbox" ' + checked1 + ' disabled="disabled" id="checkbox-1">' +
                            '' +
                            'Publisher ' +
                            '' +
                            '
' +
                            '
' +
                            '<input type="checkbox" id="checkbox-2" ' + checked2 + ' disabled="disabled">' +
                            '' +
                            'Developer' +
                            '' +
                            '
' +
                            '
';

                    return text;
                },
                "targets": 3,
            },
            {
                "render": function (data, type, row) {
                    var text = '' +
                            //'' +
                            //'' +
                            //'' +
                            //'' +
                            //'' +
                            //'' +
                            '' +
                            '' +
                            '' +
                            '' +
                            '' +
                            '' +
                            '' +
                            '' +
                            '' +
                            '' +
                            '	';

                    return text;
                },
                "targets": 4,
            }
        ],
        "columns": [
            {"data": "c.idpubdev", "name": "c.idpubdev"},
            {"data": "c.descr", "name": "c.descr"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.publisher", "name": "c.publisher"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.developer", "name": "c.developer", "visible": false, "searchable": false},
            {"data": "c.logo", "name": "c.logo", "visible": false, "searchable": false},

        ],
        "order": [[0, false], [1, 'asc'], [2, 'asc'], [3, 'asc']],

        "displayLength": 3,
        serverSide: true,
        "ajax":
                {
                    "url": "/pubdev/search/",
                    "type": "POST",
                    "data": function (d) {
                        if (val)
                            d.val = val;
                        if (search_field)
                            d.search_field = search_field;
                    }

                },
        error: function (request, status, error) {
            alert('Unable to update table contents');
            console.log(request);
            console.log(status);
            console.log(error);
        },

    });

    return table;
}

Here instead is the submit of the form which executes the search function:

 $("#search_form").submit(function (e) {
            e.preventDefault();

            var search_key = $.trim($('#val').val());
            var search_field = 'c.descr like ';

            table = $('#tablePubDev').DataTable();

            table.clear();

            table = UpdateTableCompany(search_field, search_key);

        });

I am currently using the minified format of jquery version v1.10.2
The version of datatable is 1.10.4

This is the error I get in the console

I tried an experiment: I did not load the datatable in document ready, so I made a search submit to load the datatable , and it worked! Of course if I do a second search then the same error occurs, so the problem has to do with the recreation of datatable. All the back end code (php) works correctly and gives the desired results.

Here is the table in html

                                        Company
                                        Name
                                        Listed Games
                                        Type
                                        Actions

I have tried using the unminified version of datatable (v 1.10.12) and I got still and error but now it says his:

TypeError: headerCells[i] is undefined

headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !==...

    // Clone the table header and footer - we can't use the header / footer
        // from the cloned table, since if scrolling is active, the table's
        // real header and footer are contained in different table tags
        tmpTable.find('thead, tfoot').remove();
        tmpTable
            .append( $(oSettings.nTHead).clone() )
            .append( $(oSettings.nTFoot).clone() );

        // Remove any assigned widths from the footer (from scrolling)
        tmpTable.find('tfoot th, tfoot td').css('width', '');

        // Apply custom sizing to the cloned header
        **headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0]** ); <-- This is where the error occurs <--

        for ( i=0 ; i<visibleColumns.length ; i++ ) {
            column = columns[ visibleColumns[i] ];

            headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
                _fnStringToCss( column.sWidthOrig ) :
                '';

            // For scrollX we need to force the column width otherwise the
            // browser will collapse it. If this width is smaller than the
            // width the column requires, then it will have no effect
            if ( column.sWidthOrig && scrollX ) {
                $( headerCells[i] ).append( $('
').css( {
                    width: column.sWidthOrig,
                    margin: 0,
                    padding: 0,
                    border: 0,
                    height: 1
                } ) );
            }
        }

        // Find the widest cell for each column and put it

UPDATE:

I think I know why this is happening, although I still need to find a fix for this. It just so happens that When I define my columns in the Datatable instantiation:

   "columns": [
            {"data": "c.idpubdev", "name": "c.idpubdev"},
            {"data": "c.descr", "name": "c.descr"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.publisher", "name": "c.publisher"},
            {"data": "c.date_founded", "name": "c.date_founded"},
            {"data": "c.developer", "name": "c.developer", "visible": false, "searchable": false},
            {"data": "c.logo", "name": "c.logo", "visible": false, "searchable": false},

These need to be exactly as many as the table headers that I included in my html page

                                        Company
                                        Name
                                        Listed Games
                                        Type
                                        Actions

In this case I have 5 table headers and 7  data column definitions (two have visible = false). When I used them in an older project, all I had to do was set the "visible" property to false so that they wouldn't be mapped to a table header, but here it doesn't seem to work... Why do you think that would happen? I sthere a way to work around it?


问:
String will not split using Regex
As seen in the snippet, I have a Regex that should identify any empty lines. (I'm aware I can just do /n/n, but it doesn't suit my purposes). I've tested it in a word editor, and it picks up every new line when using the find tool. But in JS, I'm still getting the entire file. What am I missing, here?

const mockData = `This is some fake data
with multiple sentences

and line breaks`;

const newArr = mockData.split(/^\s*$/);

console.log(newArr[0]);```

答:
Using the multiline flag works better

const newArr = mockData.split(/\s*$/m);

Take your pick

const re1 = /^\s*|\s*$/m
const re2 = /^\s*$/m
const re3 = /\s*$/m

const mockData = `This is some fake data
with multiple sentences

and line breaks`;

const newArr1 = mockData.split(re1);
console.log(JSON.stringify(newArr1))
const newArr2 = mockData.split(re2);
console.log(JSON.stringify(newArr2))
const newArr3 = mockData.split(re3);
console.log(JSON.stringify(newArr3))```

Title: String will not split using Regex


问:
What is a Paragraph (Microsoft.Office.Interop.Word.Paragraph)
What exactly is a paragraph in the context of Microsoft.Office.Interop.Word? I believe it is more than what the Office Word app itself considers a paragraph because the paragraphs count from the app is less than the paragraphs count returned by the Microsoft.Office.Interop.Word.Paragraphs collection. Any link that explains this will be appreciated.

UPDATE!

For example, the Microsoft Word App paragraph count (returned by clicking the word count info on the status bar) shows 40 paragraphs in the document as shown in the image below (with a red arrow pointing to the count).

The paragraph count gotten using the c# programming code in Word VSTO Add in on the other hand returns 52 paragraphs. Then every empty space (new line break without a text) added to the document (by pressing the ENTER button on the keyboard) counts as an increase in the number of paragraphs that gets returned here but that of the Word Application remains constant at 40 paragraphs. The image below shows the paragraphs count in the Visual Studio System.Diagnostics.Debug.WriteLine output.

The code used in getting the paragraph count is:

```<code>Word.Document myDoc = Globals.ThisAddIn.Application.ActiveDocument;
        Word.Paragraphs paragraphs = myDoc.Paragraphs;
        int numberOfParagraphs = paragraphs.Count;
        System.Diagnostics.Debug.WriteLine("This is the number of paragraphs returned: " + numberOfParagraphs);
</code>```

It is based on this that I need a complete understanding of which elements from the document a Microsoft.Office.Interop.Word.Paragraphscollection actually represents; especially those that are not normally counted as paragraphs by the Microsoft word application.

答:
After a little bit of testing, I think I've got an answer.

This is as much an answer as it is an educated guess, so feel free to
  correct anything wrong that you spot.

So you can actually show in word the line breaks, which defines what a paragraph is.

Now, as you can see in the picture, I have 8 line breaks but it only shows 1 paragraph in word.

So, my educated guess is that Word counts as paragraphs only the line breaks that have something written and Interop shows every line break disregarding if the text is written is null or empty.

You can actually test this hypothesis by showing the line break char in word and counting them by hand. Or, in your code, you can loop through the paragraphs and count every paragraph that has no text. If the sum of that count plus the number of paragraphs that Word shows is the same as the count of paragraphs in your code then my hypothesis is right.

If not I'm very wrong

Body:
What exactly is a paragraph in the context of Microsoft.Office.Interop.Word? I believe it is more than what the Office Word app itself considers a paragraph because the paragraphs count from the app is less than the paragraphs count returned by the Microsoft.Office.Interop.Word.Paragraphs collection. Any link that explains this will be appreciated.

UPDATE!

For example, the Microsoft Word App paragraph count (returned by clicking the word count info on the status bar) shows 40 paragraphs in the document as shown in the image below (with a red arrow pointing to the count).

The paragraph count gotten using the c# programming code in Word VSTO Add in on the other hand returns 52 paragraphs. Then every empty space (new line break without a text) added to the document (by pressing the ENTER button on the keyboard) counts as an increase in the number of paragraphs that gets returned here but that of the Word Application remains constant at 40 paragraphs. The image below shows the paragraphs count in the Visual Studio System.Diagnostics.Debug.WriteLine output.

The code used in getting the paragraph count is:

Word.Document myDoc = Globals.ThisAddIn.Application.ActiveDocument;
        Word.Paragraphs paragraphs = myDoc.Paragraphs;
        int numberOfParagraphs = paragraphs.Count;
        System.Diagnostics.Debug.WriteLine("This is the number of paragraphs returned: " + numberOfParagraphs);

It is based on this that I need a complete understanding of which elements from the document a Microsoft.Office.Interop.Word.Paragraphscollection actually represents; especially those that are not normally counted as paragraphs by the Microsoft word application.


问:
Invalid use of null error when the code shouldn't be executed
I have problem with

Invalid use of null

error. I know how to avoid it with Nz, but it doesn't answer my problem.

I have a function, which builds sql query basing on data from recordset. Here's a  (pseudo)code:

```<code>string = IIf(Nz(rst.Fields(0).Value, "") = "", "NULL", MyFunction(rst.Fields(0).Value))
</code>```

The code produces NULL value, so I think it doesn't need to execute MyFunction function, but during the runtime I receive above error and it's caused inside MyFunction - why?

答:
You could modify to:</p>

```<code>Dim NullValue As Variant

NullValue = <some value that will not cause MyFunction to fail>
string = IIf(IsNull(rst.Fields(0).Value), "NULL", MyFunction(Nz(rst.Fields(0).Value, NullValue))
</code>```

Body:
I have problem with

Invalid use of null

error. I know how to avoid it with Nz, but it doesn't answer my problem.

I have a function, which builds sql query basing on data from recordset. Here's a  (pseudo)code:

string = IIf(Nz(rst.Fields(0).Value, "") = "", "NULL", MyFunction(rst.Fields(0).Value))

The code produces NULL value, so I think it doesn't need to execute MyFunction function, but during the runtime I receive above error and it's caused inside MyFunction - why?

Body:
You could modify to:

Dim NullValue As Variant

NullValue = <some value that will not cause MyFunction to fail>
string = IIf(IsNull(rst.Fields(0).Value), "NULL", MyFunction(Nz(rst.Fields(0).Value, NullValue))


问:
Matlab coder: "All inputs must be constant"
I'm using Matlab Coder to convert this code to C++:

```<code>fs = 50;
[b,a] = butter(3,0.5/(fs/2),'high');
...
% Other code using fs
</code>```

Then, I get this error: "All inputs must be constant".

If I do: [b,a] = butter(3,0.5/(50/2),'high');, it works.

I found this post: Constants and Matlab Coder

So I tried:

```<code>fs = 50;
[b,a] = coder.const(@butter,3,0.5/(fs/2),'high');
</code>```

But it still reports the same error. How can I fix this?

答:
Define Class Properties with Constant Values

In ConstInput.m

```<code>classdef ConstInput
   properties (Constant)
      fs = 50;
   end
end
</code>```

Then rename fs as ConstInput.fs. (Unfortunately, Shift+Enter does not work. Maybe this links helps about changing variable names.)

Body:
I'm using Matlab Coder to convert this code to C++:

fs = 50;
[b,a] = butter(3,0.5/(fs/2),'high');
...
% Other code using fs

Then, I get this error: "All inputs must be constant".

If I do: [b,a] = butter(3,0.5/(50/2),'high');, it works.

I found this post: Constants and Matlab Coder

So I tried:

fs = 50;
[b,a] = coder.const(@butter,3,0.5/(fs/2),'high');

But it still reports the same error. How can I fix this?

Body:
Define Class Properties with Constant Values

In ConstInput.m

classdef ConstInput
   properties (Constant)
      fs = 50;
   end
end

Then rename fs as ConstInput.fs. (Unfortunately, Shift+Enter does not work. Maybe this links helps about changing variable names.)


问:
creating the code behind file
First i created the TimeSheet.aspx file,then added code files names TimeSheet.aspx.cs file.
created a TimeSheet class and code some code in that ,later in the @page directive added the codebehind attibute with value "TimeSheet.aspx.cs" and inherits attribute with value TimeSheet.

Now i want to make this code behind file to show up as a sub-branch of TimeSheetp.aspx.Just like a designer file.

Like

TimeSheet.aspx
|----TimeSheet.aspx.cs

how will i do that.please help me

答: If you did not let VS create the file for you when you first make the file, you just need to create a new file (class file, '.vb' or '.cs' extension) in the same directory as the file you wish to add the code behind file to with that file name as the first part of the new file name. Example, default.aspx's code behind file that you create manually will be called "default.aspx.cs".  Then in your original file, make sure you add a page directive for the newly created file: <% @Page Language="VB" Explicit="True" Codebehind="default.aspx.vb" %>

ContentLicense: CC BY-SA 2.5

Title: creating the code behind file


问:
Pass function as template argument to a class
I want to pass functions as template arguments but somehow I can't get it to work. I've written a lot of template classes in the past but only using "normal" types as arguments. I've already searched for that issue but nothing seems to fit here. So I'm stuck.

Here is what I want to achieve:
I have a couple of type specific library functions which I want to encapsulate. I know that there are other ways of doing it as well (e.g. inheritance) but since I also want to learn a little bit here, I want to get it done with the template approach.

What I want to achieve:

```<code>MyType<int> myIntObject(...);
...
int writeVal = 10;
myIntObject.Write(writeVal);
...
int readVal;
myIntObject.Read(&readVal);
</code>```

Maybe also using typedefs:

```<code>typedef MyType<int> MyIntType;
</code>```

What I did so far:

```<code>template<typename T>
struct SetFunction
{
  inline ret_code operator()(someArgs, T value) const {return E_Fail;}
}

template<typename T>
struct GetFunction
{
  inline ret_code operator()(someArgs, T& value) const {return E_Fail;}
}

//template specialization:
template<>
struct SetFunction<int>
{
  inline ret_code operator()(someArgs, T value) const
  {
    //some other code
    return libraryFunctionWriteInt(someArgs, value);
  }
}

template<>
struct GetFunction<int>
{
  inline ret_code operator()(someArgs, T& value) const
  {
    //some other code
    return libraryFunctionReadInt(someArgs, &value);
  }
}
//do the specialization for all other types as well

template<class T, typename T_get_function = GetFunction<T>(), typename T_set_function = SetFunction<T>()>
MyType
{
public:
  MyType(someArgs)
  {
    if(T_get_function(someArgs, &_value) == E_Fail)
    {
      throw someting;
    }
  }

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function(someArgs, &_value) == E_Success;
  }

private:
  T _value;
}

//and then eventually using it (maybe using some typedefs as well)
MyType<int> myIntObject(someArgs);
...
int writeVal = 10;
myIntObject.SetValue(writeValue);
...
int readVal;
myIntObject.GetValue(&readValue);
</code>```

Now I get compile errors: expression list treated as compound expression in functional cast on those two lines where I call the T_set_function / T_get_function. I also tried passing the library functions directly as template arguments and don't set any default functions but I couldn't get it to work that way as well.

Almost all of the books, articles and examples I read so far are only dealing with passing "normal" types as template arguments but since stl makes use of passing functions as well I really want to know how to do this.

答:
There is some incomplete code in regard to arguments of operator, but syntax

```<code>template<class T, typename T_get_function = GetFunction<T>(),
                  typename T_set_function = SetFunction<T>()>
</code>```

is incorrect. typename T_get_function = suggests a type parameter of template, while after = comes an expression GetFunction<T>(), not a declarator.

It should be

```<code>template<class T, typename T_get_function = GetFunction<T>,
              typename T_set_function = SetFunction<T>>
</code>```

Then it's not clear how you expect T_get_function::operator() to work without instance of class.  it's either should be static or you should have an instance.

```<code>template<class T, T_get_function getter = GetFunction<T>{},
              T_set_function setter = SetFunction<T>>{}
</code>```

in this particular case typename and class mean same thing and is nt required there. But we don't know what T_get_function is here then? putting it as a class parameter of template and assigning default class is C++20 feature.

Operator & returns a pointer to variable, you can't use it as reference (and you don't need to do that).
That metacode contains a several dozen problems ranging from missing ; to incorrect syntax and missing keywords and declarations. If you focus on C++ standard earlier than 2020, you ought to rewrite this from scratch, otherwise use Klaus's answer as guideline.

Body:
I want to pass functions as template arguments but somehow I can't get it to work. I've written a lot of template classes in the past but only using "normal" types as arguments. I've already searched for that issue but nothing seems to fit here. So I'm stuck.

Here is what I want to achieve:
I have a couple of type specific library functions which I want to encapsulate. I know that there are other ways of doing it as well (e.g. inheritance) but since I also want to learn a little bit here, I want to get it done with the template approach.

What I want to achieve:

MyType<int> myIntObject(...);
...
int writeVal = 10;
myIntObject.Write(writeVal);
...
int readVal;
myIntObject.Read(&readVal);

Maybe also using typedefs:

typedef MyType<int> MyIntType;

What I did so far:

template<typename T>
struct SetFunction
{
  inline ret_code operator()(someArgs, T value) const {return E_Fail;}
}

template<typename T>
struct GetFunction
{
  inline ret_code operator()(someArgs, T& value) const {return E_Fail;}
}

//template specialization:
template<>
struct SetFunction<int>
{
  inline ret_code operator()(someArgs, T value) const
  {
    //some other code
    return libraryFunctionWriteInt(someArgs, value);
  }
}

template<>
struct GetFunction<int>
{
  inline ret_code operator()(someArgs, T& value) const
  {
    //some other code
    return libraryFunctionReadInt(someArgs, &value);
  }
}
//do the specialization for all other types as well

template<class T, typename T_get_function = GetFunction<T>(), typename T_set_function = SetFunction<T>()>
MyType
{
public:
  MyType(someArgs)
  {
    if(T_get_function(someArgs, &_value) == E_Fail)
    {
      throw someting;
    }
  }

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function(someArgs, &_value) == E_Success;
  }

private:
  T _value;
}

//and then eventually using it (maybe using some typedefs as well)
MyType<int> myIntObject(someArgs);
...
int writeVal = 10;
myIntObject.SetValue(writeValue);
...
int readVal;
myIntObject.GetValue(&readValue);

Now I get compile errors: expression list treated as compound expression in functional cast on those two lines where I call the T_set_function / T_get_function. I also tried passing the library functions directly as template arguments and don't set any default functions but I couldn't get it to work that way as well.

Almost all of the books, articles and examples I read so far are only dealing with passing "normal" types as template arguments but since stl makes use of passing functions as well I really want to know how to do this.

Body:
There is some incomplete code in regard to arguments of operator, but syntax

template<class T, typename T_get_function = GetFunction<T>(),
                  typename T_set_function = SetFunction<T>()>

is incorrect. typename T_get_function = suggests a type parameter of template, while after = comes an expression GetFunction<T>(), not a declarator.

It should be

template<class T, typename T_get_function = GetFunction<T>,
              typename T_set_function = SetFunction<T>>

Then it's not clear how you expect T_get_function::operator() to work without instance of class.  it's either should be static or you should have an instance.

template<class T, T_get_function getter = GetFunction<T>{},
              T_set_function setter = SetFunction<T>>{}

in this particular case typename and class mean same thing and is nt required there. But we don't know what T_get_function is here then? putting it as a class parameter of template and assigning default class is C++20 feature.

Operator & returns a pointer to variable, you can't use it as reference (and you don't need to do that).
That metacode contains a several dozen problems ranging from missing ; to incorrect syntax and missing keywords and declarations. If you focus on C++ standard earlier than 2020, you ought to rewrite this from scratch, otherwise use Klaus's answer as guideline.