问:
Javascript this keyword not functioning within a function referenced by addEventListener
I'm writing a minesweeper game using HTML and Javascript which allows the user to input how big the grid is and how many mines, and the board is generated when a button is pressed. The board consists of a table with rows and cells generated in Javascript with a couple loops. Inside a loop is an addEventListener statement which is supposed to add the function to be called when a cell is clicked on.

My problem is that I'm not sure how to pass each individual cell object into the function so I can play around with it. I've been trying to use

```<code>this.setAttribute(...)
</code>```

but I'm getting an error which tells me this.setAttribute is not a function. I know that "this" is probably referring to global scope, but I'm not sure how to solve my problem then, and I've had trouble finding a solution elsewhere. Here's the relevant code:

```<code>function createGame(){
    size= document.getElementById("boardSize").value;
    //other stuff
    var table= document.createElement("table");
    table.id= "gameBoard";
    document.body.appendChild(table);
    for(var r= 1; r <= size; r++){
        var row= document.createElement("tr");
        row.setAttribute("id", "r" + r.toString(10));
        document.getElementById("gameBoard").appendChild(row);
        for(var c= 1; c <= size; c++){
            var cell= document.createElement("td");
            cell.setAttribute("id", "r" + r.toString(10) + "c" + c.toString(10));
            cell.setAttribute("class", "uClear");
            cell.innerHTML= "?";
            document.getElementById("r" + r.toString(10)).appendChild(cell);
            cell.addEventListener("click", clickClear);
        }
    }
    //other stuff
}
//the following is in global scope
function clickClear(){
    this.setAttribute("class", "kClear");   //this is undefined
    //other stuff
}
</code>```

答:
I would do it like this,by passing the element reference inside the variable:

```<code>    size= document.getElementById("boardSize").value;
    //other stuff
    var table= document.createElement("table");
    table.id= "gameBoard";
    document.body.appendChild(table);
    for(var r= 1; r <= size; r++){
        var row= document.createElement("tr");
        row.setAttribute("id", "r" + r.toString(10));
        document.getElementById("gameBoard").appendChild(row);
        for(var c= 1; c <= size; c++){
            var cell= document.createElement("td");
            cell.setAttribute("id", "r" + r.toString(10) + "c" + c.toString(10));
            cell.setAttribute("class", "uClear");
            cell.innerHTML= "?";
            document.getElementById("r" + r.toString(10)).appendChild(cell);
            cell.addEventListener("click",() => clickClear(cell)); // arrow function
        }
    }
    //other stuff
}
//the following is in global scope
function clickClear(element){
    element.setAttribute("class", "kClear");   // pass the element reference instead
    //other stuff
}
</code>```

Also, you might want to check my blog about creating a PWA minesweeper app using Web components:
https://onecompileman.com/blogs/10

Body:
I'm writing a minesweeper game using HTML and Javascript which allows the user to input how big the grid is and how many mines, and the board is generated when a button is pressed. The board consists of a table with rows and cells generated in Javascript with a couple loops. Inside a loop is an addEventListener statement which is supposed to add the function to be called when a cell is clicked on.

My problem is that I'm not sure how to pass each individual cell object into the function so I can play around with it. I've been trying to use

this.setAttribute(...)

but I'm getting an error which tells me this.setAttribute is not a function. I know that "this" is probably referring to global scope, but I'm not sure how to solve my problem then, and I've had trouble finding a solution elsewhere. Here's the relevant code:

function createGame(){
    size= document.getElementById("boardSize").value;
    //other stuff
    var table= document.createElement("table");
    table.id= "gameBoard";
    document.body.appendChild(table);
    for(var r= 1; r <= size; r++){
        var row= document.createElement("tr");
        row.setAttribute("id", "r" + r.toString(10));
        document.getElementById("gameBoard").appendChild(row);
        for(var c= 1; c <= size; c++){
            var cell= document.createElement("td");
            cell.setAttribute("id", "r" + r.toString(10) + "c" + c.toString(10));
            cell.setAttribute("class", "uClear");
            cell.innerHTML= "?";
            document.getElementById("r" + r.toString(10)).appendChild(cell);
            cell.addEventListener("click", clickClear);
        }
    }
    //other stuff
}
//the following is in global scope
function clickClear(){
    this.setAttribute("class", "kClear");   //this is undefined
    //other stuff
}

Body:
I would do it like this,by passing the element reference inside the variable:

    size= document.getElementById("boardSize").value;
    //other stuff
    var table= document.createElement("table");
    table.id= "gameBoard";
    document.body.appendChild(table);
    for(var r= 1; r <= size; r++){
        var row= document.createElement("tr");
        row.setAttribute("id", "r" + r.toString(10));
        document.getElementById("gameBoard").appendChild(row);
        for(var c= 1; c <= size; c++){
            var cell= document.createElement("td");
            cell.setAttribute("id", "r" + r.toString(10) + "c" + c.toString(10));
            cell.setAttribute("class", "uClear");
            cell.innerHTML= "?";
            document.getElementById("r" + r.toString(10)).appendChild(cell);
            cell.addEventListener("click",() => clickClear(cell)); // arrow function
        }
    }
    //other stuff
}
//the following is in global scope
function clickClear(element){
    element.setAttribute("class", "kClear");   // pass the element reference instead
    //other stuff
}

Also, you might want to check my blog about creating a PWA minesweeper app using Web components:
https://onecompileman.com/blogs/10


来源: stackexchange

问:
Python: How to print multiplication table based on two inputs?
I'm attempting to write a program called multChart(x,y) that prints a multiplication table based on two inputs, one specifying the number of rows to print and another specifying the number of columns. So it would look like this:

```<code>>>> multChart(4,5):
1: 1 2 3 4 5
2: 2 4 6 8 10
3: 3 6 9 12 15
4: 4 8 12 16 20
</code>```

Here's what my current code looks like:

```<code>def multChart(x,y):
    for i in range(1,x+1):
        print(i,':',i*1,i*2,i*3,i*4,i*5)
</code>```

I'm totally stuck on how to implement the y value. I also know there should be a better way of printing the multiplication instead of i * multiples of five, but I'm not sure what loop to use. Any help would be greatly appreciated.

答:
```<code>
def multChart(x,y):
    for i in range(1,x+1):
        print(i,':',*list(map(lambda y: i*y,list(range(1,y+1 ) ) ) ) )
multChart(4,5)

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to write a program called multChart(x,y) that prints a multiplication table based on two inputs, one specifying the number of rows to print and another specifying the number of columns. So it would look like this:

>>> multChart(4,5):
1: 1 2 3 4 5
2: 2 4 6 8 10
3: 3 6 9 12 15
4: 4 8 12 16 20

Here's what my current code looks like:

def multChart(x,y):
    for i in range(1,x+1):
        print(i,':',i*1,i*2,i*3,i*4,i*5)

I'm totally stuck on how to implement the y value. I also know there should be a better way of printing the multiplication instead of i * multiples of five, but I'm not sure what loop to use. Any help would be greatly appreciated.


问:
http request with params
Is there some function that adds the request params to an http request in way that you don't have to do it "manually"? For example, if I want to put "user": "x" as param of my request, in a way to achieve something like

```<code>http:test/testing?user=x
</code>```

how can I do it?

答:
It seems like a more direct way to do it is to use Uri.http.

```<code>// http://example.org/path?q=dart.
Uri.http("example.org", "/path", { "q" : "dart" });
</code>```

Notes:

The query parameters are { "q" : "dart" }.

Uri.https() works the same way.

Title: http request with params

Body:
Is there some function that adds the request params to an http request in way that you don't have to do it "manually"? For example, if I want to put "user": "x" as param of my request, in a way to achieve something like

http:test/testing?user=x

how can I do it?

Body:
It seems like a more direct way to do it is to use Uri.http.

// http://example.org/path?q=dart.
Uri.http("example.org", "/path", { "q" : "dart" });

Notes:

The query parameters are { "q" : "dart" }.

Uri.https() works the same way.


问:
Can I instantiate multiple instances of one program based on different configuration files?
I need to be able to run different instances of the same program structure that each uses different configuration files in JSON. I have several configuration files in JSON, and for each of them I would need to run different instances of the same program. Each instance would need to run separately and based on referenced configuration have some processes. Is this possible with python, and if yes could instantiation be automatic, or could some external request trigger instantiation of that program with specific configuration file?

I also need to be able to distoy it after the job is done. Manually or automatically.

P.S. There should be only one file, that would be called.

答:
Use argparse and pass in the config file as a parameter. That would allow multiple executions with different configs.

```<code>python myscript.py --config config1.json
python myscript.py --config configTWO.json
python myscript.py --config "C:\Users\you\Documents\superconfig.json"
</code>```

You can also do it with sys.argv.

And since you're passing in the json file name, use argparse's FileType objects.

Body:
Use argparse and pass in the config file as a parameter. That would allow multiple executions with different configs.

python myscript.py --config config1.json
python myscript.py --config configTWO.json
python myscript.py --config "C:\Users\you\Documents\superconfig.json"

You can also do it with sys.argv.

And since you're passing in the json file name, use argparse's FileType objects.


答:
```<code>def multChart(x,y):
    for i in range(1,x+1):
        print(i, ':', end=" ")
        for j in range(1,y+1):
            print(i*j, end =" ")
        print()

multChart(4,5)
</code>```

produces

```<code>1 : 1 2 3 4 5
2 : 2 4 6 8 10
3 : 3 6 9 12 15
4 : 4 8 12 16 20
</code>```

You can use a second for loop for the second index. Also, note that you can use end in the print statement.

Title: Python: How to print multiplication table based on two inputs?

Body:
def multChart(x,y):
    for i in range(1,x+1):
        print(i, ':', end=" ")
        for j in range(1,y+1):
            print(i*j, end =" ")
        print()

multChart(4,5)

produces

1 : 1 2 3 4 5
2 : 2 4 6 8 10
3 : 3 6 9 12 15
4 : 4 8 12 16 20

You can use a second for loop for the second index. Also, note that you can use end in the print statement.


问:
Randomly grab 3 items from an array, where the 3rd item can be a “restaurant" but does not have to be
I apologize for the poorly written title. I was not sure how exactly to write it. I have an array. I need to randomly grab three items from the array. Only one item can be a "restaurant" and the restaurant can ONLY ever go in the third position.

Let me explain with an example. here is a sample array

```<code>el 1 - restaurant = false
el 2 - restaurant = true
el 3 - restaurant = true
el 4 - restaurant = false
el 5 - restaurant = false
el 6 - restaurant = false
el 7 - restaurant = true
el 8 - restaurant = false
el 9 - restaurant = false
</code>```

My current code loops through this array and randomly grabs three items. Positions 1 and 2 can NEVER have a restaurant in them so they have to be taken from the items with the restaurant property set to false. The 3rd position can have a restaurant but I don't want it to always be a restaurant.

Here is my current code:

```<code>const amountOfLocations = 3

// have list of locations
// shuffle it
for (let i = locations.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [locations[i], locations[j]] = [locations[j], locations[i]];
}

let selectedLocations = locations.slice(0, amountOfLocations)
</code>```

My initial thought is I need to grab only 2 items from this current loop instead of 3, then using the original array remove these two items and shuffle the array up again to randomly grab one more item which will then be placed in the 3rd position.

答:
const third = shuffledArray[0]
const [first, second] = first two no-resturant item in shuffledArray.slice(1)
```

Body:
I apologize for the poorly written title. I was not sure how exactly to write it. I have an array. I need to randomly grab three items from the array. Only one item can be a "restaurant" and the restaurant can ONLY ever go in the third position.

Let me explain with an example. here is a sample array

el 1 - restaurant = false
el 2 - restaurant = true
el 3 - restaurant = true
el 4 - restaurant = false
el 5 - restaurant = false
el 6 - restaurant = false
el 7 - restaurant = true
el 8 - restaurant = false
el 9 - restaurant = false

My current code loops through this array and randomly grabs three items. Positions 1 and 2 can NEVER have a restaurant in them so they have to be taken from the items with the restaurant property set to false. The 3rd position can have a restaurant but I don't want it to always be a restaurant.

Here is my current code:

const amountOfLocations = 3

// have list of locations
// shuffle it
for (let i = locations.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [locations[i], locations[j]] = [locations[j], locations[i]];
}

let selectedLocations = locations.slice(0, amountOfLocations)

My initial thought is I need to grab only 2 items from this current loop instead of 3, then using the original array remove these two items and shuffle the array up again to randomly grab one more item which will then be placed in the 3rd position.


问:
ORACLE, CONNECT BY ROWNUM FROM DUAL, MULTIPLE COLUMN
I need 2 columns, the first column contains int numbers 1 -100 and the second column contains 001-100.

I have tried this query,
but the result is the second column is not 001 to 100

```<code>SELECT ROWNUM AS Nomor, to_char (ROWNUM) AS No_Row
FROM DUAL
CONNECT BY ROWNUM >= '001' AND ROWNUM <= 100;
</code>```

How can I do that?
Can somebody help me

答:
You can use lpad and hiearchical query as follows:

```<code>select level as rn,
       lpad(level,3,0) as rn_padded
  from dual
connect by level <= 100
</code>```

Db<>fiddle demo

Cheers!!

Body:
I need 2 columns, the first column contains int numbers 1 -100 and the second column contains 001-100.

I have tried this query,
but the result is the second column is not 001 to 100

SELECT ROWNUM AS Nomor, to_char (ROWNUM) AS No_Row
FROM DUAL
CONNECT BY ROWNUM >= '001' AND ROWNUM <= 100;

How can I do that?
Can somebody help me

Body:
You can use lpad and hiearchical query as follows:

select level as rn,
       lpad(level,3,0) as rn_padded
  from dual
connect by level <= 100

Db<>fiddle demo

Cheers!!


问:
36.0.0 is not valid sdk version. options are 43.0.0,35.0.0,33.0.0, unversioned
When I upgrade expo-cli to the latest version 36.0.0 I get this error running on android emulator "36.0.0 is not valid sdk version. options are 43.0.0,35.0.0,33.0.0, unversioned"

How to solve this

答:
Just use command
expo client:install:android to upgrade your expo client app


答:
You need another loop inside your print for looping over the y range:

```<code>def multChart(x, y):
    for i in range(1, x+1):
        print(i, ':', *[i * z for z in range(1, y+1)])
</code>```

Body:
You need another loop inside your print for looping over the y range:

def multChart(x, y):
    for i in range(1, x+1):
        print(i, ':', *[i * z for z in range(1, y+1)])


问:
Find a character based on position and match everything after in regex and logstash
This is my string:

msg: Malware/Virus detected -
  Rtf.Exploit.CVE_2017_11882-6584355-0:Message denied for
  delivery:Announcement: Holiday Tomorrow

The string above is a log line. I want to find the 3rd colon and match everything after it. The Announcement: Holiday Tomorrow is a subject title so I can have a colon or not.

I tried this so far

```<code>[^:]+$     // Holiday Tomorrow
(?<=:).*$  //  Malware/Virus detected - Rtf.Exploit.CVE_2017_11882-6584355-0:Message denied for delivery:Announcement: Holiday Tomorrow"
</code>```

I will be using the regex in my logstash config.

```<code>grok {

    match {
        "msg" => "(regex here)%{GREEDYDATA:subject}"
    }

}
</code>```

答:
Try this (but I don't know anything about lagstash):

(?:.+?:){3}(.*)  capture group 1 will have what you want

Skip past 3 .+:'s and capture the rest.

https://regex101.com/r/p2jodw/3

Body:
This is my string:

msg: Malware/Virus detected -
  Rtf.Exploit.CVE_2017_11882-6584355-0:Message denied for
  delivery:Announcement: Holiday Tomorrow

The string above is a log line. I want to find the 3rd colon and match everything after it. The Announcement: Holiday Tomorrow is a subject title so I can have a colon or not.

I tried this so far

[^:]+$     // Holiday Tomorrow
(?<=:).*$  //  Malware/Virus detected - Rtf.Exploit.CVE_2017_11882-6584355-0:Message denied for delivery:Announcement: Holiday Tomorrow"

I will be using the regex in my logstash config.

grok {

    match {
        "msg" => "(regex here)%{GREEDYDATA:subject}"
    }

}


问:
Is there a way to connect to Exchange Online using Logic Apps? Do I need to use a REST-api or EWS?
i'm quite new to Logic Apps. I got the task to make an auto reply function within Logic Apps that integrates with Exchange Online. Now I already performed this task using Outlook, but I have to be able to apply it to multiple mailboxes or even the entire company using Exchange. I'm about to get access to the Exchange Admin Center soon, but I don't really know how to start due to the fact that there is no simple way to make a connection to Exchange using Logic Apps. After some research, I think it's necessary for me to somehow make use of a REST API (I also read about the use of Exchange Web Services) to get the information I need, but my knowledge about this is quite small. I guess I'm gonna have to use a program like Postman to request information, so that I can start creating Custom Connectors to Exchange. If anybody has some understanding about this, feel free to reply and help me out! I will forever be gratefull!</p>

答:
There are several different approaches you could take to this if you (or probably they in your case) want your logic app to do all the work then you should use the Graph API rather then EWS (while its possible because its older API you'll loose marks on your assignment) have a look at http://martink.me/articles/using-microsoft-graph-in-logic-apps which covers the basics of what to do. To Get access to mailboxes tenant wide then you need to assigned Application Permission and get certificate (and store that in the KeyVault on Azure etc).

You can do this using Inbox Rules https://learn.microsoft.com/en-us/graph/api/mailfolder-post-messagerules?view=graph-rest-1.0&tabs=http and the Exchange Server will do all the work when it comes to doing the Auto-response (and has loop detection logic already) and your logic app then just need to do the Creation and management of the Rules.

But I would suggest you clarify with the person who assigned you the task whether they want the logic app to do the response (eg using the Graph API) or if its okay for the Exchange Server to do this for then  (which should be more reliable).

You can also create Rules via the Exchange Admin Center and you could probably also through in Power Automate into the mix to do Autoresponse's so I'd clarify what they want so you don't waste time building something they don't want.


问:
Why is `std::copy` 5x (!) slower than `memcpy` for reading one int from a char buffer, in my test program?
This is a follow-up to this question where I posted this program:

```<code>#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <vector>
#include <chrono>

class Stopwatch
{
public:
    typedef std::chrono::high_resolution_clock Clock;

    //! Constructor starts the stopwatch
    Stopwatch() : mStart(Clock::now())
    {
    }

    //! Returns elapsed number of seconds in decimal form.
    double elapsed()
    {
        return 1.0 * (Clock::now() - mStart).count() / Clock::period::den;
    }

    Clock::time_point mStart;
};

struct test_cast
{
    int operator()(const char * data) const
    {
        return *((int*)data);
    }
};

struct test_memcpy
{
    int operator()(const char * data) const
    {
        int result;
        memcpy(&result, data, sizeof(result));
        return result;
    }
};

struct test_memmove
{
    int operator()(const char * data) const
    {
        int result;
        memmove(&result, data, sizeof(result));
        return result;
    }
};

struct test_std_copy
{
    int operator()(const char * data) const
    {
        int result;
        std::copy(data, data + sizeof(int), reinterpret_cast<char *>(&result));
        return result;
    }
};

enum
{
    iterations = 2000,
    container_size = 2000
};

//! Returns a list of integers in binary form.
std::vector<char> get_binary_data()
{
    std::vector<char> bytes(sizeof(int) * container_size);
    for (std::vector<int>::size_type i = 0; i != bytes.size(); i += sizeof(int))
    {
        memcpy(&bytes[i], &i, sizeof(i));
    }
    return bytes;
}

template<typename Function>
unsigned benchmark(const Function & function, unsigned & counter)
{
    std::vector<char> binary_data = get_binary_data();
    Stopwatch sw;
    for (unsigned iter = 0; iter != iterations; ++iter)
    {
        for (unsigned i = 0; i != binary_data.size(); i += 4)
        {
            const char * c = reinterpret_cast<const char*>(&binary_data[i]);
            counter += function(c);
        }
    }
    return unsigned(0.5 + 1000.0 * sw.elapsed());
}

int main()
{
    srand(time(0));
    unsigned counter = 0;

    std::cout << "cast:      " << benchmark(test_cast(),     counter) << " ms" << std::endl;
    std::cout << "memcpy:    " << benchmark(test_memcpy(),   counter) << " ms" << std::endl;
    std::cout << "memmove:   " << benchmark(test_memmove(),  counter) << " ms" << std::endl;
    std::cout << "std::copy: " << benchmark(test_std_copy(), counter) << " ms" << std::endl;
    std::cout << "(counter:  " << counter << ")" << std::endl << std::endl;

}
</code>```

I noticed that for some reason std::copy performs much worse than memcpy. The output looks like this on my Mac using gcc 4.7.

```<code>g++ -o test -std=c++0x -O0 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      41 ms
memcpy:    46 ms
memmove:   53 ms
std::copy: 211 ms
(counter:  3838457856)

g++ -o test -std=c++0x -O1 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      8 ms
memcpy:    7 ms
memmove:   8 ms
std::copy: 19 ms
(counter:  3838457856)

g++ -o test -std=c++0x -O2 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      3 ms
memcpy:    2 ms
memmove:   3 ms
std::copy: 27 ms
(counter:  3838457856)

g++ -o test -std=c++0x -O3 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      2 ms
memcpy:    2 ms
memmove:   3 ms
std::copy: 16 ms
(counter:  3838457856)
</code>```

As you can see, even with -O3it is up to 5 times (!) slower than memcpy.

The results are similar on Linux.

Does anyone know why?

答:
EDIT: I leave this answer for reference, the odd timings with gcc seem to be an artifact of "code alignment" (see comments)

I was about to say that this was an implementation glitch in gcc 4 at the time, but it might be more complicated than that.
My results are (used 20000/20000 for the counters):

$ g++ -Ofast a.cpp; ./a.out
cast:      24 ms
memcpy:    47 ms
memmove:   24 ms
std::copy: 24 ms
(counter:  1787289600)

$ g++ -O3 a.cpp; ./a.out
cast:      24 ms
memcpy:    24 ms
memmove:   24 ms
std::copy: 47 ms
(counter:  1787289600)
```

<pre class="lang-sh prettyprint-override"><code>$ g++ --version
g++ (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
</code>```

Notice how copy and memcpy results swap when compiling with -O3 and -Ofast. Also memmove is not slower than either.

In clang the results are simpler:

$ clang++ -O3 a.cpp; ./a.out
cast:      26 ms
memcpy:    26 ms
memmove:   26 ms
std::copy: 26 ms
(counter:  1787289600)

$ clang++ -Ofast a.cpp; ./a.out
cast:      26 ms
memcpy:    26 ms
memmove:   26 ms
std::copy: 26 ms
(counter:  1787289600)
```

<pre class="lang-sh prettyprint-override"><code>$ clang++ --version
clang version 9.0.0-2 (tags/RELEASE_900/final)
</code>```

perf results: https://pastebin.com/BZCZiAWQ

Body:
This is a follow-up to this question where I posted this program:

#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <vector>
#include <chrono>

class Stopwatch
{
public:
    typedef std::chrono::high_resolution_clock Clock;

    //! Constructor starts the stopwatch
    Stopwatch() : mStart(Clock::now())
    {
    }

    //! Returns elapsed number of seconds in decimal form.
    double elapsed()
    {
        return 1.0 * (Clock::now() - mStart).count() / Clock::period::den;
    }

    Clock::time_point mStart;
};

struct test_cast
{
    int operator()(const char * data) const
    {
        return *((int*)data);
    }
};

struct test_memcpy
{
    int operator()(const char * data) const
    {
        int result;
        memcpy(&result, data, sizeof(result));
        return result;
    }
};

struct test_memmove
{
    int operator()(const char * data) const
    {
        int result;
        memmove(&result, data, sizeof(result));
        return result;
    }
};

struct test_std_copy
{
    int operator()(const char * data) const
    {
        int result;
        std::copy(data, data + sizeof(int), reinterpret_cast<char *>(&result));
        return result;
    }
};

enum
{
    iterations = 2000,
    container_size = 2000
};

//! Returns a list of integers in binary form.
std::vector<char> get_binary_data()
{
    std::vector<char> bytes(sizeof(int) * container_size);
    for (std::vector<int>::size_type i = 0; i != bytes.size(); i += sizeof(int))
    {
        memcpy(&bytes[i], &i, sizeof(i));
    }
    return bytes;
}

template<typename Function>
unsigned benchmark(const Function & function, unsigned & counter)
{
    std::vector<char> binary_data = get_binary_data();
    Stopwatch sw;
    for (unsigned iter = 0; iter != iterations; ++iter)
    {
        for (unsigned i = 0; i != binary_data.size(); i += 4)
        {
            const char * c = reinterpret_cast<const char*>(&binary_data[i]);
            counter += function(c);
        }
    }
    return unsigned(0.5 + 1000.0 * sw.elapsed());
}

int main()
{
    srand(time(0));
    unsigned counter = 0;

    std::cout << "cast:      " << benchmark(test_cast(),     counter) << " ms" << std::endl;
    std::cout << "memcpy:    " << benchmark(test_memcpy(),   counter) << " ms" << std::endl;
    std::cout << "memmove:   " << benchmark(test_memmove(),  counter) << " ms" << std::endl;
    std::cout << "std::copy: " << benchmark(test_std_copy(), counter) << " ms" << std::endl;
    std::cout << "(counter:  " << counter << ")" << std::endl << std::endl;

}

I noticed that for some reason std::copy performs much worse than memcpy. The output looks like this on my Mac using gcc 4.7.

g++ -o test -std=c++0x -O0 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      41 ms
memcpy:    46 ms
memmove:   53 ms
std::copy: 211 ms
(counter:  3838457856)

g++ -o test -std=c++0x -O1 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      8 ms
memcpy:    7 ms
memmove:   8 ms
std::copy: 19 ms
(counter:  3838457856)

g++ -o test -std=c++0x -O2 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      3 ms
memcpy:    2 ms
memmove:   3 ms
std::copy: 27 ms
(counter:  3838457856)

g++ -o test -std=c++0x -O3 -Wall -Werror -Wextra -pedantic-errors main.cpp
cast:      2 ms
memcpy:    2 ms
memmove:   3 ms
std::copy: 16 ms
(counter:  3838457856)

As you can see, even with -O3it is up to 5 times (!) slower than memcpy.

The results are similar on Linux.

Does anyone know why?

Body:
EDIT: I leave this answer for reference, the odd timings with gcc seem to be an artifact of "code alignment" (see comments)

I was about to say that this was an implementation glitch in gcc 4 at the time, but it might be more complicated than that.
My results are (used 20000/20000 for the counters):

$ g++ -Ofast a.cpp; ./a.out
cast:      24 ms
memcpy:    47 ms
memmove:   24 ms
std::copy: 24 ms
(counter:  1787289600)

$ g++ -O3 a.cpp; ./a.out
cast:      24 ms
memcpy:    24 ms
memmove:   24 ms
std::copy: 47 ms
(counter:  1787289600)

$ g++ --version
g++ (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008

Notice how copy and memcpy results swap when compiling with -O3 and -Ofast. Also memmove is not slower than either.

In clang the results are simpler:

$ clang++ -O3 a.cpp; ./a.out
cast:      26 ms
memcpy:    26 ms
memmove:   26 ms
std::copy: 26 ms
(counter:  1787289600)

$ clang++ -Ofast a.cpp; ./a.out
cast:      26 ms
memcpy:    26 ms
memmove:   26 ms
std::copy: 26 ms
(counter:  1787289600)

$ clang++ --version
clang version 9.0.0-2 (tags/RELEASE_900/final)

perf results: https://pastebin.com/BZCZiAWQ


问:
Re-use argument or use self
When defining a class and you need to use an argument twice is it better to keep using the argument or use the self version as soon as it is made?

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = name.upper()
</code>```

or

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = self.name.upper()
</code>```

And what about with list?

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [name,name,name]
</code>```

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [self.name,self.name,self.name]
</code>```

答:
TL;DR: In the specific cases you're describing, it doesn't matter. It's a very small trade-off between speed and safety against future changes, but there's no right answer.

If there is no massaging of the argument before it's stored in the attribute, then it doesn't really matter. Using the unqualified name will be slightly faster (self.name on CPython involves a cheap LOAD_FAST and a significantly more expensive, if still cheap in absolute terms, LOAD_ATTR; plain name for an argument is just a LOAD_FAST), so if you're 100% sure you're never going to massage the argument before storage (e.g. no self.name = int(name)), avoiding self when you can will speed initialization a bit.

That said, it's rare to be that sure, so using self.name is safer. You can always split the difference though even when massaging arguments, by doing something like:

```<code>self.name = name = int(name)
</code>```

which stores back to both the attribute and the local (via DUP_TOP and STORE_FAST, two of the cheapest op codes in CPython), so you get the same massaged value by either means, and the cheap loads from the unqualified name.

Title: Re-use argument or use self

Body:
When defining a class and you need to use an argument twice is it better to keep using the argument or use the self version as soon as it is made?

class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = name.upper()

or

class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = self.name.upper()

And what about with list?

class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [name,name,name]

class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [self.name,self.name,self.name]

Body:
TL;DR: In the specific cases you're describing, it doesn't matter. It's a very small trade-off between speed and safety against future changes, but there's no right answer.

If there is no massaging of the argument before it's stored in the attribute, then it doesn't really matter. Using the unqualified name will be slightly faster (self.name on CPython involves a cheap LOAD_FAST and a significantly more expensive, if still cheap in absolute terms, LOAD_ATTR; plain name for an argument is just a LOAD_FAST), so if you're 100% sure you're never going to massage the argument before storage (e.g. no self.name = int(name)), avoiding self when you can will speed initialization a bit.

That said, it's rare to be that sure, so using self.name is safer. You can always split the difference though even when massaging arguments, by doing something like:

self.name = name = int(name)

which stores back to both the attribute and the local (via DUP_TOP and STORE_FAST, two of the cheapest op codes in CPython), so you get the same massaged value by either means, and the cheap loads from the unqualified name.


问:
Exporting async functions with React, (getting error when running npm build)
I am re-using async functions within my React project, and I have a file called apiRequest.js which looks like this:

```<code>const axios = require('axios');
const serverURL = "http://localhost:8080"

getInfo = async function ({email}) {
  try {
      return await axios.post(serverURL, { email: email })
    } catch (error) {
      console.error(error)
    }
}

module.exports = {
    getInfo
};
</code>```

My component attempts to load the function like this, which works in dev mode:

```<code>import { getInfo } from "./../../util/apiRequest.js";
</code>```

When I run npm run build, I get this error:

Attempted import error: 'getInfo' is not exported from './../../util/apiRequest.js'.

What am I doing wrong when exporting this function?

I have tried removing the const & removing the fat arrow => but still get the same results.

答:
use the ES6 modules import and export

import axios from 'axios'

export const getInfo = async() => {

}
```

Body:
I am re-using async functions within my React project, and I have a file called apiRequest.js which looks like this:

const axios = require('axios');
const serverURL = "http://localhost:8080"

getInfo = async function ({email}) {
  try {
      return await axios.post(serverURL, { email: email })
    } catch (error) {
      console.error(error)
    }
}

module.exports = {
    getInfo
};

My component attempts to load the function like this, which works in dev mode:

import { getInfo } from "./../../util/apiRequest.js";

When I run npm run build, I get this error:

Attempted import error: 'getInfo' is not exported from './../../util/apiRequest.js'.

What am I doing wrong when exporting this function?

I have tried removing the const & removing the fat arrow => but still get the same results.


问:
Run Ansible Taks for several Groups in Parallel
We have many similar hosts that are grouped to specific types.
Every group has several hosts in it, mostly 2 to 8 for scalability within the type.
Now we need to run the same tasks/role on all these hosts.
Serialised within each group but all groups at the same time.
This should run much faster than all groups (about 10 groups currently) in a row.

Is this possible today with Ansible?

答:
Maybe.  I'm afriad I do not have the ability to test this idea, but here goes....

Let's say you have GroupA and GroupB.  To ping each host in a group serially, but have the groups run in parallel, you could try this hideous construct:

```<code>---
- hosts: localhost
  tasks:
  - ping:
    delegate_to: "{{ item }}"
    with_items: "{{ groups['groupA'] }}"
    forks: 1
    async: 0
    poll: 0
  - ping:
    delegate_to: "{{ item }}"
    with_items: "{{ groups['groupB'] }}"
    forks: 1
    async: 0
    poll: 0
</code>```

Ansible is still going to show the task output separately.

When I ran this, files were created in /home/ansible/.ansible_async.  Those files show the task start times, and it looked like it worked.  To verify, I ran shell: sleep 5 instead of ping:, and saw the start times in those files properly interleaved.

Good luck.

Body:
Maybe.  I'm afriad I do not have the ability to test this idea, but here goes....

Let's say you have GroupA and GroupB.  To ping each host in a group serially, but have the groups run in parallel, you could try this hideous construct:

---
- hosts: localhost
  tasks:
  - ping:
    delegate_to: "{{ item }}"
    with_items: "{{ groups['groupA'] }}"
    forks: 1
    async: 0
    poll: 0
  - ping:
    delegate_to: "{{ item }}"
    with_items: "{{ groups['groupB'] }}"
    forks: 1
    async: 0
    poll: 0

Ansible is still going to show the task output separately.

When I ran this, files were created in /home/ansible/.ansible_async.  Those files show the task start times, and it looked like it worked.  To verify, I ran shell: sleep 5 instead of ping:, and saw the start times in those files properly interleaved.

Good luck.


问:
border-radius not working
I'm working on a basic div and for some peculiar reason, border-radius: 7px isn't applying to it.

```<code>.panel {
  float: right;
  width: 120px;
  height: auto;
  background: #fff;
  border-radius: 7px; // not working
}
</code>```

答:
For my case, I have a dropdown list in my div container, so I can not use overflow: hidden or my dropdown list will be hidden.

Inspired by this discussion: https://twitter.com/siddharthkp/status/1094821277452234752
I use border-bottom-left-radius and border-bottom-right-radius in the child element to fix this issue.

make sure you add it the correct value for each child separately

ContentLicense: CC BY-SA 3.0

Title: border-radius not working

Body:
I'm working on a basic div and for some peculiar reason, border-radius: 7px isn't applying to it.

.panel {
  float: right;
  width: 120px;
  height: auto;
  background: #fff;
  border-radius: 7px; // not working
}


问:
How to center the pagination in jQuery Bootstrap DataTables plugin?
I am using jQuery's DataTables plugin with Bootstrap 3.1 for sorting & paginating server side contents.

This is how my table looks like

http://datatables.net/manual/styling/bootstrap-simple.html

Pagination & Sorting works fine...But by default pagination is on right side of the table. I want to show it on the center of the table. My knowledge in CSS is minimal, so I am not sure where to make changes. How to acheive this?

答:
what i did is :
style.css line 2731

```<code>.dataTables_wrapper .dataTables_paginate .paginate_button {
width: 50px; //def:35px;
height: 30px; //def:35px;
border-radius: 10%; //def:50%;
background-color: #f1f1f1;
vertical-align: top;
color: #7E7E7E!important;
margin: 0 2px;
border: 0!important;
line-height: 17px; //def:21px;
box-shadow: none!important; }
</code>```

the number will center at middle

Body:
what i did is :
style.css line 2731

.dataTables_wrapper .dataTables_paginate .paginate_button {
width: 50px; //def:35px;
height: 30px; //def:35px;
border-radius: 10%; //def:50%;
background-color: #f1f1f1;
vertical-align: top;
color: #7E7E7E!important;
margin: 0 2px;
border: 0!important;
line-height: 17px; //def:21px;
box-shadow: none!important; }

the number will center at middle


问:
How to pass a prop to all styled component css properties at once?
Instead of repeatedly picking the prop like this...

const BubbleContainer = styled.View`
  background-color: ${({ theme }) => (theme.debug ? 'white' : 'blue')};
  border-width: ${({ theme }) => (theme.debug ? '1px' : '0px')};
  color: ${({ theme }) => (theme.debug ? 'red' : 'black')};
`;
```

<p>I'd like to do it once like this (<em>pseudo code</em>)...</p>

<pre class="lang-js prettyprint-override"><code>const BubbleContainer = styled.View`
  ${({ theme }) =>
    background-color: {theme.debug ? 'white' : 'blue'};
    border-width: {theme.debug ? '1px' : '0px'};
    color: {theme.debug ? 'red' : 'black'};
  }
`;
</code>```

答:
You were close. You just need to use a backtick string for interpolation and multiline support.

```<code>const BubbleContainer = styled.View`
  ${({ theme }) => `
    background-color: ${theme.debug ? 'white' : 'blue'};
    border-width: ${theme.debug ? '1px' : '0px'};
    color: ${theme.debug ? 'red' : 'black'};
  `}
`;
</code>```

There are a lot of options, this may be a little more legible:

```<code>const BubbleContainer = styled.View`
  background-color: blue;
  border-width: 0px;
  color: black;

  ${({ theme }) => theme.debug && `
    background-color: white;
    border-width: 1px;
    color: red;
  `}
`;
</code>```

Body:
Instead of repeatedly picking the prop like this...

const BubbleContainer = styled.View`
  background-color: ${({ theme }) => (theme.debug ? 'white' : 'blue')};
  border-width: ${({ theme }) => (theme.debug ? '1px' : '0px')};
  color: ${({ theme }) => (theme.debug ? 'red' : 'black')};
`;

I'd like to do it once like this (pseudo code)...

const BubbleContainer = styled.View`
  ${({ theme }) =>
    background-color: {theme.debug ? 'white' : 'blue'};
    border-width: {theme.debug ? '1px' : '0px'};
    color: {theme.debug ? 'red' : 'black'};
  }
`;

Body:
You were close. You just need to use a backtick string for interpolation and multiline support.

const BubbleContainer = styled.View`
  ${({ theme }) => `
    background-color: ${theme.debug ? 'white' : 'blue'};
    border-width: ${theme.debug ? '1px' : '0px'};
    color: ${theme.debug ? 'red' : 'black'};
  `}
`;

There are a lot of options, this may be a little more legible:

const BubbleContainer = styled.View`
  background-color: blue;
  border-width: 0px;
  color: black;

  ${({ theme }) => theme.debug && `
    background-color: white;
    border-width: 1px;
    color: red;
  `}
`;


问:
When using the K-Means Clustering Algorithm, is it possible to have a set of data which results in an Infinite Loop?
This Question is more Theoretical, and not specifically trying to problem-solve.

I recently was introduced to the K-Means Clustering algorithm, and unsupervised machine learning algorithm, and I was intrigued by the though that one some sets of data, even if completely random, the average centroids drawn could keep changing through each iteration.

Example:

What I am trying to show here, is, imagine if the program flipped between iteration 6, to iteration 9, and kept doing this forever.

I have had my code randomly hang before using K-Means, so I don't believe this is impossible, but please let me know if this is a known occurrence, or if it is impossible due to the nature of the algorithm.

If you need more information just ask me in a comment. Using Python 3.7

答:
tl;dr No, a K-means algorithm always has an end point if the algorithm is coded correctly.

Explanation:

The ideal way to think about this is not in the sense of what datapoints would cause issues, but rather about how kmeans is working in the broader sense of things. The k-means algorithm is always working in a finite space. For N data points, there are only N ^ k distinct arrangements for the data points. (This number can be pretty large, but is still finite)

Secondly, a k-means algorithm is always optimizing a loss function, based on the sum of squared distances between each data point and it's assigned cluster center. This means two very important things: Each of the N ^ k distinct arrangements can be arranged in an ascending/descending order of minimum loss to maximum loss. Also, the K-means algorithm will never go from a state of lower net loss to a higher net loss.

These two conditions guarantee that the algorithm will always tend towards the minimum loss arrangement in a finite space, thus ensuring that it has an end.

The last edge case: What if more than one minimum state has equal loss? This is a highly unlikely scenario, but can cause issues if and only if the algorithm is coded poorly for tie breakers. Essentially, the only way this can cause a cycle is if a data point has equal distance for two clusters, and is allowed to change clusters away from it's current cluster even on equal distance. Suffice to say, the algorithms are generally coded so that the data points never swap on a tie, or in some other deterministic manner, thus avoiding this scenario entirely.


问:
Call node.setSelected(true) but row is not selected from React
My React application has a "Merge" button, which calls a web service to combine 2 rows in the ag-grid into one row.

After calling the web service, I want to re-render the grid, with the first row selected.  I call my ReRender function to do this.  The function calls my web service to re-retrieve the data, then it tries to select the row.

No errors happen, the data is re-rendered,  the console shows I did find the matching row to select, so I call node.setSelection(true), but the row is not selected.  What can I do?  The grid is paginated.

Code:

```<code>    ReRender = (inventorykey) => {
            console.log(inventorykey)
            this.rowChecked = []
            fetch( 'http://apsrp07823.svr.com:8088/mpa/getCockpit?userkey=' + this.state.userkey )
            .then(res=>res.json())
            .then(resj=>{
                if (resj.rows && resj.rows.length>0) {
                    this.setState({rowData:resj.rows})
                }
            })
            .then(
                    console.log('invKey loop:'),
                    this.gridApi.forEachNode( (node) => {
                        if ( node.data.inventorykey === inventorykey ) {
                        console.log('Found it!')
                        node.setSelected(true);}
                        else{console.log('no '+inventorykey)}
                    })
                )

            .catch(console.log)
            //this.gridApi.redrawRows(redrawRowsParams)
            //this.gridApi.refreshCells()
        }
</code>```

```<code>--Console log output---
</code>```

```<code>    27991
    InventoryList.js:114 invKey loop:
    InventoryList.js:119 Found it!
    105
    InventoryList.js:121 no 27991
    UserBoard.js:86 forceUpdate
</code>```

According to the Console Log, it found the row and made the call to select it.  So why isn't it selected?  Please advise.

答:
Without looking at the rest of your code, I am suspecting that your grid may have not been configured for selection.

Are you able to select any row to start with?

You may be missing the property rowSelection='single' on your gridOptions

Body:
My React application has a "Merge" button, which calls a web service to combine 2 rows in the ag-grid into one row.

After calling the web service, I want to re-render the grid, with the first row selected.  I call my ReRender function to do this.  The function calls my web service to re-retrieve the data, then it tries to select the row.

No errors happen, the data is re-rendered,  the console shows I did find the matching row to select, so I call node.setSelection(true), but the row is not selected.  What can I do?  The grid is paginated.

Code:

    ReRender = (inventorykey) => {
            console.log(inventorykey)
            this.rowChecked = []
            fetch( 'http://apsrp07823.svr.com:8088/mpa/getCockpit?userkey=' + this.state.userkey )
            .then(res=>res.json())
            .then(resj=>{
                if (resj.rows && resj.rows.length>0) {
                    this.setState({rowData:resj.rows})
                }
            })
            .then(
                    console.log('invKey loop:'),
                    this.gridApi.forEachNode( (node) => {
                        if ( node.data.inventorykey === inventorykey ) {
                        console.log('Found it!')
                        node.setSelected(true);}
                        else{console.log('no '+inventorykey)}
                    })
                )

            .catch(console.log)
            //this.gridApi.redrawRows(redrawRowsParams)
            //this.gridApi.refreshCells()
        }

--Console log output---

    27991
    InventoryList.js:114 invKey loop:
    InventoryList.js:119 Found it!
    105
    InventoryList.js:121 no 27991
    UserBoard.js:86 forceUpdate

According to the Console Log, it found the row and made the call to select it.  So why isn't it selected?  Please advise.


问:
How can I ship my app with a pre-populated Core Data database?
My app uses Core Data and I want some default entries to be inside.
What's best practices of how to do that?</p>

答:
See the CoreDataBooks example, which has sample code for copying a database at first launch.

EDIT: I've created a Core Data framework (read about it here: http://bikepress.org/?p=1120) that includes this feature.


问:
Best practices for handling changes to the UINavigationItem of child view controllers in a container controller?
Suppose I have a container controller that accepts an array of UIViewControllers and lays them out so the user can swipe left and right to transition between them. This container controller is wrapped inside a navigation controller and is made the root view controller of the application's main window.

Each child controller makes a request to the API and loads a list of items that are displayed in a table view. Based on the items that are displayed a button may be added to the navigation bar that allows the user to act on all the items in the table view.

Because UINavigationController only uses the UINavigationItems of its child view controllers, the container controller needs to update its UINavigationItem to be in sync with the UINavigationItem of its children.

There appear to be two scenarios that the container controller needs to handle:

The selected view controller of the container controller changes and therefore the UINavigationItem of the container controller should update itself to mimic the UINavigationItem of the selected view controller.

A child controller updates its UINavigationItem and the container controller must be made aware of the change and update its UINavigationItem to match.

The best solutions I've come up with are:

In the setSelectedViewController: method query the navigation item of the selected view controller and update the leftBarButtonItems, rightBarButtonItems and title properties of the container controller's UINavigationItem to be the same as the selected view controller's UINavigationItem.

In the setSelectedViewController method KVO onto the leftBarButtonItems, rightBarButtonItems and title property of the selected view controller's UINavigationItem and whenever one of those properties changes up the container controller's UINavigationItem.

This is a recurring problem with many of the container controllers that I have written and I can't seem to find any documented solutions to these problems.

What are some solutions people have found to this problem?

答:
I know this question is old, but I think that I found the solution for this problem!

The navigationItem property of a UIViewController is defined in a category/extension in the UINavigationController header file.

This property is defined as:

```<code>open var navigationItem: UINavigationItem { get }
</code>```

So, as I just found out, you can override the property in the container view controller, in my case:

```<code>public override var navigationItem: UINavigationItem {
    return child?.navigationItem ?? super.navigationItem
}
</code>```

I tried this approach and it's working for me. All buttons, title and views are being shown and updated as they change on the contained view controller.

Body:
I know this question is old, but I think that I found the solution for this problem!

The navigationItem property of a UIViewController is defined in a category/extension in the UINavigationController header file.

This property is defined as:

open var navigationItem: UINavigationItem { get }

So, as I just found out, you can override the property in the container view controller, in my case:

public override var navigationItem: UINavigationItem {
    return child?.navigationItem ?? super.navigationItem
}

I tried this approach and it's working for me. All buttons, title and views are being shown and updated as they change on the contained view controller.


问:
Why does second terminal tab prompt bundle install
If I run rails s in the terminal, it works. If I open a new terminal window or tab and run rails c, I get the following error: Run bundle install to install missing gems. If I type cd .. and then cd back into the directory and run rails c again, it works.  My question is what would be causing this to occur?

答:
I was facing some problems but didn't find the perfect solution.

An alternate working solution for the same is below which worked for me well as expected.

Steps are as below:

nano ~/.bash_profile

Then add the following code at the end of your bash_profile file

current_dir=$(pwd)

cd $current_dir

Let me know if this worked for you.


问:
Why doesn't 'encode("utf-8", 'ignore').decode("utf-8")' strip non-UTF8 chars in Python 3?
I'm using Python 3.7 and Django 2.0.  I want to strip out non-UTF-8 characters from a string, that I'm obtaining by reading this CSV file.  I tried this ...

```<code>web_site = row['website'].strip().encode("utf-8", 'ignore').decode("utf-8")
</code>```

but this doesn't seem to be doing the job, since I have a resulting string that looks like ...

```<code>web_site: "wbez.org<200e>"
</code>```

Whatever this "<200e>" thing is, is evidently non-UTF-8 string, because when I try and insert this into a MySQL database (deployed as a docker image), I get the following error ...

```<code>web_1     | django.db.utils.OperationalError: Problem installing fixture '/app/maps/fixtures/seed_data.yaml': Could not load maps.Coop(pk=191): (1366, "Incorrect string value: '\\xE2\\x80\\x8E' for column 'web_site' at row 1")
</code>```

答:
Your row['website'] is already a Unicode string.  UTF-8 can support all valid Unicode code points, so .encode('utf8','ignore') doesn't typically ignore anything and encodes the entire string in UTF-8, and .decode('utf8') changes it back to a Unicode string again.

If you simply want to strip non-ASCII characters, use the following to filter only ASCII characters and ignore the rest.

```<code>row['website'].encode('ascii','ignore').decode('ascii')
</code>```

Body:
I'm using Python 3.7 and Django 2.0.  I want to strip out non-UTF-8 characters from a string, that I'm obtaining by reading this CSV file.  I tried this ...

web_site = row['website'].strip().encode("utf-8", 'ignore').decode("utf-8")

but this doesn't seem to be doing the job, since I have a resulting string that looks like ...

web_site: "wbez.org<200e>"

Whatever this "<200e>" thing is, is evidently non-UTF-8 string, because when I try and insert this into a MySQL database (deployed as a docker image), I get the following error ...

web_1     | django.db.utils.OperationalError: Problem installing fixture '/app/maps/fixtures/seed_data.yaml': Could not load maps.Coop(pk=191): (1366, "Incorrect string value: '\\xE2\\x80\\x8E' for column 'web_site' at row 1")

Body:
Your row['website'] is already a Unicode string.  UTF-8 can support all valid Unicode code points, so .encode('utf8','ignore') doesn't typically ignore anything and encodes the entire string in UTF-8, and .decode('utf8') changes it back to a Unicode string again.

If you simply want to strip non-ASCII characters, use the following to filter only ASCII characters and ignore the rest.

row['website'].encode('ascii','ignore').decode('ascii')


问:
How to create SVG from PNG
I've been using inkscape to create SVGs. But I've come across a problem. I've created a simple plus sign with a 1px line width (as simple as you can imagine). It is currently in PNG format with a transparent background. I've imported it into inkscape so I can convert it into a SVG. However, when I use trace bitmap, Inkscape CHANGES THE SHAPE such that the straight lines that are one pixel wide are tappered with pointed ends! I've tried different options in the trace bitmap settings but nothing seems to work. I've also gone through a number of online free conversion sites with no luck.

I wouldn't mind just creating the plus sign using html and css but the exact position of the lines as well as the line thickness tends to move around between chrome and firefox. It's very strange.

..Help?

答: I think I figured it out. If I create a plus sign that is 2 px thick instead of 1 px thick, inkscape does not do its smoothing thing (as long as I have unticked smoothing options). So, I do this, but draw it much bigger than what I need. Then when I load it into my website I can reduce the size of it there, and voila the 2 px width becomes 1 px width!</p>

Title: How to create SVG from PNG


问:
Google Deployment Manager: DNS. Removing TXT record also removes A record
I have a deployment manager configuration for DNS (dns.yaml):

```<code>imports:
- path: domainorg.jinja

resources:
  - name: domainorg
    type: domainorg.jinja
</code>```

domainorg.jinja contents:

```<code>resources:
  - type: gcp-types/dns-v1:managedZones
    name: domainorg
    properties:
      description: ''
      dnsName: domain.org.
      visibility: "public"
  - type: gcp-types/dns-v1:resourceRecordSets
    name: domainorgrs
    properties:
      name: 'domain.org.'
      managedZone: "domainorg"
      records:
      - type: A
        ttl: 300
        rrdatas:
        - XXX.XXX.XXX.XXX
  - type: gcp-types/dns-v1:resourceRecordSets
    name: wwwdomainorgrs
    properties:
      name: 'www.domain.org.'
      managedZone: "domainorg"
      records:
      - type: CNAME
        ttl: 300
        rrdatas:
        - domain.org.
  - type: gcp-types/dns-v1:resourceRecordSets
    name: domainorgsgverrs
    properties:
      name: 'domain.org.'
      managedZone: "domainorg"
      records:
      - type: TXT
        ttl: 300
        rrdatas:
        - "google-site-verification=YYY"
</code>```

I performed deployment using cli:

```<code>gcloud deployment-manager deployments update dns --config dns.yaml
</code>```

It works as expected. But, when I decided to remove TXT record from domainorg.jinja and to update the deployment I've got an unexpected result: google deployment manager removed TXT record with A record and my website fails... Is there any way to remove only TXT record using deployment manager?

Guys, had someone the same problem in the past? I will be very glad to see your solution.

答: There is a workaround which is already posted in this github link. Please try if that works on your end.</p>

Body:
I have a deployment manager configuration for DNS (dns.yaml):

imports:
- path: domainorg.jinja

resources:
  - name: domainorg
    type: domainorg.jinja

domainorg.jinja contents:

resources:
  - type: gcp-types/dns-v1:managedZones
    name: domainorg
    properties:
      description: ''
      dnsName: domain.org.
      visibility: "public"
  - type: gcp-types/dns-v1:resourceRecordSets
    name: domainorgrs
    properties:
      name: 'domain.org.'
      managedZone: "domainorg"
      records:
      - type: A
        ttl: 300
        rrdatas:
        - XXX.XXX.XXX.XXX
  - type: gcp-types/dns-v1:resourceRecordSets
    name: wwwdomainorgrs
    properties:
      name: 'www.domain.org.'
      managedZone: "domainorg"
      records:
      - type: CNAME
        ttl: 300
        rrdatas:
        - domain.org.
  - type: gcp-types/dns-v1:resourceRecordSets
    name: domainorgsgverrs
    properties:
      name: 'domain.org.'
      managedZone: "domainorg"
      records:
      - type: TXT
        ttl: 300
        rrdatas:
        - "google-site-verification=YYY"

I performed deployment using cli:

gcloud deployment-manager deployments update dns --config dns.yaml

It works as expected. But, when I decided to remove TXT record from domainorg.jinja and to update the deployment I've got an unexpected result: google deployment manager removed TXT record with A record and my website fails... Is there any way to remove only TXT record using deployment manager?

Guys, had someone the same problem in the past? I will be very glad to see your solution.


问:
What is the equivalent oracle code for CREATE PROCEDURE <Proc1> WITH RECOMPILE which is available in Sybase ASE/SQL Server
This is what I see from Sybase ASE documentation:

"It instructs Adaptive Server not to save a plan for this procedure. A new plan is created each time the procedure is executed."

So this means ASE does plan the stored procedure code in order to execute it, but what about oracle?
 Does Oracle saves plan at stored procedure level?

答:
Oracle does not save plans at the stored procedure level.

Oracle stores SQL plan information in a memory structure called the shared pool, which is part of the System Global Area (SGA).  Plans will be modified and created when necessary, based on when the queries are executed.  With the default settings, the plans will automatically adjust based on things like data and bind value changes.  You don't need to worry about plans changing or not changing when compiling objects.


问:
When saving, how can you check if a field has changed?
In my model I have :

```<code>class Alias(MyBaseModel):
    remote_image = models.URLField(
        max_length=500, null=True,
        help_text='''
            A URL that is downloaded and cached for the image.
            Only used when the alias is made
        '''
    )
    image = models.ImageField(
        upload_to='alias', default='alias-default.png',
        help_text="An image representing the alias"
    )

    def save(self, *args, **kw):
        if (not self.image or self.image.name == 'alias-default.png') and self.remote_image :
            try :
                data = utils.fetch(self.remote_image)
                image = StringIO.StringIO(data)
                image = Image.open(image)
                buf = StringIO.StringIO()
                image.save(buf, format='PNG')
                self.image.save(
                    hashlib.md5(self.string_id).hexdigest() + ".png", ContentFile(buf.getvalue())
                )
            except IOError :
                pass
</code>```

Which works great for the first time the remote_image changes.

How can I fetch a new image when someone has modified the remote_image on the alias? And secondly, is there a better way to cache a remote image?

答:
Very late to the game, but this is a version of Chris Pratt's answer that protects against race conditions while sacrificing performance, by using a transaction block and select_for_update()

```<code>@receiver(pre_save, sender=MyModel)
@transaction.atomic
def do_something_if_changed(sender, instance, **kwargs):
    try:
        obj = sender.objects.select_for_update().get(pk=instance.pk)
    except sender.DoesNotExist:
        pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
    else:
        if not obj.some_field == instance.some_field: # Field has changed
            # do something
</code>```

Body:
In my model I have :

class Alias(MyBaseModel):
    remote_image = models.URLField(
        max_length=500, null=True,
        help_text='''
            A URL that is downloaded and cached for the image.
            Only used when the alias is made
        '''
    )
    image = models.ImageField(
        upload_to='alias', default='alias-default.png',
        help_text="An image representing the alias"
    )

    def save(self, *args, **kw):
        if (not self.image or self.image.name == 'alias-default.png') and self.remote_image :
            try :
                data = utils.fetch(self.remote_image)
                image = StringIO.StringIO(data)
                image = Image.open(image)
                buf = StringIO.StringIO()
                image.save(buf, format='PNG')
                self.image.save(
                    hashlib.md5(self.string_id).hexdigest() + ".png", ContentFile(buf.getvalue())
                )
            except IOError :
                pass

Which works great for the first time the remote_image changes.

How can I fetch a new image when someone has modified the remote_image on the alias? And secondly, is there a better way to cache a remote image?

Body:
Very late to the game, but this is a version of Chris Pratt's answer that protects against race conditions while sacrificing performance, by using a transaction block and select_for_update()

@receiver(pre_save, sender=MyModel)
@transaction.atomic
def do_something_if_changed(sender, instance, **kwargs):
    try:
        obj = sender.objects.select_for_update().get(pk=instance.pk)
    except sender.DoesNotExist:
        pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
    else:
        if not obj.some_field == instance.some_field: # Field has changed
            # do something


问:
Unable to get PHP script name using REGEX
I am having quite the challenge. I have my function where() which tracks where users are visiting on the site, and takes the script filename and provides a description and inserts into database.

The script was working great, until recently, and unaware of the failure of this function after a recent minor update from MySQL 5.6.40 to 5.6.47

I am not sure if that had anything to do with it, but I discovered days later that it was not working anymore.

Our function:

```<code>function where($scriptname = "index", $userid, $update=1){
    if (!is_valid_id($userid))
        die;

    if (preg_match("/details.php/i", $scriptname))
        $where = "Browsing File Details (ID $_GET[id])";
    elseif (preg_match("/files.php/i", $scriptname))
        $where = "Browsing Files";
    elseif (preg_match("/account-info.php/i", $scriptname))
        $where = "Browsing Account Info (ID $_GET[id])";
    elseif (preg_match("/upload.php/i", $scriptname))
        $where = "Uploading File";
    elseif (preg_match("/account.php/i", $scriptname))
        $where = "Browsing User Control Panel";
    elseif (preg_match("/search.php/i", $scriptname))
        $where = "Searching For Files";
    elseif (preg_match("/forums.php/i", $scriptname))
        $where = "Viewing Forums";
    elseif (preg_match("/index.php/i", $scriptname))
        $where = "Browsing Homepage";
    elseif (preg_match("/mailbox.php/i", $scriptname))
        $where = "Viewing Messages";
    elseif (preg_match("/comments.php/i", $scriptname))
        $where = "Viewing Comments";
    elseif (preg_match("/recover.php/i", $scriptname))
        $where = "Recovering Account";
    elseif (preg_match("/bookmarks.php/i", $scriptname))
        $where = "Viewing Bookmarks";
    elseif (preg_match("/getfile.php/i", $scriptname))
        $where = "Downloaded File (ID $_GET[id])";
    elseif (preg_match("/faq.php/i", $scriptname))
        $where = "Reading FAQ Page";
    elseif (preg_match("/friends.php/i", $scriptname))
        $where = "Viewing Friends";
    elseif (preg_match("/admin.php/i", $scriptname))
        $where = "Managing Admin Panel";
    else
        $where = "Unknown Location";

    if ($update) {
        // Worked until a few days ago. No site changes were made prior for quite some time.
        //$query = sprintf("UPDATE users SET page=".sqlesc($where)." WHERE id ='%s'", mysql_real_escape_string($userid));
        // Now using line below, which does insert into row if I use my own variable.
        $query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($where) . " WHERE id=" . $userid;
        $result = SQL_Query_exec($query);
    }
        return $where;
}
</code>```

Now, I have tried the following code to narrow it down to what is causing it. Currently, the function above only inserts

Unknown Location

to the Database, no matter what page is viewed.

I got it down to this:

```<code>$stringtest = "This inserts into database!";
$query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($stringtest) . " WHERE id=" . $userid;
</code>```

This works great, however it is not passing any of the $where conditions.

I've tried varies regular expressions for filename matching to no avail.

Any idea what I'm doing wrong?

Thanks in advance!

答:
I noticed your default value for $scriptname is "index". I presume this references "index.php"? Whereas your matching pattern is also looking for the file extension. (By the way, the un-escaped . doesn't mean a literal ".". It's a RegEx rule for 'any one character'. So yeah, it'll work, but kind of by accident.)

What kind of values are you passing in? Try die/dumping the value of $scriptname within that function, before the comparisons are run, as a sanity-check to verify that the expected kind of input is being received. It could be you're seeing legit, if only unexpected, failures.

Body:
I am having quite the challenge. I have my function where() which tracks where users are visiting on the site, and takes the script filename and provides a description and inserts into database.

The script was working great, until recently, and unaware of the failure of this function after a recent minor update from MySQL 5.6.40 to 5.6.47

I am not sure if that had anything to do with it, but I discovered days later that it was not working anymore.

Our function:

function where($scriptname = "index", $userid, $update=1){
    if (!is_valid_id($userid))
        die;

    if (preg_match("/details.php/i", $scriptname))
        $where = "Browsing File Details (ID $_GET[id])";
    elseif (preg_match("/files.php/i", $scriptname))
        $where = "Browsing Files";
    elseif (preg_match("/account-info.php/i", $scriptname))
        $where = "Browsing Account Info (ID $_GET[id])";
    elseif (preg_match("/upload.php/i", $scriptname))
        $where = "Uploading File";
    elseif (preg_match("/account.php/i", $scriptname))
        $where = "Browsing User Control Panel";
    elseif (preg_match("/search.php/i", $scriptname))
        $where = "Searching For Files";
    elseif (preg_match("/forums.php/i", $scriptname))
        $where = "Viewing Forums";
    elseif (preg_match("/index.php/i", $scriptname))
        $where = "Browsing Homepage";
    elseif (preg_match("/mailbox.php/i", $scriptname))
        $where = "Viewing Messages";
    elseif (preg_match("/comments.php/i", $scriptname))
        $where = "Viewing Comments";
    elseif (preg_match("/recover.php/i", $scriptname))
        $where = "Recovering Account";
    elseif (preg_match("/bookmarks.php/i", $scriptname))
        $where = "Viewing Bookmarks";
    elseif (preg_match("/getfile.php/i", $scriptname))
        $where = "Downloaded File (ID $_GET[id])";
    elseif (preg_match("/faq.php/i", $scriptname))
        $where = "Reading FAQ Page";
    elseif (preg_match("/friends.php/i", $scriptname))
        $where = "Viewing Friends";
    elseif (preg_match("/admin.php/i", $scriptname))
        $where = "Managing Admin Panel";
    else
        $where = "Unknown Location";

    if ($update) {
        // Worked until a few days ago. No site changes were made prior for quite some time.
        //$query = sprintf("UPDATE users SET page=".sqlesc($where)." WHERE id ='%s'", mysql_real_escape_string($userid));
        // Now using line below, which does insert into row if I use my own variable.
        $query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($where) . " WHERE id=" . $userid;
        $result = SQL_Query_exec($query);
    }
        return $where;
}

Now, I have tried the following code to narrow it down to what is causing it. Currently, the function above only inserts

Unknown Location

to the Database, no matter what page is viewed.

I got it down to this:

$stringtest = "This inserts into database!";
$query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($stringtest) . " WHERE id=" . $userid;

This works great, however it is not passing any of the $where conditions.

I've tried varies regular expressions for filename matching to no avail.

Any idea what I'm doing wrong?

Thanks in advance!


问:
How to Create a Global Function then use on Controller
Im From VB.net base want to learn ASP.NET MVC

For Example : Function created below (how to create in global folder/cs and how to call it then use in Controller)

```<code>Function pRound(Number ,NumDigits)
    Dim dblPower, vPSTEmp, intSgn

    dblPower = 10 ^ NumDigits
    vPSTEmp = CDbl(Number * dblPower + 0.5)
    pRound = Int(vPSTEmp) / dblPower
End Function
</code>```

For vb I just add <--#include file="include/function.asp"-->

then can use it like pRound(number, 4)

Please Teach Me How to Do it. Thx a lot.

答:
You could add a new class file in your solution and make a static class;

```<code>namespace ProjectName.Functions
{
   public static class Utility
   {
      public static float pRound(float number, int digits){
         float result = 0;
         // your code here
         return result;
      }
   }
}
</code>```

Then in your controller, since a static class is instantiated at the start of the program, you could just call it;

```<code>using ProjectName.Functions;

public ActionResult TestController
{
   // call Utility.pRound(), no need to instantiate the class
   float round = Utility.pRound(1,1);
}
</code>```

Body:
Im From VB.net base want to learn ASP.NET MVC

For Example : Function created below (how to create in global folder/cs and how to call it then use in Controller)

Function pRound(Number ,NumDigits)
    Dim dblPower, vPSTEmp, intSgn

    dblPower = 10 ^ NumDigits
    vPSTEmp = CDbl(Number * dblPower + 0.5)
    pRound = Int(vPSTEmp) / dblPower
End Function

For vb I just add <--#include file="include/function.asp"-->

then can use it like pRound(number, 4)

Please Teach Me How to Do it. Thx a lot.

Body:
You could add a new class file in your solution and make a static class;

namespace ProjectName.Functions
{
   public static class Utility
   {
      public static float pRound(float number, int digits){
         float result = 0;
         // your code here
         return result;
      }
   }
}

Then in your controller, since a static class is instantiated at the start of the program, you could just call it;

using ProjectName.Functions;

public ActionResult TestController
{
   // call Utility.pRound(), no need to instantiate the class
   float round = Utility.pRound(1,1);
}


问:
Radial Menu With Pyside/PyQt
Basically I am trying to create a radial menu like this

I was using QPainter and here is a attempt from my side. But I can't figure out how to add a click event on the pixmaps. Is there any lib available for this ?

Images Link

```<code>from PySide2 import QtWidgets, QtGui, QtCore
import sys
import os
RESPATH = "/{your_folder}/radialMenu/res"

class RadialMenu(QtWidgets.QGraphicsRectItem):
    addButton     = 1
    disableButton = 2
    clearButton   = 3
    exportButton  = 4
    infoButton    = 5
    runButton     = 6
    scriptsButton = 7
    def __init__(self, parent=None):
        super(RadialMenu, self).__init__(parent)

    def paint(self, painter, option, widget=None):
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.setBrush(QtGui.QBrush(QtGui.QColor(71, 71, 71, 0)))
        tempPen =  QtGui.QPen(QtGui.QColor(178, 141, 58), 20.0, QtCore.Qt.CustomDashLine)
        tempPen.setDashPattern([4, 4, 4, 4])
        painter.setPen(tempPen)
        painter.drawEllipse(0, 0, 150, 150)
        topX = 0
        topY = 0
        pixmap1 =  QtGui.QPixmap(os.path.join(RESPATH, "add.png"))
        painter.drawPixmap(topX + 50, topY - 8, pixmap1)
        pixmap2 = QtGui.QPixmap(os.path.join(RESPATH, "disable.png"))
        painter.drawPixmap(topX + 90, topY - 5, pixmap2)
        pixmap3 = QtGui.QPixmap(os.path.join(RESPATH, "clear.png"))
        painter.drawPixmap(topX - 10, topY + 70, pixmap3)
        pixmap4 = QtGui.QPixmap(os.path.join(RESPATH, "export.png"))
        pixmap4 = pixmap4.transformed(QtGui.QTransform().rotate(15))
        painter.drawPixmap(topX - 2, topY + 100, pixmap4)
        pixmap5 = QtGui.QPixmap(os.path.join(RESPATH, "info.png"))
        painter.drawPixmap(topX + 20, topY + 125, pixmap5)
        pixmap6 = QtGui.QPixmap(os.path.join(RESPATH, "run.png"))
        painter.drawPixmap(topX + 113, topY + 125, pixmap6)
        pixmap6 = QtGui.QPixmap(os.path.join(RESPATH, "scripts.png"))
        painter.drawPixmap(topX + 137, topY + 85, pixmap6)

class RadialTest(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.scene=QtWidgets.QGraphicsScene(self)
        buttonItem = RadialMenu()
        self.scene.addItem(buttonItem)
        buttonItem.setPos(100,100)
        buttonItem.setZValue(1000)
        self.scene.update()
        self.view = QtWidgets.QGraphicsView(self.scene, self)
        self.scene.setSceneRect(0, 0, 300, 300)
        self.setGeometry(50, 50, 305, 305)
        self.show()

if __name__ == "__main__":
    app=QtWidgets.QApplication(sys.argv)
    firstScene = RadialTest()
    sys.exit(app.exec_())
</code>```

This code will give this result

答:
For this kind of objects, keeping a hierarchical object structure is always suggested. Also, when dealing with object that possibly have "fixed" sizes (like images, but not only), fixed positioning can be tricky expecially with newer system that support different DPI screen values.

With this approach I'm not using mapped images at all (but button icons can be still set), instead I chose to use a purely geometrical concept, using pixel "radius" values and angles for each button.

```<code>from PyQt5 import QtWidgets, QtGui, QtCore
from math import sqrt

class RadialMenu(QtWidgets.QGraphicsObject):
    buttonClicked = QtCore.pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptHoverEvents(True)
        self.buttons = {}

    def addButton(self, id, innerRadius, size, startAngle, angleSize, pen=None,
                  brush=None, icon=None):
        # if a button already exists with the same id, remove it
        if id in self.buttons:
            oldItem = self.buttons.pop(id)
            if self.scene():
                self.scene().removeItem(oldItem)
            oldItem.setParent(None)

        # compute the extents of the inner and outer "circles"
        startRect = QtCore.QRectF(
            -innerRadius, -innerRadius, innerRadius * 2, innerRadius * 2)
        outerRadius = innerRadius + size
        endRect = QtCore.QRectF(
            -outerRadius, -outerRadius, outerRadius * 2, outerRadius * 2)

        # create the circle section path
        path = QtGui.QPainterPath()
        # move to the start angle, using the outer circle
        path.moveTo(QtCore.QLineF.fromPolar(outerRadius, startAngle).p2())
        # draw the arc to the end of the angle size
        path.arcTo(endRect, startAngle, angleSize)
        # draw a line that connects to the inner circle
        path.lineTo(QtCore.QLineF.fromPolar(innerRadius, startAngle + angleSize).p2())
        # draw the inner circle arc back to the start angle
        path.arcTo(startRect, startAngle + angleSize, -angleSize)
        # close the path back to the starting position; theoretically unnecessary,
        # but better safe than sorry
        path.closeSubpath()

        # create a child item for the "arc"
        item = QtWidgets.QGraphicsPathItem(path, self)
        item.setPen(pen if pen else (QtGui.QPen(QtCore.Qt.transparent)))
        item.setBrush(brush if brush else QtGui.QColor(180, 140, 70))
        self.buttons[id] = item

        if icon is not None:
            # the maximum available size is at 45 degrees, use the Pythagorean
            # theorem to compute it and create a new pixmap based on the icon
            iconSize = int(sqrt(size ** 2 / 2))
            pixmap = icon.pixmap(iconSize)
            # create the child icon (pixmap) item
            iconItem = QtWidgets.QGraphicsPixmapItem(pixmap, self)
            # push it above the "arc" item
            iconItem.setZValue(item.zValue() + 1)
            # find the mid of the angle and put the icon there
            midAngle = startAngle + angleSize / 2
            iconPos = QtCore.QLineF.fromPolar(innerRadius + size * .5, midAngle).p2()
            iconItem.setPos(iconPos)
            # use the center of the pixmap as the offset for centering
            iconItem.setOffset(-pixmap.rect().center())

    def itemAtPos(self, pos):
        for button in self.buttons.values():
            if button.shape().contains(pos):
                return button

    def checkHover(self, pos):
        hoverButton = self.itemAtPos(pos)
        for button in self.buttons.values():
            # set a visible border only for the hovered item
            button.setPen(QtCore.Qt.red if button == hoverButton else QtCore.Qt.transparent)

    def hoverEnterEvent(self, event):
        self.checkHover(event.pos())

    def hoverMoveEvent(self, event):
        self.checkHover(event.pos())

    def hoverLeaveEvent(self, event):
        for button in self.buttons.values():
            button.setPen(QtCore.Qt.transparent)

    def mousePressEvent(self, event):
        clickButton = self.itemAtPos(event.pos())
        if clickButton:
            for id, btn in self.buttons.items():
                if btn == clickButton:
                    self.buttonClicked.emit(id)

    def boundingRect(self):
        return self.childrenBoundingRect()

    def paint(self, qp, option, widget):
        # required for QGraphicsObject subclasses
        pass

ButtonData = [
    (50, 40, QtWidgets.QStyle.SP_MessageBoxInformation),
    (90, 40, QtWidgets.QStyle.SP_MessageBoxQuestion),
    (180, 20, QtWidgets.QStyle.SP_FileDialogBack),
    (200, 20, QtWidgets.QStyle.SP_DialogOkButton),
    (220, 20, QtWidgets.QStyle.SP_DialogOpenButton),
    (290, 30, QtWidgets.QStyle.SP_ArrowDown),
    (320, 30, QtWidgets.QStyle.SP_ArrowUp),
]

class RadialTest(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.scene = QtWidgets.QGraphicsScene(self)

        buttonItem = RadialMenu()
        self.scene.addItem(buttonItem)
        buttonItem.buttonClicked.connect(self.buttonClicked)
        for index, (startAngle, extent, icon) in enumerate(ButtonData):
            icon = self.style().standardIcon(icon, None, self)
            buttonItem.addButton(index, 64, 20, startAngle, extent, icon=icon)

        buttonItem.setPos(150, 150)
        buttonItem.setZValue(1000)

        self.view = QtWidgets.QGraphicsView(self.scene, self)
        self.view.setRenderHints(QtGui.QPainter.Antialiasing)
        self.scene.setSceneRect(0, 0, 300, 300)
        self.setGeometry(50, 50, 305, 305)
        self.show()

    def buttonClicked(self, id):
        print('Button id {} has been clicked'.format(id))
</code>```

And this is the result:

Title: Radial Menu With Pyside/PyQt

Body:
Basically I am trying to create a radial menu like this

I was using QPainter and here is a attempt from my side. But I can't figure out how to add a click event on the pixmaps. Is there any lib available for this ?

Images Link

from PySide2 import QtWidgets, QtGui, QtCore
import sys
import os
RESPATH = "/{your_folder}/radialMenu/res"

class RadialMenu(QtWidgets.QGraphicsRectItem):
    addButton     = 1
    disableButton = 2
    clearButton   = 3
    exportButton  = 4
    infoButton    = 5
    runButton     = 6
    scriptsButton = 7
    def __init__(self, parent=None):
        super(RadialMenu, self).__init__(parent)

    def paint(self, painter, option, widget=None):
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.setBrush(QtGui.QBrush(QtGui.QColor(71, 71, 71, 0)))
        tempPen =  QtGui.QPen(QtGui.QColor(178, 141, 58), 20.0, QtCore.Qt.CustomDashLine)
        tempPen.setDashPattern([4, 4, 4, 4])
        painter.setPen(tempPen)
        painter.drawEllipse(0, 0, 150, 150)
        topX = 0
        topY = 0
        pixmap1 =  QtGui.QPixmap(os.path.join(RESPATH, "add.png"))
        painter.drawPixmap(topX + 50, topY - 8, pixmap1)
        pixmap2 = QtGui.QPixmap(os.path.join(RESPATH, "disable.png"))
        painter.drawPixmap(topX + 90, topY - 5, pixmap2)
        pixmap3 = QtGui.QPixmap(os.path.join(RESPATH, "clear.png"))
        painter.drawPixmap(topX - 10, topY + 70, pixmap3)
        pixmap4 = QtGui.QPixmap(os.path.join(RESPATH, "export.png"))
        pixmap4 = pixmap4.transformed(QtGui.QTransform().rotate(15))
        painter.drawPixmap(topX - 2, topY + 100, pixmap4)
        pixmap5 = QtGui.QPixmap(os.path.join(RESPATH, "info.png"))
        painter.drawPixmap(topX + 20, topY + 125, pixmap5)
        pixmap6 = QtGui.QPixmap(os.path.join(RESPATH, "run.png"))
        painter.drawPixmap(topX + 113, topY + 125, pixmap6)
        pixmap6 = QtGui.QPixmap(os.path.join(RESPATH, "scripts.png"))
        painter.drawPixmap(topX + 137, topY + 85, pixmap6)

class RadialTest(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.scene=QtWidgets.QGraphicsScene(self)
        buttonItem = RadialMenu()
        self.scene.addItem(buttonItem)
        buttonItem.setPos(100,100)
        buttonItem.setZValue(1000)
        self.scene.update()
        self.view = QtWidgets.QGraphicsView(self.scene, self)
        self.scene.setSceneRect(0, 0, 300, 300)
        self.setGeometry(50, 50, 305, 305)
        self.show()

if __name__ == "__main__":
    app=QtWidgets.QApplication(sys.argv)
    firstScene = RadialTest()
    sys.exit(app.exec_())

This code will give this result

Body:
For this kind of objects, keeping a hierarchical object structure is always suggested. Also, when dealing with object that possibly have "fixed" sizes (like images, but not only), fixed positioning can be tricky expecially with newer system that support different DPI screen values.

With this approach I'm not using mapped images at all (but button icons can be still set), instead I chose to use a purely geometrical concept, using pixel "radius" values and angles for each button.

from PyQt5 import QtWidgets, QtGui, QtCore
from math import sqrt

class RadialMenu(QtWidgets.QGraphicsObject):
    buttonClicked = QtCore.pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptHoverEvents(True)
        self.buttons = {}

    def addButton(self, id, innerRadius, size, startAngle, angleSize, pen=None,
                  brush=None, icon=None):
        # if a button already exists with the same id, remove it
        if id in self.buttons:
            oldItem = self.buttons.pop(id)
            if self.scene():
                self.scene().removeItem(oldItem)
            oldItem.setParent(None)

        # compute the extents of the inner and outer "circles"
        startRect = QtCore.QRectF(
            -innerRadius, -innerRadius, innerRadius * 2, innerRadius * 2)
        outerRadius = innerRadius + size
        endRect = QtCore.QRectF(
            -outerRadius, -outerRadius, outerRadius * 2, outerRadius * 2)

        # create the circle section path
        path = QtGui.QPainterPath()
        # move to the start angle, using the outer circle
        path.moveTo(QtCore.QLineF.fromPolar(outerRadius, startAngle).p2())
        # draw the arc to the end of the angle size
        path.arcTo(endRect, startAngle, angleSize)
        # draw a line that connects to the inner circle
        path.lineTo(QtCore.QLineF.fromPolar(innerRadius, startAngle + angleSize).p2())
        # draw the inner circle arc back to the start angle
        path.arcTo(startRect, startAngle + angleSize, -angleSize)
        # close the path back to the starting position; theoretically unnecessary,
        # but better safe than sorry
        path.closeSubpath()

        # create a child item for the "arc"
        item = QtWidgets.QGraphicsPathItem(path, self)
        item.setPen(pen if pen else (QtGui.QPen(QtCore.Qt.transparent)))
        item.setBrush(brush if brush else QtGui.QColor(180, 140, 70))
        self.buttons[id] = item

        if icon is not None:
            # the maximum available size is at 45 degrees, use the Pythagorean
            # theorem to compute it and create a new pixmap based on the icon
            iconSize = int(sqrt(size ** 2 / 2))
            pixmap = icon.pixmap(iconSize)
            # create the child icon (pixmap) item
            iconItem = QtWidgets.QGraphicsPixmapItem(pixmap, self)
            # push it above the "arc" item
            iconItem.setZValue(item.zValue() + 1)
            # find the mid of the angle and put the icon there
            midAngle = startAngle + angleSize / 2
            iconPos = QtCore.QLineF.fromPolar(innerRadius + size * .5, midAngle).p2()
            iconItem.setPos(iconPos)
            # use the center of the pixmap as the offset for centering
            iconItem.setOffset(-pixmap.rect().center())

    def itemAtPos(self, pos):
        for button in self.buttons.values():
            if button.shape().contains(pos):
                return button

    def checkHover(self, pos):
        hoverButton = self.itemAtPos(pos)
        for button in self.buttons.values():
            # set a visible border only for the hovered item
            button.setPen(QtCore.Qt.red if button == hoverButton else QtCore.Qt.transparent)

    def hoverEnterEvent(self, event):
        self.checkHover(event.pos())

    def hoverMoveEvent(self, event):
        self.checkHover(event.pos())

    def hoverLeaveEvent(self, event):
        for button in self.buttons.values():
            button.setPen(QtCore.Qt.transparent)

    def mousePressEvent(self, event):
        clickButton = self.itemAtPos(event.pos())
        if clickButton:
            for id, btn in self.buttons.items():
                if btn == clickButton:
                    self.buttonClicked.emit(id)

    def boundingRect(self):
        return self.childrenBoundingRect()

    def paint(self, qp, option, widget):
        # required for QGraphicsObject subclasses
        pass

ButtonData = [
    (50, 40, QtWidgets.QStyle.SP_MessageBoxInformation),
    (90, 40, QtWidgets.QStyle.SP_MessageBoxQuestion),
    (180, 20, QtWidgets.QStyle.SP_FileDialogBack),
    (200, 20, QtWidgets.QStyle.SP_DialogOkButton),
    (220, 20, QtWidgets.QStyle.SP_DialogOpenButton),
    (290, 30, QtWidgets.QStyle.SP_ArrowDown),
    (320, 30, QtWidgets.QStyle.SP_ArrowUp),
]

class RadialTest(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.scene = QtWidgets.QGraphicsScene(self)

        buttonItem = RadialMenu()
        self.scene.addItem(buttonItem)
        buttonItem.buttonClicked.connect(self.buttonClicked)
        for index, (startAngle, extent, icon) in enumerate(ButtonData):
            icon = self.style().standardIcon(icon, None, self)
            buttonItem.addButton(index, 64, 20, startAngle, extent, icon=icon)

        buttonItem.setPos(150, 150)
        buttonItem.setZValue(1000)

        self.view = QtWidgets.QGraphicsView(self.scene, self)
        self.view.setRenderHints(QtGui.QPainter.Antialiasing)
        self.scene.setSceneRect(0, 0, 300, 300)
        self.setGeometry(50, 50, 305, 305)
        self.show()

    def buttonClicked(self, id):
        print('Button id {} has been clicked'.format(id))

And this is the result: