问:
npm start error with create-react-app
I have a project who I didn't touch for 2 weeks. I take it back and now when I try to run npm start I got this error.

```<code>> react-scripts start

sh: react-scripts: command not found

npm ERR! Darwin 16.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! UpScore@0.6.0 start: `react-scripts start`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the UpScore@0.6.0 start script 'react-scripts start'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the UpScore package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     react-scripts start
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs UpScore
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls UpScore
npm ERR! There is likely additional logging output above.
</code>```

node 6.7.0

npm 3.10.3

mac sierra 10.12

package.json

```<code>{
  "name": "UpScore",
  "version": "0.6.0",
  "private": true,
  "devDependencies": {
    "react-addons-test-utils": "^15.3.1",
    "react-scripts": "0.4.1",
    "react-test-renderer": "^15.3.1",
    "redux-logger": "^2.6.1"
  },
  "dependencies": {
    "@yoshokatana/medium-button": "^1.1.0",
    "axios": "^0.14.0",
    "bcrypt": "^0.8.7",
    "bcrypt-nodejs": "0.0.3",
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "draft-js": "^0.8.1",
    "draft-js-editor": "^1.7.2",
    "draft-js-export-html": "^0.4.0",
    "ejs": "^2.5.2",
    "email-verification": "^0.4.5",
    "express": "^4.14.0",
    "express-session": "^1.14.1",
    "flexboxgrid": "^6.3.1",
    "highlight.js": "^9.6.0",
    "immutable": "^3.8.1",
    "katex": "^0.6.0",
    "lodash": "^4.15.0",
    "markdown-it-mathjax": "^1.0.3",
    "material-ui": "^0.15.4",
    "medium-editor": "^5.22.0",
    "minutes-seconds-milliseconds": "^1.0.3",
    "moment": "^2.15.0",
    "moment-duration-format": "^1.3.0",
    "mongod": "^1.3.0",
    "mongodb": "^2.2.9",
    "mongoose": "^4.6.0",
    "monk": "^3.1.2",
    "morgan": "^1.7.0",
    "normalize.css": "^3.0.3",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "react-markdown": "^2.4.2",
    "react-medium-editor": "^1.8.1",
    "react-redux": "^4.4.5",
    "react-redux-form": "^0.14.5",
    "react-rich-markdown": "^1.0.1",
    "react-router": "^2.7.0",
    "react-router-redux": "^4.0.5",
    "react-tap-event-plugin": "^1.0.0",
    "react-tinymce": "^0.5.1",
    "redux": "^3.6.0",
    "redux-form": "^6.0.5",
    "redux-form-material-ui": "^4.0.1",
    "redux-promise-middleware": "^4.0.0",
    "redux-thunk": "^2.1.0",
    "reselect": "^2.5.3",
    "screenfull": "^3.0.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "start:prod": "pushstate-server build",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "cd client/api && pm2 start server.js --watch",
    "proxy": "http://128.199.139.144:3000"
  },
  "eslintConfig": {
    "extends": "./node_modules/react-scripts/config/eslint.js"
  }
}
</code>```

I try to clone my repos too and get the same error. If someone can give me some way to find what happen. Thank you

答:
It occurred to me but none of the above worked.

```<code>events.js:72
        throw er; // Unhandled 'error' event
              ^

npm ERR! UpScore@0.6.0 start: `react-scripts start`
npm ERR! spawn ENOENT

Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)
</code>```

This happens because you might have installed react-scripts globally.

To make this work...

Go to your C:\Users\<USER>\AppData\Roaming

Delete npm and npm-cache directories... (don't worry you can install npm globally later)

Go back to your application directory and remove node_modules folder

Now enter npm install to install the dependencies (delete package-lock.json if its already created)

Now run npm install --save react react-dom react-scripts

Get it started with npm start

This should get you back on track... Happy Coding

Title: npm start error with create-react-app

Body:
I have a project who I didn't touch for 2 weeks. I take it back and now when I try to run npm start I got this error.

> react-scripts start

sh: react-scripts: command not found

npm ERR! Darwin 16.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! UpScore@0.6.0 start: `react-scripts start`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the UpScore@0.6.0 start script 'react-scripts start'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the UpScore package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     react-scripts start
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs UpScore
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls UpScore
npm ERR! There is likely additional logging output above.

node 6.7.0

npm 3.10.3

mac sierra 10.12

package.json

{
  "name": "UpScore",
  "version": "0.6.0",
  "private": true,
  "devDependencies": {
    "react-addons-test-utils": "^15.3.1",
    "react-scripts": "0.4.1",
    "react-test-renderer": "^15.3.1",
    "redux-logger": "^2.6.1"
  },
  "dependencies": {
    "@yoshokatana/medium-button": "^1.1.0",
    "axios": "^0.14.0",
    "bcrypt": "^0.8.7",
    "bcrypt-nodejs": "0.0.3",
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "draft-js": "^0.8.1",
    "draft-js-editor": "^1.7.2",
    "draft-js-export-html": "^0.4.0",
    "ejs": "^2.5.2",
    "email-verification": "^0.4.5",
    "express": "^4.14.0",
    "express-session": "^1.14.1",
    "flexboxgrid": "^6.3.1",
    "highlight.js": "^9.6.0",
    "immutable": "^3.8.1",
    "katex": "^0.6.0",
    "lodash": "^4.15.0",
    "markdown-it-mathjax": "^1.0.3",
    "material-ui": "^0.15.4",
    "medium-editor": "^5.22.0",
    "minutes-seconds-milliseconds": "^1.0.3",
    "moment": "^2.15.0",
    "moment-duration-format": "^1.3.0",
    "mongod": "^1.3.0",
    "mongodb": "^2.2.9",
    "mongoose": "^4.6.0",
    "monk": "^3.1.2",
    "morgan": "^1.7.0",
    "normalize.css": "^3.0.3",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "react": "^15.3.1",
    "react-dom": "^15.3.1",
    "react-markdown": "^2.4.2",
    "react-medium-editor": "^1.8.1",
    "react-redux": "^4.4.5",
    "react-redux-form": "^0.14.5",
    "react-rich-markdown": "^1.0.1",
    "react-router": "^2.7.0",
    "react-router-redux": "^4.0.5",
    "react-tap-event-plugin": "^1.0.0",
    "react-tinymce": "^0.5.1",
    "redux": "^3.6.0",
    "redux-form": "^6.0.5",
    "redux-form-material-ui": "^4.0.1",
    "redux-promise-middleware": "^4.0.0",
    "redux-thunk": "^2.1.0",
    "reselect": "^2.5.3",
    "screenfull": "^3.0.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "start:prod": "pushstate-server build",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "server": "cd client/api && pm2 start server.js --watch",
    "proxy": "http://128.199.139.144:3000"
  },
  "eslintConfig": {
    "extends": "./node_modules/react-scripts/config/eslint.js"
  }
}

I try to clone my repos too and get the same error. If someone can give me some way to find what happen. Thank you

Body:
It occurred to me but none of the above worked.

events.js:72
        throw er; // Unhandled 'error' event
              ^

npm ERR! UpScore@0.6.0 start: `react-scripts start`
npm ERR! spawn ENOENT

Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

This happens because you might have installed react-scripts globally.

To make this work...

Go to your C:\Users\<USER>\AppData\Roaming

Delete npm and npm-cache directories... (don't worry you can install npm globally later)

Go back to your application directory and remove node_modules folder

Now enter npm install to install the dependencies (delete package-lock.json if its already created)

Now run npm install --save react react-dom react-scripts

Get it started with npm start

This should get you back on track... Happy Coding


来源: stackexchange

问:
Zoom out of website when using RSelenium without changing page size/resolution
I'd like to zoom out of RSelenium remote, but this is surprisingly difficult to find a solution.
I am aware of

How to zoom out page using RSelenium library in R?, but I woud like to not adjust the page size or the resolution---simply zoom out.

I have pondered sending control + substract simultaneously, but this is also not quite working. I have taken a look at How to press two keys simultaneously (i.e., control-s) in a webpage using RSelenium?, which as the OP noted, control + a worked but not control + s, and subsequently control + substract didn't work either.

I also tried the Unicode method specified in How to send simultaneous keys in RSelenium ALT+S to web driver?, which did not work either.

```<code>library(RSelenium)
driver <- rsDriver()
remDr <- driver[["client"]]
remDr$navigate("https://www.google.com/")
webElem <- remDr$findElement("css", "html")
webElem$sendKeysToElement(list(key = "control", "-"))              ## Does not work
webElem$sendKeysToElement(list(key = "control", key = "subtract")) ## Does not work
</code>```

The browser is Chrome.

答:
You can try Zoom out with Java script. Please try below code for zoom out at 90%.

```<code>library(RSelenium)
driver <- rsDriver()
remDr <- driver[["client"]]
remDr$navigate("https://www.google.com/")
webElem <- remDr$findElement("css", "html")
script <- "document.body.style.zoom='90%'"
remDr$executeScript(script, args = list())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to zoom out of RSelenium remote, but this is surprisingly difficult to find a solution.
I am aware of

How to zoom out page using RSelenium library in R?, but I woud like to not adjust the page size or the resolution---simply zoom out.

I have pondered sending control + substract simultaneously, but this is also not quite working. I have taken a look at How to press two keys simultaneously (i.e., control-s) in a webpage using RSelenium?, which as the OP noted, control + a worked but not control + s, and subsequently control + substract didn't work either.

I also tried the Unicode method specified in How to send simultaneous keys in RSelenium ALT+S to web driver?, which did not work either.

library(RSelenium)
driver <- rsDriver()
remDr <- driver[["client"]]
remDr$navigate("https://www.google.com/")
webElem <- remDr$findElement("css", "html")
webElem$sendKeysToElement(list(key = "control", "-"))              ## Does not work
webElem$sendKeysToElement(list(key = "control", key = "subtract")) ## Does not work

The browser is Chrome.

Body:
You can try Zoom out with Java script. Please try below code for zoom out at 90%.

library(RSelenium)
driver <- rsDriver()
remDr <- driver[["client"]]
remDr$navigate("https://www.google.com/")
webElem <- remDr$findElement("css", "html")
script <- "document.body.style.zoom='90%'"
remDr$executeScript(script, args = list())


问:
Get smallest available key (>= 1) in a HashMap
I am using a Map in which I save all tracks that the user registers. Every new track should be assigned a new ID which starts at 1. However, if tracks 1, 2, 3, 4 exist and the user deletes track with ID 1 the next added track gets the smallest available ID >=1 which in this case would be 1.

How is it possible to do this efficiently? Or is there a better datatype available?

```<code>private Map<Integer, Track> tracks;

public Register() {
    this.trains = new HashMap<>();
}

public void addTrack(Track track) {
    int id = <get Smallest Value Available >= 1>;
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + id + " doesn't exist.");
    }
}
</code>```

答:
Approach 1: You can use TreeMap and iterate through its keys, and if there is a gap between two keys, you can insert your element in this gap. Addition will work in O(currentKeysCount) worst-case, deletion will work in O(log(currentKeysCount)).

private TreeMap<Integer, Track> tracks;

public Register() {
    this.trains = new TreeMap<>();
}

public void addTrack(Track track) {
    int id = 1;
    for (int key : this.trains.keySet) {
        if (key > id) break;
        id = key + 1;
    }
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}
```

<p><strong>Approach 2:</strong> You can create a <code>PriorityQueue</code> that will store deleted keys. Addition and deletion will work in <code>O(log(currentKeysCount) + log(deletedKeysCount))</code>.</p>

<pre class="lang-java prettyprint-override"><code>private Map<Integer, Track> tracks;
private PriorityQueue<Integer> deletedKeys;
private int nextKey;

public Register() {
    this.trains = new HashMap<>();
    this.deletedKeys = new PriorityQueue<>();
    this.nextKey = 0;
}

public void addTrack(Track track) {
    int id = nextKey;
    if (!deletedKeys.isEmpty()) id = deletedKeys.poll();
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
        this.deletedKeys.add(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}
</code>```

Approach 3: It may be much easier to ignore missing keys and just increase nextKey counter on every addition (you can even use long instead of int). Unless you add a new key more often than once per millisecond, your program won't fail earlier than all code that uses System.currentTimeMillis() (and it will fail in more than 292 million years). Addition and deletion will work in O(log(currentKeysCount))

Body:
I am using a Map in which I save all tracks that the user registers. Every new track should be assigned a new ID which starts at 1. However, if tracks 1, 2, 3, 4 exist and the user deletes track with ID 1 the next added track gets the smallest available ID >=1 which in this case would be 1.

How is it possible to do this efficiently? Or is there a better datatype available?

private Map<Integer, Track> tracks;

public Register() {
    this.trains = new HashMap<>();
}

public void addTrack(Track track) {
    int id = <get Smallest Value Available >= 1>;
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + id + " doesn't exist.");
    }
}

Body:
Approach 1: You can use TreeMap and iterate through its keys, and if there is a gap between two keys, you can insert your element in this gap. Addition will work in O(currentKeysCount) worst-case, deletion will work in O(log(currentKeysCount)).

private TreeMap<Integer, Track> tracks;

public Register() {
    this.trains = new TreeMap<>();
}

public void addTrack(Track track) {
    int id = 1;
    for (int key : this.trains.keySet) {
        if (key > id) break;
        id = key + 1;
    }
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}

Approach 2: You can create a PriorityQueue that will store deleted keys. Addition and deletion will work in O(log(currentKeysCount) + log(deletedKeysCount)).

private Map<Integer, Track> tracks;
private PriorityQueue<Integer> deletedKeys;
private int nextKey;

public Register() {
    this.trains = new HashMap<>();
    this.deletedKeys = new PriorityQueue<>();
    this.nextKey = 0;
}

public void addTrack(Track track) {
    int id = nextKey;
    if (!deletedKeys.isEmpty()) id = deletedKeys.poll();
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
        this.deletedKeys.add(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}

Approach 3: It may be much easier to ignore missing keys and just increase nextKey counter on every addition (you can even use long instead of int). Unless you add a new key more often than once per millisecond, your program won't fail earlier than all code that uses System.currentTimeMillis() (and it will fail in more than 292 million years). Addition and deletion will work in O(log(currentKeysCount))


问:
Linq (or SQL): Get a search query and sort it order by best result
I want to create a search page for my website. The logic is the user enters some keywords and I should search those words then sort the result by best matches.
i.e:
The user enters: "MVC Microsoft WPF ASP.Net".
I want to show those results which contain most matches, such as:

Best Matches:

Learning Microsoft ASP.Net MVC

How to host a WPF form in Microsoft ASP.Net

Partial matches:

Microsoft MVC

Microsoft WPF

Microsoft ASP.Net

ASP.Net MVC

Keyword Matches:

MVC

Microsoft

WPF

ASP.Net

答: Depending on what / how you are searching, a simple solution is to build your website so it is fully indexed on Google and take advantage of Google Custom Search API.</p>

ContentLicense: CC BY-SA 3.0


问:
Plugin Un-install missing
Moodle plugins come up with install & uninstall option when $plugin variable is specified in version.php.

I couldn't see uninstall option for my customized authentication plugin:

```<code>$plugin->version   = 2015051100;
$plugin->requires  = 2015050500;
$plugin->component = 'auth_hotspot';
</code>```

Once installation is done, When I run the plugin, Un-install option is missing. I even don't have an option to delete as it shows "missing from disk". (Moodle version: 2.9).

Appreciate your suggestions.

答:
Moodle does not allow to uninstall the auth plugin if any user-created using that plugin.

You need to delete the user from Database or convert the user's authentication method to manual or others.

https://moodle.org/mod/forum/discuss.php?d=272751

Title: Plugin Un-install missing

Body:
Moodle plugins come up with install & uninstall option when $plugin variable is specified in version.php.

I couldn't see uninstall option for my customized authentication plugin:

$plugin->version   = 2015051100;
$plugin->requires  = 2015050500;
$plugin->component = 'auth_hotspot';

Once installation is done, When I run the plugin, Un-install option is missing. I even don't have an option to delete as it shows "missing from disk". (Moodle version: 2.9).

Appreciate your suggestions.


问:
Performance of indexes that use nvarchar(MAX) vs ones based on nvarchar with fixed characters?
I have a string of certain amount of characters that I want to be an index of my SQL Server table.

Would it be possible to define it as nvarchar(MAX) or it is better to specify how many characters it could possibly have (such as nvarchar(10)), to speed up both writing and retrieving data using the index?

答:
Well, you can define an index on a nvarchar column that exceed the maximum length, but not on nvarchar(max).

If you try on a column too large, you will get a warning like this:

Warning! The maximum key length for a nonclustered index is 1700 bytes. The index 'idx_t_x' has maximum length of 8000 bytes. For some combination of large values, the insert/update operation will fail.

So, inserts and upadtes will break if you have more than 900 or 1700 bytes in the record, depending on the version of SQL Server:

SQL Server 2016 and Azure SQL Database have increased the maximum size for index keys with nonclustered indexes. The new maximum key size for nonclustered indexes is 1700 bytes. The maximum key size for clustered indexes remains 900 bytes.

So, the effective answer is "no".  If you are storing text in the column, you might want a full text index.  If you want to prevent duplicates, you might consider various forms of hashing.


问:
Group objects by one of its params with javascript
Basically I would want to transform this

```<code>[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]
</code>```

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

```<code>[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];
</code>```

Would really not mind using lodash for this but couldn't find the correct array method.

答:
 function groupData(){
       var mainArray = [
        { key: 0, name: 'Some name' },
        { key: 0, name: 'Some name' },
        { key: 1, name: 'Some name' },
        { key: 1, name: 'Some name' },
      ];

      var unique = [...new Set(mainArray.map(item => item.key))];
       var tempArrays = new Array(parseInt(unique.length));
       for(var k = 0; k < unique.length; k++){
        if(! tempArrays[k] ){
         tempArrays[k] = [];
        }

          for(var i = 0; i < mainArray.length; i++){
      if (mainArray[i].key == unique[k]){
              tempArrays[k].push(mainArray[i]);
             }
          }
        }
        console.log(tempArrays);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onClick="groupData();" value="Group Data"></code>```

Body:
Basically I would want to transform this

[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];

Would really not mind using lodash for this but couldn't find the correct array method.

Body:
 function groupData(){
       var mainArray = [
        { key: 0, name: 'Some name' },
        { key: 0, name: 'Some name' },
        { key: 1, name: 'Some name' },
        { key: 1, name: 'Some name' },
      ];

      var unique = [...new Set(mainArray.map(item => item.key))];
       var tempArrays = new Array(parseInt(unique.length));
       for(var k = 0; k < unique.length; k++){
        if(! tempArrays[k] ){
         tempArrays[k] = [];
        }

          for(var i = 0; i < mainArray.length; i++){
      if (mainArray[i].key == unique[k]){
              tempArrays[k].push(mainArray[i]);
             }
          }
        }
        console.log(tempArrays);
    }

<input type="button" onClick="groupData();" value="Group Data">


问:
How to pass data with history hook to react functional components
I am trying to implement a redirection after a fetch query is executed.
I want to be able to pass data to the next component (page) with React History.

It would go like this:

```<code> const history = useHistory({});
 /* ... */
 history.push({
       pathname: '/page',
       state: { data: data }
 })
</code>```

And then to retrieve the state in the receiver, assuming receiver is a class based component:

```<code>this.state.data
</code>```

Is it even possible to achieve something like this with functional components? What is the cleanest solution to this problem?

Thank you for your help

答:
the data you pass to the history.push isn't intrinsically bound to class component like that so with a class or a functional component, you'd have to access the location state from somewhere and then assign it to your component's state

if the functional component is being rendered from a route, it should receive history as a prop and then you can get that data via simply doing something like history.location.state. you can then do whatever you want with it and assign it to state via useState

i imagine you can just use that hook useHistory to get the location state as well.

something like

```<code>function MyComponent() {
  const history = useHistory()

  return <div>
    {JSON.stringify(history.location.state)}
  </div>
}

// Rendered via <Route component={MyOtherComponent} />

function MyOtherComponent({ history }) {
  return <div>
    {JSON.stringify(history.location.state)}
  </div>
}
</code>```

Body:
I am trying to implement a redirection after a fetch query is executed.
I want to be able to pass data to the next component (page) with React History.

It would go like this:

 const history = useHistory({});
 /* ... */
 history.push({
       pathname: '/page',
       state: { data: data }
 })

And then to retrieve the state in the receiver, assuming receiver is a class based component:

this.state.data

Is it even possible to achieve something like this with functional components? What is the cleanest solution to this problem?

Thank you for your help

Body:
the data you pass to the history.push isn't intrinsically bound to class component like that so with a class or a functional component, you'd have to access the location state from somewhere and then assign it to your component's state

if the functional component is being rendered from a route, it should receive history as a prop and then you can get that data via simply doing something like history.location.state. you can then do whatever you want with it and assign it to state via useState

i imagine you can just use that hook useHistory to get the location state as well.

something like

function MyComponent() {
  const history = useHistory()

  return <div>
    {JSON.stringify(history.location.state)}
  </div>
}

// Rendered via <Route component={MyOtherComponent} />

function MyOtherComponent({ history }) {
  return <div>
    {JSON.stringify(history.location.state)}
  </div>
}


问:
Invoke JavaScript function with argument via pointer?
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

```<code>function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);
</code>```

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

答:
```<code>var process_json = function(resp) {
  // Do something with resp
}
</code>```

Body:
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?


问:
Build docker image, through docker-compose, using locally running verdaccio
I'm running verdaccio locally (through docker) to publish private npm packages. I'm building one of my packages with Dockerfile which has:

```<code>RUN npm ci
</code>```

in it. I'm actually building with docker-compose. I have a .env file to set these args:

```<code>        - NPM_CONFIG_REGISTRY
        - NPM_CONFIG_USERNAME
        - NPM_CONFIG_EMAIL
        - NPM_CONFIG_PASSWORD
</code>```

It is successfully trying to get packages from my local registry but it can't connect.

So my question is - how can I run docker-compose build myservice and have myservice use the locally running instance of verdaccio to pull packages from during the docker build?

EDIT: I'm running on a mac host.

答:
It seems to be working by adding a network: host entry under the service's build:

```<code>    build:
      context: ./packages/server
      target: dev
      network: host
</code>```

NOTE: giving some time to test this before accepting it as an answer (just in case as I've tried a number of other things to get this to work).

Body:
I'm running verdaccio locally (through docker) to publish private npm packages. I'm building one of my packages with Dockerfile which has:

RUN npm ci

in it. I'm actually building with docker-compose. I have a .env file to set these args:

        - NPM_CONFIG_REGISTRY
        - NPM_CONFIG_USERNAME
        - NPM_CONFIG_EMAIL
        - NPM_CONFIG_PASSWORD

It is successfully trying to get packages from my local registry but it can't connect.

So my question is - how can I run docker-compose build myservice and have myservice use the locally running instance of verdaccio to pull packages from during the docker build?

EDIT: I'm running on a mac host.

Body:
It seems to be working by adding a network: host entry under the service's build:

    build:
      context: ./packages/server
      target: dev
      network: host

NOTE: giving some time to test this before accepting it as an answer (just in case as I've tried a number of other things to get this to work).


问:
Javascript changing function trouble
The code below is how it was originally

```<code>   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }
</code>```

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

```<code>function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`
</code>```

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???

答:
1 emailname is already an array after the split in the initialization. Now what you need is it's length

2 to insert the variable use ${..}, not $()

```<code>function getRandomEmail() {
  var emailname = "testing testing2 testing3".split(" ");
  return `User${Math.floor(Math.random() * emailname.length)}@example.com`
}
</code>```

Title: Javascript changing function trouble

Body:
The code below is how it was originally

   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???

Body:
1 emailname is already an array after the split in the initialization. Now what you need is it's length

2 to insert the variable use ${..}, not $()

function getRandomEmail() {
  var emailname = "testing testing2 testing3".split(" ");
  return `User${Math.floor(Math.random() * emailname.length)}@example.com`
}


问:
Please use 'MongoMappingContext#setAutoIndexCreation(boolean)' or override 'MongoConfigurationSupport#autoIndexCreation()' to be explicit
I went through https://docs.spring.io/spring-data/mongodb/docs/2.2.0.RC1/reference/html/#mapping-usage and other sources on the web, but the solution did not work for me.

I am using Spring Boot 2.2.2.RELEASE and Spring Data Mongo. In this example, at Model/Pojo field level we're using

```<code>@Indexed(name = AppConstants.FIRSTNAME_INDEX, direction = IndexDirection.ASCENDING)
private String firstName;
</code>```

Error:

```<code>Please use 'MongoMappingContext#setAutoIndexCreation(boolean)' or override 'MongoConfigurationSupport#autoIndexCreation()' to be explicit.
However, we recommend setting up indices manually in an application ready block. You may use index derivation there as well.

> -----------------------------------------------------------------------------------------
> @EventListener(ApplicationReadyEvent.class)
> public void initIndicesAfterStartup() {
>
>     IndexOperations indexOps = mongoTemplate.indexOps(DomainType.class);
>
>     IndexResolver resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);
>     resolver.resolveIndexFor(DomainType.class).forEach(indexOps::ensureIndex);
> }
> -----------------------------------------------------------------------------------------
</code>```

As suggested in the log, I implemented, but I don't see method setAutoIndexCreation.

```<code>public class MongoConfig extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String getDatabaseName() {
        // TODO Auto-generated method stub
        return null;
    }
}
</code>```

答: But the solution doesn't work well, at least within the reactive context. The mongoMappingContext.getPersistentEntities() is empty at this time. Only auto-index-creation: true (or even mongoMappingContext.setAutoIndexCreation(true)) ensure the creation of indexes.

Body:
I went through https://docs.spring.io/spring-data/mongodb/docs/2.2.0.RC1/reference/html/#mapping-usage and other sources on the web, but the solution did not work for me.

I am using Spring Boot 2.2.2.RELEASE and Spring Data Mongo. In this example, at Model/Pojo field level we're using

@Indexed(name = AppConstants.FIRSTNAME_INDEX, direction = IndexDirection.ASCENDING)
private String firstName;

Error:

Please use 'MongoMappingContext#setAutoIndexCreation(boolean)' or override 'MongoConfigurationSupport#autoIndexCreation()' to be explicit.
However, we recommend setting up indices manually in an application ready block. You may use index derivation there as well.

> -----------------------------------------------------------------------------------------
> @EventListener(ApplicationReadyEvent.class)
> public void initIndicesAfterStartup() {
>
>     IndexOperations indexOps = mongoTemplate.indexOps(DomainType.class);
>
>     IndexResolver resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);
>     resolver.resolveIndexFor(DomainType.class).forEach(indexOps::ensureIndex);
> }
> -----------------------------------------------------------------------------------------

As suggested in the log, I implemented, but I don't see method setAutoIndexCreation.

public class MongoConfig extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected String getDatabaseName() {
        // TODO Auto-generated method stub
        return null;
    }
}


问:
send mail python asyncio
I'm trying to learn asyncio. If I run this program normally without the asyncio library than it takes less time while it takes more time in this way so is this the right way to send mail using asyncio or there is any other way?</p>
```<code>import smtplib
import ssl
import time
import asyncio

async def send_mail(receiver_email):
    try:
        print(f"trying..{receiver_email}")
        server = smtplib.SMTP(smtp_server, port)
        server.ehlo()
        server.starttls(context=context)
        server.ehlo()
        server.login(sender_email, password)
        message = "test"
        await asyncio.sleep(0)
        server.sendmail(sender_email, receiver_email, message)
        print(f"done...{receiver_email}")
    except Exception as e:
        print(e)
    finally:
        server.quit()

async def main():
     t1 = time.time()
     await asyncio.gather(
         send_mail("test@test.com"),
         send_mail("test@test.com"),
         send_mail("test@test.com"),
         send_mail("test@test.com")
     )
    print(f"End in {time.time() - t1}sec")

if __name__ == "__main__":
     smtp_server = "smtp.gmail.com"
     port = 587  # For starttls
     sender_email = "*****"
     password = "*****"
     context = ssl.create_default_context()
     asyncio.run(main())
</code>```

答:
You are not really doing sending your emails correctly using asyncio. You should be using the aiosmtplib for making asynchronous SMTP calls such as connect,  starttls, login, etc. See the following example, which I have stripped down from a more complicated program that handled attachments. This code sends two emails asynchronously:

```<code>#!/usr/bin/env python3

import asyncio
import aiosmtplib
import sys

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MAIL_PARAMS = {'TLS': True, 'host': 'xxxxxxxx', 'password': 'xxxxxxxx', 'user': 'xxxxxxxx', 'port': 587}

async def send_mail_async(sender, to, subject, text, textType='plain', **params):
    """Send an outgoing email with the given parameters.

    :param sender: From whom the email is being sent
    :type sender: str

    :param to: A list of recipient email addresses.
    :type to: list

    :param subject: The subject of the email.
    :type subject: str

    :param text: The text of the email.
    :type text: str

    :param textType: Mime subtype of text, defaults to 'plain' (can be 'html').
    :type text: str

    :param params: An optional set of parameters. (See below)
    :type params; dict

    Optional Parameters:
    :cc: A list of Cc email addresses.
    :bcc: A list of Bcc email addresses.
    """

    # Default Parameters
    cc = params.get("cc", [])
    bcc = params.get("bcc", [])
    mail_params = params.get("mail_params", MAIL_PARAMS)

    # Prepare Message
    msg = MIMEMultipart()
    msg.preamble = subject
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = ', '.join(to)
    if len(cc): msg['Cc'] = ', '.join(cc)
    if len(bcc): msg['Bcc'] = ', '.join(bcc)

    msg.attach(MIMEText(text, textType, 'utf-8'))

    # Contact SMTP server and send Message
    host = mail_params.get('host', 'localhost')
    isSSL = mail_params.get('SSL', False);
    isTLS = mail_params.get('TLS', False);
    port = mail_params.get('port', 465 if isSSL else 25)
    smtp = aiosmtplib.SMTP(hostname=host, port=port, use_tls=isSSL)
    await smtp.connect()
    if isTLS:
        await smtp.starttls()
    if 'user' in mail_params:
        await smtp.login(mail_params['user'], mail_params['password'])
    await smtp.send_message(msg)
    await smtp.quit()

if __name__ == "__main__":
    email = "xxxxxxxx";
    co1 = send_mail_async(email,
              [email],
              "Test 1",
              'Test 1 Message',
              textType="plain")
    co2 = send_mail_async(email,
              [email],
              "Test 2",
              'Test 2 Message',
              textType="plain")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(co1, co2))
    loop.close()
</code>```

Title: send mail python asyncio

Body:
I'm trying to learn asyncio. If I run this program normally without the asyncio library than it takes less time while it takes more time in this way so is this the right way to send mail using asyncio or there is any other way?

import smtplib
import ssl
import time
import asyncio

async def send_mail(receiver_email):
    try:
        print(f"trying..{receiver_email}")
        server = smtplib.SMTP(smtp_server, port)
        server.ehlo()
        server.starttls(context=context)
        server.ehlo()
        server.login(sender_email, password)
        message = "test"
        await asyncio.sleep(0)
        server.sendmail(sender_email, receiver_email, message)
        print(f"done...{receiver_email}")
    except Exception as e:
        print(e)
    finally:
        server.quit()

async def main():
     t1 = time.time()
     await asyncio.gather(
         send_mail("test@test.com"),
         send_mail("test@test.com"),
         send_mail("test@test.com"),
         send_mail("test@test.com")
     )
    print(f"End in {time.time() - t1}sec")

if __name__ == "__main__":
     smtp_server = "smtp.gmail.com"
     port = 587  # For starttls
     sender_email = "*****"
     password = "*****"
     context = ssl.create_default_context()
     asyncio.run(main())

Body:
You are not really doing sending your emails correctly using asyncio. You should be using the aiosmtplib for making asynchronous SMTP calls such as connect,  starttls, login, etc. See the following example, which I have stripped down from a more complicated program that handled attachments. This code sends two emails asynchronously:

#!/usr/bin/env python3

import asyncio
import aiosmtplib
import sys

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MAIL_PARAMS = {'TLS': True, 'host': 'xxxxxxxx', 'password': 'xxxxxxxx', 'user': 'xxxxxxxx', 'port': 587}

async def send_mail_async(sender, to, subject, text, textType='plain', **params):
    """Send an outgoing email with the given parameters.

    :param sender: From whom the email is being sent
    :type sender: str

    :param to: A list of recipient email addresses.
    :type to: list

    :param subject: The subject of the email.
    :type subject: str

    :param text: The text of the email.
    :type text: str

    :param textType: Mime subtype of text, defaults to 'plain' (can be 'html').
    :type text: str

    :param params: An optional set of parameters. (See below)
    :type params; dict

    Optional Parameters:
    :cc: A list of Cc email addresses.
    :bcc: A list of Bcc email addresses.
    """

    # Default Parameters
    cc = params.get("cc", [])
    bcc = params.get("bcc", [])
    mail_params = params.get("mail_params", MAIL_PARAMS)

    # Prepare Message
    msg = MIMEMultipart()
    msg.preamble = subject
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = ', '.join(to)
    if len(cc): msg['Cc'] = ', '.join(cc)
    if len(bcc): msg['Bcc'] = ', '.join(bcc)

    msg.attach(MIMEText(text, textType, 'utf-8'))

    # Contact SMTP server and send Message
    host = mail_params.get('host', 'localhost')
    isSSL = mail_params.get('SSL', False);
    isTLS = mail_params.get('TLS', False);
    port = mail_params.get('port', 465 if isSSL else 25)
    smtp = aiosmtplib.SMTP(hostname=host, port=port, use_tls=isSSL)
    await smtp.connect()
    if isTLS:
        await smtp.starttls()
    if 'user' in mail_params:
        await smtp.login(mail_params['user'], mail_params['password'])
    await smtp.send_message(msg)
    await smtp.quit()

if __name__ == "__main__":
    email = "xxxxxxxx";
    co1 = send_mail_async(email,
              [email],
              "Test 1",
              'Test 1 Message',
              textType="plain")
    co2 = send_mail_async(email,
              [email],
              "Test 2",
              'Test 2 Message',
              textType="plain")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(co1, co2))
    loop.close()


问:
Angular - How to disable mouse click events outside a specific DIV based on a condition?
I'm using a RAD tool that generates angular code, and I want to make some modifications to a specific behaviour.

I have a grid and I can enter "edit" mode for a specific row with a button click, now once in edit mode, I want to disable completely mouse clicks outside the div containing that grid, because if the users clicks on some components outside the grid, before saving his edit, it will cause some bugs.

So I when the "Edit" button is clicked, I want to stop mouse events outside a specific div, and as soon as the "Save" button is clicked, I want to allow again mouse events everywhere.

I have no code to show, as it would be just some html code with some buttons tags.

The solution I'm looking for is just to know what is the correct way to do this, then I Can implement it by myself

答:
You can do the following thing. Look at the code and find the (click) event and pass the reference of the MouseEvent to this event.

Template:

```<code><div (click)="stopEvent($event)"></div>
</code>```

Then call:

```<code>stopEvent(e: MouseEvent) {
  e.stopPropagation();
}

</code>```

Another solution would be to add a disable to the div tag:

```<code><div [disabled]="true"></div>
</code>```

Body:
You can do the following thing. Look at the code and find the (click) event and pass the reference of the MouseEvent to this event.

Template:

<div (click)="stopEvent($event)"></div>

Then call:

stopEvent(e: MouseEvent) {
  e.stopPropagation();
}

Another solution would be to add a disable to the div tag:

<div [disabled]="true"></div>


问:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
I have created tables in MySQL Workbench as shown below :

ORDRE table:

```<code>CREATE TABLE Ordre (
  OrdreID   INT NOT NULL,
  OrdreDato DATE DEFAULT NULL,
  KundeID   INT  DEFAULT NULL,
  CONSTRAINT Ordre_pk PRIMARY KEY (OrdreID),
  CONSTRAINT Ordre_fk FOREIGN KEY (KundeID) REFERENCES Kunde (KundeID)
)
  ENGINE = InnoDB;
</code>```

PRODUKT table:

```<code>CREATE TABLE Produkt (
  ProduktID          INT NOT NULL,
  ProduktBeskrivelse VARCHAR(100) DEFAULT NULL,
  ProduktFarge       VARCHAR(20)  DEFAULT NULL,
  Enhetpris          INT          DEFAULT NULL,
  CONSTRAINT Produkt_pk PRIMARY KEY (ProduktID)
)
  ENGINE = InnoDB;
</code>```

and ORDRELINJE table:

```<code>CREATE TABLE Ordrelinje (
  Ordre         INT NOT NULL,
  Produkt       INT NOT NULL,
  AntallBestilt INT DEFAULT NULL,
  CONSTRAINT Ordrelinje_pk PRIMARY KEY (Ordre, Produkt),
  CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID),
  CONSTRAINT Ordrelinje_fk1 FOREIGN KEY (Produkt) REFERENCES Produkt (ProduktID)
)
  ENGINE = InnoDB;
</code>```

so when I try to insert values into ORDRELINJE table i get:

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (srdjank.Ordrelinje, CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID))

I've seen the other posts on this topic, but no luck.
Am I overseeing something or any idea what to do?

答:
The problem occurs because you set the foreign key in child table after you insert some data in the child table.

Try removing all the data from child table, then set the foreign key and afterwards add/insert the data in table, it will work.

Body:
I have created tables in MySQL Workbench as shown below :

ORDRE table:

CREATE TABLE Ordre (
  OrdreID   INT NOT NULL,
  OrdreDato DATE DEFAULT NULL,
  KundeID   INT  DEFAULT NULL,
  CONSTRAINT Ordre_pk PRIMARY KEY (OrdreID),
  CONSTRAINT Ordre_fk FOREIGN KEY (KundeID) REFERENCES Kunde (KundeID)
)
  ENGINE = InnoDB;

PRODUKT table:

CREATE TABLE Produkt (
  ProduktID          INT NOT NULL,
  ProduktBeskrivelse VARCHAR(100) DEFAULT NULL,
  ProduktFarge       VARCHAR(20)  DEFAULT NULL,
  Enhetpris          INT          DEFAULT NULL,
  CONSTRAINT Produkt_pk PRIMARY KEY (ProduktID)
)
  ENGINE = InnoDB;

and ORDRELINJE table:

CREATE TABLE Ordrelinje (
  Ordre         INT NOT NULL,
  Produkt       INT NOT NULL,
  AntallBestilt INT DEFAULT NULL,
  CONSTRAINT Ordrelinje_pk PRIMARY KEY (Ordre, Produkt),
  CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID),
  CONSTRAINT Ordrelinje_fk1 FOREIGN KEY (Produkt) REFERENCES Produkt (ProduktID)
)
  ENGINE = InnoDB;

so when I try to insert values into ORDRELINJE table i get:

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (srdjank.Ordrelinje, CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID))

I've seen the other posts on this topic, but no luck.
Am I overseeing something or any idea what to do?


问:
How to parse XML with several Attributes and an options list
I have an XML file that looks something similar to this:

```<code><root>
    <data label="product data" min="0" max="10">
        <option>
            <id>1</id>
            <name>Name1</name>
        </option>
        <option>
            <id>2</id>
            <name>Name2</name>
        </option>
        <option>
            <id>3</id>
            <name>Name3</name>
        </option>
    </data>
</root>
</code>```

I need to retreive both data attributes and the option list.

I tried this:

```<code>[XmlRoot(ElementName = "root")]
public class Data
{
    // Retreive data attributes
    [XmlElement(ElementName = "data")]
    public Options Attributes { get; set; }

    // Retrieve option list
    [XmlArray("data")]
    [XmlArrayItem("option", Type = typeof(GeneralOptions))]
    public GeneralOptions[] Options { get; set; }
}
</code>```

Optional classes:

Options

```<code>public class Options
{
    [XmlAttribute("label")]
    public string Label{ get; set; }

    [XmlAttribute("min")]
    public string Min{ get; set; }

    [XmlAttribute("max")]
    public string Max{ get; set; }
}
</code>```

GeneralOptions

```<code>public class GeneralOptions
{
    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "name")]
    public string Name{ get; set; }
}
</code>```

But when I try to deserialize the object, it launches the following exception:

The XML element 'data' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

I imagine the problem is that I'm trying to retreive the same element "twice". But I need to retreive both things. I cannot use the [Attribute] thing because there are several Attributes to retreive, and I need to do this with several XML Elements with the same format and I want to reuse it.

So, how can I retreive both of them?

答:
You'll need to restructure it slightly:

[XmlRoot("root")]
public class Data
{
    [XmlElement("data")]
    public OptionsData Options { get; set; }
}

public class OptionsData
{
    [XmlAttribute("label")]
    public string Label { get; set; }

    [XmlAttribute("min")]
    public string Min { get; set; }

    [XmlAttribute("max")]
    public string Max { get; set; }

    [XmlElement("option")]
    public List<GeneralOptions> Items { get; } = new List<GeneralOptions>();
}

public class GeneralOptions
{
    [XmlElement("id")]
    public string Id { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }
}
```

Body:
I have an XML file that looks something similar to this:

<root>
    <data label="product data" min="0" max="10">
        <option>
            <id>1</id>
            <name>Name1</name>
        </option>
        <option>
            <id>2</id>
            <name>Name2</name>
        </option>
        <option>
            <id>3</id>
            <name>Name3</name>
        </option>
    </data>
</root>

I need to retreive both data attributes and the option list.

I tried this:

[XmlRoot(ElementName = "root")]
public class Data
{
    // Retreive data attributes
    [XmlElement(ElementName = "data")]
    public Options Attributes { get; set; }

    // Retrieve option list
    [XmlArray("data")]
    [XmlArrayItem("option", Type = typeof(GeneralOptions))]
    public GeneralOptions[] Options { get; set; }
}

Optional classes:

Options

public class Options
{
    [XmlAttribute("label")]
    public string Label{ get; set; }

    [XmlAttribute("min")]
    public string Min{ get; set; }

    [XmlAttribute("max")]
    public string Max{ get; set; }
}

GeneralOptions

public class GeneralOptions
{
    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "name")]
    public string Name{ get; set; }
}

But when I try to deserialize the object, it launches the following exception:

The XML element 'data' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

I imagine the problem is that I'm trying to retreive the same element "twice". But I need to retreive both things. I cannot use the [Attribute] thing because there are several Attributes to retreive, and I need to do this with several XML Elements with the same format and I want to reuse it.

So, how can I retreive both of them?


问:
firebase auth with MIcrosoft Graph (accessToken)
I am super hopeful someone can help me - I'm kind of stuck.

I'm happily using firebase auth with Microsoft AD. My AuthProvider is firebase.auth.OAuthProvider('microsoft.com').

When I call firebase.auth().signInWithPopup() with that provider, everything works GREAT. I can pick out the accessToken from the resulting UserCredential and access Microsoft Graph api's no problem (yay!).

Firebase persists and renews the authentication and my app gets the expected callback via onAuthStateChanged with the new firebase.User when the user returns to my SPA later (also yay!).

The bad news (where I'm stuck) is: how do I get the Microsoft Graph accessToken in this flow (e.g. when the user returns to my app later)? I don't want them to have to re-authenticate with another popup (yech).

Basically, how do I go from a valid firebase.User to a MS Graph accessToken when the user returns?

Thanks so so much for any help!

答:
When you are using signInWithPopup, the result object contains the credentials you are looking for.

```<code>firebase.auth().signInWithPopup(provider)
  .then(function(result) {
    // User is signed in.
    // IdP data available in result.additionalUserInfo.profile.
    // OAuth access token can also be retrieved:
    // result.credential.accessToken
    // OAuth ID token can also be retrieved:
    // result.credential.idToken
  })
  .catch(function(error) {
    // Handle error.
  });
</code>```

Hope this helps.

Body:
When you are using signInWithPopup, the result object contains the credentials you are looking for.

firebase.auth().signInWithPopup(provider)
  .then(function(result) {
    // User is signed in.
    // IdP data available in result.additionalUserInfo.profile.
    // OAuth access token can also be retrieved:
    // result.credential.accessToken
    // OAuth ID token can also be retrieved:
    // result.credential.idToken
  })
  .catch(function(error) {
    // Handle error.
  });

Hope this helps.


问:
(ibm_db) ImportError: DLL load failed while importing ibm_db: The specified module could not be found
I have installed Python 3.8.1 and have installed the ibm_db 3.0.1 API for IBM DB2.
When I try to 'import ibm_db' in debug mode I get

"ImportError: DLL load failed while importing ibm_db: The specified
module could not be found."
```

<p>I tried uninstalling and re-installing Python and the API, installing prior versions of Python but nothing worked.
I also tried to see if adding the path prior to the import ibm_db would make a difference:</p>

```sys.path.append(
    "C:\\Users\\<userid>\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\ibm_db")
```

It should not be that hard so please feel free to suggest what might be considered obvious.

答:
Update: 16/June/2020, the ibm_db module versions 3.0.2 and higher now supports Python 3.8 on Microsoft Windows platform.

The ibm_db module versions lower than v3.0.2 do not support Python 3.8 on Microsoft-Windows.

You can see this mentioned on the related github issue github.

ibm_db v3.0.1 will install and work correctly with Python 3.7.x on Microsoft Windows.

Body:
I have installed Python 3.8.1 and have installed the ibm_db 3.0.1 API for IBM DB2.
When I try to 'import ibm_db' in debug mode I get

"ImportError: DLL load failed while importing ibm_db: The specified
module could not be found."

I tried uninstalling and re-installing Python and the API, installing prior versions of Python but nothing worked.
I also tried to see if adding the path prior to the import ibm_db would make a difference:

sys.path.append(
    "C:\\Users\\<userid>\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\\ibm_db")

It should not be that hard so please feel free to suggest what might be considered obvious.


问:
Chosen JS - Add the optgroup to the selected item
I want to find the way to enter the optgroup label into the inserted search-choice item, when the user select a option. With the format [optgroup]-[option].

The problem is that by default there is no a clear way to do it.
Any suggestions on how to achieve this behavior?

Thank you in advance.

This is the default behavior

This is what I am trying to do

答:
I don't know why nobody suggested the right way of doing this. Just set the paramter include_group_label_in_selected to true when initializing the plugin. You will get

<OptGroupLabel> : <OptionText>

in the selected option.


问:
How to display A B C D E if a input 5 numbers 1 2 3 4 5

import random
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(ltr.strip())
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
var1 = random.randrange(1,26)
var2 = random.randrange(1,26)
var3 = random.randrange(1,26)
var4 = random.randrange(1,26)
var5 = random.randrange(1,26)
print(var1,var2,var3,var4,var5)
```

What I want to do is when I input numbers from 1 to 26 it should display a corresponding result. As you can see, the user must input 5 numbers. For example, if we input 1 2 3 4 5 the result must be A B C D E. Also, we have random numbers. For example, if our random numbers are 4 5 3 1 2 the result must be D E C A B.
I don't know what to do to display the result.

答:
strip() your ltr and find element at (entered_position-1) , repeat for five times ,and join the list separated by a space</p>

```<code>ltr = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(' '.join([ltr.strip()[int(input('number 1-26: '))-1] for _ in range(5)]))
print(' '.join([ltr.strip()[random.randrange(1,27)-1] for _ in range(5)]))
</code>```

Body:
import random
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(ltr.strip())
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
var1 = random.randrange(1,26)
var2 = random.randrange(1,26)
var3 = random.randrange(1,26)
var4 = random.randrange(1,26)
var5 = random.randrange(1,26)
print(var1,var2,var3,var4,var5)

What I want to do is when I input numbers from 1 to 26 it should display a corresponding result. As you can see, the user must input 5 numbers. For example, if we input 1 2 3 4 5 the result must be A B C D E. Also, we have random numbers. For example, if our random numbers are 4 5 3 1 2 the result must be D E C A B.
I don't know what to do to display the result.

Body:
strip() your ltr and find element at (entered_position-1) , repeat for five times ,and join the list separated by a space

ltr = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(' '.join([ltr.strip()[int(input('number 1-26: '))-1] for _ in range(5)]))
print(' '.join([ltr.strip()[random.randrange(1,27)-1] for _ in range(5)]))


问:
Import and Combine Multiple CSV in R
I have 12 csv files in one folder, and try to import combine it into 1 single file. Currently i use this code:

```<code>    allFileNames <- list.files("AllData")

for (filename in allFileNames) {
  fullFilename <- paste0("AllData/", filename)
  data <- read.csv(fullFilename,
                          skip=2,
                          na.strings="<1")

  data[is.na(data)] <- 0
  names(data) <- c("x","y","z")
  data <- rbind(data,deparse.level = 0,make.row.names = TRUE,
                   stringsAsFactors = default.stringsAsFactors(),
                   factor.exclude = NA)

}
</code>```

But it only shows 1 file instead of combine all 12 files. In which part did i do wrong?

答: You are intializing data each iteration and replacing whatever was stored there in the beginning. You need to initialize data before the loop, store the temporary file in a new variable then rbind it.

Title: Import and Combine Multiple CSV in R

Body:
I have 12 csv files in one folder, and try to import combine it into 1 single file. Currently i use this code:

    allFileNames <- list.files("AllData")

for (filename in allFileNames) {
  fullFilename <- paste0("AllData/", filename)
  data <- read.csv(fullFilename,
                          skip=2,
                          na.strings="<1")

  data[is.na(data)] <- 0
  names(data) <- c("x","y","z")
  data <- rbind(data,deparse.level = 0,make.row.names = TRUE,
                   stringsAsFactors = default.stringsAsFactors(),
                   factor.exclude = NA)

}

But it only shows 1 file instead of combine all 12 files. In which part did i do wrong?


问:
How to test a checkbox is checked in angular unit test
Hi there I am using a checkbox to be pretend as a toggle button with the help of CSS. The function is simple when the checkbox is true it enables the toggle button and vice versa. I want to check that in my unit test. I know I'm missing something on the below code. Any help would be appreciated

Test

```<code>it('should toggle switch to on if user response equals true', fakeAsync(() => {
    spectator.get(service).user.and.returnValue({});
    spyOn(spectator.get(serivce2), 'method').and.returnValue({Payload: {success: true}});
    tick();
    spectator.detectChanges();
    expect(spectator.query('.toggle-button').getAttribute('checked')).toBeTruthy();
}));
</code>```

答: Assuming .toggle-button is on an <input type="checkbox">. You can use spectator.query('.toggle-button').checked which is standard HTML DOM API.

Body:
Hi there I am using a checkbox to be pretend as a toggle button with the help of CSS. The function is simple when the checkbox is true it enables the toggle button and vice versa. I want to check that in my unit test. I know I'm missing something on the below code. Any help would be appreciated

Test

it('should toggle switch to on if user response equals true', fakeAsync(() => {
    spectator.get(service).user.and.returnValue({});
    spyOn(spectator.get(serivce2), 'method').and.returnValue({Payload: {success: true}});
    tick();
    spectator.detectChanges();
    expect(spectator.query('.toggle-button').getAttribute('checked')).toBeTruthy();
}));


问:
Count all possible combinations no matter the column order
I have a dataset which looks like

```<code>df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2
</code>```

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

```<code>     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....
</code>```

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

答:
Not sure what you want to do and it would be helpful to add a minimal reproducible example as well as an expected example. That way you can help others to help you! But if you want the counts for the letters in any and all columns:

```<code>library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols =everything()) %>%
group_by(value) %>%
summarise(N = n())
</code>```

Body:
I have a dataset which looks like

df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

Body:
Not sure what you want to do and it would be helpful to add a minimal reproducible example as well as an expected example. That way you can help others to help you! But if you want the counts for the letters in any and all columns:

library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols =everything()) %>%
group_by(value) %>%
summarise(N = n())


问:
c# ews login error
Summary:
I need to login to my mailbox using EWS and but i keep getting 440/401 error.

question:
Anything obvious in my code as to why I keep getting either 401 or 440 errors?

Code:

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;

namespace MailboxListenerEWS
{
    class Program
    {
        //Authentication to exchange 2007 with webdav and filebasedauth (FBA) in C#
        //can hardcode a username to connect a mailbox with
        internal static string dUser = "username";//username to log into email account
        internal static string dDomain = "domain";//domain of username used
        internal static string dPassword = "Password";//password of username used
        internal static string MailBoxAliasName = "mailboxname";//mailbox to authenticate too
        internal static string ExchangeServerName = "exchangeName"; //not always needed
        internal static string ReadAttachments = "0"; //1 means read attachments, 0 means dont
        internal static string MailBoxEarliestDateToRead = "2011-01-05T00:00:00.000Z";//date of emails to read from

        static void Main(string[] args)
        {
            //Connect to server
            //ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            //service.Credentials = new NetworkCredential("name", "pwd", "domain");
            service.Credentials = new NetworkCredential("dUser", "dPassword", "dDomain");

            //log in to mailbox
            try
            {
                //service.Url = new Uri(serviceurl);
                //Console.WriteLine(serviceurl);
                //service.AutodiscoverUrl(MailBoxAliasName);
                service.Url = new Uri("https://" + ExchangeServerName + "/EWS/" + MailBoxAliasName + "/inbox");
            }
            catch (AutodiscoverRemoteException ex)
            {
                Console.WriteLine("Exception thrown: " + ex.Error.Message);
                Console.ReadLine();
            }

            //List folders
            try
            {
                //Listing all the subfolders of the Inbox
                FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
                foreach (Item item in findResults)
                {
                    Console.WriteLine(item.Subject);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception thrown: " + ex.Message);
                Console.ReadLine();
            }

        }
    }
}
</code>```

答:
Are you sure your server uses 2007 SP1?  Also, if you're not sure of the correct URL, try using the AutoDiscover, where "user@domain.com" is an actual email address on your domain.

```<code>service.AutodiscoverUrl("user@domain.com");
</code>```

Also, you're setting your URL equal to a URi . I don't think that's legal; is it even compiling?

Here is some sample code that I used as a starting point when I implemented something similar - codeproject.com

Title: c# ews login error

Body:
Summary:
I need to login to my mailbox using EWS and but i keep getting 440/401 error.

question:
Anything obvious in my code as to why I keep getting either 401 or 440 errors?

Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;

namespace MailboxListenerEWS
{
    class Program
    {
        //Authentication to exchange 2007 with webdav and filebasedauth (FBA) in C#
        //can hardcode a username to connect a mailbox with
        internal static string dUser = "username";//username to log into email account
        internal static string dDomain = "domain";//domain of username used
        internal static string dPassword = "Password";//password of username used
        internal static string MailBoxAliasName = "mailboxname";//mailbox to authenticate too
        internal static string ExchangeServerName = "exchangeName"; //not always needed
        internal static string ReadAttachments = "0"; //1 means read attachments, 0 means dont
        internal static string MailBoxEarliestDateToRead = "2011-01-05T00:00:00.000Z";//date of emails to read from

        static void Main(string[] args)
        {
            //Connect to server
            //ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            //service.Credentials = new NetworkCredential("name", "pwd", "domain");
            service.Credentials = new NetworkCredential("dUser", "dPassword", "dDomain");

            //log in to mailbox
            try
            {
                //service.Url = new Uri(serviceurl);
                //Console.WriteLine(serviceurl);
                //service.AutodiscoverUrl(MailBoxAliasName);
                service.Url = new Uri("https://" + ExchangeServerName + "/EWS/" + MailBoxAliasName + "/inbox");
            }
            catch (AutodiscoverRemoteException ex)
            {
                Console.WriteLine("Exception thrown: " + ex.Error.Message);
                Console.ReadLine();
            }

            //List folders
            try
            {
                //Listing all the subfolders of the Inbox
                FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
                foreach (Item item in findResults)
                {
                    Console.WriteLine(item.Subject);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception thrown: " + ex.Message);
                Console.ReadLine();
            }

        }
    }
}

Body:
Are you sure your server uses 2007 SP1?  Also, if you're not sure of the correct URL, try using the AutoDiscover, where "user@domain.com" is an actual email address on your domain.

service.AutodiscoverUrl("user@domain.com");

Also, you're setting your URL equal to a URi . I don't think that's legal; is it even compiling?

Here is some sample code that I used as a starting point when I implemented something similar - codeproject.com


问:
Not all kafka consumers are getting assigned to partitions
I have 10 consumers and 10 partitions.
I take the number of partitions

```<code>int partitionCount = getPartitionCount(kafkaUrl);
</code>```

and I create the same number of consumers with the same group.id.

```<code>    public void listen() {
        try {
            String kafkaUrl = getKafkaUrl();
            int partitionCount = getPartitionCount(kafkaUrl);
            Stream.iterate(0, i -> i + 1)
                    .limit(partitionCount)
                    .forEach(index -> executorService.execute(() ->
                            consumerTask.invokeKafkaConsumerTask(prepareConsumerConfig(index, kafkaUrl), INPUT_TOPIC)));
        } catch (Exception exception) {
            logger.error("Cannot receive event from kafka ", exception);
        }

    public void invokeKafkaConsumerTask(Properties properties, String topicName) {
        try(KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties)) {
            consumer.subscribe(Collections.singletonList(topicName));
            logger.info("[KAFKA] consumer created");
            invokeKafkaConsumer(consumer);
        } catch (IllegalArgumentException exception) {
            logger.error("Cannot create kafka consumer ", exception);
        }
    }

    private void invokeKafkaConsumer(KafkaConsumer<String, String> consumer) {
        try {
            while (true) {
                ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(4));
                if (consumerRecords.count() > 0) {
                    consumeRecords(consumerRecords);
                    consumer.commitSync();
                }
            }
        } catch (Exception e) {
            logger.error("Error while receiving records ", e);
        }
    }
</code>```

method getPartitionCount
return 10 partitions so it's working right

config looks like this

```<code>Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_CLIENT_ID);
properties.put(ConsumerConfig.CLIENT_ID_CONFIG, CONSUMER_CLIENT_ID + index);
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "300000");
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "10000");
properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, String.valueOf(Integer.MAX_VALUE));
properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");
</code>```

what I see after assigning consumers to the partition

```<code>TOPIC      PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CLIENT-ID
topicName  1          89391           89391           0               consumer0
topicName  3          88777           88777           0               consumer1
topicName  5          89280           89280           0               consumer2
topicName  4          88776           88776           0               consumer2
topicName  0          4670991         4670991         0               consumer0
topicName  9          23307           89343           66036           consumer4
topicName  7          89610           89610           0               consumer3
topicName  8          88167           88167           0               consumer4
topicName  2          89138           89138           0               consumer1
topicName  6          88967           88967           0               consumer3
</code>```

only half of the consumers have been assigned to the partitions
why did this happen?
There should be one consumer per partition acording to documentation.
 Am I doing something wrong?
 kafka version 2.1.1.

I also find few this logs ->

```<code>Setting newly assigned partitions:[empty]
</code>```

答:
Are you subscribing to a collection of topic name or java Pattern?

  If you are subscribing to a Pattern , change partition.assignment.strategy to RoundRobinAssignor or StickyAssignor.

Body:
I have 10 consumers and 10 partitions.
I take the number of partitions

int partitionCount = getPartitionCount(kafkaUrl);

and I create the same number of consumers with the same group.id.

    public void listen() {
        try {
            String kafkaUrl = getKafkaUrl();
            int partitionCount = getPartitionCount(kafkaUrl);
            Stream.iterate(0, i -> i + 1)
                    .limit(partitionCount)
                    .forEach(index -> executorService.execute(() ->
                            consumerTask.invokeKafkaConsumerTask(prepareConsumerConfig(index, kafkaUrl), INPUT_TOPIC)));
        } catch (Exception exception) {
            logger.error("Cannot receive event from kafka ", exception);
        }

    public void invokeKafkaConsumerTask(Properties properties, String topicName) {
        try(KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties)) {
            consumer.subscribe(Collections.singletonList(topicName));
            logger.info("[KAFKA] consumer created");
            invokeKafkaConsumer(consumer);
        } catch (IllegalArgumentException exception) {
            logger.error("Cannot create kafka consumer ", exception);
        }
    }

    private void invokeKafkaConsumer(KafkaConsumer<String, String> consumer) {
        try {
            while (true) {
                ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofSeconds(4));
                if (consumerRecords.count() > 0) {
                    consumeRecords(consumerRecords);
                    consumer.commitSync();
                }
            }
        } catch (Exception e) {
            logger.error("Error while receiving records ", e);
        }
    }

method getPartitionCount
return 10 partitions so it's working right

config looks like this

Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_CLIENT_ID);
properties.put(ConsumerConfig.CLIENT_ID_CONFIG, CONSUMER_CLIENT_ID + index);
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "300000");
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "10000");
properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, String.valueOf(Integer.MAX_VALUE));
properties.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RoundRobinAssignor");

what I see after assigning consumers to the partition

TOPIC      PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CLIENT-ID
topicName  1          89391           89391           0               consumer0
topicName  3          88777           88777           0               consumer1
topicName  5          89280           89280           0               consumer2
topicName  4          88776           88776           0               consumer2
topicName  0          4670991         4670991         0               consumer0
topicName  9          23307           89343           66036           consumer4
topicName  7          89610           89610           0               consumer3
topicName  8          88167           88167           0               consumer4
topicName  2          89138           89138           0               consumer1
topicName  6          88967           88967           0               consumer3

only half of the consumers have been assigned to the partitions
why did this happen?
There should be one consumer per partition acording to documentation.
 Am I doing something wrong?
 kafka version 2.1.1.

I also find few this logs ->

Setting newly assigned partitions:[empty]


问:
loop through array, find sub-string in cell, replace text in Google Sheets
I want to create a function in Google Sheets that loops through an array, finds a string, and replaces the text of the string with a new value.  I have code that works but it only replaces the text if the cell ONLY contains the string (ie search for "office" replace with "Office" only works if the cell only contains "office).  I want to be able to replace "office" with "Office" even if the cell contains "office 867".  Below is the code that works. Also, how can I get the function to search column A, row 1 to whatever?  As of now, the function only finds and replaces if the values are in B2 to whatever (ie the first column A is not searched and the first row of every other row is not searched. Function works on B2 to whatever but won't work on B1, C1, D1, etc.  I know it is because of the searchRange variable but I can't figure out how to set the parameters so that it searches the entire sheet (ie all columns and all rows).  So here's the code I have so far.  The questions I have are in the code as comments:</p>

```<code>// This code works but ONLY if entire cell matches the string being searched for
// I want to search for all cells that contain the string even if other text is present
// So if cell contains "office 98" I want to change that to "Office 98"
// If cell contains "blg 78" I want to change that to "Building 78"
// If cell contains "space 9876" I want to change that to "Space 9876"
// Also, how do I change the var searchRange so that the range is the entire sheet?

var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,2, lastRow-1, lastColumn-1);

function findReplace() {
  var rangeValues = searchRange.getValues();
  for ( i = 0; i < lastColumn - 1; i++){
    for ( j = 0 ; j < lastRow - 1; j++){
      if(rangeValues[j][i] === "office"){
        sheet.getRange(j+2,i+2).setValue("Office");
      }else if (rangeValues[j][i] === "blg"){
        sheet.getRange(j+2,i+2).setValue("Building");
       }else if (rangeValues[j][i] === "space"){
        sheet.getRange(j+2,i+2).setValue("Space");
      };
    };
  };
};
</code>```

答:
You can use getDataRange function [1] to get the entire range where there's data in the sheet. To avoid matching the entire string, use indexOf method [2] to check if the searched string is inside the cell string. To only replace the searched string, use replace function [3] on the cell value. I also put a string validation so any other type of cell value will be ignored (Number, Date, Boolean):

```<code>var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var searchRange = sheet.getDataRange();
var lastColumn = searchRange.getLastColumn();
var lastRow = searchRange.getLastRow();

function findReplace() {
  var rangeValues = searchRange.getValues();
  for ( i = 0; i < lastColumn; i++){
    for ( j = 0 ; j < lastRow; j++){
      var value = rangeValues[j][i];
      if(typeof value != "string") { continue; }
      if(value.indexOf("office") > -1){
        var newValue = value.replace("office", "Office")
        sheet.getRange(j+1,i+1).setValue(newValue);
      }
      else if (value.indexOf("blg") > -1){
        var newValue = value.replace("blg", "Building")
        sheet.getRange(j+1,i+1).setValue(newValue);
      }
      else if (value.indexOf("space") > -1){
        var newValue = value.replace("space", "Space")
        sheet.getRange(j+1,i+1).setValue(newValue);
      };
    };
  };
};
</code>```

[1] https://developers.google.com/apps-script/reference/spreadsheet/sheet#getdatarange

[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

[3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Body:
I want to create a function in Google Sheets that loops through an array, finds a string, and replaces the text of the string with a new value.  I have code that works but it only replaces the text if the cell ONLY contains the string (ie search for "office" replace with "Office" only works if the cell only contains "office).  I want to be able to replace "office" with "Office" even if the cell contains "office 867".  Below is the code that works. Also, how can I get the function to search column A, row 1 to whatever?  As of now, the function only finds and replaces if the values are in B2 to whatever (ie the first column A is not searched and the first row of every other row is not searched. Function works on B2 to whatever but won't work on B1, C1, D1, etc.  I know it is because of the searchRange variable but I can't figure out how to set the parameters so that it searches the entire sheet (ie all columns and all rows).  So here's the code I have so far.  The questions I have are in the code as comments:

// This code works but ONLY if entire cell matches the string being searched for
// I want to search for all cells that contain the string even if other text is present
// So if cell contains "office 98" I want to change that to "Office 98"
// If cell contains "blg 78" I want to change that to "Building 78"
// If cell contains "space 9876" I want to change that to "Space 9876"
// Also, how do I change the var searchRange so that the range is the entire sheet?

var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,2, lastRow-1, lastColumn-1);

function findReplace() {
  var rangeValues = searchRange.getValues();
  for ( i = 0; i < lastColumn - 1; i++){
    for ( j = 0 ; j < lastRow - 1; j++){
      if(rangeValues[j][i] === "office"){
        sheet.getRange(j+2,i+2).setValue("Office");
      }else if (rangeValues[j][i] === "blg"){
        sheet.getRange(j+2,i+2).setValue("Building");
       }else if (rangeValues[j][i] === "space"){
        sheet.getRange(j+2,i+2).setValue("Space");
      };
    };
  };
};

Body:
You can use getDataRange function [1] to get the entire range where there's data in the sheet. To avoid matching the entire string, use indexOf method [2] to check if the searched string is inside the cell string. To only replace the searched string, use replace function [3] on the cell value. I also put a string validation so any other type of cell value will be ignored (Number, Date, Boolean):

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var searchRange = sheet.getDataRange();
var lastColumn = searchRange.getLastColumn();
var lastRow = searchRange.getLastRow();

function findReplace() {
  var rangeValues = searchRange.getValues();
  for ( i = 0; i < lastColumn; i++){
    for ( j = 0 ; j < lastRow; j++){
      var value = rangeValues[j][i];
      if(typeof value != "string") { continue; }
      if(value.indexOf("office") > -1){
        var newValue = value.replace("office", "Office")
        sheet.getRange(j+1,i+1).setValue(newValue);
      }
      else if (value.indexOf("blg") > -1){
        var newValue = value.replace("blg", "Building")
        sheet.getRange(j+1,i+1).setValue(newValue);
      }
      else if (value.indexOf("space") > -1){
        var newValue = value.replace("space", "Space")
        sheet.getRange(j+1,i+1).setValue(newValue);
      };
    };
  };
};

[1] https://developers.google.com/apps-script/reference/spreadsheet/sheet#getdatarange

[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

[3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace


问:
How to scroll the page to the very bottom in Android Espresso?
I need to check the presence of the button that is located below. To do this, scroll through the page

```<code>@Test
public void checkMoneyBackButton() throws Exception {

    onView(withId(R.id.btnAuthLogin)).perform(click());

    Thread.sleep(10000);
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();

    SystemClock.sleep(45000);

    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());

    Thread.sleep(3000);

    onView(withId(R.id.cardContainer))
            .perform(swipeUp());

    onView(withId(R.id.statementMoneyBack)).check(matches(isDisplayed()));
}
</code>```

But using this code, I get an error:

```<code> Error performing 'fast swipe' on view 'with id:...
</code>```

答:
Hacky style, but should do the trick:</p>

```<code>`` // Scroll down the view with for loop (as many times you need to iterate)
        for(int i=0;i<=20;i++){
            onView(withText("Use_here_any_text_from_the_view")).perform(swipeUp());
        }
``
</code>```

Body:
I need to check the presence of the button that is located below. To do this, scroll through the page

@Test
public void checkMoneyBackButton() throws Exception {

    onView(withId(R.id.btnAuthLogin)).perform(click());

    Thread.sleep(10000);
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();

    SystemClock.sleep(45000);

    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());

    Thread.sleep(3000);

    onView(withId(R.id.cardContainer))
            .perform(swipeUp());

    onView(withId(R.id.statementMoneyBack)).check(matches(isDisplayed()));
}

But using this code, I get an error:

 Error performing 'fast swipe' on view 'with id:...

Body:
Hacky style, but should do the trick:

`` // Scroll down the view with for loop (as many times you need to iterate)
        for(int i=0;i<=20;i++){
            onView(withText("Use_here_any_text_from_the_view")).perform(swipeUp());
        }
``


问:
yup.number().typeError() not cheking for character other than dot(.)
I use yup for validation along with formik . I was using typeError() for checking wether the number contains any other characters than numbers. It works properly with character dot(.), but not working for other characters.

This is my validation code:

```<code>credits: Yup.number()
      .required('general.mandatory')
      .typeError('settings.credit_not_allow_decimal_validation_text')
      .min(1, 'settings.credit_credit_range_validation_text')
      .max(100000, 'settings.credit_credit_range_validation_text')
      .positive('settings.credit_not_allow_decimal_validation_text')
      .integer('settings.credit_not_allow_decimal_validation_text')
</code>```

I'm also posting the versions of formik and yup

"formik": "^0.11.11", "yup": "^0.25.1"

I'll also post images of errors I'm supposed to get

// Validation error shown

//No validation error shown

I want to have like detecting any characters other than numbers used to throw error message while using Yup.number(). Please help Thanks in advance :)

答:
At last after some updates i found out that this issue was fixed with updating my formik and yup libraries to their latest versions

The current versions are:

"formik": "^2.1.4", "yup": "^0.28.1"

Body:
I use yup for validation along with formik . I was using typeError() for checking wether the number contains any other characters than numbers. It works properly with character dot(.), but not working for other characters.

This is my validation code:

credits: Yup.number()
      .required('general.mandatory')
      .typeError('settings.credit_not_allow_decimal_validation_text')
      .min(1, 'settings.credit_credit_range_validation_text')
      .max(100000, 'settings.credit_credit_range_validation_text')
      .positive('settings.credit_not_allow_decimal_validation_text')
      .integer('settings.credit_not_allow_decimal_validation_text')

I'm also posting the versions of formik and yup

"formik": "^0.11.11", "yup": "^0.25.1"

I'll also post images of errors I'm supposed to get

// Validation error shown

//No validation error shown

I want to have like detecting any characters other than numbers used to throw error message while using Yup.number(). Please help Thanks in advance :)


问:
WordPress Contact-Form 7
I would like to add a field with 2 emails for reception but I don't find it.

```<code>[select* recipient
"Problem|tata@gmail.com"
"Idea|titi@gmail.com"
"Other|toto@gmail.com"]
</code>```

I would like to do something like this :

```<code>[select* recipient
"Problem|tata@gmail.com"
"Idea|titi@gmail.com"
"Other|toto@gmail.com|tutu@gmail.com"]
</code>```

It gives me an error and I don't find any syntax to do this.

How to send to two email addresses with a specific field with contact form 7 ?

EDIT : I found the solution here : Contact Form 7 send to multiple contacts at once upon user selection

答: To get value before pipe, you can use [raw{field name}], that means [_raw_recipient] in your form

Title: WordPress Contact-Form 7

Body:
I would like to add a field with 2 emails for reception but I don't find it.

[select* recipient
"Problem|tata@gmail.com"
"Idea|titi@gmail.com"
"Other|toto@gmail.com"]

I would like to do something like this :

[select* recipient
"Problem|tata@gmail.com"
"Idea|titi@gmail.com"
"Other|toto@gmail.com|tutu@gmail.com"]

It gives me an error and I don't find any syntax to do this.

How to send to two email addresses with a specific field with contact form 7 ?

EDIT : I found the solution here : Contact Form 7 send to multiple contacts at once upon user selection


问:
how get get file name in file chooser in react?
could you please tell me how get get file name in file chooser in react ?
I am trying to set value in input field after choosing file from file chooser
here is my code
https://stackblitz.com/edit/react-d4kp1d?file=bulk.js
I tried like this

```<code><input
        id="file_input_file"
        className="none"
        type="file"
        ref={inputRef }
        onChange={(e)=>{
          console.log('---')
          console.log(inputRef.current[0].files[0].name)

        }}
      />
</code>```

it gives me undefined

答:
You can get selected file name without using ref

```<code>  function handleChange(event) {
    console.log(`Selected file - ${event.target.files[0].name}`);
  }

  <input type="file" onChange={handleChange} />

</code>```

Body:
could you please tell me how get get file name in file chooser in react ?
I am trying to set value in input field after choosing file from file chooser
here is my code
https://stackblitz.com/edit/react-d4kp1d?file=bulk.js
I tried like this

<input
        id="file_input_file"
        className="none"
        type="file"
        ref={inputRef }
        onChange={(e)=>{
          console.log('---')
          console.log(inputRef.current[0].files[0].name)

        }}
      />

it gives me undefined

Body:
You can get selected file name without using ref

  function handleChange(event) {
    console.log(`Selected file - ${event.target.files[0].name}`);
  }

  <input type="file" onChange={handleChange} />


问:
Google datastudio change report filter dynamically
I have data from many clients collected via my Google Analytics and clients would like to access their reports. At this point, I clone a report, change a report filter, and give them access. But now I end up having a lot of similar reports where the only difference is the client name in the filter.

I would to create one report template and simply pass programmatically the filter value equal to the client name. Is it something possible to do in Google Data Studio?

Added clarification:
We use a custom content group called Business to record what client the data belong to and then we filter Content Group(Business) = Client_name

答:
Depending on how the data is set up (if required you could perhaps use a blended Google Sheet to link the contact details), one way could be to have a look through the recently introduced Filter by email address, thus if each row of data has a clients email address, then it will automatically filter based on the respective client.

Adding a link to a blog post by Mehdi Oudjida to elaborate: Google Data Studio – Filter by email address overview & creative usage for report personalization