问:
can't inject repository when use @Autowired in a non-web-application
I want to use spring-boot-jpa in my spider application, and I already have the maven dependency, models, modelRepository and the application.properties. After I use the annotation @autowired to use these repository, it will have a NullPointerException. How can I use them in my spider?
Here is my spider.

```<code>@Component
public class Crawler implements PageProcessor {
    SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    CategoryRepository categoryRepository;
    @Autowired
    NewsRepository newsRepository;
    @Autowired
    SourceRepository sourceRepository;
    public static String content;
    private Site site = Site.me().setRetryTimes(0).setSleepTime(100000000);
    public void process(Page page) {
        Pattern pattern = Pattern.compile("artiList\\((.*)\\)");
        Matcher matcher = pattern.matcher(page.getRawText());
        String json = null;
        if (matcher.find()) {
            json = matcher.group(1);
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode;
        try {
            rootNode = mapper.readTree(json);
            JsonNode mainJson = rootNode.path("BAI6RHDKwangning");
            Iterator<JsonNode> iterator = mainJson.elements();
            String cur = null;
            JsonNode mark = null;
            List<Map<String, Object>> list = new ArrayList<>();
            while (iterator.hasNext()) {
                mark = iterator.next();
                cur = mark.toString();
                Map<String, Object> map = mapper.readValue(cur, Map.class);
                list.add(map);
            }

            dbService(list);

        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    public void dbService(List<Map<String, Object>> list) {
        try {
                for (Map<String, Object> map : list) {

                    for (String s : map.keySet()) {
                        System.out.println(s + "=" + map.get(s));
                        System.out.println();
                    }
                    Article article = new Article();
                    article.setUrl(map.get("url").toString());
                    if (categoryRepository == null) {
                        System.out.println("================================================asdasasdsad");
                    }
                    Category category = categoryRepository.findByCategoryName("game");
                    News news = new News();
                    Source source = sourceRepository.findBySourceName(map.get("source").toString());
                    if (source == null) {
                        source = new Source();
                        source.setSourceName(map.get("source").toString());
                    } else {
                        source.setPublishCount(source.getPublishCount() + 1);
                    }
                    news.setDocid(map.get("docid").toString());
                    news.setCommentCount(Integer.valueOf(map.get("commentCount").toString()));
                    news.setDigest(map.get("digest").toString());
                    news.setHasImg(Integer.valueOf(map.get("hasImg").toString()));
                    news.setImgsrc(map.get("imgsrc").toString());
                    news.setPriority(Integer.valueOf(map.get("priority").toString()));
                    news.setPtime(sdf.parse(map.get("ptime").toString()));
                    news.setTitle(map.get("title").toString());
                    news.setArticleId(article);
                    news.setCategoryCode(category);
                    news.setArticleId(article);
                    news.setSourceId(source);

                    articleRepository.save(article);
                    sourceRepository.save(source);
                    newsRepository.save(news);

                }
        } catch (ParseException e) {
            System.out.println(e.getMessage() );
            e.printStackTrace();
        }
    }

    public Site getSite() {
        return site;
    }
    public void runSpider() {
        Spider.create(new Crawler())
        .addUrl("http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html")

        .thread(5)

        .run();
    }
}
</code>```

This is my MainApplication.

```<code>@SpringBootApplication
public class NethardApplication implements CommandLineRunner{

    @Autowired
    Crawler crawler;
    public static void main(String[] args) {
        SpringApplication.run(NethardApplication.class, args);
    }
    @Override
    public void run(String... args) {
        crawler.runSpider();
    }
}
</code>```

And this is my project directory.

This is the console

```<code>10:05:34.602 [pool-1-thread-1] ERROR us.codecraft.webmagic.Spider - process request Request{url='http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html', method='null', extras=null, priority=0, headers={}, cookies={}} error
java.lang.NullPointerException: null
    at com.cmh.Crawler.dbService(Crawler.java:90)
    at com.cmh.Crawler.process(Crawler.java:70)
    at us.codecraft.webmagic.Spider.onDownloadSuccess(Spider.java:414)
    at us.codecraft.webmagic.Spider.processRequest(Spider.java:406)
    at us.codecraft.webmagic.Spider.access$000(Spider.java:61)
    at us.codecraft.webmagic.Spider$1.run(Spider.java:320)
    at us.codecraft.webmagic.thread.CountableThreadPool$1.run(CountableThreadPool.java:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
10:05:34.603 [main] INFO us.codecraft.webmagic.Spider - Spider 3g.163.com closed! 1 pages downloaded.
</code>```

答:
When you are creating an object with new, that object will no be managed by Spring, therefore no Autowire will happen.

But you already have a Crawler bean managed by Spring in runSpider method, can you just inject that one, like:

```<code>Spider.create(this).addUrl("http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html")
    .thread(5)
    .run();
</code>```

Body:
I want to use spring-boot-jpa in my spider application, and I already have the maven dependency, models, modelRepository and the application.properties. After I use the annotation @autowired to use these repository, it will have a NullPointerException. How can I use them in my spider?
Here is my spider.

@Component
public class Crawler implements PageProcessor {
    SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    CategoryRepository categoryRepository;
    @Autowired
    NewsRepository newsRepository;
    @Autowired
    SourceRepository sourceRepository;
    public static String content;
    private Site site = Site.me().setRetryTimes(0).setSleepTime(100000000);
    public void process(Page page) {
        Pattern pattern = Pattern.compile("artiList\\((.*)\\)");
        Matcher matcher = pattern.matcher(page.getRawText());
        String json = null;
        if (matcher.find()) {
            json = matcher.group(1);
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode;
        try {
            rootNode = mapper.readTree(json);
            JsonNode mainJson = rootNode.path("BAI6RHDKwangning");
            Iterator<JsonNode> iterator = mainJson.elements();
            String cur = null;
            JsonNode mark = null;
            List<Map<String, Object>> list = new ArrayList<>();
            while (iterator.hasNext()) {
                mark = iterator.next();
                cur = mark.toString();
                Map<String, Object> map = mapper.readValue(cur, Map.class);
                list.add(map);
            }

            dbService(list);

        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    public void dbService(List<Map<String, Object>> list) {
        try {
                for (Map<String, Object> map : list) {

                    for (String s : map.keySet()) {
                        System.out.println(s + "=" + map.get(s));
                        System.out.println();
                    }
                    Article article = new Article();
                    article.setUrl(map.get("url").toString());
                    if (categoryRepository == null) {
                        System.out.println("================================================asdasasdsad");
                    }
                    Category category = categoryRepository.findByCategoryName("game");
                    News news = new News();
                    Source source = sourceRepository.findBySourceName(map.get("source").toString());
                    if (source == null) {
                        source = new Source();
                        source.setSourceName(map.get("source").toString());
                    } else {
                        source.setPublishCount(source.getPublishCount() + 1);
                    }
                    news.setDocid(map.get("docid").toString());
                    news.setCommentCount(Integer.valueOf(map.get("commentCount").toString()));
                    news.setDigest(map.get("digest").toString());
                    news.setHasImg(Integer.valueOf(map.get("hasImg").toString()));
                    news.setImgsrc(map.get("imgsrc").toString());
                    news.setPriority(Integer.valueOf(map.get("priority").toString()));
                    news.setPtime(sdf.parse(map.get("ptime").toString()));
                    news.setTitle(map.get("title").toString());
                    news.setArticleId(article);
                    news.setCategoryCode(category);
                    news.setArticleId(article);
                    news.setSourceId(source);

                    articleRepository.save(article);
                    sourceRepository.save(source);
                    newsRepository.save(news);

                }
        } catch (ParseException e) {
            System.out.println(e.getMessage() );
            e.printStackTrace();
        }
    }

    public Site getSite() {
        return site;
    }
    public void runSpider() {
        Spider.create(new Crawler())
        .addUrl("http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html")

        .thread(5)

        .run();
    }
}

This is my MainApplication.

@SpringBootApplication
public class NethardApplication implements CommandLineRunner{

    @Autowired
    Crawler crawler;
    public static void main(String[] args) {
        SpringApplication.run(NethardApplication.class, args);
    }
    @Override
    public void run(String... args) {
        crawler.runSpider();
    }
}

And this is my project directory.

This is the console

10:05:34.602 [pool-1-thread-1] ERROR us.codecraft.webmagic.Spider - process request Request{url='http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html', method='null', extras=null, priority=0, headers={}, cookies={}} error
java.lang.NullPointerException: null
    at com.cmh.Crawler.dbService(Crawler.java:90)
    at com.cmh.Crawler.process(Crawler.java:70)
    at us.codecraft.webmagic.Spider.onDownloadSuccess(Spider.java:414)
    at us.codecraft.webmagic.Spider.processRequest(Spider.java:406)
    at us.codecraft.webmagic.Spider.access$000(Spider.java:61)
    at us.codecraft.webmagic.Spider$1.run(Spider.java:320)
    at us.codecraft.webmagic.thread.CountableThreadPool$1.run(CountableThreadPool.java:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
10:05:34.603 [main] INFO us.codecraft.webmagic.Spider - Spider 3g.163.com closed! 1 pages downloaded.

Body:
When you are creating an object with new, that object will no be managed by Spring, therefore no Autowire will happen.

But you already have a Crawler bean managed by Spring in runSpider method, can you just inject that one, like:

Spider.create(this).addUrl("http://3g.163.com/touch/reconstruct/article/list/BAI6RHDKwangning/0-1.html")
    .thread(5)
    .run();


来源: stackexchange

问:
"Internal Server Error" when refreshing page or typing URL manually when using React Router
I am having a problem that I have seen many questions for, but I can't find a solution that works for me.

This problem only happens when I push to Heroku and load it from the web.  If i go to the root of my site (i.e. domain.com) the page loads.  If I click around, the page rerenders with the correct components while changing the URL.  If I refresh the page, type the URL, or navigate to the page via any way but a set of links that originated at the home page I get an "Internal Server Error".

I understand that this is a React-Router problem. I have tried changing my devServer config historyApiFallback to true.  I have also tried changing the index in historyApiFallback to the root of my application.

Update
When I go into my logs on Heroku, I get this error when trying to navigate to domain.com/activity

```<code>2017-11-13T05:43:36.957344+00:00 app[web.1]: ReferenceError: path is not defined
2017-11-13T05:43:36.957347+00:00 app[web.1]:     at /app/server.js:7:23
2017-11-13T05:43:36.957348+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-11-13T05:43:36.957349+00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/route.js:137:13)
2017-11-13T05:43:36.957350+00:00 app[web.1]:     at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
2017-11-13T05:43:36.957351+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-11-13T05:43:36.957352+00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:281:22
2017-11-13T05:43:36.957353+00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:354:14)
2017-11-13T05:43:36.957354+00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:365:14)
2017-11-13T05:43:36.957355+00:00 app[web.1]:     at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3)
2017-11-13T05:43:36.957355+00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/index.js:275:10)
</code>```

package.json

```<code>{
  "name": "app",
  "version": "1.0.0",
  "description": "App",
  "main": "index.js",
  "repository": "xxx@github.com",
  "scripts": {
    "start": "webpack-dev-server --inline --content-base . --history-api-fallback",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch",
    "prod": "NODE_ENV=production node server.js",
    "postinstall": "webpack -p"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.16.2",
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^0.14.3",
    "react-autosuggest": "^9.3.2",
    "react-dom": "^0.14.3",
    "react-dropzone": "^4.2.1",
    "react-pdf": "^2.1.1",
    "react-redux": "4.3.0",
    "react-router": "^2.0.1",
    "react-router-dom": "^4.1.2",
    "react-select": "^1.0.0-rc.10",
    "recharts": "^1.0.0-beta.0",
    "redux": "^3.0.4",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.2.0"
  }
}
</code>```

server.js

```<code>var express = require('express');
var app = express();

app.use(express.static(__dirname + '/'));
app.get('*', function (request, response){
    response.sendFile(path.resolve(__dirname, 'index.html'))
});
app.listen(process.env.PORT || 8080);
</code>```

webpack.config.js

```<code>module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};
</code>```

答:
I think I resolved the issue.  To server.js, I added

```<code>var path = require('path');
</code>```

and it began routing properly.

ContentLicense: CC BY-SA 3.0

Body:
I am having a problem that I have seen many questions for, but I can't find a solution that works for me.

This problem only happens when I push to Heroku and load it from the web.  If i go to the root of my site (i.e. domain.com) the page loads.  If I click around, the page rerenders with the correct components while changing the URL.  If I refresh the page, type the URL, or navigate to the page via any way but a set of links that originated at the home page I get an "Internal Server Error".

I understand that this is a React-Router problem. I have tried changing my devServer config historyApiFallback to true.  I have also tried changing the index in historyApiFallback to the root of my application.

Update
When I go into my logs on Heroku, I get this error when trying to navigate to domain.com/activity

2017-11-13T05:43:36.957344+00:00 app[web.1]: ReferenceError: path is not defined
2017-11-13T05:43:36.957347+00:00 app[web.1]:     at /app/server.js:7:23
2017-11-13T05:43:36.957348+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-11-13T05:43:36.957349+00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/route.js:137:13)
2017-11-13T05:43:36.957350+00:00 app[web.1]:     at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
2017-11-13T05:43:36.957351+00:00 app[web.1]:     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2017-11-13T05:43:36.957352+00:00 app[web.1]:     at /app/node_modules/express/lib/router/index.js:281:22
2017-11-13T05:43:36.957353+00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:354:14)
2017-11-13T05:43:36.957354+00:00 app[web.1]:     at param (/app/node_modules/express/lib/router/index.js:365:14)
2017-11-13T05:43:36.957355+00:00 app[web.1]:     at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3)
2017-11-13T05:43:36.957355+00:00 app[web.1]:     at next (/app/node_modules/express/lib/router/index.js:275:10)

package.json

{
  "name": "app",
  "version": "1.0.0",
  "description": "App",
  "main": "index.js",
  "repository": "xxx@github.com",
  "scripts": {
    "start": "webpack-dev-server --inline --content-base . --history-api-fallback",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch",
    "prod": "NODE_ENV=production node server.js",
    "postinstall": "webpack -p"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "axios": "^0.16.2",
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^0.14.3",
    "react-autosuggest": "^9.3.2",
    "react-dom": "^0.14.3",
    "react-dropzone": "^4.2.1",
    "react-pdf": "^2.1.1",
    "react-redux": "4.3.0",
    "react-router": "^2.0.1",
    "react-router-dom": "^4.1.2",
    "react-select": "^1.0.0-rc.10",
    "recharts": "^1.0.0-beta.0",
    "redux": "^3.0.4",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.2.0"
  }
}

server.js

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/'));
app.get('*', function (request, response){
    response.sendFile(path.resolve(__dirname, 'index.html'))
});
app.listen(process.env.PORT || 8080);

webpack.config.js

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

Body:
I think I resolved the issue.  To server.js, I added

var path = require('path');

and it began routing properly.


问:
JMeter read from csv file to array
Is there any possibility to read files from .csv into array of variables?

Instead of getting:

https://loadtest.com/mo/75245.json

https://loadtest.com/mo/190554MHG.json

https://loadtest.com/mo/190223MJG.json

https://loadtest.com/mo/198533FTR.json

...

I would like to get an array:

https://loadtest.com/mo/75245.190554MHG.190223MJG.198533FTR.19023.HGTYTRWEYRWEHF.1922MHGDGO.json

Does anybody have some idea?

Thank you in advance.

答:
Check out the following JMeter Functions:

__FileToString() - to read your CSV file into a JMeter Variable

__split() - to "split" the aforementioned JMeter Variable holding CSV file content into separate variables using any suitable delimited (comma, tabulation symbol, newline, whatever)

Title: JMeter read from csv file to array


问:
Programmatically uncheck checkboxcolumn in datagridview
How can I programmatically uncheck all rows in a DataGridViewCheckboxColumn in a datagridview?

I can get the correct value of the checkbox using

```<code>(bool)row.Cells[CheckBoxColumn.Index].FormattedValue
</code>```

but that's only a getter.

I have tried setting the value of the cell using

```<code>(bool)row.Cells[CheckBoxColumn.Index].value = false
</code>```

but that doesn't affect the FormattedValue.

How can I solve this?

答:
Loop through each row of grid view and use the find control method:</p>

```<code>foreach ( GridViewRow row in myGridView )
{
     CheckBox checkBox = ( CheckBox ) row.FindControl( "myCheckBox" );
     checkbox.Checked = false;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can I programmatically uncheck all rows in a DataGridViewCheckboxColumn in a datagridview?

I can get the correct value of the checkbox using

(bool)row.Cells[CheckBoxColumn.Index].FormattedValue

but that's only a getter.

I have tried setting the value of the cell using

(bool)row.Cells[CheckBoxColumn.Index].value = false

but that doesn't affect the FormattedValue.

How can I solve this?

Body:
Loop through each row of grid view and use the find control method:

foreach ( GridViewRow row in myGridView )
{
     CheckBox checkBox = ( CheckBox ) row.FindControl( "myCheckBox" );
     checkbox.Checked = false;
}


问:
How to display nested json object in json array on Server side using Mustache
I am using mustache to create template using Spring-boot-starter-mustache on Server side to create templates.

I referred : https://www.mkyong.com/spring-boot/spring-boot-hello-world-example-mustache/

pom.xml:

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mustache</artifactId>
        <version>1.5.8.RELEASE</version>
</dependency>
</code>```

I have a Java JSON object that I am creating in my Controller:

```<code>model.put("schoolJson", schoolJson);
return "viewJson";
</code>```

JSON structure:

```<code>{
"school": "abc",
"loc":  "def",
"type": [
            {
            "section": "sec1",
            "test": {
                    "grade": "gradea"
                    }
            },{
            "section": "sec2",
            "test": {
                    "grade": "gradeb"
                    }
            }
        ]
}
</code>```

In my viewJson I want to display the 'grade' of each 'test' in 'type'. But it does not get displayed. Can someone help out here.

```<code><div>
 <p>{{schoolJson.school}}</p>

  {{#schoolJson.type}}
   <ul>
    <li>schoolJson.type.grade</li>
   </ul>
  {{/schoolJson.type}}
</div>
</code>```

答:
Your li should be done this way:

```<code><li>
    {{#test}}
        {{grade}}
    {{/test}}
</li>
</code>```

This is because you have to go into the context of the nested test object to be able to get the grade value

Body:
I am using mustache to create template using Spring-boot-starter-mustache on Server side to create templates.

I referred : https://www.mkyong.com/spring-boot/spring-boot-hello-world-example-mustache/

pom.xml:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mustache</artifactId>
        <version>1.5.8.RELEASE</version>
</dependency>

I have a Java JSON object that I am creating in my Controller:

model.put("schoolJson", schoolJson);
return "viewJson";

JSON structure:

{
"school": "abc",
"loc":  "def",
"type": [
            {
            "section": "sec1",
            "test": {
                    "grade": "gradea"
                    }
            },{
            "section": "sec2",
            "test": {
                    "grade": "gradeb"
                    }
            }
        ]
}

In my viewJson I want to display the 'grade' of each 'test' in 'type'. But it does not get displayed. Can someone help out here.

{{schoolJson.school}}

  {{#schoolJson.type}}

schoolJson.type.grade

  {{/schoolJson.type}}

Body:
Your li should be done this way:

<li>
    {{#test}}
        {{grade}}
    {{/test}}
</li>

This is because you have to go into the context of the nested test object to be able to get the grade value


问:
How to unit test Rx.Net foreach subscription
All messages should be published to the message bus:

```<code> upstream.Get().ForEachAsync(async e => await _bus.Publish(e, cancellationToken));
</code>```

I want to unit test to verify that the publish method is being called correctly:

```<code>    [Theory, AutoMoqData]
    public void Publish_ShouldPublishAllDataSources(
        [Frozen]Mock<IBus> bus,
        [Frozen]Mock<IUpstream> upstream,
        SUT sut,
        TestScheduler scheduler,
        CancellationToken cancellationToken
        )
    {
        {
            Arrange();
            Act();
            Assert();
        }
        ITestableObservable<Event> inputObservable;

        void Arrange()
        {
            inputObservable =
                    scheduler.CreateColdObservable(
                        OnNext(1L,new Event("e1")),
                        OnNext(1L,new Event("e2")),
                        OnNext(1L,new Event("e3"))
                    );
            upstream
            .Setup(c => c.Get())
            .Returns(inputObservable);

        }

        void Act()
        {
            sut.Exercise(cancellationToken);
            //Do sth with scheduller to fire all events
            //I've tested these:
            //scheduler.Start();
            //scheduler.AdvanceTo(30000L);
        }

        void Assert()
        {
            inputObservable.ForEach(e =>
                bus.Verify(b =>
                    b.Publish(e, cancellationToken)
                ));
        }
    }
</code>```

But whatever I try the test never stops.

Update:

Here's the complete production code:

```<code>class SUT
{
     IUpstream _upstream;
     public SUT(IUpstream upstream)
     {
          _upstream = upstream;
     }
     void Exercise(CancellationToken cancellationToken)
     {
         _upstream .Get()
               .ForEachAsync(async
                    e => await _bus.Publish(e, cancellationToken));
     }
}

interface IUpstream
{
    IObservable<string> Get();
}

interface IBus
{
    void Publish<T>(T,System.Threading.CancellationToken)
}
</code>```

答:
The ITestableObservable<T>.Messages should be used for assertion not the ITestableObservable<T> itself.

```<code>    void Assert()
    {
        inputObservable
                .Messages.ToList()
                .ForEach(e =>
                bus.Verify(b =>
                    b.Publish(e.Value.Value, cancellationToken)));
    }
</code>```

So the action should be like the following:

```<code>    void Act()
    {
        sut.Exercise(cancellationToken);
        scheduler.Start();
        //OR:
        //scheduler.AdvanceBy(1L);
    }
</code>```

Body:
All messages should be published to the message bus:

 upstream.Get().ForEachAsync(async e => await _bus.Publish(e, cancellationToken));

I want to unit test to verify that the publish method is being called correctly:

    [Theory, AutoMoqData]
    public void Publish_ShouldPublishAllDataSources(
        [Frozen]Mock<IBus> bus,
        [Frozen]Mock<IUpstream> upstream,
        SUT sut,
        TestScheduler scheduler,
        CancellationToken cancellationToken
        )
    {
        {
            Arrange();
            Act();
            Assert();
        }
        ITestableObservable<Event> inputObservable;

        void Arrange()
        {
            inputObservable =
                    scheduler.CreateColdObservable(
                        OnNext(1L,new Event("e1")),
                        OnNext(1L,new Event("e2")),
                        OnNext(1L,new Event("e3"))
                    );
            upstream
            .Setup(c => c.Get())
            .Returns(inputObservable);

        }

        void Act()
        {
            sut.Exercise(cancellationToken);
            //Do sth with scheduller to fire all events
            //I've tested these:
            //scheduler.Start();
            //scheduler.AdvanceTo(30000L);
        }

        void Assert()
        {
            inputObservable.ForEach(e =>
                bus.Verify(b =>
                    b.Publish(e, cancellationToken)
                ));
        }
    }

But whatever I try the test never stops.

Update:

Here's the complete production code:

class SUT
{
     IUpstream _upstream;
     public SUT(IUpstream upstream)
     {
          _upstream = upstream;
     }
     void Exercise(CancellationToken cancellationToken)
     {
         _upstream .Get()
               .ForEachAsync(async
                    e => await _bus.Publish(e, cancellationToken));
     }
}

interface IUpstream
{
    IObservable<string> Get();
}

interface IBus
{
    void Publish<T>(T,System.Threading.CancellationToken)
}

Body:
The ITestableObservable<T>.Messages should be used for assertion not the ITestableObservable<T> itself.

    void Assert()
    {
        inputObservable
                .Messages.ToList()
                .ForEach(e =>
                bus.Verify(b =>
                    b.Publish(e.Value.Value, cancellationToken)));
    }

So the action should be like the following:

    void Act()
    {
        sut.Exercise(cancellationToken);
        scheduler.Start();
        //OR:
        //scheduler.AdvanceBy(1L);
    }


问:
Finding corresponding graph from given shortest paths
Given n by n points and the distance d between these points, I need to find the corresponding undirected weighted graph that would result in these distances. I tried using Prim's algorithm to find the MST, however this set is of size n-1 and does not include the n needed edges. E.g. given n by n distances

```<code>0 3 5
3 0 4
5 4 0
</code>```

I need to find the corresponding edges:

```<code>1 - 2 = 3
1 - 3 = 5
2 - 3 = 4
</code>```

Which results in the graph:

```<code>      3
1 --------- 2
 \         /
  \5      /4
   \     /
    \   /
      3
</code>```

However Prim's would return only the first 2 edges since a MST doesn't contain any cycles.

答:
One graph that would result in these distances is the graph that has an edge from every node to every other node and the length of that edge is the distance according to the matrix. (I'm not sure what you mean by unweighted directed because the example you give appears to be undirected and I'm not sure what the difference is between weights and lengths here).

Another option would be to consider the distances in increasing order, as you have done with Prim's algorithm, and, as well as checking to see if the edge is required to connect its two ends, check to see if the minimum distance between those ends in the graph reconstructed so far is the same as the distance in the matrix. If it is not, add the edge even if the ends are connected in the graph so far.

Body:
Given n by n points and the distance d between these points, I need to find the corresponding undirected weighted graph that would result in these distances. I tried using Prim's algorithm to find the MST, however this set is of size n-1 and does not include the n needed edges. E.g. given n by n distances

0 3 5
3 0 4
5 4 0

I need to find the corresponding edges:

1 - 2 = 3
1 - 3 = 5
2 - 3 = 4

Which results in the graph:

      3
1 --------- 2
 \         /
  \5      /4
   \     /
    \   /
      3

However Prim's would return only the first 2 edges since a MST doesn't contain any cycles.


问:
how to exclude the debug sample from the summary report in jmeter?
How to exclude the debug sample from the summary report?

I tried removing but for some reason it does not work the process below, so is there a way to exclude from the results?

答:
You can use Filter Results Tool JMeter Plugin like:

```<code>FilterResults.bat --input-file your_existing_file.jtl --output-file result_without_debug_samplers.jtl --exclude-labels "Debug Sampler"
</code>```

The above command line will parse existing results file and remove any Debug Sampler instances from it.

Filter Results Tool plugin can be installed using JMeter Plugins Manager

Upon installation you will find FilterResults.bat and FilterResults.sh scripts under JMeter's "bin" folder

Body:
You can use Filter Results Tool JMeter Plugin like:

FilterResults.bat --input-file your_existing_file.jtl --output-file result_without_debug_samplers.jtl --exclude-labels "Debug Sampler"

The above command line will parse existing results file and remove any Debug Sampler instances from it.

Filter Results Tool plugin can be installed using JMeter Plugins Manager

Upon installation you will find FilterResults.bat and FilterResults.sh scripts under JMeter's "bin" folder


问:
Pass data to model from controller in codeigniter
I am getting data from view using post method ie., in $data variable
and I need pass this  i.e, $data to model I have tried like below but it is showing like A PHP

Error was encountered Severity: Notice Message:  Undefined property:
  Post::$data Filename: core/Model.php Line Number: 77

Below is mycode:

```<code>Array
(
    [name] => Mohan
    [email] => mohan@gmail.com
    [phone] => 9739764966
    [location] => TEST
    [website] => 192.168.1.156
    [useragent] => Chrome
    [ipaddress] => 192.168.1.23
    [desc] => Bengaluru
    [captcha] => 20701449
    [captcha_word] => 20701449
    [submit] => Submit
)
</code>```

controller:

```<code>public function postEnquiry()
{
    $data = $this->input->post();
    // echo "```";print_r($data);die;
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }

}
```

<p>Model:</p>

```<?php
class Enquiry extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function sendenquiry($data)
    {
        print_r($data);die;
    }

}
?>
```

答:
You must load the db library first in autoload.php

```<code>$autoload['libraries'] = array('database');
</code>```

I hope this will help you

ContentLicense: CC BY-SA 4.0

Body:
I am getting data from view using post method ie., in $data variable
and I need pass this  i.e, $data to model I have tried like below but it is showing like A PHP

Error was encountered Severity: Notice Message:  Undefined property:
  Post::$data Filename: core/Model.php Line Number: 77

Below is mycode:

Array
(
    [name] => Mohan
    [email] => mohan@gmail.com
    [phone] => 9739764966
    [location] => TEST
    [website] => 192.168.1.156
    [useragent] => Chrome
    [ipaddress] => 192.168.1.23
    [desc] => Bengaluru
    [captcha] => 20701449
    [captcha_word] => 20701449
    [submit] => Submit
)

controller:

public function postEnquiry()
{
    $data = $this->input->post();
    // echo "
";print_r($data);die;
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }

}

Model:

<?php
class Enquiry extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function sendenquiry($data)
    {
        print_r($data);die;
    }

}
?>

Body:
You must load the db library first in autoload.php

$autoload['libraries'] = array('database');

I hope this will help you


问:
How to register an OData Serializer Provider with AspNet.OData v6
Microsoft.AspNet.Odata changed the way you register services like serializers. What should the new format look like?</p>

答:
Your new config should look something like this. You need to add at least the first 2 services (IEdmModel and IEnumerable IODataRoutingConvention), and then you can add your own. For example, a custom odata serializer provider.

```<code>using Boomerang.OData;
using Boomerang.Models;
using Microsoft.OData;
using Microsoft.OData.Edm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Formatter;
using System.Web.OData.Formatter.Serialization;
using System.Web.OData.Routing.Conventions;

namespace Boomerang
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.MapODataServiceRoute(
                "ODataRoute",
                "api",
                containerBuilder => containerBuilder
                .AddService<IEdmModel>(ServiceLifetime.Singleton, s => BuildEdmModelForOData())
                .AddService<IEnumerable<IODataRoutingConvention>>(ServiceLifetime.Singleton, sp =>
                    ODataRoutingConventions.CreateDefaultWithAttributeRouting("ODataRoute", config))
                .AddService<ODataSerializerProvider>(ServiceLifetime.Singleton, s => new CustomODataSerializerProvider(s))
                );

            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
        }

        public static IEdmModel BuildEdmModelForOData()
        {
            ODataConventionModelBuilder
                oDataConventionModelBuilder = new ODataConventionModelBuilder();

            // Build model here
            oDataConventionModelBuilder.EntitySet<Post>("Posts");
            oDataConventionModelBuilder.EntitySet<Feeling>("Feelings");

            return oDataConventionModelBuilder.GetEdmModel();
        }
    }
}
</code>```

I'm adding this answer because most of the guides online give instructions for versions before 6. This information can be found here: http://odata.github.io/WebApi/#13-04-DependencyInjection

Body:
Your new config should look something like this. You need to add at least the first 2 services (IEdmModel and IEnumerable IODataRoutingConvention), and then you can add your own. For example, a custom odata serializer provider.

using Boomerang.OData;
using Boomerang.Models;
using Microsoft.OData;
using Microsoft.OData.Edm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Formatter;
using System.Web.OData.Formatter.Serialization;
using System.Web.OData.Routing.Conventions;

namespace Boomerang
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.MapODataServiceRoute(
                "ODataRoute",
                "api",
                containerBuilder => containerBuilder
                .AddService<IEdmModel>(ServiceLifetime.Singleton, s => BuildEdmModelForOData())
                .AddService<IEnumerable<IODataRoutingConvention>>(ServiceLifetime.Singleton, sp =>
                    ODataRoutingConventions.CreateDefaultWithAttributeRouting("ODataRoute", config))
                .AddService<ODataSerializerProvider>(ServiceLifetime.Singleton, s => new CustomODataSerializerProvider(s))
                );

            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
        }

        public static IEdmModel BuildEdmModelForOData()
        {
            ODataConventionModelBuilder
                oDataConventionModelBuilder = new ODataConventionModelBuilder();

            // Build model here
            oDataConventionModelBuilder.EntitySet<Post>("Posts");
            oDataConventionModelBuilder.EntitySet<Feeling>("Feelings");

            return oDataConventionModelBuilder.GetEdmModel();
        }
    }
}

I'm adding this answer because most of the guides online give instructions for versions before 6. This information can be found here: http://odata.github.io/WebApi/#13-04-DependencyInjection


问:
Running kaa notification demo
When i run the notification demo,following warning and errors are shown click here for image description

Please let me know how to solve this problem.

答: It seems like a connection problem. Meaning your SDK is not able to reach kaa sandbox server. Make sure your server is running properly.</p>

Title: Running kaa notification demo


问:
JMeter: Stop test if the fail count rate is higher than success
In JMeter,

I'm creating a test plan

In which I need to set a condition

(if the fail count rate is high than success, then I want my test to stop)

Tried :

Auto-stop listener but its useful if we specify error rate %

Tried bean shell post-processor but unsuccessful.

if (!prev.isSuccessful()) {
         prev.setStopThread(true);
    }

Any ideas much appreciated.! thanks in advance.!

答:
By calling setStopThread you are "asking" JMeter to attempt to stop current thread only, the correct method would be prev.setStopTest(true). Again, if you call this method JMeter will "ask" threads to stop, if you want JMeter terminate in less graceful manner you can go for prev.setStopTestNow(true) method (you can get more failures this way as samplers will be abnormally terminated)

And finally you can call System.exit(1) method which will immediately terminate the whole JVM.

Be aware that since JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language for scripting consider migrating from Beanshell to Groovy on next available opportunity.


问:
MVC Code First using Navigation Properties
It is a simple system for comments and messages. They have also two actors: FromActor and ToActor... My codes are like this:

```<code> public class Comment
 {
    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public virtual Actor AboutActor { get; set; }
    public virtual Actor FromActor { get; set; }
 }

 public class Message
 {
    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public virtual Actor ToActor { get; set; }
    public virtual Actor FromActor { get; set; }
}

public class Actor
{
    public int Id { get; set; }
    public string Username { get; set; }
    public virtual List<Comment> Comments { get; set; }
    public virtual List<Message> Messages { get; set; }
}
</code>```

I'm in trouble with navigation props in code first. Is it true? How should I edit navigation links or models for solution? Thanks...

答:
You should add additional references to Comments and Messages at Actor class and use InversePropertyAttribute to map them with corresponding properties. Also you can declare FKs directly:

```<code>public class Comment
{
    //other stuff...
    public int AboutActorId { get; set; }
    public int FromActorId { get; set; }
    public virtual Actor AboutActor { get; set; }
    public virtual Actor FromActor { get; set; }
}

public class Message
{
    //other stuff...
    public int ToActorId { get; set; }
    public int FromActorId { get; set; }
    public virtual Actor ToActor { get; set; }
    public virtual Actor FromActor { get; set; }
}

public class Actor
{
    public int Id { get; set; }
    public string Username { get; set; }

    [InverseProperty("AboutActor")]
    public virtual ICollection<Comment> CommentsAbout { get; set; }
    [InverseProperty("FromActor")]
    public virtual ICollection<Comment> CommentsFrom { get; set; }

    [InverseProperty("ToActor")]
    public virtual ICollection<Message> MessagesTo { get; set; }
    [InverseProperty("FromActor")]
    public virtual ICollection<Message> MessagesFrom { get; set; }
}
</code>```

Body:
It is a simple system for comments and messages. They have also two actors: FromActor and ToActor... My codes are like this:

 public class Comment
 {
    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public virtual Actor AboutActor { get; set; }
    public virtual Actor FromActor { get; set; }
 }

 public class Message
 {
    public int Id { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public virtual Actor ToActor { get; set; }
    public virtual Actor FromActor { get; set; }
}

public class Actor
{
    public int Id { get; set; }
    public string Username { get; set; }
    public virtual List<Comment> Comments { get; set; }
    public virtual List<Message> Messages { get; set; }
}

I'm in trouble with navigation props in code first. Is it true? How should I edit navigation links or models for solution? Thanks...

Body:
You should add additional references to Comments and Messages at Actor class and use InversePropertyAttribute to map them with corresponding properties. Also you can declare FKs directly:

public class Comment
{
    //other stuff...
    public int AboutActorId { get; set; }
    public int FromActorId { get; set; }
    public virtual Actor AboutActor { get; set; }
    public virtual Actor FromActor { get; set; }
}

public class Message
{
    //other stuff...
    public int ToActorId { get; set; }
    public int FromActorId { get; set; }
    public virtual Actor ToActor { get; set; }
    public virtual Actor FromActor { get; set; }
}

public class Actor
{
    public int Id { get; set; }
    public string Username { get; set; }

    [InverseProperty("AboutActor")]
    public virtual ICollection<Comment> CommentsAbout { get; set; }
    [InverseProperty("FromActor")]
    public virtual ICollection<Comment> CommentsFrom { get; set; }

    [InverseProperty("ToActor")]
    public virtual ICollection<Message> MessagesTo { get; set; }
    [InverseProperty("FromActor")]
    public virtual ICollection<Message> MessagesFrom { get; set; }
}


问:
Changing int result `15` to `{ "result" : 15 }`
I am creating an ASP.NET Web API that calls an addition function from a dll file and finds the sum of the numbers that user input in the URL. E.g: http://localhost:52241/api/dlladdition/9/6 (user inputs numbers 9 and 6). The result will be 15. I want the result to be something like { "result" : 15 }. How do i achieve that?

Here are my codes:

dll file

Mathclass.cs

```<code>public static class MathClass
{
    //method for Addition
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}
</code>```

ASP.NET Web API

Addition.cs

```<code>using ClassLibraryDll;
public class Addition
{
    public static int num1 { get; set; }
    public static int num2 { get; set; }

    public static int sum = MathClass.Add(num1, num2);
}
</code>```

AdditionController.cs

```<code>private Addition addition = new Addition();

public int GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return result;
}
</code>```

WebApiConfig.cs

```<code>public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DllAdditionApi",
            routeTemplate: "api/dlladdition/{num1}/{num2}",
            defaults: new { action = "Get", controller = "DllAddition" }
        );
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept","text/html",
            StringComparison.InvariantCultureIgnoreCase,true,"application/json")
       );

    }
</code>```

答:
Just return an object of anonymous type with Result property. Asp.net will format it to JSON for you:

```<code>public Object GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return new
    {
        Result = result
    };
}
</code>```

Body:
I am creating an ASP.NET Web API that calls an addition function from a dll file and finds the sum of the numbers that user input in the URL. E.g: http://localhost:52241/api/dlladdition/9/6 (user inputs numbers 9 and 6). The result will be 15. I want the result to be something like { "result" : 15 }. How do i achieve that?

Here are my codes:

dll file

Mathclass.cs

public static class MathClass
{
    //method for Addition
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}

ASP.NET Web API

Addition.cs

using ClassLibraryDll;
public class Addition
{
    public static int num1 { get; set; }
    public static int num2 { get; set; }

    public static int sum = MathClass.Add(num1, num2);
}

AdditionController.cs

private Addition addition = new Addition();

public int GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return result;
}

WebApiConfig.cs

public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DllAdditionApi",
            routeTemplate: "api/dlladdition/{num1}/{num2}",
            defaults: new { action = "Get", controller = "DllAddition" }
        );
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept","text/html",
            StringComparison.InvariantCultureIgnoreCase,true,"application/json")
       );

    }

Body:
Just return an object of anonymous type with Result property. Asp.net will format it to JSON for you:

public Object GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return new
    {
        Result = result
    };
}


问:
Printing from nested dictionary
How to print either 1 specific value, or a select key2 values for all key1 from a nested dictionary? The lines in my code display nothing.

Foe example, how to print (a single value):

```<code>Canon-PS-G7-X-Mark-II`
</code>```

or (select key2 values for all key1):

```<code>Canon-PS-G7-X-Mark-II
Nikon-D5
Sony-alpha9
</code>```

The dictionary (part of it) and code

```<code>config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """
1 camera:
(config['g7']['cam_name'])

all cameras
(config[.]['cam_name'])

"""
print(camtype)
</code>```

答:
I am sure someone else can do better than I.</p>

```<code>config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """1 camera: %s""" %(config['g7']['cam_name']) #search up python print function
allcam = [ value['cam_name'] for key, value in config.items()] #creates list with all cameras
str_allcam = "all cameras " + ', '.join( str(p) for p in allcam) # prints all cameras with a comma seperator

print(camtype +"\n" + str_allcam) # outputs a two lines because of newline seperator
</code>```

Title: Printing from nested dictionary

Body:
How to print either 1 specific value, or a select key2 values for all key1 from a nested dictionary? The lines in my code display nothing.

Foe example, how to print (a single value):

Canon-PS-G7-X-Mark-II`

or (select key2 values for all key1):

Canon-PS-G7-X-Mark-II
Nikon-D5
Sony-alpha9

The dictionary (part of it) and code

config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """
1 camera:
(config['g7']['cam_name'])

all cameras
(config[.]['cam_name'])

"""
print(camtype)

Body:
I am sure someone else can do better than I.

config = {
    'g7': {},
    'd5': {},
    'a9': {},
}
config['g7']['cam_name'] = ('Canon-PS-G7-X-Mark-II')
config['d5']['cam_name'] = ('Nikon-D5')
config['a9']['cam_name'] = ('Sony-alpha9')

camtype = """1 camera: %s""" %(config['g7']['cam_name']) #search up python print function
allcam = [ value['cam_name'] for key, value in config.items()] #creates list with all cameras
str_allcam = "all cameras " + ', '.join( str(p) for p in allcam) # prints all cameras with a comma seperator

print(camtype +"\n" + str_allcam) # outputs a two lines because of newline seperator


问:
Click on element after fading in on hover
I have a paragraph and an anchor, when i hover into the paragraph, the anchor fades in, how can I keep it for a little while so I can click on it? because when I move the mouse away from the p element it disappears and I cant click on it, here is my code:

$(function() {
  $('p').hover(function() {
    $('a').fadeIn();
  }, function() {
    $('a').css('display','none');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{
  display: none;
}</code>```

Show anchor

Hi```

答:
If you need to animate minor things like drop down menus or fading links, you should use CSS. It's easier to write, and modern browsers are optimized to run CSS animations using the GPU (it's a CPU for graphics).

This demo only uses CSS:

@keyframes for smoother transitions fade in and out with opacity values

pointer-events in order to control how the link behaves. In this demo, the link will only appear if the paragraph is hovered over.

padding and borders of paragraph and link are touching. This design allows the user to move the mouse over to the link without interruptions of the hover. There are dashed outlines to show the hover area only, they are for the demo and are optional.

Demo

* {
  margin: 0;
  padding: 0;
}

body {
  font: 700 18px/1.2 Verdana;
}

a {
  display: block;
  padding: 1em .5em;
  border: 0 none rgba(0, 0, 0, 0);
  pointer-events: none;
  cursor: default;
  animation: out;
  opacity: 0;
  transition: all 0s, opacity 4s ease;
}

p {
  margin-top:30px;
  padding: .5em
}

p:hover+a,
a:hover {
  border: 1em;
  pointer-events: auto;
  cursor: pointer;
  animation: in;
  opacity: 1;
  transition: all 0s, opacity 2s ease;
}

@keyframes in {
  0% {
    opacity: 0
  }
  33% {
    opacity: .33
  }
  66% {
    opacity: .66
  }
  100% {
    opacity: 1
  }
}

@keyframes out {
  0% {
    opacity: 1
  }
  33% {
    opacity: .66
  }
  66% {
    opacity: .33
  }
  100% {
    opacity: 0
  }
}

a {
  outline: 1px dashed red
}
p {
  outline: 1px dashed blue
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Show anchor</p>
Hi</code>```

Body:
I have a paragraph and an anchor, when i hover into the paragraph, the anchor fades in, how can I keep it for a little while so I can click on it? because when I move the mouse away from the p element it disappears and I cant click on it, here is my code:

$(function() {
  $('p').hover(function() {
    $('a').fadeIn();
  }, function() {
    $('a').css('display','none');
  });
});

a{
  display: none;
}

Show anchor

Hi

Body:
If you need to animate minor things like drop down menus or fading links, you should use CSS. It's easier to write, and modern browsers are optimized to run CSS animations using the GPU (it's a CPU for graphics).

This demo only uses CSS:

@keyframes for smoother transitions fade in and out with opacity values

pointer-events in order to control how the link behaves. In this demo, the link will only appear if the paragraph is hovered over.

padding and borders of paragraph and link are touching. This design allows the user to move the mouse over to the link without interruptions of the hover. There are dashed outlines to show the hover area only, they are for the demo and are optional.

Demo

* {
  margin: 0;
  padding: 0;
}

body {
  font: 700 18px/1.2 Verdana;
}

a {
  display: block;
  padding: 1em .5em;
  border: 0 none rgba(0, 0, 0, 0);
  pointer-events: none;
  cursor: default;
  animation: out;
  opacity: 0;
  transition: all 0s, opacity 4s ease;
}

p {
  margin-top:30px;
  padding: .5em
}

p:hover+a,
a:hover {
  border: 1em;
  pointer-events: auto;
  cursor: pointer;
  animation: in;
  opacity: 1;
  transition: all 0s, opacity 2s ease;
}

@keyframes in {
  0% {
    opacity: 0
  }
  33% {
    opacity: .33
  }
  66% {
    opacity: .66
  }
  100% {
    opacity: 1
  }
}

@keyframes out {
  0% {
    opacity: 1
  }
  33% {
    opacity: .66
  }
  66% {
    opacity: .33
  }
  100% {
    opacity: 0
  }
}

a {
  outline: 1px dashed red
}
p {
  outline: 1px dashed blue
}

<p>Show anchor</p>
<a href="#">Hi</a>


问:
Error while trying integration between JMeter and Kibana
I am trying to connect Jmeter to Kibana using this manual:
https://blogs.sap.com/2016/04/06/load-testing-with-jmeter-test-results-visualization-using-kibana-dashboards/comment-page-1/#comment-398399

I am using JMeter 3.2, and downloaded elasticsearch-5.6.4.zip.

I extract the zip and put the folder elasticsearch-5.6.4 in C:\Jmeter\apache-jmeter-3.2\lib

I downloaded the jar JMeter_ElasticsearchListener.jar and put it in C:\Jmeter\apache-jmeter-3.2\lib\ext

I restart JMeter and pressed add -> listener -> backend listener and get these errors:

    017-11-11 09:39:12,429 ERROR o.a.j.g.GuiPackage: Problem retrieving gui for org.apache.jmeter.visualizers.backend.BackendListenerGui
    java.lang.NoClassDefFoundError: org/elasticsearch/client/RestClientBuilder$HttpClientConfigCallback
        at java.lang.Class.forName0(Native Method) ~[?:1.8.0_141]
        at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_141]
        at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.2 r1790748]
        at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_141]
        at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_141]
        at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_141]
        at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.2 r1790748]
        at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:74) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:59) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_141]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_141]
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_141]
    Caused by: java.lang.ClassNotFoundException: org.elasticsearch.client.RestClientBuilder$HttpClientConfigCallback
        at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_141]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_141]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_141]
        ... 25 more
    2017-11-11 09:39:40,782 ERROR o.a.j.g.a.AddToTree: Exception while adding a component to tree.
    java.lang.RuntimeException: java.lang.NoClassDefFoundError: org/elasticsearch/client/RestClientBuilder$HttpClientConfigCallback
        at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:359) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:74) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:59) ~[ApacheJMeter_core.jar:3.2 r1790748]
        at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_141]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_141]
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_141]
        at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_141]
        at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_141]
    Caused by: java.lang.NoClassDefFoundError: org/elasticsearch/client/RestClientBuilder$HttpClientConfigCallback
        at java.lang.Class.forName0(Native Method) ~[?:1.8.0_141]
        at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_141]
        at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.2 r1790748]
        at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_141]
        at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_141]
        at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_141]
        at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.2 r1790748]
        at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.2 r1790748]
        ... 17 more
    Caused by: java.lang.ClassNotFoundException: org.elasticsearch.client.RestClientBuilder$HttpClientConfigCallback
        at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_141]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_141]
        at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_141]
        at java.lang.Class.forName0(Native Method) ~[?:1.8.0_141]
        at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_141]
        at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.2 r1790748]
        at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_141]
        at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_141]
        at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_141]
        at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.2 r1790748]
        at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.2 r1790748]
        ... 17 more

答:
I don't think JMeter recursively searches any folders in its "lib" folder looking for any .jars it can add to its classpath, so I would recommend either moving all .jars from the elasticsearch-5.6.4 folder to JMeter's "lib" folder.

Alternatively you can add the next line to user.properties file (lives under "bin" folder of your JMeter installation)

```<code>user.classpath=C:\Jmeter\apache-jmeter-3.2\lib\elasticsearch-5.6.4`
</code>```

In both cases JMeter restart will be required to pick the libraries up.

More information:

JMeter Classpath

Apache JMeter Properties Customization Guide

Body:
I don't think JMeter recursively searches any folders in its "lib" folder looking for any .jars it can add to its classpath, so I would recommend either moving all .jars from the elasticsearch-5.6.4 folder to JMeter's "lib" folder.

Alternatively you can add the next line to user.properties file (lives under "bin" folder of your JMeter installation)

user.classpath=C:\Jmeter\apache-jmeter-3.2\lib\elasticsearch-5.6.4`

In both cases JMeter restart will be required to pick the libraries up.

More information:

JMeter Classpath

Apache JMeter Properties Customization Guide


问:
Windows batch file to get C:\ drive total space and free space available
I need a bat file to get C:\ drive total space and free space available in GB (giga bytes) in a Windows system and create a text file with the details.

Note: i dont want to use any external utilities.

答:
This should work in batch:</p>

```<code>for /f "tokens=2" %%S in ('wmic volume get DriveLetter^, FreeSpace ^| findstr "^C:"') do set space=%%S
echo %space%
</code>```

Body:
This should work in batch:

for /f "tokens=2" %%S in ('wmic volume get DriveLetter^, FreeSpace ^| findstr "^C:"') do set space=%%S
echo %space%


答:
Change the result type of the controller, and then you can return an anonymous class projecting the shape you need:

```<code>[Route("api/dlladdition/{num1}/{num2}")]
public IHttpActionResult GET(int num1, int num2)
{
    var res = ClassLibraryDll.MathClass.Add(num1, num2);
    return Ok(new {result = res});
}
</code>```

One other suggestion is to use the WebApi RouteAttribute to perform tailored route mapping, rather than resorting to using the global  config.Routes.MapHttpRoute for the same purpose. (You've already registered RouteAttributes with the call to config.MapHttpAttributeRoutes();)

Title: Changing int result `15` to `{ "result" : 15 }`

Body:
Change the result type of the controller, and then you can return an anonymous class projecting the shape you need:

[Route("api/dlladdition/{num1}/{num2}")]
public IHttpActionResult GET(int num1, int num2)
{
    var res = ClassLibraryDll.MathClass.Add(num1, num2);
    return Ok(new {result = res});
}

One other suggestion is to use the WebApi RouteAttribute to perform tailored route mapping, rather than resorting to using the global  config.Routes.MapHttpRoute for the same purpose. (You've already registered RouteAttributes with the call to config.MapHttpAttributeRoutes();)


问:
Waiting for response after clickling
I click on button, and which send ajax request and change input hidden value.
How can I wait for an answer and trace the change of the hidden field?

I had tried make "sleep" and get events, but sometimes you get bad data, because the request is very long.

```<code>http.createServer(async (req, res) => {
if (req.url === '/') {
    if (req.method === 'GET') {
        res.writeHead(200, {
            'content-type': 'text/html; charset=utf-8',
            'cache-control': 'public,max-age=31536000',
        });
        res.end(fs.readFileSync(__dirname + '/templates/index.html'));
        return;
    } else if (req.method === 'POST') {

        let body = '';
        await req.on('data', (data) => body += data);

        body = qs.parse(body);

        let url = body.url;

        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(url);

        let count = (selector) => page.evaluate((selector) => {
            return (document.querySelectorAll(selector)).length;
        }, selector);

        let sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

        const countM = await count(MSEL),
            countS = await count(SSEL);
        console.log(countS, countM);

        let click = (selector, number) => page.click(`${selector}:nth-child(${number})`);

        let data = [];

        for (let i = 1; i <= countS; i++) {
            await click(SSEL, i);
            sleep(SLEEP);

            for (let j = 1; j <= countM; j++) {
                await click(MSEL, j);
                sleep(SLEEP);

                const info = await page.evaluate(() => {
                    return {
                        val: document.getElementById('val').value,
                        cc: document.getElementById('cc').value
                    };
                });
                data.push(info);
            }
        }
    }

} else {
    res.writeHead(400, {
        'content-type': 'text/plain',
    });
    res.end('Something is wrong. Missing URL.');
    return;
}
}).listen(3000);
</code>```

Sorry for my english.
Thank you

答:
I could ask you a lot of questions before answering,

what is MSEL and SSEL?

What is the URL?

What is in the templates/index.html?

What kind of bad data you get?

Why you are looping inside a loop?

Why you have a sleep() promise but not awaiting that promise?

What happens when you push info to the data, do you return it as response?

etc etc. the list can go on, but we have to start somewhere, right? I will not write the whole code, and do everything for you. But I'll help you understand the problem.

Lots of part in your code is missing, as well as there are errors because you did not write things properly.

I'd separate the functions. I'm assuming you have the variables called MSEL, SSEL somewhere defined.

First, you are not returning anything in response. That's something you need to watch for, if you are not returning response, then the request is never going to end, and result in timeout.

```<code>http
  .createServer(async (req, res) => {
    if (req.url === "/") {
      if (req.method === "GET") {
        res.writeHead(200, {
          "content-type": "text/html; charset=utf-8",
          "cache-control": "public,max-age=31536000"
        });
        res.end(fs.readFileSync(__dirname + "/templates/index.html"));
        return;
      } else if (req.method === "POST") {
        let body = "";
        await req.on("data", data => (body += data));
        body = qs.parse(body);
        const returnData = await getData({ body, MSEL, SSEL }); // <-- seperate the function
        res.end(returnData); // <-- return the data
      }
    } else {
      res.writeHead(400, {
        "content-type": "text/plain"
      });
      res.end("Something is wrong. Missing URL.");
      return;
    }
  })
  .listen(3000);
</code>```

And here is the function seperately, notice how I wrote await before sleep and also refactored some bits and parts a little bit, also returning the function after everything is done.

```<code>async function getData({ body, MSEL, SSEL }) {
  let url = body.url;

  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(url);

  let count = selector =>
    page.evaluate(selector => {
      return document.querySelectorAll(selector).length;
    }, selector);

  let sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

  const countM = await count(MSEL),
    countS = await count(SSEL);

  let click = (selector, number) =>
    page.click(`${selector}:nth-child(${number})`);

  let data = [];

  for (let i = 1; i <= countS; i++) {
    await click(SSEL, i);
    await sleep(SLEEP);

    for (let j = 1; j <= countM; j++) {
      await click(MSEL, j);
      await sleep(SLEEP);

      const info = await page.evaluate(() => {
        return {
          val: document.getElementById("val").value,
          cc: document.getElementById("cc").value
        };
      });
      data.push(info);
    }
  }
  return data;
}
</code>```

What I did was refactor and fix your code a bit, but this is not the solution you are looking for, the code might not even work.

You need to understand how promises works. Refer to the following tutorials before copy-pasting my solution hoping that it'll work ;) ,

https://ponyfoo.com/articles/es6-promises-in-depth

https://ponyfoo.com/articles/understanding-javascript-async-await

Title: Waiting for response after clickling

Body:
I click on button, and which send ajax request and change input hidden value.
How can I wait for an answer and trace the change of the hidden field?

I had tried make "sleep" and get events, but sometimes you get bad data, because the request is very long.

http.createServer(async (req, res) => {
if (req.url === '/') {
    if (req.method === 'GET') {
        res.writeHead(200, {
            'content-type': 'text/html; charset=utf-8',
            'cache-control': 'public,max-age=31536000',
        });
        res.end(fs.readFileSync(__dirname + '/templates/index.html'));
        return;
    } else if (req.method === 'POST') {

        let body = '';
        await req.on('data', (data) => body += data);

        body = qs.parse(body);

        let url = body.url;

        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(url);

        let count = (selector) => page.evaluate((selector) => {
            return (document.querySelectorAll(selector)).length;
        }, selector);

        let sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

        const countM = await count(MSEL),
            countS = await count(SSEL);
        console.log(countS, countM);

        let click = (selector, number) => page.click(`${selector}:nth-child(${number})`);

        let data = [];

        for (let i = 1; i <= countS; i++) {
            await click(SSEL, i);
            sleep(SLEEP);

            for (let j = 1; j <= countM; j++) {
                await click(MSEL, j);
                sleep(SLEEP);

                const info = await page.evaluate(() => {
                    return {
                        val: document.getElementById('val').value,
                        cc: document.getElementById('cc').value
                    };
                });
                data.push(info);
            }
        }
    }

} else {
    res.writeHead(400, {
        'content-type': 'text/plain',
    });
    res.end('Something is wrong. Missing URL.');
    return;
}
}).listen(3000);

Sorry for my english.
Thank you

Body:
I could ask you a lot of questions before answering,

what is MSEL and SSEL?

What is the URL?

What is in the templates/index.html?

What kind of bad data you get?

Why you are looping inside a loop?

Why you have a sleep() promise but not awaiting that promise?

What happens when you push info to the data, do you return it as response?

etc etc. the list can go on, but we have to start somewhere, right? I will not write the whole code, and do everything for you. But I'll help you understand the problem.

Lots of part in your code is missing, as well as there are errors because you did not write things properly.

I'd separate the functions. I'm assuming you have the variables called MSEL, SSEL somewhere defined.

First, you are not returning anything in response. That's something you need to watch for, if you are not returning response, then the request is never going to end, and result in timeout.

http
  .createServer(async (req, res) => {
    if (req.url === "/") {
      if (req.method === "GET") {
        res.writeHead(200, {
          "content-type": "text/html; charset=utf-8",
          "cache-control": "public,max-age=31536000"
        });
        res.end(fs.readFileSync(__dirname + "/templates/index.html"));
        return;
      } else if (req.method === "POST") {
        let body = "";
        await req.on("data", data => (body += data));
        body = qs.parse(body);
        const returnData = await getData({ body, MSEL, SSEL }); // <-- seperate the function
        res.end(returnData); // <-- return the data
      }
    } else {
      res.writeHead(400, {
        "content-type": "text/plain"
      });
      res.end("Something is wrong. Missing URL.");
      return;
    }
  })
  .listen(3000);

And here is the function seperately, notice how I wrote await before sleep and also refactored some bits and parts a little bit, also returning the function after everything is done.

async function getData({ body, MSEL, SSEL }) {
  let url = body.url;

  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(url);

  let count = selector =>
    page.evaluate(selector => {
      return document.querySelectorAll(selector).length;
    }, selector);

  let sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

  const countM = await count(MSEL),
    countS = await count(SSEL);

  let click = (selector, number) =>
    page.click(`${selector}:nth-child(${number})`);

  let data = [];

  for (let i = 1; i <= countS; i++) {
    await click(SSEL, i);
    await sleep(SLEEP);

    for (let j = 1; j <= countM; j++) {
      await click(MSEL, j);
      await sleep(SLEEP);

      const info = await page.evaluate(() => {
        return {
          val: document.getElementById("val").value,
          cc: document.getElementById("cc").value
        };
      });
      data.push(info);
    }
  }
  return data;
}

What I did was refactor and fix your code a bit, but this is not the solution you are looking for, the code might not even work.

You need to understand how promises works. Refer to the following tutorials before copy-pasting my solution hoping that it'll work ;) ,

https://ponyfoo.com/articles/es6-promises-in-depth

https://ponyfoo.com/articles/understanding-javascript-async-await


问:
How to have a global variable in Jmeter for Inter thread communication?
I want to have a global variable for inter thread communication.

Current setup:

Thread Group 1: It is a multi-user thread, that will be accessing certain API's in a flow.

Thread group 2: Now, as per our current system, the auth-token refreshes after every 10 min. So in this thread group, I am calling refreshToken API.

Approach1: Tried using jmeter property. But since all threads are in parallel, so if one thread updates the token, all other threads fail.

Approach2: Using InterThreadCommunication plugin. Since I don't know when and where in the system, the token will expire, so don't know where to call in the inter thread communication pre-processor.

答:
Use thread-specific properties like:

In "Refresh Token" Thread Group specify individual properties to hold tokens for each virtual user like:

```<code>${__setProperty(token_${__threadNum},YOUR_TOKEN_VALUE_HERE,)}
</code>```

In "PA APIs" Thread Group access individual token values like:

```<code>${__P(token_${__threadNum},)}
</code>```

References:

__setProperty() function

__threadNum() function

Apache JMeter Functions - An Introduction

Body:
Use thread-specific properties like:

In "Refresh Token" Thread Group specify individual properties to hold tokens for each virtual user like:

${__setProperty(token_${__threadNum},YOUR_TOKEN_VALUE_HERE,)}

In "PA APIs" Thread Group access individual token values like:

${__P(token_${__threadNum},)}

References:

__setProperty() function

__threadNum() function

Apache JMeter Functions - An Introduction


问:
C: why does pointer address set to null in function, have a non-null address in main?
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

```<code>//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...
</code>```

答:
The thing is when you pass something to a function, a local copy of it is made. Now you are sending an address to the function. It is the content of t in CreateTree().

What is t in called function? t is a local variable to the CreateTree function. The type of t is org_tree* meaning it contains address of a org_tree variable.

You are allocating a piece of memory in CreateTree(). You are assigning the address of that chunk to the t variable. But that doesn't mean anything to the called function.

Local variable t's life ends once the called function's } is reached.

So back to main() it is still the old t variable that it was. Nothing(it's value) changed.

Now what are you trying to achieve here? Maybe you want to allocate a node dynamically.

Now let's look at an valid exmaple:-

```<code>    org_tree* t;

    CreateTree(&t);

    void CreateTree(org_tree **t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        (*t) = temp;
    }
</code>```

Now here can you tell what is there in t in called function now?
        It's still a pointer variable, having as content an address. Whose address?
        A pointer variable's address. More precisely org_tree* variable's address.

What does that mean? (*t) is basically the original t of callee- function. That means we can change it now. And that's what is being done.
        Here also if we do change value of t in callee function it is a change that will not stay in callee function. It is a local copy nothing more than that.

Is there a simple way to do this without **?
 There is.

```<code>    org_tree *t = CreateTree();

    org_tree * CreateTree(){
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        return temp;
    }
</code>```

Here how is this working? Isn't temp a local variable?
        Yes it is. And after the function ends temp is out of life. But the memory address that it points to is not like that. That value is returned. Dynamically allocated memory is still there when the function CreateTree ends. And that memory is not de-allocated when the function is done execution.

Memory leak

Now look at the example (the very first one you wrote).

```<code>    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }
</code>```

Here you have assigned that allocated chunk's memory address to the local variable t in CreateTree().
  CreateTree() ends and now is there anyway you can access that allocated memory?
  Nope.

That's why the previous function is said to be leaking memory. You call these 10000 times you will leak a large amount of memory.

Passing a pointer is nothing special. What makes them special is, we refer the address that it contains and the change is made to what is there in that address. And we start to think that it's pointer magic. It's a side effect that you exploit to persist change in value between functions.

Also here don't forget to check the return type of malloc and free the memory when you are done working with it.

Body:
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...

Body:
The thing is when you pass something to a function, a local copy of it is made. Now you are sending an address to the function. It is the content of t in CreateTree().

What is t in called function? t is a local variable to the CreateTree function. The type of t is org_tree* meaning it contains address of a org_tree variable.

You are allocating a piece of memory in CreateTree(). You are assigning the address of that chunk to the t variable. But that doesn't mean anything to the called function.

Local variable t's life ends once the called function's } is reached.

So back to main() it is still the old t variable that it was. Nothing(it's value) changed.

Now what are you trying to achieve here? Maybe you want to allocate a node dynamically.

Now let's look at an valid exmaple:-

    org_tree* t;

    CreateTree(&t);

    void CreateTree(org_tree **t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        (*t) = temp;
    }

Now here can you tell what is there in t in called function now?
        It's still a pointer variable, having as content an address. Whose address?
        A pointer variable's address. More precisely org_tree* variable's address.

What does that mean? (*t) is basically the original t of callee- function. That means we can change it now. And that's what is being done.
        Here also if we do change value of t in callee function it is a change that will not stay in callee function. It is a local copy nothing more than that.

Is there a simple way to do this without **?
 There is.

    org_tree *t = CreateTree();

    org_tree * CreateTree(){
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        return temp;
    }

Here how is this working? Isn't temp a local variable?
        Yes it is. And after the function ends temp is out of life. But the memory address that it points to is not like that. That value is returned. Dynamically allocated memory is still there when the function CreateTree ends. And that memory is not de-allocated when the function is done execution.

Memory leak

Now look at the example (the very first one you wrote).

    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

Here you have assigned that allocated chunk's memory address to the local variable t in CreateTree().
  CreateTree() ends and now is there anyway you can access that allocated memory?
  Nope.

That's why the previous function is said to be leaking memory. You call these 10000 times you will leak a large amount of memory.

Passing a pointer is nothing special. What makes them special is, we refer the address that it contains and the change is made to what is there in that address. And we start to think that it's pointer magic. It's a side effect that you exploit to persist change in value between functions.

Also here don't forget to check the return type of malloc and free the memory when you are done working with it.