问:
How do I use Nitrogen as a GUI frontend for an Erlang app?
I have got a basic server-side Erlang app (not fully OTP'd yet) which I start on a command-line. I want to turn it into an interactive system using a browser as GUI with Nitrogen (version 2.0.4). The general plan is to

turn the current module into a gen_server as the MODEL part; it analyses data and generates events from it which reflect certain properties of the data I am interested in.

add a CONTROLLER module which is both gen_event (to pick up events generated by the model) and gen_server (to allow queries from the GUI frontend)

use Nitrogen as the VIEW, updating the relevant pages with the Ajax facilities through calls to the controller module (which in turn queries the model)

As far as I can see I would want a general application supervisor with three children: the model, view, and controller. Then they would talk to each other via the APIs mapped to the OTP communication modes.

And this is where I am stuck: should I put all of this into the Nitrogen directory tree? Should I set up a new app dir structure and have the three components (including Nitrogen) under there? What exactly do I need to do to start up the Nitrogen server as a child of my app supervisor (the Nitrogen start script looks rather more complex than I expected)? I have started going through Erlang and OTP in Action, but haven't quite finished it yet. And I need to demo the system the day after tomorrow ;)

What I want is to type "start.sh" on the command-line, and then use the browser to connect to the app via Nitrogen.

答:
Because of the way the Nitrogen App is built, you should not build your application tightly coupled to it. Rather, you build your application, provide APIs to Nitrogen (APIs you will call from your Nitrogen events e.t.c).

Then you would package your app as an OTP filesystem, put it into the apps folder of nitrogen. When nitrogen makes or starts it will add the ebin paths of your apps as long as they are in its apps directory.

For example: the model and controller will be implemented within your application. Then in your application you expose function calls in your module (which could be gen_server behaving) which you would call right from your nitrogen page. The beauty is all these would be in the same code path.

What to do: you look at the Nitrogen quickstart.sh script, at the point where it starts erlang VM.

```
echo "Starting Nitrogen on Inets (http://localhost:8000)..."
erl \
    -name YOUR_NODE_NAME_HERE \
    -pa ./ebin ../apps/*/ebin ../apps/*/include \
    -env ERL_FULLSWEEP_AFTER 10 \
    -eval "application:start(nprocreg)" \
    -eval "application:start(quickstart)" \
    -eval "application:start(YOUR_APPLICATION)"
```

if your application is not OTP like, then create a folder called "ebin" in which you will put the beam files you have.The create a folder called: "my_app-1.0" and paste this ebin folder in that folder

```
  Nitrogen--|--/apps --|--/my_app-1.0 --|--/ebin
            |--/doc
            |--/rel
            |--/support
            |--/Quickstart
```

The full path to your beam files should be ```"$NITROGEN/apps/my_app-1.0/ebin"```.
Whenever Nitrogen starts it will add to the code path all your beam files. Then, if in your code you have the function that starts your stuff say: main_server:start().
You will change the quickstart.sh found in $NITROGEN/Quickstart/quickstart.sh to appear this way.

```
echo "Starting Nitrogen on Inets (http://localhost:8000)..."
erl \
    -name YOUR_NODE_NAME_HERE \
    -pa ./ebin ../apps/*/ebin ../apps/*/include \
    -setcookie YOUR_FUNNY_COOKIE_HERE \
    -mnesia dir '"PATH/TO/MNESIA/DIRECTORY"' \
    -env ERL_FULLSWEEP_AFTER 10 \
    -eval "application:start(nprocreg)" \
    -eval "application:start(quickstart)" \
    <b>-eval "main_server:start()"</b>
```

The advantage of this is that if you happen to change your view to say erlyweb, erlang web, you will not need to make changes to your model or controller but rather you exposed APIs that can be called from any view type library.

Body:
Because of the way the Nitrogen App is built, you should not build your application tightly coupled to it. Rather, you build your application, provide APIs to Nitrogen (APIs you will call from your Nitrogen events e.t.c).

Then you would package your app as an OTP filesystem, put it into the apps folder of nitrogen. When nitrogen makes or starts it will add the ebin paths of your apps as long as they are in its apps directory.

For example: the model and controller will be implemented within your application. Then in your application you expose function calls in your module (which could be gen_server behaving) which you would call right from your nitrogen page. The beauty is all these would be in the same code path.

What to do: you look at the Nitrogen quickstart.sh script, at the point where it starts erlang VM.

echo "Starting Nitrogen on Inets (http://localhost:8000)..."
erl \
    -name YOUR_NODE_NAME_HERE \
    -pa ./ebin ../apps/*/ebin ../apps/*/include \
    -env ERL_FULLSWEEP_AFTER 10 \
    -eval "application:start(nprocreg)" \
    -eval "application:start(quickstart)" \
    -eval "application:start(YOUR_APPLICATION)"

if your application is not OTP like, then create a folder called "ebin" in which you will put the beam files you have.The create a folder called: "my_app-1.0" and paste this ebin folder in that folder

  Nitrogen--|--/apps --|--/my_app-1.0 --|--/ebin
            |--/doc
            |--/rel
            |--/support
            |--/Quickstart

The full path to your beam files should be
"$NITROGEN/apps/my_app-1.0/ebin"
.
Whenever Nitrogen starts it will add to the code path all your beam files. Then, if in your code you have the function that starts your stuff say: main_server:start().
You will change the quickstart.sh found in $NITROGEN/Quickstart/quickstart.sh to appear this way.

echo "Starting Nitrogen on Inets (http://localhost:8000)..."
erl \
    -name YOUR_NODE_NAME_HERE \
    -pa ./ebin ../apps/*/ebin ../apps/*/include \
    -setcookie YOUR_FUNNY_COOKIE_HERE \
    -mnesia dir '"PATH/TO/MNESIA/DIRECTORY"' \
    -env ERL_FULLSWEEP_AFTER 10 \
    -eval "application:start(nprocreg)" \
    -eval "application:start(quickstart)" \
    -eval "main_server:start()"

The advantage of this is that if you happen to change your view to say erlyweb, erlang web, you will not need to make changes to your model or controller but rather you exposed APIs that can be called from any view type library.


来源: stackexchange

问:
CSS multiple input[type] selectors
According to the W3 CSS spec, something like: input[type~="text password"] should select input fields whose type is set to either "text" or "password", but it doesn't work! Did I misinterpret this line?

E[foo~="warning"] Matches any E element whose "foo" attribute value is
  a list of space-separated values, one of which is exactly equal to
  "warning".

CSS spec source, it's the fourth from the bottom in the table.

答:
I tried input{property: ....} and it worked.

For example input{border: 3px solid red;}

ContentLicense: CC BY-SA 3.0

Title: CSS multiple input[type] selectors

ContentLicense: CC BY-SA 4.0


问:
Correctly hiding database credentials
As you may see, I have my db connection file and another "protected" file, where my credentials are, and this file is included in .gitignore. I import it and reach the data. Quite basic. Therefore my questions are:

Is this the right way to do it?

If not, how should I do it? Plus: how could I add extra security to my account,connection?

Let's suppose I have a private collection, that no one should see, how could I protect specially this collection? I mean, with a password or a two step verification let's say.

Current code:

```<code>const mongoose = require("mongoose");
const mongoCredentials = require("../protected/mongoCredential");

const URI = `mongodb+srv://${mongoCredentials.username}:${mongoCredential.password}
              @firstcluster-eldi8.mongodb.net/culturapp?retryWrites=true&w=majority`;

mongoose.connect(URI, { useUnifiedTopology: true, useNewUrlParser: true })
  .then(db => console.log("MongoDB is connected"))
  .catch(err => console.log(">> ERROR: ",err));

module.exports = mongoose;
</code>```

答:
Like you mentioned along lines, using environment variables is more like security through obfuscation.

I would try to have the credentials in a separate configuration file. With a bit of design, encrypt this file and store those keys in secure enclaves or TPMs.

Check this thread.

Title: Correctly hiding database credentials

Body:
As you may see, I have my db connection file and another "protected" file, where my credentials are, and this file is included in .gitignore. I import it and reach the data. Quite basic. Therefore my questions are:

Is this the right way to do it?

If not, how should I do it? Plus: how could I add extra security to my account,connection?

Let's suppose I have a private collection, that no one should see, how could I protect specially this collection? I mean, with a password or a two step verification let's say.

Current code:

const mongoose = require("mongoose");
const mongoCredentials = require("../protected/mongoCredential");

const URI = `mongodb+srv://${mongoCredentials.username}:${mongoCredential.password}
              @firstcluster-eldi8.mongodb.net/culturapp?retryWrites=true&w=majority`;

mongoose.connect(URI, { useUnifiedTopology: true, useNewUrlParser: true })
  .then(db => console.log("MongoDB is connected"))
  .catch(err => console.log(">> ERROR: ",err));

module.exports = mongoose;


问:
Interface argument of TypeScript is not working when the code is transpiled
I have a method inside a class named get()

```<code>import optionsInst from "./options";
get(url, opt: optionsInst){}
</code>```

optionsInst is an interface of another file

```<code>export interface Options {
  tipoRespuesta?: "json" | "arrayBuffer";
  params?: string;
  data?: string;
  headers?: HeadersInit;
}
export default Options;
</code>```

My tsconfig is:

```<code>{
  "compilerOptions": {
    "target": "es6",
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "outDir": "./dist",
    "module": "CommonJS",
    "declaration": true,
    "allowJs": true
  },
  "exclude": ["node_modules"]
}
</code>```

To transpile i use npm run build and a dist folder is generated.
To test it, i create a new file and run npm test.js

```<code>var CL = require("../dist/index.js");

let instancia = new CL("https://reqres.in/api/");
instancia.get("users").then(console.log);
</code>```

The error is like this:

```<code>  if (utils.isEmpty(opt.headers)) {
                              ^

TypeError: Cannot read property 'headers' of undefined
</code>```

答:
If the following line is inside the get(url, opts: optionsInst) method in the class

```<code>if (utils.isEmpty(opt.headers)) {
</code>```

Then your problem is that you're calling it without the ops argument defined, here:

```<code>instancia.get("users").then(console.log);
</code>```

The error is just saying that it can't read the property opt.headers because opt is undefined.

You should actually be getting a Typescript error for that line above, telling you that the opts argument is missing in the call - check that. But Typescript will still compile the code anyway, just resulting in a runtime error when you run it - obviously the very thing Typescript is trying to help you avoid!

Body:
I have a method inside a class named get()

import optionsInst from "./options";
get(url, opt: optionsInst){}

optionsInst is an interface of another file

export interface Options {
  tipoRespuesta?: "json" | "arrayBuffer";
  params?: string;
  data?: string;
  headers?: HeadersInit;
}
export default Options;

My tsconfig is:

{
  "compilerOptions": {
    "target": "es6",
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "outDir": "./dist",
    "module": "CommonJS",
    "declaration": true,
    "allowJs": true
  },
  "exclude": ["node_modules"]
}

To transpile i use npm run build and a dist folder is generated.
To test it, i create a new file and run npm test.js

var CL = require("../dist/index.js");

let instancia = new CL("https://reqres.in/api/");
instancia.get("users").then(console.log);

The error is like this:

  if (utils.isEmpty(opt.headers)) {
                              ^

TypeError: Cannot read property 'headers' of undefined

Body:
If the following line is inside the get(url, opts: optionsInst) method in the class

if (utils.isEmpty(opt.headers)) {

Then your problem is that you're calling it without the ops argument defined, here:

instancia.get("users").then(console.log);

The error is just saying that it can't read the property opt.headers because opt is undefined.

You should actually be getting a Typescript error for that line above, telling you that the opts argument is missing in the call - check that. But Typescript will still compile the code anyway, just resulting in a runtime error when you run it - obviously the very thing Typescript is trying to help you avoid!


问:
How to generate a sample time series data set containing multiple individuals of different length (rows)?
I want to simulate a time series data frame that contains observations of 5 variables that were taken on 10 individuals. I want the number of rows (observations) to be different between each individual. For instance, I could start with something like this:

ID = rep(c("alp", "bet", "char", "delta", "echo"), times = c(1000,1200,1234,980,1300))
```

in which case ID represents each unique individual (I would later turn this into a factor), and the number of times each ID was repeated would represent the length of measurements for that factor. I would next need to create a column called Time with sequences from 1:1000, 1:1200, 1:1234, 1:980, and 1:1300 (to represent the length of measurements for each individual). Lastly I would need to generate 5 columns of random numbers for each of the 5 variables.
There are tons of ways to go about generating this data set, but what would be the most practical way to do it?

Body:
I want to simulate a time series data frame that contains observations of 5 variables that were taken on 10 individuals. I want the number of rows (observations) to be different between each individual. For instance, I could start with something like this:

ID = rep(c("alp", "bet", "char", "delta", "echo"), times = c(1000,1200,1234,980,1300))

in which case ID represents each unique individual (I would later turn this into a factor), and the number of times each ID was repeated would represent the length of measurements for that factor. I would next need to create a column called Time with sequences from 1:1000, 1:1200, 1:1234, 1:980, and 1:1300 (to represent the length of measurements for each individual). Lastly I would need to generate 5 columns of random numbers for each of the 5 variables.
There are tons of ways to go about generating this data set, but what would be the most practical way to do it?

Body:
You can do :

ID = c("alp", "bet", "char", "delta", "echo")
num = c(1000,1200,1234,980,1300)
df <- data.frame(ID = rep(ID, num), num = sequence(num))
df[paste0('rand', seq_along(ID))] <- rnorm(length(ID) * sum(num))

head(df)
#   ID num      rand1       rand2       rand3      rand4       rand5
#1 alp   1  0.1340386  0.95900538  0.84573154  0.7151784 -0.07921171
#2 alp   2  0.2210195  1.67105483 -1.26068288  0.9171749 -0.09736927
#3 alp   3  1.6408462  0.05601673 -0.35454240 -2.6609228  0.21615254
#4 alp   4 -0.2190504 -0.05198191 -0.07355602  1.1102771  0.88246516
#5 alp   5  0.1680654 -1.75323736 -1.16865142 -0.4849876  0.20559750
#6 alp   6  1.1683839  0.09932759 -0.63474826  0.2306168 -0.61643584

I have used rnorm here, you can use any other distribution to generate random numbers.


问:
Disable LAN connection
My system is connected with a LAN connection.

I need to disable my LAN connection,

How could i do this using C# program

Can you help me please??

答:
As I've answered this over on SuperUser - just adding this here as it should only have been on SO:

You can disable/enable your NIC from the command line:

```<code>netsh interface set interface “Local Area Connection” disabled
netsh interface set interface “Local Area Connection” enabled
</code>```

Replace "Local Area Connection" with the name of the Network Interface you want to disable.

You can call this from C# using something like the following:

Enable

```<code>static void Enable(string interfaceName)
{
    System.Diagnostics.ProcessStartInfo psi =
        new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = psi;
    p.Start();
}
</code>```

Disable

```<code>static void Disable(string interfaceName)
{
    System.Diagnostics.ProcessStartInfo psi =
        new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = psi;
    p.Start();
}
</code>```

Title: Disable LAN connection

Body:
As I've answered this over on SuperUser - just adding this here as it should only have been on SO:

You can disable/enable your NIC from the command line:

netsh interface set interface “Local Area Connection” disabled
netsh interface set interface “Local Area Connection” enabled

Replace "Local Area Connection" with the name of the Network Interface you want to disable.

You can call this from C# using something like the following:

Enable

static void Enable(string interfaceName)
{
    System.Diagnostics.ProcessStartInfo psi =
        new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = psi;
    p.Start();
}

Disable

static void Disable(string interfaceName)
{
    System.Diagnostics.ProcessStartInfo psi =
        new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = psi;
    p.Start();
}


问:
Return a map with file sizes using a lambda expression and a regular expression java
How to return a map with the size of files in the specified directory whose names match the specified mask. A DOS mask can contain special characters ' * ' and '?'.

My code:

```<code>public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    return Files.walk(dir)
            .filter(Files::isRegularFile)
            .filter( x -> x.toFile().getName().equals(mask))
            How to make a filter by mask and regular expression correctly? Where to insert "regex"?
            .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
}
}
</code>```

And if you know, tell me the correct regular expression. I made this expression: "(?:(?:*)?(?:\w+))|(?:(?:\?)(?:\w))"

答:
So to combine VGR's excellent suggestion and your slightly tweaked code we're getting something like that:

```<code>public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    PathMatcher pathMatcher = dir.getFileSystem().getPathMatcher("glob:" + mask);
    return Files.walk(dir, recursive ? Integer.MAX_VALUE : 1)
            .filter(Files::isRegularFile)
            .filter(path -> pathMatcher.matches(path.getFileName()))
            .collect(Collectors.toMap(
                    Path::getFileName,
                    path -> {
                        try {
                            return Files.size(path);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }
            ));
}
</code>```

The ugliest part here is handling IOException inside lambda...

Body:
How to return a map with the size of files in the specified directory whose names match the specified mask. A DOS mask can contain special characters ' * ' and '?'.

My code:

public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    return Files.walk(dir)
            .filter(Files::isRegularFile)
            .filter( x -> x.toFile().getName().equals(mask))
            How to make a filter by mask and regular expression correctly? Where to insert "regex"?
            .collect(Collectors.toMap(Path::getFileName, (x) -> x.toFile().length()));
}
}

And if you know, tell me the correct regular expression. I made this expression: "(?:(?:*)?(?:\w+))|(?:(?:\?)(?:\w))"

Body:
So to combine VGR's excellent suggestion and your slightly tweaked code we're getting something like that:

public Map<Path, Long> fileSizes(Path dir, String mask, boolean recursive) throws IOException {
    PathMatcher pathMatcher = dir.getFileSystem().getPathMatcher("glob:" + mask);
    return Files.walk(dir, recursive ? Integer.MAX_VALUE : 1)
            .filter(Files::isRegularFile)
            .filter(path -> pathMatcher.matches(path.getFileName()))
            .collect(Collectors.toMap(
                    Path::getFileName,
                    path -> {
                        try {
                            return Files.size(path);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }
            ));
}

The ugliest part here is handling IOException inside lambda...


问:
Does including ncurses.h in C programming also include stdio.h?
I was studying up on ncurses.h because I am trying to learn a bit of design aspects for c, and stumbled across a statement saying that stdio.h is inside of ncurses

```<code>  #include <ncurses.h>        /*ncurses.h includes stdio.h*/
</code>```

Is this true? If so, can someone explain to me why, and if that means I don't have to ever include it again?

Also, does this cause any issues because I am not exactly defining it in a regular sense

答:
Yes, including <ncurses.h> will  almost certainly include
<stdio.h>.  But I advise not taking advantage of this.

The documentation for ncurses does say:

NOTES

  The header file <curses.h> automatically includes the header
  files <stdio.h> and <unctrl.h>.

(ncurses.h is (usually?) a symbolic link to curses.h.)

Thomas Dickey, the primary maintainer of ncurses, tells
us that this goes
back to 1994, so you're extremely unlikely to encounter an ncurses
implementation that doesn't do this.

The X/Open Curses standard, which ncurses supports, says (emphasis added):

The inclusion of <curses.h> may make visible all symbols from
  the headers <stdio.h>, <term.h>, <termios.h>, and <wchar.h>.

Furthermore, some functions defined in <ncurses.h> and/or
<curses.h> take arguments of type FILE, which is defined in
<stdio.h>. (It's conceivable that something could use the FILE
type without including <stdio.h>, but that would be contrived and
silly, and the possibility is not worth worrying about.)

So #include <ncurses.h> is practically guaranteed to include
<stdio.h>.

Having said all that, I advise against taking advantage of this
guarantee.  If your C source file depends on things declared in
<stdio.h>, as a matter of style you should have an explicit
#include <stdio.h>, even though it's strictly redundant.
More generally, a C source file should have a #include directive
for any header that it depends on.  This is a matter of style and
maintainability, not an absolute requirement.  See, for example,
this question. The C standard guarantees that including <stdio.h> more than once
will not cause problems.

Body:
I was studying up on ncurses.h because I am trying to learn a bit of design aspects for c, and stumbled across a statement saying that stdio.h is inside of ncurses

  #include <ncurses.h>        /*ncurses.h includes stdio.h*/

Is this true? If so, can someone explain to me why, and if that means I don't have to ever include it again?

Also, does this cause any issues because I am not exactly defining it in a regular sense


问:
How to create a Boolean array from an array of indices in numpy?
Given I have an multidimensional array of indices, how do I create a Boolean array from these? For the 1D case it would look like this:

```<code>a = [1,5,6]
b = somefunction(total_array_length=10, a)
>>> [False, True, False, False, False, True, True, False, False, False]
</code>```

For the 2D case it would look like this:

```<code>a = [[1,3],[4,2]]
b = somefunction(total_array_length=5, a)
>>> [[False, True, False, True, False], [False, False, True, False, True]]
</code>```

I want to use this to create a mask for an array. I have a multi dimensional array of dimension 8 and for the last axis I can find the indices of the elements I want to keep. In other words, I have an 8D array in which the last axis consists all indices I want to keep in the original array. Does anyone know how to do this?

In the function above the total_array_length would be equal to the length of the original array.

So how would I do this for an array of shape (23,5,76,32,1,3,8,9) with indices array of shape (23,5,76,32,1,3,8,4)? Note 4<9 but other than that it has the same dimensions.

```<code>a.shape = (23,5,76,32,1,3,8,4)
b = somefunction(total_array_length=9, a)
b.shape =(23,5,76,32,1,3,8,9)
</code>```

答:
For 1D:

```<code>n = 10
inds_all = np.arange(n)
inds = [1, 5, 6]

b = np.isin(inds_all, inds)
# array([False, True, False, False, False, True, True, False, False, False])
</code>```

For 2D it's a little bit trickier, especially when the list of list-indices is of uneven sizes:

```<code>n = 5
inds_all = np.arange(len(inds)*n).reshape(len(inds), n)
inds = [[1,3], [4,2], [3]]
inds = np.concatenate(inds) + np.repeat(inds_all[:,0], list(map(len, inds)))

b = np.isin(inds_all, inds)
# array([[False,  True, False,  True, False],
#        [False, False,  True, False,  True],
#        [False, False, False,  True, False]])
</code>```

Body:
Given I have an multidimensional array of indices, how do I create a Boolean array from these? For the 1D case it would look like this:

a = [1,5,6]
b = somefunction(total_array_length=10, a)
>>> [False, True, False, False, False, True, True, False, False, False]

For the 2D case it would look like this:

a = [[1,3],[4,2]]
b = somefunction(total_array_length=5, a)
>>> [[False, True, False, True, False], [False, False, True, False, True]]

I want to use this to create a mask for an array. I have a multi dimensional array of dimension 8 and for the last axis I can find the indices of the elements I want to keep. In other words, I have an 8D array in which the last axis consists all indices I want to keep in the original array. Does anyone know how to do this?

In the function above the total_array_length would be equal to the length of the original array.

So how would I do this for an array of shape (23,5,76,32,1,3,8,9) with indices array of shape (23,5,76,32,1,3,8,4)? Note 4<9 but other than that it has the same dimensions.

a.shape = (23,5,76,32,1,3,8,4)
b = somefunction(total_array_length=9, a)
b.shape =(23,5,76,32,1,3,8,9)

Body:
For 1D:

n = 10
inds_all = np.arange(n)
inds = [1, 5, 6]

b = np.isin(inds_all, inds)
# array([False, True, False, False, False, True, True, False, False, False])

For 2D it's a little bit trickier, especially when the list of list-indices is of uneven sizes:

n = 5
inds_all = np.arange(len(inds)*n).reshape(len(inds), n)
inds = [[1,3], [4,2], [3]]
inds = np.concatenate(inds) + np.repeat(inds_all[:,0], list(map(len, inds)))

b = np.isin(inds_all, inds)
# array([[False,  True, False,  True, False],
#        [False, False,  True, False,  True],
#        [False, False, False,  True, False]])


问:
Running into segmentation fault when creating an array of a struct
For whatever reason, I cant figure out why I'm running into a segmentation fault.
I've created an array of type 'Card' that should hold 5 cards. Then in make hand I want to add a suit and face to each card in that array.

I think the problem is either occurring with the type of data (Constant or non-constant??)
With something passing the array and accessing it in the new function
OR
with allocating the memory properly.

Please help!!
Thank you.

Here is my code to create a user's "hand"
This is where the segmentation fault is happening

```<code>// Make the user's hand here
void makeHand(const Card * deck, Card * cardArray[5]){
    // loop through Deck
    for (size_t i = 0; i < 5; ++i) {
        printf("%5s of %-8s%s", deck[i].face, deck[i].suit,
               (i + 1) % 4 ? "  " : "\n");

        cardArray[i]->face = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->face, deck[i].face);

        cardArray[i]->suit = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->suit, deck[i].suit);
    }
}
</code>```

Here is my main function:

```<code>int main(void){
   Card deck[CARDS]; // define array of Cards

   // initialize array of pointers
   const char *face[] = { "Ace", "Two", "Three", "Four", "Five",
      "Six", "Seven", "Eight", "Nine", "Ten",
      "Jack", "Queen", "King"};

   // initialize array of pointers
   const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"};

   srand(time(NULL)); // randomize

   fillDeck(deck, face, suit); // load the deck with Cards
   shuffle(deck); // put Cards in random order
   deal(deck); // deal all 52 Cards

   // Make an array that holds 5 cards, initialize to 0
   Card cardArray[5];
   makeHand(deck, cardArray);

   //twoPair(cardArray);
}
</code>```

General Definitions:

```<code>#define CARDS 52
#define FACES 13

// card structure definition
struct card {
    const char *face; // define pointer face
    const char *suit; // define pointer suit
};

typedef struct card Card; // new type name for struct card

// prototypes
void fillDeck(Card * wDeck, const char * wFace[],
   const char * wSuit[]);
void shuffle(Card * wDeck);
void deal(const Card * wDeck);

// Make a 5 card hand and return it
// should return an array of 5 cards
void makeHand(const Card * deck, Card * cardArray[5]);

// Definitions to check for each condition
void twoPair(Card *cardArray[5]);
</code>```

答:
I believe you problem lies in your understanding of pointers.

Essentially, marking a variable with * and making it an "array" with [] do very very similar things.  They BOTH make a pointer, but with the [] operator, you are specifying to the system the length of the array.  The variable is holding the memory address of a point in memory, and an array, before you dereference it, is holding the memory address of a point in memory.  your function:

```<code>void makeHand(const Card * deck, Card * cardArray[5]){
    // loop through Deck
    for (size_t i = 0; i < 5; ++i) {
        printf("%5s of %-8s%s", deck[i].face, deck[i].suit,
               (i + 1) % 4 ? "  " : "\n");

        cardArray[i]->face = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->face, deck[i].face);

        cardArray[i]->suit = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->suit, deck[i].suit);
    }
}
</code>```

This function takes in a pointer(array) of type Card called deck, and a pointer(array) of an array of type Card called cardArray.  Then you call this function like:

makeHand(deck, cardArray);

deck is the correct type, it is a pointer of type Card.  However, cardArray is only an array, not a pointer to an array.  I'm not sure exactly the functionality you are trying to achieve, but changing makeHand to look like:

```<code>void makeHand(Card* deck, Card* cardArray) {}
</code>```

should suit your needs.

CLARIFICATION: a pointer is not the same exact thing as an array, I just think it's a useful comparison in understanding the difference between the two.

```<code>Card* deck;
</code>```

and

```<code>Card deck[];
</code>```

will do the same thing in memory

Body:
For whatever reason, I cant figure out why I'm running into a segmentation fault.
I've created an array of type 'Card' that should hold 5 cards. Then in make hand I want to add a suit and face to each card in that array.

I think the problem is either occurring with the type of data (Constant or non-constant??)
With something passing the array and accessing it in the new function
OR
with allocating the memory properly.

Please help!!
Thank you.

Here is my code to create a user's "hand"
This is where the segmentation fault is happening

// Make the user's hand here
void makeHand(const Card * deck, Card * cardArray[5]){
    // loop through Deck
    for (size_t i = 0; i < 5; ++i) {
        printf("%5s of %-8s%s", deck[i].face, deck[i].suit,
               (i + 1) % 4 ? "  " : "\n");

        cardArray[i]->face = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->face, deck[i].face);

        cardArray[i]->suit = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->suit, deck[i].suit);
    }
}

Here is my main function:

int main(void){
   Card deck[CARDS]; // define array of Cards

   // initialize array of pointers
   const char *face[] = { "Ace", "Two", "Three", "Four", "Five",
      "Six", "Seven", "Eight", "Nine", "Ten",
      "Jack", "Queen", "King"};

   // initialize array of pointers
   const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"};

   srand(time(NULL)); // randomize

   fillDeck(deck, face, suit); // load the deck with Cards
   shuffle(deck); // put Cards in random order
   deal(deck); // deal all 52 Cards

   // Make an array that holds 5 cards, initialize to 0
   Card cardArray[5];
   makeHand(deck, cardArray);

   //twoPair(cardArray);
}

General Definitions:

#define CARDS 52
#define FACES 13

// card structure definition
struct card {
    const char *face; // define pointer face
    const char *suit; // define pointer suit
};

typedef struct card Card; // new type name for struct card

// prototypes
void fillDeck(Card * wDeck, const char * wFace[],
   const char * wSuit[]);
void shuffle(Card * wDeck);
void deal(const Card * wDeck);

// Make a 5 card hand and return it
// should return an array of 5 cards
void makeHand(const Card * deck, Card * cardArray[5]);

// Definitions to check for each condition
void twoPair(Card *cardArray[5]);

Body:
I believe you problem lies in your understanding of pointers.

Essentially, marking a variable with * and making it an "array" with [] do very very similar things.  They BOTH make a pointer, but with the [] operator, you are specifying to the system the length of the array.  The variable is holding the memory address of a point in memory, and an array, before you dereference it, is holding the memory address of a point in memory.  your function:

void makeHand(const Card * deck, Card * cardArray[5]){
    // loop through Deck
    for (size_t i = 0; i < 5; ++i) {
        printf("%5s of %-8s%s", deck[i].face, deck[i].suit,
               (i + 1) % 4 ? "  " : "\n");

        cardArray[i]->face = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->face, deck[i].face);

        cardArray[i]->suit = malloc(sizeof(char) * 25);
        strcpy(cardArray[i]->suit, deck[i].suit);
    }
}

This function takes in a pointer(array) of type Card called deck, and a pointer(array) of an array of type Card called cardArray.  Then you call this function like:

makeHand(deck, cardArray);

deck is the correct type, it is a pointer of type Card.  However, cardArray is only an array, not a pointer to an array.  I'm not sure exactly the functionality you are trying to achieve, but changing makeHand to look like:

void makeHand(Card* deck, Card* cardArray) {}

should suit your needs.

CLARIFICATION: a pointer is not the same exact thing as an array, I just think it's a useful comparison in understanding the difference between the two.

Card* deck;

and

Card deck[];

will do the same thing in memory


问:
Prevent React-native WebView from downloading a PDF
This question is relevant to all Android Chrome browsers I think, but in my case I am using the React-native WebView (which is compiling to the native webview in the app). I should add that this works fine on iOS because a URL which points to a PDF just loads that PDF in the browser.

So, I'm wondering whether there's a way to force the Chrome browser to load a PDF in the browser using a header?

Or, is there a URL that allows you to pass the PDF url in as a param? Some kind of proxy service.

Any ideas?

答:
I solved this issue by using Google Docs to display the given pdf url. Just replace my_pdf_url with your pdf url.

https://docs.google.com/gview?embedded=true&url=my_pdf_url


问:
Calling MPI_Comm_Split function
My question is probably stupid but still I'm gonna ask it to be sure !

Question : Do you expect the two codes below to work the same using MPI_Comm_Split to build 1 sub-communicator ? (for example, let's say I'm running the code with 6 procs with a rank between 0 and 5)

NB : The code is in fortran 90 with intel compiler 2019 and I use Mpich for the Mpi.

CODE 1

```<code>call Mpi_Init(ierror)
call Mpi_Comm_Rank(mpi_comm_world,rank,ierror)

if (rank > 2) then
    call Mpi_Comm_Split(mpi_comm_world,0,rank,new_comm,ierror)
else
    call Mpi_Comm_Split(mpi_comm_world,mpi_undefined,rank,new_comm,ierror)
endif
</code>```

CODE 2

```<code>call Mpi_Init(ierror)
call Mpi_Comm_Rank(mpi_comm_world,rank,ierror)

if (rank > 2) then
    color = 0
else
    color = mpi_undefined
endif

call Mpi_Comm_Split(mpi_comm_world,color,rank,new_comm,ierror)

</code>```

The Mpi_Comm_Split is not called the same way in the 2 codes but to me, it should behave the same but I'm not sure... I read that Mpi_Comm_Split has to be invoked at the same line but how procs can know that the call of Mpi_Comm_Split is done at a one line or another one (it doesn't make anysense to me) ?!

NB : With Mpich and intel fortran, I tested it and both implentation of the communicator splitting works, but I'm afraid of the behavior of different Mpi compilers...

答:
Assuming you declared color correctly, both codes are equivalent.

MPI_Comm_split() is a collective operation, and hence must be invoked by all the ranks of the parent communicator. That does not mandate the call has to be performed by the same line of code.

Title: Calling MPI_Comm_Split function

Body:
My question is probably stupid but still I'm gonna ask it to be sure !

Question : Do you expect the two codes below to work the same using MPI_Comm_Split to build 1 sub-communicator ? (for example, let's say I'm running the code with 6 procs with a rank between 0 and 5)

NB : The code is in fortran 90 with intel compiler 2019 and I use Mpich for the Mpi.

CODE 1

call Mpi_Init(ierror)
call Mpi_Comm_Rank(mpi_comm_world,rank,ierror)

if (rank > 2) then
    call Mpi_Comm_Split(mpi_comm_world,0,rank,new_comm,ierror)
else
    call Mpi_Comm_Split(mpi_comm_world,mpi_undefined,rank,new_comm,ierror)
endif

CODE 2

call Mpi_Init(ierror)
call Mpi_Comm_Rank(mpi_comm_world,rank,ierror)

if (rank > 2) then
    color = 0
else
    color = mpi_undefined
endif

call Mpi_Comm_Split(mpi_comm_world,color,rank,new_comm,ierror)

The Mpi_Comm_Split is not called the same way in the 2 codes but to me, it should behave the same but I'm not sure... I read that Mpi_Comm_Split has to be invoked at the same line but how procs can know that the call of Mpi_Comm_Split is done at a one line or another one (it doesn't make anysense to me) ?!

NB : With Mpich and intel fortran, I tested it and both implentation of the communicator splitting works, but I'm afraid of the behavior of different Mpi compilers...


问:
DFT matrix in python
What's the easiest way to get the DFT matrix for 2-d DFT in python? I could not find such function in numpy.fft. Thanks!</p>

答:
If you wish to compute the 2D DFT as a single matrix operation, it is necessary to unravel the matrix X on which you wish to compute the DFT into a vector, as each output of the DFT has a sum over every index in the input, and a single square matrix multiplication does not have this ability. Taking care to be sure we are handling the indices correctly, I find the following works:

```<code>M = 16
N = 16
X = np.random.random((M,N)) + 1j*np.random.random((M,N))
Y = np.fft.fft2(X)
W = np.zeros((M*N,M*N),dtype=np.complex)

hold = []
for m in range(M):
    for n in range(N):
        hold.append((m,n))

for j in range(M*N):
    for i in range(M*N):
        k,l = hold[j]
        m,n = hold[i]
        W[j,i] = np.exp(-2*np.pi*1j*(m*k/M + n*l/N))

np.allclose(np.dot(W,X.ravel()),Y.ravel())
True
</code>```

If you wish to change the normalization to orthogonal, you can divide by 1/sqrt(MN) or if you wish to have the inverse transformation, just change the sign in the exponent.

Title: DFT matrix in python

Body:
If you wish to compute the 2D DFT as a single matrix operation, it is necessary to unravel the matrix X on which you wish to compute the DFT into a vector, as each output of the DFT has a sum over every index in the input, and a single square matrix multiplication does not have this ability. Taking care to be sure we are handling the indices correctly, I find the following works:

M = 16
N = 16
X = np.random.random((M,N)) + 1j*np.random.random((M,N))
Y = np.fft.fft2(X)
W = np.zeros((M*N,M*N),dtype=np.complex)

hold = []
for m in range(M):
    for n in range(N):
        hold.append((m,n))

for j in range(M*N):
    for i in range(M*N):
        k,l = hold[j]
        m,n = hold[i]
        W[j,i] = np.exp(-2*np.pi*1j*(m*k/M + n*l/N))

np.allclose(np.dot(W,X.ravel()),Y.ravel())
True

If you wish to change the normalization to orthogonal, you can divide by 1/sqrt(MN) or if you wish to have the inverse transformation, just change the sign in the exponent.


答:
Correct code:

```<code>void makeHand(const Card * deck, Card *cardArray){
    // loop through Deck
    for (size_t i = 0; i < 5; ++i) {
        printf("%5s of %-8s%s", deck[i].face, deck[i].suit,
               (i + 1) % 4 ? "  " : "\n");

        cardArray[i].face = malloc(sizeof(char) * 25);
        strcpy(cardArray[i].face, deck[i].face);

        cardArray[i].suit = malloc(sizeof(char) * 25);
        strcpy(cardArray[i].suit, deck[i].suit);
    }
}
</code>```

You probably want to use cardArray[5]; defined in main? For now, you take the array, use it's elements as pointers (they are not pointing to anywhere valid) and try to find the Card structures there (and write to that non-existing "faces" and "suits".

Title: Running into segmentation fault when creating an array of a struct

Body:
Correct code:

void makeHand(const Card * deck, Card *cardArray){
    // loop through Deck
    for (size_t i = 0; i < 5; ++i) {
        printf("%5s of %-8s%s", deck[i].face, deck[i].suit,
               (i + 1) % 4 ? "  " : "\n");

        cardArray[i].face = malloc(sizeof(char) * 25);
        strcpy(cardArray[i].face, deck[i].face);

        cardArray[i].suit = malloc(sizeof(char) * 25);
        strcpy(cardArray[i].suit, deck[i].suit);
    }
}

You probably want to use cardArray[5]; defined in main? For now, you take the array, use it's elements as pointers (they are not pointing to anywhere valid) and try to find the Card structures there (and write to that non-existing "faces" and "suits".


问:
Implementing List-Unsubscribe header(s) with swiftmailer (rfc2369, rfc6068, rfc8058, and friends)
Has anyone implemented the List-Unsubscribe & List-Unsubscribe-Post headers using swiftmailer ?

I know how to insert headers ...

```<code>$_headers = $message->getHeaders();
$_headers->addTextHeader( 'List-Unsubscribe', $list_unsubscribe );
if ( $has_dkim ) $_headers->addTextHeader( 'List-Unsubscribe-Post', 'List-Unsubscribe=One-Click' );
</code>```

$list_unsubscribe variable may contain one <url> and/or one <mailto>

1st problem : Whatever the order of List-Unsubscribe and List-Unsubscribe-Post headers are set, they always appear in the wrong order (List-Unsubscribe-Post before List-Unsubscribe).
I tried to change header ordering using method defineOrdering, but that did not work as intended.
I even tried to hack the swiftmailer code to append those two new headers to the existing order list ... but did not work !

2nd problem : Would appreciate any hint on how to encode properly these two <url> & <mailto> using swiftmailer toolbox (i am also using the Decorator plugin).

Thank you for your answers.

答:
So, 1st problem is solved !

According to RFC 5322

... header fields are not guaranteed to be in a particular order.

Body:
Has anyone implemented the List-Unsubscribe & List-Unsubscribe-Post headers using swiftmailer ?

I know how to insert headers ...

$_headers = $message->getHeaders();
$_headers->addTextHeader( 'List-Unsubscribe', $list_unsubscribe );
if ( $has_dkim ) $_headers->addTextHeader( 'List-Unsubscribe-Post', 'List-Unsubscribe=One-Click' );

$list_unsubscribe variable may contain one <url> and/or one <mailto>

1st problem : Whatever the order of List-Unsubscribe and List-Unsubscribe-Post headers are set, they always appear in the wrong order (List-Unsubscribe-Post before List-Unsubscribe).
I tried to change header ordering using method defineOrdering, but that did not work as intended.
I even tried to hack the swiftmailer code to append those two new headers to the existing order list ... but did not work !

2nd problem : Would appreciate any hint on how to encode properly these two <url> & <mailto> using swiftmailer toolbox (i am also using the Decorator plugin).

Thank you for your answers.


问:
regex pattern to tokenize sentence while stripping end punctuation?
I need to make a regex pattern that can tokenize a sentence with that also has punctuation tokenized separately, except for acronyms, contractions, and hyphens.

```<code>"This is a test sentence. I won't write this sentence. J. Smith lives in the U.S.A. and it is nice there."
</code>```

should return as

```<code>["This" "is" "a" "test" "sentence" "." "I" "won't" "write" "this" "sentence" "." "J." "Smith" "lives"
 "in" "the" "U.S.A." "and" "it" "is" "nice" "there" ."]
</code>```

My code currently is:

```<code>tokens = re.findall(r'((\.\s)|(\S+))', sentence)
</code>```

But this doesn't work correctly. It matches the period at the end of words as part of the word.

答:
This isn't possible with regex.  There's no way to differentiate words containing punctuation ("J." in your example, or "Jr." would be one that's not a single character) where you want the punctuation as part of the token, from words followed by punctuation ("sentence." in your example) where you want the punctuation as its own token.

You need a natural language parsing library to get this to work as you've described the problem.

It may be possible to devise some heuristics like the length of the word and whether it's followed by a word with a capital letter, or whitelist common words that break the rules, but you're going to have issues making this work robustly.

Body:
I need to make a regex pattern that can tokenize a sentence with that also has punctuation tokenized separately, except for acronyms, contractions, and hyphens.

"This is a test sentence. I won't write this sentence. J. Smith lives in the U.S.A. and it is nice there."

should return as

["This" "is" "a" "test" "sentence" "." "I" "won't" "write" "this" "sentence" "." "J." "Smith" "lives"
 "in" "the" "U.S.A." "and" "it" "is" "nice" "there" ."]

My code currently is:

tokens = re.findall(r'((\.\s)|(\S+))', sentence)

But this doesn't work correctly. It matches the period at the end of words as part of the word.


问:
Creating a box plot with facets
I am trying to create a box plot that shows the variance for values from 8 cities. With them being displayed using facets based on education attainment levels.
Here is data frame 1

for example I want to see how much variance there is between HS_grad numbers for all the cities.

Update

Here is data frame 2

答:
Welcome! Please read up on How to make a great R reproducible example.

Based on your screenshots, you will need to convert your dataset into a "long format" rather than the current "wide format". I think the code below should achieve what you want.

```<code># Install packages
install.packages("tidyverse")

# Load
library(tidyverse)

# "df" is your data frame as shown in your screenshot
df %>%
  # Change from wide to long format
  gather(City, Value, -EA) %>%
  # Plot
  ggplot(aes(x = EA, y = Value)) +
  facet_wrap(~ City) +
  geom_boxplot()
</code>```

Title: Creating a box plot with facets

Body:
Welcome! Please read up on How to make a great R reproducible example.

Based on your screenshots, you will need to convert your dataset into a "long format" rather than the current "wide format". I think the code below should achieve what you want.

# Install packages
install.packages("tidyverse")

# Load
library(tidyverse)

# "df" is your data frame as shown in your screenshot
df %>%
  # Change from wide to long format
  gather(City, Value, -EA) %>%
  # Plot
  ggplot(aes(x = EA, y = Value)) +
  facet_wrap(~ City) +
  geom_boxplot()


问:
Change WPF DataGrid column cell background color based on values
I am trying to fill cells with color in certain column. Column name is "NRO" and I want to fill cells staring with 2 yellow color and cells starting with 3 blue color. I went through answer given here: Change DataGrid cell colour based on values

Also tried several other approaches but can't get any of them work. I also don't understand how to implement any of them in my setup. They all seems to have <DataGridTextColumn Binding="{Binding Name}">. What it should be in my case?

Here is my XAML:

```<code><Window x:Class="DB_inspector_FilterTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="DB database inspector v.0.0.01" Height="600" Width="1000" Icon="logo_icon-small.jpg" Background="White">
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="DataGrid1" Margin="0,103,0,0" Background="White" BorderBrush="#FF38853F"/>
        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="20" Margin="22,41,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="437" TextChanged="NameSearch_TextChanged"/>
        <Button Content="Load" Margin="640,41,0,0" Click="Button_Click_1" BorderBrush="{x:Null}" Foreground="White" Background="#FF55B432" Width="66" Height="29" HorizontalAlignment="Left" VerticalAlignment="Top"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="11" VerticalAlignment="Top" Width="992" BorderBrush="{x:Null}" Background="{x:Null}"/>
        <Label Content="Customer name" HorizontalAlignment="Left" Height="25" Margin="22,11,0,0" VerticalAlignment="Top" Width="154"/>
        <CheckBox x:Name="ActiveCustomer" Content="Active" HorizontalAlignment="Left" Height="24" Margin="486,63,0,0" VerticalAlignment="Top" Width="86" Click="ActiveCustomer_Click_1"/>
        <CheckBox x:Name="Only" Content="Leave only good" HorizontalAlignment="Left" Height="17" Margin="486,41,0,0" VerticalAlignment="Top" Width="115" Click="CheckBox_Click"/>
        <Image Margin="856,0,22,520" VerticalAlignment="Bottom" Source="logo_small.jpg" Height="27"/>

    </Grid>
</Window>
</code>```

ADDITION:

If anybody have time, while I will be trying to figure it out myself, give me some hints how to proceed with my application, here is my full code:

```<code>using System.Data.Odbc;
using System.Windows;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;

namespace DB_inspector_FilterTest
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                ProgressBar.IsIndeterminate = true;

                DataGrid1.ItemsSource = await GetDataAsync();

                ProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private Task<DataView> GetDataAsync()
        {
            return Task.Run(() =>
            {

                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSSE;Uid=ADMIN;Pwd=123;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSFI;Uid=ADMIN;Pwd=123;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                DataTable dataTable = new DataTable("COMPANY");
                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    dadapterDE.Fill(dataTable);

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var newTable = new DataTable("COMPANY");
                    dadapterFR.Fill(newTable);

                    dataTable.Merge(newTable);

                }

                return dataTable.DefaultView;

            });
        }

        private Dictionary<string, string> _conditions = new Dictionary<string, string>();

        private void UpdateFilter()
        {
            try
            {
                var activeConditions = _conditions.Where(c => c.Value != null).Select(c => "(" + c.Value + ")");
                DataView dv = DataGrid1.ItemsSource as DataView;
                dv.RowFilter = string.Join(" AND ", activeConditions);
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void NameSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            string filter = NameSearch.Text;
            if (string.IsNullOrEmpty(filter))
                _conditions["name"] = null;
            else
                _conditions["name"] = string.Format("NAME Like '%{0}%'", filter);
            UpdateFilter();
        }

        private void ActiveCustomer_Click_1(object sender, RoutedEventArgs e)
        {
            if (ActiveCustomer.IsChecked == true)
            {
                _conditions["active"] = string.Format("ACTIVE Like '%{0}%'", "1");
                UpdateFilter();
            }
            else
            {
                _conditions["active"] = null;
                UpdateFilter();
            }
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (OnlyFIandSE.IsChecked == true)
            {
                _conditions["onlyfrandde"] = string.Format("NRO Like '2%' OR NRO Like '3%'");
                UpdateFilter();
            }
            else
            {
                _conditions["onlyfrandde"] = null;
                UpdateFilter();
            }
        }
    }
}
</code>```

Things I don't understand at least now: How in my case I should setup ItemSource for binding? Should I import databases to List first and then Bind to the list?

ATTEMPT 3:

Here is my latest MVVM attempt.

C#:

```<code>using System;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Windows;
using System.Windows.Input;

namespace DB_inspector
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

    }

    public class ViewModel : INotifyPropertyChanged
    {
        public ICommand myCommand => new RelayCommand(obj =>
        {
            try
            {
                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSSE;Uid=ADMIN;Pwd=123;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSFI;Uid=ADMIN;Pwd=123;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                DataTable dataTable = new DataTable("COMPANY");
                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    dadapterDE.Fill(dataTable);

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var newTable = new DataTable("COMPANY");
                    dadapterFR.Fill(newTable);

                    dataTable.Merge(newTable);

                }

                _ = dataTable.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        });

        private bool _allowUIChanges = true;
        public bool AllowUIChanges
        {
            get => _allowUIChanges;
            set
            {
                _allowUIChanges = value;
                OnPropertyChanged(nameof(AllowUIChanges));
                OnPropertyChanged(nameof(IsReadOnlyDataGrid));
            }
        }

        private void OnPropertyChanged(string v)
        {
            throw new NotImplementedException();
        }

        public bool IsReadOnlyDataGrid
        {
            get => !_allowUIChanges;
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object, bool> _canExecute;

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }
        public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

        public void Execute(object parameter) => _execute(parameter);
    }
}
</code>```

XAML:

```<code><Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <DataGrid IsReadOnly="{Binding IsReadOnlyDataGrid}" AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}" Width="998" Margin="0,98,0,0" >
        </DataGrid>
        <Image Height="41" Margin="0,21,10,0" Width="141" Source="logo_small.jpg" HorizontalAlignment="Right" VerticalAlignment="Top"/>
        <Button Content="Go" Command="{Binding myCommand}" Width="80" Height="30" Margin="48,42,870,492"/>

    </Grid>
</Window>
</code>```

Any suggestions what is still wrong here? No errors, but button does not process anything.

答:
I suggest IValueConverter or IMultiValueConverter binding for Cell's Background property.

I'm not sure how it works with autogenerated columns set but with manual it looks like this. I'm providing here not a working copy but a markup example.

XAML

<Window.Resources>
    <local:MyCellBackgroundConverter x:Key="myCellBackgroundConverter"/>
</Window.Resources>
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
<Grid>

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}">
    <DataGridTextColumn Header="Column1" Binding="{Binding Value1}">
        <DataGridTextColumn.CellStyle>

        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    <DataGridTextColumn Header="Column2" Binding="{Binding Value2}"/>
</DataGrid>
</Grid>
```

<p>The ViewModel Class</p>

<pre class="lang-cs prettyprint-override"><code>using System.Collections.ObjectModel;
using System.ComponentModel;

// ...

public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<MyItem> _myCollection = new ObservableCollection<MyItem>();
    public ObservableCollection<MyItem> MyCollection
    {
        get => _myCollection;
        set
        {
            _myCollection = value;
            OnPropertyChanged(nameof(MyCollection));
        }
    }

    public ViewModel()
         // you may load or add the data to MyCollection here
    {

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
</code>```

Item

using System.ComponentModel;

// ...

public class MyItem : INotifyPropertyChanged
{
    private string _value1 = string.Empty;
    private string _value2 = string.Empty;

    public string Value1
    {
        get => _value1;
        set { _value1 = value; OnPropertyChanged(nameof(Value1)); }
    }

    public string Value2
    {
        get => _value2;
        set { _value2 = value; OnPropertyChanged(nameof(Value2)); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
```

<p>And finally the Converter</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

//...

public class MyCellBackgroundConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[0] is string value1 && values[1] is string value2)
        {
            if (value1.Length > 0)
            {
                return Brushes.Green;
            }
            else
            if (value2.Length > 0)
            {
                return Brushes.Yellow;
            }
            else
                return Brushes.Red;
        }
        else return Brushes.White;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => null;
}
</code>```

In alternative way you may use Style.DataTriggers directly in XAML.

For additional information about bindings and properties look for MVVM programming pattern. In short you're not need x:Name anymore because in MVVM pattern you interacting only with ViewModel class data instances and can't interact with contols directly there (and that's fine). Meanwhile Contols automatically sync with data binded to them. Calling OnPropertyChanged("PropertyName") here simply cause the GUI refresh.

In relation to markup of your XAML example, try wrapping the Control groups in StackPanel and learn about it. It will save your time spent fighting with margins. Simply set few colums and/or rows in Window's Grid and place StackPanels there assigning Grid.Column and Grid.Row to them.

ADDITION:

How in my case I should setup ItemSource for binding? Should I import databases to List first and then Bind to the list?

ObservableCollection<> is same as List<> and you may use it in the same way. The difference that first one implements CollectionChanged event that notifies DataGrid if any items was added or removed from the collection.

Your Button.Click event handler contains redundant async/await declaration.

Let's move forward and see how it can be done with MVVM.

XAML

<Button Content="Go" Command="{Binding myCommand}"/>
```

<p>Command must implement ICommand interface. You have to do 2 things for proper implementation:</p>

<p>1) Add <code>RelayCommand</code> separate Class implementing <code>ICommand</code> interface</p>

<pre class="lang-cs prettyprint-override"><code>public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

    public void Execute(object parameter) => _execute(parameter);
}
</code>```

2) Add the Command instance to your ViewModel class

public ICommand myCommand => new RelayCommand(obj =>
{
    // do the same here as in Button.Click above
});
```

<p>Next, you may need some blocking UI thing that will prevent user from any actions while data is loading.</p>

<p>ViewModel</p>

<pre class="lang-cs prettyprint-override"><code>private bool _allowUIChanges = true;
public bool AllowUIChanges
{
    get => _allowUIChanges;
    set
    {
        _allowUIChanges = value;
        OnPropertyChanged(nameof(AllowUIChanges));
        OnPropertyChanged(nameof(IsReadOnlyDataGrid));
    }
}
public bool IsReadOnlyDataGrid
{
    get => !_allowUIChanges;
}
</code>```

Finally bind your Control properties to it

XAML

<Button Content="Go" Command="{Binding myCommand}" Enabled="{Binding AllowUIChanges}"/>
<DataGrid IsReadOnly="{Binding IsReadOnlyDataGrid}" AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}">
```

Then set AllowUIChanges to false while data is loading.

Body:
I am trying to fill cells with color in certain column. Column name is "NRO" and I want to fill cells staring with 2 yellow color and cells starting with 3 blue color. I went through answer given here: Change DataGrid cell colour based on values

Also tried several other approaches but can't get any of them work. I also don't understand how to implement any of them in my setup. They all seems to have <DataGridTextColumn Binding="{Binding Name}">. What it should be in my case?

Here is my XAML:

<Window x:Class="DB_inspector_FilterTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="DB database inspector v.0.0.01" Height="600" Width="1000" Icon="logo_icon-small.jpg" Background="White">
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="DataGrid1" Margin="0,103,0,0" Background="White" BorderBrush="#FF38853F"/>
        <TextBox x:Name="NameSearch" HorizontalAlignment="Left" Height="20" Margin="22,41,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="437" TextChanged="NameSearch_TextChanged"/>
        <Button Content="Load" Margin="640,41,0,0" Click="Button_Click_1" BorderBrush="{x:Null}" Foreground="White" Background="#FF55B432" Width="66" Height="29" HorizontalAlignment="Left" VerticalAlignment="Top"/>
        <ProgressBar x:Name="ProgressBar" HorizontalAlignment="Left" Height="11" VerticalAlignment="Top" Width="992" BorderBrush="{x:Null}" Background="{x:Null}"/>

        <CheckBox x:Name="ActiveCustomer" Content="Active" HorizontalAlignment="Left" Height="24" Margin="486,63,0,0" VerticalAlignment="Top" Width="86" Click="ActiveCustomer_Click_1"/>
        <CheckBox x:Name="Only" Content="Leave only good" HorizontalAlignment="Left" Height="17" Margin="486,41,0,0" VerticalAlignment="Top" Width="115" Click="CheckBox_Click"/>
        <Image Margin="856,0,22,520" VerticalAlignment="Bottom" Source="logo_small.jpg" Height="27"/>

    </Grid>
</Window>

ADDITION:

If anybody have time, while I will be trying to figure it out myself, give me some hints how to proceed with my application, here is my full code:

using System.Data.Odbc;
using System.Windows;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;

namespace DB_inspector_FilterTest
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                ProgressBar.IsIndeterminate = true;

                DataGrid1.ItemsSource = await GetDataAsync();

                ProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private Task<DataView> GetDataAsync()
        {
            return Task.Run(() =>
            {

                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSSE;Uid=ADMIN;Pwd=123;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSFI;Uid=ADMIN;Pwd=123;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                DataTable dataTable = new DataTable("COMPANY");
                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    dadapterDE.Fill(dataTable);

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var newTable = new DataTable("COMPANY");
                    dadapterFR.Fill(newTable);

                    dataTable.Merge(newTable);

                }

                return dataTable.DefaultView;

            });
        }

        private Dictionary<string, string> _conditions = new Dictionary<string, string>();

        private void UpdateFilter()
        {
            try
            {
                var activeConditions = _conditions.Where(c => c.Value != null).Select(c => "(" + c.Value + ")");
                DataView dv = DataGrid1.ItemsSource as DataView;
                dv.RowFilter = string.Join(" AND ", activeConditions);
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void NameSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            string filter = NameSearch.Text;
            if (string.IsNullOrEmpty(filter))
                _conditions["name"] = null;
            else
                _conditions["name"] = string.Format("NAME Like '%{0}%'", filter);
            UpdateFilter();
        }

        private void ActiveCustomer_Click_1(object sender, RoutedEventArgs e)
        {
            if (ActiveCustomer.IsChecked == true)
            {
                _conditions["active"] = string.Format("ACTIVE Like '%{0}%'", "1");
                UpdateFilter();
            }
            else
            {
                _conditions["active"] = null;
                UpdateFilter();
            }
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (OnlyFIandSE.IsChecked == true)
            {
                _conditions["onlyfrandde"] = string.Format("NRO Like '2%' OR NRO Like '3%'");
                UpdateFilter();
            }
            else
            {
                _conditions["onlyfrandde"] = null;
                UpdateFilter();
            }
        }
    }
}

Things I don't understand at least now: How in my case I should setup ItemSource for binding? Should I import databases to List first and then Bind to the list?

ATTEMPT 3:

Here is my latest MVVM attempt.

C#:

using System;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Windows;
using System.Windows.Input;

namespace DB_inspector
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {

    }

    public class ViewModel : INotifyPropertyChanged
    {
        public ICommand myCommand => new RelayCommand(obj =>
        {
            try
            {
                string connectionStringDE = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSSE;Uid=ADMIN;Pwd=123;";

                string queryStringDE = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                string connectionStringFR = "Driver={Pervasive ODBC Client Interface};ServerName=DB123;dbq=@DBFSFI;Uid=ADMIN;Pwd=123;";

                string queryStringFR = "select NRO,NAME,NAMEA,NAMEB,ADDRESS,POSTA,POSTN,POSTB,CORPORATION,COUNTRY,ID,ACTIVE from COMPANY";

                DataTable dataTable = new DataTable("COMPANY");
                // using-statement will cleanly close and dispose unmanaged resources i.e. IDisposable instances
                using (OdbcConnection dbConnectionDE = new OdbcConnection(connectionStringDE))
                {
                    dbConnectionDE.Open();
                    OdbcDataAdapter dadapterDE = new OdbcDataAdapter();
                    dadapterDE.SelectCommand = new OdbcCommand(queryStringDE, dbConnectionDE);

                    dadapterDE.Fill(dataTable);

                }
                using (OdbcConnection dbConnectionFR = new OdbcConnection(connectionStringFR))
                {
                    dbConnectionFR.Open();
                    OdbcDataAdapter dadapterFR = new OdbcDataAdapter();
                    dadapterFR.SelectCommand = new OdbcCommand(queryStringFR, dbConnectionFR);

                    var newTable = new DataTable("COMPANY");
                    dadapterFR.Fill(newTable);

                    dataTable.Merge(newTable);

                }

                _ = dataTable.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        });

        private bool _allowUIChanges = true;
        public bool AllowUIChanges
        {
            get => _allowUIChanges;
            set
            {
                _allowUIChanges = value;
                OnPropertyChanged(nameof(AllowUIChanges));
                OnPropertyChanged(nameof(IsReadOnlyDataGrid));
            }
        }

        private void OnPropertyChanged(string v)
        {
            throw new NotImplementedException();
        }

        public bool IsReadOnlyDataGrid
        {
            get => !_allowUIChanges;
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object, bool> _canExecute;

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }
        public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

        public void Execute(object parameter) => _execute(parameter);
    }
}

XAML:

<Window x:Class="DB_inspector.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="DB database inspector" Height="595.404" Width="1005.571">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <DataGrid IsReadOnly="{Binding IsReadOnlyDataGrid}" AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}" Width="998" Margin="0,98,0,0" >
        </DataGrid>
        <Image Height="41" Margin="0,21,10,0" Width="141" Source="logo_small.jpg" HorizontalAlignment="Right" VerticalAlignment="Top"/>
        <Button Content="Go" Command="{Binding myCommand}" Width="80" Height="30" Margin="48,42,870,492"/>

    </Grid>
</Window>

Any suggestions what is still wrong here? No errors, but button does not process anything.

Body:
I suggest IValueConverter or IMultiValueConverter binding for Cell's Background property.

I'm not sure how it works with autogenerated columns set but with manual it looks like this. I'm providing here not a working copy but a markup example.

XAML

<Window.Resources>
    <local:MyCellBackgroundConverter x:Key="myCellBackgroundConverter"/>
</Window.Resources>
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
<Grid>
<!-- some your markup here -->
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}">
    <DataGridTextColumn Header="Column1" Binding="{Binding Value1}">
        <DataGridTextColumn.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="Background">
                    <Setter.Value>
                        <MultiBinding Converter="{StaticResource myCellBackgroundConverter}">
                            <Binding Path="Value1"/>
                            <Binding Path="Value2"/>
                        </MultiBinding>
                    </Setter.Value>
                </Setter>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    <DataGridTextColumn Header="Column2" Binding="{Binding Value2}"/>
</DataGrid>
</Grid>

The ViewModel Class

using System.Collections.ObjectModel;
using System.ComponentModel;

// ...

public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<MyItem> _myCollection = new ObservableCollection<MyItem>();
    public ObservableCollection<MyItem> MyCollection
    {
        get => _myCollection;
        set
        {
            _myCollection = value;
            OnPropertyChanged(nameof(MyCollection));
        }
    }

    public ViewModel()
         // you may load or add the data to MyCollection here
    {

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Item

using System.ComponentModel;

// ...

public class MyItem : INotifyPropertyChanged
{
    private string _value1 = string.Empty;
    private string _value2 = string.Empty;

    public string Value1
    {
        get => _value1;
        set { _value1 = value; OnPropertyChanged(nameof(Value1)); }
    }

    public string Value2
    {
        get => _value2;
        set { _value2 = value; OnPropertyChanged(nameof(Value2)); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

And finally the Converter

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

//...

public class MyCellBackgroundConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[0] is string value1 && values[1] is string value2)
        {
            if (value1.Length > 0)
            {
                return Brushes.Green;
            }
            else
            if (value2.Length > 0)
            {
                return Brushes.Yellow;
            }
            else
                return Brushes.Red;
        }
        else return Brushes.White;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => null;
}

In alternative way you may use Style.DataTriggers directly in XAML.

For additional information about bindings and properties look for MVVM programming pattern. In short you're not need x:Name anymore because in MVVM pattern you interacting only with ViewModel class data instances and can't interact with contols directly there (and that's fine). Meanwhile Contols automatically sync with data binded to them. Calling OnPropertyChanged("PropertyName") here simply cause the GUI refresh.

In relation to markup of your XAML example, try wrapping the Control groups in StackPanel and learn about it. It will save your time spent fighting with margins. Simply set few colums and/or rows in Window's Grid and place StackPanels there assigning Grid.Column and Grid.Row to them.

ADDITION:

How in my case I should setup ItemSource for binding? Should I import databases to List first and then Bind to the list?

ObservableCollection<> is same as List<> and you may use it in the same way. The difference that first one implements CollectionChanged event that notifies DataGrid if any items was added or removed from the collection.

Your Button.Click event handler contains redundant async/await declaration.

Let's move forward and see how it can be done with MVVM.

XAML

<Button Content="Go" Command="{Binding myCommand}"/>

Command must implement ICommand interface. You have to do 2 things for proper implementation:

1) Add RelayCommand separate Class implementing ICommand interface

public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }
    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

    public void Execute(object parameter) => _execute(parameter);
}

2) Add the Command instance to your ViewModel class

public ICommand myCommand => new RelayCommand(obj =>
{
    // do the same here as in Button.Click above
});

Next, you may need some blocking UI thing that will prevent user from any actions while data is loading.

ViewModel

private bool _allowUIChanges = true;
public bool AllowUIChanges
{
    get => _allowUIChanges;
    set
    {
        _allowUIChanges = value;
        OnPropertyChanged(nameof(AllowUIChanges));
        OnPropertyChanged(nameof(IsReadOnlyDataGrid));
    }
}
public bool IsReadOnlyDataGrid
{
    get => !_allowUIChanges;
}

Finally bind your Control properties to it

XAML

<Button Content="Go" Command="{Binding myCommand}" Enabled="{Binding AllowUIChanges}"/>
<DataGrid IsReadOnly="{Binding IsReadOnlyDataGrid}" AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}">

Then set AllowUIChanges to false while data is loading.


问:
How carry out specific task with multiselect in streamlit?
I want to execute one or both operations according to the STREAMLIT multiselect option (specific task) but I can't see what I´m doing wrong. Please, any idea about how to solve it?.

My code:

```<code>import streamlit as st

calculation = st.multiselect("Select one or both operations:", ('SUM','DIV'))

if calculation =='SUM':st.write(2+2)

elif calculation =='DIV':st.write(10/2)
</code>```

答:
st.multiselect returns an array with the selected options

```<code>import streamlit as st

calculation = st.multiselect("Select one or both operations:", ('SUM','DIV'))

if 'SUM' in calculation:
    st.write(2+2)

if 'DIV' in calculation:
    st.write(10/2)

</code>```

Body:
I want to execute one or both operations according to the STREAMLIT multiselect option (specific task) but I can't see what I´m doing wrong. Please, any idea about how to solve it?.

My code:

import streamlit as st

calculation = st.multiselect("Select one or both operations:", ('SUM','DIV'))

if calculation =='SUM':st.write(2+2)

elif calculation =='DIV':st.write(10/2)

Body:
st.multiselect returns an array with the selected options

import streamlit as st

calculation = st.multiselect("Select one or both operations:", ('SUM','DIV'))

if 'SUM' in calculation:
    st.write(2+2)

if 'DIV' in calculation:
    st.write(10/2)


问:
Spring Boot - Ambiguous Mapping
Pulling my hair out over this one, makes absolutely no sense

```<code>@RestController("/firmwareAShkcwdsdskl")
public class FirmwareController {
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> createNewFirmwareVersion(DetailedFirmwareVersionRequest detailedFirmwareVersionRequest) {
    // Code Block
    }
}
</code>```

```<code>
@RestController("/jobs/firmwareUpgrade")
public class FirmwareUpgradeController {
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> createNewJob(DetailedFirmwareUpgradeRequest detailedFirmwareUpgradeRequest) {
    // Code Block
    }
}
</code>```

Attempting to start my Spring Boot application with these two controllers is throwing the following error

```<code>Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map '/jobs/firmwareUpgrade' method
eshepherd.admin.api.controller.FirmwareUpgradeController#createNewJob(DetailedFirmwareUpgradeRequest)
to {POST , produces [application/json]}: There is already '/firmwareAShkcwdsdskl' bean method
eshepherd.admin.api.controller.FirmwareController#createNewFirmwareVersion(DetailedFirmwareVersionRequest) mapped.
</code>```

The class name, method name, request mapping and parameters are all unique, I just don't understand it.

As you can tell I've descended into pure frustration trying all kinds of string changes to just get it to work initially, but if anyone could help me identify the problem I'd be extremely grateful.

Edit: Using Spring-Boot 2.2.4

答:
Okay.. I managed to get it compiling.. I think I was misunderstanding how you can use the @RestController annotation

If you provide

```<code>@RestController
@RequestMapping("/firmware")
</code>```

Instead of

```<code>@RestController("/firmware")
</code>```

It will build. I guess I had assumed the default argument on the controller would be more useful, and looked to be working as I expected from the build messages.

Hope this helps someone!

Title: Spring Boot - Ambiguous Mapping

Body:
Pulling my hair out over this one, makes absolutely no sense

@RestController("/firmwareAShkcwdsdskl")
public class FirmwareController {
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> createNewFirmwareVersion(DetailedFirmwareVersionRequest detailedFirmwareVersionRequest) {
    // Code Block
    }
}

@RestController("/jobs/firmwareUpgrade")
public class FirmwareUpgradeController {
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Result> createNewJob(DetailedFirmwareUpgradeRequest detailedFirmwareUpgradeRequest) {
    // Code Block
    }
}

Attempting to start my Spring Boot application with these two controllers is throwing the following error

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map '/jobs/firmwareUpgrade' method
eshepherd.admin.api.controller.FirmwareUpgradeController#createNewJob(DetailedFirmwareUpgradeRequest)
to {POST , produces [application/json]}: There is already '/firmwareAShkcwdsdskl' bean method
eshepherd.admin.api.controller.FirmwareController#createNewFirmwareVersion(DetailedFirmwareVersionRequest) mapped.

The class name, method name, request mapping and parameters are all unique, I just don't understand it.

As you can tell I've descended into pure frustration trying all kinds of string changes to just get it to work initially, but if anyone could help me identify the problem I'd be extremely grateful.

Edit: Using Spring-Boot 2.2.4

Body:
Okay.. I managed to get it compiling.. I think I was misunderstanding how you can use the @RestController annotation

If you provide

@RestController
@RequestMapping("/firmware")

Instead of

@RestController("/firmware")

It will build. I guess I had assumed the default argument on the controller would be more useful, and looked to be working as I expected from the build messages.

Hope this helps someone!


问:
React Native Web - Control the html tag generated by View?
I have a react native web project. At one point, I would like my View instead of generating a
 to generate a  element.

Is there a way to control this? I am hoping for some sort of htmlTag attribute that gets ignored if this is not compiling for a browser environment.

答: How about making your own wrapper of View? It could check what environment it is running in, and then if it's in a browser then you can return the label element instead.</p>


问:
Error obtaining UI hierarchy Error while obtaining UI hierarchy XML file: com.android.ddmlib.SyncException: Remote object doesn't exist
I am testing my app with adb, but i get this error when i execute "dump view hierarchy for uiautomator":

Error obtaining UI hierarchy Error while obtaining UI hierarchy XML
  file: com.android.ddmlib.SyncException: Remote object doesn't exist!

My adb version is 1.0.36 and my android version is 6.0.1.

This error comes launched only when in the interface there is a dynamic element that is in motion.

thank you in advance.

答: I have tried all the above steps and none of them did not work. The reason being I have tried to run the uiautomatorviewer after opening the app using Appium. Whenever I manually open my app on the device and then run the uiautomatorviewer works perfectly well. Just sharing my experience. Thanks</p>


问:
Python code comparison with if validates False when it should be True
I have the following Python code below. I'm expecting the code to return True but when I run it, it seems to always return False. It seems to fail when checking if 361 is 361 but I can't work out why:

```<code>def comp(array1, array2):
    if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
        return False

    aListSquared = [x * x for x in sorted(array1)]
    array2.sort()

    print(aListSquared)
    print(array2)

    for x in range(len(aListSquared)):
        print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
        print('{0}:{1}'.format(array2[x], type(array2[x])))

        if int(aListSquared[x]) is not int(array2[x]):
            return False

    return True

a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))

</code>```

Can anyone tell me what i'm doing wrong or why the validation doesn't seem to be working correctly?

Many Thanks

答:
Rewriting this expression:

if int(aListSquared[x]) is not int(array2[x]):
    return False

with this:

if int(aListSquared[x]) != int(array2[x]):
    return False

The code returns True.

Body:
I have the following Python code below. I'm expecting the code to return True but when I run it, it seems to always return False. It seems to fail when checking if 361 is 361 but I can't work out why:

def comp(array1, array2):
    if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
        return False

    aListSquared = [x * x for x in sorted(array1)]
    array2.sort()

    print(aListSquared)
    print(array2)

    for x in range(len(aListSquared)):
        print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
        print('{0}:{1}'.format(array2[x], type(array2[x])))

        if int(aListSquared[x]) is not int(array2[x]):
            return False

    return True

a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))

Can anyone tell me what i'm doing wrong or why the validation doesn't seem to be working correctly?

Many Thanks


问:
Microsoft Graph API creating recurring event returns 500
I'm writing an app that synchronizes with Office365's events using the Microsoft Graph API v1.0.

When creating a single event, the event gets created as expected:

```<code>Response Status Code: 201 Created
Request URL: https://graph.microsoft.com/v1.0/me/calendars/<myCalendarId>/events
Request Method: POST
Request Payload:
{
    "subject": "single event",
    "start": {
        "dateTime": "2020-02-15T09:00:00",
        "timeZone": "Europe/Berlin"
    },
    "end": {
        "dateTime": "2020-02-15T10:00:00",
        "timeZone": "Europe/Berlin"
    },
    "attendees": [],
    "type": "singleInstance",
    "location": {
        "displayName": null
    },
    "recurrence": null
}
</code>```

If, however, I send a create request for a recurring event, I get a error response.

```<code>Response Status Code: 500 Internal Server Error
Request URL: https://graph.microsoft.com/v1.0/me/calendars/<myCalendarId>/events
Request Method: POST
Request Payload:
{
    "subject": "test recurring event",
    "start": {
        "dateTime": "2020-02-14T09:00:00",
        "timeZone": "Europe/Berlin"
    },
    "end": {
        "dateTime": "2020-02-14T10:00:00",
        "timeZone": "Europe/Berlin"
    },
    "attendees": [],
    "location": {
        "displayName": null
    },
    "recurrence": {
        "pattern": {
            "daysOfWeek": [],
            "type": "daily"
        },
        "range": {
            "numberOfOccurrences": "2",
            "recurrenceTimeZone": "Europe/Berlin",
            "startDate": "2020-02-14",
            "type": "numbered"
        }
    }
}
Response Body:
{
  "error": {
    "code": "ErrorInternalServerError",
    "message": "An internal server error occurred. The operation failed.",
    "innerError": {
      "request-id": "2d97931c-e08c-45a8-8167-5849df53a694",
      "date": "2020-02-14T14:38:28"
    }
  }
}
</code>```

I find it strange that the addition of the recurrence settings causes an Internal Server Error.
What can I do to create a recurring event with the API?

答:
If you want to create a recurring event that occurs daily, instead of setting pattern in the following way:

```<code>    "pattern": {
        "daysOfWeek": [],
        "type": "daily"
    },
</code>```

Please set pattern this way:

```<code>"pattern": {
  "type": "daily",
  "interval": 1
},
</code>```

Creating a daily recurrence pattern is described here in the conceptual docs. Within the next day, there will also be a REST example in the reference docs.

Body:
I'm writing an app that synchronizes with Office365's events using the Microsoft Graph API v1.0.

When creating a single event, the event gets created as expected:

Response Status Code: 201 Created
Request URL: https://graph.microsoft.com/v1.0/me/calendars/<myCalendarId>/events
Request Method: POST
Request Payload:
{
    "subject": "single event",
    "start": {
        "dateTime": "2020-02-15T09:00:00",
        "timeZone": "Europe/Berlin"
    },
    "end": {
        "dateTime": "2020-02-15T10:00:00",
        "timeZone": "Europe/Berlin"
    },
    "attendees": [],
    "type": "singleInstance",
    "location": {
        "displayName": null
    },
    "recurrence": null
}

If, however, I send a create request for a recurring event, I get a error response.

Response Status Code: 500 Internal Server Error
Request URL: https://graph.microsoft.com/v1.0/me/calendars/<myCalendarId>/events
Request Method: POST
Request Payload:
{
    "subject": "test recurring event",
    "start": {
        "dateTime": "2020-02-14T09:00:00",
        "timeZone": "Europe/Berlin"
    },
    "end": {
        "dateTime": "2020-02-14T10:00:00",
        "timeZone": "Europe/Berlin"
    },
    "attendees": [],
    "location": {
        "displayName": null
    },
    "recurrence": {
        "pattern": {
            "daysOfWeek": [],
            "type": "daily"
        },
        "range": {
            "numberOfOccurrences": "2",
            "recurrenceTimeZone": "Europe/Berlin",
            "startDate": "2020-02-14",
            "type": "numbered"
        }
    }
}
Response Body:
{
  "error": {
    "code": "ErrorInternalServerError",
    "message": "An internal server error occurred. The operation failed.",
    "innerError": {
      "request-id": "2d97931c-e08c-45a8-8167-5849df53a694",
      "date": "2020-02-14T14:38:28"
    }
  }
}

I find it strange that the addition of the recurrence settings causes an Internal Server Error.
What can I do to create a recurring event with the API?

Body:
If you want to create a recurring event that occurs daily, instead of setting pattern in the following way:

    "pattern": {
        "daysOfWeek": [],
        "type": "daily"
    },

Please set pattern this way:

"pattern": {
  "type": "daily",
  "interval": 1
},

Creating a daily recurrence pattern is described here in the conceptual docs. Within the next day, there will also be a REST example in the reference docs.