问:
how can i get the "validade" value from the array and get only?
The array

```<code>    {"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02-
    01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade":"2026-06-
    01","bandeira":"Mastercard"}]}
</code>```

Inside digiAno I wanted to put only the year value of the array

```<code>this.dadosCC.reset({
  'parcelas': '1',
  'digiNumero': ['**** **** ****', cartao.mask] ,
  'digiNome': cartao.holder,
  'digiMes': '',
  'digiAno': cartao.validade,
  'valor': this.cartS.cart.valorTotal,
  'cpfInput': this.userS.user.cpf,
  'cardToken': this.cardToken,
  'digiCVV':''
 });
</code>```

答:
If you want to get the entire information of validade and put that information inside cartao use this code:

```<code>myObject: any = {
    "status": true,
    "data": [{
      "id": 1,
      "pessoa_id": 75505,
      "created_at": "2022-02-01T17:42:46.000000Z",
      "holder": "LEONARDO LIMA",
      "validade": "2026-06-01",
      "bandeira": "Mastercard"
    }]
  };

  cartao: any = this.myObject.data[0].validade;
</code>```

If you want to get year, month and the day use this.

```<code>myObject: any = {
    "status": true,
    "data": [{
      "id": 1,
      "pessoa_id": 75505,
      "created_at": "2022-02-01T17:42:46.000000Z",
      "holder": "LEONARDO LIMA",
      "validade": "2026-06-01",
      "bandeira": "Mastercard"
    }]
  };

  cartao: any = this.myObject.data[0].validade;

  dateArray: any = this.cartao.split('-');

  year = this.dateArray[0];
  month = this.dateArray[1];
  day = this.dateArray[2];
</code>```

Body:
The array

    {"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02-
    01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade":"2026-06-
    01","bandeira":"Mastercard"}]}

Inside digiAno I wanted to put only the year value of the array

this.dadosCC.reset({
  'parcelas': '1',
  'digiNumero': ['**** **** ****', cartao.mask] ,
  'digiNome': cartao.holder,
  'digiMes': '',
  'digiAno': cartao.validade,
  'valor': this.cartS.cart.valorTotal,
  'cpfInput': this.userS.user.cpf,
  'cardToken': this.cardToken,
  'digiCVV':''
 });

Body:
If you want to get the entire information of validade and put that information inside cartao use this code:

myObject: any = {
    "status": true,
    "data": [{
      "id": 1,
      "pessoa_id": 75505,
      "created_at": "2022-02-01T17:42:46.000000Z",
      "holder": "LEONARDO LIMA",
      "validade": "2026-06-01",
      "bandeira": "Mastercard"
    }]
  };

  cartao: any = this.myObject.data[0].validade;

If you want to get year, month and the day use this.

myObject: any = {
    "status": true,
    "data": [{
      "id": 1,
      "pessoa_id": 75505,
      "created_at": "2022-02-01T17:42:46.000000Z",
      "holder": "LEONARDO LIMA",
      "validade": "2026-06-01",
      "bandeira": "Mastercard"
    }]
  };

  cartao: any = this.myObject.data[0].validade;

  dateArray: any = this.cartao.split('-');

  year = this.dateArray[0];
  month = this.dateArray[1];
  day = this.dateArray[2];


来源: stackexchange

问:
How do I join two queries in SQL using UNION ALL operation?
everyone.

This is my first query

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC ;
</code>```

And this is my second query

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;
</code>```

So, I just want to know what do I have to do to join these queries using UNION ALL (and not any JOIN operator). Cz the next is not working for me.

```<code>SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;
</code>```

Thank u'all, community.
(I really appreciate any kind of feedback).

答:
Its not possible to use two different order by in Union and union all statements. Alternatively it can achieved in the following way.

```<code>USE tempdb ;

CREATE TABLE t1 (ID INT, Col1 VARCHAR(100));
CREATE TABLE t2 (ID INT, Col1 VARCHAR(100));
INSERT INTO t1 (ID, Col1) SELECT 1, 'Col1-t1' UNION ALL SELECT 2, 'Col2-t1' UNION ALL SELECT 3, 'Col3-t1';
INSERT INTO t2 (ID, Col1) SELECT 3, 'Col1-t2' UNION ALL SELECT 2, 'Col2-t2' UNION ALL SELECT 1, 'Col3-t2';

SELECT result1.* FROM
    (SELECT top 1000 tblA.ID, tblA.Col1 FROM t1 AS tblA ORDER BY Col1 desc) AS result1
UNION ALL
    SELECT tblB.ID, tblB.Col1 FROM t2 AS tblB ORDER BY Col1 asc

 DROP TABLE t1;
 DROP TABLE t2;
</code>```

References:

https://blog.sqlauthority.com/2012/10/30/sql-server-union-all-and-order-by-how-to-order-table-separately-while-using-union-all/

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql?view=sql-server-ver15

ContentLicense: CC BY-SA 4.0

Body:
everyone.

This is my first query

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC ;

And this is my second query

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;

So, I just want to know what do I have to do to join these queries using UNION ALL (and not any JOIN operator). Cz the next is not working for me.

SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.apellidos_Autor DESC
UNION ALL
SELECT A.nombres_Autor,A.apellidos_Autor,A.fechaNacimiento_Autor,A.fechaFallecimiento_Autor,L.nombre_Libro,G.nombre_Genero
FROM Autor A , Libro L , Genero G , Autores_X_Libro AXL
WHERE AXL.codigoAutor_AXL = A.codigo_Autor AND AXL.codigoISBN_AXL = L.codigoISBN AND L.codigoGenero_Libro = G.codigo_Genero
ORDER BY A.nombres_Autor ASC ;

Thank u'all, community.
(I really appreciate any kind of feedback).

Body:
Its not possible to use two different order by in Union and union all statements. Alternatively it can achieved in the following way.

USE tempdb ;

CREATE TABLE t1 (ID INT, Col1 VARCHAR(100));
CREATE TABLE t2 (ID INT, Col1 VARCHAR(100));
INSERT INTO t1 (ID, Col1) SELECT 1, 'Col1-t1' UNION ALL SELECT 2, 'Col2-t1' UNION ALL SELECT 3, 'Col3-t1';
INSERT INTO t2 (ID, Col1) SELECT 3, 'Col1-t2' UNION ALL SELECT 2, 'Col2-t2' UNION ALL SELECT 1, 'Col3-t2';

SELECT result1.* FROM
    (SELECT top 1000 tblA.ID, tblA.Col1 FROM t1 AS tblA ORDER BY Col1 desc) AS result1
UNION ALL
    SELECT tblB.ID, tblB.Col1 FROM t2 AS tblB ORDER BY Col1 asc

 DROP TABLE t1;
 DROP TABLE t2;

References:

https://blog.sqlauthority.com/2012/10/30/sql-server-union-all-and-order-by-how-to-order-table-separately-while-using-union-all/

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql?view=sql-server-ver15


问:
Get last entry of a range with identical numbers in R, vectorized
I’ve got this data:

```<code>tribble(
    ~ranges, ~last,
    0,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    2,     NA,
    2,     NA,
    2,     NA,
    3,     NA,
    3,     NA
)
</code>```

and I want to fill the last column only at the row index at the last entry of the number by the ranges column. That means, it should look like this:

```<code>tribble(
    ~ranges, ~last,
    0,     0,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     1,
    2,     NA,
    2,     NA,
    2,     2,
    3,     NA,
    3,     3
)
</code>```

So far I came up with a row-wise approach:

```<code>for (r in seq.int(max(tmp$ranges))) {
  print(r)
  range <- which(tmp$ranges == r) |> max()
  tmp$last[range] <- r
}
</code>```

The main issue is that it is terribly slow. I am looking for a vectorized approach to this issue. Any creative solution out there?

答:
Using replace:

library(dplyr)
df %>%
  group_by(ranges) %>%
  mutate(last = replace(last, n(), ranges[n()]))
```
<hr />
<p>Using <code>ifelse</code>:</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
df %>%
  group_by(ranges) %>%
  mutate(last = ifelse(row_number() == n(), ranges, NA))
</code>```

Using tail:

library(dplyr)
df %>%
  group_by(ranges) %>%
  mutate(last = c(last[-n()], tail(ranges, 1)))
```
<p>output</p>
<pre class="lang-r prettyprint-override"><code>   ranges  last
    <dbl> <dbl>
 1      0     0
 2      1    NA
 3      1    NA
 4      1    NA
 5      1     1
 6      2    NA
 7      2    NA
 8      2     2
 9      3    NA
10      3     3
</code>```

Body:
I’ve got this data:

tribble(
    ~ranges, ~last,
    0,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     NA,
    2,     NA,
    2,     NA,
    2,     NA,
    3,     NA,
    3,     NA
)

and I want to fill the last column only at the row index at the last entry of the number by the ranges column. That means, it should look like this:

tribble(
    ~ranges, ~last,
    0,     0,
    1,     NA,
    1,     NA,
    1,     NA,
    1,     1,
    2,     NA,
    2,     NA,
    2,     2,
    3,     NA,
    3,     3
)

So far I came up with a row-wise approach:

for (r in seq.int(max(tmp$ranges))) {
  print(r)
  range <- which(tmp$ranges == r) |> max()
  tmp$last[range] <- r
}

The main issue is that it is terribly slow. I am looking for a vectorized approach to this issue. Any creative solution out there?

Body:
Using replace:

library(dplyr)
df %>%
  group_by(ranges) %>%
  mutate(last = replace(last, n(), ranges[n()]))

Using ifelse:

library(dplyr)
df %>%
  group_by(ranges) %>%
  mutate(last = ifelse(row_number() == n(), ranges, NA))

Using tail:

library(dplyr)
df %>%
  group_by(ranges) %>%
  mutate(last = c(last[-n()], tail(ranges, 1)))

output

   ranges  last
    <dbl> <dbl>
 1      0     0
 2      1    NA
 3      1    NA
 4      1    NA
 5      1     1
 6      2    NA
 7      2    NA
 8      2     2
 9      3    NA
10      3     3


问:
KMongo custom serializer: readEndDocument can only be called when State is END_OF_DOCUMENT, not when State is VALUE
I'm trying to make a custom serializer for the Color class using the kmongo-coroutine-serialization dependency.
I'm getting an exception when doing it saying:

```<code>Exception in thread "main" org.bson.BsonInvalidOperationException: readEndDocument can only be called when State is END_OF_DOCUMENT, not when State is VALUE.
</code>```

Document I test it on as json

{
    "_id": {
        "$oid": "61fe4f745064370bd1473c41"
    },
    "id": 1,
    "color": "#9ac0db"
}
```
<p><strong><code>ExampleDocument</code> class:</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>@Serializable
data class ExampleDocument(
    @Serializable(with = ColorHexSerializer::class) val color: Color
)
</code>```

ColorHexSerializer object:
for testing purposes I always return blue

internal object ColorHexSerializer : KSerializer<Color> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("color_hex", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Color) {
        val hex = String.format("#%06x", value.rgb and 0xFFFFFF)
        encoder.encodeString(hex)
    }

    override fun deserialize(decoder: Decoder): Color {
        return Color.BLUE
    }
}
```
<p><strong>main function:</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>suspend fun main() {
    registerSerializer(ColorHexSerializer)
    val document =
        KMongo.createClient("connectionString")
            .getDatabase("database")
            .getCollectionOfName<ExampleDocument>("testing")
            .find(eq("id", 1))
            .awaitFirst()
}
</code>```

Converting the bson document to json and deserialize it then with kotlinxserialization works just fine.
Can anyone help me here?

Thanks in advance

答:
From the documentation of Decoder:

Deserialization process takes a decoder and asks him for a sequence of primitive elements, defined by a deserializer serial form, while decoder knows how to retrieve these primitive elements from an actual format representations.

and

To be more specific, serialization asks a decoder for a sequence of "give me an int, give me a double, give me a list of strings and give me another object that is a nested int"

You need to specify all the values you read from the decoder in order. All values written also need to be read. It just seems that (at least in your case) kotlinx.serialization ignores the mistake of leftover content to read while kmongo throws an exception.

By returning the color blue by default, you skip the step of reading the string resulting in the string to be left.

Since there is a String left, the state of the object is VALUE (there is a value left to read) while you try to finish reading the document.

override fun deserialize(decoder: Decoder): Color {
    decoder.decodeString()
    return Color.BLUE
}
```

Body:
I'm trying to make a custom serializer for the Color class using the kmongo-coroutine-serialization dependency.
I'm getting an exception when doing it saying:

Exception in thread "main" org.bson.BsonInvalidOperationException: readEndDocument can only be called when State is END_OF_DOCUMENT, not when State is VALUE.

Document I test it on as json

{
    "_id": {
        "$oid": "61fe4f745064370bd1473c41"
    },
    "id": 1,
    "color": "#9ac0db"
}

ExampleDocument class:

@Serializable
data class ExampleDocument(
    @Serializable(with = ColorHexSerializer::class) val color: Color
)

ColorHexSerializer object:
for testing purposes I always return blue

internal object ColorHexSerializer : KSerializer<Color> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("color_hex", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Color) {
        val hex = String.format("#%06x", value.rgb and 0xFFFFFF)
        encoder.encodeString(hex)
    }

    override fun deserialize(decoder: Decoder): Color {
        return Color.BLUE
    }
}

main function:

suspend fun main() {
    registerSerializer(ColorHexSerializer)
    val document =
        KMongo.createClient("connectionString")
            .getDatabase("database")
            .getCollectionOfName<ExampleDocument>("testing")
            .find(eq("id", 1))
            .awaitFirst()
}

Converting the bson document to json and deserialize it then with kotlinxserialization works just fine.
Can anyone help me here?

Thanks in advance


问:
Python: concise properties
I'm implementing a class in Python which has many properties. Here's an example of a property:

class Test:
    def __init__(self):
        self._value = None

    def get_value(self):
        if self._value is None:
            self._value = datetime.datetime.now()
        return self._value

    def set_value(self, new_value):
        self._value = new_value

    value = property(get_value, set_value)
```

This seems like a lot of code.

Is there a more concise way to implement this pattern? I'm using PyCharm if that makes any difference.

答:
You can use the property decorator:

```<code>class Test:

    def __init__(self):
        self._value = None

    @property
    def value(self):
        if self._value is None:
            self._value = datetime.datetime.now()
        return self._value
</code>```

Of course, you could also get almost the same behavior in this case by writing:

```<code>    def __init__(self):
        self.value = datetime.datetime.now()
</code>```

The difference being that the solution with @property will be read-only by default (see the docs on adding setter and deleter methods), while the latter solution creats a read/write attribute.

Title: Python: concise properties

Body:
I'm implementing a class in Python which has many properties. Here's an example of a property:

class Test:
    def __init__(self):
        self._value = None

    def get_value(self):
        if self._value is None:
            self._value = datetime.datetime.now()
        return self._value

    def set_value(self, new_value):
        self._value = new_value

    value = property(get_value, set_value)

This seems like a lot of code.

Is there a more concise way to implement this pattern? I'm using PyCharm if that makes any difference.

Body:
You can use the property decorator:

class Test:

    def __init__(self):
        self._value = None

    @property
    def value(self):
        if self._value is None:
            self._value = datetime.datetime.now()
        return self._value

Of course, you could also get almost the same behavior in this case by writing:

    def __init__(self):
        self.value = datetime.datetime.now()

The difference being that the solution with @property will be read-only by default (see the docs on adding setter and deleter methods), while the latter solution creats a read/write attribute.


问:
C++ equivalent of Python properties
Is there an equivalent of Python properties in C++? Or would it just be better to do this using getters and setters?</p>

答:
There are no properties in standard C++. However, if you're developing on the Microsoft platform you could use their language extension:

http://msdn.microsoft.com/en-us/library/yhfk0thd.aspx

ContentLicense: CC BY-SA 3.0

Title: C++ equivalent of Python properties


问:
npm err missing script lint when deploying
When running the following command:

npm --prefix "$RESOURCE_DIR" run lint
```

<p>It returns the following error:</p>

<blockquote>
  <p><code>npm ERR! missing script: lint</code></p>

  <p><code>npm ERR! A complete log of this run can be found in:</code></p>

  <p><code>npm ERR! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-04-13T01_27_59_009Z-debug.log</code></p>

  <p><code>Error: functions predeploy error: Command terminated with non-zero exit code1</code></p>
</blockquote>

<p>This is my <code>package.json</code>:</p>

<pre class="lang-js prettyprint-override"><code>  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "firebase-admin": "~5.12.0",
    "firebase-functions": "^1.0.1"
  },
  "private": true
}
</code>```

答: try to replace $RESOURCE_DIR with %RESOURCE_DIR% in your firebase.json file.</p>

Body:
When running the following command:

npm --prefix "$RESOURCE_DIR" run lint

It returns the following error:

npm ERR! missing script: lint

npm ERR! A complete log of this run can be found in:

npm ERR! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-04-13T01_27_59_009Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

This is my package.json:

  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "firebase-admin": "~5.12.0",
    "firebase-functions": "^1.0.1"
  },
  "private": true
}


问:
Pandas: Include rows where column_x.min() and column_y between two values
I have a dataset containing rows of measurements (weight) in the following format:

user_id, day_n, weight

user_id is the identifier of the user. There are multiple rows
with the same user_id.

day_n is the day number on which the measurement is done.

weight is the weight in kg.

For removing outliers or incorrect data, I use a min and max value for both the weight and the day_n column.

For now, I plot all data into a scatter plot.

My question:

How can I only include users, which have their first measurement (weight) between two values (min_weight and max_weight)?

Considering the following example data and min_weight = 70 and max_weight = 75, user_id 1 should be included, but user_id 2 should not.

```<code>user_id, day_n, weight
1, 0, 72
1, 28, 70
1, 68, 69
2, 5, 76
2, 28, 80
2, 78, 78
</code>```

I tried:

I tried to group by user_id and looked for the min() of day_n. I couldn't figure out how to check the weight in this row.

My code:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('../datasets/measurements_2019-12-31_2021-07-01.csv')

# Min and max weights
df = df[df['weight'] > 25]
df = df[df['weight'] < 300]

# Min and max days
df = df[df['day_n'] > -7]
df = df[df['day_n'] < 187]

# Only include rows with > 3 measurements
df = df.groupby('user_id').filter(lambda x: len(x) > 3)

# Scatter plot
plt.scatter(df['day_n'], df['weight'])

# Regression line
m, b = np.polyfit(df['day_n'], df['weight'], 1)
plt.plot(df['day_n'], m*df['day_n']+b,color='red')

plt.show()
</code>```

答:
sort then find the user id to keep:</p>
```<code>df = pd.DataFrame({'user_id':[1,1,1,2,2,2],
                   'day_n': [0, 28, 68, 5, 28, 78],
                   'weight': [72, 70, 69, 76, 80, 78]})
df = df.sort_values(['user_id', 'day_n'])
keep_user = df.groupby('user_id')['weight'].first().between(70, 75)
df.loc[df['user_id'].isin(keep_user[keep_user].index)]
</code>```
```<code>    user_id day_n   weight
0   1       0       72
1   1       28      70
2   1       68      69
</code>```

Body:
I have a dataset containing rows of measurements (weight) in the following format:

user_id, day_n, weight

user_id is the identifier of the user. There are multiple rows
with the same user_id.

day_n is the day number on which the measurement is done.

weight is the weight in kg.

For removing outliers or incorrect data, I use a min and max value for both the weight and the day_n column.

For now, I plot all data into a scatter plot.

My question:

How can I only include users, which have their first measurement (weight) between two values (min_weight and max_weight)?

Considering the following example data and min_weight = 70 and max_weight = 75, user_id 1 should be included, but user_id 2 should not.

user_id, day_n, weight
1, 0, 72
1, 28, 70
1, 68, 69
2, 5, 76
2, 28, 80
2, 78, 78

I tried:

I tried to group by user_id and looked for the min() of day_n. I couldn't figure out how to check the weight in this row.

My code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('../datasets/measurements_2019-12-31_2021-07-01.csv')

# Min and max weights
df = df[df['weight'] > 25]
df = df[df['weight'] < 300]

# Min and max days
df = df[df['day_n'] > -7]
df = df[df['day_n'] < 187]

# Only include rows with > 3 measurements
df = df.groupby('user_id').filter(lambda x: len(x) > 3)

# Scatter plot
plt.scatter(df['day_n'], df['weight'])

# Regression line
m, b = np.polyfit(df['day_n'], df['weight'], 1)
plt.plot(df['day_n'], m*df['day_n']+b,color='red')

plt.show()

Body:
sort then find the user id to keep:

df = pd.DataFrame({'user_id':[1,1,1,2,2,2],
                   'day_n': [0, 28, 68, 5, 28, 78],
                   'weight': [72, 70, 69, 76, 80, 78]})
df = df.sort_values(['user_id', 'day_n'])
keep_user = df.groupby('user_id')['weight'].first().between(70, 75)
df.loc[df['user_id'].isin(keep_user[keep_user].index)]

    user_id day_n   weight
0   1       0       72
1   1       28      70
2   1       68      69


问:
How to mock Django queryset which was got from related_name?
I want to unittest this function, which is service-function inside my Django app:

```<code>from datetime import date, timedelta
from account.models import Profile
from lesson.models import Lesson, Question
from repeat.models import RepetitionSession

class QuestionService:
    @staticmethod
    def get_next_question_by_rep_session(rep_session: RepetitionSession) -> Question:
        today_date = date.today()
        questions_filter = rep_session.questions.filter(next_repeat_at=today_date)
        sorted_questions_filter = questions_filter.order_by('edited_at')
        next_question = sorted_questions_filter.first()
        return next_question
</code>```

It was like this, but I've separated it for 3 lines:

```<code>next_question = rep_session.questions.filter(next_repeat_at=today_date).order_by('edited_at').first()
</code>```

Here is my unittest:

```<code>from datetime import date, timedelta
from random import randint
from unittest.mock import patch, MagicMock
from django.test import SimpleTestCase
from lesson.services import QuestionService

class QuestionServicesTest(SimpleTestCase):
    FILE_PATH = 'lesson.services.question_service'

    def test_get_next_question_by_rep_session(self):
        test_query = MagicMock()
        test_question = MagicMock()
        test_rep_session = MagicMock()

        test_rep_session.questions = test_query
        test_query.filter().return_value = test_query
        test_query.order_by().return_value = test_query
        test_query.first().return_value = test_question

        result = QuestionService.get_next_question_by_rep_session(test_rep_session)

        test_query.filter().assert_called_once_with(next_repeat_at=date.today())
</code>```

I'm getting this fail
https://i.stack.imgur.com/85Dzl.png

AssertionError: Expected 'mock' to be called once. Called 0 times.
Calls: [call.order_by('edited_at'), call.order_by().first()].

So if I want to test filter() I'm usually do this:

```<code>    @patch(f'{FILE_PATH}.Model_name.objects.filter')
    def test_example_func(self, patch_filter):

    test_attr = MagickMock()
    test_query = MagickMock()
    patch_filter.return_value = test_query

    result = example_func(test_attr)

    patch_filter.assert_called_once_with(test_attr)

</code>```

Please, help me find what I've missed.

答:
I figured out my mistake. Lets see changes:

```<code>    def test_get_next_question_by_rep_session(self):
        test_query = MagicMock()
        expected_question = MagicMock()
        fail_question = MagicMock()
        test_rep_session = MagicMock()

        test_rep_session.questions = test_query
        test_query.filter.return_value = test_query  # Mistake was here
        test_query.order_by.return_value = test_query  # Mistake was here
        test_query.first.return_value = expected_question  # Mistake was here

        result = QuestionService.get_next_question_by_rep_session(test_rep_session)

        test_query.filter.assert_called_once_with(next_repeat_at=date.today())  # Mistake was here
        test_query.order_by.assert_called_once_with('edited_at')
        test_query.first.assert_called_once()
        self.assertEqual(result, expected_question)
        self.assertNotEqual(result, fail_question)
</code>```

So when we mock objects it works like that:

```<code>x.return_value = 420
# When we will call x we will get 420
>>> x()
>>> 420

def x() -> y:
     ...

x().return_value = 665
# However when we will call result of the x() we will get 665
>>> y
>>> 665
</code>```

If I did mistake somewhere please let me know.

Body:
I want to unittest this function, which is service-function inside my Django app:

from datetime import date, timedelta
from account.models import Profile
from lesson.models import Lesson, Question
from repeat.models import RepetitionSession

class QuestionService:
    @staticmethod
    def get_next_question_by_rep_session(rep_session: RepetitionSession) -> Question:
        today_date = date.today()
        questions_filter = rep_session.questions.filter(next_repeat_at=today_date)
        sorted_questions_filter = questions_filter.order_by('edited_at')
        next_question = sorted_questions_filter.first()
        return next_question

It was like this, but I've separated it for 3 lines:

next_question = rep_session.questions.filter(next_repeat_at=today_date).order_by('edited_at').first()

Here is my unittest:

from datetime import date, timedelta
from random import randint
from unittest.mock import patch, MagicMock
from django.test import SimpleTestCase
from lesson.services import QuestionService

class QuestionServicesTest(SimpleTestCase):
    FILE_PATH = 'lesson.services.question_service'

    def test_get_next_question_by_rep_session(self):
        test_query = MagicMock()
        test_question = MagicMock()
        test_rep_session = MagicMock()

        test_rep_session.questions = test_query
        test_query.filter().return_value = test_query
        test_query.order_by().return_value = test_query
        test_query.first().return_value = test_question

        result = QuestionService.get_next_question_by_rep_session(test_rep_session)

        test_query.filter().assert_called_once_with(next_repeat_at=date.today())

I'm getting this fail
https://i.stack.imgur.com/85Dzl.png

AssertionError: Expected 'mock' to be called once. Called 0 times.
Calls: [call.order_by('edited_at'), call.order_by().first()].

So if I want to test filter() I'm usually do this:

    @patch(f'{FILE_PATH}.Model_name.objects.filter')
    def test_example_func(self, patch_filter):

    test_attr = MagickMock()
    test_query = MagickMock()
    patch_filter.return_value = test_query

    result = example_func(test_attr)

    patch_filter.assert_called_once_with(test_attr)

Please, help me find what I've missed.

Body:
I figured out my mistake. Lets see changes:

    def test_get_next_question_by_rep_session(self):
        test_query = MagicMock()
        expected_question = MagicMock()
        fail_question = MagicMock()
        test_rep_session = MagicMock()

        test_rep_session.questions = test_query
        test_query.filter.return_value = test_query  # Mistake was here
        test_query.order_by.return_value = test_query  # Mistake was here
        test_query.first.return_value = expected_question  # Mistake was here

        result = QuestionService.get_next_question_by_rep_session(test_rep_session)

        test_query.filter.assert_called_once_with(next_repeat_at=date.today())  # Mistake was here
        test_query.order_by.assert_called_once_with('edited_at')
        test_query.first.assert_called_once()
        self.assertEqual(result, expected_question)
        self.assertNotEqual(result, fail_question)

So when we mock objects it works like that:

x.return_value = 420
# When we will call x we will get 420
>>> x()
>>> 420

def x() -> y:
     ...

x().return_value = 665
# However when we will call result of the x() we will get 665
>>> y
>>> 665

If I did mistake somewhere please let me know.


问:
How to calculate if a date is within the last 12 months in Salesforce?
I am looking for a Salesforce boolean formula that calculates if a Salesforce date is within the last 12 months. For example, if CloseDate was Dec. 31, 2020, it will be false on Dec. 31, 2019.</p>

答:
Maybe this can help you, you just need to create the Formula field with a checkbox value and insert this formula

```<code>IF(DATEVALUE(CloseDate) > DATE(YEAR(TODAY())- 1, MONTH(TODAY()), DAY(TODAY())),TRUE,FALSE)
</code>```

I hope it helps!

Body:
Maybe this can help you, you just need to create the Formula field with a checkbox value and insert this formula

IF(DATEVALUE(CloseDate) > DATE(YEAR(TODAY())- 1, MONTH(TODAY()), DAY(TODAY())),TRUE,FALSE)

I hope it helps!


问:
How to merge two pandas columns into one column?
I merged two data frames together and I want to combine two pandas columns as follows:

df1:

```<code>A   B   C
1   3  NaN
2  Nan  2
3   5  NaN
4  NaN  1
</code>```

I want to get a result like the following:

df1:

```<code>A   BC
1   3
2   2
3   5
4   1
</code>```

答:
You could use bfill and ffill on your B,C columns, and concat the result with column A:

```<code>pd.concat([df['A'],df[['B','C']].bfill(axis=1).ffill(axis=1).iloc[:,-1].to_frame().rename({'C':'BC'},axis=1)],axis=1)
</code>```

prints:

```<code>   A   BC
0  1    3
1  2  2.0
2  3    5
3  4  1.0
</code>```

Body:
I merged two data frames together and I want to combine two pandas columns as follows:

df1:

A   B   C
1   3  NaN
2  Nan  2
3   5  NaN
4  NaN  1

I want to get a result like the following:

df1:

A   BC
1   3
2   2
3   5
4   1

Body:
You could use bfill and ffill on your B,C columns, and concat the result with column A:

pd.concat([df['A'],df[['B','C']].bfill(axis=1).ffill(axis=1).iloc[:,-1].to_frame().rename({'C':'BC'},axis=1)],axis=1)

prints:

   A   BC
0  1    3
1  2  2.0
2  3    5
3  4  1.0


问:
How to diagnose dotnet process consuming high CPU?
I have an ASP.NET Core process running in Kubernetes. Suddenly something went wrong and CPU usage jumped from 8% to 100% and settled at that level. Memory usage did not change so it looks like an infinite loop in a thread.

What instruments can I use to diagnose what is happening in the process?

What should I do to be able to diagnose such problems in the future?

答:
.net core support some command that let us diagnose CPU high or Memory problem.

first, install tools

```<code>dotnet tool install --global dotnet-trace
dotnet tool install --global dotnet-counters
</code>```

then we can use dotnet-trace ps to get the process id that we want to trace.

then use dotnet-counters command we can see the process using resource situations.

```<code>dotnet-counters monitor -p 22884 --refresh-interval 1
</code>```

-p: which process id you want to trace

--refresh-interval: How often to refresh the monitor screen from commandline window (unit is second)

if you want to only focus on  cpu-usage you can try to add this parameter --counters System.Runtime[cpu-usage]

when we use the above command we will get a lot of Runtime information that can help us to diagnose from your process.

```<code>[System.Runtime]
% Time in GC since last GC (%)
Allocation Rate (B / 1 sec)
CPU Usage (%)
Exception Count (Count / 1 sec)
GC Committed Bytes (MB)
GC Fragmentation (%)
GC Heap Size (MB)
Gen 0 GC Count (Count / 1 sec)
Gen 0 Size (B)
Gen 1 GC Count (Count / 1 sec)
Gen 1 Size (B)
Gen 2 GC Count (Count / 1 sec)
Gen 2 Size (B)
IL Bytes Jitted (B)
LOH Size (B)
Monitor Lock Contention Count (Count / 1 sec)
Number of Active Timers
Number of Assemblies Loaded
Number of Methods Jitted
POH (Pinned Object Heap) Size (B)
ThreadPool Completed Work Item Count (Count / 1 sec)
ThreadPool Queue Length
ThreadPool Thread Count
Time spent in JIT (ms / 1 sec)
Working Set (MB)
</code>```

more detail you can see Debug high CPU usage in .NET Core & dotnet-counters

Body:
.net core support some command that let us diagnose CPU high or Memory problem.

first, install tools

dotnet tool install --global dotnet-trace
dotnet tool install --global dotnet-counters

then we can use dotnet-trace ps to get the process id that we want to trace.

then use dotnet-counters command we can see the process using resource situations.

dotnet-counters monitor -p 22884 --refresh-interval 1

-p: which process id you want to trace

--refresh-interval: How often to refresh the monitor screen from commandline window (unit is second)

if you want to only focus on  cpu-usage you can try to add this parameter --counters System.Runtime[cpu-usage]

when we use the above command we will get a lot of Runtime information that can help us to diagnose from your process.

[System.Runtime]
% Time in GC since last GC (%)
Allocation Rate (B / 1 sec)
CPU Usage (%)
Exception Count (Count / 1 sec)
GC Committed Bytes (MB)
GC Fragmentation (%)
GC Heap Size (MB)
Gen 0 GC Count (Count / 1 sec)
Gen 0 Size (B)
Gen 1 GC Count (Count / 1 sec)
Gen 1 Size (B)
Gen 2 GC Count (Count / 1 sec)
Gen 2 Size (B)
IL Bytes Jitted (B)
LOH Size (B)
Monitor Lock Contention Count (Count / 1 sec)
Number of Active Timers
Number of Assemblies Loaded
Number of Methods Jitted
POH (Pinned Object Heap) Size (B)
ThreadPool Completed Work Item Count (Count / 1 sec)
ThreadPool Queue Length
ThreadPool Thread Count
Time spent in JIT (ms / 1 sec)
Working Set (MB)

more detail you can see Debug high CPU usage in .NET Core & dotnet-counters


问:
Custom MSP for Hyperledger Fabric
I'm trying to use DIDs/VCs from hyperledger Indy with Hyperledger Fabric. Simply I want to replace Fabric's certificate based identity/MSP with DIDs/VCs. However, as far as I understand this is not direct. The existing code based have lots of dependencies on Fabric-CA. Could someone help me to figure out potential starting points to do this customisation?</p>

答:
you cant try to use this modified peen-node:

https://github.com/trustbloc/fabric-mod

https://github.com/trustbloc/trustbloc-did-method/blob/main/docs/spec/trustbloc-did-method.md

or read this research:

https://arxiv.org/pdf/2104.03277.pdf

or check other did:methods that support HLF:

https://www.w3.org/TR/did-spec-registries/

or look to this project:

https://github.com/BLOCKOTUS/blockotus-organism

Title: Custom MSP for Hyperledger Fabric


问:
Visualizing a project tracker in R
Does anyone have any ideas on how to visualize something like this using R?

Basically I want to make a plot to track the percentage completeness of different jobs in a few projects. The percentage completeness should be color coded (in the example, dark blue means the job is 100% complete, white means 0% complete etc.)
Here's some sample code to make the dataframe:

```<code>project <- c('Project 1', 'Project 2', 'Project 3', 'Project 4')

job1 <- c(100, 100, NA, 100)

job2 <- c(100, 100, NA, 100)

job3 <- c(100, NA, NA, NA)

job4 <- c(NA, 100, 100, 100)

job5 <- c(50, 100, 100, 100)

job6 <- c(0, 40, 100, 100)

df <- data.frame(project, job1, job2, job3, job4, job5, job6)
</code>```

I've tried a gantt chart but couldn't get that to work as there is no time data. I've tried a bar chart but that didn't work as some of the projects have NA or 0 values followed by 100/50 etc. so the jobs don't line up. I also tried a heatmap but that doesn't really work either, as there needs to be a visible distinction between the NA values and the 0 values i.e. NA means that a job isn't applicable to that project, whereas 0 means the job hasn't started yet.

Any suggestions would be really appreciated!

答:
First you have to change the data to a long format; tidyr::pivot_longer() does that. ggplot2::geom_tile() can then be used to create a heatmap plot.

library(tidyr)
library(ggplot2)
df |>
  pivot_longer(-project) |>
  ggplot(aes(name, project, fill = value)) +
  geom_tile()
```
<p><img src="https://i.imgur.com/NqCUTEd.png" alt="" /></p>
<p>You can tune it some more, to reach a result that more closely resembles your example:</p>
<pre class="lang-r prettyprint-override"><code>library(tidyr)
library(ggplot2)
library(forcats)
library(dplyr)

df |>
  pivot_longer(-project) |>
  mutate(project = fct_rev(factor(project))) |>
  ggplot(aes(name, project, fill = value)) +
  geom_tile(color = "grey", size = 3) +
  scale_x_discrete(position = "top") +
  labs(x ="", y = "")
</code>```

Title: Visualizing a project tracker in R

Body:
Does anyone have any ideas on how to visualize something like this using R?

Basically I want to make a plot to track the percentage completeness of different jobs in a few projects. The percentage completeness should be color coded (in the example, dark blue means the job is 100% complete, white means 0% complete etc.)
Here's some sample code to make the dataframe:

project <- c('Project 1', 'Project 2', 'Project 3', 'Project 4')

job1 <- c(100, 100, NA, 100)

job2 <- c(100, 100, NA, 100)

job3 <- c(100, NA, NA, NA)

job4 <- c(NA, 100, 100, 100)

job5 <- c(50, 100, 100, 100)

job6 <- c(0, 40, 100, 100)

df <- data.frame(project, job1, job2, job3, job4, job5, job6)

I've tried a gantt chart but couldn't get that to work as there is no time data. I've tried a bar chart but that didn't work as some of the projects have NA or 0 values followed by 100/50 etc. so the jobs don't line up. I also tried a heatmap but that doesn't really work either, as there needs to be a visible distinction between the NA values and the 0 values i.e. NA means that a job isn't applicable to that project, whereas 0 means the job hasn't started yet.

Any suggestions would be really appreciated!

Body:
First you have to change the data to a long format; tidyr::pivot_longer() does that. ggplot2::geom_tile() can then be used to create a heatmap plot.

library(tidyr)
library(ggplot2)
df |>
  pivot_longer(-project) |>
  ggplot(aes(name, project, fill = value)) +
  geom_tile()

You can tune it some more, to reach a result that more closely resembles your example:

library(tidyr)
library(ggplot2)
library(forcats)
library(dplyr)

df |>
  pivot_longer(-project) |>
  mutate(project = fct_rev(factor(project))) |>
  ggplot(aes(name, project, fill = value)) +
  geom_tile(color = "grey", size = 3) +
  scale_x_discrete(position = "top") +
  labs(x ="", y = "")


问:
How to make replication faster for mysql table with 8 million records
I take my Live server backup using mysqldump command via CRON job in my Ubuntu Server via Bash Shell Script and the same script uploads the backup to my backup server also. Earlier this was working fine but now I am facing slowness issue (it takes 1 hour to backup and upload on backup server) as one of the database Table size has grown to 5GB and consists of 10 Million Records. I saw on a thread that we can fasten the SQL insertion via bulk/group execution of SQL -  How can mysql insert millions records faster?

But in my case I am unsure how can I create a Shell Script to perform the same.

The requirement is I want to export all my SQL Database tables in groups of maximum 10k so that execution can be faster while it is getting imported on the server.

I have written this code on my server bash script:

```<code>#!/bin/bash
cd /tmp
file=$(date +%F-%T).sql
mysqldump \
  --host ${MYSQL_HOST} \
  --port ${MYSQL_PORT} \
  -u ${MYSQL_USER} \
  --password="${MYSQL_PASS}" \
  ${MYSQL_DB} > ${file}
if [ "${?}" -eq 0 ]; then
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "show databases"
  mysql -umyuser -pmypassword -h 198.168.1.3 -D backup_db -e "drop database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "create database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3 backup_db < ${file}
  gzip ${file}
  aws s3 cp ${file}.gz s3://${S3_BUCKET}/live_db/
  rm ${file}.gz
else
  echo "Error backing up mysql"
  exit 255
fi
</code>```

The backup server and live server share the same AWS hardware configuration: 16GB RAM, 4 CPU, 100GB SSD.

These are the screenshots and data:

Screenshot and Queries for Debugging on the Live Server:
Information Schema Tables:

```<code>https://i.imgur.com/RnjQwbP.png
</code>```

SHOW GLOBAL STATUS:

```<code>https://pastebin.com/raw/MuJYwnsm
</code>```

SHOW GLOBAL VARIABLES:

```<code>https://pastebin.com/raw/wdvn97XP
</code>```

Screenshot and Queries for Debugging on the Backup Server:

```<code>https://i.imgur.com/rB7qcYU.png
https://pastebin.com/raw/K7vHXqWi
https://pastebin.com/raw/PR2gWpqe
</code>```

Server workload is almost negligible. There is no load all the times, I have also monitored via AWS Monitoring Panel, and that's the only reason to take more than required resource server so that it never gets exhausted. I have taken 16GB RAM and 4 CPU which are more than more than sufficient. AWS Monitoring Panel showed Max usage 6% rarely and maximum times it is around 1%.

答:
Rate Per Second = RPS

Suggestions to consider for your 'Backup' AWS instance Parameters Group

```<code>innodb_buffer_pool_size=10G  # from 128M to reduce innodb_data_reads RPS of 16
innodb_change_buffer_max_size=50  # from 25 percent to speed up INSERT completion
innodb_buffer_pool_instances=3  # from 1 to reduce mutex contention
innodb_write_io_threads=16  # from 4 for your intense data INSERT operations
innodb_buffer_pool_dump_pct=90  # from 25 percent to reduce WARM UP delays
innodb_fast_shutdown=0  #  from 1 to help avoid RECOVERY on instance START
</code>```

You should find these changes reduce your refresh DATA time required on your BACKUP instance.  Your LIVE instance has different operating characteristics but should have all these suggestions applied, as well as others.  Please view profile for contact info and get in touch for additional assistance.

Your mention of REPLICATION should likely be ignored since you can not have SERVER_ID of 1 on both the MASTER and SLAVE with replication to survive.  Your LIVE server can not be MASTER because LOG_BIN is OFF for the first reason.

LIVE observations,
com_begin count was 30, com_commit was 0 after 3 + days of uptime.
Usually we find commit to be the same as com_begin.  Did someone forget to COMMIT the data?

com_savepoint reported 430 operations. com_rollback_to_savepoint reported 430 operations. We do not normally see a rollback for every savepoint in 3 dqys.

com_stmt_prepare reported 473 operations.
com_stmt_execute reported 1211 operations.
com_stmt_close reported 0 operations.  Forgetting to CLOSE prepared statements
when done leaves resources in use that could have been released.

handler_rollback counter 961 in 3 days.  Seems unusual for 3 days of uptime.

slow_queries counted 87338 in 3 days exceeding 5 seconds to completion.
log_slow_verbosity=query_plan,explain  would help your team identify the cause of slow.   Your slow query logs is already ON.

Kerry, The VERY BEST to you and your team.

Body:
I take my Live server backup using mysqldump command via CRON job in my Ubuntu Server via Bash Shell Script and the same script uploads the backup to my backup server also. Earlier this was working fine but now I am facing slowness issue (it takes 1 hour to backup and upload on backup server) as one of the database Table size has grown to 5GB and consists of 10 Million Records. I saw on a thread that we can fasten the SQL insertion via bulk/group execution of SQL -  How can mysql insert millions records faster?

But in my case I am unsure how can I create a Shell Script to perform the same.

The requirement is I want to export all my SQL Database tables in groups of maximum 10k so that execution can be faster while it is getting imported on the server.

I have written this code on my server bash script:

#!/bin/bash
cd /tmp
file=$(date +%F-%T).sql
mysqldump \
  --host ${MYSQL_HOST} \
  --port ${MYSQL_PORT} \
  -u ${MYSQL_USER} \
  --password="${MYSQL_PASS}" \
  ${MYSQL_DB} > ${file}
if [ "${?}" -eq 0 ]; then
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "show databases"
  mysql -umyuser -pmypassword -h 198.168.1.3 -D backup_db -e "drop database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3  -e "create database backup_db"
  mysql -umyuser -pmypassword -h 198.168.1.3 backup_db < ${file}
  gzip ${file}
  aws s3 cp ${file}.gz s3://${S3_BUCKET}/live_db/
  rm ${file}.gz
else
  echo "Error backing up mysql"
  exit 255
fi

The backup server and live server share the same AWS hardware configuration: 16GB RAM, 4 CPU, 100GB SSD.

These are the screenshots and data:

Screenshot and Queries for Debugging on the Live Server:
Information Schema Tables:

https://i.imgur.com/RnjQwbP.png

SHOW GLOBAL STATUS:

https://pastebin.com/raw/MuJYwnsm

SHOW GLOBAL VARIABLES:

https://pastebin.com/raw/wdvn97XP

Screenshot and Queries for Debugging on the Backup Server:

https://i.imgur.com/rB7qcYU.png
https://pastebin.com/raw/K7vHXqWi
https://pastebin.com/raw/PR2gWpqe

Server workload is almost negligible. There is no load all the times, I have also monitored via AWS Monitoring Panel, and that's the only reason to take more than required resource server so that it never gets exhausted. I have taken 16GB RAM and 4 CPU which are more than more than sufficient. AWS Monitoring Panel showed Max usage 6% rarely and maximum times it is around 1%.

Body:
Rate Per Second = RPS

Suggestions to consider for your 'Backup' AWS instance Parameters Group

innodb_buffer_pool_size=10G  # from 128M to reduce innodb_data_reads RPS of 16
innodb_change_buffer_max_size=50  # from 25 percent to speed up INSERT completion
innodb_buffer_pool_instances=3  # from 1 to reduce mutex contention
innodb_write_io_threads=16  # from 4 for your intense data INSERT operations
innodb_buffer_pool_dump_pct=90  # from 25 percent to reduce WARM UP delays
innodb_fast_shutdown=0  #  from 1 to help avoid RECOVERY on instance START

You should find these changes reduce your refresh DATA time required on your BACKUP instance.  Your LIVE instance has different operating characteristics but should have all these suggestions applied, as well as others.  Please view profile for contact info and get in touch for additional assistance.

Your mention of REPLICATION should likely be ignored since you can not have SERVER_ID of 1 on both the MASTER and SLAVE with replication to survive.  Your LIVE server can not be MASTER because LOG_BIN is OFF for the first reason.

LIVE observations,
com_begin count was 30, com_commit was 0 after 3 + days of uptime.
Usually we find commit to be the same as com_begin.  Did someone forget to COMMIT the data?

com_savepoint reported 430 operations. com_rollback_to_savepoint reported 430 operations. We do not normally see a rollback for every savepoint in 3 dqys.

com_stmt_prepare reported 473 operations.
com_stmt_execute reported 1211 operations.
com_stmt_close reported 0 operations.  Forgetting to CLOSE prepared statements
when done leaves resources in use that could have been released.

handler_rollback counter 961 in 3 days.  Seems unusual for 3 days of uptime.

slow_queries counted 87338 in 3 days exceeding 5 seconds to completion.
log_slow_verbosity=query_plan,explain  would help your team identify the cause of slow.   Your slow query logs is already ON.

Kerry, The VERY BEST to you and your team.


问:
Dynamically position text within, right to or left to an element
I am completely new to CSS. I want to display a simple Gantt chart and I am looking for a way to position the text indicating the number of month within, left to or right to the colored gantt bar.

Right now all the text is within in the bar and as the bar gets narrower it increases in height as the text needs to be wrapped.

In contrast to what the screenshot currently shows, I would want to have the text for Step 1 to be displayed to the right of the bar, the one for step 5 to be displayed to the left. The rest of the text should remain the same as long as the next is not too long to be wrapped over multiple lines, in that case the next should be displayed on that side right next to the bar where there is more space.

2months

 ```

答:
The easiest way is probably to just use the padding and margin properties to position your colored div blocks, then displace the text either to the left or right like so:

2 months

7 months

```

However, this will cause issues if your screen doesn't have a fixed size... you can see this by running the code snippet in full screen. If that isn't the case, hard coding the position like this will work, albeit not necessarily the most elegant solution.

Also, your initial code had a typo in
 instead of
.

Body:
The easiest way is probably to just use the padding and margin properties to position your colored div blocks, then displace the text either to the left or right like so:

<div style="background-color:green;
            padding:15px;
            margin-top:10px;
            width:10%;
            border-radius: 10px;
            color:black;
            font-weight:bold">

    <div style = "padding: 0px 90px;
                  white-space: nowrap;"
    >2 months</div>
</div>

<br />

<div style = "position: absolute;margin-right: 225px;
              white-space: nowrap;
              color:black;
              font-weight:bold"
>7 months</div>

<div style="background-color:red;
            padding:22px;
            margin-top:-10px;
            margin-left:75px;
            width:10%;
            border-radius: 10px;
            color:black;
            font-weight:bold;"
> </div>

However, this will cause issues if your screen doesn't have a fixed size... you can see this by running the code snippet in full screen. If that isn't the case, hard coding the position like this will work, albeit not necessarily the most elegant solution.

Also, your initial code had a typo in <div/> instead of </div>.


问:
ABAddressBookCopyArrayOfAllPeopleInSource
I built an iphone app that syncs with the iphone address book.

with some users, the contact list has "linked contacts" or unified or merged contacts, they appear at the bottom. so some users have one person as the main contact and more linked contacts for the same/or other contact in the exchange server or mobileMe or whatever.

I tried running ABAddressBookCopyArrayOfAllPeopleInSource with kABSourceTypeLocal but it still returned duplicate contacts when encountering contacts with linked contacts

how can I make sure I sync only the main identify without duplicates ?

答: You can use a class with the singleton pattern.</p>


问:
ModuleNotFoundError on own folder
I have this folder structure:

```<code>main.py
utils
--forms.py
</code>```

and am now trying in main.py to import something from forms.py with this:

from utils.forms import search_form

but I am getting this Exception

```<code>Traceback (most recent call last):
  File "/home/kofi/Desktop/projects/groundtruth_auswertung/main.py", line 4, in <module>
    from utils.forms import search_form
ModuleNotFoundError: No module named 'utils.forms'; 'utils' is not a package
</code>```

答:
for me its working and on linux too.

 [~/Alexzander__/programming/python3/learning/modulenotfounderror]
❱  tree
 .
├──  main.py
└──  utils
   └──  forms.py

 [~/Alexzander__/programming/python3/learning/modulenotfounderror]
❱  ca main.py

from utils.forms import search_form

print("success")%

 [~/Alexzander__/programming/python3/learning/modulenotfounderror]
❱  python main.py
success
```

Title: ModuleNotFoundError on own folder

Body:
I have this folder structure:

main.py
utils
--forms.py

and am now trying in main.py to import something from forms.py with this:

from utils.forms import search_form

but I am getting this Exception

Traceback (most recent call last):
  File "/home/kofi/Desktop/projects/groundtruth_auswertung/main.py", line 4, in <module>
    from utils.forms import search_form
ModuleNotFoundError: No module named 'utils.forms'; 'utils' is not a package


问:
AttributeError: type object 'Factory' has no attribute '_get_provider_class'
when launching paytests it gives an error AttributeError: type object 'Factory' has no attribute '_get_provider_class'  I'm learning to program and don't know what to do</p>

答:
It seems that the problem is with Faker library.

I have managed to solve it with these commands (with venv activated):

```<code>$ pip uninstall Faker
$ pip install Faker==6.0.0
</code>```

Maybe you want to try different versions instead of 6.0.0

Body:
It seems that the problem is with Faker library.

I have managed to solve it with these commands (with venv activated):

$ pip uninstall Faker
$ pip install Faker==6.0.0

Maybe you want to try different versions instead of 6.0.0


问:
how Inner join work on two foreign key from single table
I am working on Bus route management system , I made two table first one is Cities and second one is route have following queries

```<code>CREATE TABLE Cities
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
)
CREATE TABLE route
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
      from NUMBER not null,
      to NUMBER NOT NULL,
      CONSTRAINT FROM_id_FK FOREIGN KEY(from) REFERENCES Cities(ID),
      CONSTRAINT TO_id_FK FOREIGN KEY(to) REFERENCES Cities(ID),
)
</code>```

i am joining the table through inner join

```<code>select CITIES.Name
from CITIES
inner join ROUTES on CITIES.ID=ROUTES.ID
</code>```

but it show single column as

```<code>   Name
-----------
</code>```

but i want result as

```<code>    from  |     to
------------------------
</code>```

what is possible way to do this using inner join

答:
I suspect you need something like the following:</p>
```<code>select r.Name, cs.Name SourceCity, cd.Name DestinationCity
from routes r
join cities cs on cs.id = r.from
join cities cd on cd.id = r.to
</code>```

Body:
I am working on Bus route management system , I made two table first one is Cities and second one is route have following queries

CREATE TABLE Cities
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
)
CREATE TABLE route
    (
      ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
      Name Varchar(30) not null,
      from NUMBER not null,
      to NUMBER NOT NULL,
      CONSTRAINT FROM_id_FK FOREIGN KEY(from) REFERENCES Cities(ID),
      CONSTRAINT TO_id_FK FOREIGN KEY(to) REFERENCES Cities(ID),
)

i am joining the table through inner join

select CITIES.Name
from CITIES
inner join ROUTES on CITIES.ID=ROUTES.ID

but it show single column as

   Name
-----------

but i want result as

    from  |     to
------------------------

what is possible way to do this using inner join

Body:
I suspect you need something like the following:

select r.Name, cs.Name SourceCity, cd.Name DestinationCity
from routes r
join cities cs on cs.id = r.from
join cities cd on cd.id = r.to


问:
Filter rows of two datasets based on the content of a column in common
I have two large datasets with one column in common; I have to filter these tow datasets, row by row, based on the content of the cells in the column in common: if the value of a cell in the column in common in dataset 1 is also present in a cell of the column in common in dataset 2, i have to keep the row with this value in both datasets; if a value in the column in common is present only in dataset 1 or in dataset 2 i have to delete the row with this value.
exlample datasets</p>

答:
Based on this limited explanation of the problem try importing the two datasets into Pandas dataframes and then merging on the common column.

please see the examples in the pandas documentation. carefully selecting the how= argument of the merge will accomplish your filtering for you. based on your description, how='inner', on='common column' might be your solution.

see documentation here:
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html


问:
Fetch API return json object or response status
I'm a bit stuck with the fetch API.
This is a simple Login function

```<code>export default class LoginService {
    async loginUser(u, p) {
        return fetch(API_URL + '/users/authenticate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'username': u, 'password': p })
        })
            .then(response => response.json())
            .catch(e => console.log(e))
        }
}
</code>```

When user is not found the in the backend return 400 bad request. How can I return the json object or the response status? Or maybe this practice is wrong?

Thank you!

答:
How can I return the json object or the response status?

The ok response property gives you the high-level "worked/didn't work" for the HTTP call (fetch only rejects its promise on network errors, not HTTP errors — a footgun in the api you constantly see people falling afoul of).

I wouldn't return the response status, I'd include it in an error thrown by the async function. I typically do that like this:

```<code>async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`};
        }
        return response.json();
    }); // Note: No `catch` here!
}
</code>```

But if you really want to return it:

```<code>async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            return {failed: true, status: response.status};
        }
        return response.json();
    })
    .catch(e => console.log(e));
}
</code>```

Turning rejections into fulfilments that way is generally not best practice, though.

Body:
I'm a bit stuck with the fetch API.
This is a simple Login function

export default class LoginService {
    async loginUser(u, p) {
        return fetch(API_URL + '/users/authenticate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'username': u, 'password': p })
        })
            .then(response => response.json())
            .catch(e => console.log(e))
        }
}

When user is not found the in the backend return 400 bad request. How can I return the json object or the response status? Or maybe this practice is wrong?

Thank you!

Body:
How can I return the json object or the response status?

The ok response property gives you the high-level "worked/didn't work" for the HTTP call (fetch only rejects its promise on network errors, not HTTP errors — a footgun in the api you constantly see people falling afoul of).

I wouldn't return the response status, I'd include it in an error thrown by the async function. I typically do that like this:

async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`};
        }
        return response.json();
    }); // Note: No `catch` here!
}

But if you really want to return it:

async loginUser(u, p) {
    return fetch(API_URL + '/users/authenticate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 'username': u, 'password': p })
    })
    .then(response => {
        if (!response.ok) {
            return {failed: true, status: response.status};
        }
        return response.json();
    })
    .catch(e => console.log(e));
}

Turning rejections into fulfilments that way is generally not best practice, though.


问:
Declare a variable to maximize it in Minizinc
I have a problem which is determine the maximum length of movements that a set of knights could make inside a board, which the conditions:

There are 4 knights and they move in the order: A -> B -> C -> D. Their first positions are the corners.

Some cells cannot be visited, and the rest, only can be visited k times. The first positions don't count.

The result should to be the set of movements that the knight could do in the board.

Here is my code, but I don't know how to modify the program to maximize the value of the path (t):

```<code>include "globals.mzn";

int: n=4; %nxnxt board
int: k=1; %k times visited cell
var 0..100: t; %Lenth of the path

%Initial board
array[1..t, 1..n, 1..n] of var 0..k:b;

% Decision variables (*CHANGED*)
array[1..t,1..4] of var 1..n: r;% The sequence of moves in the path
array[1..t,1..4] of var 1..n: c;% (row and column of each move).
%%% Always the same order A -> B -> C -> D knights

%Constraints

   % Forcing the first moves.

constraint r[1,1] = 1;%A
constraint c[1,1] = 1;
constraint r[1,2] = 1;%B
constraint c[1,2] = n;
constraint r[1,3] = n;%C
constraint c[1,3] = 1;
constraint r[1,4] = n;%D
constraint c[1,4] = n;

constraint b[1,1,2] = k;
constraint b[1,1,3] = k;
constraint b[1,2,1] = k;
constraint b[1,3,1] = k;
constraint b[1,2,4] = k;
constraint b[1,3,4] = k;
constraint b[1,4,2] = k;
constraint b[1,4,3] = k;

% LIMIT ON VISITS (*ADDED*)
constraint
     forall (i in 1..t, j in 1..n, l in 1..n) (
           b[i,j,l] <= k
     );

% SUCCESSOR (STEP OF THE KNIGHT)

constraint
     forall (i in 1..t-1, j in 1..4) (
           c[i,j] != c[i+1,j] /\%Each movement has to be diferent than the previous one
           r[i,j] != r[i+1,j] /\
           abs(c[i,j] - c[i+1,j]) + abs(r[i,j] - r[i+1,j]) = 3
     );

% NEVER TWO QUEENS ON THE SAME CELL

constraint forall(i in 1..t, j in 1..3, p in 2..4 where p > j )(
        r[i,j] != r[i,p] \/
        c[i,j] != c[i,p]);

constraint forall(i in 2..t, j in 1..n, l in 1..n)(
      if b[i-1,j,l] = k then
          b[i, j, l] = k
      endif
);

% APPLY THE MOVE IN THE MATRIX
constraint
     forall (i in 2..t, j in 1..4) (
         exists(w in {-2, 2}, q in {-1, 1}) ( % Set up the possible moviments.
         if  1 <= r[i-1,j]+w /\ r[i-1,j]+w <= n /\
             1 <= c[i-1,j]+q /\ c[i-1,j]+q <= n /\
             b[i-1, r[i-1, j]+w, c[i-1, j]+q] < k then
              (r[i,j] = r[i-1, j] + w /\
               c[i,j] = c[i-1, j] + q)
         endif
              \/
         if  1 <= r[i-1,j]+q /\ r[i-1,j]+q <= n /\
             1 <= c[i-1,j]+w /\ c[i-1,j]+w <= n /\
             b[i-1, r[i-1,j]+q, c[i-1,j]+w] < k then
              (r[i,j] = r[i-1, j] + q /\
               c[i,j] = c[i-1, j] + w)
        endif) /\
        b[i, r[i,j], c[i,j]] = b[i-1, r[i,j], c[i,j]] + 1
);
solve maximize t;

output["r"]++[
  if j = 1 then "\n" else "" endif ++
    show(r[i,j]) ++ " "
  | i in 1..t, j in 1..n
]++["\n\nc"]++
[
  if j = 1 then "\n" else "" endif ++
    show(c[i,j]) ++ " "
  | i in 1..t, j in 1..n
]++["\n"] ++
[ if l = 1 then "\n" else "" endif ++
show(b[i,j,l]) ++ " "
|i in 1..t, j in 1..n, l in 1..n];

include "globals.mzn";

int: n=4; %nxnxt board
int: k=1; %k times visited cell
var 0..100: t; %Lenth of the path
l in 1..n];
</code>```

答: A general approach in planning style problems is to first set an upper bound on the number of possible steps. Then the model is modified so that there is some sentinel no-move move that can be applied, but only at the end of the moves. Finally, you can count he number of moves used by counting the number of no-moves and subtracting that from the fixed upper bound.</p>

Body:
I have a problem which is determine the maximum length of movements that a set of knights could make inside a board, which the conditions:

There are 4 knights and they move in the order: A -> B -> C -> D. Their first positions are the corners.

Some cells cannot be visited, and the rest, only can be visited k times. The first positions don't count.

The result should to be the set of movements that the knight could do in the board.

Here is my code, but I don't know how to modify the program to maximize the value of the path (t):

include "globals.mzn";

int: n=4; %nxnxt board
int: k=1; %k times visited cell
var 0..100: t; %Lenth of the path

%Initial board
array[1..t, 1..n, 1..n] of var 0..k:b;

% Decision variables (*CHANGED*)
array[1..t,1..4] of var 1..n: r;% The sequence of moves in the path
array[1..t,1..4] of var 1..n: c;% (row and column of each move).
%%% Always the same order A -> B -> C -> D knights

%Constraints

   % Forcing the first moves.

constraint r[1,1] = 1;%A
constraint c[1,1] = 1;
constraint r[1,2] = 1;%B
constraint c[1,2] = n;
constraint r[1,3] = n;%C
constraint c[1,3] = 1;
constraint r[1,4] = n;%D
constraint c[1,4] = n;

constraint b[1,1,2] = k;
constraint b[1,1,3] = k;
constraint b[1,2,1] = k;
constraint b[1,3,1] = k;
constraint b[1,2,4] = k;
constraint b[1,3,4] = k;
constraint b[1,4,2] = k;
constraint b[1,4,3] = k;

% LIMIT ON VISITS (*ADDED*)
constraint
     forall (i in 1..t, j in 1..n, l in 1..n) (
           b[i,j,l] <= k
     );

% SUCCESSOR (STEP OF THE KNIGHT)

constraint
     forall (i in 1..t-1, j in 1..4) (
           c[i,j] != c[i+1,j] /\%Each movement has to be diferent than the previous one
           r[i,j] != r[i+1,j] /\
           abs(c[i,j] - c[i+1,j]) + abs(r[i,j] - r[i+1,j]) = 3
     );

% NEVER TWO QUEENS ON THE SAME CELL

constraint forall(i in 1..t, j in 1..3, p in 2..4 where p > j )(
        r[i,j] != r[i,p] \/
        c[i,j] != c[i,p]);

constraint forall(i in 2..t, j in 1..n, l in 1..n)(
      if b[i-1,j,l] = k then
          b[i, j, l] = k
      endif
);

% APPLY THE MOVE IN THE MATRIX
constraint
     forall (i in 2..t, j in 1..4) (
         exists(w in {-2, 2}, q in {-1, 1}) ( % Set up the possible moviments.
         if  1 <= r[i-1,j]+w /\ r[i-1,j]+w <= n /\
             1 <= c[i-1,j]+q /\ c[i-1,j]+q <= n /\
             b[i-1, r[i-1, j]+w, c[i-1, j]+q] < k then
              (r[i,j] = r[i-1, j] + w /\
               c[i,j] = c[i-1, j] + q)
         endif
              \/
         if  1 <= r[i-1,j]+q /\ r[i-1,j]+q <= n /\
             1 <= c[i-1,j]+w /\ c[i-1,j]+w <= n /\
             b[i-1, r[i-1,j]+q, c[i-1,j]+w] < k then
              (r[i,j] = r[i-1, j] + q /\
               c[i,j] = c[i-1, j] + w)
        endif) /\
        b[i, r[i,j], c[i,j]] = b[i-1, r[i,j], c[i,j]] + 1
);
solve maximize t;

output["r"]++[
  if j = 1 then "\n" else "" endif ++
    show(r[i,j]) ++ " "
  | i in 1..t, j in 1..n
]++["\n\nc"]++
[
  if j = 1 then "\n" else "" endif ++
    show(c[i,j]) ++ " "
  | i in 1..t, j in 1..n
]++["\n"] ++
[ if l = 1 then "\n" else "" endif ++
show(b[i,j,l]) ++ " "
|i in 1..t, j in 1..n, l in 1..n];

include "globals.mzn";

int: n=4; %nxnxt board
int: k=1; %k times visited cell
var 0..100: t; %Lenth of the path
l in 1..n];


问:
helm helpers file can't evaluate field type interface array/string
I am rather new to helm, and I am trying to create a chart, but running into values not transforming from the values.yaml file into my generated chart.

here are my values.yaml

```<code>apiVersion: security.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
  namespace: ns-01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
        - user1
        - user2
</code>```

then with my helm template:

```<code>apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences: |-
        {{- range .Values.spec.jwtRules.audiences }}
          - {{ . | title | quote }}
      {{ end }}
---
</code>```

I also have a helpers file.

_helpers.tpl

```<code>{{/* vim: set filetype=mustache: */}}
{{- define "jwtRules.audiences" -}}
{{- range $.Values.spec.jwtRules.audiences }}
      audiences:
        - {{ . | quote }}
{{- end }}
{{- end }}
</code>```

the error its producing: at <.Values.spec.jwtRules.audiences>: can't evaluate field audiences in type interface {}

答:
Thank you @andrew. I also came to a simple solution but would like feedback on it.

I removed the helpers file then modified my helm chart with the following.

values.yaml (is kept the same as above)

helmchart:

```<code>apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      {{- with index .Values.spec.jwtRules 0 }}
      audiences:
         {{- range $a := .audiences }}
         - {{ $a -}}
      {{ end }}
      {{ end }}
---
</code>```

This produces the following:

```<code>apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
         - user1
         - user2
</code>```

Should I continue to use a helpers file?

Thanks again for all the help.

Body:
I am rather new to helm, and I am trying to create a chart, but running into values not transforming from the values.yaml file into my generated chart.

here are my values.yaml

apiVersion: security.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
  namespace: ns-01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
        - user1
        - user2

then with my helm template:

apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences: |-
        {{- range .Values.spec.jwtRules.audiences }}
          - {{ . | title | quote }}
      {{ end }}
---

I also have a helpers file.

_helpers.tpl

{{/* vim: set filetype=mustache: */}}
{{- define "jwtRules.audiences" -}}
{{- range $.Values.spec.jwtRules.audiences }}
      audiences:
        - {{ . | quote }}
{{- end }}
{{- end }}

the error its producing: at <.Values.spec.jwtRules.audiences>: can't evaluate field audiences in type interface {}

Body:
Thank you @andrew. I also came to a simple solution but would like feedback on it.

I removed the helpers file then modified my helm chart with the following.

values.yaml (is kept the same as above)

helmchart:

apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: {{ .Values.spec.selector.matchLabels.app }}
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      {{- with index .Values.spec.jwtRules 0 }}
      audiences:
         {{- range $a := .audiences }}
         - {{ $a -}}
      {{ end }}
      {{ end }}
---

This produces the following:

apiVersion: networking.istio.io/v1alpha2
kind: RequestAuthentication
metadata:
  name: name01
spec:
  selector:
    matchLabels:
      app: app-label
  jwtRules:
    - issuer: foo
      jwksUri: bar
      forwardOriginalToken: true
      audiences:
         - user1
         - user2

Should I continue to use a helpers file?

Thanks again for all the help.


问:
jQuery Color Animation doesn't work
I'm trying to animate a div's background color. I've downloaded jquery.color.js from here - http://plugins.jquery.com/project/color but it didn't work. I deleted the content of jquery.color.js, copy/pasted it from here - jQuery animate backgroundColor and saved it.
Still nothing happens.

Here's the code:

```<code><link href="@Url.Content("/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("/Scripts/jquery-1.6.1.js")" type="text/javascript"></script>
<script src="@Url.Content("/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.color.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
    $('#firstDiv').animate({ backgroundColor: '#ff9f5f' }, 2000);
});
</script>
</code>```

I've tried src="@Url.Content("/Scripts/jquery.color.js")" instead of src="/Scripts/jquery.color.js", but then I get runtime error: 'jQuery' is undefined.
I have no idea why it doesn't work.

答:
Seems to be working ok for me. Probable because you included jquery twice.

http://jsfiddle.net/7wxyj/ jsfiddle is going really slow for me, so if that doesnt work check out the jsbin one:

http://jsbin.com/ejurov/2

Title: jQuery Color Animation doesn't work

Body:
I'm trying to animate a div's background color. I've downloaded jquery.color.js from here - http://plugins.jquery.com/project/color but it didn't work. I deleted the content of jquery.color.js, copy/pasted it from here - jQuery animate backgroundColor and saved it.
Still nothing happens.

Here's the code:

<link href="@Url.Content("/Content/Site.css")" rel="stylesheet" type="text/css" />

I've tried src="@Url.Content("/Scripts/jquery.color.js")" instead of src="/Scripts/jquery.color.js", but then I get runtime error: 'jQuery' is undefined.
I have no idea why it doesn't work.


问:
melt function gives size allocation error
Whenever I am trying to melt data. I am getting this error. Pls let me know how to fix this error.</p>
```<code>dd1<-melt.data.table(abc_comments,id.vars = c('user_id','date','source','value','value_clean','ids'))

#Error

Error: cannot allocate vector of size 2.9 Gb
</code>```

答:
I'm un-duping this because while the symptom is a duplicate, there is a method not discussed (in detail) there that can resolve the issue.

Split, melt, recombine

I'll demonstrate using iris.

library(data.table)
irisDT <- as.data.table(iris)

# this is our "control"
melt1 <- melt(irisDT, id.vars = "Species")
head(melt1, 3)
#    Species     variable value
#     <fctr>       <fctr> <num>
# 1:  setosa Sepal.Length   4.3
# 2:  setosa Sepal.Length   4.4
# 3:  setosa Sepal.Length   4.4
```
<p>The split-melt-combine solution:</p>
<pre class="lang-r prettyprint-override"><code>melt2 <- rbindlist(lapply(split(irisDT, seq_len(nrow(irisDT)) %/% 51), melt, id.vars = "Species"))
</code>```

Verification:

setorder(melt1, Species, variable, value)
setorder(melt2, Species, variable, value)
identical(melt1, melt2)
# [1] TRUE
```
<p>Breakdown:</p>
<ol>
<li><p><strong>Split</strong>. <code>split(irisDT, 1:150 %/% 51)</code> breaks it down into frames of up to 51 rows each. (I chose 51 arbitrarily.) In this case, it is a 3-long list of around 48-51 rows each. They don't need to be equal, just <em>each</em> small enough.</p>
</li>
<li><p><strong>Melt</strong>. <code>melt</code> each one individually using <code>lapply(., melt, id.vars="Species")</code>. This produces (again) a 3-long list, now of melted data.</p>
</li>
<li><p><strong>Combine</strong>. <code>rbindlist</code> speaks for itself.</p>
</li>
</ol>
<hr />
<p>Without exhaustive testing (I'm not in the practice of trying to fill memory, and I have 64GB so it'll take a lot more to do so), I wonder if running this as-is will not work directly. If that is the case, and you cannot find a size that makes it work, consider this alternative:</p>
<pre class="lang-r prettyprint-override"><code>out <- list()
irisDTspl <- split(irisDT, seq_len(nrow(irisDT)) %/% 51)
out <- list()
for (i in seq_along(irisDTspl)) {
  out[[i]] <- melt(irisDTspl[[i]], id.vars = "Species")
  irisDTspl[i] <- NA      # anything small, but need to keep the index filled
  gc()
}
melt3 <- rbindlist(out)
setorder(melt3, Species, variable, value)
identical(melt1, melt3)
# [1] TRUE
</code>```

Body:
Whenever I am trying to melt data. I am getting this error. Pls let me know how to fix this error.

dd1<-melt.data.table(abc_comments,id.vars = c('user_id','date','source','value','value_clean','ids'))

#Error

Error: cannot allocate vector of size 2.9 Gb

Body:
I'm un-duping this because while the symptom is a duplicate, there is a method not discussed (in detail) there that can resolve the issue.

Split, melt, recombine

I'll demonstrate using iris.

library(data.table)
irisDT <- as.data.table(iris)

# this is our "control"
melt1 <- melt(irisDT, id.vars = "Species")
head(melt1, 3)
#    Species     variable value
#     <fctr>       <fctr> <num>
# 1:  setosa Sepal.Length   4.3
# 2:  setosa Sepal.Length   4.4
# 3:  setosa Sepal.Length   4.4

The split-melt-combine solution:

melt2 <- rbindlist(lapply(split(irisDT, seq_len(nrow(irisDT)) %/% 51), melt, id.vars = "Species"))

Verification:

setorder(melt1, Species, variable, value)
setorder(melt2, Species, variable, value)
identical(melt1, melt2)
# [1] TRUE

Breakdown:

Split. split(irisDT, 1:150 %/% 51) breaks it down into frames of up to 51 rows each. (I chose 51 arbitrarily.) In this case, it is a 3-long list of around 48-51 rows each. They don't need to be equal, just each small enough.

Melt. melt each one individually using lapply(., melt, id.vars="Species"). This produces (again) a 3-long list, now of melted data.

Combine. rbindlist speaks for itself.

Without exhaustive testing (I'm not in the practice of trying to fill memory, and I have 64GB so it'll take a lot more to do so), I wonder if running this as-is will not work directly. If that is the case, and you cannot find a size that makes it work, consider this alternative:

out <- list()
irisDTspl <- split(irisDT, seq_len(nrow(irisDT)) %/% 51)
out <- list()
for (i in seq_along(irisDTspl)) {
  out[[i]] <- melt(irisDTspl[[i]], id.vars = "Species")
  irisDTspl[i] <- NA      # anything small, but need to keep the index filled
  gc()
}
melt3 <- rbindlist(out)
setorder(melt3, Species, variable, value)
identical(melt1, melt3)
# [1] TRUE


问:
Is if(A | B) always faster than if(A || B)?
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

```<code>void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}
</code>```

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?

答:
So the question is why don't we always use | instead of || in branches?

Branch prediction is relevant only to fairly hot pieces of code, and it depends on the branch being predictable enough to matter.  In most places, | has little or no performance benefit over ||.

Also, taking A and B as expressions of suitable type (not necessarily single variables), key relevant differences include:

In A || B, B is evaluated only if A evaluates to 0, but in A | B, B is always evaluated.  Conditionally avoiding evaluation of B is sometimes exactly the point of using the former.

In A || B there is a sequence point between evaluation of A and evaluation of B, but there isn't one in A | B.  Even if you don't care about short-circuiting, you may care about the sequencing, even in relatively simple examples.  For example, given an integer x, x-- || x-- has well-defined behavior, but x-- | x-- has undefined behavior.

When used in conditional context, the intent of A || B is clear to other humans, but the reason to substitute A | B less so.  Code clarity is extremely important.  And after all, if the compiler can see that it is safe to do so (and in most cases it is more reliable than a human at making the determination) then it is at liberty to compile one of those expressions as if it were the other.

If you cannot be sure that A and B both have built-in types -- in a template, for example -- you have to account for the possibility that one or both of | and || have been overloaded.  In that case, it is reasonable to suppose that || will still do something that makes sense for branch control, but it is much less safe to assume that | will do something equivalent or even suitable.

As an additional minor matter, the precedence of | is different from that of ||.  This can bite you if you rely on precedence instead of parentheses for grouping, and you need to watch out for that if you are considering modifying existing code to change || expressions to | expressions.  For example, A && B || C && D groups as (A && B) || (C && D), but A && B | C && D groups as (A && (B | C)) && D.

Body:
I am reading this book by Fedor Pikus and he has some very very interesting examples which for me were a surprise.

Particularly this benchmark caught me, where the only difference is that in one of them we use || in if and in another we use |.

void BM_misspredict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] || b2[i])  // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

void BM_predict(benchmark::State& state)
{

    std::srand(1);
    const unsigned int N = 10000;;
    std::vector<unsigned long> v1(N), v2(N);
    std::vector<int> c1(N), c2(N);

    for (int i = 0; i < N; ++i)
    {
        v1[i] = rand();
        v2[i] = rand();
        c1[i] = rand() & 0x1;
        c2[i] = !c1[i];
    }

    unsigned long* p1 = v1.data();
    unsigned long* p2 = v2.data();
    int* b1 = c1.data();
    int* b2 = c2.data();

    for (auto _ : state)
    {
        unsigned long a1 = 0, a2 = 0;
        for (size_t i = 0; i < N; ++i)
        {
            if (b1[i] | b2[i]) // Only difference
            {
                a1 += p1[i];
            }
            else
            {
                a2 *= p2[i];
            }
        }
        benchmark::DoNotOptimize(a1);
        benchmark::DoNotOptimize(a2);
        benchmark::ClobberMemory();

    }
    state.SetItemsProcessed(state.iterations());
}

I will not go in all the details explained in the book why the latter is faster, but the idea is that hardware branch predictor is given 2 chances to misspredict in slower version and in the | (bitwise or) version. See the benchmark results below.

So the question is why don't we always use | instead of || in branches?


问:
WITH queries with INSERT in MySQL
I'm trying to do something that I'm almost positive works in Postgresql:

```<code>WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT cte.id, 'John'
UNION ALL
SELECT cte.id, 'Frank'
UNION ALL
SELECT cte.id, 'Thomas'
;
</code>```

In other words, I want to grab the "something" row to be used for a bunch of new rows in "somwhere". Each new entry should have a reference (like  foreign key value) back to the same "something" row in the cte, mostly just to avoid a mess. However, MySQL is giving me that "blank stare" syntax error mechanism. Does MySQL allow WITH ... INSERT ...;?

Here's the actual code; it's just setting up test data:

```<code>WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;
</code>```

答:
Proof of concept script for mySQL "INSERT WITH"</p>
```<code>CREATE TABLE fromm field char(10));
INSERT INTO fromm VALUES ('Hello!');
CREATE TABLE too field char(10));
INSERT INTO too (field)
WITH pre AS
( SELECT field f FROM fromm)
SELECT f FROM pre;
SELECT field FROM too;
DROP TABLE fromm;
DROP TABLE too;
</code>```

Title: WITH queries with INSERT in MySQL

Body:
I'm trying to do something that I'm almost positive works in Postgresql:

WITH cte AS (SELECT something FROM something WHERE something.name='reference')
INSERT INTO somewhere (id, name)
SELECT cte.id, 'John'
UNION ALL
SELECT cte.id, 'Frank'
UNION ALL
SELECT cte.id, 'Thomas'
;

In other words, I want to grab the "something" row to be used for a bunch of new rows in "somwhere". Each new entry should have a reference (like  foreign key value) back to the same "something" row in the cte, mostly just to avoid a mess. However, MySQL is giving me that "blank stare" syntax error mechanism. Does MySQL allow WITH ... INSERT ...;?

Here's the actual code; it's just setting up test data:

WITH
  pr AS (SELECT pr_id from property AS p WHERE p.pr_name = 'Royal Oaks Plaza'),
  u AS (SELECT pr.pr_id AS pr_id, utyp.utyp_name AS utyp_name, utyp.utyp_id AS utyp_id FROM unit_type AS utyp, pr)
    INSERT INTO unit (pr_id, unt_number, utyp_id, unt_size)
    SELECT pr_id, '100', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'BEAUTY'
    UNION ALL
    SELECT pr_id, '110', utyp_id, FLOOR(500 + RAND() * 2000)
      FROM u WHERE utyp_name = 'RESTAURANT'
;

Body:
Proof of concept script for mySQL "INSERT WITH"

CREATE TABLE fromm field char(10));
INSERT INTO fromm VALUES ('Hello!');
CREATE TABLE too field char(10));
INSERT INTO too (field)
WITH pre AS
( SELECT field f FROM fromm)
SELECT f FROM pre;
SELECT field FROM too;
DROP TABLE fromm;
DROP TABLE too;


问:
How to select only Month/Year with the InputDate control
The ASP.NET Razor components are nice. It's so easy to get a month/day/year.

```<code><div class="form-group col-md-3">
    <label for="birthdayBox">Birth</label>
    <InputDate id="birthdayBox" class="form-control" @bind-Value="UserInput.BirthDay" />
</div>
</code>```

But does the control support month/year without the day? Thanks.

答:
This is supported in Blazor (at least it is now, I'm not sure about last year. Here's how to do this, using the InputDateType enumeration:

```<code><InputDate Type="InputDateType.Month" class="form-control" @bind-Value="SelectedMonth"/>
</code>```

Body:
The ASP.NET Razor components are nice. It's so easy to get a month/day/year.

    Birth
    <InputDate id="birthdayBox" class="form-control" @bind-Value="UserInput.BirthDay" />

But does the control support month/year without the day? Thanks.

Body:
This is supported in Blazor (at least it is now, I'm not sure about last year. Here's how to do this, using the InputDateType enumeration:

<InputDate Type="InputDateType.Month" class="form-control" @bind-Value="SelectedMonth"/>


问:
Python: concise properties
I'm implementing a class in Python which has many properties. Here's an example of a property:

class Test:
    def __init__(self):
        self._value = None

    def get_value(self):
        if self._value is None:
            self._value = datetime.datetime.now()
        return self._value

    def set_value(self, new_value):
        self._value = new_value

    value = property(get_value, set_value)
```

This seems like a lot of code.

Is there a more concise way to implement this pattern? I'm using PyCharm if that makes any difference.

答:
If you have same logic/validation for some of your properties you can write your own descriptor(Properties are descriptors).

Here for example I accept only string with length higher than 3. Instead of two properties, one for first_name and one for last_name, I created a descriptor ValidName and use it for both first_name and last_name:

class ValidName:
    def __set_name__(self, owner, name):
        self.name = f"_{name}"

    def __set__(self, instance, value):
        if len(value) < 3:
            raise ValueError("The lenght must be larger than 3.")
        setattr(instance, self.name, value)

    def __get__(self, instance, owner):
        return getattr(instance, self.name)

class Person:
    first_name = ValidName()
    last_name = ValidName()

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
```

Title: Python: concise properties

Body:
I'm implementing a class in Python which has many properties. Here's an example of a property:

class Test:
    def __init__(self):
        self._value = None

    def get_value(self):
        if self._value is None:
            self._value = datetime.datetime.now()
        return self._value

    def set_value(self, new_value):
        self._value = new_value

    value = property(get_value, set_value)

This seems like a lot of code.

Is there a more concise way to implement this pattern? I'm using PyCharm if that makes any difference.


问:
What type should I use instead of any?

Code

Slider.tsx

```<code>import { useSelector, connect } from "react-redux";
import { ProductType, ProductItem, StateType } from "types";
const Slider = ({ products, number }: any) => {    ------------------> what type?
//  const number = useSelector((state: StateType) => state.number);
  return (
    <S.Slider>
         <S.SliderWrapper widthSize={number}>
           {products}
             ...
         <S.SliderWrapper>
    </S.Slider>
  );
};

export default connect((state: StateType, { products }: ProductType) => {
  return { number: state.number, products };
}, null)(Slider);

</code>```

types.ts

```<code>export interface ProductItem {
  id: number;
  title: string;
  price: number;
  bgcolor: string;
  colors: { code: string; img: any }[];
}
export interface ProductType {
  products: ProductItem[];
}

export interface StateType {
  number: number;
}
</code>```

I set the type on connect now, and I don't know the type of prop of Slider Component, so I set it to 'any' and it works well.

How can I change it to put in the type instead of "any"?

答:
You need to create an interface describing the type of products. I assume that number is type of number and create a product since I don't know the shape of your object, adapt it to your needs. So you will have something like that :

export interface IProduct{
  id: number,
  name: string,
}
```
<p>And, either create an interface for the props of your slider, as follow :</p>
<pre class="lang-js prettyprint-override"><code>interface ISliderProps {
  products: Array<Product>,
  number: number
}

export const Slider = ({products, number}: ISliderProps) => {
  // ...
}
</code>```

or define it directly next to your props :

export const Slider = ({products, number}: {products: Array<Product>, number: number}) => {
  // ...
}
```
<p>You can also use the <code>React.FC<></code> interface that allow you to type your props this way :</p>
<pre class="lang-js prettyprint-override"><code>export const Slider: React.FC<ISliderProps> = ({product, number}) {
  // ...
}
</code>```

But note that this last solution expose your component to children by default, which is not what you always want.

Title: What type should I use instead of any?

Body:
Code

Slider.tsx

import { useSelector, connect } from "react-redux";
import { ProductType, ProductItem, StateType } from "types";
const Slider = ({ products, number }: any) => {    ------------------> what type?
//  const number = useSelector((state: StateType) => state.number);
  return (
    <S.Slider>
         <S.SliderWrapper widthSize={number}>
           {products}
             ...
         <S.SliderWrapper>
    </S.Slider>
  );
};

export default connect((state: StateType, { products }: ProductType) => {
  return { number: state.number, products };
}, null)(Slider);

types.ts

export interface ProductItem {
  id: number;
  title: string;
  price: number;
  bgcolor: string;
  colors: { code: string; img: any }[];
}
export interface ProductType {
  products: ProductItem[];
}

export interface StateType {
  number: number;
}

I set the type on connect now, and I don't know the type of prop of Slider Component, so I set it to 'any' and it works well.

How can I change it to put in the type instead of "any"?

Body:
You need to create an interface describing the type of products. I assume that number is type of number and create a product since I don't know the shape of your object, adapt it to your needs. So you will have something like that :

export interface IProduct{
  id: number,
  name: string,
}

And, either create an interface for the props of your slider, as follow :

interface ISliderProps {
  products: Array<Product>,
  number: number
}

export const Slider = ({products, number}: ISliderProps) => {
  // ...
}

or define it directly next to your props :

export const Slider = ({products, number}: {products: Array<Product>, number: number}) => {
  // ...
}

You can also use the React.FC<> interface that allow you to type your props this way :

export const Slider: React.FC<ISliderProps> = ({product, number}) {
  // ...
}

But note that this last solution expose your component to children by default, which is not what you always want.