问:
What is the best way to tell the compiler to differentiate between two types which hold the same kind of data
Suppose we have two types which are basically ints:

```<code>alias UserID = int;
alias ItemID = int;
</code>```

And suppose we have two functions which take arguments of the two types:

```<code>void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; }
void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\n'; }
</code>```

The problem is that we can do:

```<code>UserID uid {5};
add_item(uid);
</code>```

And the compiler will not be able to protect me from passing the wrong type because both types alias the same underlying type.

What is the least boilerplate I need to add to make the compiler differentiate between the two types?

My current solution is to define the types as structs like this:

```<code>struct UserID
{
  int val;
  operator int() { return val; }
};

struct ItemID
{
  int val;
  operator int() { return val; }
};
</code>```

The operator int() is to allow for an implicit conversion to the base type.

One problem with this approach is that sometimes I need to do arithmetic operations on the types, like for example:

```<code>UserID uid {5};
++uid;
</code>```

Another problem is when these types are passed to a template and a template-argument deduction takes place where the correct type to deduce is int but the compiler is not able to see through the conversion operator.

I'm wondering if there's a more elegant solution where both types would seamlessly convert to their base type when the base type is required but would still be different when the wrapping type is required.
What I want is the following:

```<code>add_user(UserID{1}); //compiles
add_item(ItemID{2}); //compiles
add_user(ItemID{3}); //doesn't compile
UserID uid = UserID{4} + 1; //compiles
++uid; //compiles
UserID uid2 = ItemID{5} + 1; //doesn't compile
</code>```

By 'the least boilerplate' I mean the total boilerplate code I need to write both in the definition of the types as well as in the user code.

答:
You can use "shadow types" (they have names but no definition) and a template (or use some "strong typedef" library):

```<code>template <typename>
class Id
{
    int val;
    operator int() const { return val; }
};

using UserID = Id<struct user_tag_>;
using ItemID = Id<struct item_tag_>;
</code>```

And you should provide operator overloads for the operations that make sense - you most likely don't want to divide or multiply these IDs by anything.

Body:
Suppose we have two types which are basically ints:

alias UserID = int;
alias ItemID = int;

And suppose we have two functions which take arguments of the two types:

void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; }
void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\n'; }

The problem is that we can do:

UserID uid {5};
add_item(uid);

And the compiler will not be able to protect me from passing the wrong type because both types alias the same underlying type.

What is the least boilerplate I need to add to make the compiler differentiate between the two types?

My current solution is to define the types as structs like this:

struct UserID
{
  int val;
  operator int() { return val; }
};

struct ItemID
{
  int val;
  operator int() { return val; }
};

The operator int() is to allow for an implicit conversion to the base type.

One problem with this approach is that sometimes I need to do arithmetic operations on the types, like for example:

UserID uid {5};
++uid;

Another problem is when these types are passed to a template and a template-argument deduction takes place where the correct type to deduce is int but the compiler is not able to see through the conversion operator.

I'm wondering if there's a more elegant solution where both types would seamlessly convert to their base type when the base type is required but would still be different when the wrapping type is required.
What I want is the following:

add_user(UserID{1}); //compiles
add_item(ItemID{2}); //compiles
add_user(ItemID{3}); //doesn't compile
UserID uid = UserID{4} + 1; //compiles
++uid; //compiles
UserID uid2 = ItemID{5} + 1; //doesn't compile

By 'the least boilerplate' I mean the total boilerplate code I need to write both in the definition of the types as well as in the user code.

Body:
You can use "shadow types" (they have names but no definition) and a template (or use some "strong typedef" library):

template <typename>
class Id
{
    int val;
    operator int() const { return val; }
};

using UserID = Id<struct user_tag_>;
using ItemID = Id<struct item_tag_>;

And you should provide operator overloads for the operations that make sense - you most likely don't want to divide or multiply these IDs by anything.


来源: stackexchange

问:
Combining multiple columns/variables into a single column
I have the following problem (I guess there is an easy answer to it, but I can't figure it out...).

I want to combine multiple columns into a single column. I have 3 variables and there are cases that answered variable 1, cases that answered variable 2, cases that answered variable 3 and cases that answered none of the variables.

Now, I want to combine them all in a single variable, that looks like column vx:

```<code>Ideal result:

  v1 v2 v3 vx
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA

</code>```
```<code>v1 <- c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 <- c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 <- c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df <- data.frame(v1, v2, v3)

</code>```

I tried it with df$vx <- paste(df$v1, df$v2, df$v3) but then I get the following result:

```<code>My result:

 v1 v2 v3       vx
1   1 NA NA  1 NA NA
2   3 NA NA  3 NA NA
3   6 NA NA  6 NA NA
4  NA  5 NA  NA 5 NA
5  NA  1 NA  NA 1 NA
6  NA  3 NA  NA 3 NA
7  NA NA  4  NA NA 4
8  NA NA  2  NA NA 2
9  NA NA  1  NA NA 1
10 NA NA NA NA NA NA
</code>```

Can someone tell me how I get a result like the one above (ideal result) without the NAs (except if there are only NAs then I would like to have only one NA in column vx)

I hope I made clear what my issue is.

Thanks a lot!

答:
Using apply()

```<code># Your data.
v1 = c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 = c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 = c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df = data.frame(v1, v2, v3)
df

# Solution: writing a function to be passed in apply().
useful.function = function(x)
{
  # The input "x" is a row of a dataframe.

  # If all the values are NA, return NA.
  if(sum(!is.na(x)) == 0)
    return(NA)

  # Otherwise, return the non-NA value.
  return(x[!is.na(x)])
}

df$vx = apply(df, MARGIN = 1, useful.function)
df
</code>```

Clearly, other solutions may be faster and require less coding (as those relying on the dplyr package, posted by @Maël). However, I really suggest you to get confident in using apply() and the other functions from the same family (see lapply() and sapply()), as they are really flexible (and sometimes you may not be aware of the existence of a certain function or package).

ContentLicense: CC BY-SA 4.0

Body:
I have the following problem (I guess there is an easy answer to it, but I can't figure it out...).

I want to combine multiple columns into a single column. I have 3 variables and there are cases that answered variable 1, cases that answered variable 2, cases that answered variable 3 and cases that answered none of the variables.

Now, I want to combine them all in a single variable, that looks like column vx:

Ideal result:

  v1 v2 v3 vx
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA

v1 <- c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 <- c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 <- c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df <- data.frame(v1, v2, v3)

I tried it with df$vx <- paste(df$v1, df$v2, df$v3) but then I get the following result:

My result:

 v1 v2 v3       vx
1   1 NA NA  1 NA NA
2   3 NA NA  3 NA NA
3   6 NA NA  6 NA NA
4  NA  5 NA  NA 5 NA
5  NA  1 NA  NA 1 NA
6  NA  3 NA  NA 3 NA
7  NA NA  4  NA NA 4
8  NA NA  2  NA NA 2
9  NA NA  1  NA NA 1
10 NA NA NA NA NA NA

Can someone tell me how I get a result like the one above (ideal result) without the NAs (except if there are only NAs then I would like to have only one NA in column vx)

I hope I made clear what my issue is.

Thanks a lot!

Body:
Using apply()

# Your data.
v1 = c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 = c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 = c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df = data.frame(v1, v2, v3)
df

# Solution: writing a function to be passed in apply().
useful.function = function(x)
{
  # The input "x" is a row of a dataframe.

  # If all the values are NA, return NA.
  if(sum(!is.na(x)) == 0)
    return(NA)

  # Otherwise, return the non-NA value.
  return(x[!is.na(x)])
}

df$vx = apply(df, MARGIN = 1, useful.function)
df

Clearly, other solutions may be faster and require less coding (as those relying on the dplyr package, posted by @Maël). However, I really suggest you to get confident in using apply() and the other functions from the same family (see lapply() and sapply()), as they are really flexible (and sometimes you may not be aware of the existence of a certain function or package).


问:
How do I determine the video codec used in a file
The HTML5  tag exposes a canPlayType() method to JavaScript. It takes a MIME type for the media to be played, and returns an indication as to whether the browser thinks it can actually play the media.

Unfortunately, most of the common media types ('video/mp4', for example) are container types, and the media type itself isn't enough to determine whether the content can actually be played. In response to this, RFC 4281 defines a "codecs" parameter that can be added to the MIME type to identify the specific codec.

So, for example, a type of "video/3gpp2; codecs='mp4v.20.9, mp4a.E1'" is (according to the RFC) "MPEG-4 Visual Simple Profile Level 0 plus 13K voice".

I've found a variety of places that tell me what values to use if I know the codec, but I often find myself in the position of receiving a video file with unknown provenance -- all I know is that it's got an .mp4 filetype.

How can I determine from the actual file what the correct "codecs" value is for canPlayType()?

答:
Here's a small Python snippet that'll give you the answer for MP4-files containing h.264 video:

import re
import sys

with open(sys.argv[1], 'rb') as f:
    match = re.search(b'\x61\x76\x63\x43\x01', f.read())
    if not match:
        print('No avc1-bytestring found. File is likely not an .mp4-file containing h.264 video.')
        exit()
    f.seek(0)
    f.seek(match.end())
    print('avc1.' + f.read(3).hex())
```
<p>If you save that to <code>mp4-codec-reader.py</code> you can get the h.264 codec like so:</p>
```python mp4-codec-reader.py <YOUR_FILE.mp4>
```

Note that this doesn't work h.265 (avc2) and other codecs.
Other container formats may or may not work.

ContentLicense: CC BY-SA 3.0

Body:
Here's a small Python snippet that'll give you the answer for MP4-files containing h.264 video:

import re
import sys

with open(sys.argv[1], 'rb') as f:
    match = re.search(b'\x61\x76\x63\x43\x01', f.read())
    if not match:
        print('No avc1-bytestring found. File is likely not an .mp4-file containing h.264 video.')
        exit()
    f.seek(0)
    f.seek(match.end())
    print('avc1.' + f.read(3).hex())

If you save that to mp4-codec-reader.py you can get the h.264 codec like so:

python mp4-codec-reader.py <YOUR_FILE.mp4>

Note that this doesn't work h.265 (avc2) and other codecs.
Other container formats may or may not work.


问:
Concurrent requests not working in Siege - Http stress testing
I'm testing an app located in a AWS EC2 instance via a POST request.

I'm posting an image with the url in the form of a json string by converting it to base64. All the settings are in place. The problem is that even though I'm sending 10 concurrent requests for the same image, by using the -c parameter, only the first request gets processed and the Siege stress test stops.

This is the code I'm using

```<code>'siege -c10 -r11 --content-type "application/json" -g 'http://www.hello.com POST {"img": "test64", fname: "img.jpg"}'
</code>```

答:
The solution is to remove the -g command since that's for GET requests and not for POST

```<code>'siege -c10 -r11 --content-type "application/json"  'http://www.hello.com POST {"img": "test64", fname: "img.jpg"}'
</code>```

Body:
I'm testing an app located in a AWS EC2 instance via a POST request.

I'm posting an image with the url in the form of a json string by converting it to base64. All the settings are in place. The problem is that even though I'm sending 10 concurrent requests for the same image, by using the -c parameter, only the first request gets processed and the Siege stress test stops.

This is the code I'm using

'siege -c10 -r11 --content-type "application/json" -g 'http://www.hello.com POST {"img": "test64", fname: "img.jpg"}'

Body:
The solution is to remove the -g command since that's for GET requests and not for POST

'siege -c10 -r11 --content-type "application/json"  'http://www.hello.com POST {"img": "test64", fname: "img.jpg"}'


问:
Presto equivalent to StringTokenizerDelim (Vertica) / Explode(Python)
I am migrating a query from Vertica to Presto(0.246). The query contains a Vertica function StringTokenizerDelim, which basically explodes and array (market column) into rows.

This is the mockup of the table:

```<code>+----+---------+-------------+
| id | product |   market    |
+----+---------+-------------+
|  1 | Cabinet | AU,GB,FR    |
|  2 | Chair   | US,GB       |
|  3 | Desk    | BE,GB,FR,US |
+----+---------+-------------+
</code>```

The output should be:

```<code>+----+---------+--------+
| id | product | market |
+----+---------+--------+
|  1 | Cabinet | AU     |
|  1 | Cabinet | GB     |
|  1 | Cabinet | FR     |
|  2 | Chair   | US     |
|  2 | Chair   | GB     |
|  3 | Desk    | BE     |
|  3 | Desk    | GB     |
|  3 | Desk    | FR     |
|  3 | Desk    | US     |
+----+---------+--------+
</code>```

What is the equivalent to that function in Presto (if there is any? couldn't find it on the documentation)?

Cheers,

答:
split with UNNEST should do the trick:

-- sample data
WITH dataset (id, product,   market ) AS (
    values (1, 'Cabinet', 'AU,GB,FR'),
    (2, 'Chair', 'US,GB'),
    (3, 'Desk', 'BE,GB,FR,US')
)

--query
SELECT id, product, m as market
FROM dataset
CROSS JOIN UNNEST (split(market, ',')) as t(m)
```

Output:

id
product
market

1
Cabinet
AU

1
Cabinet
GB

1
Cabinet
FR

2
Chair
US

2
Chair
GB

3
Desk
BE

3
Desk
GB

3
Desk
FR

3
Desk
US

Body:
I am migrating a query from Vertica to Presto(0.246). The query contains a Vertica function StringTokenizerDelim, which basically explodes and array (market column) into rows.

This is the mockup of the table:

+----+---------+-------------+
| id | product |   market    |
+----+---------+-------------+
|  1 | Cabinet | AU,GB,FR    |
|  2 | Chair   | US,GB       |
|  3 | Desk    | BE,GB,FR,US |
+----+---------+-------------+

The output should be:

+----+---------+--------+
| id | product | market |
+----+---------+--------+
|  1 | Cabinet | AU     |
|  1 | Cabinet | GB     |
|  1 | Cabinet | FR     |
|  2 | Chair   | US     |
|  2 | Chair   | GB     |
|  3 | Desk    | BE     |
|  3 | Desk    | GB     |
|  3 | Desk    | FR     |
|  3 | Desk    | US     |
+----+---------+--------+

What is the equivalent to that function in Presto (if there is any? couldn't find it on the documentation)?

Cheers,

Body:
split with UNNEST should do the trick:

-- sample data
WITH dataset (id, product,   market ) AS (
    values (1, 'Cabinet', 'AU,GB,FR'),
    (2, 'Chair', 'US,GB'),
    (3, 'Desk', 'BE,GB,FR,US')
)

--query
SELECT id, product, m as market
FROM dataset
CROSS JOIN UNNEST (split(market, ',')) as t(m)

Output:

id
product
market

1
Cabinet
AU

1
Cabinet
GB

1
Cabinet
FR

2
Chair
US

2
Chair
GB

3
Desk
BE

3
Desk
GB

3
Desk
FR

3
Desk
US


问:
Trackbar functions
I'm learning C++/CLI with .NET in Visual Studio.

I want to create a TrackBar, where the minimum value is RGB white and the maximum value is RGB black.

I've dropped into the Form a Label that shows the value of the TrackBar's pointer position, but I want to show it only while I'm scrolling or holding the TrackBar's pointer with the mouse. Can someone help me?

Here's the TrackBar scroll listener:

```<code>private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e) {
    //Set label text to trackbar value
    label2->Text = trackBar1->Value.ToString();
    //Set label2 visible to show trackbar value
    label2->Visible = true;
}
</code>```

答:
First of all, thank you all for help! I finally decided to show the label only when trackbar is set to 0 or 100 and instead of showing up 0 or 100 it says Light or Dark.
Now i need to get the trackbar to go from rgb white to rgb black and set it as  system color for window background...
My idea is to use GetSysColor and use the trackbar value as a multiplier for for the actual rgb system window color but i don't know how to convert this to code.

Btw, here's the code for the label behavior:

```<code>#pragma endregion
    private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e) {

        label2->Text = trackBar1->Value.ToString();
        if (trackBar1->Value == 0 || trackBar1->Value == 100)
        {
            label2->Visible = true;
        }
        else
        {
            label2->Visible = false;
        }

        if (trackBar1->Value == 0)
        {
            label2->Text = "Light";
        }
        if (trackBar1->Value == 100)
        {
            label2->Text = "Dark";
        }

    }
    };
</code>```

Title: Trackbar functions

Body:
I'm learning C++/CLI with .NET in Visual Studio.

I want to create a TrackBar, where the minimum value is RGB white and the maximum value is RGB black.

I've dropped into the Form a Label that shows the value of the TrackBar's pointer position, but I want to show it only while I'm scrolling or holding the TrackBar's pointer with the mouse. Can someone help me?

Here's the TrackBar scroll listener:

private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e) {
    //Set label text to trackbar value
    label2->Text = trackBar1->Value.ToString();
    //Set label2 visible to show trackbar value
    label2->Visible = true;
}

Body:
First of all, thank you all for help! I finally decided to show the label only when trackbar is set to 0 or 100 and instead of showing up 0 or 100 it says Light or Dark.
Now i need to get the trackbar to go from rgb white to rgb black and set it as  system color for window background...
My idea is to use GetSysColor and use the trackbar value as a multiplier for for the actual rgb system window color but i don't know how to convert this to code.

Btw, here's the code for the label behavior:

#pragma endregion
    private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e) {

        label2->Text = trackBar1->Value.ToString();
        if (trackBar1->Value == 0 || trackBar1->Value == 100)
        {
            label2->Visible = true;
        }
        else
        {
            label2->Visible = false;
        }

        if (trackBar1->Value == 0)
        {
            label2->Text = "Light";
        }
        if (trackBar1->Value == 100)
        {
            label2->Text = "Dark";
        }

    }
    };


问:
Pandas merging connected groups from multiple columns
How can I group rows which have at least one value in common? I can pass multiple columns to groupby but I want any one of them to be considered, not all of them.

Sample code:

import pandas as pd

input = pd.DataFrame({
  'fruit': ['peach', 'banana', pd.NA, 'peach', 'apple', 'avocado', pd.NA],
  'vegetable': [pd.NA, pd.NA, 'zucchini', pd.NA, pd.NA, pd.NA, 'potato'],
  'sugar': [17, 17, 2, 18, 20, pd.NA, 4],
  'color': ['orange', 'yellow', 'green', 'orange', 'red', 'green', 'brown']
})

output = input.groupby(['fruit', 'vegetable', 'sugar', 'color']).agg({
  'fruit': lambda x: list(set(x)),
  'vegetable': lambda x: list(set(x)),
  'sugar': lambda x: list(set(x)),
  'color': lambda x: list(set(x))
})
```
<p>Input:</p>
```    fruit       vegetable   sugar   color
0   peach                   17      orange
1   banana                  17      yellow
2               zucchini    2       green
3   peach                   18      orange
4   apple                   20      red
5   avocado                         green
6               potato      4       brown
```
<p>Expected output:</p>
```    fruit               vegetable   sugar       color
0   [peach, banana]     []          [17, 18]    [orange, yellow]
1   [avocado]           [zucchini]  [2]         [green]
2   [apple]             []          [20]        [red]
3   []                  [potato]    [4]         [brown]
```

答:
You problem seems to be a graph problem.

finding the groups per column

First, lets see which rows are grouped per column

```<code>from itertools import combinations, chain
groups = {col:
          list(chain.from_iterable(list(combinations(x, 2))
                                   for x in df.index.groupby(df[col]).values()
                                   if len(x)>1))
          for col in df.columns}

# {'fruit': [(0, 3)],
#  'vegetable': [],
#  'sugar': [(0, 1)],
#  'color': [(2, 5), (0, 3)]}
</code>```

So, here we would like to merge the groups (0,3) and (0,1) as 0 is common.

getting the connected components

Let's use networkx:

```<code>import networkx as nx

edges = list(chain.from_iterable(groups.values()))

G = nx.from_edgelist(edges)
G.add_nodes_from(df.index)

combined_groups = {k:v for v,l in enumerate(nx.connected_components(G))
                   for k in l}
# index: group_id
# {0: 0, 1: 0, 3: 0, 2: 1, 5: 1, 4: 2, 6: 3}
</code>```

final groupby

```<code>df.groupby(df.index.map(combined_groups)).agg(list)
</code>```

output:

```<code>                    fruit           vegetable         sugar                     color
0  [peach, banana, peach]  [<NA>, <NA>, <NA>]  [17, 17, 18]  [orange, yellow, orange]
1         [<NA>, avocado]    [zucchini, <NA>]     [2, <NA>]            [green, green]
2                 [apple]              [<NA>]          [20]                     [red]
3                  [<NA>]            [potato]           [4]                   [brown]
</code>```

Body:
How can I group rows which have at least one value in common? I can pass multiple columns to groupby but I want any one of them to be considered, not all of them.

Sample code:

import pandas as pd

input = pd.DataFrame({
  'fruit': ['peach', 'banana', pd.NA, 'peach', 'apple', 'avocado', pd.NA],
  'vegetable': [pd.NA, pd.NA, 'zucchini', pd.NA, pd.NA, pd.NA, 'potato'],
  'sugar': [17, 17, 2, 18, 20, pd.NA, 4],
  'color': ['orange', 'yellow', 'green', 'orange', 'red', 'green', 'brown']
})

output = input.groupby(['fruit', 'vegetable', 'sugar', 'color']).agg({
  'fruit': lambda x: list(set(x)),
  'vegetable': lambda x: list(set(x)),
  'sugar': lambda x: list(set(x)),
  'color': lambda x: list(set(x))
})

Input:

    fruit       vegetable   sugar   color
0   peach                   17      orange
1   banana                  17      yellow
2               zucchini    2       green
3   peach                   18      orange
4   apple                   20      red
5   avocado                         green
6               potato      4       brown

Expected output:

    fruit               vegetable   sugar       color
0   [peach, banana]     []          [17, 18]    [orange, yellow]
1   [avocado]           [zucchini]  [2]         [green]
2   [apple]             []          [20]        [red]
3   []                  [potato]    [4]         [brown]

Body:
You problem seems to be a graph problem.

finding the groups per column

First, lets see which rows are grouped per column

from itertools import combinations, chain
groups = {col:
          list(chain.from_iterable(list(combinations(x, 2))
                                   for x in df.index.groupby(df[col]).values()
                                   if len(x)>1))
          for col in df.columns}

# {'fruit': [(0, 3)],
#  'vegetable': [],
#  'sugar': [(0, 1)],
#  'color': [(2, 5), (0, 3)]}

So, here we would like to merge the groups (0,3) and (0,1) as 0 is common.

getting the connected components

Let's use networkx:

import networkx as nx

edges = list(chain.from_iterable(groups.values()))

G = nx.from_edgelist(edges)
G.add_nodes_from(df.index)

combined_groups = {k:v for v,l in enumerate(nx.connected_components(G))
                   for k in l}
# index: group_id
# {0: 0, 1: 0, 3: 0, 2: 1, 5: 1, 4: 2, 6: 3}

final groupby

df.groupby(df.index.map(combined_groups)).agg(list)

output:

                    fruit           vegetable         sugar                     color
0  [peach, banana, peach]  [<NA>, <NA>, <NA>]  [17, 17, 18]  [orange, yellow, orange]
1         [<NA>, avocado]    [zucchini, <NA>]     [2, <NA>]            [green, green]
2                 [apple]              [<NA>]          [20]                     [red]
3                  [<NA>]            [potato]           [4]                   [brown]


问:
Get feature names after sklearn pipeline
I want to match the output np array with the features to make a new pandas dataframe

Here is my pipeline:

```<code>from sklearn.pipeline import Pipeline
# Categorical pipeline
categorical_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
    ('Ordinal encoding', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)),
]
)
# Continuous pipeline
continuous_preprocessing = Pipeline(
[
     ('Imputation', SimpleImputer(missing_values=np.nan, strategy='mean')),
     ('Scaling', StandardScaler())
]
)
# Creating preprocessing pipeline
preprocessing = make_column_transformer(
     (continuous_preprocessing, continuous_cols),
     (categorical_preprocessing, categorical_cols),
)
# Final pipeline
pipeline = Pipeline(
[('Preprocessing', preprocessing)]
)
</code>```

Here is how I call it:

```<code>X_train = pipeline.fit_transform(X_train)
X_val = pipeline.transform(X_val)
X_test = pipeline.transform(X_test)
</code>```

Here is what I get when trying to get the feature names:

```<code>pipeline['Preprocessing'].transformers_[1][1]['Ordinal encoding'].get_feature_names()
</code>```

OUT:

```<code>AttributeError: 'OrdinalEncoder' object has no attribute 'get_feature_names'
</code>```

Here is a SO question that was similar: Sklearn Pipeline: Get feature names after OneHotEncode In ColumnTransformer

答:
Point is that, as of today, some transformers do expose a method .get_feature_names_out() and some others do not, which generates some problems - for instance - whenever you want to create a well-formatted DataFrame from the np.array outputted by a Pipeline or ColumnTransformer instance. (Instead, afaik, .get_feature_names() was deprecated in latest versions in favor of .get_feature_names_out()).

For what concerns the transformers that you are using, StandardScaler belongs to the first category of transformers exposing the method, while both SimpleImputer and OrdinalEncoder do belong to the second. The docs show the exposed methods within the Methods paragraphs. As said, this causes problems when doing something like pd.DataFrame(pipeline.fit_transform(X_train), columns=pipeline.get_feature_names_out()) on your pipeline, but it would cause problems as well on your categorical_preprocessing and continuous_preprocessing pipelines (as in both cases at least one transformer lacks of the method) and on the preprocessing ColumnTransformer instance.

There's an ongoing attempt in sklearn to enrich all estimators with the .get_feature_names_out() method. It is tracked within github issue #21308, which, as you might see, branches in many PRs (each one dealing with a specific module). For instance, issue #21079 for the preprocessing module, which will enrich the OrdinalEncoder among the others, issue #21078 for the impute module, which will enrich the SimpleImputer. I guess that they'll be available in a new release as soon as  all the referenced PR will be merged.

In the meanwhile, imo, you should go with a custom solution that might fit your needs. Here's a simple example, which do not necessarily resemble your need, but which is meant to give a (possible) way of proceeding:

```<code>import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder, StandardScaler
from sklearn.compose import make_column_transformer, make_column_selector

X = pd.DataFrame({'city': ['London', 'London', 'Paris', 'Sallisaw', ''],
                  'title': ['His Last Bow', 'How Watson Learned the Trick', 'A Moveable Feast', 'The Grapes of Wrath', 'The Jungle'],
                  'expert_rating': [5, 3, 4, 5, np.NaN],
                  'user_rating': [4, 5, 4, np.NaN, 3]})
X
</code>```

```<code>num_cols = X.select_dtypes(include=np.number).columns.tolist()
cat_cols = X.select_dtypes(exclude=np.number).columns.tolist()

# Categorical pipeline
categorical_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values='', strategy='most_frequent')),
    ('Ordinal encoding', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)),
]
)
# Continuous pipeline
continuous_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values=np.nan, strategy='mean')),
    ('Scaling', StandardScaler())
]
)
# Creating preprocessing pipeline
preprocessing = make_column_transformer(
    (continuous_preprocessing, num_cols),
    (categorical_preprocessing, cat_cols),
)

# Final pipeline
pipeline = Pipeline(
    [('Preprocessing', preprocessing)]
)

X_trans = pipeline.fit_transform(X)

pd.DataFrame(X_trans, columns= num_cols + cat_cols)
</code>```

Body:
I want to match the output np array with the features to make a new pandas dataframe

Here is my pipeline:

from sklearn.pipeline import Pipeline
# Categorical pipeline
categorical_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
    ('Ordinal encoding', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)),
]
)
# Continuous pipeline
continuous_preprocessing = Pipeline(
[
     ('Imputation', SimpleImputer(missing_values=np.nan, strategy='mean')),
     ('Scaling', StandardScaler())
]
)
# Creating preprocessing pipeline
preprocessing = make_column_transformer(
     (continuous_preprocessing, continuous_cols),
     (categorical_preprocessing, categorical_cols),
)
# Final pipeline
pipeline = Pipeline(
[('Preprocessing', preprocessing)]
)

Here is how I call it:

X_train = pipeline.fit_transform(X_train)
X_val = pipeline.transform(X_val)
X_test = pipeline.transform(X_test)

Here is what I get when trying to get the feature names:

pipeline['Preprocessing'].transformers_[1][1]['Ordinal encoding'].get_feature_names()

OUT:

AttributeError: 'OrdinalEncoder' object has no attribute 'get_feature_names'

Here is a SO question that was similar: Sklearn Pipeline: Get feature names after OneHotEncode In ColumnTransformer

Body:
Point is that, as of today, some transformers do expose a method .get_feature_names_out() and some others do not, which generates some problems - for instance - whenever you want to create a well-formatted DataFrame from the np.array outputted by a Pipeline or ColumnTransformer instance. (Instead, afaik, .get_feature_names() was deprecated in latest versions in favor of .get_feature_names_out()).

For what concerns the transformers that you are using, StandardScaler belongs to the first category of transformers exposing the method, while both SimpleImputer and OrdinalEncoder do belong to the second. The docs show the exposed methods within the Methods paragraphs. As said, this causes problems when doing something like pd.DataFrame(pipeline.fit_transform(X_train), columns=pipeline.get_feature_names_out()) on your pipeline, but it would cause problems as well on your categorical_preprocessing and continuous_preprocessing pipelines (as in both cases at least one transformer lacks of the method) and on the preprocessing ColumnTransformer instance.

There's an ongoing attempt in sklearn to enrich all estimators with the .get_feature_names_out() method. It is tracked within github issue #21308, which, as you might see, branches in many PRs (each one dealing with a specific module). For instance, issue #21079 for the preprocessing module, which will enrich the OrdinalEncoder among the others, issue #21078 for the impute module, which will enrich the SimpleImputer. I guess that they'll be available in a new release as soon as  all the referenced PR will be merged.

In the meanwhile, imo, you should go with a custom solution that might fit your needs. Here's a simple example, which do not necessarily resemble your need, but which is meant to give a (possible) way of proceeding:

import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder, StandardScaler
from sklearn.compose import make_column_transformer, make_column_selector

X = pd.DataFrame({'city': ['London', 'London', 'Paris', 'Sallisaw', ''],
                  'title': ['His Last Bow', 'How Watson Learned the Trick', 'A Moveable Feast', 'The Grapes of Wrath', 'The Jungle'],
                  'expert_rating': [5, 3, 4, 5, np.NaN],
                  'user_rating': [4, 5, 4, np.NaN, 3]})
X

num_cols = X.select_dtypes(include=np.number).columns.tolist()
cat_cols = X.select_dtypes(exclude=np.number).columns.tolist()

# Categorical pipeline
categorical_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values='', strategy='most_frequent')),
    ('Ordinal encoding', OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)),
]
)
# Continuous pipeline
continuous_preprocessing = Pipeline(
[
    ('Imputation', SimpleImputer(missing_values=np.nan, strategy='mean')),
    ('Scaling', StandardScaler())
]
)
# Creating preprocessing pipeline
preprocessing = make_column_transformer(
    (continuous_preprocessing, num_cols),
    (categorical_preprocessing, cat_cols),
)

# Final pipeline
pipeline = Pipeline(
    [('Preprocessing', preprocessing)]
)

X_trans = pipeline.fit_transform(X)

pd.DataFrame(X_trans, columns= num_cols + cat_cols)


问:
Front end web-development: good resources
I am about to move to a job where I will be doing front end web development (mainly CSS and jQuery).

What are good resources (books, websites, blogs etc.) for learning more about those technologies in particular and anything front-end web development related (good technologies to know, user interface ideas etc.) in general?

Thank you!

ETA: Just to give some idea of where I'm holding, I have about 1.5 years of experience in web development. So I already have a pretty good grasp of CSS and know the basics of jQuery. I also know a fair amount about user interface design.

答:
i assume you will also be doing HTML since this is at the core of FE dev. HTML, seems simple and is easy to ignore as a technology, but you should not turn your nose up to it. Writing terse, clean and semantic HTML is a skill and requires lots of learning and practice just as CSS and JS.

Right, now onto things you actually requested :)

For jQuery i would definitely consider learning as much as you can about JavaScript proper. Whilst you can write jQuery without knowing all that much about JavaScript, you need to understand JavaScript to make the most of jQuery and write better code. And of course to know when you can get away with using plain ol' JS.

JS resources:

JavaScript: The Good Parts - a concise but dense book by JS guru Douglas Crockford

JavaScript: The Definitive Guide - a mammoth bible,  not for the faint of heart!

Crockford on JS video series - a ton of videos on crockford's site :-)

jQuery docs - the jquery docs are very comprehensive and contain lots of examples and explanations

CSS resources:

web standards solutions - it's the only CSS book i've ever read and is an excellent primer

CSS Floats 101 - a list apart (an excellent website for FE development)

CSS Positioning 101 - a list apart

Good websites to have in your RSS client:

CSS Tricks - lots of cutting edge CSS

Specky Boy - general front-end dev

MS Script Junkie

A List Apart (Again!)

Smashing Magazine

hope that helps in your quest into front-end development!


问:
on_failure_callback not working in airflow DAG()
I want to call two different functions for dag failure and success. For that i want to use on_failure_callback and on_success_callback in DAG() function.

As per my requirement, this callbacks should be on dag level and not task level. That's why i am writing this callbacks insiled DAG() functions while declaring dag variable.

but this callback function are not being called. Same function if i call on task level , then working fine.

This is my code:

```<code>def success():
      print("successful")

dag = DAG(dag_id='callback_test',schedule_interval=None,default_args=default_args,on_success_callback=success)

    def fun1(**kwargs):
        print("function called")

    task1 = PythonOperator(
        task_id='task1',
        provide_context=True,
        python_callable=fun1,
        dag=dag
        )

    task1
</code>```

答: If you want to pass agrument, you can do it by creating higher order function just like crearing decorator returning actual callback function by outer function.</p>

Body:
I want to call two different functions for dag failure and success. For that i want to use on_failure_callback and on_success_callback in DAG() function.

As per my requirement, this callbacks should be on dag level and not task level. That's why i am writing this callbacks insiled DAG() functions while declaring dag variable.

but this callback function are not being called. Same function if i call on task level , then working fine.

This is my code:

def success():
      print("successful")

dag = DAG(dag_id='callback_test',schedule_interval=None,default_args=default_args,on_success_callback=success)

    def fun1(**kwargs):
        print("function called")

    task1 = PythonOperator(
        task_id='task1',
        provide_context=True,
        python_callable=fun1,
        dag=dag
        )

    task1


问:
Convert RGB32 image to ofPixels in Open Frameworks
I am trying to display a video from a video decoder library.
The video is delivered as a byte array with RGB32 pixel format.
Meaning every pixel is represented by 32 bits.

RRBBGGFF - 8bit R, 8bit G, 8bit B, 8bit 0xFF.

Similar to QT Qimage Format_RGB32.

I thnik I need to convert the pixel array to ofPixels, Then load the pixels to ofTexture.
Then I can draw the texture.

I don't know how to convert/set the ofPixels from this pixel format.

Any tips/ideas are so so welcome.

Thanks!

答:
Try using a ofThreadChannel as described in this example in order to avoid writing and reading from your ofTexture / ofPixels.

Then you can load a uint8_t* by doing :

by using an ofTexture's method loadFromPixels() :

// assuming data is populating the externalBuffer
void* externalBuffer;
tex.loadFromPixels((uint8*)externalData, width, height, GL_RGBA);
```

Hope this helps,

Best,

P

Body:
Try using a ofThreadChannel as described in this example in order to avoid writing and reading from your ofTexture / ofPixels.

Then you can load a uint8_t* by doing :

by using an ofTexture's method loadFromPixels() :

// assuming data is populating the externalBuffer
void* externalBuffer;
tex.loadFromPixels((uint8*)externalData, width, height, GL_RGBA);

Hope this helps,

Best,

P


问:
python regex text extraction
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

```<code>West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5
</code>```

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

```<code>['West Team', 'Eastern']
</code>```

What I currently have in mind is to use regex

```<code>result = re.sub("[\n^\s$\d]", "", text).split(",")
</code>```

this code results in this:

```<code>['WestTeam','Eastern']
</code>```

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

答:
You can remove the digits and replace possible double spaced gaps with a single space.

Then split on a comma, do not keep empty values and trim the output:

```<code>import re

s = "West Team 4 , Eastern 3, test 23 99 test\n,"

res = [
    m.strip() for m in re.sub(r"[^\S\n]{2,}", " ", re.sub(r"\d+", "", s)).split(",") if m
]
print(res)
</code>```

Output

```<code>['West Team', 'Eastern', 'test test']
</code>```

See a Python demo.

Title: python regex text extraction

Body:
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

['West Team', 'Eastern']

What I currently have in mind is to use regex

result = re.sub("[\n^\s$\d]", "", text).split(",")

this code results in this:

['WestTeam','Eastern']

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

Body:
You can remove the digits and replace possible double spaced gaps with a single space.

Then split on a comma, do not keep empty values and trim the output:

import re

s = "West Team 4 , Eastern 3, test 23 99 test\n,"

res = [
    m.strip() for m in re.sub(r"[^\S\n]{2,}", " ", re.sub(r"\d+", "", s)).split(",") if m
]
print(res)

Output

['West Team', 'Eastern', 'test test']

See a Python demo.


问:
QuickBlox: Undefined symbols for architecture arm64
I am using Xcode 6.4 and installed QuickBlox framework using cocoapods. After using the framework I am getting some errors like

```<code>Undefined symbols for architecture arm64
"_OBJC_CLASS_$_QBSettings", referenced from:
      objc-class-ref in AppDelegate.o
</code>```

Would anyone please help me to figure out. I am not able to fix this. Any suggestion will be appreciable.

Update:

Below is my pod file

```<code>pod 'QuickBlox'
target 'myApp' do
</code>```

答:
After getting in touch with QuickBlox developers I was provided with the following information :

At this moment for correctly launch samples in iOS simulator you need update pod file with next snippet:

post_install do |installer|
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end
```
<p>And reinstall the pods.</p>
<p>Podfile example (update pod file for the chat sample swift):</p>
<pre class="lang-rb prettyprint-override"><code>platform :ios, "13.0"

use_frameworks!

inhibit_all_warnings!

target 'sample-chat-swift' do
    pod 'QuickBlox', '~> 2.17.10'
    pod 'SVProgressHUD'
    pod 'SDWebImage', '~> 4.4.7'
    pod 'TTTAttributedLabel', '~> 2.0.0'
end

post_install do |installer|
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end
</code>```

They promised to release a new SDK within a month.

Body:
I am using Xcode 6.4 and installed QuickBlox framework using cocoapods. After using the framework I am getting some errors like

Undefined symbols for architecture arm64
"_OBJC_CLASS_$_QBSettings", referenced from:
      objc-class-ref in AppDelegate.o

Would anyone please help me to figure out. I am not able to fix this. Any suggestion will be appreciable.

Update:

Below is my pod file

pod 'QuickBlox'
target 'myApp' do

Body:
After getting in touch with QuickBlox developers I was provided with the following information :

At this moment for correctly launch samples in iOS simulator you need update pod file with next snippet:

post_install do |installer|
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end

And reinstall the pods.

Podfile example (update pod file for the chat sample swift):

platform :ios, "13.0"

use_frameworks!

inhibit_all_warnings!

target 'sample-chat-swift' do
    pod 'QuickBlox', '~> 2.17.10'
    pod 'SVProgressHUD'
    pod 'SDWebImage', '~> 4.4.7'
    pod 'TTTAttributedLabel', '~> 2.0.0'
end

post_install do |installer|
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end

They promised to release a new SDK within a month.


问:
how to append block of file to another file
I have a requirement that I need to append block of a file to other file.

let say I have 100 lines in source file and I need to append the 50 lines from the bottom to destination file.

To navigate to the 50th line I using .readLine() of the BufferedReader.

Once I reached to 50 th line I want to append remaining content to the destination file.
I don't want to append line by line as it is consuming much time.

Please help me how to do that..

Please provide a code snippet if possible.

答:
read the file line by line and append in StringBuffer object

for eg

```<code>StringBuffer lineBuffer = new StringBuffer();
String line = "";

while((line=br.readLine())!=null){
///// any condition or anything you want to do
     lineBuffer.append(line);
}
</code>```

now after you get the lines into the stringbuffer object write this into another file

Body:
read the file line by line and append in StringBuffer object

for eg

StringBuffer lineBuffer = new StringBuffer();
String line = "";

while((line=br.readLine())!=null){
///// any condition or anything you want to do
     lineBuffer.append(line);
}

now after you get the lines into the stringbuffer object write this into another file


问:
Make ModalBottomSheetLayout always Expanded
I am using ModalBottomSheetLayout in Jetpack Compose. Whenever it is shown with modalBottomSheetState.show(), it shows HalfExpanded or Expanded depending on the height of its content. This is from the source code:

```<code>val anchors = if (sheetHeight < fullHeight / 2) {
        mapOf(
            fullHeight to Hidden,
            fullHeight - sheetHeight to Expanded
        )
    } else {
        mapOf(
            fullHeight to Hidden,
            fullHeight / 2 to HalfExpanded,
            max(0f, fullHeight - sheetHeight) to Expanded
        )
    }
    Modifier.swipeable(
        state = sheetState,
        anchors = anchors,
        orientation = Orientation.Vertical,
        enabled = sheetState.currentValue != Hidden,
        resistance = null
    )
</code>```

Then show() works like here:

```<code> internal val isHalfExpandedEnabled: Boolean
    get() = anchors.values.contains(HalfExpanded)

/**
 * Show the bottom sheet with animation and suspend until it's shown. If half expand is
 * enabled, the bottom sheet will be half expanded. Otherwise it will be fully expanded.
 *
 * @throws [CancellationException] if the animation is interrupted
 */
suspend fun show() {
    val targetValue =
        if (isHalfExpandedEnabled) HalfExpanded
        else Expanded
    animateTo(targetValue = targetValue)
}
</code>```

I wonder if we can set it to always Expanded somehow

答:
Use skipHalfExpanded</p>
```<code>val bottomSheetStatus =
    rememberModalBottomSheetState(
        ModalBottomSheetValue.Hidden,
        skipHalfExpanded = true,
    )
</code>```

Body:
I am using ModalBottomSheetLayout in Jetpack Compose. Whenever it is shown with modalBottomSheetState.show(), it shows HalfExpanded or Expanded depending on the height of its content. This is from the source code:

val anchors = if (sheetHeight < fullHeight / 2) {
        mapOf(
            fullHeight to Hidden,
            fullHeight - sheetHeight to Expanded
        )
    } else {
        mapOf(
            fullHeight to Hidden,
            fullHeight / 2 to HalfExpanded,
            max(0f, fullHeight - sheetHeight) to Expanded
        )
    }
    Modifier.swipeable(
        state = sheetState,
        anchors = anchors,
        orientation = Orientation.Vertical,
        enabled = sheetState.currentValue != Hidden,
        resistance = null
    )

Then show() works like here:

 internal val isHalfExpandedEnabled: Boolean
    get() = anchors.values.contains(HalfExpanded)

/**
 * Show the bottom sheet with animation and suspend until it's shown. If half expand is
 * enabled, the bottom sheet will be half expanded. Otherwise it will be fully expanded.
 *
 * @throws [CancellationException] if the animation is interrupted
 */
suspend fun show() {
    val targetValue =
        if (isHalfExpandedEnabled) HalfExpanded
        else Expanded
    animateTo(targetValue = targetValue)
}

I wonder if we can set it to always Expanded somehow

Body:
Use skipHalfExpanded

val bottomSheetStatus =
    rememberModalBottomSheetState(
        ModalBottomSheetValue.Hidden,
        skipHalfExpanded = true,
    )


问:
How and where to validate uniqueness of attribute/property in ASP.NET Core MVC using Entity Framework Core 6
I want to check, that users table records does not have specific email already stored.

If there is, then ModelState.IsValid returns false in controller action.

I understand need of unique constraint and I understand issues with race conditions. Those are not my concern right now.

At this point I just want to make ModelState.IsValid to return false after querying data in right place and making model invalid.

Should I implement such validation:

in DbContext?

in my entity classes (User / Company etc.)?

in SomeCustomValidation class?

directly in controller (since there I can already query the database...)

somewhere else...

And nice bonus would be create solution reusable across all entities :)

How should I do it?

答:
better way is that you check it before every insert or update by :

```<code>if(db.Table.Any(x => x.UniqueCloumn == newValue))
    error = "this record is already exist"
else
{
    db.Table.Add(newObject);
    db.Savechanges()
}
</code>```

also there is some approach for reusable code that I do not recommend :
https://www.codeproject.com/Tips/1143215/Validate-a-Unique-Constraint-at-dbContext-Validate

Body:
better way is that you check it before every insert or update by :

if(db.Table.Any(x => x.UniqueCloumn == newValue))
    error = "this record is already exist"
else
{
    db.Table.Add(newObject);
    db.Savechanges()
}

also there is some approach for reusable code that I do not recommend :
https://www.codeproject.com/Tips/1143215/Validate-a-Unique-Constraint-at-dbContext-Validate


问:
How can I loop through IEnumerble<Card> CreateDeck(); and print to the console?
So I recently wrote an algorithm which I posted on stack exchange/code review and it was very well received and I got loads of improvements suggested. I'm new to C# and I don't really understand the IEnumerable interface.

How do I print to the console my entire deck?

The code below is a method, if I call the method there is nothing else I can do... Or can I?

One of the Methods I was suggested to use is:

```<code>public IEnumerable<Card> CreateDeck()
{
  var deck = new List<Card>();

  foreach(var value in Enum.GetValues<CardValue>())
    foreach (var suit in Enum.GetValues<CardSuit>())
      deck.Add(new Card(value, suit));

  return deck;
}
</code>```

My Enums for Cards

```<code>public enum CardValue {Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two};
public enum CardSuit {Spades, Clubs, Hearts, Diamonds};
</code>```

Creating a Card

```<code>public struct Card
{
  public CardValue Value { get; }
  public CardSuit Suit { get; }

  public Card(CardValue value, CardSuit suit)
  {
    Value = value;
    Suit = suit;
  }

  public override string ToString()
  {
    return $"{Value} of {Suit}";
  }
}

</code>```

答:
Just use a simple foreach loop:

```<code>foreach (var card in CreateDeck()) Console.WriteLine(card);
</code>```

This uses the Console.WriteLine(object) overload, that will internally call the ToString() method defined on Card.

As an aside, you could reduce memory usage in your CreateDeck method by using yield return instead of allocating a list:

```<code>public IEnumerable<Card> CreateDeck()
{
    foreach (var value in Enum.GetValues<CardValue>())
    {
        foreach (var suit in Enum.GetValues<CardSuit>())
        {
            yield return new Card(value, suit);
        }
    }
}
</code>```

This way, Cards are created on-demand as you iterate, and immediately become eligible for garbage collection after they leave scope.

If you find that you need a list, you can always do this:

```<code>var cards = CreateDeck().ToList();
</code>```

Body:
So I recently wrote an algorithm which I posted on stack exchange/code review and it was very well received and I got loads of improvements suggested. I'm new to C# and I don't really understand the IEnumerable interface.

How do I print to the console my entire deck?

The code below is a method, if I call the method there is nothing else I can do... Or can I?

One of the Methods I was suggested to use is:

public IEnumerable<Card> CreateDeck()
{
  var deck = new List<Card>();

  foreach(var value in Enum.GetValues<CardValue>())
    foreach (var suit in Enum.GetValues<CardSuit>())
      deck.Add(new Card(value, suit));

  return deck;
}

My Enums for Cards

public enum CardValue {Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two};
public enum CardSuit {Spades, Clubs, Hearts, Diamonds};

Creating a Card

public struct Card
{
  public CardValue Value { get; }
  public CardSuit Suit { get; }

  public Card(CardValue value, CardSuit suit)
  {
    Value = value;
    Suit = suit;
  }

  public override string ToString()
  {
    return $"{Value} of {Suit}";
  }
}

Body:
Just use a simple foreach loop:

foreach (var card in CreateDeck()) Console.WriteLine(card);

This uses the Console.WriteLine(object) overload, that will internally call the ToString() method defined on Card.

As an aside, you could reduce memory usage in your CreateDeck method by using yield return instead of allocating a list:

public IEnumerable<Card> CreateDeck()
{
    foreach (var value in Enum.GetValues<CardValue>())
    {
        foreach (var suit in Enum.GetValues<CardSuit>())
        {
            yield return new Card(value, suit);
        }
    }
}

This way, Cards are created on-demand as you iterate, and immediately become eligible for garbage collection after they leave scope.

If you find that you need a list, you can always do this:

var cards = CreateDeck().ToList();


问:
Unit test running forever for call back method in C#
Following is the method to receive the message on RabbitMq Queue. Method works fine but the unit testing this method has problem mentioned below

```<code>      public void GetMessage(Action<string> action)
    {
        //create a connection factory
        var factory = new ConnectionFactory();

        if (_connectionString != null)
        {
            //assign connection string of rabbitmq
            factory.Uri = new Uri(_connectionString);
        }

        //create connection and channel from connectionfactory
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {

            //declare the queque on the channel
            channel.QueueDeclare(queue: _queque,
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            //create consumer using the channel
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                //When message is recieved on the consumer this will be triggered
                var body = ea.Body.ToArray();
                _message = Encoding.UTF8.GetString(body);

                //call the method passed by the caller method
                action(_message);
            };

            //add the consumer on this channel
            channel.BasicConsume(queue: _queque,
                                 autoAck: true,
                                 consumer: consumer);

            Console.ReadLine();
        }

    }
</code>```

How to write a unit test test above message. Below unit test loading forever inside the call back method and the execution never goes to Assert.Equal line.

```<code>      [Fact]
    public async Task AddMessageAsync_ShouldAddToQueue()
    {
        //Arrange
        string messageToSend = "Test";
        string recievedMessage = null;
        var queue = GetQueueManager();

        queue.Message = messageToSend;

        await queue.AddMessageAsync();

        //Act
        queue.GetMessage((string message) =>
        {
            //Hit here and recieved the message but does not exist from this method
            recievedMessage = message;
        });

        //Assert
        Assert.Equal(messageToSend, recievedMessage);
    }
</code>```

答:
One way to adress the issue would be a synchronization barrier.
Here is an example: (There may be more efficient ways, though.)

```<code>... // Your code with some changes:
//create connection and channel from connectionfactory
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {

            //declare the queque on the channel
            channel.QueueDeclare(queue: _queque,
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            // Set up a synchronization barrier.
            using (var barrier = new ManualResetEventSlim(false))
            {

                //create consumer using the channel
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                //When message is recieved on the consumer this will be triggered
                    var body = ea.Body.ToArray();
                    _message = Encoding.UTF8.GetString(body);

                    try // you don't want "injected" code to break yours.
                    {
                        //call the method passed by the caller method
                        action(_message);
                    }
                    catch(Exception)
                    {
                        // at least log it!
                    }
                    finally
                    {
                        barrier.Set(); // Signal Event fired.
                    }
                };

                //add the consumer on this channel
                channel.BasicConsume(queue: _queque,
                                     autoAck: true,
                                     consumer: consumer);

                barrier.Wait(); // Wait for Event to fire.
            }
        }
</code>```

I would imagine that the RabbitMQ API has had an update to support async/await instead of event-based? If so, then using that would of course be preferable.

If not: You may also want to explore Tasks and the Event-based Asynchronous Pattern (EAP)

Body:
Following is the method to receive the message on RabbitMq Queue. Method works fine but the unit testing this method has problem mentioned below

      public void GetMessage(Action<string> action)
    {
        //create a connection factory
        var factory = new ConnectionFactory();

        if (_connectionString != null)
        {
            //assign connection string of rabbitmq
            factory.Uri = new Uri(_connectionString);
        }

        //create connection and channel from connectionfactory
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {

            //declare the queque on the channel
            channel.QueueDeclare(queue: _queque,
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            //create consumer using the channel
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                //When message is recieved on the consumer this will be triggered
                var body = ea.Body.ToArray();
                _message = Encoding.UTF8.GetString(body);

                //call the method passed by the caller method
                action(_message);
            };

            //add the consumer on this channel
            channel.BasicConsume(queue: _queque,
                                 autoAck: true,
                                 consumer: consumer);

            Console.ReadLine();
        }

    }

How to write a unit test test above message. Below unit test loading forever inside the call back method and the execution never goes to Assert.Equal line.

      [Fact]
    public async Task AddMessageAsync_ShouldAddToQueue()
    {
        //Arrange
        string messageToSend = "Test";
        string recievedMessage = null;
        var queue = GetQueueManager();

        queue.Message = messageToSend;

        await queue.AddMessageAsync();

        //Act
        queue.GetMessage((string message) =>
        {
            //Hit here and recieved the message but does not exist from this method
            recievedMessage = message;
        });

        //Assert
        Assert.Equal(messageToSend, recievedMessage);
    }

Body:
One way to adress the issue would be a synchronization barrier.
Here is an example: (There may be more efficient ways, though.)

... // Your code with some changes:
//create connection and channel from connectionfactory
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {

            //declare the queque on the channel
            channel.QueueDeclare(queue: _queque,
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            // Set up a synchronization barrier.
            using (var barrier = new ManualResetEventSlim(false))
            {

                //create consumer using the channel
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                //When message is recieved on the consumer this will be triggered
                    var body = ea.Body.ToArray();
                    _message = Encoding.UTF8.GetString(body);

                    try // you don't want "injected" code to break yours.
                    {
                        //call the method passed by the caller method
                        action(_message);
                    }
                    catch(Exception)
                    {
                        // at least log it!
                    }
                    finally
                    {
                        barrier.Set(); // Signal Event fired.
                    }
                };

                //add the consumer on this channel
                channel.BasicConsume(queue: _queque,
                                     autoAck: true,
                                     consumer: consumer);

                barrier.Wait(); // Wait for Event to fire.
            }
        }

I would imagine that the RabbitMQ API has had an update to support async/await instead of event-based? If so, then using that would of course be preferable.

If not: You may also want to explore Tasks and the Event-based Asynchronous Pattern (EAP)


问:
delete element in Vue JS in checkbox
Adding new elements into array evento works fine when checking the checkbox, but how can I delete an element when I uncheck the checkbox?

Play with it:
https://codesandbox.io/s/heuristic-currying-uqib1?file=/index.html

v-model is not an option because I'm working with a very complex structure that comes from GraphQL, and a vuex store

```<code>    <div id="myapp">
      <!-- Checkboxes list -->
      <ul>
        <li v-for="lang in languages">
          <input
            type="checkbox"
            v-bind:value="returnArray(lang)"
            v-bind:checked="evento.includes(lang)"
            v-on:input="evento = $event.target._value"
          />{{ lang }}
        </li>
      </ul>
      evento : {{ evento }}
    </div>

    <script>
      var app = new Vue({
        el: "#myapp",
        data: {
          languages: [
            "PHPPPPPPPPPPP",
            "Vue.js",
            "Java",
            "C",
            "AngularJS",
            "jQuery",
            "JavaScript"
          ],
          evento: []
        },
        methods: {
          returnArray: function (lang) {
            console.log("lang: " + lang);
            let arreglo = [];
            console.log("evento: " + JSON.stringify(this.evento));
            // agregar dentro del arreglo la seccion si no existe dentrol del evento
            // add language into array if does not exist in evento
            if (!this.evento.includes(lang)) {
              arreglo.push.apply(arreglo, this.evento);
              arreglo.push(lang);
              console.log("ENTRO!");
            }
            console.log("arreglo: " + JSON.stringify(arreglo));
            console.log("+++++++++++++: ");
            return arreglo;
          }
        }
      });
    </script>
</code>```

答:
The best solution =>

```<code>    deleteUsers() {
      this.users = this.users.filter(user => {
        if (user.selected === false) {
          return user;
        }
      });

</code>```

In my case, for deleting by checkbox, this helped me ... in the users array there is a line selected : false.

```<code>  for (let i = 0; i < this.users.length; i++) {
        if (this.users[i].selected === true) {
          console.log(i)
          this.users.splice(i, 1);
        }
      }
</code>```

Also maybe this will help you.
But this is without the selected one in the users array.. And another array of the selected

```<code> if (this.selected.length === 0) {
        this.msg = 'Please select to remove!!!'
      } else {
        this.msg = ' '
        for (let i = 0; i < this.selected.length; i++) {
          this.users.splice(this.selected, 1);
        }
        this.selected = []
        this.selectAll = false
      }
      for (let i = 0; i < this.selected.length; i++) {
        this.users.splice(this.selected[i], 1);
      }
</code>```

Title: delete element in Vue JS in checkbox

Body:
Adding new elements into array evento works fine when checking the checkbox, but how can I delete an element when I uncheck the checkbox?

Play with it:
https://codesandbox.io/s/heuristic-currying-uqib1?file=/index.html

v-model is not an option because I'm working with a very complex structure that comes from GraphQL, and a vuex store

          <input
            type="checkbox"
            v-bind:value="returnArray(lang)"
            v-bind:checked="evento.includes(lang)"
            v-on:input="evento = $event.target._value"
          />{{ lang }}

      evento : {{ evento }}

Body:
The best solution =>

    deleteUsers() {
      this.users = this.users.filter(user => {
        if (user.selected === false) {
          return user;
        }
      });

In my case, for deleting by checkbox, this helped me ... in the users array there is a line selected : false.

  for (let i = 0; i < this.users.length; i++) {
        if (this.users[i].selected === true) {
          console.log(i)
          this.users.splice(i, 1);
        }
      }

Also maybe this will help you.
But this is without the selected one in the users array.. And another array of the selected

 if (this.selected.length === 0) {
        this.msg = 'Please select to remove!!!'
      } else {
        this.msg = ' '
        for (let i = 0; i < this.selected.length; i++) {
          this.users.splice(this.selected, 1);
        }
        this.selected = []
        this.selectAll = false
      }
      for (let i = 0; i < this.selected.length; i++) {
        this.users.splice(this.selected[i], 1);
      }


答:
Implement GetEnumerator method in CardDeck class or any class as

    class Program
    {
        static void Main(string[] args)
        {
            var cd = new CardDeck();
            cd.cards = new List<Card>()
                {
                    new Card(CardValue.Ace, CardSuit.Spades),
                    new Card(CardValue.Five, CardSuit.Clubs)
                };

            foreach (var c in cd)
            {
                Console.WriteLine(c);
            }

        }
    }

```
<p>Above is example how to use in look</p>
<p>OP Code</p>
<pre class="lang-cs prettyprint-override"><code>
    public enum CardValue { Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two };
    public enum CardSuit { Spades, Clubs, Hearts, Diamonds };

    public struct Card
    {
        public CardValue Value { get; }
        public CardSuit Suit { get; }

        public Card(CardValue value, CardSuit suit)
        {
            Value = value;
            Suit = suit;
        }

        public override string ToString()
        {
            return $"{Value} of {Suit}";
        }
    }

</code>```

IEnumerable implementation

    class CardDeck
    {
        public List<Card> cards;

        public IEnumerator<Card> GetEnumerator()
        {
            foreach (var contact in cards)
                yield return contact;
        }
    }
```

Title: How can I loop through IEnumerble<Card> CreateDeck(); and print to the console?

Body:
Implement GetEnumerator method in CardDeck class or any class as

    class Program
    {
        static void Main(string[] args)
        {
            var cd = new CardDeck();
            cd.cards = new List<Card>()
                {
                    new Card(CardValue.Ace, CardSuit.Spades),
                    new Card(CardValue.Five, CardSuit.Clubs)
                };

            foreach (var c in cd)
            {
                Console.WriteLine(c);
            }

        }
    }

Above is example how to use in look

OP Code

    public enum CardValue { Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two };
    public enum CardSuit { Spades, Clubs, Hearts, Diamonds };

    public struct Card
    {
        public CardValue Value { get; }
        public CardSuit Suit { get; }

        public Card(CardValue value, CardSuit suit)
        {
            Value = value;
            Suit = suit;
        }

        public override string ToString()
        {
            return $"{Value} of {Suit}";
        }
    }

IEnumerable implementation

    class CardDeck
    {
        public List<Card> cards;

        public IEnumerator<Card> GetEnumerator()
        {
            foreach (var contact in cards)
                yield return contact;
        }
    }


问:
LambdaExpression.CompileToMethod not working with System.Type?
I am trying to make a programming language. The problem occurs when trying compile lambda into a module, more precisely when trying to convert from string to t(some type) using Convert.ChangeType instead of t.Parse. If I use LambdaExpression.Compile and using DynamicInvoke on the delegate it works, but if I use CompileToMethod and generate a module(abc.exe) and convert using Convert.ChangeType it throws an exception when I run the module:
System.TypeAccessException was unhandled
  Message=Attempt by method 'Foo.Main()' to access type 'System.RuntimeType' failed.

Method used to convert:

```<code>        private static Expression ConvertExpression<T>(Expression exprToConvert)
    {
        Type[] types = new Type[] { typeof(object), typeof(Type) };
        MethodInfo changeTypeMethod = typeof(System.Convert).GetMethod("ChangeType", types);
        Expression convertedExprAsObject = Expression.Call(changeTypeMethod, exprToConvert, Expression.Constant(typeof(T)));
        return Expression.Convert(convertedExprAsObject, typeof(T));
    }
</code>```

答:
I was able to reproduce the exception you got (that was the hardest part :-)).  Then I was able to see if changing the following code made a difference:

```<code> Expression.Constant(typeof(T))
</code>```

to:

```<code> Expression.Constant(typeof(T), typeof(Type))
</code>```

With just that one small change it all seemed to work correctly.  Creating the Constant as being of type Type makes everything happy.

Body:
I am trying to make a programming language. The problem occurs when trying compile lambda into a module, more precisely when trying to convert from string to t(some type) using Convert.ChangeType instead of t.Parse. If I use LambdaExpression.Compile and using DynamicInvoke on the delegate it works, but if I use CompileToMethod and generate a module(abc.exe) and convert using Convert.ChangeType it throws an exception when I run the module:
System.TypeAccessException was unhandled
  Message=Attempt by method 'Foo.Main()' to access type 'System.RuntimeType' failed.

Method used to convert:

        private static Expression ConvertExpression<T>(Expression exprToConvert)
    {
        Type[] types = new Type[] { typeof(object), typeof(Type) };
        MethodInfo changeTypeMethod = typeof(System.Convert).GetMethod("ChangeType", types);
        Expression convertedExprAsObject = Expression.Call(changeTypeMethod, exprToConvert, Expression.Constant(typeof(T)));
        return Expression.Convert(convertedExprAsObject, typeof(T));
    }

Body:
I was able to reproduce the exception you got (that was the hardest part :-)).  Then I was able to see if changing the following code made a difference:

 Expression.Constant(typeof(T))

to:

 Expression.Constant(typeof(T), typeof(Type))

With just that one small change it all seemed to work correctly.  Creating the Constant as being of type Type makes everything happy.


问:
How to use an existing DB for unit testing in Django?
I have created a REST-API application using Django Rest Framework.

The API just converts the data from an existing Read-only Postgres DB to a REST- API to be consumed by the front-end.

Now I need to write some unit tests to test the application. Since there are lots of tables and views involved, I cannot create mock data and test.

Is there a way to run the tests in Django using the existing DB (Postgres) without creating any mock data ?

Note: I have read a lot of SO posts related to my problem but none of them worked as they were for old versions of Django.

答:
You can't use the Django test command for looking at production data. It always creates an empty database that is populated from fixtures in the TestCase.

This is not a good practice and should not be done. But if you want to achieve what you stated, you can try this -

```<code>DATABASES = {
  'default': {
     ...
     'TEST': {
        'NAME': 'your prod db'
     }
}
</code>```

in your settings.py file.
(This may interfere with your production database)

I will suggest you use hypothesis and factories for data production to writing tests as it will help you in the long run and will be foolproof.

What you are suggesting will not be called a test though. So it will be helpful for you to reconsider writing tests for your application.

Body:
You can't use the Django test command for looking at production data. It always creates an empty database that is populated from fixtures in the TestCase.

This is not a good practice and should not be done. But if you want to achieve what you stated, you can try this -

DATABASES = {
  'default': {
     ...
     'TEST': {
        'NAME': 'your prod db'
     }
}

in your settings.py file.
(This may interfere with your production database)

I will suggest you use hypothesis and factories for data production to writing tests as it will help you in the long run and will be foolproof.

What you are suggesting will not be called a test though. So it will be helpful for you to reconsider writing tests for your application.


问:
Spring Boot Actuator - Get your own /info data
Is there a way to get your own /info response from the service?

I am having one service that is exposed to frontend and I would like to aggregate /info responses from all of the internal services, and also add my own.

However, the only option to get my own data is to call myself ... And I would like to avoid that unnecessary HTTP call to my own service.

Can I somehow dig that information from some kind of actuator bean?

答:
If you have info endpoint enabled you can simply autowire (or obtain from the context) InfoEndpoint which will be created by InfoEndpointAutoConfiguration and call it's info method :

```<code>@Service
class Svc {

    private static final Logger LOG = LoggerFactory.getLogger(Svc.class);
    private InfoEndpoint infoEndpoint;

    Svc(final InfoEndpoint infoEndpoint) {
        this.infoEndpoint = infoEndpoint;
    }

    void perform() {
        LOG.info("{}", infoEndpoint.info());
    }

}
</code>```

Body:
If you have info endpoint enabled you can simply autowire (or obtain from the context) InfoEndpoint which will be created by InfoEndpointAutoConfiguration and call it's info method :

@Service
class Svc {

    private static final Logger LOG = LoggerFactory.getLogger(Svc.class);
    private InfoEndpoint infoEndpoint;

    Svc(final InfoEndpoint infoEndpoint) {
        this.infoEndpoint = infoEndpoint;
    }

    void perform() {
        LOG.info("{}", infoEndpoint.info());
    }

}


问:
Can't import torch in jupyter notebook
System: macOS 10.13.6
Python: 3.7
Anaconda3

I have trouble when import torch in jupyter notebook.

```<code>ModuleNotFoundError: No module named 'torch'
</code>```

Here is how I install pytorch:

```<code>conda install pytorch torchvision -c pytorch
</code>```

I've checked PyTorch is installed in my anaconda environment:

When I command python3 in my terminal and import torch, it works. But not work in jupyter notebook

I've tried:

```<code>conda update conda
conda install mkl=2018
</code>```

But still the same error.

答:
enter image description herePersonllay, I have tried different solutions and it solves my problem.
First, enter anaconda prompt and use the command conda install nb_conda.
Second, enter the env of pytorch and use conda install ipykernel.
After this, we can find in jupyter notebook, we have more language to use. Choose the language Python [conda env:conda-pytorch], then we can run code using pytorch successfully.
Hope it can help you!

Title: Can't import torch in jupyter notebook

Body:
System: macOS 10.13.6
Python: 3.7
Anaconda3

I have trouble when import torch in jupyter notebook.

ModuleNotFoundError: No module named 'torch'

Here is how I install pytorch:

conda install pytorch torchvision -c pytorch

I've checked PyTorch is installed in my anaconda environment:

When I command python3 in my terminal and import torch, it works. But not work in jupyter notebook

I've tried:

conda update conda
conda install mkl=2018

But still the same error.


问:
Filtering IDS which has the same elements in a list pandas
I have grouped columns and got the following sample dataframe. After this I would like to filter IDs which has identical elements in a list.

df

```<code>ID     Value
1      [0,0,50,0,0]
2      [0,0,0,0,0,0,0]
3      [0,100,0,0,50]
4      [0,0,0,0,0]
</code>```

I would like to filter IDs which has same elements in a list under Value columns and those elements must be only 0s.

The expected output is just IDs and it should be 2 and 4.

Can anyone help on this?

答:
You can compare sets by set([0]):

```<code>df1 = df[df['Value'].map(set).eq(set([0]))]
print (df1)
   ID                  Value
1   2  [0, 0, 0, 0, 0, 0, 0]
3   4        [0, 0, 0, 0, 0]
</code>```

If need filter only same values per list compare lengths in Series.str.len:

```<code>df2 = df[df['Value'].map(set).str.len().eq(1)]
</code>```

Body:
I have grouped columns and got the following sample dataframe. After this I would like to filter IDs which has identical elements in a list.

df

ID     Value
1      [0,0,50,0,0]
2      [0,0,0,0,0,0,0]
3      [0,100,0,0,50]
4      [0,0,0,0,0]

I would like to filter IDs which has same elements in a list under Value columns and those elements must be only 0s.

The expected output is just IDs and it should be 2 and 4.

Can anyone help on this?

Body:
You can compare sets by set([0]):

df1 = df[df['Value'].map(set).eq(set([0]))]
print (df1)
   ID                  Value
1   2  [0, 0, 0, 0, 0, 0, 0]
3   4        [0, 0, 0, 0, 0]

If need filter only same values per list compare lengths in Series.str.len:

df2 = df[df['Value'].map(set).str.len().eq(1)]


问:
(Vue.js 3 Options API) How do I access a child method?
I need to access a child component's method using Vue.js 3 with Options API. There is an answer at How to access to a child method from the parent in vue.js, but it is for Vue.js 2 and Vue.js 3 but with Composition API.

I still tried this, all in the parent component:

```<code><dropdown-list @update="updateChildComponents"></dropdown-list>
<child-component-1 ref="childComponent1Ref" :url="url"></child-component-1>
<child-component-2 ref="childComponent2Ref" :url="url"></child-component-2>
</code>```

and

```<code>methods: {
  updateChildComponents() {
    this.$refs.childComponent1Ref.childComponentMethod();
    this.$refs.childComponent2Ref.childComponentMethod();
  }
}

</code>```

This actually successfully accesses the method, but I think this may not be the right way.

Secondly, I use a prop in the child component that I update in the parent and use in the child component's method, which updates only after the second event. I think these two may be related.

Child component:

```<code>props: ['url'],
methods: {
  childComponentMethod() {
    console.log(this.url); // can access the value from the previous event
  }
}
</code>```

I appreciate any help.

答:
For communication between the parent and the children you should trasfer the value with props. In case the value is changing in the parent you must add watch.
It called 1 way binding because the parent cant see the changes in the child component.

Parent -> child = use props.

Child -> parent = use emits and on event.

```<code><script>
import { reactive,watch, computed,onMounted } from "vue";

export default {
  components: {
  },
  props: { metadata: String },
  emits: [""],
  setup(props) {
    onMounted(async () => {
    //first initilize
      if (props.metadata) {
        state.metadataName = props.metadata;
      }
    });
    //track after the changes in the parent
    watch(
      () => props.metadata,
      async (metadata) => {
        if (metadata) {

        }
      }
    );
    return {

    };
  },
};
</script>
</code>```

Body:
I need to access a child component's method using Vue.js 3 with Options API. There is an answer at How to access to a child method from the parent in vue.js, but it is for Vue.js 2 and Vue.js 3 but with Composition API.

I still tried this, all in the parent component:

<dropdown-list @update="updateChildComponents"></dropdown-list>
<child-component-1 ref="childComponent1Ref" :url="url"></child-component-1>
<child-component-2 ref="childComponent2Ref" :url="url"></child-component-2>

and

methods: {
  updateChildComponents() {
    this.$refs.childComponent1Ref.childComponentMethod();
    this.$refs.childComponent2Ref.childComponentMethod();
  }
}

This actually successfully accesses the method, but I think this may not be the right way.

Secondly, I use a prop in the child component that I update in the parent and use in the child component's method, which updates only after the second event. I think these two may be related.

Child component:

props: ['url'],
methods: {
  childComponentMethod() {
    console.log(this.url); // can access the value from the previous event
  }
}

I appreciate any help.

Body:
For communication between the parent and the children you should trasfer the value with props. In case the value is changing in the parent you must add watch.
It called 1 way binding because the parent cant see the changes in the child component.

Parent -> child = use props.

Child -> parent = use emits and on event.

<script>
import { reactive,watch, computed,onMounted } from "vue";

export default {
  components: {
  },
  props: { metadata: String },
  emits: [""],
  setup(props) {
    onMounted(async () => {
    //first initilize
      if (props.metadata) {
        state.metadataName = props.metadata;
      }
    });
    //track after the changes in the parent
    watch(
      () => props.metadata,
      async (metadata) => {
        if (metadata) {

        }
      }
    );
    return {

    };
  },
};
</script>


问:
Pandas to_sql() CREATE TABLE permission denied
I am trying to write a df to an existing table with pandas.to_sql with this code:

```<code>import sqlalchemy

#CREATE CONNECTION
constring = "mssql+pyodbc://UID:PASSWORD@SERVER/DATABASE?driver=SQL Server"
dbEngine = sqlalchemy.create_engine(constring, fast_executemany=True, connect_args={'connect_timeout':10}, echo=False)

#WRITE INTO TABLE
df.to_sql(con=dbEngine, schema="dbo", name="target_table", if_exists="replace", index=False, chunksize=1000)
</code>```

But it gives the following error:

```<code>ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE TABLE permission denied in database 'database'. (262) (SQLExecDirectW)")
[SQL:
CREATE TABLE [target_table] (
[chLocalIndustryCode] VARCHAR(max) NULL,
[vcLocalIndustryDesc] VARCHAR(max) NULL,
[chLocalSectorCode] VARCHAR(max) NULL,
[vcLocalSectorDesc] VARCHAR(max) NULL,
[chLocalClusterCode] VARCHAR(max) NULL,
[vcLocalClusterDesc] VARCHAR(max) NULL,
[chLocalMegaClusterCode] VARCHAR(max) NULL,
[vcLocalMegaClusterDesc] VARCHAR(max) NULL)
]

(Background on this error at: https://sqlalche.me/e/14/f405)
</code>```

I have checked the connection and works properly when reading the table , so I assume the problem is with pandas to_sql() function. I have also tried writing into the table with a cursor, but takes to long.

I am using pandas 1.3.4

Is there any way of fixing this error or any alternative to pd.to_sql() function that I can use to increase writing speed?

答:
You might need to add create permission to the SQL Server user. You can follow below steps from the link:

To add a Windows user that has the login “domainname \username” to the
sysadmin fixed server role

a. Log on to the computer using the credentials for the
domainname\username account.

b. Click the Start button, point to All Programs, click Microsoft SQL
Server, right-click SQL Server Management Studio, and then click Run
as administrator. ps: "Run As Administrator" option elevates the user
permissions In the User Access Control dialog box, click Continue.

c. In SQL Server Management Studio, connect to an instance of SQL
Server.

d. Click Security, right-click Logins, and then click New Login.

e. In the Login name box, enter the user name.

f. In the Select a page pane, click Server Roles, select the sysadmin
check box, and then click OK.

Body:
I am trying to write a df to an existing table with pandas.to_sql with this code:

import sqlalchemy

#CREATE CONNECTION
constring = "mssql+pyodbc://UID:PASSWORD@SERVER/DATABASE?driver=SQL Server"
dbEngine = sqlalchemy.create_engine(constring, fast_executemany=True, connect_args={'connect_timeout':10}, echo=False)

#WRITE INTO TABLE
df.to_sql(con=dbEngine, schema="dbo", name="target_table", if_exists="replace", index=False, chunksize=1000)

But it gives the following error:

ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE TABLE permission denied in database 'database'. (262) (SQLExecDirectW)")
[SQL:
CREATE TABLE [target_table] (
[chLocalIndustryCode] VARCHAR(max) NULL,
[vcLocalIndustryDesc] VARCHAR(max) NULL,
[chLocalSectorCode] VARCHAR(max) NULL,
[vcLocalSectorDesc] VARCHAR(max) NULL,
[chLocalClusterCode] VARCHAR(max) NULL,
[vcLocalClusterDesc] VARCHAR(max) NULL,
[chLocalMegaClusterCode] VARCHAR(max) NULL,
[vcLocalMegaClusterDesc] VARCHAR(max) NULL)
]

(Background on this error at: https://sqlalche.me/e/14/f405)

I have checked the connection and works properly when reading the table , so I assume the problem is with pandas to_sql() function. I have also tried writing into the table with a cursor, but takes to long.

I am using pandas 1.3.4

Is there any way of fixing this error or any alternative to pd.to_sql() function that I can use to increase writing speed?


问:
Styled component react checkbox doesn't appears
Hello i have a problem with my style , checkbox does'nt appears even with a classical input i tried lot of things but bug continue .
i use styled-component, react-hook-form, typescript.

```<code>//import tools
import React, { FunctionComponent, useState } from "react";
import styled from "styled-components";
import { useForm, SubmitHandler } from "react-hook-form";

//import model will be useless with api
import Pokemon from "../models/pokemon";

//import helpers
import formatType from "../helpers/format-type";

type Props = {
  pokemon: Pokemon;
};
// type field
type Field = {
  value: any;
  error?: string;
  isValid: boolean;
};
// types form

type Inputs = {
  name: Field;
  hp: Field;
  cp: Field;
  types: Field;
};
// style

const CardHoverable = styled.div``;
const CardImage = styled.div`
  display: flex;
  justify-content: center;
  img {
    width: 250px;
  }
`;
const CardStacked = styled.div``;
const CardContent = styled.div`
  display: flex;
  justify-content: center;
  flex-direction: column;
`;
const FormGroup = styled.div`
  box-shadow: 10px 5px 5px grey;
  margin-bottom: 5px;
`;
const CardAction = styled.div``;
const Input = styled.input.attrs({ type: "checkbox" })`
  display: flex;
  position: absolute;
  width: 50px;
`;
const PokemonForm: FunctionComponent<Props> = ({ pokemon }) => {
  const [form] = useState<Inputs>({
    name: { value: pokemon.name, isValid: true },
    hp: { value: pokemon.hp, isValid: true },
    cp: { value: pokemon.cp, isValid: true },
    types: { value: pokemon.types, isValid: true },
  });

  // const changeValue = () => {
  //   setForm(onSubmit);
  // };
  //types pokemon
  const types: string[] = [
    "Plante",
    "Feu",
    "Eau",
    "Insecte",
    "Normal",
    "Electrik",
    "Poison",
    "Fée",
    "Vol",
    "Combat",
    "Psy",
  ];
  const hasType = (type: string): boolean => {
    return form.types.value.includes(type);
  };

  //form using maybe moved in other folder after
  const {
    register,
    handleSubmit,
    watch,
    // formState: { errors },
  } = useForm<Inputs>();
  const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data);
  console.log(watch("name"));
  console.log(watch("hp"));
  console.log(watch("cp"));
  console.log(watch("types"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <CardImage>
        <img src={pokemon.picture} alt={pokemon.name} />
      </CardImage>

      <CardHoverable>
        <CardStacked>
          <CardContent>
            {/* Pokemon name */}
            <FormGroup>
              <label>Nom</label>
              <input
                value={form.name.value}
                {...register("name", { required: true, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon hp */}
            <FormGroup>
              <label>Point de vie</label>
              <input
                value={form.hp.value}
                type="number"
                {...register("hp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon cp */}
            <FormGroup>
              <label>Dégâts</label>
              <input
                value={form.cp.value}
                type="number"
                {...register("cp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon types */}
            <FormGroup>
              <label>Types</label>
              {types.map((type) => (
                <div key={type}>
                  <Input
                    type={"checkbox"}
                    id={type}
                    value={type}
                    checked={hasType(type)}
                  ></Input>

                  <p className={formatType(type)}>{type}</p>
                </div>
              ))}
            </FormGroup>
          </CardContent>
          <CardAction>
            {/* Submit button */}
            <input type="submit" name="Valider" />
          </CardAction>
        </CardStacked>
      </CardHoverable>
    </form>
  );
};

export default PokemonForm;
</code>```

If you know that issue could you help me thanks.
i tried to pass in inputs .attrs the type checkbox so i don't know how resolve that situation
i have some questions is it problem with styled component or typescript or i didn't saw something that you could see.

答:
Your input has a "position:absolute" css rule. Try to add "position:relative" to FormGroup so it gets positioned relative to it.

From MDN docs : "The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static). If a positioned ancestor doesn't exist, it is positioned relative to the ICB (initial containing block — see also the W3C definition), which is the containing block of the document's root element."

Body:
Hello i have a problem with my style , checkbox does'nt appears even with a classical input i tried lot of things but bug continue .
i use styled-component, react-hook-form, typescript.

//import tools
import React, { FunctionComponent, useState } from "react";
import styled from "styled-components";
import { useForm, SubmitHandler } from "react-hook-form";

//import model will be useless with api
import Pokemon from "../models/pokemon";

//import helpers
import formatType from "../helpers/format-type";

type Props = {
  pokemon: Pokemon;
};
// type field
type Field = {
  value: any;
  error?: string;
  isValid: boolean;
};
// types form

type Inputs = {
  name: Field;
  hp: Field;
  cp: Field;
  types: Field;
};
// style

const CardHoverable = styled.div``;
const CardImage = styled.div`
  display: flex;
  justify-content: center;
  img {
    width: 250px;
  }
`;
const CardStacked = styled.div``;
const CardContent = styled.div`
  display: flex;
  justify-content: center;
  flex-direction: column;
`;
const FormGroup = styled.div`
  box-shadow: 10px 5px 5px grey;
  margin-bottom: 5px;
`;
const CardAction = styled.div``;
const Input = styled.input.attrs({ type: "checkbox" })`
  display: flex;
  position: absolute;
  width: 50px;
`;
const PokemonForm: FunctionComponent<Props> = ({ pokemon }) => {
  const [form] = useState<Inputs>({
    name: { value: pokemon.name, isValid: true },
    hp: { value: pokemon.hp, isValid: true },
    cp: { value: pokemon.cp, isValid: true },
    types: { value: pokemon.types, isValid: true },
  });

  // const changeValue = () => {
  //   setForm(onSubmit);
  // };
  //types pokemon
  const types: string[] = [
    "Plante",
    "Feu",
    "Eau",
    "Insecte",
    "Normal",
    "Electrik",
    "Poison",
    "Fée",
    "Vol",
    "Combat",
    "Psy",
  ];
  const hasType = (type: string): boolean => {
    return form.types.value.includes(type);
  };

  //form using maybe moved in other folder after
  const {
    register,
    handleSubmit,
    watch,
    // formState: { errors },
  } = useForm<Inputs>();
  const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data);
  console.log(watch("name"));
  console.log(watch("hp"));
  console.log(watch("cp"));
  console.log(watch("types"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <CardImage>

      </CardImage>

      <CardHoverable>
        <CardStacked>
          <CardContent>
            {/* Pokemon name */}
            <FormGroup>
              Nom
              <input
                value={form.name.value}
                {...register("name", { required: true, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon hp */}
            <FormGroup>
              Point de vie
              <input
                value={form.hp.value}
                type="number"
                {...register("hp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon cp */}
            <FormGroup>
              Dégâts
              <input
                value={form.cp.value}
                type="number"
                {...register("cp", { min: 1, max: 100, maxLength: 20 })}
              />
            </FormGroup>
            {/* Pokemon types */}
            <FormGroup>
              Types
              {types.map((type) => (

                  <Input
                    type={"checkbox"}
                    id={type}
                    value={type}
                    checked={hasType(type)}
                  ></Input>

{type}

              ))}
            </FormGroup>
          </CardContent>
          <CardAction>
            {/* Submit button */}
            <input type="submit" name="Valider" />
          </CardAction>
        </CardStacked>
      </CardHoverable>
    </form>
  );
};

export default PokemonForm;

If you know that issue could you help me thanks.
i tried to pass in inputs .attrs the type checkbox so i don't know how resolve that situation
i have some questions is it problem with styled component or typescript or i didn't saw something that you could see.