答:
Is this it?

```<code>library(dplyr)
library(tibble)

# make fake data
dates <- expand.grid(1910:1950, 1:12)
dates <- dates[order(dates$Var1), ]
data <- tibble(
  CENTROID_ID = rep("c1763_1", 240),
  YEAR = dates$Var1[1:240],
  MONTH = dates$Var2[1:240],
  PPT = runif(min = 1, max = 100, n = 240)
)
</code>```

And then we can determine the SEASON based on YEAR and MONTH, group and calculate the mean per group:

```<code>data <- data %>%
  mutate(SEASON = case_when(
    MONTH == 12 | MONTH == 1 | MONTH == 2 ~ "WINTER",
    MONTH == 3 | MONTH == 4 | MONTH == 5 ~ "SPRING",
    MONTH == 6 | MONTH == 7 | MONTH == 8 ~ "SUMMER",
    MONTH == 9 | MONTH == 10 | MONTH == 11 ~ "AUTUMN",
  )) %>%
  group_by(CENTROID_ID, YEAR, SEASON) %>%
  summarise(PPT_AVG = mean(PPT))
</code>```

With this result:

```<code>> data
# A tibble: 80 x 4
# Groups:   CENTROID_ID, YEAR [20]
   CENTROID_ID  YEAR SEASON PPT_AVG
   <chr>       <int> <chr>    <dbl>
 1 c1763_1      1910 AUTUMN    35.7
 2 c1763_1      1910 SPRING    44.3
 3 c1763_1      1910 SUMMER    63.3
 4 c1763_1      1910 WINTER    37.1
 5 c1763_1      1911 AUTUMN    40.7
 6 c1763_1      1911 SPRING    52.3
 7 c1763_1      1911 SUMMER    36.7
 8 c1763_1      1911 WINTER    10.7
 9 c1763_1      1912 AUTUMN    45.4
10 c1763_1      1912 SPRING    45.7
# ... with 70 more rows
</code>```

UPDATE
To shift the year we need to introduce lead(YEAR, 1). Updated the code and included SEASON as a factor with defined levels such that it sorts in a decent chronological order.

```<code>data <- data %>%
  mutate(SEASON = case_when(
    MONTH == 12 | MONTH == 1 |MONTH == 2 ~ "WINTER",
    MONTH == 3 | MONTH == 4 | MONTH == 5 ~ "SPRING",
    MONTH == 6 | MONTH == 7 | MONTH == 8 ~ "SUMMER",
    MONTH == 9 | MONTH == 10 | MONTH == 11~ "AUTUMN",
  )) %>%
  mutate(SEASON = factor(SEASON, levels = c("WINTER", "SPRING", "SUMMER", "AUTUMN"))) %>%
  mutate(YEAR_LEAD = lead(YEAR, 1)) %>%
  group_by(CENTROID_ID, YEAR_LEAD, SEASON) %>%
  summarise(PPT_AVG = mean(PPT),
            PPT_MIN = min(PPT),
            PPT_MAX = max(PPT))
</code>```

With this result:

```<code>> data
# A tibble: 81 x 6
# Groups:   CENTROID_ID, YEAR_LEAD [21]
   CENTROID_ID YEAR_LEAD SEASON PPT_AVG PPT_MIN PPT_MAX
   <chr>           <int> <fct>    <dbl>   <dbl>   <dbl>
 1 c1763_1          1910 WINTER    83.5   81.4     85.7
 2 c1763_1          1910 SPRING    72.3   52.7     96.0
 3 c1763_1          1910 SUMMER    49.9   10.9     90.0
 4 c1763_1          1910 AUTUMN    26.4    7.17    63.1
 5 c1763_1          1911 WINTER    60.9   19.0     92.6
 6 c1763_1          1911 SPRING    62.9   58.6     67.4
 7 c1763_1          1911 SUMMER    49.2   23.7     76.4
 8 c1763_1          1911 AUTUMN    43.9   15.1     84.4
 9 c1763_1          1912 WINTER    38.5   18.4     67.9
10 c1763_1          1912 SPRING    72.1   53.4     93.9
# ... with 71 more rows
</code>```

Title: How to find the average, max, and min based on multiple sets of criteria

Body:
I have found a few options from other posts but I am having trouble reproducing the code for my specific needs.

I have climate data that I would like to find the average based on season from 1910-2015 for specific locations.

Here is an example of what I need: the average PPT for CENTROID_ID c1763_1 in 1911 for Winter (Month 12 of the preceding year [1910], month 1 and 2 of year in question [1911]), Spring (months 3,4,5 in 1911), Summer (months 6,7,8 in 1911) and Fall (months 9,10,11 in 1911). This would then need to be done for all individual centroid IDs for every year. I have over 400 unique CENTROID_IDs covering years 1910-2015.

I envision the new dataframe to have the columns CENTROID_ID, YEAR, WINT_PPT, SPR_PPT, SUM_PPT, FALL_PPT.

 CENTROID_ID    YEAR MONTH  PPT
1       c1763_1 1910     1  52.639
2       c1763_1 1910     2  20.870
3       c1763_1 1910     3  21.706
4       c1763_1 1910     4   9.347
5       c1763_1 1910     5   1.201
6       c1763_1 1910     6  11.267
7       c1763_1 1910     7  41.870
8       c1763_1 1910     8  61.260
9       c1763_1 1910     9  27.815
10      c1763_1 1910    10  67.377
11      c1763_1 1910    11  24.719
12      c1763_1 1910    12  30.212
13      c1763_1 1911     1  88.728
14      c1763_1 1911     2  50.035
15      c1763_1 1911     3  37.720
16      c1763_1 1911     4  12.831
17      c1763_1 1911     5   0.739
18      c1763_1 1911     6  18.198
19      c1763_1 1911     7  74.731
20      c1763_1 1911     8  40.873
21      c1763_1 1911     9  86.340
22      c1763_1 1911    10  36.423
23      c1763_1 1911    11  12.491
24      c1763_1 1911    12  19.428
25      c1763_1 1912     1  11.010
26      c1763_1 1912     2  16.339
27      c1763_1 1912     3  72.017
28      c1763_1 1912     4  25.887
29      c1763_1 1912     5   5.314
30      c1763_1 1912     6   8.595
31      c1763_1 1912     7  47.781
32      c1763_1 1912     8  51.188
33      c1763_1 1912     9  10.931
34      c1763_1 1912    10 119.725
35      c1763_1 1912    11  10.420
36      c1763_1 1912    12   8.777
37      c1763_1 1913     1  27.771
38      c1763_1 1913     2  62.622
39      c1763_1 1913     3  17.533
40      c1763_1 1913     4   8.008
41      c1763_1 1913     5   1.423
42      c1763_1 1913     6   3.773
43      c1763_1 1913     7  42.982
44      c1763_1 1913     8  40.541
45      c1763_1 1913     9  58.495
46      c1763_1 1913    10  22.729
47      c1763_1 1913    11  48.130
48      c1763_1 1913    12  32.049
49      c1763_1 1914     1 104.197
50      c1763_1 1914     2  31.707

Body:
Is this it?

library(dplyr)
library(tibble)

# make fake data
dates <- expand.grid(1910:1950, 1:12)
dates <- dates[order(dates$Var1), ]
data <- tibble(
  CENTROID_ID = rep("c1763_1", 240),
  YEAR = dates$Var1[1:240],
  MONTH = dates$Var2[1:240],
  PPT = runif(min = 1, max = 100, n = 240)
)

And then we can determine the SEASON based on YEAR and MONTH, group and calculate the mean per group:

data <- data %>%
  mutate(SEASON = case_when(
    MONTH == 12 | MONTH == 1 | MONTH == 2 ~ "WINTER",
    MONTH == 3 | MONTH == 4 | MONTH == 5 ~ "SPRING",
    MONTH == 6 | MONTH == 7 | MONTH == 8 ~ "SUMMER",
    MONTH == 9 | MONTH == 10 | MONTH == 11 ~ "AUTUMN",
  )) %>%
  group_by(CENTROID_ID, YEAR, SEASON) %>%
  summarise(PPT_AVG = mean(PPT))

With this result:

> data
# A tibble: 80 x 4
# Groups:   CENTROID_ID, YEAR [20]
   CENTROID_ID  YEAR SEASON PPT_AVG
   <chr>       <int> <chr>    <dbl>
 1 c1763_1      1910 AUTUMN    35.7
 2 c1763_1      1910 SPRING    44.3
 3 c1763_1      1910 SUMMER    63.3
 4 c1763_1      1910 WINTER    37.1
 5 c1763_1      1911 AUTUMN    40.7
 6 c1763_1      1911 SPRING    52.3
 7 c1763_1      1911 SUMMER    36.7
 8 c1763_1      1911 WINTER    10.7
 9 c1763_1      1912 AUTUMN    45.4
10 c1763_1      1912 SPRING    45.7
# ... with 70 more rows

UPDATE
To shift the year we need to introduce lead(YEAR, 1). Updated the code and included SEASON as a factor with defined levels such that it sorts in a decent chronological order.

data <- data %>%
  mutate(SEASON = case_when(
    MONTH == 12 | MONTH == 1 |MONTH == 2 ~ "WINTER",
    MONTH == 3 | MONTH == 4 | MONTH == 5 ~ "SPRING",
    MONTH == 6 | MONTH == 7 | MONTH == 8 ~ "SUMMER",
    MONTH == 9 | MONTH == 10 | MONTH == 11~ "AUTUMN",
  )) %>%
  mutate(SEASON = factor(SEASON, levels = c("WINTER", "SPRING", "SUMMER", "AUTUMN"))) %>%
  mutate(YEAR_LEAD = lead(YEAR, 1)) %>%
  group_by(CENTROID_ID, YEAR_LEAD, SEASON) %>%
  summarise(PPT_AVG = mean(PPT),
            PPT_MIN = min(PPT),
            PPT_MAX = max(PPT))

With this result:

> data
# A tibble: 81 x 6
# Groups:   CENTROID_ID, YEAR_LEAD [21]
   CENTROID_ID YEAR_LEAD SEASON PPT_AVG PPT_MIN PPT_MAX
   <chr>           <int> <fct>    <dbl>   <dbl>   <dbl>
 1 c1763_1          1910 WINTER    83.5   81.4     85.7
 2 c1763_1          1910 SPRING    72.3   52.7     96.0
 3 c1763_1          1910 SUMMER    49.9   10.9     90.0
 4 c1763_1          1910 AUTUMN    26.4    7.17    63.1
 5 c1763_1          1911 WINTER    60.9   19.0     92.6
 6 c1763_1          1911 SPRING    62.9   58.6     67.4
 7 c1763_1          1911 SUMMER    49.2   23.7     76.4
 8 c1763_1          1911 AUTUMN    43.9   15.1     84.4
 9 c1763_1          1912 WINTER    38.5   18.4     67.9
10 c1763_1          1912 SPRING    72.1   53.4     93.9
# ... with 71 more rows


来源: stackexchange

问:
How to eliminate entity view's duplicate values?
I created a custom view for an entity. But it contains duplicate column values.

How can I show only unique values like SQL Distinct?

UPDATE:
By default, CRM consider checks for distinct record based on entire row(displayed) not just column.

答:
I can try my best to answer you. You have to understand these are not exact duplicates, unless you wanted to show the cases under each student - if that's what you meant.

If you use editable grid, then you will get grouping option. Read more

Otherwise you have to merge duplicate cases or enable duplicate detection to avoid in first place.

Update:

Looks like a reporting requirement, so probably FetchXML SSRS report or PowerBI report can be developed and embedded in this case.

ContentLicense: CC BY-SA 4.0


问:
Continuous integration server for Erlang code
What kind of agile tools are you using for Erlang development? What continuous integration (CI) server are you using to build Erlang code? The only reference I got was from Quora question How do I integrate Erlang unit tests in Jenkins (Hudson)?.

I am also interested in the nifty details of setting them up and making talk to each other.

答: We use Jenkins for our Python code, so I think you may use Jenkins with Erlang code.</p>

ContentLicense: CC BY-SA 3.0


问:
setCloseButtonIcon() method doesn't change default Close button
I try to change default icon for Close Button in Chrome custom tabs (CustomTabsIntent.Builder)

Simple code for testing:

```<code>Bitmap closeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
intentBuilder.setCloseButtonIcon(closeIcon);
</code>```

But nothing happens. Why? (Nexus 7, Marshmallow)

答:
The close icon needs to be 24dp x 24dp. Something like this:

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M7.2,14.4m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M14.8,18m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M15.2,8.8m-4.8,0a4.8,4.8 0,1 1,9.6 0a4.8,4.8 0,1 1,-9.6 0"/>
</vector>
</code>```

In Kotlin, you can retrieve this drawable and add it to your builder like this:

```<code>AppCompatResources.getDrawable(main, R.drawable.close_icon)?.let {
            DrawableCompat.setTint(it, Color.WHITE)
            builder.setCloseButtonIcon(it.toBitmap())
        }
</code>```

This answer has some more details.

Body:
I try to change default icon for Close Button in Chrome custom tabs (CustomTabsIntent.Builder)

Simple code for testing:

Bitmap closeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
intentBuilder.setCloseButtonIcon(closeIcon);

But nothing happens. Why? (Nexus 7, Marshmallow)

Body:
The close icon needs to be 24dp x 24dp. Something like this:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M7.2,14.4m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M14.8,18m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M15.2,8.8m-4.8,0a4.8,4.8 0,1 1,9.6 0a4.8,4.8 0,1 1,-9.6 0"/>
</vector>

In Kotlin, you can retrieve this drawable and add it to your builder like this:

AppCompatResources.getDrawable(main, R.drawable.close_icon)?.let {
            DrawableCompat.setTint(it, Color.WHITE)
            builder.setCloseButtonIcon(it.toBitmap())
        }

This answer has some more details.


问:
How to print data found in Binary Search Tree?
I am doing this program which reads a CSV file and enters it in a tree, until now I have managed to create the tree and it shows them in order, however with the search I have a failure since it does not show the information of the element that is being searched , someone who can help me correct the fault, thanks....

The csv file contains the data(contains several but I leave these for example.):

1,name1,number1

2,name2,number2

3,name3,number3

```<code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include <utility>
#include <experimental/optional>
intmax_t dato;

struct Person {
  intmax_t key;
  std::string name;
  intmax_t num;
};

struct Node : Person {
  Node(const Person &person) : Person(person) {}
  std::unique_ptr<Node> left, right;
  void insert(const Person &person);
};

void Node::insert(const Person &person) {
  /* recur down the tree */
  if (key > person.key) {
    if (left)
        left->insert(person);
    else
        left = std::make_unique<Node>(person);
  } else if (key < person.key) {
    if (right)
        right->insert(person);
    else
        right = std::make_unique<Node>(person);
  }
}

std::vector<Person> persons;

void inorder(Node *root) {
  if (root) {
    // cout<<"\t";

    inorder(root->left.get());
    std::cout <<  "\tID: "<< root->key << "\tName: "<< root->name << "\t\tNum: " << root->num << '\n'; //'\t' ' '
    inorder(root->right.get());
  }
}

std::experimental::optional<Person> busqueda(Node *root, intmax_t dato) {
    if(root==NULL){
    return {};
    }
    else if(root->key==dato){
        return *root;
    }
    else if(dato<root->key){
       return busqueda(root->left.get(),dato);
    }
    else{
        return busqueda(root->right.get(),dato);
    }
}

int main() {

  std::unique_ptr<Node> root;
  std::ifstream fin("data.txt");
  if (!fin) {
    std::cout << "File not open\n";
    return 1;
  }

  std::string line;
  const char delim = ',';
   std::cout<<"\t\tData\n"<<std::endl;
  while (std::getline(fin, line)) {
    std::istringstream ss(line);
    Person person;
    ss >> person.key;
    ss.ignore(10, delim);
    std::getline(ss, person.name, delim);
    ss >> person.num;
    if (ss) persons.push_back(person);
  }

  for (unsigned int i = 0; i < persons.size(); i++) {
    std::cout << std::setw(10)<<"ID:   " << persons[i].key << std::setw(30)<<"Name:   "
              << persons[i].name << std::setw(20) <<"Num:   "<< persons[i].num << '\n';
    if (!root) root = std::make_unique<Node>(persons[i]);
    else root->insert(persons[i]);
  }

  std::cout << "\n\n\t\tInorder:\n\n";

  inorder(root.get());

    std::cout<<" Enter data: "; std::cin>> dato;
        busqueda(root.get(),dato);
        if(busqueda(root.get(),dato)){
                std::cout<<"Data found"<<std::endl;
                std::cout<<root->name;//does not show the wanted, only the first of the document.
         }
        else{
            std::cout<<"\nData not found"<<std::endl;
        }

  return 0;
}
</code>```

答:
From the comments you throw away the result of your search in the following statement:

busqueda(root.get(),dato); returns an optional value std::experimental::optional but you don't make use of the value.

You test the value with if(busqueda(root.get(),dato)){ but since you did not store the result you both searched a second time and do not have a way to get the Person object.

Instead you can do this to get the person object and show its name:

```<code>std::cout << " Enter data: "; std::cin >> dato;
auto result = busqueda(root.get(), dato);
if (result) {
    std::cout << "Data found" << std::endl;
    std::cout <<result->name; // This should be the name of the found Person
}
else {
    std::cout << "\nData not found" << std::endl;
}
</code>```

Body:
I am doing this program which reads a CSV file and enters it in a tree, until now I have managed to create the tree and it shows them in order, however with the search I have a failure since it does not show the information of the element that is being searched , someone who can help me correct the fault, thanks....

The csv file contains the data(contains several but I leave these for example.):

1,name1,number1

2,name2,number2

3,name3,number3

#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include <utility>
#include <experimental/optional>
intmax_t dato;

struct Person {
  intmax_t key;
  std::string name;
  intmax_t num;
};

struct Node : Person {
  Node(const Person &person) : Person(person) {}
  std::unique_ptr<Node> left, right;
  void insert(const Person &person);
};

void Node::insert(const Person &person) {
  /* recur down the tree */
  if (key > person.key) {
    if (left)
        left->insert(person);
    else
        left = std::make_unique<Node>(person);
  } else if (key < person.key) {
    if (right)
        right->insert(person);
    else
        right = std::make_unique<Node>(person);
  }
}

std::vector<Person> persons;

void inorder(Node *root) {
  if (root) {
    // cout<<"\t";

    inorder(root->left.get());
    std::cout <<  "\tID: "<< root->key << "\tName: "<< root->name << "\t\tNum: " << root->num << '\n'; //'\t' ' '
    inorder(root->right.get());
  }
}

std::experimental::optional<Person> busqueda(Node *root, intmax_t dato) {
    if(root==NULL){
    return {};
    }
    else if(root->key==dato){
        return *root;
    }
    else if(dato<root->key){
       return busqueda(root->left.get(),dato);
    }
    else{
        return busqueda(root->right.get(),dato);
    }
}

int main() {

  std::unique_ptr<Node> root;
  std::ifstream fin("data.txt");
  if (!fin) {
    std::cout << "File not open\n";
    return 1;
  }

  std::string line;
  const char delim = ',';
   std::cout<<"\t\tData\n"<<std::endl;
  while (std::getline(fin, line)) {
    std::istringstream ss(line);
    Person person;
    ss >> person.key;
    ss.ignore(10, delim);
    std::getline(ss, person.name, delim);
    ss >> person.num;
    if (ss) persons.push_back(person);
  }

  for (unsigned int i = 0; i < persons.size(); i++) {
    std::cout << std::setw(10)<<"ID:   " << persons[i].key << std::setw(30)<<"Name:   "
              << persons[i].name << std::setw(20) <<"Num:   "<< persons[i].num << '\n';
    if (!root) root = std::make_unique<Node>(persons[i]);
    else root->insert(persons[i]);
  }

  std::cout << "\n\n\t\tInorder:\n\n";

  inorder(root.get());

    std::cout<<" Enter data: "; std::cin>> dato;
        busqueda(root.get(),dato);
        if(busqueda(root.get(),dato)){
                std::cout<<"Data found"<<std::endl;
                std::cout<<root->name;//does not show the wanted, only the first of the document.
         }
        else{
            std::cout<<"\nData not found"<<std::endl;
        }

  return 0;
}

Body:
From the comments you throw away the result of your search in the following statement:

busqueda(root.get(),dato); returns an optional value std::experimental::optional but you don't make use of the value.

You test the value with if(busqueda(root.get(),dato)){ but since you did not store the result you both searched a second time and do not have a way to get the Person object.

Instead you can do this to get the person object and show its name:

std::cout << " Enter data: "; std::cin >> dato;
auto result = busqueda(root.get(), dato);
if (result) {
    std::cout << "Data found" << std::endl;
    std::cout <<result->name; // This should be the name of the found Person
}
else {
    std::cout << "\nData not found" << std::endl;
}


问:
How can I find the dimensions of a matrix in Python?
How can I find the dimensions of a matrix in Python. Len(A) returns only one variable.

Edit:

```<code>close = dataobj.get_data(timestamps, symbols, closefield)
</code>```

Is (I assume) generating a matrix of integers (less likely strings). I need to find the size of that matrix, so I can run some tests without having to iterate through all of the elements. As far as the data type goes, I assume it's an array of arrays (or list of lists).

Body:
How can I find the dimensions of a matrix in Python. Len(A) returns only one variable.

Edit:

close = dataobj.get_data(timestamps, symbols, closefield)

Is (I assume) generating a matrix of integers (less likely strings). I need to find the size of that matrix, so I can run some tests without having to iterate through all of the elements. As far as the data type goes, I assume it's an array of arrays (or list of lists).

Body:
m = [[1, 1, 1, 0],[0, 5, 0, 1],[2, 1, 3, 10]]

print(len(m),len(m[0]))

Output

(3 4)


问:
Swing thread safety boilerplate
For the sake of simplicity, imagine an application that downloads a file. There is a simple GUI with one label that displays progress. To avoid EDT violations, like every lawful citizen I download the file in one thread (main), and update GUI in another (EDT). So, here's the relevant chunk of pseudcode:

```<code>class Downloader {
    download() {
        progress.startDownload();
        while(hasMoreChunks()) {
            downloadChunk();
            progress.downloadedBytes(n);
        }
        progress.finishDownload();
    }
}

class ProgressDisplay extends JPanel {
    JLabel label;
    startDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download started");
            }
        });
    }
    downloadedBytes(int n) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Downloaded bytes: " + n);
            }
        });
    }
    finishDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download finished");
            }
        });
    }
}
</code>```

I love the fact that Java does not support closures and the code is crystal clear to me. Jokes aside, I'm wondering... Am I doing it wrong? Is it possible to eliminate all this ugly boilerplate with SwingUtilities, anonymous implementation of Runnable in every method etc.?

My case is slightly more complicated than this, but I'm trying not to overengineer by implementing proxies or something like that.

答:
Just a raw idea:

```<code>public class ThreadSafeJLabel extends JLabel {

    @Override
    public void setText(final String text) {
        if (SwingUtilities.isEventDispatchThread()) {
            super.setText(text);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setText(text);
                }
            });
        }
    }

}
</code>```

Haven't tried it but I guess when called setText() from EDT, super will be used; but when other thread is involved, the overridden (ThreadSafeJLabel.setText()) will be called later, this time inside EDT.

Title: Swing thread safety boilerplate

Body:
For the sake of simplicity, imagine an application that downloads a file. There is a simple GUI with one label that displays progress. To avoid EDT violations, like every lawful citizen I download the file in one thread (main), and update GUI in another (EDT). So, here's the relevant chunk of pseudcode:

class Downloader {
    download() {
        progress.startDownload();
        while(hasMoreChunks()) {
            downloadChunk();
            progress.downloadedBytes(n);
        }
        progress.finishDownload();
    }
}

class ProgressDisplay extends JPanel {
    JLabel label;
    startDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download started");
            }
        });
    }
    downloadedBytes(int n) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Downloaded bytes: " + n);
            }
        });
    }
    finishDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download finished");
            }
        });
    }
}

I love the fact that Java does not support closures and the code is crystal clear to me. Jokes aside, I'm wondering... Am I doing it wrong? Is it possible to eliminate all this ugly boilerplate with SwingUtilities, anonymous implementation of Runnable in every method etc.?

My case is slightly more complicated than this, but I'm trying not to overengineer by implementing proxies or something like that.

Body:
Just a raw idea:

public class ThreadSafeJLabel extends JLabel {

    @Override
    public void setText(final String text) {
        if (SwingUtilities.isEventDispatchThread()) {
            super.setText(text);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setText(text);
                }
            });
        }
    }

}

Haven't tried it but I guess when called setText() from EDT, super will be used; but when other thread is involved, the overridden (ThreadSafeJLabel.setText()) will be called later, this time inside EDT.


问:
How to check if database schema matches Entity Framework schema?
For my surprise, using the CreateDatabaseIfNotExists context initializer, the line

```<code>context.Database.Initialize(true)
</code>```

doesn't throw an exception if the schema does not match my code first schema.

Is there a way to validate if the current database matches our schema before, for instance, we try to access a entity, whose table doesn't exist on the database anymore, and an exception is thrown by EF?

答:
There are two tools to do this. This first one is popular and highly developed:

the developer's explanation: https://www.thereformedprogrammer.net/ef-core-taking-full-control-of-the-database-schema/

As you'll see, the developer's own explanation includes a thorough overview of Code-First, Database-First, and SQL-First approaches. He discusses pros and cons of all approaches. And shows why the Schema Compare tool is necessary to use a SQL-First approach.

the github project: https://github.com/JonPSmith/EfCore.TestSupport/wiki/9.-EfSchemaCompare

And there is a lesser-known second one mentioned by another commentor above:
https://github.com/reckface/EntityFramework.Verify

The second developer also suggests DbUp, which offers a Philosophy article that I think is a worthwhile read on why the "Microsofty" code-first and db-first approaches are problematic, and why the idea of viewing database changes as a state system is arguably a poor choice.
https://dbup.readthedocs.io/en/latest/philosophy-behind-dbup/

Body:
For my surprise, using the CreateDatabaseIfNotExists context initializer, the line

context.Database.Initialize(true)

doesn't throw an exception if the schema does not match my code first schema.

Is there a way to validate if the current database matches our schema before, for instance, we try to access a entity, whose table doesn't exist on the database anymore, and an exception is thrown by EF?


问:
How can I run two queries and return two objects in my route call?
I would like to add another query call (using Mongoose for MongoDB) and return the object the same way I am returning my Car object. Is there a way I can run the second query for the router to return both objects?    </p>

```<code>router.get('/:car', ensureAuthenticated, (req, res) =>
    Car.find({user: req.user._id, car: req.params.car}).lean().exec( function(err, cars){
        return res.render('cardetails', {
            user: req.user,
            cars: JSON.stringify(cars),
            carnum: req.params.car,
            content: cars[0].content,
            status: cars[0].status
        });
    }));
</code>```

答:
```<code>exports.postDelete=(req,res,next)=>{
  const shname=req.body.sname;
  let fod='';
  Shop.find().then(food=>{
    fod=food;
    return fod;
  }).then(result=>{    //1st obj
    Shop.findOne({shopName:shname})
    .populate({path: 'foodId',
    match: { isVerified: true }})
    .then(foods=>{  //2nd obj
      console.log(foods);
      res.render('admin/delete',{
        pageTitle:'Delete Food',
        path:'admin/deletefood',
        foodlist:result,
        flist:foods.foodId
    });
    })

    .catch(err=>{
      console.log(err);
      res.send("error");
    });

  })

  .catch(err=>{
    console.log(err);
    res.send("error");
  });

};

refer the above snippet
</code>```

Body:
I would like to add another query call (using Mongoose for MongoDB) and return the object the same way I am returning my Car object. Is there a way I can run the second query for the router to return both objects?

router.get('/:car', ensureAuthenticated, (req, res) =>
    Car.find({user: req.user._id, car: req.params.car}).lean().exec( function(err, cars){
        return res.render('cardetails', {
            user: req.user,
            cars: JSON.stringify(cars),
            carnum: req.params.car,
            content: cars[0].content,
            status: cars[0].status
        });
    }));


问:
Check if redis key is hash or string using restTemplate
I have Redis DB consisting of hashes and strings.

I got all keys from DB using this code:

```<code>        Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());

        Iterator<byte[]> it = keys.iterator();

        while(it.hasNext()){

            byte[] data = (byte[])it.next();

            String key = (new String(data, 0, data.length));
            System.out.println(key);
        }
</code>```

from here: How to get all Keys from Redis using redis template

Since the key can be hash or string, how to determine when I can use opsForHash and opsForValue i.e. how to check if it is hash or it is a string in spring boot using restTemplate.

答:
The Redis command to get the type of a key is TYPE: https://redis.io/commands/type

You can use RedisTemplate's public DataType type(K key) method to execute this: https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate.html#type-K-

Here's an example:

```<code>Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());

Iterator<byte[]> it = keys.iterator();

while(it.hasNext()){
    byte[] data = (byte[])it.next();
    String key = (new String(data, 0, data.length));

    DataType type = redisTemplate.type(key);

    if (type == DataType.HASH) {
       // ...
    } else if (type == DataType.STRING) {
       // ...
    }
}
</code>```

Edit: one more piece of advice is that you may want to use SCAN instead of KEYS * (mentioned in one answer to the SO question you linked). Scan is generally better in production since it doesn't try to get and return all keys at once.

Body:
I have Redis DB consisting of hashes and strings.

I got all keys from DB using this code:

        Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());

        Iterator<byte[]> it = keys.iterator();

        while(it.hasNext()){

            byte[] data = (byte[])it.next();

            String key = (new String(data, 0, data.length));
            System.out.println(key);
        }

from here: How to get all Keys from Redis using redis template

Since the key can be hash or string, how to determine when I can use opsForHash and opsForValue i.e. how to check if it is hash or it is a string in spring boot using restTemplate.

Body:
The Redis command to get the type of a key is TYPE: https://redis.io/commands/type

You can use RedisTemplate's public DataType type(K key) method to execute this: https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate.html#type-K-

Here's an example:

Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());

Iterator<byte[]> it = keys.iterator();

while(it.hasNext()){
    byte[] data = (byte[])it.next();
    String key = (new String(data, 0, data.length));

    DataType type = redisTemplate.type(key);

    if (type == DataType.HASH) {
       // ...
    } else if (type == DataType.STRING) {
       // ...
    }
}

Edit: one more piece of advice is that you may want to use SCAN instead of KEYS * (mentioned in one answer to the SO question you linked). Scan is generally better in production since it doesn't try to get and return all keys at once.


问:
Something get wrong with musicCursor in "react-native-get-music-files"
I am calling this function MusicFiles.getAll. It returns Something get wrong with musicCursor. Instead, it should return an array of all the music tracks.

```<code> MusicFiles.getAll({})
        .then(tracks => {
          console.log(tracks);
        })
        .catch(error => {
          console.log(error);
        });
</code>```

The expected output is supposed to be something like this.

```<code>[
  {
    id : 1,
    title : "La danza del fuego",
    author : "Mago de Oz",
    album : "Finisterra",
    genre : "Folk",
    duration : 132132312321, // miliseconds
    cover : "file:///sdcard/0/123.png",
    blur : "file:///sdcard/0/123.png",
    path : "/sdcard/0/la-danza-del-fuego.mp3"
  }
]
</code>```

答: In my case this was happening when no music on my device. I was running an emulator. I copied files using drag n' drop. Files were copied but not showing in device file manager. Restarted the device. Got the files.</p>

Body:
I am calling this function MusicFiles.getAll. It returns Something get wrong with musicCursor. Instead, it should return an array of all the music tracks.

 MusicFiles.getAll({})
        .then(tracks => {
          console.log(tracks);
        })
        .catch(error => {
          console.log(error);
        });

The expected output is supposed to be something like this.

[
  {
    id : 1,
    title : "La danza del fuego",
    author : "Mago de Oz",
    album : "Finisterra",
    genre : "Folk",
    duration : 132132312321, // miliseconds
    cover : "file:///sdcard/0/123.png",
    blur : "file:///sdcard/0/123.png",
    path : "/sdcard/0/la-danza-del-fuego.mp3"
  }
]


问:
problems with a perl "system" script
Im trying to write a very simple script that copies files from several remote computers to my computer. I've written the following in perl:

```<code>@Comps = ("comp1","comp2","comp3","comp4");

foreach $comp (@Comps)
{
  system("copy /Y \\\\$comp\\c\$\\myfolder\\$comp*.log   C:\\Program Files\\My Cont Folder\\input\\");
}
</code>```

I get a syntax error and cant understand why.

Thanks!

答:
Perl and windows paths don't mix very well, why not use File::Copy instead?

```<code>use File::Copy;
copy($file1,$file2) or die "Copy failed: $!";
</code>```

And then you can use forward slash in your paths instead. Much easier.

Title: problems with a perl "system" script

Body:
Im trying to write a very simple script that copies files from several remote computers to my computer. I've written the following in perl:

@Comps = ("comp1","comp2","comp3","comp4");

foreach $comp (@Comps)
{
  system("copy /Y \\\\$comp\\c\$\\myfolder\\$comp*.log   C:\\Program Files\\My Cont Folder\\input\\");
}

I get a syntax error and cant understand why.

Thanks!

Body:
Perl and windows paths don't mix very well, why not use File::Copy instead?

use File::Copy;
copy($file1,$file2) or die "Copy failed: $!";

And then you can use forward slash in your paths instead. Much easier.


问:
bootstrap and npm - How do I import only the "reboot.scss" file in my project?
I've started a simple playground project where I only have installed bootstrap (with npm install bootstrap), and the scss compiler package (with node install nose-sass).

I only need the reboot.scss code at the moment.

I would like to import it in my custom scss file and then start writing my bespoke scss code.

My scss file is in /src/scss/style.scss.

And I'm trying to import the bootstrap reboot file, which is /node_modules/bootstrap/scss/bootstrap-reboot.scss.

In my /src/scss/style.scss I wrote:

```<code>@import "../../node_modules/bootstrap/scss/bootstrap-reboot";
</code>```

I need the reboot style from bootstrap. Is there a better way to do it?

答:
Yep, you are correct.

Check this out: this is the documentation on how to do exactly what you mention.

https://getbootstrap.com/docs/4.0/getting-started/theming/#importing

Body:
I've started a simple playground project where I only have installed bootstrap (with npm install bootstrap), and the scss compiler package (with node install nose-sass).

I only need the reboot.scss code at the moment.

I would like to import it in my custom scss file and then start writing my bespoke scss code.

My scss file is in /src/scss/style.scss.

And I'm trying to import the bootstrap reboot file, which is /node_modules/bootstrap/scss/bootstrap-reboot.scss.

In my /src/scss/style.scss I wrote:

@import "../../node_modules/bootstrap/scss/bootstrap-reboot";

I need the reboot style from bootstrap. Is there a better way to do it?


问:
CSS Grid - Rules for a column that must be as narrow as possible but with a max width of 50%
I have a very simple grid, with two columns. The left column is a picture and the right column is some text.

I want the left column to adjust to the picture width (so the column must be as narrow as possible, as long as the picture fits). But I also want this column to take maximum 50% of the grid width.

I tried a couple of things like:

```<code>display: grid;
grid-template-columns: minmax(auto, 50%) 1fr;
</code>```

But that doesn't work: the left column always takes 50%, even with a small picture!

So how can I tell it to take less width if the picture is smaller?

(Please note that the width of the picture is max-width: 100%)

答:
You were on the right track, you can use a combination of minmax() and max-content.

Set the image column to a minimum of auto and a maximum of max-content while setting the text column to a minimum of 50% and a maximum of auto.

```<code>grid-template-columns: minmax(auto, max-content) minmax(50%, auto);
</code>```

The minimum of 50% on the text column will ensure that the picture is never wider than 50%, while the maximum of auto ensures that the text will grow larger when the image is less than 50% wide.

On the other hand, the minimum of auto on the image will ensure that it adjusts to fit to the image's size when less than 50%... while the maximum of max-content allows the text column to extend all the way passed 50% to meet the image's intrinsic width.

You could also use fit-content() for the image column instead of minmax(auto, max-content), but that amounts to the same thing (see https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content).

Here a snippet:

#grid {
  display: grid;
  grid-template-columns: minmax(auto, max-content) minmax(50%, auto);

}
img {
  max-width: 100%;
}
.grid-item {
  border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="grid">
  <img class="grid-item"src="https://via.placeholder.com/150" alt="">
  <p class="grid-item">Some Text</p>
</div></code>```

To test you can adjust the number at the end of the placeholder image URL to make it bigger or smaller. Here in fiddle form: https://jsfiddle.net/98gme470/

Note the lacking support for max-content and fit-content() in IE: https://caniuse.com/#search=max-content

Body:
I have a very simple grid, with two columns. The left column is a picture and the right column is some text.

I want the left column to adjust to the picture width (so the column must be as narrow as possible, as long as the picture fits). But I also want this column to take maximum 50% of the grid width.

I tried a couple of things like:

display: grid;
grid-template-columns: minmax(auto, 50%) 1fr;

But that doesn't work: the left column always takes 50%, even with a small picture!

So how can I tell it to take less width if the picture is smaller?

(Please note that the width of the picture is max-width: 100%)

Body:
You were on the right track, you can use a combination of minmax() and max-content.

Set the image column to a minimum of auto and a maximum of max-content while setting the text column to a minimum of 50% and a maximum of auto.

grid-template-columns: minmax(auto, max-content) minmax(50%, auto);

The minimum of 50% on the text column will ensure that the picture is never wider than 50%, while the maximum of auto ensures that the text will grow larger when the image is less than 50% wide.

On the other hand, the minimum of auto on the image will ensure that it adjusts to fit to the image's size when less than 50%... while the maximum of max-content allows the text column to extend all the way passed 50% to meet the image's intrinsic width.

You could also use fit-content() for the image column instead of minmax(auto, max-content), but that amounts to the same thing (see https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content).

Here a snippet:

#grid {
  display: grid;
  grid-template-columns: minmax(auto, max-content) minmax(50%, auto);

}
img {
  max-width: 100%;
}
.grid-item {
  border: 1px solid red;
}

<div id="grid">
  <img class="grid-item"src="https://via.placeholder.com/150" alt="">
  <p class="grid-item">Some Text</p>
</div>

To test you can adjust the number at the end of the placeholder image URL to make it bigger or smaller. Here in fiddle form: https://jsfiddle.net/98gme470/

Note the lacking support for max-content and fit-content() in IE: https://caniuse.com/#search=max-content


问:
Deleting one row (only if it is empty) before specific word
For the topic "VBA - WORD Deleting rows after and before specific word".

I almost need the same macro, I would like to delete one row before specific text (#N/A), but only if that row is empty.

```<code>Sub ScratchMacroIII()
Dim oRng As Word.Range
Dim para As Word.Paragraph
Dim found As Boolean

Set oRng = ActiveDocument.Range
With oRng.Find
  .Text = "#N/A"
  .wrap = wdFindStop
  found = .Execute
    Do While found
        Set para = oRng.Next(wdParagraph, -1).Paragraphs(1)
        para.Range.Delete
        oRng.Collapse wdCollapseEnd
        oRng.End = ActiveDocument.content.End
        found = oRng.Find.Execute
     Loop

End With
End Sub
</code>```

答:
Try:</p>

```<code>Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
  .Text = "#N/A"
  .Wrap = wdFindStop
  End With
  Do While .Find.Execute = True
    If .Information(wdWithInTable) = True Then
      If .Cells(1).RowIndex > 1 Then
        With .Tables(1).Rows(.Cells(1).RowIndex - 1)
          If Len(.Range.Text) = .Cells.Count * 2 + 2 Then .Delete
        End With
      End If
    Else
      If .Paragraphs.First.Range.Start > 0 Then
        With .Paragraphs.First.Previous.Range.Paragraphs.First.Range
          If Len(.Text) = 1 Then .Delete
        End With
      End If
    End If
    .Collapse wdCollapseEnd
  Loop
End With
Application.ScreenUpdating = True
End Sub
</code>```

Body:
For the topic "VBA - WORD Deleting rows after and before specific word".

I almost need the same macro, I would like to delete one row before specific text (#N/A), but only if that row is empty.

Sub ScratchMacroIII()
Dim oRng As Word.Range
Dim para As Word.Paragraph
Dim found As Boolean

Set oRng = ActiveDocument.Range
With oRng.Find
  .Text = "#N/A"
  .wrap = wdFindStop
  found = .Execute
    Do While found
        Set para = oRng.Next(wdParagraph, -1).Paragraphs(1)
        para.Range.Delete
        oRng.Collapse wdCollapseEnd
        oRng.End = ActiveDocument.content.End
        found = oRng.Find.Execute
     Loop

End With
End Sub

Body:
Try:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
  .Text = "#N/A"
  .Wrap = wdFindStop
  End With
  Do While .Find.Execute = True
    If .Information(wdWithInTable) = True Then
      If .Cells(1).RowIndex > 1 Then
        With .Tables(1).Rows(.Cells(1).RowIndex - 1)
          If Len(.Range.Text) = .Cells.Count * 2 + 2 Then .Delete
        End With
      End If
    Else
      If .Paragraphs.First.Range.Start > 0 Then
        With .Paragraphs.First.Previous.Range.Paragraphs.First.Range
          If Len(.Text) = 1 Then .Delete
        End With
      End If
    End If
    .Collapse wdCollapseEnd
  Loop
End With
Application.ScreenUpdating = True
End Sub


问:
Numpy Array Multiplication
I couldn't seem to find this problem on stackoverflow although I'm sure someone has asked this before.

I have two numpy arrays as follows:

```<code>a = np.ones(shape = (2,10))
b = np.ones(2)

</code>```

I want to multiply the first row of 10 of a by the first number in b and the second row by the second number. I can do this using lists as follows:

```<code>np.array([x*y for x,y in zip(b,a)])

</code>```

I was wondering if there is a way to do this in numpy that would be a similar one liner to the list method.

I am aware I can reshape a to (1,2,10) and b to (2,1) to effectively achieve this - is this the only solution? Or is there a numpy method that can do this without manually reshaping.

答:
This might be what you are looking for:

```<code>a*np.tile(np.expand_dims(b,axis=1),(1,10))
</code>```

If you want to make use of the automatic numpy broadcasting, you need to reshape b first:

```<code>np.multiply(a, b.reshape(2,1))
</code>```

Title: Numpy Array Multiplication

Body:
I couldn't seem to find this problem on stackoverflow although I'm sure someone has asked this before.

I have two numpy arrays as follows:

a = np.ones(shape = (2,10))
b = np.ones(2)

I want to multiply the first row of 10 of a by the first number in b and the second row by the second number. I can do this using lists as follows:

np.array([x*y for x,y in zip(b,a)])

I was wondering if there is a way to do this in numpy that would be a similar one liner to the list method.

I am aware I can reshape a to (1,2,10) and b to (2,1) to effectively achieve this - is this the only solution? Or is there a numpy method that can do this without manually reshaping.

Body:
This might be what you are looking for:

a*np.tile(np.expand_dims(b,axis=1),(1,10))

If you want to make use of the automatic numpy broadcasting, you need to reshape b first:

np.multiply(a, b.reshape(2,1))


问:
Get domain the server was reached over?
In general on any non-HTTP server. Would there be a way to detect what domain was used to reach the IP?

I know HTTP servers get the domain passed within the request header, but would this be possible with any other server that does not require this information to be received from the client?

I'm especially looking for a way to do this with the minecraft server (Bukkit) so my preferred language (if needed for you to answer) would be Java. But I'd like to not have the theories about this language specific.

答: No. The only way to get the DNS name used to connect to a server is to have the client provide it.</p>

Title: Get domain the server was reached over?


问:
Tensorflow Keras RMSE metric returns different results than my own built RMSE loss function
This is a regression problem

My custom RMSE loss:

```<code>def root_mean_squared_error_loss(y_true, y_pred):
    return tf.keras.backend.sqrt(tf.keras.losses.MSE(y_true, y_pred))
</code>```

Training code sample, where create_model returns a dense fully connected sequential model

```<code>from tensorflow.keras.metrics import RootMeanSquaredError
model = create_model()
model.compile(loss=root_mean_squared_error_loss, optimizer='adam', metrics=[RootMeanSquaredError()])

model.fit(train_.values,
          targets,
          validation_split=0.1,
          verbose=1,
          batch_size=32)
</code>```

```<code>Train on 3478 samples, validate on 387 samples
Epoch 1/100
3478/3478 [==============================] - 2s 544us/sample - loss: 1.1983 - root_mean_squared_error: 0.7294 - val_loss: 0.7372 - val_root_mean_squared_error: 0.1274
Epoch 2/100
3478/3478 [==============================] - 1s 199us/sample - loss: 0.8371 - root_mean_squared_error: 0.3337 - val_loss: 0.7090 - val_root_mean_squared_error: 0.1288
Epoch 3/100
3478/3478 [==============================] - 1s 187us/sample - loss: 0.7336 - root_mean_squared_error: 0.2468 - val_loss: 0.6366 - val_root_mean_squared_error: 0.1062
Epoch 4/100
3478/3478 [==============================] - 1s 187us/sample - loss: 0.6668 - root_mean_squared_error: 0.2177 - val_loss: 0.5823 - val_root_mean_squared_error: 0.0818
</code>```

I expected both loss and root_mean_squared_error to have same values, why is there a difference?

答:
Two key differences, from source code:

RMSE is a stateful metric (it keeps memory) - yours is stateless

Square root is applied after taking a global mean, not before an axis=-1 mean like MSE does

As a result of 1, 2 is more involved: mean of a running quantity, total, is taken, with respect to another running quantity, count; both quantities are reset via RMSE.reset_states().

The raw formula fix is easy - but integrating statefulness will require work, as is beyond the scope of this question; refer to source code to see how it's done. A fix for 2 with a comparison, below.

import numpy as np
import tensorflow as tf
from tensorflow.keras.metrics import RootMeanSquaredError as RMSE

def root_mean_squared_error_loss(y_true, y_pred):
    return tf.sqrt(tf.reduce_mean(tf.math.squared_difference(y_true, y_pred)))

np.random.seed(0)

#%%###########################################################################
rmse = RMSE(dtype='float64')
rmsel = root_mean_squared_error_loss

x1 = np.random.randn(32, 10)
y1 = np.random.randn(32, 10)
x2 = np.random.randn(32, 10)
y2 = np.random.randn(32, 10)

#%%###########################################################################
print("TensorFlow RMSE:")
print(rmse(x1, y1))
print(rmse(x2, y2))
print("=" * 46)
print(rmse(x1, y1))
print(rmse(x2, y2))

print("\nMy RMSE:")
print(rmsel(x1, y1))
print(rmsel(x2, y2))
```

<pre class="lang-py prettyprint-override"><code>TensorFlow RMSE:
tf.Tensor(1.4132492562096124, shape=(), dtype=float64)
tf.Tensor(1.3875944990740972, shape=(), dtype=float64)
==============================================
tf.Tensor(1.3961984634354354, shape=(), dtype=float64)  # same inputs, different result
tf.Tensor(1.3875944990740972, shape=(), dtype=float64)  # same inputs, different result

My RMSE:
tf.Tensor(1.4132492562096124, shape=(), dtype=float64)  # first result agrees
tf.Tensor(1.3614563994283353, shape=(), dtype=float64)  # second differs since stateless
</code>```

Body:
This is a regression problem

My custom RMSE loss:

def root_mean_squared_error_loss(y_true, y_pred):
    return tf.keras.backend.sqrt(tf.keras.losses.MSE(y_true, y_pred))

Training code sample, where create_model returns a dense fully connected sequential model

from tensorflow.keras.metrics import RootMeanSquaredError
model = create_model()
model.compile(loss=root_mean_squared_error_loss, optimizer='adam', metrics=[RootMeanSquaredError()])

model.fit(train_.values,
          targets,
          validation_split=0.1,
          verbose=1,
          batch_size=32)

Train on 3478 samples, validate on 387 samples
Epoch 1/100
3478/3478 [==============================] - 2s 544us/sample - loss: 1.1983 - root_mean_squared_error: 0.7294 - val_loss: 0.7372 - val_root_mean_squared_error: 0.1274
Epoch 2/100
3478/3478 [==============================] - 1s 199us/sample - loss: 0.8371 - root_mean_squared_error: 0.3337 - val_loss: 0.7090 - val_root_mean_squared_error: 0.1288
Epoch 3/100
3478/3478 [==============================] - 1s 187us/sample - loss: 0.7336 - root_mean_squared_error: 0.2468 - val_loss: 0.6366 - val_root_mean_squared_error: 0.1062
Epoch 4/100
3478/3478 [==============================] - 1s 187us/sample - loss: 0.6668 - root_mean_squared_error: 0.2177 - val_loss: 0.5823 - val_root_mean_squared_error: 0.0818

I expected both loss and root_mean_squared_error to have same values, why is there a difference?

Body:
Two key differences, from source code:

RMSE is a stateful metric (it keeps memory) - yours is stateless

Square root is applied after taking a global mean, not before an axis=-1 mean like MSE does

As a result of 1, 2 is more involved: mean of a running quantity, total, is taken, with respect to another running quantity, count; both quantities are reset via RMSE.reset_states().

The raw formula fix is easy - but integrating statefulness will require work, as is beyond the scope of this question; refer to source code to see how it's done. A fix for 2 with a comparison, below.

import numpy as np
import tensorflow as tf
from tensorflow.keras.metrics import RootMeanSquaredError as RMSE

def root_mean_squared_error_loss(y_true, y_pred):
    return tf.sqrt(tf.reduce_mean(tf.math.squared_difference(y_true, y_pred)))

np.random.seed(0)

#%%###########################################################################
rmse = RMSE(dtype='float64')
rmsel = root_mean_squared_error_loss

x1 = np.random.randn(32, 10)
y1 = np.random.randn(32, 10)
x2 = np.random.randn(32, 10)
y2 = np.random.randn(32, 10)

#%%###########################################################################
print("TensorFlow RMSE:")
print(rmse(x1, y1))
print(rmse(x2, y2))
print("=" * 46)
print(rmse(x1, y1))
print(rmse(x2, y2))

print("\nMy RMSE:")
print(rmsel(x1, y1))
print(rmsel(x2, y2))

TensorFlow RMSE:
tf.Tensor(1.4132492562096124, shape=(), dtype=float64)
tf.Tensor(1.3875944990740972, shape=(), dtype=float64)
==============================================
tf.Tensor(1.3961984634354354, shape=(), dtype=float64)  # same inputs, different result
tf.Tensor(1.3875944990740972, shape=(), dtype=float64)  # same inputs, different result

My RMSE:
tf.Tensor(1.4132492562096124, shape=(), dtype=float64)  # first result agrees
tf.Tensor(1.3614563994283353, shape=(), dtype=float64)  # second differs since stateless


问:
placement new on a class with reference field
This is a code example from the C++20 spec ([basic.life]/8):

```<code>struct C {
  int i;
  void f();
  const C& operator=( const C& );
};

const C& C::operator=( const C& other) {
  if ( this != &other ) {
    this->~C();              // lifetime of *this ends
    new (this) C(other);     // new object of type C created
    f();                     // well-defined
  }
  return *this;
}

int main() {
  C c1;
  C c2;
  c1 = c2;   // well-defined
  c1.f();    // well-defined; c1 refers to a new object of type C
}
</code>```

Would the following be legal or undefined behavior:

```<code>struct C {
  int& i; // <= the field is now a reference
  void foo(const C& other) {
    if ( this != &other ) {
      this->~C();
      new (this) C(other);
    }
  }
};

int main() {
    int i = 3, j = 5;
    C c1 {.i = i};
    std::cout << c1.i << std::endl;
    C c2 {.i = j};
    c1.foo(c2);
    std::cout << c1.i << std::endl;
}
</code>```

In case it is illegal, would std::launder make it legal? where should it be added?

Note: p0532r0 (page 5) uses launder for a similar case.

In case it is legal, how can it work without "Pointer optimization barrier" (i.e. std::launder)? how do we avoid the compiler from caching the value of c1.i?

The question relates to an old ISO thread regarding Implementability of std::optional.

The question applies also, quite similarly, to a constant field (i.e. if above i in struct C is: const int i).

EDIT

It seems, as @Language Lawyer points out in an answer below, that the rules have been changed in C++20, in response to RU007/US042 NB comments.

C++17 Specifications [ptr.launder] (§ 21.6.4.4): --emphasis mine--

[ Note: If a new object is created in storage occupied by an existing
  object of the same type, a pointer to the original object can be used
  to refer to the new object unless the type contains const or reference
  members; in the latter cases, this function can be used to obtain a
  usable pointer to the new object. ...— end note ]

C++17 [ptr.launder] code example in the spec (§ 21.6.4.5):

```<code>struct X { const int n; };
X *p = new X{3};
const int a = p->n;
new (p) X{5}; // p does not point to new object (6.8) because X::n is const
const int b = p->n; // undefined behavior
const int c = std::launder(p)->n; // OK
</code>```

C++20 [ptr.launder] Specifications (§ 17.6.4.5):

[ Note: If a new object is created in storage occupied by an existing
  object of the same type, a pointer to the original object can be used
  to refer to the new object unless its complete object is a const
  object or it is a base class subobject; in the latter cases, this
  function can be used to obtain a usable pointer to the new object.
  ...— end note ]

Note that the part:

unless the type contains const or reference members;

that appeared in C++17 was removed in C++20, and the example was changed accordingly.

C++20 [ptr.launder] code example in the spec (§ 17.6.4.6):

```<code>struct X { int n; };
const X *p = new const X{3};
const int a = p->n;
new (const_cast<X*>(p)) const X{5}; // p does not point to new object ([basic.life])
                                    // because its type is const
const int b = p->n;                 // undefined behavior
const int c = std::launder(p)->n;   // OK
</code>```

Thus, apparently the code in question is legal in C++20 as is, while with C++17 it requires using std::launder when accessing the new object.

Open Questions:

What is the case of such code in C++14 or before (when std::launder didn't exist)? Probably it is UB - this is why std::launder was brought to the game, right?

If in C++20 we do not need std::launder for such a case, how the compiler can understand that the reference is being manipulated without our help (i.e. without "Pointer optimization barrier") to avoid caching of the reference value?

Similar questions here, here, here and here got contradicting answers, some see that as a valid syntax but advise to rewrite it. I'm focusing on the validity of the syntax and the need (yes or no) for std::launder, in the different C++ versions.

答:
It is legal to replace objects with const-qualified and reference non-static data members. And now, in C++20, [the name of|a [pointer|reference] to] the original object will refer to the new object after replacement. The rules has been changed in response to RU007/US042 NB comments http://wg21.link/p1971r0#RU007:

RU007. [basic.life].8.3 Relax pointer value/aliasing rules

...

Change 6.7.3 [basic.life] bullet 8.3 as follows:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:

...

the <s>type of the</s> original object is <s>not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type</s> neither a complete object that is const-qualified nor a subobject of such an object, and

...

Body:
This is a code example from the C++20 spec ([basic.life]/8):

struct C {
  int i;
  void f();
  const C& operator=( const C& );
};

const C& C::operator=( const C& other) {
  if ( this != &other ) {
    this->~C();              // lifetime of *this ends
    new (this) C(other);     // new object of type C created
    f();                     // well-defined
  }
  return *this;
}

int main() {
  C c1;
  C c2;
  c1 = c2;   // well-defined
  c1.f();    // well-defined; c1 refers to a new object of type C
}

Would the following be legal or undefined behavior:

struct C {
  int& i; // <= the field is now a reference
  void foo(const C& other) {
    if ( this != &other ) {
      this->~C();
      new (this) C(other);
    }
  }
};

int main() {
    int i = 3, j = 5;
    C c1 {.i = i};
    std::cout << c1.i << std::endl;
    C c2 {.i = j};
    c1.foo(c2);
    std::cout << c1.i << std::endl;
}

In case it is illegal, would std::launder make it legal? where should it be added?

Note: p0532r0 (page 5) uses launder for a similar case.

In case it is legal, how can it work without "Pointer optimization barrier" (i.e. std::launder)? how do we avoid the compiler from caching the value of c1.i?

The question relates to an old ISO thread regarding Implementability of std::optional.

The question applies also, quite similarly, to a constant field (i.e. if above i in struct C is: const int i).

EDIT

It seems, as @Language Lawyer points out in an answer below, that the rules have been changed in C++20, in response to RU007/US042 NB comments.

C++17 Specifications [ptr.launder] (§ 21.6.4.4): --emphasis mine--

[ Note: If a new object is created in storage occupied by an existing
  object of the same type, a pointer to the original object can be used
  to refer to the new object unless the type contains const or reference
  members; in the latter cases, this function can be used to obtain a
  usable pointer to the new object. ...— end note ]

C++17 [ptr.launder] code example in the spec (§ 21.6.4.5):

struct X { const int n; };
X *p = new X{3};
const int a = p->n;
new (p) X{5}; // p does not point to new object (6.8) because X::n is const
const int b = p->n; // undefined behavior
const int c = std::launder(p)->n; // OK

C++20 [ptr.launder] Specifications (§ 17.6.4.5):

[ Note: If a new object is created in storage occupied by an existing
  object of the same type, a pointer to the original object can be used
  to refer to the new object unless its complete object is a const
  object or it is a base class subobject; in the latter cases, this
  function can be used to obtain a usable pointer to the new object.
  ...— end note ]

Note that the part:

unless the type contains const or reference members;

that appeared in C++17 was removed in C++20, and the example was changed accordingly.

C++20 [ptr.launder] code example in the spec (§ 17.6.4.6):

struct X { int n; };
const X *p = new const X{3};
const int a = p->n;
new (const_cast<X*>(p)) const X{5}; // p does not point to new object ([basic.life])
                                    // because its type is const
const int b = p->n;                 // undefined behavior
const int c = std::launder(p)->n;   // OK

Thus, apparently the code in question is legal in C++20 as is, while with C++17 it requires using std::launder when accessing the new object.

Open Questions:

What is the case of such code in C++14 or before (when std::launder didn't exist)? Probably it is UB - this is why std::launder was brought to the game, right?

If in C++20 we do not need std::launder for such a case, how the compiler can understand that the reference is being manipulated without our help (i.e. without "Pointer optimization barrier") to avoid caching of the reference value?

Similar questions here, here, here and here got contradicting answers, some see that as a valid syntax but advise to rewrite it. I'm focusing on the validity of the syntax and the need (yes or no) for std::launder, in the different C++ versions.


问:
Using IntelliJ IDEA for project using Makefiles
An existing Java project uses makefiles (which in turn uses ANT).

I want to work on this project using IntelliJ IDEA. However, no IntelliJ specific files, e.g. project files, should be checked in to version control.

How can I configure the project so that:

Makefiles can be run from inside IntelliJ IDEA.

Change Build > Make Project so that it either does nothing or runs some make target (in a makefile). I do not want to the standard behavior of compiling into ./bin since this potentially can conflict with the makefiles.

答:
A compilation database feature became available in 2018.

The help page says:

Make-based projects:
The compiledb-generator tool creates compilation databases for make-based build systems.

Bear and intercept-build tools:
Bear and intercept-build from scan-build are the tools to help you get a compilation database by intercepting compiler calls during the build.

(Bear and intercept-build work on Linux, by injecting themselves into LD_LIBRARY_PATH)


问:
Handle key press by function in VueJs
in my component I am using VueStrap's modal like this:

<template>
    <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed="close()" ... >
       ...
    </modal-window>
 ...
</template>

```

I want handle key press when that modal is opened and ensure submit modal when enter pressed or close modal when esc pressed.

I added custom function keyHandler which is unfortunately never fired. Can you tell me how to fix code to handle key press in that function? Or when is better way how to close and submit vue strap modal I will be grateful for advice. Thank you.

答:
Alternatively, you may want to consider using the v-hotkey directive for key input in Vue (docs, github).  This will keep your code relatively clean and simple if you must consider several different key inputs.

1.  Install it:

```<code>npm i --save v-hotkey
</code>```

 Have Vue 'use' it:

import VueHotkey from "v-hotkey";
Vue.use(VueHotkey);

3.  Apply it to your Vue components, like so:

<template>
    <modal-window ... v-hotkey="keymap">
       ...
    </modal-window>
</template>

```

Title: Handle key press by function in VueJs

Body:
in my component I am using VueStrap's modal like this:

<template>
    <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed="close()" ... >
       ...
    </modal-window>
 ...
</template>

I want handle key press when that modal is opened and ensure submit modal when enter pressed or close modal when esc pressed.

I added custom function keyHandler which is unfortunately never fired. Can you tell me how to fix code to handle key press in that function? Or when is better way how to close and submit vue strap modal I will be grateful for advice. Thank you.

Body:
Alternatively, you may want to consider using the v-hotkey directive for key input in Vue (docs, github).  This will keep your code relatively clean and simple if you must consider several different key inputs.

1.  Install it:

npm i --save v-hotkey

 Have Vue 'use' it:

import VueHotkey from "v-hotkey";
Vue.use(VueHotkey);

3.  Apply it to your Vue components, like so:

<template>
    <modal-window ... v-hotkey="keymap">
       ...
    </modal-window>
</template>
<script>
  ...
  data() {
    return {
      showModal: false
    };
  },
  computed: {
    keymap() {
      return {
        "esc": this.toggleModal
      };
    }
  },
  methods: {
    toggleModal() {
      this.showModal = !this.showModal;
    }
  }
</script>


问:
How to filter FileUpload Control?
How to add filter to the fileupload control in asp.net? I want a filter for Oasis File (.000).?

Please advice me... thank you very much!

答:
You can use RegularExpressionValidator

```<code><asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="fupProduct"
     ErrorMessage="Only .gif, .jpg, .png, .tiff and .jpeg"
     ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([tT][iI][iI][fF])$)"></asp:RegularExpressionValidator>
</code>```

Title: How to filter FileUpload Control?

Body:
You can use RegularExpressionValidator

<asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="fupProduct"
     ErrorMessage="Only .gif, .jpg, .png, .tiff and .jpeg"
     ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([tT][iI][iI][fF])$)"></asp:RegularExpressionValidator>


问:
Public page access with Azure AD on Web Forms
I got the marching orders to apply Azure Active Directory to an existing WebForms c# site which has 2 public facing pages. I was able to integrate the site with Azure AD using owin packages and configuring the app in Azure. The single sign-in is working as expected.

The problem I'm having is getting the public facing pages to allow anonymous access. I'm used to data annotations such as [AllowAnonymous] in MVC but I'm not sure of a good approach to implement something like that in Web Forms.

I've already tried placing the public aspx pages in a public folder along with this web.config:

```<code><configuration>
  <system.web>
      <authorization>
          <allow users="*"/>
      </authorization>
  </system.web>
</configuration>
</code>```

Thanks in advance for the help!

答:
take a look here: https://www.codeproject.com/tips/849113/four-easy-steps-to-set-up-owin-for-form-authentica

basically for web forms apps, you set it in the configuration sections of the web.config files in either root, or etc. , you tell it which paths require what auth, which don't, etc.
as per the above link, something like

```<code><?xml version="1.0"?>
<configuration>
  <location path="About.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
 </configuration>
</code>```

so this basically says deny all anonymous users for the about.aspx page. meaning the equivalent of [authorize] in mvc

Body:
I got the marching orders to apply Azure Active Directory to an existing WebForms c# site which has 2 public facing pages. I was able to integrate the site with Azure AD using owin packages and configuring the app in Azure. The single sign-in is working as expected.

The problem I'm having is getting the public facing pages to allow anonymous access. I'm used to data annotations such as [AllowAnonymous] in MVC but I'm not sure of a good approach to implement something like that in Web Forms.

I've already tried placing the public aspx pages in a public folder along with this web.config:

<configuration>
  <system.web>
      <authorization>
          <allow users="*"/>
      </authorization>
  </system.web>
</configuration>

Thanks in advance for the help!

Body:
take a look here: https://www.codeproject.com/tips/849113/four-easy-steps-to-set-up-owin-for-form-authentica

basically for web forms apps, you set it in the configuration sections of the web.config files in either root, or etc. , you tell it which paths require what auth, which don't, etc.
as per the above link, something like

<?xml version="1.0"?>
<configuration>
  <location path="About.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
 </configuration>

so this basically says deny all anonymous users for the about.aspx page. meaning the equivalent of [authorize] in mvc


问:
How to access python library in javascript react native library
I am developing a mobile application using the react native library with the JavaScript language. On the other hand, I have an image processing code that I wrote in python. Is it possible to combine them? Can I put python in my React native code?</p>

答: No this is not possible. What are you trying to achieve? Why do you thing that embedding python in your React native code is the way to achieve it?</p>


问:
Change the format of the datepicker to weekday - material ui
I want to change the format of the datepicker to weekday (Monday, Tuesday,..) The default version of the datepicker format is format="MM/dd/yyyy" Is it possible to change it?

Source code:

```<code>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
      <Grid container justify="space-around">
        <KeyboardDatePicker
          disableToolbar
          variant="inline"
          format="MM/dd/yyyy"
          margin="normal"
          id="date-picker-inline"
          label="Date picker inline"
          value={selectedDate}
          onChange={handleDateChange}
          KeyboardButtonProps={{
            'aria-label': 'change date',
          }}
        />
</code>```

答:
You can change the format value of KeyboardDatePicker to format="EE - MM/dd/yyyy" show the weekdays with month/date/year. Moreover, if you want to change the format of KeyboardDatePicker you can refer to here.Try this:

<KeyboardDatePicker
  disableToolbar
  variant="inline"
  format="EE-MM/dd/yyyy"
  margin="normal"
  id="date-picker-inline"
  label="Date picker inline"
  value={selectedDate}
  onChange={handleDateChange}
  KeyboardButtonProps={{
    'aria-label': 'change date',
  }}
/>```

Body:
I want to change the format of the datepicker to weekday (Monday, Tuesday,..) The default version of the datepicker format is format="MM/dd/yyyy" Is it possible to change it?

Source code:

<MuiPickersUtilsProvider utils={DateFnsUtils}>
      <Grid container justify="space-around">
        <KeyboardDatePicker
          disableToolbar
          variant="inline"
          format="MM/dd/yyyy"
          margin="normal"
          id="date-picker-inline"
          label="Date picker inline"
          value={selectedDate}
          onChange={handleDateChange}
          KeyboardButtonProps={{
            'aria-label': 'change date',
          }}
        />


问:
How to apply machine learning for streaming data in Apache NIFI
I have a processor that generates time series data in JSON format. Based on the received data I need to make a forecast using machine learning algorithms on python. Then write the new forecast values to another flow file.

The problem is: when you run such a python script, it must perform many massive preprocessing operations: queries to a database, creating a complex data structure, initializing forecasting models, etc.

If you use ExecuteStreamCommand, then for each flow file the script will be run every time. Is this true?

Can I make in NIFI a python script that starts once and receives the flow files many times, storing the history of previously received data. Or do I need to make an HTTP service that will receive data from NIFI?

答:
You have a few options:

Build a custom processor. This is my suggested approach. The code would need to be in Java (or Groovy, which provides a more Python-like experience) but would not have Python dependencies, etc. However, I have seen examples of this approach for ML model application (see Tim Spann's examples) and this is generally very effective. The initialization and individual flowfile trigger logic is cleanly separated, and performance is good.

Use InvokeScriptedProcessor. This will allow you to write the code in Python and separate the initialization (pre-processing, DB connections, etc., onScheduled in NiFi processor parlance) with the execution phase (onTrigger). Some examples exist but I have not personally pursued this with Python specifically. You can use Python dependencies but not "native modules" (i.e. compiled C code), as the execution engine is still Jython.

Use ExecuteStreamCommand. Not strongly recommended. As you mention, every invocation would require the preprocessing steps to occur, unless you designed your external application in such a way that it ran a long-lived "server" component and each ESC command sent data to it and returned an individual response. I don't know what your existing Python application looks like, but this would likely involve complicated changes. Tim has another example using CDSW to host and deploy the model and NiFi to send it data via HTTP to evaluate.


问:
classification with large number of classes
Let us say I have a training dataset of 10 million images containing images of 100,000 different people. I want to create an ML model that can identify which person is in a given image.
What would be the best approach considering the huge number of people(classes) ?</p>

答: One possible approach is to treat this as a verification problem instead of multi-classification. That is, train a binary classifier for each person. You can also consult this paper: https://arxiv.org/abs/1503.03832</p>


问:
ASP.NET GridView/ListView Print Functionality
I'm trying to give users an ability to print asp.net gridview/listview report. Could anyone please guide me how it's best achieved?

Ability to export to Excel/PDF would be good as well.

Thank you in advance.

答:
Set up a print stylesheet that strips out everything you don't want on the page.

Have a javascript print button for printing the page.

Job done.


问:
KafkaStreams, Error Registering Avro Schema
Disclaimer: My experience with KafkaStreams is quite limited.
I do not quite understand why am I getting a org.apache.kafka.common.errors.SerializationException: Error registering Avro schema: and Schema being registered is incompatible with an earlier schema; error when all I'm doing is Streaming a Topic into a KTable so I can later use Interactive Queries on that Store.

here's the SerDes config.

```<code>props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);
</code>```

Streams code: Note I do not wish to do any filtering or grouping with the Stream at this point, I just want the data to be available for future querying over a Store.

```<code>final KStream<String,GenericRecord> stream = builder.stream("my-topic");
stream.toTable(Materialized.as("my-state-store"));
</code>```

whenever I streams.start() I keep getting those Exceptions whilst Serialising.
I've got a schema for this so I've used the SpecificAvroSerdes but the problem is the same.
I guess I am missing some fundamental understanding on why my KTable is attempting to register a new Schema with Confluent.

Edit 1:
I now understand the role being played by the schema register here. Using the KStream with a GenericAvroSerde I can consume the data from the Topic however still not being able to Materialize it in the KTable.
My questions now are:

Why do I keep getting the above exception always in the same partition and offset, even thought I am not calling streams.cleanUp(). Why isn't it moving on (committing).

This exception seems to be un-recoverable. All the Streams threads die bringing the app down. Is there a way to circumvent this? Note: I'm already using the LogAndContinue exception handlers for Production and Deserialization.

Edit 2:

I was able to overcome that exception. My StateStore contained previous entries with an incompatible schema. After I Purged the Topic and changed the ApplicationId it started to work.

This still doesn't negate the need to trap the Schema being registered is incompatible with an earlier schema; Exception though. This brings the Streams Application to a halt. I have tried usingstreams.setUncaughtExceptionHandler where I'm able to log the Error however this doesn't prevent the Streams Threads to die and I can't even start them after that. Surely there's a way to trap this?

答:
The exception you describe is fatal and you cannot prevent the thread from dying atm, because the thread cannot make any progress and thus gives up. Only after you fixed the issue you can restart the application (as you observed).

Btw: why do you not simply use builder.table() to read the topic?

Body:
Disclaimer: My experience with KafkaStreams is quite limited.
I do not quite understand why am I getting a org.apache.kafka.common.errors.SerializationException: Error registering Avro schema: and Schema being registered is incompatible with an earlier schema; error when all I'm doing is Streaming a Topic into a KTable so I can later use Interactive Queries on that Store.

here's the SerDes config.

props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);

Streams code: Note I do not wish to do any filtering or grouping with the Stream at this point, I just want the data to be available for future querying over a Store.

final KStream<String,GenericRecord> stream = builder.stream("my-topic");
stream.toTable(Materialized.as("my-state-store"));

whenever I streams.start() I keep getting those Exceptions whilst Serialising.
I've got a schema for this so I've used the SpecificAvroSerdes but the problem is the same.
I guess I am missing some fundamental understanding on why my KTable is attempting to register a new Schema with Confluent.

Edit 1:
I now understand the role being played by the schema register here. Using the KStream with a GenericAvroSerde I can consume the data from the Topic however still not being able to Materialize it in the KTable.
My questions now are:

Why do I keep getting the above exception always in the same partition and offset, even thought I am not calling streams.cleanUp(). Why isn't it moving on (committing).

This exception seems to be un-recoverable. All the Streams threads die bringing the app down. Is there a way to circumvent this? Note: I'm already using the LogAndContinue exception handlers for Production and Deserialization.

Edit 2:

I was able to overcome that exception. My StateStore contained previous entries with an incompatible schema. After I Purged the Topic and changed the ApplicationId it started to work.

This still doesn't negate the need to trap the Schema being registered is incompatible with an earlier schema; Exception though. This brings the Streams Application to a halt. I have tried usingstreams.setUncaughtExceptionHandler where I'm able to log the Error however this doesn't prevent the Streams Threads to die and I can't even start them after that. Surely there's a way to trap this?


问:
How can I parse xmlrpc response (Odoo API read), using Java
I have to fetch the category a product is related to, using the read method of Odoo API. I get a list of objects, then for each category, I need to extract the field product_tmpl_ids, a list of integers. I'm not sure how to do it. This is the method:

```<code>public List readModelfields(String modelName, List<Integer> ids, List<String> fields, Integer uid) throws XmlRpcException {
    List record = (List) Arrays.asList((Object[]) models.execute("execute_kw", Arrays.asList(
            db, uid, password,
            modelName, "read",
            ids,
            new HashMap() {{
                put("fields", fields);
            }}
    )));
    return record;
}
</code>```

This is the rest of the code:

```<code>List<String> fields = new ArrayList<>();
fields.add("product_tmpl_ids");
List categoryIds = (List<Integer>)service.searchByStrParameter("product.public.category", "name", "A - Administration / Office", uid);
List result = (List)service.readModelfields("product.public.category", categoryIds, fields, uid);
</code>```

Can anybody help? How to extract the fields from the fetched objects?

答:
You passed the result of the search method (a list) to readModelfields which is used as-is to call read method, as documented in External API read method ids must be passed in a list:

```<code>Arrays.asList(ids),
</code>```

You used search followed with the read method on the same model, you can use search_read instead.

The following example shows how to fetch the many2many field category_id of res.partners

```<code>public List searchReadModelfields(String modelName, List domain, List<String> fields, Integer uid) throws XmlRpcException {
    return (List)Arrays.asList((Object[])models.execute("execute_kw", Arrays.asList(
            db, uid, password,
            modelName,
            "search_read",
            Arrays.asList(domain),
            new HashMap() {{
                put("fields", fields);
            }}
    )));
}
</code>```

Call searchReadModelfields and print out the values:

```<code>List<String> fields = new ArrayList<>();
fields.add("category_id");
List domain = Arrays.asList(
        Arrays.asList("category_id", "!=", false)
);

// return list of hashmaps)
List result = (List)service.searchReadModelfields("res.partner", domain, fields, uid);

HashMap values;
Integer partner_id;
Object[] category_ids;
for(Object partner_data: result) {
    values  = (HashMap)partner_data;
    partner_id = (Integer) values.get("id");
    category_ids = (Object [])values.get("category_id");

    System.out.printf("{partner_id: %s, ", partner_id);
    System.out.print("category_ids:[");
    for(Object category_id: category_ids) {
        System.out.printf("%s,",
                category_id
        );
    }
    System.out.println("]}");
 }
</code>```

Body:
I have to fetch the category a product is related to, using the read method of Odoo API. I get a list of objects, then for each category, I need to extract the field product_tmpl_ids, a list of integers. I'm not sure how to do it. This is the method:

public List readModelfields(String modelName, List<Integer> ids, List<String> fields, Integer uid) throws XmlRpcException {
    List record = (List) Arrays.asList((Object[]) models.execute("execute_kw", Arrays.asList(
            db, uid, password,
            modelName, "read",
            ids,
            new HashMap() {{
                put("fields", fields);
            }}
    )));
    return record;
}

This is the rest of the code:

List<String> fields = new ArrayList<>();
fields.add("product_tmpl_ids");
List categoryIds = (List<Integer>)service.searchByStrParameter("product.public.category", "name", "A - Administration / Office", uid);
List result = (List)service.readModelfields("product.public.category", categoryIds, fields, uid);

Can anybody help? How to extract the fields from the fetched objects?

Body:
You passed the result of the search method (a list) to readModelfields which is used as-is to call read method, as documented in External API read method ids must be passed in a list:

Arrays.asList(ids),

You used search followed with the read method on the same model, you can use search_read instead.

The following example shows how to fetch the many2many field category_id of res.partners

public List searchReadModelfields(String modelName, List domain, List<String> fields, Integer uid) throws XmlRpcException {
    return (List)Arrays.asList((Object[])models.execute("execute_kw", Arrays.asList(
            db, uid, password,
            modelName,
            "search_read",
            Arrays.asList(domain),
            new HashMap() {{
                put("fields", fields);
            }}
    )));
}

Call searchReadModelfields and print out the values:

List<String> fields = new ArrayList<>();
fields.add("category_id");
List domain = Arrays.asList(
        Arrays.asList("category_id", "!=", false)
);

// return list of hashmaps)
List result = (List)service.searchReadModelfields("res.partner", domain, fields, uid);

HashMap values;
Integer partner_id;
Object[] category_ids;
for(Object partner_data: result) {
    values  = (HashMap)partner_data;
    partner_id = (Integer) values.get("id");
    category_ids = (Object [])values.get("category_id");

    System.out.printf("{partner_id: %s, ", partner_id);
    System.out.print("category_ids:[");
    for(Object category_id: category_ids) {
        System.out.printf("%s,",
                category_id
        );
    }
    System.out.println("]}");
 }


问:
how to use html2canvas and jspdf to export to pdf in a proper and simple way
I am currently working on a school management software that usually requires exporting of html contents that contains data tables and div tag.

I have tried all possible means to write a code that will be able to export my html data in a good way, with css preferably. After checking some question and answers here, I tried using spdf, but no luck.

It keeps destroying my table alignment, then I read about html2canvas but to implement it with jspdf was my problem, i would like to capture the content if a div tag with html2canvas then send the canvas to jspdf to export the canvas as pdf.

Here is my code below:

```<code><script src="assets/js/pdfconvert/jspdf.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.from_html.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.split_text_to_size.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.standard_fonts_metrics.js">  </script>
<script src="assets/js/pdfconvert/jspdf.plugin.addhtml.js"></script>
<script src="assets/js/pdfconvert/filesaver.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.cell.js"></script>
<script src="assets/js/pdfconvert/html2canvas.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.addimage.js"></script>
</code>```

here is the js code

```<code>var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
pdf.save('Test.pdf');
});
</code>```

答:
Changing this line:

```<code>var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);
</code>```

To fix the dimensions.

Body:
I am currently working on a school management software that usually requires exporting of html contents that contains data tables and div tag.

I have tried all possible means to write a code that will be able to export my html data in a good way, with css preferably. After checking some question and answers here, I tried using spdf, but no luck.

It keeps destroying my table alignment, then I read about html2canvas but to implement it with jspdf was my problem, i would like to capture the content if a div tag with html2canvas then send the canvas to jspdf to export the canvas as pdf.

Here is my code below:

here is the js code

var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
pdf.save('Test.pdf');
});

Body:
Changing this line:

var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);

To fix the dimensions.


问:
C++: What is the size of an object of an empty class?
I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and point to it like any other object. But, how big is such an object?

I used this small program:

```<code>#include <iostream>
using namespace std;

class Empty {};

int main()
{
    Empty e;
    cerr << sizeof(e) << endl;
    return 0;
}
</code>```

The output I got on both Visual C++ and Cygwin-g++ compilers was 1 byte! This was a little surprising to me since I was expecting it to be of the size of the machine word (32 bits or 4 bytes).

Can anyone explain why the size of 1 byte? Why not 4 bytes? Is this dependent on compiler or the machine too? Also, can someone give a more cogent reason for why an empty class object will not be of size 0 bytes?

答:
The standard states that all most derived  objects have sizeof() >= 1:

Unless it is a bit-field (class.bit), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size.
  ISO/IEC FDIS 14882:1998(E) intro.object

OwnerDisplayName: Ash

ContentLicense: CC BY-SA 2.5

Body:
I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and point to it like any other object. But, how big is such an object?

I used this small program:

#include <iostream>
using namespace std;

class Empty {};

int main()
{
    Empty e;
    cerr << sizeof(e) << endl;
    return 0;
}

The output I got on both Visual C++ and Cygwin-g++ compilers was 1 byte! This was a little surprising to me since I was expecting it to be of the size of the machine word (32 bits or 4 bytes).

Can anyone explain why the size of 1 byte? Why not 4 bytes? Is this dependent on compiler or the machine too? Also, can someone give a more cogent reason for why an empty class object will not be of size 0 bytes?

LastEditorDisplayName: Ash

OwnerDisplayName: TrayMan

LastEditorDisplayName: Pete Kirkham


问:
How to check if scp command is available?
I am looking for a multiplatform solution that would allow me to check if scp command is available.

The problem is that scp does not have a --version command line and when called without parameters it will return with exit code 1 (error).

Update: in case it wasn't clear, by multiplatform I mean a solution that will work on Windows, OS X and Linux without requiring me to install anything.

答:
```<code>#!/bin/sh

scp_path=`which scp || echo NOT_FOUND`

if test $scp_path != "NOT_FOUND"; then
        if test -x ${scp_path}; then
                echo "$scp_path is usable"
                exit 0
        fi
fi
echo "No usable scp found"
</code>```

sh does not have a built-in which, thus we rely on a system provided which command. I'm not entirely sure if the -x check is needed - on my system which actually verifies if the found file is executable by the user, but this may not be portable. On the rare case where the system has no which command, one can write a which function here.

Body:
#!/bin/sh

scp_path=`which scp || echo NOT_FOUND`

if test $scp_path != "NOT_FOUND"; then
        if test -x ${scp_path}; then
                echo "$scp_path is usable"
                exit 0
        fi
fi
echo "No usable scp found"

sh does not have a built-in which, thus we rely on a system provided which command. I'm not entirely sure if the -x check is needed - on my system which actually verifies if the found file is executable by the user, but this may not be portable. On the rare case where the system has no which command, one can write a which function here.


问:
Subsetting, Matrices
I am super new to R and currently playing with the "diamond" dataset.

I am trying to return the row corresponding to the lowest, mean and largest prices and put everything in a 10 by 4 matrix. Please explain an easier way of doing this if possible.

```<code>library(ggplot2)
data(diamonds)

min(diamonds$price)
mean(diamonds$price)
max(diamonds$price) # this one gives me the wrong val!

M<-matrix(1:cols, nrow = 1, ncol = cols)
colnames(M)<-c("carat","cut" , "color" , "clarity", "depth" , "table" , "price" ,  "x" , "y" ,"z")

# Here I need to add the rows corresponding to the min,mean,max to this matrix.
</code>```

Thanks

答:
matrix and dataframes are different in R. diamonds is a dataframe it is better and easy to process if you keep it as dataframe only.

summary(diamonds) gives you some nice summary stats for each column.

If you want to apply specific functions to columns using dplyr, you can do :

```<code>library(dplyr)
diamonds %>%
  summarise(across(where(is.numeric),list(min = min, max = max, mean = mean))) %>%
  tidyr::pivot_longer(cols = everything(),
                      names_to = c('col', '.value'),
                      names_sep = '_')

# A tibble: 7 x 4
#  col     min      max     mean
#  <chr> <dbl>    <dbl>    <dbl>
#1 carat   0.2     5.01    0.798
#2 depth  43      79      61.7
#3 table  43      95      57.5
#4 price 326   18823    3933.
#5 x       0      10.7     5.73
#6 y       0      58.9     5.73
#7 z       0      31.8     3.54
</code>```

Note that I applied these functions only to numeric columns since cut, color, clarity are factor columns.

Title: Subsetting, Matrices

Body:
I am super new to R and currently playing with the "diamond" dataset.

I am trying to return the row corresponding to the lowest, mean and largest prices and put everything in a 10 by 4 matrix. Please explain an easier way of doing this if possible.

library(ggplot2)
data(diamonds)

min(diamonds$price)
mean(diamonds$price)
max(diamonds$price) # this one gives me the wrong val!

M<-matrix(1:cols, nrow = 1, ncol = cols)
colnames(M)<-c("carat","cut" , "color" , "clarity", "depth" , "table" , "price" ,  "x" , "y" ,"z")

# Here I need to add the rows corresponding to the min,mean,max to this matrix.

Thanks

Body:
matrix and dataframes are different in R. diamonds is a dataframe it is better and easy to process if you keep it as dataframe only.

summary(diamonds) gives you some nice summary stats for each column.

If you want to apply specific functions to columns using dplyr, you can do :

library(dplyr)
diamonds %>%
  summarise(across(where(is.numeric),list(min = min, max = max, mean = mean))) %>%
  tidyr::pivot_longer(cols = everything(),
                      names_to = c('col', '.value'),
                      names_sep = '_')

# A tibble: 7 x 4
#  col     min      max     mean
#  <chr> <dbl>    <dbl>    <dbl>
#1 carat   0.2     5.01    0.798
#2 depth  43      79      61.7
#3 table  43      95      57.5
#4 price 326   18823    3933.
#5 x       0      10.7     5.73
#6 y       0      58.9     5.73
#7 z       0      31.8     3.54

Note that I applied these functions only to numeric columns since cut, color, clarity are factor columns.


问:
Get comma separated string from Mysql
I'm saving a string from PHP to MySQL like this..

```<code>$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");
</code>```

I'm then trying to extract data from the table if $a = "15"

```<code>$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");
</code>```

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?

答: If $a contains only one id I would suggest seperating it into multiple records, because in string search (/ select) is slower.

Title: Get comma separated string from Mysql

Body:
I'm saving a string from PHP to MySQL like this..

$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");

I'm then trying to extract data from the table if $a = "15"

$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?


问:
Python Shell says I have version 3.6 but terminal says I have 2.7
which python returns:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python

When I open my shell, the first couple lines of the shell read:
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.

And finally, the issue is that when I am in my shell and I try to import pandas (which is installed), I receive no module named 'pandas'. Which, according to this article, is due to having multiple installations of Python and running Python from the system.

The solution proposed by the aforementioned article is to use conda. But, will simply installing conda solve my issue of my shell returning something different from terminal? I am really new to programming so assume I don't know how any of this works!

答: The reason you can't import pandas in your shell is because you installed it into a different a python. You can install it to the python you need via the pip.exe from the python you need. The reason you can import pandas after installing anaconda is because installing anaconda will install many modules with it, like numpy, scipy, sympy, etc.