问:
How to transpose a column in a dataframe while keeping the order of the elements?
```<code>  OECD2012  GDP2012 GDP2012born  countrynew countrybornText permile
1        1 56149.67    50632.44 Switzerland   United States       3
2        1 56149.67    45948.54 Switzerland     Netherlands       2
3        1 56149.67    44829.27 Switzerland         Ireland       1
4        1 56149.67    44551.62 Switzerland         Austria       9
5        1 56149.67    44336.81 Switzerland         Denmark       3
6        1 56149.67    43355.81 Switzerland          Sweden       1
</code>```

Hi my data looks like this and I need to make it a matrix. So I run the following:

```<code>df2 <- df %>% spread(key = countrybornText, value = permile)
</code>```

My problem is that I want the columns to be ordered by GDP2012born and they show up in alphabetical order when I transpose. Any idea how to keep the order I had in the column countrybornText?

```<code>df <- structure(list(OECD2012 = c(1, 1, 1, 1, 1, 1), GDP2012 = c(56149.67,
      56149.67, 56149.67, 56149.67, 56149.67, 56149.67), GDP2012born = c(50632.44,
      45948.54, 44829.27, 44551.62, 44336.81, 43355.81), countrynew = structure(c(1L,
      1L, 1L, 1L, 1L, 1L), .Label = "Switzerland", class = "factor"),
      countrybornText = structure(c(6L, 4L, 3L, 1L, 2L, 5L), .Label = c("Austria",
      "Denmark", "Ireland", "Netherlands", "Sweden", "United States"),
      class = "factor"), permile = c(3, 2, 1, 9, 3, 1)), class = "data.frame",
      row.names = c(NA, -6L))
</code>```

答:
You can make sure that the column is a factor, with the levels in the order that you want:

library(dplyr)
library(tidyr)

df$countrybornText <-factor(as.character(df$countrybornText), as.character(df$countrybornText))
df2 <- df %>% spread(key = countrybornText, value = permile)

df2
#>   OECD2012  GDP2012 GDP2012born  countrynew United States Netherlands Ireland
#> 1        1 56149.67    43355.81 Switzerland            NA          NA      NA
#> 2        1 56149.67    44336.81 Switzerland            NA          NA      NA
#> 3        1 56149.67    44551.62 Switzerland            NA          NA      NA
#> 4        1 56149.67    44829.27 Switzerland            NA          NA       1
#> 5        1 56149.67    45948.54 Switzerland            NA           2      NA
#> 6        1 56149.67    50632.44 Switzerland             3          NA      NA
#>   Austria Denmark Sweden
#> 1      NA      NA      1
#> 2      NA       3     NA
#> 3       9      NA     NA
#> 4      NA      NA     NA
#> 5      NA      NA     NA
#> 6      NA      NA     NA
```

Created on 2020-02-18 by the reprex package (v0.3.0)

Body:
  OECD2012  GDP2012 GDP2012born  countrynew countrybornText permile
1        1 56149.67    50632.44 Switzerland   United States       3
2        1 56149.67    45948.54 Switzerland     Netherlands       2
3        1 56149.67    44829.27 Switzerland         Ireland       1
4        1 56149.67    44551.62 Switzerland         Austria       9
5        1 56149.67    44336.81 Switzerland         Denmark       3
6        1 56149.67    43355.81 Switzerland          Sweden       1

Hi my data looks like this and I need to make it a matrix. So I run the following:

df2 <- df %>% spread(key = countrybornText, value = permile)

My problem is that I want the columns to be ordered by GDP2012born and they show up in alphabetical order when I transpose. Any idea how to keep the order I had in the column countrybornText?

df <- structure(list(OECD2012 = c(1, 1, 1, 1, 1, 1), GDP2012 = c(56149.67,
      56149.67, 56149.67, 56149.67, 56149.67, 56149.67), GDP2012born = c(50632.44,
      45948.54, 44829.27, 44551.62, 44336.81, 43355.81), countrynew = structure(c(1L,
      1L, 1L, 1L, 1L, 1L), .Label = "Switzerland", class = "factor"),
      countrybornText = structure(c(6L, 4L, 3L, 1L, 2L, 5L), .Label = c("Austria",
      "Denmark", "Ireland", "Netherlands", "Sweden", "United States"),
      class = "factor"), permile = c(3, 2, 1, 9, 3, 1)), class = "data.frame",
      row.names = c(NA, -6L))

Body:
You can make sure that the column is a factor, with the levels in the order that you want:

library(dplyr)
library(tidyr)

df$countrybornText <-factor(as.character(df$countrybornText), as.character(df$countrybornText))
df2 <- df %>% spread(key = countrybornText, value = permile)

df2
#>   OECD2012  GDP2012 GDP2012born  countrynew United States Netherlands Ireland
#> 1        1 56149.67    43355.81 Switzerland            NA          NA      NA
#> 2        1 56149.67    44336.81 Switzerland            NA          NA      NA
#> 3        1 56149.67    44551.62 Switzerland            NA          NA      NA
#> 4        1 56149.67    44829.27 Switzerland            NA          NA       1
#> 5        1 56149.67    45948.54 Switzerland            NA           2      NA
#> 6        1 56149.67    50632.44 Switzerland             3          NA      NA
#>   Austria Denmark Sweden
#> 1      NA      NA      1
#> 2      NA       3     NA
#> 3       9      NA     NA
#> 4      NA      NA     NA
#> 5      NA      NA     NA
#> 6      NA      NA     NA

Created on 2020-02-18 by the reprex package (v0.3.0)


来源: stackexchange

问:
How to copy one row in a .csv file to another row with python
I am trying to merge the strings from the first two rows of a .csv file into one row in python.
I am using a file with over 150 columns.

Right now it looks like this:

;; Test1; Test1; Test1; Test 2; Test 2; Test2

Name;Birthday; Points Q1; Points Q2; Points Q3; Points Q1; Points Q2; Points Q3

but I need to merge the information into one row, that looks like this:

Name;Birthday;Test1 PointsQ1; Test1 Points Q2; Test1 Points Q3; Test2 Points Q1;...

答:
Using the pandas library you can do this,

First of installing the pandas library if you don't have,

By using this command

```<code>pip install pandas
</code>```

Then add this script in your code

```<code>import pandas as pd
data=pd.read_csv("YOUR FILE LOCATION WITH FILE NAME")
</code>```

This line will print you the first row of your excel sheet

```<code>print(data.ioc[0])
</code>```

You can combine the first two rows into one row and save in the first row

```<code>data.iloc[0]=[data.iloc['YOUR COLUMN NAME'][0]+data.iloc['YOUR COLUMN NAME'][1],data.iloc[]+.......]
</code>```

Like this for your every column and it will save in the first row
And Run a loop for remaining rows and update it.

For saving from the data variable that is data frame  TO CSV

```<code>data.to_csv('your-file-name.csv', sep=',')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using the pandas library you can do this,

First of installing the pandas library if you don't have,

By using this command

pip install pandas

Then add this script in your code

import pandas as pd
data=pd.read_csv("YOUR FILE LOCATION WITH FILE NAME")

This line will print you the first row of your excel sheet

print(data.ioc[0])

You can combine the first two rows into one row and save in the first row

data.iloc[0]=[data.iloc['YOUR COLUMN NAME'][0]+data.iloc['YOUR COLUMN NAME'][1],data.iloc[]+.......]

Like this for your every column and it will save in the first row
And Run a loop for remaining rows and update it.

For saving from the data variable that is data frame  TO CSV

data.to_csv('your-file-name.csv', sep=',')


问:
Redirect HTTP to HTTPS on localhost
I want to have a dev setup on my local machine to more easily test new versions of my programm - it's a server/client application. The client does need SSL and so I want to have traefik as a proxy to the (local) server which will use a self signed certificate.

I managed to get a connection without SSL but as soon as I enable HTTPS / Redirecting, traefik only responses with "backend not found" "/" 0ms.

The SSL certificate is valid according to my browsers.

Here is my setup:

traefik.toml

```<code>[docker]
watch = true
exposedByDefault = false

logLevel = "DEBUG"
defaultEntryPoints = ["https", "http"]

[accessLog]
[traefikLog]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
  [entryPoints.https.tls]
    [[entryPoints.https.tls.certificates]]
      ca = "etc/traefik/ca.cert.pem"
      certFile = "/etc/traefik/dev-cert.pem"
      keyFile = "/etc/traefik/dev-key.nopass.pem"

# API definition
[api]
entryPoint = "traefik"
dashboard = true
</code>```

docker-compose.yaml

```<code>version: '3'
services:
  edv-reverse-proxy:
    image: traefik
    container_name: edv-reverse-proxy
    expose:
      - 8080
    ports:
      - 80:80
      - 443:443
      - 8080:8080
    volumes:
      - ./traefik/dev-cert.pem:/etc/traefik/dev-cert.pem
      - ./traefik/dev-key.nopass.pem:/etc/traefik/dev-key.nopass.pem
      - ./traefik/ca.cert.pem:/etc/traefik/ca.cert.pem
      - ./traefik/traefik.toml:/etc/traefik/traefik.toml
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - proxy

  whoami:
    image: emilevauge/whoami
    expose:
      - 80
    labels:
      - traefik.enable=true
      - "traefik.frontend.rule=Host:whoami.test"
      - traefik.port=80
    networks:
      - proxy

networks:
  proxy:
    external: true
</code>```

/etc/hosts

```<code>127.0.0.1       whoami.test
</code>```

If I disable the whole entrypoints section I can connect to the service with whoami.test like expected. I tried a lot of different settings which didn't seem to have any effect.

So if anyone knows how to solve this I would be really glad!

答:
For a traefik v2.1 default router http to https redirect you can do the following:

```<code>traefik:
    image: traefik:v2.1
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    ports:
      - 80:80
      - 443:443
    labels:
      - "traefik.enable=true"
      ### Default HTTP Router
      - "traefik.http.routers.default-http2https.rule=HostRegexp(`{subdomain:[a-z,0-9]+}.example.com`)"
      - "traefik.http.routers.default-http2https.entrypoints=http"
      - "traefik.http.routers.default-http2https.middlewares=https-redirect@file"
      ### SSL
      - "traefik.http.routers.frontend.rule=Host(`traefik.example.com`)"
      - "traefik.http.routers.frontend.entrypoints=https"
      - "traefik.http.routers.frontend.tls.certresolver=example.com"
      - "traefik.http.routers.frontend.tls.domains[0].main=example.com"
      - "traefik.http.routers.frontend.tls.domains[0].sans=*.example.com"
      - "traefik.http.routers.frontend.service=api@internal"
</code>```

I found the solution here: https://docs.traefik.io/routing/routers/#rule

Title: Redirect HTTP to HTTPS on localhost

Body:
I want to have a dev setup on my local machine to more easily test new versions of my programm - it's a server/client application. The client does need SSL and so I want to have traefik as a proxy to the (local) server which will use a self signed certificate.

I managed to get a connection without SSL but as soon as I enable HTTPS / Redirecting, traefik only responses with "backend not found" "/" 0ms.

The SSL certificate is valid according to my browsers.

Here is my setup:

traefik.toml

[docker]
watch = true
exposedByDefault = false

logLevel = "DEBUG"
defaultEntryPoints = ["https", "http"]

[accessLog]
[traefikLog]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
  [entryPoints.https.tls]
    [[entryPoints.https.tls.certificates]]
      ca = "etc/traefik/ca.cert.pem"
      certFile = "/etc/traefik/dev-cert.pem"
      keyFile = "/etc/traefik/dev-key.nopass.pem"

# API definition
[api]
entryPoint = "traefik"
dashboard = true

docker-compose.yaml

version: '3'
services:
  edv-reverse-proxy:
    image: traefik
    container_name: edv-reverse-proxy
    expose:
      - 8080
    ports:
      - 80:80
      - 443:443
      - 8080:8080
    volumes:
      - ./traefik/dev-cert.pem:/etc/traefik/dev-cert.pem
      - ./traefik/dev-key.nopass.pem:/etc/traefik/dev-key.nopass.pem
      - ./traefik/ca.cert.pem:/etc/traefik/ca.cert.pem
      - ./traefik/traefik.toml:/etc/traefik/traefik.toml
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - proxy

  whoami:
    image: emilevauge/whoami
    expose:
      - 80
    labels:
      - traefik.enable=true
      - "traefik.frontend.rule=Host:whoami.test"
      - traefik.port=80
    networks:
      - proxy

networks:
  proxy:
    external: true

/etc/hosts

127.0.0.1       whoami.test

If I disable the whole entrypoints section I can connect to the service with whoami.test like expected. I tried a lot of different settings which didn't seem to have any effect.

So if anyone knows how to solve this I would be really glad!

Body:
For a traefik v2.1 default router http to https redirect you can do the following:

traefik:
    image: traefik:v2.1
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    ports:
      - 80:80
      - 443:443
    labels:
      - "traefik.enable=true"
      ### Default HTTP Router
      - "traefik.http.routers.default-http2https.rule=HostRegexp(`{subdomain:[a-z,0-9]+}.example.com`)"
      - "traefik.http.routers.default-http2https.entrypoints=http"
      - "traefik.http.routers.default-http2https.middlewares=https-redirect@file"
      ### SSL
      - "traefik.http.routers.frontend.rule=Host(`traefik.example.com`)"
      - "traefik.http.routers.frontend.entrypoints=https"
      - "traefik.http.routers.frontend.tls.certresolver=example.com"
      - "traefik.http.routers.frontend.tls.domains[0].main=example.com"
      - "traefik.http.routers.frontend.tls.domains[0].sans=*.example.com"
      - "traefik.http.routers.frontend.service=api@internal"

I found the solution here: https://docs.traefik.io/routing/routers/#rule


问:
Excluding unit tests from external library
I newly replaced spongyCastle by bouncyCastle in an Android project:

```<code>implementation "org.bouncycastle:bcpkix-jdk15on:$project.bouncyCastleVersion"
</code>```

Since then on Jenkins (our CI) it seems that there are tests being executed from this lib, could this be true? I never saw external libs with units tests executing automatically. The issue is now I see many failed tests, for example:

```<code>org.bouncycastle.pqc.crypto.qtesla.QTeslaKeyEncodingTests.testDecodeEncodePrivateKeyQT3P    27 ms   1
 org.bouncycastle.pqc.crypto.qtesla.QTeslaKeyEncodingTests.testDecodeEncodePublicKeyQT3P
</code>```

Is there a way to exlude al unit tets from an imported library in gradle?

答:
idk if it helps, but I had some issues with my CI related to spongy castle. I solved them by ignoring linting to its packages.
In app.gradle, add:

```<code>  lintOptions {
    lintConfig file("lint.xml")
  }
</code>```

lint.xml

```<code><lint>
  <issue id="InvalidPackage">
    <!-- ignore Invalid Package check for spongycastle -->
    <ignore path="**/*spongycastle*.jar"/>
  </issue>
</lint>
</code>```

My problem was with linting, but you can probably ignore it for testing too.

Body:
I newly replaced spongyCastle by bouncyCastle in an Android project:

implementation "org.bouncycastle:bcpkix-jdk15on:$project.bouncyCastleVersion"

Since then on Jenkins (our CI) it seems that there are tests being executed from this lib, could this be true? I never saw external libs with units tests executing automatically. The issue is now I see many failed tests, for example:

org.bouncycastle.pqc.crypto.qtesla.QTeslaKeyEncodingTests.testDecodeEncodePrivateKeyQT3P    27 ms   1
 org.bouncycastle.pqc.crypto.qtesla.QTeslaKeyEncodingTests.testDecodeEncodePublicKeyQT3P

Is there a way to exlude al unit tets from an imported library in gradle?

Body:
idk if it helps, but I had some issues with my CI related to spongy castle. I solved them by ignoring linting to its packages.
In app.gradle, add:

  lintOptions {
    lintConfig file("lint.xml")
  }

lint.xml

<lint>
  <issue id="InvalidPackage">
    <!-- ignore Invalid Package check for spongycastle -->
    <ignore path="**/*spongycastle*.jar"/>
  </issue>
</lint>

My problem was with linting, but you can probably ignore it for testing too.


问:
Question on threading in C#
I have a Windows Forms application at the moment, and I want to create a new thread and run a method on another class that accepts an input.

For example

```<code>public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
}

class SMS
{
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other codes
    }
}
</code>```

How do I perform this in C#? I have seen numerous examples on the web, and most of them run the method on the same class with no parameters, but none that suits my requirements.

答:
How about just use the ThreadPool directly with a anonymous method allowing you to access your surrounding locals?</p>

```<code>    public void OnButtonClick(object sender, EventArgs e)
    {
        SerialPort serialInput = this.SerialInput;
        System.Threading.ThreadPool.QueueUserWorkItem(delegate
        {
            SmsListener listener = new SmsListener(serialInput);
        });
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Question on threading in C#

Body:
I have a Windows Forms application at the moment, and I want to create a new thread and run a method on another class that accepts an input.

For example

public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
}

class SMS
{
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other codes
    }
}

How do I perform this in C#? I have seen numerous examples on the web, and most of them run the method on the same class with no parameters, but none that suits my requirements.

Body:
How about just use the ThreadPool directly with a anonymous method allowing you to access your surrounding locals?

    public void OnButtonClick(object sender, EventArgs e)
    {
        SerialPort serialInput = this.SerialInput;
        System.Threading.ThreadPool.QueueUserWorkItem(delegate
        {
            SmsListener listener = new SmsListener(serialInput);
        });
    }


问:
Why does itoa expect a signed character instead of an unsigned?
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

```<code>main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'
</code>```

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)

答:
So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices

This is true mainly for the reason that (accidentally or intentionally) signed operands mixed with the bitwise operators create havoc. But also there aren't many cases in low level programming where you actually need to use signed types.

For example, MISRA-C enforces you to always use unsigned variables, operands and integer constant unless the intention is to actually use a signed type. So this isn't just something opinion-based, MISRA-C is de facto industry standard for most professional embedded systems.

so I've started to use uint8_t arrays to hold strings

That's ok but it isn't wrong to use char for that purpose either. The only time when it is ok to use char is when you intend to store text. Note that char is especially nasty, because unlike all other types in the language, it has unknown signedness. Each compiler can make char either signed or unsigned and still conform with the C standard. So code relying on char being either signed or unsigned is broken. However, for text strings this doesn't matter since they are always positive.

However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

Your compiler apparently treats char as signed then. First of all please note that itoa isn't standard C and isn't allowed to exist inside stdlib.h when strict C standard conformance is desired. But more importantly, different compilers might implement the function differently since it isn't standardized.

As it turns out, you can safely cast wildly between the various character types: char, unsigned char, signed char, int8_t and uint8_t (the stdint.h 8 bit types are pretty much dead certain to be character types even though the standard doesn't say so explicitly). The character types specifically have various special rules associated with them, meaning that you can always cast something to a character type.

You can safely cast your uint8_t array to a char*, as long as there are no qualifiers (const etc) present.

Body:
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)


问:
How to "flatten" a multi-dimensional array to simple one in PHP?
It's probably beginner question but I'm going through documentation for longer time already and I can't find any solution. I thought I could use implode for each dimension and then put those strings back together with str_split to make new simple array. However I never know if the join pattern isn't also in values and so after doing str_split my original values could break.

Is there something like combine($array1, $array2) for arrays inside of multi-dimensional array?

答:
Someone might find this useful, I had a problem flattening array at some dimension, I would call it last dimension so for example, if I have array like:

```<code>array (
  'germany' =>
  array (
    'cars' =>
    array (
      'bmw' =>
      array (
        0 => 'm4',
        1 => 'x3',
        2 => 'x8',
      ),
    ),
  ),
  'france' =>
  array (
    'cars' =>
    array (
      'peugeot' =>
      array (
        0 => '206',
        1 => '3008',
        2 => '5008',
      ),
    ),
  ),
)
</code>```

Or:

```<code>array (
  'earth' =>
  array (
    'germany' =>
    array (
      'cars' =>
      array (
        'bmw' =>
        array (
          0 => 'm4',
          1 => 'x3',
          2 => 'x8',
        ),
      ),
    ),
  ),
  'mars' =>
  array (
    'france' =>
    array (
      'cars' =>
      array (
        'peugeot' =>
        array (
          0 => '206',
          1 => '3008',
          2 => '5008',
        ),
      ),
    ),
  ),
)
</code>```

For both of these arrays when I call method below I get result:

```<code>array (
  0 =>
  array (
    0 => 'm4',
    1 => 'x3',
    2 => 'x8',
  ),
  1 =>
  array (
    0 => '206',
    1 => '3008',
    2 => '5008',
  ),
)
</code>```

So I am flattening to last array dimension which should stay the same, method below could be refactored to actually stop at any kind of level:

```<code>function flattenAggregatedArray($aggregatedArray) {
    $final = $lvls = [];
    $counter = 1;
    $lvls[$counter] = $aggregatedArray;

    $elem = current($aggregatedArray);

    while ($elem){
        while(is_array($elem)){
            $counter++;
            $lvls[$counter] = $elem;
            $elem =  current($elem);
        }

        $final[] = $lvls[$counter];
        $elem = next($lvls[--$counter]);
        while ( $elem  == null){
            if (isset($lvls[$counter-1])){
                $elem = next($lvls[--$counter]);
            }
            else{
                return $final;
            }
        }
    }
}
</code>```

OwnerDisplayName: perfectDay

Body:
Someone might find this useful, I had a problem flattening array at some dimension, I would call it last dimension so for example, if I have array like:

array (
  'germany' =>
  array (
    'cars' =>
    array (
      'bmw' =>
      array (
        0 => 'm4',
        1 => 'x3',
        2 => 'x8',
      ),
    ),
  ),
  'france' =>
  array (
    'cars' =>
    array (
      'peugeot' =>
      array (
        0 => '206',
        1 => '3008',
        2 => '5008',
      ),
    ),
  ),
)

Or:

array (
  'earth' =>
  array (
    'germany' =>
    array (
      'cars' =>
      array (
        'bmw' =>
        array (
          0 => 'm4',
          1 => 'x3',
          2 => 'x8',
        ),
      ),
    ),
  ),
  'mars' =>
  array (
    'france' =>
    array (
      'cars' =>
      array (
        'peugeot' =>
        array (
          0 => '206',
          1 => '3008',
          2 => '5008',
        ),
      ),
    ),
  ),
)

For both of these arrays when I call method below I get result:

array (
  0 =>
  array (
    0 => 'm4',
    1 => 'x3',
    2 => 'x8',
  ),
  1 =>
  array (
    0 => '206',
    1 => '3008',
    2 => '5008',
  ),
)

So I am flattening to last array dimension which should stay the same, method below could be refactored to actually stop at any kind of level:

function flattenAggregatedArray($aggregatedArray) {
    $final = $lvls = [];
    $counter = 1;
    $lvls[$counter] = $aggregatedArray;

    $elem = current($aggregatedArray);

    while ($elem){
        while(is_array($elem)){
            $counter++;
            $lvls[$counter] = $elem;
            $elem =  current($elem);
        }

        $final[] = $lvls[$counter];
        $elem = next($lvls[--$counter]);
        while ( $elem  == null){
            if (isset($lvls[$counter-1])){
                $elem = next($lvls[--$counter]);
            }
            else{
                return $final;
            }
        }
    }
}


问:
Azure functions output bindings parameter name does not included in context.bindings
I use Iothub trigger functions , and I want to set Cosmosdb as output . When its done, I logged out context.bindings only shows {"IoTHubMessages":["Test Message"]}

did i miss something?

any suggestion would be appreciated, Thanks

EDITED :
functions.json

index.js

as third parameter, it is undefined.

答:
Please refer to the official binding documentation.

If you want to store a single document during the Function execution

If your name your binding outputDocument in the function.json file, then you need to use context.bindings.outputDocument = variable_containing_the_document;.

If you want to store multiple documents during the Function execution

You need to use an Array. Create an Array, push any documents you want to save to it, and finally assign it to the context.bindings.outputDocument:

```<code>var documentsToSave = [];
documentsToSave.push(some_document_data);
documentsToSave.push(some_other_document_data);
//...
context.bindings.outputDocument = documentsToSave;
</code>```

Body:
Please refer to the official binding documentation.

If you want to store a single document during the Function execution

If your name your binding outputDocument in the function.json file, then you need to use context.bindings.outputDocument = variable_containing_the_document;.

If you want to store multiple documents during the Function execution

You need to use an Array. Create an Array, push any documents you want to save to it, and finally assign it to the context.bindings.outputDocument:

var documentsToSave = [];
documentsToSave.push(some_document_data);
documentsToSave.push(some_other_document_data);
//...
context.bindings.outputDocument = documentsToSave;


问:
React TS - How to map through FontAwesome icons and display them
I'm trying to create a reusable component that allows me to pass in the href, target, rel attributes along with the type of FontAwesome Icon I would like to use. I'd like to be able to pass as many icons as I would like into this list and it would map through them, using the Social component as a template.

I would like the map to happen within the Social.tsx file, then I can simply just add the component anywhere in my project and then pass the props to it.

Something like this:

```<code><Social
  icons={[
    { icon: "facebook", href: "", target: "", rel: "" },
    { icon: "twitter", href: "", target: "", rel: "" },
    { icon: "discord", href: "", target: "", rel: "" }
  ]}
/>
</code>```

I currently have my component:

Social.tsx

```<code>import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";

interface ISocial {
  href?: string
  target?: string
  rel?: string
}

const Social: React.FC<ISocial> = (props) => {
  return (
    <div>
      <a href={props.href} target={props.target} rel={props.rel}>
        {/* I don't want to hardcode the icon, but dynamically pass it as a prop */}
        <FontAwesomeIcon icon={["fab", "discord"]} />
      </a>
    </div>
  );
};

export default Social;
</code>```

App.tsx

```<code>import * as React from "react";
import "./styles.css";
import Social from "./components/Social";

export default function App() {
  // I'd like to be able to pass in a list of different icons
  // followed by the href, target, rel, etc for each item.
  // The Social component would be able to map through them
  // and display them.
  return <Social />;
</code>```

How can I adapt this to do what I described above?

Here's a CodeSandBox

Thanks for any help in advance!

答:
So, I think the problem is with structuring the props that you want to pass.

For instance, we will pass an array of type IconProp then you can easily map over it.

Now you can make your own interface and pass props of this type

```<code>interface myType {
  href?: string;
  target?: string;
  rel?: string;
  icon: IconProp;
}
const dummyProp: myType[] = [
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] }
];

const Social: React.FC<ISocial> = props => {
  return (
    <div>
      {dummyProp.map(p => (
        <a href={p.href} target={p.target} rel={p.rel}>
          <FontAwesomeIcon icon={p.icon} />
        </a>
      ))}
    </div>
  );
</code>```

Body:
I'm trying to create a reusable component that allows me to pass in the href, target, rel attributes along with the type of FontAwesome Icon I would like to use. I'd like to be able to pass as many icons as I would like into this list and it would map through them, using the Social component as a template.

I would like the map to happen within the Social.tsx file, then I can simply just add the component anywhere in my project and then pass the props to it.

Something like this:

<Social
  icons={[
    { icon: "facebook", href: "", target: "", rel: "" },
    { icon: "twitter", href: "", target: "", rel: "" },
    { icon: "discord", href: "", target: "", rel: "" }
  ]}
/>

I currently have my component:

Social.tsx

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";

interface ISocial {
  href?: string
  target?: string
  rel?: string
}

const Social: React.FC<ISocial> = (props) => {
  return (

        {/* I don't want to hardcode the icon, but dynamically pass it as a prop */}
        <FontAwesomeIcon icon={["fab", "discord"]} />

  );
};

export default Social;

App.tsx

import * as React from "react";
import "./styles.css";
import Social from "./components/Social";

export default function App() {
  // I'd like to be able to pass in a list of different icons
  // followed by the href, target, rel, etc for each item.
  // The Social component would be able to map through them
  // and display them.
  return <Social />;

How can I adapt this to do what I described above?

Here's a CodeSandBox

Thanks for any help in advance!

Body:
So, I think the problem is with structuring the props that you want to pass.

For instance, we will pass an array of type IconProp then you can easily map over it.

Now you can make your own interface and pass props of this type

interface myType {
  href?: string;
  target?: string;
  rel?: string;
  icon: IconProp;
}
const dummyProp: myType[] = [
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] }
];

const Social: React.FC<ISocial> = props => {
  return (
    <div>
      {dummyProp.map(p => (
        <a href={p.href} target={p.target} rel={p.rel}>
          <FontAwesomeIcon icon={p.icon} />
        </a>
      ))}
    </div>
  );


问:
IISExpress Custom Domains
I've been (successfully) running a couple of ASP.NET (.NET Framework 4.6.2, WebForms) websites through Visual Studio 2017 / IISExpress using custom domains. I installed Visual Studio 2019 (Community) the other day, and all of a sudden the custom domains have stopped working on all projects in both Visual Studio 2017 and 2019! The system-tray for IIS Express still continues to show that the binding is accepted:

However, when attempting to browse to that URL, Chrome gives me a "ERR_CONNECTION_REFUSED" error:

Just to be clear, the steps are taken on each project are as follows:

Modify the applicationhost.config file in the web project's .vs folder to include:

<binding protocol="http" bindingInformation="*:80:agentdesktop.local" />

In an elevated command prompt, execute:

netsh http add urlacl url=http://agentdesktop.local:80/ user=everyone

Add to the hosts file:

127.0.0.1    agentdesktop.local

I've deleted the .vs directory, removed the urlacl entry, removed the IISExpress directory in the Documents folder. Performed all actions outlined above as had been done previously, and still I cannot get it to accept the connection!

If I ping agentdesktop.local then I get a valid response from 127.0.0.1, and the fact it's appearing in the IIS Express system tray, makes me think that something in between is intercepting and blocking.

Does anybody else have any ideas as to how I could get this back working again, or what might have gone wrong!?

答:
I did some more digging, and found that running

netsh http show iplisten

Had a single entry of ::1. I removed this using:

netsh http delete iplisten address=::1

and everything started working again. Not quite sure what happened, but glad I found it.

Title: IISExpress Custom Domains


问:
Angular 2 : No NgModule metadata found
I'm brand new to Angular 2 and attempting to follow along with a video tutorial I found. Despite following all of the steps, Angular just won't work; I get the following error:

```<code>compiler.umd.js:13854 Uncaught Error: No NgModule metadata found for 'App'.
</code>```

and the component doesn't load at all.

Here are my files:

package.json:

```<code>{
  "name": "retain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "webpack --config webpack.spec.ts --progress --color && karma start",
    "start": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "core-js": "2.4.1",
    "lodash": "4.16.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "0.9.33",
    "@types/lodash": "4.14.35",
    "@types/node": "6.0.39",
    "awesome-typescript-loader": "2.2.4",
    "css-loader": "0.23.1",
    "jasmine-core": "2.4.1",
    "karma": "1.1.1",
    "karma-chrome-launcher": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-mocha-reporter": "2.0.4",
    "raw-loader": "0.5.1",
    "to-string-loader": "1.1.4",
    "ts-helpers": "1.1.1",
    "typescript": "2.0.2",
    "webpack": "1.13.1",
    "webpack-dev-server": "1.14.1"
  }
}
</code>```

index.html:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset=UTF-8>
    <title>Retain</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/flexboxgrid/6.3.0/flexboxgrid.min.css" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link href="global.css" rel="stylesheet">
    <base href="/">
  </head>
  <body>

    <app>
      ... before angular loads.
    </app>

    <script src="polyfills.bundle.js"></script>
    <script src="vendor.bundle.js"></script>
    <script src="main.bundle.js"></script>

  </body>
</html>
</code>```

main.ts:

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

import { App } from './app/app';

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

app.ts:

```<code>import { Component } from '@angular/core';
import { NgModule }      from '@angular/core';

@Component({
  selector: 'app',
  template: `
    <div>
      <h3>
        Yo, world!
      </h3>
    </div>
    `
})

export class App {}
</code>```

app.module.ts:

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { App } from './app';

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App]
})

export class AppModule{};
</code>```

Thanks for your time.

答: I had the same issue and I resolved it by closing the editor i.e. Visual Studio Code, started it again, run ng serve and it worked.

Title: Angular 2 : No NgModule metadata found

Body:
I'm brand new to Angular 2 and attempting to follow along with a video tutorial I found. Despite following all of the steps, Angular just won't work; I get the following error:

compiler.umd.js:13854 Uncaught Error: No NgModule metadata found for 'App'.

and the component doesn't load at all.

Here are my files:

package.json:

{
  "name": "retain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "webpack --config webpack.spec.ts --progress --color && karma start",
    "start": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "core-js": "2.4.1",
    "lodash": "4.16.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "0.9.33",
    "@types/lodash": "4.14.35",
    "@types/node": "6.0.39",
    "awesome-typescript-loader": "2.2.4",
    "css-loader": "0.23.1",
    "jasmine-core": "2.4.1",
    "karma": "1.1.1",
    "karma-chrome-launcher": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-mocha-reporter": "2.0.4",
    "raw-loader": "0.5.1",
    "to-string-loader": "1.1.4",
    "ts-helpers": "1.1.1",
    "typescript": "2.0.2",
    "webpack": "1.13.1",
    "webpack-dev-server": "1.14.1"
  }
}

index.html:

<!DOCTYPE html>

    <meta charset=UTF-8>
    <title>Retain</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/flexboxgrid/6.3.0/flexboxgrid.min.css" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link href="global.css" rel="stylesheet">
    <base href="/">

    <app>
      ... before angular loads.
    </app>

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

import { App } from './app/app';

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

platformBrowserDynamic().bootstrapModule(AppModule);

app.ts:

import { Component } from '@angular/core';
import { NgModule }      from '@angular/core';

@Component({
  selector: 'app',
  template: `

        Yo, world!

    `
})

export class App {}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { App } from './app';

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App]
})

export class AppModule{};

Thanks for your time.


问:
Mock: assert mock_calls with a numpy array as argument raises ValueError and np.testing.assert_array_equal does not work
I have a mocked object that I would like to check its calls using mock_calls, where it is called with numpy arrays. But the problem is that it raises ValueError, as shown in the following simple toy example.

```<code>>>> mocked_model_called_with_np_array = mock.Mock()
>>> mocked_model_called_with_np_array(np.array([1, 2]))
>>> mocked_model_called_with_np_array.mock_calls
[call(array([1, 2]))]
</code>```

Now I set the expected calls:

```<code>>>> expected_call_with_numpy = [mock.call(np.array([1, 2]))]
</code>```

Now if I check it as shown below, it raises error:

```<code>>>> assert expected_call_with_numpy == mocked_model_called_with_np_array.mock_calls

---------------------------------------------------------------------------
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-61-9806e62badf5> in <module>
----> 1 assert expected_call_with_numpy == mocked_model_called_with_np_array.mock_calls

c:\..\python\python36\lib\unittest\mock.py in __eq__(self, other)
   2053
   2054         # this order is important for ANY to work!
-> 2055         return (other_args, other_kwargs) == (self_args, self_kwargs)
   2056
   2057

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

My search on stackoverflow and the found solutions:

HERE it is suggested to use np.testing.assert_array_equal while you have numpy arrays, but this also does not solve my problems as shown below.

```<code>>>> np.testing.assert_array_equal(expected_call_with_numpy, mocked_model_called_with_np_array.mock_calls)

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-57-4a0373c94354> in <module>
----> 1 np.testing.assert_array_equal(expected_call_with_numpy, mocked_model_called_with_np_array.mock_calls)

c:\...\python\python36\lib\site-packages\numpy\testing\utils.py in assert_array_equal(x, y, err_msg, verbose)
    852     __tracebackhide__ = True  # Hide traceback for py.test
    853     assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
--> 854                          verbose=verbose, header='Arrays are not equal')
    855
    856

c:\...\python\python36\lib\site-packages\numpy\testing\utils.py in assert_array_compare(comparison, x, y, err_msg, verbose, header, precision, equal_nan, equal_inf)
    776                                 names=('x', 'y'), precision=precision)
    777             if not cond:
--> 778                 raise AssertionError(msg)
    779     except ValueError:
    780         import traceback

AssertionError:
Arrays are not equal

(mismatch 100.0%)
 x: array([['', (array([1, 2]),), {}]], dtype=object)
 y: array([['', (array([1, 2]),), {}]], dtype=object)
</code>```

Note that the arrays are the same, but it produces error!

Can anyone comment on how to use mock_calls for a mockec object called with a numpy array and then check if the mock_calls produce the expected calls? e.g., something like below

```<code>assert expected_call_with_numpy == mocked_model_called_with_np_array.mock_calls
</code>```

答:
Ran in to the same problem trying to check if mocked calls contained a specific numpy array.
Turns out that the call object is indexable so you can also do stuff like this:

```<code>>>> import numpy as np
>>> from unittest import mock
>>> mock_object = mock.MagicMock()
>>> mock_object(1, np.array([1, 2, 3]), a=3)
>>> mock_object(10, np.array([10, 20, 30]), b=30)
>>> calls = mock_object.call_args_list
>>> calls
[call(1, array([1, 2, 3]), a=3), call(10, array([10, 20, 30]), b=30)]
>>> calls[0]
call(1, array([1, 2, 3]), a=3)
>>> calls[0][0]
(1, array([1, 2, 3]))
>>> calls[0][1]
{'a': 3}
</code>```

So that instead of asserting that the calls are equal you can just check that the calls were made and that arguments passed were correct individually, ugly but it works:

```<code>>>> assert mock_object.call_count == 2
>>> assert calls[0][0][0] == 1
>>> np.testing.assert_array_equal(calls[0][0][1], np.array([1, 2, 3]))
>>> assert calls[0][1]['a'] == 3
...
</code>```

Body:
I have a mocked object that I would like to check its calls using mock_calls, where it is called with numpy arrays. But the problem is that it raises ValueError, as shown in the following simple toy example.

>>> mocked_model_called_with_np_array = mock.Mock()
>>> mocked_model_called_with_np_array(np.array([1, 2]))
>>> mocked_model_called_with_np_array.mock_calls
[call(array([1, 2]))]

Now I set the expected calls:

>>> expected_call_with_numpy = [mock.call(np.array([1, 2]))]

Now if I check it as shown below, it raises error:

>>> assert expected_call_with_numpy == mocked_model_called_with_np_array.mock_calls

---------------------------------------------------------------------------
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-61-9806e62badf5> in <module>
----> 1 assert expected_call_with_numpy == mocked_model_called_with_np_array.mock_calls

c:\..\python\python36\lib\unittest\mock.py in __eq__(self, other)
   2053
   2054         # this order is important for ANY to work!
-> 2055         return (other_args, other_kwargs) == (self_args, self_kwargs)
   2056
   2057

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

My search on stackoverflow and the found solutions:

HERE it is suggested to use np.testing.assert_array_equal while you have numpy arrays, but this also does not solve my problems as shown below.

>>> np.testing.assert_array_equal(expected_call_with_numpy, mocked_model_called_with_np_array.mock_calls)

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-57-4a0373c94354> in <module>
----> 1 np.testing.assert_array_equal(expected_call_with_numpy, mocked_model_called_with_np_array.mock_calls)

c:\...\python\python36\lib\site-packages\numpy\testing\utils.py in assert_array_equal(x, y, err_msg, verbose)
    852     __tracebackhide__ = True  # Hide traceback for py.test
    853     assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
--> 854                          verbose=verbose, header='Arrays are not equal')
    855
    856

c:\...\python\python36\lib\site-packages\numpy\testing\utils.py in assert_array_compare(comparison, x, y, err_msg, verbose, header, precision, equal_nan, equal_inf)
    776                                 names=('x', 'y'), precision=precision)
    777             if not cond:
--> 778                 raise AssertionError(msg)
    779     except ValueError:
    780         import traceback

AssertionError:
Arrays are not equal

(mismatch 100.0%)
 x: array([['', (array([1, 2]),), {}]], dtype=object)
 y: array([['', (array([1, 2]),), {}]], dtype=object)

Note that the arrays are the same, but it produces error!

Can anyone comment on how to use mock_calls for a mockec object called with a numpy array and then check if the mock_calls produce the expected calls? e.g., something like below

assert expected_call_with_numpy == mocked_model_called_with_np_array.mock_calls

Body:
Ran in to the same problem trying to check if mocked calls contained a specific numpy array.
Turns out that the call object is indexable so you can also do stuff like this:

>>> import numpy as np
>>> from unittest import mock
>>> mock_object = mock.MagicMock()
>>> mock_object(1, np.array([1, 2, 3]), a=3)
>>> mock_object(10, np.array([10, 20, 30]), b=30)
>>> calls = mock_object.call_args_list
>>> calls
[call(1, array([1, 2, 3]), a=3), call(10, array([10, 20, 30]), b=30)]
>>> calls[0]
call(1, array([1, 2, 3]), a=3)
>>> calls[0][0]
(1, array([1, 2, 3]))
>>> calls[0][1]
{'a': 3}

So that instead of asserting that the calls are equal you can just check that the calls were made and that arguments passed were correct individually, ugly but it works:

>>> assert mock_object.call_count == 2
>>> assert calls[0][0][0] == 1
>>> np.testing.assert_array_equal(calls[0][0][1], np.array([1, 2, 3]))
>>> assert calls[0][1]['a'] == 3
...


问:
Publish messages that could not be de-serialized to DLT topic
I do not understand how messages that could not be de-serialized can be written to a DLT topic with spring kafka.

I configured the consumer according to the spring kafka docs and this works well for exceptions that occur after de-serialization of the message.

But when the message is not de-serializable a org.apache.kafka.common.errors.SerializationExceptionis thrown while polling for messages.

Subsequently, SeekToCurrentErrorHandler.handle(Exception thrownException, List<ConsumerRecord<?, ?>> records, ...) is called with this exception but with an empty list of records and is therefore unable to write something to DLT topic.

How can I write those messages to DLT topic also?

答:
The problem is that the exception is thrown by the Kafka client itself so Spring doesn't get to see the actual record that failed.

That's why we added the ErrorHandlingDeserializer2 which can be used to wrap the actual deserializer; the failure is passed to the listener container and re-thrown as a DeserializationException.

See the documentation.

When a deserializer fails to deserialize a message, Spring has no way to handle the problem, because it occurs before the poll() returns. To solve this problem, version 2.2 introduced the ErrorHandlingDeserializer2. This deserializer delegates to a real deserializer (key or value). If the delegate fails to deserialize the record content, the ErrorHandlingDeserializer2 returns a null value and a DeserializationException in a header that contains the cause and the raw bytes. When you use a record-level MessageListener, if the ConsumerRecord contains a DeserializationException header for either the key or value, the container’s ErrorHandler is called with the failed ConsumerRecord. The record is not passed to the listener.

The DeadLetterPublishingRecoverer has logic to detect the exception and publish the failed record.


问:
Which Database is SQLEditor supposed to query on
DBeaver 6.2.1

Regularily, I want to perform an sql query on the database I am currently working on. Since there is no "query sql" in the context menu, I try to use the SQL Editor, which opens an editor window where I can write the sql I like. However, this does not work as expected. Actually, there is no information which Database the sql Editor is working on, and my expectation that it must be the one currently selected just proved to be wrong.

So 2 Questions:

What is the expected way to query sql on the currently selected Database in DBeaver

What Database is the SQL Editor defaultly working on and how can I change this?

答:
What is the expected way to query sql on the currently selected Database in DBeaver

Use ANSI SQL standard queries. For example, I execute queries on Sybase using DBeaver as this

```<code>SELECT COUNT(1) FROM UserTable1
</code>```

What Database is the SQL Editor defaultly working on and how can I change this?

Menu Bar > Window > Database Navigator : This lists out all the schemas/databases on the connected server and the one highlighted in BOLD is the one DBeaver is connected to based on what is mentioned while creating connection.

You can activate/change/select Database/schema by pressing ctrl+0 to bring up "Active Catalog/Schema" option.

-- In 'thoughts'...

Body:
What is the expected way to query sql on the currently selected Database in DBeaver

Use ANSI SQL standard queries. For example, I execute queries on Sybase using DBeaver as this

SELECT COUNT(1) FROM UserTable1

What Database is the SQL Editor defaultly working on and how can I change this?

Menu Bar > Window > Database Navigator : This lists out all the schemas/databases on the connected server and the one highlighted in BOLD is the one DBeaver is connected to based on what is mentioned while creating connection.

You can activate/change/select Database/schema by pressing ctrl+0 to bring up "Active Catalog/Schema" option.

-- In 'thoughts'...


答:
Have a list of strings with icon names and use map if required to have list.

```<code>export default function App() {
  return (
    <Social
      icons={[
        { icon: "facebook", href: "", target: "", rel: "" },
        { icon: "twitter", href: "", target: "", rel: "" },
        { icon: "discord", href: "", target: "", rel: "" }
      ]}
    />
  );
}
</code>```

Changes to Social Component. Just add new prop like name

```<code>import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";
import { IconName } from "@fortawesome/fontawesome-svg-core";

interface ISocial {
  href?: string;
  target?: string;
  rel?: string;
  icon: IconName;
}

interface ISocialList {
  icons: Array<ISocial>;
}

const Social: React.FC<ISocialList> = props => {
  const { icons } = props;
  return (
    <div>
      {icons.map(item => {
        return (
          <a href={item.href} target={item.target} rel={item.rel}>
            <FontAwesomeIcon icon={["fab", item.icon]} />
          </a>
        );
      })}
    </div>
  );
};

export default Social;
</code>```

Code changes to your sandbox https://codesandbox.io/s/headless-bush-br14l

Title: React TS - How to map through FontAwesome icons and display them

Body:
Have a list of strings with icon names and use map if required to have list.

export default function App() {
  return (
    <Social
      icons={[
        { icon: "facebook", href: "", target: "", rel: "" },
        { icon: "twitter", href: "", target: "", rel: "" },
        { icon: "discord", href: "", target: "", rel: "" }
      ]}
    />
  );
}

Changes to Social Component. Just add new prop like name

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";
import { IconName } from "@fortawesome/fontawesome-svg-core";

interface ISocial {
  href?: string;
  target?: string;
  rel?: string;
  icon: IconName;
}

interface ISocialList {
  icons: Array<ISocial>;
}

const Social: React.FC<ISocialList> = props => {
  const { icons } = props;
  return (
    <div>
      {icons.map(item => {
        return (
          <a href={item.href} target={item.target} rel={item.rel}>
            <FontAwesomeIcon icon={["fab", item.icon]} />
          </a>
        );
      })}
    </div>
  );
};

export default Social;

Code changes to your sandbox https://codesandbox.io/s/headless-bush-br14l


问:
Check if double are given with a specific accuracy
I have a vector of double. Those numbers are given with a precision such as 0.001 meaning that the numbers are given with a thousandth of units accuracy. For example I'm expecting to have 123456789.012 but not 123456789.01231. In practice, because of floating-point arithmetic the actual numbers are more like 123456789.01199999452 which is the valid and closest representation of 123456789.012.

I'd like to robustly test if my numbers are actually given with the accuracy there are supposed to be. For example I'd like to warn if I have the 123456789.01231 which does not match with the accuracy 0.001. Another valid option to me is to find the accuracy of a given number.

What I've done so far is to test if (x - offset)/accuracy is an integer. The offset protects against integer overflow. In practice, because of floating-point arithmetic, it cannot be an integer so I added an arbitrary threshold. It works but it is not a robust solution in my opinion.

dx = (x[i]-offset)/accuracy;
ix = std::round(dx);
if (std::abs(dx - ix) > 1e-5)
  throw exception("...");
```

No string is involved in this process. The numbers come from binary files or from runtime computations. The accuracy is given by the user and the numbers are expected to be compliant with this accuracy. In my previous example of 123456789.012 I do know that this number does not actually exist but 123456789.01199999452 is valid because it is its best representation with double. But 123456789.01231 (actually 123456789.01230999827) is not valid because it is not the best representation of the 3 digits rounded value.

答:
It seems you want to ensure that your numbers are as close as possible to a set of numbers, which are an arithmetic progression from 0 to infinity with common difference of the accuracy value. In this case, this is basically a quantization task with further evaluation of the quantization error.

```<code>#include <cmath>
#include <iostream>

bool is_number_accurate(double n, double accuracy)
{
    bool accurate = false;

    std::cout << "n: " << n << ", ";

    n = std::abs(n);
    if (n > accuracy)
    {
        // Epsilon to account for precision loss from the calculations below,
        // as well as floating point representation error.
        const double epsilon = 0.00001;

        // Remainder from quantizing n to accuracy precision
        // (i.e. quantization error)
        double rem = std::fmod(n, accuracy);

        // Normalize to 1.0. Here 0 means n exactly matches the quantized value,
        // and slightly greater than 0 means that n is slightly greater than the
        // quantized value.
        // Values close to 1.0 also mean n is close to match the quantized value,
        // but is slightly less than it.
        double error = rem / accuracy;
        std::cout << "error: " << error << ", ";

        accurate = error < epsilon || (error <= 1.0 && error > (1.0 - epsilon));
    }
    else
    {
        accurate = n == 0.0 || n == accuracy;
    }

    std::cout << "accurate: " << accurate << std::endl;

    return accurate;
}

int main()
{
    is_number_accurate(0.0, 0.001);
    is_number_accurate(0.0000000000001, 0.001);
    is_number_accurate(0.001, 0.001);
    is_number_accurate(0.01, 0.001);
    is_number_accurate(123456789.012, 0.001);
    is_number_accurate(123456789.0121, 0.001);
    is_number_accurate(123456789.0125, 0.001);
    is_number_accurate(123456789.0129, 0.001);
    is_number_accurate(123456789.013, 0.001);
    is_number_accurate(123456789.01231, 0.001);
}
</code>```

The output is:

```<code>n: 0, accurate: 1
n: 1e-13, accurate: 0
n: 0.001, accurate: 1
n: 0.01, error: 0, accurate: 1
n: 1.23457e+08, error: 0.999992, accurate: 1
n: 1.23457e+08, error: 0.0999936, accurate: 0
n: 1.23457e+08, error: 0.5, accurate: 0
n: 1.23457e+08, error: 0.899992, accurate: 0
n: 1.23457e+08, error: 0.999994, accurate: 1
n: 1.23457e+08, error: 0.309996, accurate: 0
</code>```

Body:
I have a vector of double. Those numbers are given with a precision such as 0.001 meaning that the numbers are given with a thousandth of units accuracy. For example I'm expecting to have 123456789.012 but not 123456789.01231. In practice, because of floating-point arithmetic the actual numbers are more like 123456789.01199999452 which is the valid and closest representation of 123456789.012.

I'd like to robustly test if my numbers are actually given with the accuracy there are supposed to be. For example I'd like to warn if I have the 123456789.01231 which does not match with the accuracy 0.001. Another valid option to me is to find the accuracy of a given number.

What I've done so far is to test if (x - offset)/accuracy is an integer. The offset protects against integer overflow. In practice, because of floating-point arithmetic, it cannot be an integer so I added an arbitrary threshold. It works but it is not a robust solution in my opinion.

dx = (x[i]-offset)/accuracy;
ix = std::round(dx);
if (std::abs(dx - ix) > 1e-5)
  throw exception("...");

No string is involved in this process. The numbers come from binary files or from runtime computations. The accuracy is given by the user and the numbers are expected to be compliant with this accuracy. In my previous example of 123456789.012 I do know that this number does not actually exist but 123456789.01199999452 is valid because it is its best representation with double. But 123456789.01231 (actually 123456789.01230999827) is not valid because it is not the best representation of the 3 digits rounded value.

Body:
It seems you want to ensure that your numbers are as close as possible to a set of numbers, which are an arithmetic progression from 0 to infinity with common difference of the accuracy value. In this case, this is basically a quantization task with further evaluation of the quantization error.

#include <cmath>
#include <iostream>

bool is_number_accurate(double n, double accuracy)
{
    bool accurate = false;

    std::cout << "n: " << n << ", ";

    n = std::abs(n);
    if (n > accuracy)
    {
        // Epsilon to account for precision loss from the calculations below,
        // as well as floating point representation error.
        const double epsilon = 0.00001;

        // Remainder from quantizing n to accuracy precision
        // (i.e. quantization error)
        double rem = std::fmod(n, accuracy);

        // Normalize to 1.0. Here 0 means n exactly matches the quantized value,
        // and slightly greater than 0 means that n is slightly greater than the
        // quantized value.
        // Values close to 1.0 also mean n is close to match the quantized value,
        // but is slightly less than it.
        double error = rem / accuracy;
        std::cout << "error: " << error << ", ";

        accurate = error < epsilon || (error <= 1.0 && error > (1.0 - epsilon));
    }
    else
    {
        accurate = n == 0.0 || n == accuracy;
    }

    std::cout << "accurate: " << accurate << std::endl;

    return accurate;
}

int main()
{
    is_number_accurate(0.0, 0.001);
    is_number_accurate(0.0000000000001, 0.001);
    is_number_accurate(0.001, 0.001);
    is_number_accurate(0.01, 0.001);
    is_number_accurate(123456789.012, 0.001);
    is_number_accurate(123456789.0121, 0.001);
    is_number_accurate(123456789.0125, 0.001);
    is_number_accurate(123456789.0129, 0.001);
    is_number_accurate(123456789.013, 0.001);
    is_number_accurate(123456789.01231, 0.001);
}

The output is:

n: 0, accurate: 1
n: 1e-13, accurate: 0
n: 0.001, accurate: 1
n: 0.01, error: 0, accurate: 1
n: 1.23457e+08, error: 0.999992, accurate: 1
n: 1.23457e+08, error: 0.0999936, accurate: 0
n: 1.23457e+08, error: 0.5, accurate: 0
n: 1.23457e+08, error: 0.899992, accurate: 0
n: 1.23457e+08, error: 0.999994, accurate: 1
n: 1.23457e+08, error: 0.309996, accurate: 0


问:
How do you reference and dereference a cstring array in a function for C?
```<code>char *wordList[15];
</code>```

This is the char point array, my question is if I were to put in a function like this:

```<code>decodeMessage(input, wordList);
</code>```

how would I dereference it in the function so changes could be made to it?

答:
Arrays are converted to a pointer to the first element when passed to a function.

As a result, changes to array elements in the function involve a pointer dereference and thus are visible from the calling function.

Body:
char *wordList[15];

This is the char point array, my question is if I were to put in a function like this:

decodeMessage(input, wordList);

how would I dereference it in the function so changes could be made to it?


问:
Django, connect one field with multiple models
I guess it is a "normal" problem. I want to connect model C with different Models A,B,..

```<code>Model A "buildings"
 - time_built
 - description
 - adress
 - architects[]=Model C
 - places

Model B "photos":
 - time_taken
 - title
 - architects[]=Model C
 - places

Model C "architects"
- title
- time_born
- website
- items[]=Model A+Model B
</code>```

So items should be connected m:n to Model A or B for querying like "find architects by buildings in California". Model A and B can have multiple architects.

Is it possible to realize something like this in Django? I thought to use a Intermediate Model, but as I understood it does not help me too.

答:
Yes, Django has Many-to-many relationships.

In Buildings, put

```<code>    architects = models.ManyToManyField(Architect)
</code>```

In Photos, put

```<code>    architects = models.ManyToManyField(Architect)
</code>```

This will handle the relationship and by creation the migration file and running it, the DB tables will be created automatically (they should be 5).

Body:
I guess it is a "normal" problem. I want to connect model C with different Models A,B,..

Model A "buildings"
 - time_built
 - description
 - adress
 - architects[]=Model C
 - places

Model B "photos":
 - time_taken
 - title
 - architects[]=Model C
 - places

Model C "architects"
- title
- time_born
- website
- items[]=Model A+Model B

So items should be connected m:n to Model A or B for querying like "find architects by buildings in California". Model A and B can have multiple architects.

Is it possible to realize something like this in Django? I thought to use a Intermediate Model, but as I understood it does not help me too.

Body:
Yes, Django has Many-to-many relationships.

In Buildings, put

    architects = models.ManyToManyField(Architect)

In Photos, put

    architects = models.ManyToManyField(Architect)

This will handle the relationship and by creation the migration file and running it, the DB tables will be created automatically (they should be 5).


问:
How to use the AIO fingerprint?
I need to use a fingerprint scanner on android and iphone. How to do it right?

I found several options:

1) try(mhartington Ionic Team)

when(In app.module.ts)

```<code>import { FingerprintAIO } from '@ionic-native/fingerprint-aio'

@NgModule({
  providers: [
...
    FingerprintAIO,
...

  ]
})
</code>```

error:

index.js:92 Uncaught TypeError: Object(...) is not a function

My attempt.

2) try (from ionicframework.com)

when(In app.component.ts)

```<code>import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
</code>```

error:

TS2307: Cannot find module '@ionic-native/fingerprint-aio/ngx'.

My attempt.

How to use a fingerprint right now?

3) try

error:

"SECURITY_EXCEPTION"

or

"plugin_not_installed"

答:
You should run this cmd </p>

```<code>npm install @ionic-native/fingerprint-aio@5.22.0-beta-1
</code>```

<p>to add this dependency to your project and fix </p>

```<code>import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
</code>```

Title: How to use the AIO fingerprint?

Body:
I need to use a fingerprint scanner on android and iphone. How to do it right?

I found several options:

1) try(mhartington Ionic Team)

when(In app.module.ts)

import { FingerprintAIO } from '@ionic-native/fingerprint-aio'

@NgModule({
  providers: [
...
    FingerprintAIO,
...

  ]
})

error:

index.js:92 Uncaught TypeError: Object(...) is not a function

My attempt.

2) try (from ionicframework.com)

when(In app.component.ts)

import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';

error:

TS2307: Cannot find module '@ionic-native/fingerprint-aio/ngx'.

My attempt.

How to use a fingerprint right now?

3) try

error:

"SECURITY_EXCEPTION"

or

"plugin_not_installed"

Body:
You should run this cmd

npm install @ionic-native/fingerprint-aio@5.22.0-beta-1

to add this dependency to your project and fix

import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';


问:
How to get value from select?
I have select list:

```<code>   <select (change)="onChange($event.target.value)">
            <option
              *ngFor="let option of tab.content.value()"
              [value]="option"
              >{{ option.name }}</option
            >
          </select>
</code>```

I have tried to get model option as selected value:

```<code>onChange(data) {
    console.log(data);
}
</code>```

答:
Can you try:</p>

```<code>   <select (change)="onChange($event)">
            <option
              *ngFor="let option of tab.content.value"
              [value]="option"
              >{{ option.name }}</option
            >
          </select>

onChange(data: Event) {
    console.log(data.target.value);
}
</code>```

Title: How to get value from select?

Body:
I have select list:

   <select (change)="onChange($event.target.value)">
            <option
              *ngFor="let option of tab.content.value()"
              [value]="option"
              >{{ option.name }}</option
            >
          </select>

I have tried to get model option as selected value:

onChange(data) {
    console.log(data);
}

Body:
Can you try:

   <select (change)="onChange($event)">
            <option
              *ngFor="let option of tab.content.value"
              [value]="option"
              >{{ option.name }}</option
            >
          </select>

onChange(data: Event) {
    console.log(data.target.value);
}


问:
OnCreate is called multiply when app is started from Play Store App first and then from home screen
It occurred to me that under some circumstances our app seems to be restarted from scratch after being backgrounded. I managed to track to issue down to MainActivity.OnCreate being called multiply under the following circumstances

App is installed from APK and then ran from the installer, after backgrounding the app and starting it from the home screen it's reset to scratch

This behavior persists until the app is killed and then restarted from the home screen

App is run from Google Play app, after backgrounding the app and starting it from the home screen it's reset to scratch

If the app is backgrounded and then started from Play Store it's started correctly

App is run from home screen, after backgrounding the app and starting it from Google Play it's reset to scratch

When the app is foregrounded from the same launcher it has been started initially, OnCreate is not called again. There is at least one question reporting a similar behavior, unfortunately there is no answer providing a solution for the behavior.

When MainActivity.OnCreate is called, the instance of MainActivity seems to be a different instance than the initial one, since private members that are set in OnCreate are null when I'm trying to log them, anyway, the application context does not seem to be recreated from scratch, because AppCenter seems to be initialized right away on the second run, Xamarin.Forms starts up way quicker and static variables keep their values.

Is there any way to prevent this behavior and just keep a single instance of MainActivity active?

答:
in your android manifest set on the activity tag

```<code>android:launchMode="singleTop"
</code>```

It will have consequences on how you handle notifications, and in some cases onActivityResult

Body:
in your android manifest set on the activity tag

android:launchMode="singleTop"

It will have consequences on how you handle notifications, and in some cases onActivityResult


问:
"infinite" sql statement?
I've got a very strange sql-related problem.

I'm accessing a MSSQL Server 2005 with PHP (odbc), when I profile the sql statement the following is executed:

```<code>declare @p1 int
set @p1=180150003
declare @p3 int
set @p3=2
declare @p4 int
set @p4=1
declare @p5 int
set @p5=-1
exec sp_cursoropen @p1 output,N'SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5

exec sp_cursorfetch 180150003,2,1,1
</code>```

On my own server it's working fine, on the customer-server the sp_cursorfetch reads infinite rows and loads the full cpu.
When I try to execute the statement itself

```<code>SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL
</code>```

in SQL Server Management Studio it works fine (under 1sec).

Any ideas?

Edit:
the main difference between the servers is that my server is a x86 (Win2003) and the server of the customer is a x64 (Win2008).

Edit2: Added Where-Clause

答:
Your cursor is declared as DYNAMIC (@p3 =2). In the Management Studio, try to declare it as FAST FORWARD (@p3=16) and see if it helps.

Paste the profiler output you posted into Management Studio, replacing the parameter in sp_cursorfecth:

```<code>exec sp_cursorfetch @p1, 2, 1, 1
</code>```

and see if the problem persists.

OwnerDisplayName: chris

ContentLicense: CC BY-SA 2.5

Title: "infinite" sql statement?

Body:
I've got a very strange sql-related problem.

I'm accessing a MSSQL Server 2005 with PHP (odbc), when I profile the sql statement the following is executed:

declare @p1 int
set @p1=180150003
declare @p3 int
set @p3=2
declare @p4 int
set @p4=1
declare @p5 int
set @p5=-1
exec sp_cursoropen @p1 output,N'SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5

exec sp_cursorfetch 180150003,2,1,1

On my own server it's working fine, on the customer-server the sp_cursorfetch reads infinite rows and loads the full cpu.
When I try to execute the statement itself

SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL

in SQL Server Management Studio it works fine (under 1sec).

Any ideas?

Edit:
the main difference between the servers is that my server is a x86 (Win2003) and the server of the customer is a x64 (Win2008).

Edit2: Added Where-Clause

LastEditorDisplayName: DJ

Body:
Your cursor is declared as DYNAMIC (@p3 =2). In the Management Studio, try to declare it as FAST FORWARD (@p3=16) and see if it helps.

Paste the profiler output you posted into Management Studio, replacing the parameter in sp_cursorfecth:

exec sp_cursorfetch @p1, 2, 1, 1

and see if the problem persists.

OwnerDisplayName: Quassnoi

LastEditorDisplayName: Quassnoi


问:
Sentiment analysis with Lambda Expressions in Python
I'm trying to use TextBlob to perform sentiment analysis in Power BI. I'd like to use a lamdba expression because it seems to be substantially faster than running an iterative loop in Power BI.

For example, using Text Blob:

```<code>dataset['Polarity Score'] =dataset['Comment'].apply(lambda x: TextBlob(str(x).lower()).sentiment.polarity)
</code>```

creates a Power BI data column named "Polarity Score" that has the numerical values from TextBlob.

I would like to do similar withe the TextBlob.classify() function. However, I don't know how to pass it the second argument of the classifier.

Tutorials show to create and use a classifier:

```<code>from textblob.classifiers import NaiveBayesClassifier
from textblob import TextBlob

cl = NaiveBayesClassifier(train)
blob = TextBlob("The beer is good. But the hangover is horrible.", classifier=cl)
blob.classify()
</code>```

I've tried

```<code>dataset['Polarity Class'] =dataset['Comment'].apply(lambda x: TextBlob(str(x).lower()).classify(), classifier=cl)
</code>```

and

```<code>dataset['Polarity Class'] =dataset['Comment'].apply(lambda x,y: TextBlob(str(x).lower()).classify(), y=cl)
</code>```

Neither work and point to the way I'm passing the classifier. How would I pass the classifier parameter in a lambda expression?

答:
Simply

```<code>cl = NaiveBayesClassifier(train)
dataset['Polarity Class'] = dataset['Comment'].apply(
    lambda x: TextBlob(str(x).lower(), classifier=cl).classify()
)
</code>```

Or if you want to refactor the possibly confusing lambda expression out,

```<code>cl = NaiveBayesClassifier(train)

def classify(x):
    return TextBlob(str(x).lower(), classifier=cl).classify()

dataset['Polarity Class'] = dataset['Comment'].apply(classify)
</code>```

is equivalent.

Body:
I'm trying to use TextBlob to perform sentiment analysis in Power BI. I'd like to use a lamdba expression because it seems to be substantially faster than running an iterative loop in Power BI.

For example, using Text Blob:

dataset['Polarity Score'] =dataset['Comment'].apply(lambda x: TextBlob(str(x).lower()).sentiment.polarity)

creates a Power BI data column named "Polarity Score" that has the numerical values from TextBlob.

I would like to do similar withe the TextBlob.classify() function. However, I don't know how to pass it the second argument of the classifier.

Tutorials show to create and use a classifier:

from textblob.classifiers import NaiveBayesClassifier
from textblob import TextBlob

cl = NaiveBayesClassifier(train)
blob = TextBlob("The beer is good. But the hangover is horrible.", classifier=cl)
blob.classify()

I've tried

dataset['Polarity Class'] =dataset['Comment'].apply(lambda x: TextBlob(str(x).lower()).classify(), classifier=cl)

and

dataset['Polarity Class'] =dataset['Comment'].apply(lambda x,y: TextBlob(str(x).lower()).classify(), y=cl)

Neither work and point to the way I'm passing the classifier. How would I pass the classifier parameter in a lambda expression?

Body:
Simply

cl = NaiveBayesClassifier(train)
dataset['Polarity Class'] = dataset['Comment'].apply(
    lambda x: TextBlob(str(x).lower(), classifier=cl).classify()
)

Or if you want to refactor the possibly confusing lambda expression out,

cl = NaiveBayesClassifier(train)

def classify(x):
    return TextBlob(str(x).lower(), classifier=cl).classify()

dataset['Polarity Class'] = dataset['Comment'].apply(classify)

is equivalent.


问:
Limiting Request to Web API that are coming from same location
We have a web api where we allow anon[AllowAnonymous] users to register using our own mobile apps(android & iOS). Recently it was reported that there are multiple users registered with the same email address which we do not allow. We have multiple check to not allow this to happen. When we check our IIS log. We have something like this:

```<code>2020-02-15 18:40:42 XXX.XXX.X.XX POST /api/Account/Register - 8082 - Y.YY.YYY.YYY OurIOSAppName/3+CFNetwork/1121.2.2+Darwin/19.3.0 - 400 0 64 69968
2020-02-15 18:40:42 XXX.XXX.X.XX POST /api/Account/Register - 8082 - Y.YY.YYY.YYY OurIOSAppName/3+CFNetwork/1121.2.2+Darwin/19.3.0 - 200 0 0 13218
2020-02-15 18:40:42 XXX.XXX.X.XX POST /api/Account/Register - 8082 - Y.YY.YYY.YYY OurIOSAppName/3+CFNetwork/1121.2.2+Darwin/19.3.0 - 200 0 0 17390
</code>```

it seems that the our web api is receiving multiple request from the iOS mobile app using AlamoFire and the same with RetroFit for Android. Is there away prevent this?

答:
The issue isn't that there are multiple requests coming at the same time, but rather your code for creating users has a race condition. There are numerous ways to deal with this with the below two tickets just being a start.

Preventing race condition of if-exists-update-else-insert in Entity Framework

https://softwareengineering.stackexchange.com/questions/263726/how-to-prevent-race-conditions-in-a-web-application

Body:
We have a web api where we allow anon[AllowAnonymous] users to register using our own mobile apps(android & iOS). Recently it was reported that there are multiple users registered with the same email address which we do not allow. We have multiple check to not allow this to happen. When we check our IIS log. We have something like this:

2020-02-15 18:40:42 XXX.XXX.X.XX POST /api/Account/Register - 8082 - Y.YY.YYY.YYY OurIOSAppName/3+CFNetwork/1121.2.2+Darwin/19.3.0 - 400 0 64 69968
2020-02-15 18:40:42 XXX.XXX.X.XX POST /api/Account/Register - 8082 - Y.YY.YYY.YYY OurIOSAppName/3+CFNetwork/1121.2.2+Darwin/19.3.0 - 200 0 0 13218
2020-02-15 18:40:42 XXX.XXX.X.XX POST /api/Account/Register - 8082 - Y.YY.YYY.YYY OurIOSAppName/3+CFNetwork/1121.2.2+Darwin/19.3.0 - 200 0 0 17390

it seems that the our web api is receiving multiple request from the iOS mobile app using AlamoFire and the same with RetroFit for Android. Is there away prevent this?


问:
Can't connect to remote mongodb with macOS
I am trying to connect to a mongodb service hosted on IBM Cloud following this instructions.

When I run the following command

```<code>mongo -u $USERNAME -p $PASSWORD --ssl --sslCAFile c5f07836-d94c-11e8-a2e9-62ec2ed68f84 --authenticationDatabase admin --host replset/bdb98a3ac10-0.b8a5e798d2d04f2e860d042c915.databases.appdomain.cloud:30484,bd576-96db98a3ac10-1.b8a5e4e5d042c915.databases.appdomain.cloud:30484
</code>```

I get this error on macOs, while on Windows 10 the connection is correctly estiblished:

SSL peer certificate validation failed: Certificate trust failure:
  Invalid Extended Key Usage for policy; connection rejected

If I connect via MongoDB Compass instead of using the terminal the connection works

答:
I had to add --sslAllowInvalidCertificates flag

https://docs.mongodb.com/manual/reference/configuration-options/#net.ssl.allowConnectionsWithoutCertificates

Body:
I am trying to connect to a mongodb service hosted on IBM Cloud following this instructions.

When I run the following command

mongo -u $USERNAME -p $PASSWORD --ssl --sslCAFile c5f07836-d94c-11e8-a2e9-62ec2ed68f84 --authenticationDatabase admin --host replset/bdb98a3ac10-0.b8a5e798d2d04f2e860d042c915.databases.appdomain.cloud:30484,bd576-96db98a3ac10-1.b8a5e4e5d042c915.databases.appdomain.cloud:30484

I get this error on macOs, while on Windows 10 the connection is correctly estiblished:

SSL peer certificate validation failed: Certificate trust failure:
  Invalid Extended Key Usage for policy; connection rejected

If I connect via MongoDB Compass instead of using the terminal the connection works


问:
Compare two dataframes Pyspark
I'm trying to compare two data frames with have same number of columns i.e. 4 columns with id as key column in both data frames

```<code>df1 = spark.read.csv("/path/to/data1.csv")
df2 = spark.read.csv("/path/to/data2.csv")
</code>```

Now I want to append new column to DF2 i.e. column_names which is the list of the columns with different values than df1

```<code>df2.withColumn("column_names",udf())
</code>```

DF1

```<code>+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | UK      |
|     3|  GHI   | 3000 | JPN     |
|     4|  JKL   | 4500 | CHN     |
+------+---------+--------+------+
</code>```

DF2:

```<code>+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | CAN     |
|     3|  GHI   | 3500 | JPN     |
|     4|  JKL_M | 4800 | CHN     |
+------+---------+--------+------+
</code>```

Now I want DF3

DF3:

```<code>+------+---------+--------+------+--------------+
|   id | |name  | sal  | Address | column_names |
+------+---------+--------+------+--------------+
|     1|  ABC   | 5000 | US      |  []          |
|     2|  DEF   | 4000 | CAN     |  [address]   |
|     3|  GHI   | 3500 | JPN     |  [sal]       |
|     4|  JKL_M | 4800 | CHN     |  [name,sal]  |
+------+---------+--------+------+--------------+
</code>```

I saw this SO question, How to compare two dataframe and print columns that are different in scala. Tried that, however the result is different.

I'm thinking of going with a UDF function by passing row from each dataframe to udf and compare column by column and return column list. However for that both the data frames should be in sorted order so that same id rows will be sent to udf. Sorting is costly operation here. Any solution?

答:
Assuming that we can use id to join these two datasets I don't think that there is a need for UDF. This could be solved just by using inner join, array and array_remove functions among others.

First let's create the two datasets:

df1 = spark.createDataFrame([
  [1, "ABC", 5000, "US"],
  [2, "DEF", 4000, "UK"],
  [3, "GHI", 3000, "JPN"],
  [4, "JKL", 4500, "CHN"]
], ["id", "name", "sal", "Address"])

df2 = spark.createDataFrame([
  [1, "ABC", 5000, "US"],
  [2, "DEF", 4000, "CAN"],
  [3, "GHI", 3500, "JPN"],
  [4, "JKL_M", 4800, "CHN"]
], ["id", "name", "sal", "Address"])
```
<p>First we do an inner join between the two datasets then we generate the condition <code>df1[col] != df2[col]</code> for each column except <code>id</code>. When the columns aren't equal we return the column name otherwise an empty string. The list of conditions will consist the items of an array from which finally we remove the empty items:</p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql.functions import col, array, when, array_remove

# get conditions for all columns except id
conditions_ = [when(df1[c]!=df2[c], lit(c)).otherwise("") for c in df1.columns if c != 'id']

select_expr =[
                col("id"),
                *[df2[c] for c in df2.columns if c != 'id'],
                array_remove(array(*conditions_), "").alias("column_names")
]

df1.join(df2, "id").select(*select_expr).show()

# +---+-----+----+-------+------------+
# | id| name| sal|Address|column_names|
# +---+-----+----+-------+------------+
# |  1|  ABC|5000|     US|          []|
# |  3|  GHI|3500|    JPN|       [sal]|
# |  2|  DEF|4000|    CAN|   [Address]|
# |  4|JKL_M|4800|    CHN| [name, sal]|
# +---+-----+----+-------+------------+
</code>```

Title: Compare two dataframes Pyspark

Body:
I'm trying to compare two data frames with have same number of columns i.e. 4 columns with id as key column in both data frames

df1 = spark.read.csv("/path/to/data1.csv")
df2 = spark.read.csv("/path/to/data2.csv")

Now I want to append new column to DF2 i.e. column_names which is the list of the columns with different values than df1

df2.withColumn("column_names",udf())

DF1

+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | UK      |
|     3|  GHI   | 3000 | JPN     |
|     4|  JKL   | 4500 | CHN     |
+------+---------+--------+------+

DF2:

+------+---------+--------+------+
|   id | |name  | sal  | Address |
+------+---------+--------+------+
|     1|  ABC   | 5000 | US      |
|     2|  DEF   | 4000 | CAN     |
|     3|  GHI   | 3500 | JPN     |
|     4|  JKL_M | 4800 | CHN     |
+------+---------+--------+------+

Now I want DF3

DF3:

+------+---------+--------+------+--------------+
|   id | |name  | sal  | Address | column_names |
+------+---------+--------+------+--------------+
|     1|  ABC   | 5000 | US      |  []          |
|     2|  DEF   | 4000 | CAN     |  [address]   |
|     3|  GHI   | 3500 | JPN     |  [sal]       |
|     4|  JKL_M | 4800 | CHN     |  [name,sal]  |
+------+---------+--------+------+--------------+

I saw this SO question, How to compare two dataframe and print columns that are different in scala. Tried that, however the result is different.

I'm thinking of going with a UDF function by passing row from each dataframe to udf and compare column by column and return column list. However for that both the data frames should be in sorted order so that same id rows will be sent to udf. Sorting is costly operation here. Any solution?

Body:
Assuming that we can use id to join these two datasets I don't think that there is a need for UDF. This could be solved just by using inner join, array and array_remove functions among others.

First let's create the two datasets:

df1 = spark.createDataFrame([
  [1, "ABC", 5000, "US"],
  [2, "DEF", 4000, "UK"],
  [3, "GHI", 3000, "JPN"],
  [4, "JKL", 4500, "CHN"]
], ["id", "name", "sal", "Address"])

df2 = spark.createDataFrame([
  [1, "ABC", 5000, "US"],
  [2, "DEF", 4000, "CAN"],
  [3, "GHI", 3500, "JPN"],
  [4, "JKL_M", 4800, "CHN"]
], ["id", "name", "sal", "Address"])

First we do an inner join between the two datasets then we generate the condition df1[col] != df2[col] for each column except id. When the columns aren't equal we return the column name otherwise an empty string. The list of conditions will consist the items of an array from which finally we remove the empty items:

from pyspark.sql.functions import col, array, when, array_remove

# get conditions for all columns except id
conditions_ = [when(df1[c]!=df2[c], lit(c)).otherwise("") for c in df1.columns if c != 'id']

select_expr =[
                col("id"),
                *[df2[c] for c in df2.columns if c != 'id'],
                array_remove(array(*conditions_), "").alias("column_names")
]

df1.join(df2, "id").select(*select_expr).show()

# +---+-----+----+-------+------------+
# | id| name| sal|Address|column_names|
# +---+-----+----+-------+------------+
# |  1|  ABC|5000|     US|          []|
# |  3|  GHI|3500|    JPN|       [sal]|
# |  2|  DEF|4000|    CAN|   [Address]|
# |  4|JKL_M|4800|    CHN| [name, sal]|
# +---+-----+----+-------+------------+


问:
Flutter How to handle text selection?
I need to display a styled text for reading and some actions. User should be able to select piece of text and mark it with color, save it or expand it (show an additional information, for example a translation to another language).

I can display text by using RichText widget.

1) How to make it selectable and how/where to add onTextSelected listener? There is a class TextSelection but I can't see how/where its used.

2) What is a simplest way to expand text? I can reload full text (with changes added) and totally update widget, but this will result to scrolling to the top of a text and I think there should be a better approach.

答: You now have SelectableText() widget available

Title: Flutter How to handle text selection?


问:
efficient method to sync up two tables in different servers with java
we have a source table which is updated from various external systems. i require the destination table (in different server) to be in sync with this source table. the destination table is not an exact replica of the source table, some data processing has to be done before the data is inserted/updated into destination table.

i have thought of the following logic

every 15min we run this java consumer code which fetches the records where the timestamp is created than that of previous update and stored in a CachedRowSet. and call a stored procedure with CachedRowSet as parameter, where the data processing is done and the data is inserted/updated into the destination table.

do you believe above mentioned is an efficient way as we are dealing over a million records every update ?

also when a record is deleted in the source table in would not be replicated in the above method ! can you suggest what to do in such scenario

答:
Something similar to technique used by database for save point and rollback.
Whenever there is some change in the source table e.g. CRUD. keep the scripts of change as per format required to the target table. periodically you can push those changes to the target server. As your source table is updated by various external system, you'll need to have trigger on your source table for keeping script logs.</p>


问:
Using EF Core, what is the most efficient way to dynamically switch schemas given a single DbContext?
I own an application with ~500 users, and for security and separation of concerns, we use a separate schema to manage a user's data with tables that are identical in structure for everyone. I cannot create a new dbcontext class for each user, and they are dynamic so we create the schema via code (which works great). I recently figured out how to use EF migrations for each user's schema as well, so the only thing I'm struggling with is dynamically swapping the schema I wish to point to for each web request.

The scenario is very similar to the one that this answer (not the chosen answer) solves: https://stackoverflow.com/a/50529432
But this question was posted nearly 4 years ago, so I'm not sure that this answer is the most efficient or even the suggested way to go about it. The github docs point all questions to StackOverflow, so I'm hoping for an up-to-date workaround so that I can leverage the greatness that is EF without having to create my own entire implementation from scratch.

答:
The normal way to accomplish this is to use separate databases per user/tenant.  Then you can simply vary the connection string, instead of having separate schemas in a single database.  Separate databases are more secure, enable scaling across multiple servers, and enable per-tenant backup and restore.

The referenced approach of using a custom ModelKeyCacheFactory to configure and cache a seperate DbContext model for each user should work.  The downside is that you will configure and cache a large number of models, which is not free.

But to use schemas you do have another option.  In EF Core 3.1 (at least) if you don't configure a schema for an Entity, and don't configure a default schema for the DbContext, object names will not be schema-qualified.  So you can potentially use the schema resolution rules of your database to direct queries to the correct schema.  In SQL Server for instance, you would provision a seperate database user for each tenant, with permissions on that tenant's schema, and with the tenant's schema configured as the user's default schema.

You could also potentially use Query Interception to rewrite the queries, after configuring the DbContext to insert some easy-to-replace token as the schema name.


问:
HYPERLINK Formula with Word bookmarks
I'm trying to link some cells to a specific bookmark within a Word document.

Doing this manually...

(Right click > Hyperlink > Address: Word-Document-Adress # Bookmark-Name-1)

...works ok. Clicking this cell opens the word document to the desired bookmark.

But what I want is to automatize this somehow.

I have a given Cell A1 containing Word-Document-Adress # Bookmark-Name-1

So I'm trying to use HYPERLINK formula:

```<code>=HYPERLINK(A1; "Go to Bookmark 1")
</code>```

The hyperlink created contains just the Word_Document_Adress information so does not navigate to the desired bookmark.

Any clue? Thanks

答:
Ok, odd enough I solve this while I'm posting it.

If I select the cell and remove the hyperlink... it lose the blue format but still navigates and this time to the correct section of the Word document.

Title: HYPERLINK Formula with Word bookmarks

Body:
I'm trying to link some cells to a specific bookmark within a Word document.

Doing this manually...

(Right click > Hyperlink > Address: Word-Document-Adress # Bookmark-Name-1)

...works ok. Clicking this cell opens the word document to the desired bookmark.

But what I want is to automatize this somehow.

I have a given Cell A1 containing Word-Document-Adress # Bookmark-Name-1

So I'm trying to use HYPERLINK formula:

=HYPERLINK(A1; "Go to Bookmark 1")

The hyperlink created contains just the Word_Document_Adress information so does not navigate to the desired bookmark.

Any clue? Thanks