问:
Need help to improve MYSQL SubQuery Performance
I just learning MYSQL, I have MySql subquery like this:

```<code>EXPLAIN EXTENDED SELECT brand_name, stars, hh_stock, hh_stock_value, sales_monthly_1, sales_monthly_2, sales_monthly_3, sold_monthly_1, sold_monthly_2,
  sold_monthly_3, price_uvp, price_ecp, price_default, price_margin AS margin, vc_percent as vc, cogs, products_length, products_id, material_expenses,
  MAX(price) AS products_price, SUM(total_sales) AS total_sales,
  IFNULL(MAX(active_age), DATEDIFF(NOW(), products_date_added)) AS products_age, DATEDIFF(NOW(), products_date_added) AS jng_products_age,
  AVG(sales_weekly) AS sales_weekly, AVG(sales_monthly) AS sales_monthly, SUM(total_sold) AS total_sold, SUM(total_returned) AS total_returned,
  ((SUM(total_returned)/SUM(total_sold)) * 100) AS returned_rate
FROM
  (
    SELECT p.products_id, jc.price, jc.price_end_customer AS price_ecp, jc.total_sales, jc.active_age, jc.sales_weekly,
      jc.sales_monthly, jc.total_sold, jc.total_returned, jc.price_uvp, p.price_margin, p.vc_percent, p.material_expenses,
      p.products_date_added, p.stars , pb.brand_name, p.family_id, p.products_price_default AS price_default, pl.sales_monthly_1,
      pl.sales_monthly_2, pl.sales_monthly_3, pl.sold_monthly_1, pl.sold_monthly_2, pl.sold_monthly_3, pst.stock AS hh_stock,
      (pst.stock * p.average_stock_value) AS hh_stock_value, pnc.products_length,
      IF(ploc.cogs IS NULL OR ploc.cogs=0,
         (CASE p.complexity
          WHEN 'F' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'E' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'N' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'M' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'I' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          WHEN 'H' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          ELSE ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2),2) END), ploc.cogs) AS cogs
    FROM products p
      LEFT  JOIN jng_sp_catalog jc ON  jc.products_id=p.products_id
      LEFT JOIN products_description pd ON pd.products_id = p.products_id AND pd.language_id = 2
      LEFT JOIN products_description2 pd2 ON pd2.products_id = p.products_id
      LEFT JOIN products_brand pb ON pb.products_brand_id = p.products_brand_id
      LEFT JOIN products_log pl ON pl.products_id = p.products_id
      LEFT JOIN products_log_static pls ON pls.products_id=p.products_id
      LEFT JOIN products_local ploc ON ploc.products_id = p.products_id
      LEFT JOIN products_non_configurator pnc ON pnc.products_id = p.products_id
      INNER JOIN
      (
        SELECT shp.products_id, CONCAT(',', GROUP_CONCAT(shp.styles_id), ',') AS styles_id
        FROM styles_has_products shp GROUP BY shp.products_id HAVING styles_id NOT LIKE '%,1967,%') subquery_styles ON subquery_styles.products_id = p.products_id
      LEFT JOIN products_stock_temp pst ON pst.products_id=p.products_id WHERE p.active_status='1'  AND p.categories_top_id  =  '1') dt  GROUP BY products_id ORDER BY  products_id;
</code>```

The result of explain is like this:

```<code>+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
| id | select_type | table      | partitions | type   | possible_keys       | key         | key_len | ref                                | rows   | filtered | Extra                                        |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
|  1 | PRIMARY     | p          | NULL       | ALL    | PRIMARY             | NULL        | NULL    | NULL                               |  40458 |     1.00 | Using where; Using temporary; Using filesort |
|  1 | PRIMARY     | pb         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_brand_id |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | ploc       | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pl         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pls        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pst        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pd2        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pnc        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pd         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 8       | manobo_central.p.products_id,const |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | jc         | NULL       | ref    | products_id         | products_id | 4       | manobo_central.p.products_id       |      4 |   100.00 | Using where                                  |
|  1 | PRIMARY     | <derived3> | NULL       | ref    | <auto_key0>         | <auto_key0> | 4       | manobo_central.p.products_id       |     10 |   100.00 | Using where                                  |
|  3 | DERIVED     | shp        | NULL       | index  | PRIMARY,products_id | PRIMARY     | 8       | NULL                               | 208226 |   100.00 | Using index; Using filesort                  |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
</code>```

I have options in mind.

I will drop subquery and use VIEWS to output the data just like using query. Because i have subquery in FROM, so i will use VIEWS from VIEWS. But some said it will affected in performances. How you guys think about this?

I will still using subquery, but will try and search how to optimize the query. For this one, i wanted to ask you guys, for the first result row in EXPLAIN TABLE, It shows table production p which the type 'all', how to avoid 'all' ? I've managed to use type 'eq_ref' for others table, but still have no clue why the product table is 'all'?

Again,
Do you think i need to switch to VIEW? Or just try to optimise again the subquery.

Many Thanks!

EDIT: table products index

```<code>create index family_id on products (family_id);
create index idx_products_date_added on products (products_date_added);
create index material_expenses on products (material_expenses);
create index products_brand_id on products (products_brand_id);
create index products_ean on products (products_ean);
create index products_status on products (products_status);
create index tb_status on products (tb_status);
</code>```

EDIT: table style_has_products

```<code>CREATE TABLE `styles_has_products` (
  `styles_id` int(10) unsigned NOT NULL DEFAULT '0',
  `products_id` int(10) unsigned NOT NULL DEFAULT '0',
  `date_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`styles_id`,`products_id`),
  KEY `products_id` (`products_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
</code>```

答:
The first thing I notice is your subquery_styles. You don't use its result other than to filter. Criteria, however, belongs in the WHERE clause in my opinion. As it seems you want to exclude products for which exists a style_id 1967, I'd use NOT EXISTS or NOT IN:

```<code>WHERE p.active_status = 1
AND p.categories_top_id = 1
AND p.products_id NOT IN
(
  SELECT products_id
  FROM styles_has_products
  WHERE styles_id = 1967
)
</code>```

The second thing is that there is no appropriate index for your query. You are selecting products with active_status 1 and categories_top_id 1, but there is no index on these columns. With the third condition on product_id not matching style_id 1967, I'd suggest one of the following indexes:

```<code>create index idx1 on products (active_status, categories_top_id, products_id);
create index idx2 on products (categories_top_id, active_status, products_id);
</code>```

Create both, see which is being used, and drop the other.

A last point that can and maybe should be optimized/changed is your aggregation. But in order to help here, I must know the table's unique keys. As soon as you post them, I'll extend this answer :-)

Body:
I just learning MYSQL, I have MySql subquery like this:

EXPLAIN EXTENDED SELECT brand_name, stars, hh_stock, hh_stock_value, sales_monthly_1, sales_monthly_2, sales_monthly_3, sold_monthly_1, sold_monthly_2,
  sold_monthly_3, price_uvp, price_ecp, price_default, price_margin AS margin, vc_percent as vc, cogs, products_length, products_id, material_expenses,
  MAX(price) AS products_price, SUM(total_sales) AS total_sales,
  IFNULL(MAX(active_age), DATEDIFF(NOW(), products_date_added)) AS products_age, DATEDIFF(NOW(), products_date_added) AS jng_products_age,
  AVG(sales_weekly) AS sales_weekly, AVG(sales_monthly) AS sales_monthly, SUM(total_sold) AS total_sold, SUM(total_returned) AS total_returned,
  ((SUM(total_returned)/SUM(total_sold)) * 100) AS returned_rate
FROM
  (
    SELECT p.products_id, jc.price, jc.price_end_customer AS price_ecp, jc.total_sales, jc.active_age, jc.sales_weekly,
      jc.sales_monthly, jc.total_sold, jc.total_returned, jc.price_uvp, p.price_margin, p.vc_percent, p.material_expenses,
      p.products_date_added, p.stars , pb.brand_name, p.family_id, p.products_price_default AS price_default, pl.sales_monthly_1,
      pl.sales_monthly_2, pl.sales_monthly_3, pl.sold_monthly_1, pl.sold_monthly_2, pl.sold_monthly_3, pst.stock AS hh_stock,
      (pst.stock * p.average_stock_value) AS hh_stock_value, pnc.products_length,
      IF(ploc.cogs IS NULL OR ploc.cogs=0,
         (CASE p.complexity
          WHEN 'F' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'E' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+1.7+0.25+2.2),2)
          WHEN 'N' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'M' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+2.4+0.25+2.2),2)
          WHEN 'I' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          WHEN 'H' THEN ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+3.5+0.25+2.2),2)
          ELSE ROUND(5*(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2)/100+(p.material_expenses+(7.5/100*p.material_expenses)+5+0.25+2.2),2) END), ploc.cogs) AS cogs
    FROM products p
      LEFT  JOIN jng_sp_catalog jc ON  jc.products_id=p.products_id
      LEFT JOIN products_description pd ON pd.products_id = p.products_id AND pd.language_id = 2
      LEFT JOIN products_description2 pd2 ON pd2.products_id = p.products_id
      LEFT JOIN products_brand pb ON pb.products_brand_id = p.products_brand_id
      LEFT JOIN products_log pl ON pl.products_id = p.products_id
      LEFT JOIN products_log_static pls ON pls.products_id=p.products_id
      LEFT JOIN products_local ploc ON ploc.products_id = p.products_id
      LEFT JOIN products_non_configurator pnc ON pnc.products_id = p.products_id
      INNER JOIN
      (
        SELECT shp.products_id, CONCAT(',', GROUP_CONCAT(shp.styles_id), ',') AS styles_id
        FROM styles_has_products shp GROUP BY shp.products_id HAVING styles_id NOT LIKE '%,1967,%') subquery_styles ON subquery_styles.products_id = p.products_id
      LEFT JOIN products_stock_temp pst ON pst.products_id=p.products_id WHERE p.active_status='1'  AND p.categories_top_id  =  '1') dt  GROUP BY products_id ORDER BY  products_id;

The result of explain is like this:

+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
| id | select_type | table      | partitions | type   | possible_keys       | key         | key_len | ref                                | rows   | filtered | Extra                                        |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+
|  1 | PRIMARY     | p          | NULL       | ALL    | PRIMARY             | NULL        | NULL    | NULL                               |  40458 |     1.00 | Using where; Using temporary; Using filesort |
|  1 | PRIMARY     | pb         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_brand_id |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | ploc       | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pl         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pls        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pst        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | NULL                                         |
|  1 | PRIMARY     | pd2        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | pnc        | NULL       | eq_ref | PRIMARY             | PRIMARY     | 4       | manobo_central.p.products_id       |      1 |   100.00 | Using where                                  |
|  1 | PRIMARY     | pd         | NULL       | eq_ref | PRIMARY             | PRIMARY     | 8       | manobo_central.p.products_id,const |      1 |   100.00 | Using index                                  |
|  1 | PRIMARY     | jc         | NULL       | ref    | products_id         | products_id | 4       | manobo_central.p.products_id       |      4 |   100.00 | Using where                                  |
|  1 | PRIMARY     | <derived3> | NULL       | ref    | <auto_key0>         | <auto_key0> | 4       | manobo_central.p.products_id       |     10 |   100.00 | Using where                                  |
|  3 | DERIVED     | shp        | NULL       | index  | PRIMARY,products_id | PRIMARY     | 8       | NULL                               | 208226 |   100.00 | Using index; Using filesort                  |
+----+-------------+------------+------------+--------+---------------------+-------------+---------+------------------------------------+--------+----------+----------------------------------------------+

I have options in mind.

I will drop subquery and use VIEWS to output the data just like using query. Because i have subquery in FROM, so i will use VIEWS from VIEWS. But some said it will affected in performances. How you guys think about this?

I will still using subquery, but will try and search how to optimize the query. For this one, i wanted to ask you guys, for the first result row in EXPLAIN TABLE, It shows table production p which the type 'all', how to avoid 'all' ? I've managed to use type 'eq_ref' for others table, but still have no clue why the product table is 'all'?

Again,
Do you think i need to switch to VIEW? Or just try to optimise again the subquery.

Many Thanks!

EDIT: table products index

create index family_id on products (family_id);
create index idx_products_date_added on products (products_date_added);
create index material_expenses on products (material_expenses);
create index products_brand_id on products (products_brand_id);
create index products_ean on products (products_ean);
create index products_status on products (products_status);
create index tb_status on products (tb_status);

EDIT: table style_has_products

CREATE TABLE `styles_has_products` (
  `styles_id` int(10) unsigned NOT NULL DEFAULT '0',
  `products_id` int(10) unsigned NOT NULL DEFAULT '0',
  `date_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`styles_id`,`products_id`),
  KEY `products_id` (`products_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Body:
The first thing I notice is your subquery_styles. You don't use its result other than to filter. Criteria, however, belongs in the WHERE clause in my opinion. As it seems you want to exclude products for which exists a style_id 1967, I'd use NOT EXISTS or NOT IN:

WHERE p.active_status = 1
AND p.categories_top_id = 1
AND p.products_id NOT IN
(
  SELECT products_id
  FROM styles_has_products
  WHERE styles_id = 1967
)

The second thing is that there is no appropriate index for your query. You are selecting products with active_status 1 and categories_top_id 1, but there is no index on these columns. With the third condition on product_id not matching style_id 1967, I'd suggest one of the following indexes:

create index idx1 on products (active_status, categories_top_id, products_id);
create index idx2 on products (categories_top_id, active_status, products_id);

Create both, see which is being used, and drop the other.

A last point that can and maybe should be optimized/changed is your aggregation. But in order to help here, I must know the table's unique keys. As soon as you post them, I'll extend this answer :-)


来源: stackexchange

问:
How to populate documents with unlimited nested levels using mongoose
I'm designing a web application that manages organizational structure for parent and child companies. There are two types of companies: 1- Main company, 2 -Subsidiary company.The company can belong only to one company but can have a few child companies. My mongoose Schema looks like this:

```<code>var companySchema = new mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },
    estimatedAnnualEarnings: {
        type: Number,
        required: true
    },
    companyChildren: [{type: mongoose.Schema.Types.ObjectId, ref: 'Company'}],
    companyType: {type: String, enum: ['Main', 'Subsidiary']}
})

module.exports = mongoose.model('Company', companySchema);
</code>```

I store all my companies in one collection and each company has an array with references to its child companies. Then I want to display all companies as a tree(on client side). I want query all Main companies that populates their children and children populate their children and so on,with unlimited nesting level. How can I do that? Or maybe you know better approach. Also I need ability to view,add,edit,delete any company.

Now I have this:

```<code>router.get('/companies', function(req, res) {
    Company.find({companyType: 'Main'}).populate({path: 'companyChildren'}).exec(function(err, list) {
        if(err) {
            console.log(err);
        } else {
            res.send(list);
        }
    })
});
</code>```

But it populates only one nested level.
I appreciate any help

答:
I think a simpler approach would be to track the parent since that is unique instead of tracking an array of children which could get messy. There is a nifty module called mongoose-tree built just for this:

```<code>var tree = require('mongoose-tree');

var CompanySchema = new mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },
    estimatedAnnualEarnings: {
        type: Number,
        required: true
    },
    companyType: {type: String, enum: ['Main', 'Subsidiary']}
})

CompanySchema.plugin(tree);
module.exports = mongoose.model('Company', CompanySchema);
</code>```

Set some test data:

```<code>var comp1 = new CompanySchema({name:'Company 1'});
var comp2 = new CompanySchema({name:'Company 2'});
var comp3 = new CompanySchema({name:'Company 3'});

comp3.parent = comp2;
comp2.parent = comp1;

comp1.save(function() {
   comp2.save(function() {
      comp3.save();
   });
});
</code>```

Then use mongoose-tree to build a function that can get either the ancestors or children:

```<code>router.get('/company/:name/:action', function(req, res) {
    var name = req.params.name;
    var action = req.params.action;
    Company.find({name: name}, function(err, comp){
       //typical error handling omitted for brevity
       if (action == 'ancestors'){
          comp.getAncestors(function(err, companies) {
             // companies is an array
             res.send(companies);
          });
       }else if (action == 'children'){
          comp.getChildren(function(err, companies) {
             res.send(companies);
          });
       }
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm designing a web application that manages organizational structure for parent and child companies. There are two types of companies: 1- Main company, 2 -Subsidiary company.The company can belong only to one company but can have a few child companies. My mongoose Schema looks like this:

var companySchema = new mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },
    estimatedAnnualEarnings: {
        type: Number,
        required: true
    },
    companyChildren: [{type: mongoose.Schema.Types.ObjectId, ref: 'Company'}],
    companyType: {type: String, enum: ['Main', 'Subsidiary']}
})

module.exports = mongoose.model('Company', companySchema);

I store all my companies in one collection and each company has an array with references to its child companies. Then I want to display all companies as a tree(on client side). I want query all Main companies that populates their children and children populate their children and so on,with unlimited nesting level. How can I do that? Or maybe you know better approach. Also I need ability to view,add,edit,delete any company.

Now I have this:

router.get('/companies', function(req, res) {
    Company.find({companyType: 'Main'}).populate({path: 'companyChildren'}).exec(function(err, list) {
        if(err) {
            console.log(err);
        } else {
            res.send(list);
        }
    })
});

But it populates only one nested level.
I appreciate any help

Body:
I think a simpler approach would be to track the parent since that is unique instead of tracking an array of children which could get messy. There is a nifty module called mongoose-tree built just for this:

var tree = require('mongoose-tree');

var CompanySchema = new mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },
    estimatedAnnualEarnings: {
        type: Number,
        required: true
    },
    companyType: {type: String, enum: ['Main', 'Subsidiary']}
})

CompanySchema.plugin(tree);
module.exports = mongoose.model('Company', CompanySchema);

Set some test data:

var comp1 = new CompanySchema({name:'Company 1'});
var comp2 = new CompanySchema({name:'Company 2'});
var comp3 = new CompanySchema({name:'Company 3'});

comp3.parent = comp2;
comp2.parent = comp1;

comp1.save(function() {
   comp2.save(function() {
      comp3.save();
   });
});

Then use mongoose-tree to build a function that can get either the ancestors or children:

router.get('/company/:name/:action', function(req, res) {
    var name = req.params.name;
    var action = req.params.action;
    Company.find({name: name}, function(err, comp){
       //typical error handling omitted for brevity
       if (action == 'ancestors'){
          comp.getAncestors(function(err, companies) {
             // companies is an array
             res.send(companies);
          });
       }else if (action == 'children'){
          comp.getChildren(function(err, companies) {
             res.send(companies);
          });
       }
    });
});


问:
SoapUI Connection closed
I got a few SOAP tests and unfortunately our test environment is very slow, that's why the default 15000ms are not enough I think.

Every once in a while, I get a Connection closed and it takes ages for the test to continue. I do have seen requests that took up to 7 seconds, guess 15 might be possible too then.

I changed the Socket Timeout of my test case to 25000 in the settings, but it didn't change anything, the console still says Connection can be kept alive for 15000.

```<code>10:20:43,347 DEBUG
[SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection]
Sending request: POST /WebService/tcs HTTP/1.1
10:20:43,367 DEBUG
[SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection]
Receiving response: HTTP/1.1 200 OK
10:20:43,368 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be
kept alive for 15000 MILLISECONDS
10:21:01,461 DEBUG
[SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection]
Connection closed
</code>```

After 1-3 minutes the test continues, so any hint where I can change those 15000?

答: Try Preferences -> HTTP Settings for Socket Timeout</p>

Title: SoapUI Connection closed

Body:
I got a few SOAP tests and unfortunately our test environment is very slow, that's why the default 15000ms are not enough I think.

Every once in a while, I get a Connection closed and it takes ages for the test to continue. I do have seen requests that took up to 7 seconds, guess 15 might be possible too then.

I changed the Socket Timeout of my test case to 25000 in the settings, but it didn't change anything, the console still says Connection can be kept alive for 15000.

10:20:43,347 DEBUG
[SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection]
Sending request: POST /WebService/tcs HTTP/1.1
10:20:43,367 DEBUG
[SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection]
Receiving response: HTTP/1.1 200 OK
10:20:43,368 DEBUG [HttpClientSupport$SoapUIHttpClient] Connection can be
kept alive for 15000 MILLISECONDS
10:21:01,461 DEBUG
[SoapUIMultiThreadedHttpConnectionManager$SoapUIDefaultClientConnection]
Connection closed

After 1-3 minutes the test continues, so any hint where I can change those 15000?


问:
Selenium 3 - Add Port for Node when run Selenium Grid
At the moment, I am configuring Hub and Nodes for a Selenium 3 Grid setup.

Hub :
Start Selenium Hub
java -jar selenium-server-standalone-3.0.1.jar -role hub;

Node :
Start Selenium node
java -Dwebdriver.ie.driver=c:\ws\IEDriverServer.exe -jar selenium-server-standalone-3.4.0.jar -role node -hub http://10.0.12.110:4444/grid/register

Question: I want to have the Node connecting to my Hub through a predefined port (-port 5555). How should I configure the port property for the Node?

!!! Note: with Selenium 2, I successfully configured the node with port 5555: java -jar selenium-server-standalone-2.53.0.jar -role webdriver -hub http://10.0.12.110:4444/grid/register -port 5555 -browser  "browserName=chrome,version=ANY,platform=WINDOWS" -Dwebdriver.chrome.driver=c:\WS\chromedriver.exe -browser

However, property -port 5555 doesn't seem to work/have effect in Selenium 3.

How can I make it work?

答:
You can create node-config.json file and store port parameter there. Format of config file:

```<code>{
    "capabilities": [
        {
            "browserName": "chrome",
        }
    ],
    "port": 5555,
}
</code>```

Then start your node with

```<code>java -jar /path_to_driver/serve.jar -role node -hub HUB_ADDRESS -nodeConfig /path_to_node_config/node-config.json
</code>```

More config options you can find HERE
Detailed about configuration in Selenium 3

Body:
You can create node-config.json file and store port parameter there. Format of config file:

{
    "capabilities": [
        {
            "browserName": "chrome",
        }
    ],
    "port": 5555,
}

Then start your node with

java -jar /path_to_driver/serve.jar -role node -hub HUB_ADDRESS -nodeConfig /path_to_node_config/node-config.json

More config options you can find HERE
Detailed about configuration in Selenium 3


问:
Move up cache bar from down to header
I'm trying to move up the cache bar at the webpage: http://www.skandicinkasso.de/ -  cant move the element because it is at the bottom of the "DOM"

I have been trying remove that positioning, and put the element inline where i wanted it, but i cant do that way.

i want to move the bar to here: http://prntscr.com/fsqb5d

答:
Change your ginger_container.bottom css to

```<code>.ginger_container.bottom {
    position: fixed;
    left: 0;
    right: 0;
    top: 125px;
    overflow: hidden;
    padding: 10px;
    width: 1100px;
    margin: 0 auto;
}
</code>```

remove bottom: 0 and add top: 125px; width: 1100px; margin: 0 auto;

Title: Move up cache bar from down to header

Body:
Change your ginger_container.bottom css to

.ginger_container.bottom {
    position: fixed;
    left: 0;
    right: 0;
    top: 125px;
    overflow: hidden;
    padding: 10px;
    width: 1100px;
    margin: 0 auto;
}

remove bottom: 0 and add top: 125px; width: 1100px; margin: 0 auto;


问:
How to disable all attribute menu items in a ul/li List when one of them is clicked?
I can click on the Photos1, Photos2, Photos3, and Photos4 menus very quickly, and the "$.get(..." is sent to the server 4 times. I need to disable all these menus after any one is clicked. Environment: NodeJS, Express, Pug, Jquery Thanks, Pat</p>

```<code>--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos1') Photos1
li: a.navigation(href='#', data-level='/images/cs/Photos2') Photos2
li: a.navigation(href='#', data-level='/images/cs/Photos3') Photos3
li: a.navigation(href='#', data-level='/images/cs/Photos4') Photos4
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {

            $(this).css({   // Disable this menu item
                "pointer-events": "none",
                "cursor": "default"
            });
// ??????? I NEED TO DISABLE ALL Menus in this List ???????
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });
</code>```

答:
Since you need to respond to a click event fired by more than one element, you better use event delegation.
I suggest you give your enclosing ul tag a descriptive class name "navigation-menu" so your selector won't target all the ul tags.

$(function(){ // jQuery DOM ready
    var navigationMenu = $("ul.navigation-menu");
    navigationMenu.on("click", "a", disableLinks);
    function disableLinks(e) {
       navigationMenu.find('a.navigation').css({
        "pointer-events": "none",
        "cursor": "default",
        "color": "#aaa"
      });
      e.stopPropagation();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul class="navigation-menu">
   <li>link1</li>
   <li>link2</li>
   <li>link3</li>
</ul></code>```

Body:
I can click on the Photos1, Photos2, Photos3, and Photos4 menus very quickly, and the "$.get(..." is sent to the server 4 times. I need to disable all these menus after any one is clicked. Environment: NodeJS, Express, Pug, Jquery Thanks, Pat

--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos1') Photos1
li: a.navigation(href='#', data-level='/images/cs/Photos2') Photos2
li: a.navigation(href='#', data-level='/images/cs/Photos3') Photos3
li: a.navigation(href='#', data-level='/images/cs/Photos4') Photos4
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {

            $(this).css({   // Disable this menu item
                "pointer-events": "none",
                "cursor": "default"
            });
// ??????? I NEED TO DISABLE ALL Menus in this List ???????
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });

Body:
Since you need to respond to a click event fired by more than one element, you better use event delegation.
I suggest you give your enclosing ul tag a descriptive class name "navigation-menu" so your selector won't target all the ul tags.

$(function(){ // jQuery DOM ready
    var navigationMenu = $("ul.navigation-menu");
    navigationMenu.on("click", "a", disableLinks);
    function disableLinks(e) {
       navigationMenu.find('a.navigation').css({
        "pointer-events": "none",
        "cursor": "default",
        "color": "#aaa"
      });
      e.stopPropagation();
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul class="navigation-menu">
   <li><a class="navigation" href="#link1" >link1</a></li>
   <li><a class="navigation" href="#link2" >link2</a></li>
   <li><a class="navigation" href="#link3" >link3</a></li>
</ul>


问:
JQuery Autocomplete Problem
I am using JQuery UI Autocomplete in my JSP. Whenever user keys character, i made the request to server and get the data as JSON and load with the pulgin.

It's working fine. But Whenever i typed the same character as previous term. It's not populating any values.

For eg., First i typed p, it lists the p starting elements. I have the button to reset the text content of autocompleter. After reset, if i am typing same character p, it doesn't show anything.

my code as follows,

```<code>var cache = {};

   $("#Name").autocomplete({
             source: function(req, add){
      if (req.term in cache) {
                 add(cache[req.term]);
                 return;
             }
     $.getJSON("/store/StockManagement?action=getMedicinesStock",req, function(data) {
                  var medicines = [];
                  $.each(data, function(i, val){
                   medicines.push(val.name + "," + val.code);
             });

             cache[req.term] = medicines;
             add(medicines);
         });
     },select: function(e, ui) {
         var medicine = ui.item.value;
         $('#Code').val(medicine.split(",")[1]);
         setTimeout(function(){
             var med = $('#Name').val();
             $('#Name').val(med.split(",")[0]);
         },500);
         }
     });
</code>```

答:
```<code>// Taken from jquery-ui-1.8.4.custom.min.js
if (a.term != a.element.val()) { // *** THE MATCH IS HERE
    //console.log("a.term != a.element.val(): "+a.term+", "+a.element.val());
    a.selectedItem = null;
    a.search(null, c) // *** SEARCH IS TRIGGERED HERE
}
</code>```

<p>I just commented the condition. now it's works fine. </p>

Title: JQuery Autocomplete Problem

Body:
I am using JQuery UI Autocomplete in my JSP. Whenever user keys character, i made the request to server and get the data as JSON and load with the pulgin.

It's working fine. But Whenever i typed the same character as previous term. It's not populating any values.

For eg., First i typed p, it lists the p starting elements. I have the button to reset the text content of autocompleter. After reset, if i am typing same character p, it doesn't show anything.

my code as follows,

var cache = {};

   $("#Name").autocomplete({
             source: function(req, add){
      if (req.term in cache) {
                 add(cache[req.term]);
                 return;
             }
     $.getJSON("/store/StockManagement?action=getMedicinesStock",req, function(data) {
                  var medicines = [];
                  $.each(data, function(i, val){
                   medicines.push(val.name + "," + val.code);
             });

             cache[req.term] = medicines;
             add(medicines);
         });
     },select: function(e, ui) {
         var medicine = ui.item.value;
         $('#Code').val(medicine.split(",")[1]);
         setTimeout(function(){
             var med = $('#Name').val();
             $('#Name').val(med.split(",")[0]);
         },500);
         }
     });

Body:
// Taken from jquery-ui-1.8.4.custom.min.js
if (a.term != a.element.val()) { // *** THE MATCH IS HERE
    //console.log("a.term != a.element.val(): "+a.term+", "+a.element.val());
    a.selectedItem = null;
    a.search(null, c) // *** SEARCH IS TRIGGERED HERE
}

I just commented the condition. now it's works fine.


问:
How do you kill a Thread in Java?
How do you kill a java.lang.Thread in Java?

答:
I didn't get the interrupt to work in Android, so I used this method, works perfectly:</p>

```<code>boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    Thread t = new Thread(new CheckUpdates());
    t.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            //Thread sleep 3 seconds
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }
</code>```

OwnerDisplayName: andy

ContentLicense: CC BY-SA 4.0

Title: How do you kill a Thread in Java?

Body:
I didn't get the interrupt to work in Android, so I used this method, works perfectly:

boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    Thread t = new Thread(new CheckUpdates());
    t.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            //Thread sleep 3 seconds
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }


问:
No application is associated with the specified file for this operation. error
I have tried to open a .jpg file in default program in this way:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Test {
public static void main(String[] args) throws IOException {
    File image = new File(System.getProperty("user.home") +
"/Desktop/project/XL-116/DATAFILE17.jpg");
    try {
        java.awt.Desktop.getDesktop().open(image);
    } catch (FileNotFoundException ex) {
        // .....
    }
}
}
</code>```

And I have got this error:

```<code>Exception in thread "main" java.io.IOException: Failed to open C:\Users\khuda
Dad\Desktop\project\XL-116\DATAFILE17.jpg. Error message: No application is
associated with the specified file for this operation.

at sun.awt.windows.WDesktopPeer.ShellExecute(Unknown Source)
at sun.awt.windows.WDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
at Test.main(Test.java:9)
</code>```

And I have checked the default program. There's nothing wrong. So what is the problem?

答:
Apparently, the fact that the file has an associated application to run, doesn't mean that the "open" operation can be applied.

No application is associated with the specified file for this operation.

(Emphasis mine)

The action "open" is not applicable. What happens if you right-click on DATAFILE17.jpg? It for me it appears as Edit. That could be the actual action which is issued.

Of course, it can depend from computer to computer, but my guess is that the action is "edit". Try this:

```<code>Desktop.getDesktop().edit(image);
</code>```

The method isSupported(Desktop.Action action) returns whether the action is supported.

Body:
I have tried to open a .jpg file in default program in this way:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Test {
public static void main(String[] args) throws IOException {
    File image = new File(System.getProperty("user.home") +
"/Desktop/project/XL-116/DATAFILE17.jpg");
    try {
        java.awt.Desktop.getDesktop().open(image);
    } catch (FileNotFoundException ex) {
        // .....
    }
}
}

And I have got this error:

Exception in thread "main" java.io.IOException: Failed to open C:\Users\khuda
Dad\Desktop\project\XL-116\DATAFILE17.jpg. Error message: No application is
associated with the specified file for this operation.

at sun.awt.windows.WDesktopPeer.ShellExecute(Unknown Source)
at sun.awt.windows.WDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
at Test.main(Test.java:9)

And I have checked the default program. There's nothing wrong. So what is the problem?

Body:
Apparently, the fact that the file has an associated application to run, doesn't mean that the "open" operation can be applied.

No application is associated with the specified file for this operation.

(Emphasis mine)

The action "open" is not applicable. What happens if you right-click on DATAFILE17.jpg? It for me it appears as Edit. That could be the actual action which is issued.

Of course, it can depend from computer to computer, but my guess is that the action is "edit". Try this:

Desktop.getDesktop().edit(image);

The method isSupported(Desktop.Action action) returns whether the action is supported.


问:
RxJS Observable: Emit when specific part of the object changes
I have a complex object having child objects and arrays and so on.

I can easily create a Subject/BehaviourSubject or Observable from this object so that I can "next" (emit) the new state to the subscribers.

[ex: let appEnv$ = new Rx.BehaviorSubject<IWebSocketAppEnv>(appEnv);]

However I don't want all my subscribers to be notified every time the object changes. For instance for one of my subscriber, I only want to be notified when a change occurs on an elements of an array of that object.

Actually what I want is something redux is already doing. In redux, I can subscribe to the store but selecting only a child element.

I want to implement the same infrastructure for my back-end websocket server application.

How can I achieve that with RxJS?

答:
Use distinctUntilChanged operator. (docs)

Let's assume that the object's structure is:

```<code>{
  articleId: 0,
  comments: [ 'lorem', 'ipsum' ]
}
</code>```

We want to be as cool as firebase guys so we'll update comments in real-time when the updated object has a different array.

I'm using RxJS5 for observables and lodash to compare arrays because operator's default behavior won't compare them in the way we want them to be compared.

```<code>// Our BehaviorSubject which emits new object.
// For those who don't know: it'll emit the latest emitted value when subscribing to it.
const object$ = new Rx.BehaviorSubject({
  articleId: 0,
  comments: [],
});

// If you want specific parts of your application
// to react only when a specific part of the object has changed, you
// have to create another observable using 'map' and
// 'distinctUntilChanged' operator and subscribe to it.
const comments$ = object$
  .map(object => object.comments) // we want to emit comments only
  .distinctUntilChanged((a, b) => _.isEqual(a, b)); // emit only when currently emitted value is different than previous one.

comments$.subscribe(v => console.log(v)); // log fresh comments

object$.next({
  articleId: 1,
  comments: [],
});

object$.next({
  articleId: 1,
  comments: ['lorem', 'ipsum'],
});

object$.next({
  articleId: 2,
  comments: ['lorem', 'ipsum'],
});

object$.next({
  articleId: 2,
  comments: ['lorem', 'ipsum', 'dolor', 'sit', 'amet'],
});
</code>```

effect:

```<code>[]
["lorem", "ipsum"]
["lorem", "ipsum", "dolor", "sit", "amet"]
</code>```

effect without distinctUntilChanged operator:

```<code>[]
[]
["lorem", "ipsum"]
["lorem", "ipsum"]
["lorem", "ipsum", "dolor", "sit", "amet"]
</code>```

JSFiddle

Body:
Use distinctUntilChanged operator. (docs)

Let's assume that the object's structure is:

{
  articleId: 0,
  comments: [ 'lorem', 'ipsum' ]
}

We want to be as cool as firebase guys so we'll update comments in real-time when the updated object has a different array.

I'm using RxJS5 for observables and lodash to compare arrays because operator's default behavior won't compare them in the way we want them to be compared.

// Our BehaviorSubject which emits new object.
// For those who don't know: it'll emit the latest emitted value when subscribing to it.
const object$ = new Rx.BehaviorSubject({
  articleId: 0,
  comments: [],
});

// If you want specific parts of your application
// to react only when a specific part of the object has changed, you
// have to create another observable using 'map' and
// 'distinctUntilChanged' operator and subscribe to it.
const comments$ = object$
  .map(object => object.comments) // we want to emit comments only
  .distinctUntilChanged((a, b) => _.isEqual(a, b)); // emit only when currently emitted value is different than previous one.

comments$.subscribe(v => console.log(v)); // log fresh comments

object$.next({
  articleId: 1,
  comments: [],
});

object$.next({
  articleId: 1,
  comments: ['lorem', 'ipsum'],
});

object$.next({
  articleId: 2,
  comments: ['lorem', 'ipsum'],
});

object$.next({
  articleId: 2,
  comments: ['lorem', 'ipsum', 'dolor', 'sit', 'amet'],
});

effect:

[]
["lorem", "ipsum"]
["lorem", "ipsum", "dolor", "sit", "amet"]

effect without distinctUntilChanged operator:

[]
[]
["lorem", "ipsum"]
["lorem", "ipsum"]
["lorem", "ipsum", "dolor", "sit", "amet"]

JSFiddle


问:
Get specific Product for each category of a brand in WordPress Custom Post Types
I have a custom post type called products with its taxonomy called category

```<code>register_post_type( 'products',
        array(
            'labels' => array(
                'name' => __( 'Products' ),
                'singular_name' => __( 'Product' ),
                'add_new_item' => __( 'Add New Product' ),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'Products'),
            'taxonomies'  => array( 'category' )
        )
    );
</code>```

I have another which is brands

```<code>register_post_type( 'brands',
    // CPT Options
        array(
            'labels' => array(
                'name' => __( 'Brands' ),
                'singular_name' => __( 'BRAND' ),
                'add_new_item' => __( 'Add New Brand' ),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'BRANDS'),
            'taxonomies'  => array( 'category' ),
        )
    );
</code>```

I have a page called page-brands.php where i have used the below code to get all the brands.

```<code>$args = array(
    'post_type' => 'brands',
    'posts_per_page' => -1,
    'order' => 'ASC'
);
$brands = new WP_Query( $args );
</code>```

Then i am displaying brand title and logo..

```<code><a class="hvr-grow" href="<?php the_permalink(); ?>">
   <img src="<?php the_field('brand_logo'); ?>">
   <div class="brands_title"><?php the_title(); ?></div>
</a>
</code>```

It works perfectly, After clicking on the brand title which is a link. It goes to single-brands.php page. For Example, We have clicked on Brand title which is 'LG'. It will go to single-brands page and it will display all the products of its first category.

I'm getting its first category and saving it in first_brand_category by another function then using in below query to display.

```<code>$proucts_args = array(
    'posts_per_page' => 50,
    'post_type' => 'products',
    'cat' => $first_brand_category,
);
$products_query = new WP_Query($proucts_args);
</code>```

Everything works until there perfectly. But now i want to change above query because i want to display one specific product for each category. For example..

Brand is LG
Categories for LG Brands are TV , Mobiles , Air Conditioners etc
There are multiple products for TV category & multiple products for mobiles etc.

I want to display one specific product of TV for LG, One specific product of Mobiles for LG and one specific product of Air Conditioners for LG with the hyper link of that category.

How can i do this? any suggestion, I am new to wordpress

答:
It depends upon your need.

If you know what specific product you need to display:
One way is to pass the product id in the parameters, Wp_query will return only that product. Please refer: https://developer.wordpress.org/reference/classes/wp_query/. OR you can also sort the product and select only one product by giving 1 to post_count paramerter.

Body:
I have a custom post type called products with its taxonomy called category

register_post_type( 'products',
        array(
            'labels' => array(
                'name' => __( 'Products' ),
                'singular_name' => __( 'Product' ),
                'add_new_item' => __( 'Add New Product' ),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'Products'),
            'taxonomies'  => array( 'category' )
        )
    );

I have another which is brands

register_post_type( 'brands',
    // CPT Options
        array(
            'labels' => array(
                'name' => __( 'Brands' ),
                'singular_name' => __( 'BRAND' ),
                'add_new_item' => __( 'Add New Brand' ),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'BRANDS'),
            'taxonomies'  => array( 'category' ),
        )
    );

I have a page called page-brands.php where i have used the below code to get all the brands.

$args = array(
    'post_type' => 'brands',
    'posts_per_page' => -1,
    'order' => 'ASC'
);
$brands = new WP_Query( $args );

Then i am displaying brand title and logo..

<a class="hvr-grow" href="<?php the_permalink(); ?>">
   <img src="<?php the_field('brand_logo'); ?>">

<?php the_title(); ?>

It works perfectly, After clicking on the brand title which is a link. It goes to single-brands.php page. For Example, We have clicked on Brand title which is 'LG'. It will go to single-brands page and it will display all the products of its first category.

I'm getting its first category and saving it in first_brand_category by another function then using in below query to display.

$proucts_args = array(
    'posts_per_page' => 50,
    'post_type' => 'products',
    'cat' => $first_brand_category,
);
$products_query = new WP_Query($proucts_args);

Everything works until there perfectly. But now i want to change above query because i want to display one specific product for each category. For example..

Brand is LG
Categories for LG Brands are TV , Mobiles , Air Conditioners etc
There are multiple products for TV category & multiple products for mobiles etc.

I want to display one specific product of TV for LG, One specific product of Mobiles for LG and one specific product of Air Conditioners for LG with the hyper link of that category.

How can i do this? any suggestion, I am new to wordpress


问:
Cannot find declaration of the element company
my xml document company.xml,my xsd document companyxsd.xsd I don't know where I was getting wrong.Exception:cvc-elt:1.a:Cannot find declaration of element'company'.

```<code> <?xml version="1.0" encoding="UTF-8"?>
 <companies xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="companyxsd.xsd">
 <company>
 <companyname>capgemini</companyname>
 <address>chalapathischool</address>
 <department>
 <dname>cse</dname>
 <deptphoneno>995674314</deptphoneno>
 <deptfaxno>08776455508</deptfaxno>
 <deptemail>gvn@gmail.com</deptemail>
  <employee>
 <empid>1</empid>
 <ename>tarun</ename>
<emailid>tar@gmail.com</emailid>
<phoneno>1234567890</phoneno>
</employee>
<contractemployee>
<name>gvn</name>
 <phoneno>9989956882</phoneno>
 </contractemployee>
 </department>
 </company>
 </companies>

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="companies">
<xs:complexType>
<xs:sequence>
<xs:element name="company" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="department" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"/>
<xs:element name="deptphoneno" type="xs:integer"/>
<xs:element name="deptfaxno" type="xs:long"/>
<xs:element name="deptemail" type="xs:string"/>
<xs:element name="employee" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:integer"/>
<xs:element name="ename" type="xs:string"/>
<xs:element name="emailid" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="contractemployee" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
 </xs:element>
 </xs:schema>
</code>```

I am confident that all my code was not wrong still i am getting error.If anyone who knows the answer please let me know.

答:
Listed below is a code for correct answer</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="companyxsd.xsd">
<companyname>capgemini</companyname>
<address>chalapathischool</address>
<department>
<dname>cse</dname>
<deptphoneno>995674314</deptphoneno>
<deptfaxno>08776</deptfaxno>
<deptemail>gvn@gmail.com</deptemail>
<employee>
<empid>1</empid>
<ename>tarun</ename>
<emailid>tar@gmail.com</emailid>
<phoneno>1234567890</phoneno>
</employee>
<contractemployee>
<name>gvn</name>
<phoneno>9989956882</phoneno>
</contractemployee>
</department>
</company>

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="department" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"/>
<xs:element name="deptphoneno" type="xs:integer"/>
<xs:element name="deptfaxno" type="xs:long"/>
<xs:element name="deptemail" type="xs:string"/>
<xs:element name="employee" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:integer"/>
<xs:element name="ename" type="xs:string"/>
<xs:element name="emailid" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="contractemployee" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</code>```

Body:
my xml document company.xml,my xsd document companyxsd.xsd I don't know where I was getting wrong.Exception:cvc-elt:1.a:Cannot find declaration of element'company'.

 <?xml version="1.0" encoding="UTF-8"?>
 <companies xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="companyxsd.xsd">
 <company>
 <companyname>capgemini</companyname>
 <address>chalapathischool</address>
 <department>
 <dname>cse</dname>
 <deptphoneno>995674314</deptphoneno>
 <deptfaxno>08776455508</deptfaxno>
 <deptemail>gvn@gmail.com</deptemail>
  <employee>
 <empid>1</empid>
 <ename>tarun</ename>
<emailid>tar@gmail.com</emailid>
<phoneno>1234567890</phoneno>
</employee>
<contractemployee>
<name>gvn</name>
 <phoneno>9989956882</phoneno>
 </contractemployee>
 </department>
 </company>
 </companies>

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="companies">
<xs:complexType>
<xs:sequence>
<xs:element name="company" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="department" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"/>
<xs:element name="deptphoneno" type="xs:integer"/>
<xs:element name="deptfaxno" type="xs:long"/>
<xs:element name="deptemail" type="xs:string"/>
<xs:element name="employee" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:integer"/>
<xs:element name="ename" type="xs:string"/>
<xs:element name="emailid" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="contractemployee" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
 </xs:element>
 </xs:schema>

I am confident that all my code was not wrong still i am getting error.If anyone who knows the answer please let me know.

Body:
Listed below is a code for correct answer

<?xml version="1.0" encoding="UTF-8"?>
<company xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="companyxsd.xsd">
<companyname>capgemini</companyname>
<address>chalapathischool</address>
<department>
<dname>cse</dname>
<deptphoneno>995674314</deptphoneno>
<deptfaxno>08776</deptfaxno>
<deptemail>gvn@gmail.com</deptemail>
<employee>
<empid>1</empid>
<ename>tarun</ename>
<emailid>tar@gmail.com</emailid>
<phoneno>1234567890</phoneno>
</employee>
<contractemployee>
<name>gvn</name>
<phoneno>9989956882</phoneno>
</contractemployee>
</department>
</company>

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="companyname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="department" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="dname" type="xs:string"/>
<xs:element name="deptphoneno" type="xs:integer"/>
<xs:element name="deptfaxno" type="xs:long"/>
<xs:element name="deptemail" type="xs:string"/>
<xs:element name="employee" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="empid" type="xs:integer"/>
<xs:element name="ename" type="xs:string"/>
<xs:element name="emailid" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="contractemployee" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="phoneno" type="xs:long"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>


问:
iteration over 3 large lists to compare and assign value python
I have a piece of code where I need to go through many lists to read and assign values

The code does the following:
First, for each element in the entities (1st list 1300), the code will read its text file that contains many lines (2nd list 5000) each line contains two values. After that, the code will check if the first value in each line exists in the features list (3rdlist 17000), if yes it will write the second value in the line into the matrix.
The code is working but it is inefficient and extremely slow.(more than 12 hours)

```<code> #first list
for i in range(len(entities_list)-1):
    fin = open('/home/rana/'+entities_list[i]+'.txt','r')
            #Second List
            for line in fin.readlines():
                 #Third List
                for j in range(len(features_list)-1):
                if features_list[j]==line.split()[0]:
                    co_occurrence_matrix[i,j]=float(line.split()[1])
</code>```

I will appreciate if someone gives me an Idea how to solve this issue

答:
You can completely optimize away the third loop by creating a map upfront:

```<code># first create a matrix map for fast features lookup
features_map = {feature: index for index, feature in enumerate(features_list)}
for index, entity in enumerate(entities_list):
    with open('/home/rana/{}.txt'.format(entity), 'r') as f:
        for line in f:
            feature, value = line.split()  # you might want to validate this, tho
            if feature in features_map:
                co_occurrence_matrix[index, features_map[feature]] = float(value)
</code>```

You might be able to speed it up further by delegating your I/O part (loading of the files) over multiple threads if the files are particularly big.

Body:
I have a piece of code where I need to go through many lists to read and assign values

The code does the following:
First, for each element in the entities (1st list 1300), the code will read its text file that contains many lines (2nd list 5000) each line contains two values. After that, the code will check if the first value in each line exists in the features list (3rdlist 17000), if yes it will write the second value in the line into the matrix.
The code is working but it is inefficient and extremely slow.(more than 12 hours)

 #first list
for i in range(len(entities_list)-1):
    fin = open('/home/rana/'+entities_list[i]+'.txt','r')
            #Second List
            for line in fin.readlines():
                 #Third List
                for j in range(len(features_list)-1):
                if features_list[j]==line.split()[0]:
                    co_occurrence_matrix[i,j]=float(line.split()[1])

I will appreciate if someone gives me an Idea how to solve this issue

Body:
You can completely optimize away the third loop by creating a map upfront:

# first create a matrix map for fast features lookup
features_map = {feature: index for index, feature in enumerate(features_list)}
for index, entity in enumerate(entities_list):
    with open('/home/rana/{}.txt'.format(entity), 'r') as f:
        for line in f:
            feature, value = line.split()  # you might want to validate this, tho
            if feature in features_map:
                co_occurrence_matrix[index, features_map[feature]] = float(value)

You might be able to speed it up further by delegating your I/O part (loading of the files) over multiple threads if the files are particularly big.


问:
Loading .NET 4.5.2 assembly in .NET 4 application, reflection & reference
It is allowed to load the .NET 4.5.2 assembly (using reflection) in the application whose exe is compiled using .NET 4 framework. However if I reference the same assembly in that application during development (added as any other assembly reference), build fails.

Why is it the case that thing which is not allowed during development is allowed at runtime using reflection?

答:
Loading an assembly, or doing anything really, via Reflection is a "here there be dragons" scenario where you're assuming the risk, and reacting to, anything that goes wrong (such as an assembly that targets a later version of the framework than is available).

I only see Compiler warnings when referencing a project that targets a higher framework version:

The referenced project 'ProjectForNetFramework45' is targeting a higher framework version (4.6.1) than this project’s current target framework version (4.0). This may lead to build failures if types from assemblies outside this project’s target framework are used by any project in the dependency chain.

Rather than a build failure, until I actually attempt to call a method in the v4.5 assembly at which point the following pops up:

error CS0400: The type or namespace name 'ProjectForNetFramework45' could not be found in the global namespace (are you missing an assembly reference?)

The 4.5 version of the .net Framework is an "in-place update" rather than a new version, see the notes in this Microsoft blog post about Compatibility of .NET Framework 4.5:

.NET Framework 4.5 is an in-place update that replaces .NET Framework 4 (rather than a side-by-side installation). Our goal is for .NET 4.5 to be fully backward compatible with applications built for .NET 4 (.NET 3.5 and .NET 4.5 will be side-by-side). We’ll talk about the compatibility story for .NET 3.5 in a later post. One of the first things you’ll notice about .NET 4.5 is the version number (4.0.30319) is the same as .NET 4; this is the practice used by other in-place updates.

This means that, rather than being a different version of the runtime (i.e. the JIT, Garabage Collector, etc,.. although these do change!), a newer framework will likely add new classes, interfaces and methods to existing classes giving a wider API to work against. This is one of the things that "netstandard" is an attempt to add clarity to.


问:
When can we NOT specify type parameter
Given the following test case, there are 3 scenarios in it. I would ask what's the rules here that govern when we must and when we don't have to specify the type parameter

```<code>  @Test
  def testTypeParamter(): Unit = {

    class Cat[A]

    //1. Don't need to specify the type parameter for Cat
    def getCat() = new Cat
    println(getCat())

    import scala.collection.mutable.ArrayBuffer

    //2. Don't need to specify the type parameter for ArrayBuffer

    val bf = new ArrayBuffer()
    println(bf)

    //3. Do need to specify the type parameter for ArrayBuffer to make bf2 += 1 work
    val bf2 = new ArrayBuffer[Int]()
    bf2 += 1

    println(getCat())
  }
</code>```

Compared with #2 and #3, what can we do if we create an empty ArrayBuffer without type parameter

答:
Let's check in REPL,

1.1 scenario without a type param

```<code>scala> class Bag[A]
defined class Bag

scala> def createBag = new Bag
createBag: Bag[Nothing]
</code>```

1.2 ArrayBuffer[T] without type param

```<code>scala>  val buffer = new ArrayBuffer()
buffer: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()
</code>```

In both case you see the default type parameter as scala.Nothing. scala.Nothing is abstract and can not be instantiated which means you can't operate on your generics instance like
buffer+=new String("apple") etc because Nothing is at the bottom of scala class hierarchy.

2. providing type parameter

This is obviously the purpose of having generic type that you want Generics for certain type.

```<code>scala> var buffer = new ArrayBuffer[Long]()
buffer: scala.collection.mutable.ArrayBuffer[Long] = ArrayBuffer()

scala> buffer+=89l
res0: scala.collection.mutable.ArrayBuffer[Long] = ArrayBuffer(89)
</code>```

Title: When can we NOT specify type parameter

Body:
Given the following test case, there are 3 scenarios in it. I would ask what's the rules here that govern when we must and when we don't have to specify the type parameter

  @Test
  def testTypeParamter(): Unit = {

    class Cat[A]

    //1. Don't need to specify the type parameter for Cat
    def getCat() = new Cat
    println(getCat())

    import scala.collection.mutable.ArrayBuffer

    //2. Don't need to specify the type parameter for ArrayBuffer

    val bf = new ArrayBuffer()
    println(bf)

    //3. Do need to specify the type parameter for ArrayBuffer to make bf2 += 1 work
    val bf2 = new ArrayBuffer[Int]()
    bf2 += 1

    println(getCat())
  }

Compared with #2 and #3, what can we do if we create an empty ArrayBuffer without type parameter

Body:
Let's check in REPL,

1.1 scenario without a type param

scala> class Bag[A]
defined class Bag

scala> def createBag = new Bag
createBag: Bag[Nothing]

1.2 ArrayBuffer[T] without type param

scala>  val buffer = new ArrayBuffer()
buffer: scala.collection.mutable.ArrayBuffer[Nothing] = ArrayBuffer()

In both case you see the default type parameter as scala.Nothing. scala.Nothing is abstract and can not be instantiated which means you can't operate on your generics instance like
buffer+=new String("apple") etc because Nothing is at the bottom of scala class hierarchy.

2. providing type parameter

This is obviously the purpose of having generic type that you want Generics for certain type.

scala> var buffer = new ArrayBuffer[Long]()
buffer: scala.collection.mutable.ArrayBuffer[Long] = ArrayBuffer()

scala> buffer+=89l
res0: scala.collection.mutable.ArrayBuffer[Long] = ArrayBuffer(89)


问:
Passing a user defined number between component through service angular 2
example.service.ts

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class ExampleService {

    number1 : number;
    number2 : number;
    result : number;
    constructor() { }

}
</code>```

component1.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'

@Component({
    selector: 'app-component1',
    templateUrl: './component1.component.html',
    styleUrls: ['./component1.component.css'],
    providers: [ExampleService]
})
export class Component1Component implements OnInit {

    number1v = null;
    number2v = null;
    resultv = null;

    constructor(public aService : ExampleService ) {
        this.aService.number1 = this.number1v;
        this.aService.number2 = this.number2v;
        this.aService.result = this.resultv;
    }
    ngOnInit() {
    }
    processForm(){
    this.resultv = this.number1v + this.number2v;
    }
}
</code>```

component2.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'

@Component({
    selector: 'app-component2',
    templateUrl: './component2.component.html',
    styleUrls: ['./component2.component.css'],
    providers: [ExampleService]
})
export class Component2Component implements OnInit {
    resultv;
    constructor(public aService : ExampleService) {
        this.aService.result = this.resultv;
    }

    ngOnInit() {
    }
    getResult(){
        alert(this.resultv)
    }
}
</code>```

Want to pass a value of result from component1 to component2.

No parent to child or child to parent component.

the result i get is undefined.

答:
The problem, is when component A updates the service, component B is not aware of the changes. So, to solve this we need to use Observer pattern and let all observers be informed of the change.

Luckily Angular comes with rxjs, so we can use BehaviorSubject to implement the observer pattern.

Service Code

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class ExampleService {

    number1 = new BehaviorSubject<number>(0);
    number2 = new BehaviorSubject<number>(0);
    result = new BehaviorSubject<number>(0);
    constructor() { }

}
</code>```

Inside component you can read their values

```<code>service.number1.subscribe(num => {
   // ....
});
</code>```

To change any number you can just update it this way

```<code>service.number1.next(1); // set new number
</code>```

Ofcourse this is crude way, you can get better examples reading online tutorials or answers on BehaaviorSubject

Body:
example.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class ExampleService {

    number1 : number;
    number2 : number;
    result : number;
    constructor() { }

}

component1.component.ts

import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'

@Component({
    selector: 'app-component1',
    templateUrl: './component1.component.html',
    styleUrls: ['./component1.component.css'],
    providers: [ExampleService]
})
export class Component1Component implements OnInit {

    number1v = null;
    number2v = null;
    resultv = null;

    constructor(public aService : ExampleService ) {
        this.aService.number1 = this.number1v;
        this.aService.number2 = this.number2v;
        this.aService.result = this.resultv;
    }
    ngOnInit() {
    }
    processForm(){
    this.resultv = this.number1v + this.number2v;
    }
}

component2.component.ts

import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'

@Component({
    selector: 'app-component2',
    templateUrl: './component2.component.html',
    styleUrls: ['./component2.component.css'],
    providers: [ExampleService]
})
export class Component2Component implements OnInit {
    resultv;
    constructor(public aService : ExampleService) {
        this.aService.result = this.resultv;
    }

    ngOnInit() {
    }
    getResult(){
        alert(this.resultv)
    }
}

Want to pass a value of result from component1 to component2.

No parent to child or child to parent component.

the result i get is undefined.

Body:
The problem, is when component A updates the service, component B is not aware of the changes. So, to solve this we need to use Observer pattern and let all observers be informed of the change.

Luckily Angular comes with rxjs, so we can use BehaviorSubject to implement the observer pattern.

Service Code

import { Injectable } from '@angular/core';

@Injectable()
export class ExampleService {

    number1 = new BehaviorSubject<number>(0);
    number2 = new BehaviorSubject<number>(0);
    result = new BehaviorSubject<number>(0);
    constructor() { }

}

Inside component you can read their values

service.number1.subscribe(num => {
   // ....
});

To change any number you can just update it this way

service.number1.next(1); // set new number

Ofcourse this is crude way, you can get better examples reading online tutorials or answers on BehaaviorSubject


问:
How to change the background color of a JSpinner dependent on the current edited content of the field?
I have a GUI with a JSpinner using a SpinnerNumberModel using double values.

As soon as I change the content of the Editor of the JSpinner, I want the background to change to yellow (to show that the currently displayed value is not the one "saved" in the JSpinner respectively its Model.

If that content is not valid (e.g. out of the allowed range specified by my SpinnerNumberModel or a text as "abc") the background should change to red.

I tried to achieve what I want with a FocusListener already but yet have not been successful, also I am not sure if It could work anyway, as I need to check the content somewhere between focussing and defocussing.

I checked Tutorials for all Listeners that exist for Swing components, but could not find a right one that suits the job. (here I informed myself)

I am new to the concept of Listeners and would really appreciate any help that gets me closer to solving the problem but also helps generally understanding Listeners and how to use them in this context better!

My really basic code example with the mentioned poor attempt using a focus listener:

```<code>public class test implements FocusListener{

JFrame frame;

SpinnerNumberModel model;
JSpinner spinner;
JComponent comp;
JFormattedTextField field;

public test() {
    JFrame frame = new JFrame("frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

    model = new SpinnerNumberModel(0., 0., 100., 0.1);
    spinner = new JSpinner(model);
    comp = spinner.getEditor();
    field = (JFormattedTextField) comp.getComponent(0);
    field.addFocusListener(this);

    frame.getContentPane().add(spinner);
    frame.getContentPane().add(new JButton("defocus spinner")); //to have something to defocus when testing :)
    frame.pack();
    frame.setVisible(true);
}

@Override
public void focusGained(FocusEvent e) {
    // TODO Auto-generated method stub
    //when the values of the field and the spinner don't match, the field should get yellow
    if(!field.getValue().equals(spinner.getModel().getValue())) {
        field.setBackground(Color.YELLOW);
    }
}

@Override
public void focusLost(FocusEvent e) {
    // TODO Auto-generated method stub
    //if they match again, reset to white
            if(!field.getValue().equals(spinner.getModel().getValue())) {
                field.setBackground(Color.RED);
            }
}
}
</code>```

答:
I was able to fulfill the task with a combination of a KeyListener, a DocumentListener and a FocusListener. The solution might not be the easiest, but finally I coded sth. that works. Comments in the file appended should explain how I dealt with the problem.

I expanded the original task with a CommaReplacingNumericDocumentFilter expands DocumentFilter class that was not written by me, I got the code from my professor and edited it to my needs only. Now only digits, minus and e, E are accepted as entries in the JSpinner.
Commas are replaced with dots also.

Code:

```<code>import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class test implements DocumentListener, ChangeListener, KeyListener{
    boolean keyPressed;
    JFrame frame;
    SpinnerNumberModel model;
    JSpinner spinner;
    JComponent comp;
    JFormattedTextField field;

public test() {
    JFrame frame = new JFrame("frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

    model = new SpinnerNumberModel(0., 0., 100000., .1);
    spinner = new JSpinner(model);

    //disable grouping for spinner
    JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner);
    editor.getFormat().setGroupingUsed(false);
    spinner.setEditor(editor);

    comp = spinner.getEditor();
    field = (JFormattedTextField) comp.getComponent(0);
    field.getDocument().addDocumentListener(this);
    field.addKeyListener(this);
    spinner.addChangeListener(this);

    frame.getContentPane().add(spinner);
    frame.pack();
    frame.setVisible(true);
}

@Override
public void insertUpdate(DocumentEvent e) {
    DocumentEventHandler(e);
}

@Override
public void removeUpdate(DocumentEvent e) {
    DocumentEventHandler(e);
}

@Override
public void changedUpdate(DocumentEvent e) {
    DocumentEventHandler(e);
}

public static boolean isNumeric(String str)
{
  try
  {
    double d = Double.parseDouble(str);
  }
  catch(NumberFormatException nfe)
  {
    return false;
  }
  return true;
}

public static void main(String[] args) {
    //to get the right format for double precision numbers
    Locale.setDefault(Locale.US);
    test test = new test();
}

@Override
public void stateChanged(ChangeEvent e) {
    System.out.println("valuechanged: " + spinner.getValue().toString());
    if(keyPressed) {
        field.setBackground(Color.WHITE);
    }
    keyPressed = false;
}

public void DocumentEventHandler(DocumentEvent e) {
    //as soon as update is inserted, set background to yellow
    if (keyPressed) {
        field.setBackground(Color.YELLOW);

        //check if input is numeric and in bounds
        String text = field.getText();
        if (isNumeric(text)) {
            double value = Double.parseDouble(text);
            if (value < (Double)model.getMinimum() || value > (Double)model.getMaximum()) {
                field.setBackground(Color.RED);
            }
        }
        else { //set background to red
            field.setBackground(Color.RED);
        }
    }

    keyPressed = false;

    //System.out.println(e.toString());
    //System.out.println("Text: " + field.getText());
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

 /** If not done yet, replaces the DocumentFilter with one replacing commas by decimal points.
    *  This can't be done at the very beginning because the DocumentFilter would be changed to a
    *  javax.swing.text.DefaultFormatter$DefaultDocumentFilter when setting up the JSpinner GUI. */
   public void keyPressed(KeyEvent e) {
       PlainDocument document = (PlainDocument)(field.getDocument());
       if(!(document.getDocumentFilter() instanceof CommaReplacingNumericDocumentFilter))
           document.setDocumentFilter(new CommaReplacingNumericDocumentFilter());
       /*Tell the other handlers that a key has been pressed and the change in the document does
        * not come from using the JSpinner buttons or the MouseWheel.
        */
       keyPressed = true;
   }

}

/** A javax.swing.text.DocumentFilter that replaces commas to decimal points
 *  and ignores non-numeric characters except 'e' and 'E'. This is called before
 *  modi */
class CommaReplacingNumericDocumentFilter extends DocumentFilter {
    @Override
    public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
            throws BadLocationException {
    text = filter(text);
    if (text.length() > 0)
        super.insertString(fb, offset, text, attr);
}

@Override
public void replace(FilterBypass fb, int offset, int length, String text,
    AttributeSet attrs) throws BadLocationException {
    text = filter(text);
    if (text.length() > 0)
        super.replace(fb, offset, length, text, attrs);
}

String filter(String text) {
    return text.replace(',', '.').replaceAll("[^0-9eE.-]","");
}
}
</code>```

Body:
I have a GUI with a JSpinner using a SpinnerNumberModel using double values.

As soon as I change the content of the Editor of the JSpinner, I want the background to change to yellow (to show that the currently displayed value is not the one "saved" in the JSpinner respectively its Model.

If that content is not valid (e.g. out of the allowed range specified by my SpinnerNumberModel or a text as "abc") the background should change to red.

I tried to achieve what I want with a FocusListener already but yet have not been successful, also I am not sure if It could work anyway, as I need to check the content somewhere between focussing and defocussing.

I checked Tutorials for all Listeners that exist for Swing components, but could not find a right one that suits the job. (here I informed myself)

I am new to the concept of Listeners and would really appreciate any help that gets me closer to solving the problem but also helps generally understanding Listeners and how to use them in this context better!

My really basic code example with the mentioned poor attempt using a focus listener:

public class test implements FocusListener{

JFrame frame;

SpinnerNumberModel model;
JSpinner spinner;
JComponent comp;
JFormattedTextField field;

public test() {
    JFrame frame = new JFrame("frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

    model = new SpinnerNumberModel(0., 0., 100., 0.1);
    spinner = new JSpinner(model);
    comp = spinner.getEditor();
    field = (JFormattedTextField) comp.getComponent(0);
    field.addFocusListener(this);

    frame.getContentPane().add(spinner);
    frame.getContentPane().add(new JButton("defocus spinner")); //to have something to defocus when testing :)
    frame.pack();
    frame.setVisible(true);
}

@Override
public void focusGained(FocusEvent e) {
    // TODO Auto-generated method stub
    //when the values of the field and the spinner don't match, the field should get yellow
    if(!field.getValue().equals(spinner.getModel().getValue())) {
        field.setBackground(Color.YELLOW);
    }
}

@Override
public void focusLost(FocusEvent e) {
    // TODO Auto-generated method stub
    //if they match again, reset to white
            if(!field.getValue().equals(spinner.getModel().getValue())) {
                field.setBackground(Color.RED);
            }
}
}

Body:
I was able to fulfill the task with a combination of a KeyListener, a DocumentListener and a FocusListener. The solution might not be the easiest, but finally I coded sth. that works. Comments in the file appended should explain how I dealt with the problem.

I expanded the original task with a CommaReplacingNumericDocumentFilter expands DocumentFilter class that was not written by me, I got the code from my professor and edited it to my needs only. Now only digits, minus and e, E are accepted as entries in the JSpinner.
Commas are replaced with dots also.

Code:

import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class test implements DocumentListener, ChangeListener, KeyListener{
    boolean keyPressed;
    JFrame frame;
    SpinnerNumberModel model;
    JSpinner spinner;
    JComponent comp;
    JFormattedTextField field;

public test() {
    JFrame frame = new JFrame("frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

    model = new SpinnerNumberModel(0., 0., 100000., .1);
    spinner = new JSpinner(model);

    //disable grouping for spinner
    JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner);
    editor.getFormat().setGroupingUsed(false);
    spinner.setEditor(editor);

    comp = spinner.getEditor();
    field = (JFormattedTextField) comp.getComponent(0);
    field.getDocument().addDocumentListener(this);
    field.addKeyListener(this);
    spinner.addChangeListener(this);

    frame.getContentPane().add(spinner);
    frame.pack();
    frame.setVisible(true);
}

@Override
public void insertUpdate(DocumentEvent e) {
    DocumentEventHandler(e);
}

@Override
public void removeUpdate(DocumentEvent e) {
    DocumentEventHandler(e);
}

@Override
public void changedUpdate(DocumentEvent e) {
    DocumentEventHandler(e);
}

public static boolean isNumeric(String str)
{
  try
  {
    double d = Double.parseDouble(str);
  }
  catch(NumberFormatException nfe)
  {
    return false;
  }
  return true;
}

public static void main(String[] args) {
    //to get the right format for double precision numbers
    Locale.setDefault(Locale.US);
    test test = new test();
}

@Override
public void stateChanged(ChangeEvent e) {
    System.out.println("valuechanged: " + spinner.getValue().toString());
    if(keyPressed) {
        field.setBackground(Color.WHITE);
    }
    keyPressed = false;
}

public void DocumentEventHandler(DocumentEvent e) {
    //as soon as update is inserted, set background to yellow
    if (keyPressed) {
        field.setBackground(Color.YELLOW);

        //check if input is numeric and in bounds
        String text = field.getText();
        if (isNumeric(text)) {
            double value = Double.parseDouble(text);
            if (value < (Double)model.getMinimum() || value > (Double)model.getMaximum()) {
                field.setBackground(Color.RED);
            }
        }
        else { //set background to red
            field.setBackground(Color.RED);
        }
    }

    keyPressed = false;

    //System.out.println(e.toString());
    //System.out.println("Text: " + field.getText());
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

 /** If not done yet, replaces the DocumentFilter with one replacing commas by decimal points.
    *  This can't be done at the very beginning because the DocumentFilter would be changed to a
    *  javax.swing.text.DefaultFormatter$DefaultDocumentFilter when setting up the JSpinner GUI. */
   public void keyPressed(KeyEvent e) {
       PlainDocument document = (PlainDocument)(field.getDocument());
       if(!(document.getDocumentFilter() instanceof CommaReplacingNumericDocumentFilter))
           document.setDocumentFilter(new CommaReplacingNumericDocumentFilter());
       /*Tell the other handlers that a key has been pressed and the change in the document does
        * not come from using the JSpinner buttons or the MouseWheel.
        */
       keyPressed = true;
   }

}

/** A javax.swing.text.DocumentFilter that replaces commas to decimal points
 *  and ignores non-numeric characters except 'e' and 'E'. This is called before
 *  modi */
class CommaReplacingNumericDocumentFilter extends DocumentFilter {
    @Override
    public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr)
            throws BadLocationException {
    text = filter(text);
    if (text.length() > 0)
        super.insertString(fb, offset, text, attr);
}

@Override
public void replace(FilterBypass fb, int offset, int length, String text,
    AttributeSet attrs) throws BadLocationException {
    text = filter(text);
    if (text.length() > 0)
        super.replace(fb, offset, length, text, attrs);
}

String filter(String text) {
    return text.replace(',', '.').replaceAll("[^0-9eE.-]","");
}
}


问:
No numbered pagination custom post type
I have a problem showing numbered pagination on only one of my Wordpress pages.

```<code><?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
$query = new WP_Query($args);
?>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="product-overview">

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>
                            <div class="col-md-3">
                                <div class="featured-block">
                                    <div class="featured-block-image">
                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>"></a>
                                    </div>
                                    <div class="featured-block-info">
                                        <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                                        <?php if (get_field('prijs_oud')) : ?>
                                            <span class="oud"><?php the_field('prijs_oud'); ?></span>
                                        <?php endif; ?>
                                        <span class="nieuw"><?php the_field('prijs_nieuw'); ?></span> p/m<sub>2</sub>
                                    </div>
                                </div>
                            </div>

                        <?php endwhile; ?>
                    <?php endif; ?>
                    <?php the_posts_pagination(array(
                        'prev_text' => '«',
                        'next_text' => '»',
                    )); ?>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

The query returns about 70 products, so I would expect it to show at least 7 numbers. However, it does not show any pagination.

答:
If you give your full code it will be more easier to find out your problem.

May be you use wp_reset_postdata(); before the_posts_pagination();

Please check this.

Title: No numbered pagination custom post type

Body:
I have a problem showing numbered pagination on only one of my Wordpress pages.

<?php
/**
 * Template Name: Sale template
 */
?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
    'post_type' => array(
        'houten_vloeren', 'keramische_tegels', 'natuursteen_vloeren', 'tegels', 'laminaat', 'pvc_vloeren', 'tafels_stoelen',

    ),
    'posts_per_page' => 5,
    'post_status' => 'publish',
    'paged' => $paged,
    'meta_query' => array(
        'key' => 'prijsknaller',
        'value' => '1',
        'compare' => '==',
        //'type'    => 'date',
    ),
);
$query = new WP_Query($args);
?>

                    <?php if ($query->have_posts()) :
                        while ($query->have_posts()) : $query->the_post(); ?>

                                        <a href="<?php the_permalink(); ?>"><img src="<?php the_field('productafbeelding'); ?>"
                                                                                alt="<?php the_title(); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                                        <?php if (get_field('prijs_oud')) : ?>
                                            <?php the_field('prijs_oud'); ?>
                                        <?php endif; ?>
                                        <?php the_field('prijs_nieuw'); ?> p/m2

                        <?php endwhile; ?>
                    <?php endif; ?>
                    <?php the_posts_pagination(array(
                        'prev_text' => '«',
                        'next_text' => '»',
                    )); ?>

The query returns about 70 products, so I would expect it to show at least 7 numbers. However, it does not show any pagination.