问:
How to do nesting manufacturers like site.com/brands/BrandName/productName in OpenCart?
I need to do nesting links like site.com/brands/brandName/productName. Now it's like site.com/brandName/productName.

I've tried .htaccess and add '/brands' in seo_url.php and it's doesn't work. In seo url option of a brand, I've added 'brands/bmw' and received 404.
Should I rewrite a controller or seo_url.php differently?

OpenCart v3.0.2.0

```<code><?php
class ControllerStartupSeoUrl extends Controller {
    public function index() {
        // Add rewrite to url class
        if ($this->config->get('config_seo_url')) {
            $this->url->addRewrite($this);
        }

        // Decode URL
        if (isset($this->request->get['_route_'])) {
            $parts = explode('/', $this->request->get['_route_']);

            // remove any empty arrays from trailing
            if (utf8_strlen(end($parts)) == 0) {
                array_pop($parts);
            }

            foreach ($parts as $part) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE keyword = '" . $this->db->escape($part) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "'");

                if ($query->num_rows) {
                    $url = explode('=', $query->row['query']);

                    if ($url[0] == 'product_id') {
                        $this->request->get['product_id'] = $url[1];
                    }

                    if ($url[0] == 'category_id') {
                        if (!isset($this->request->get['path'])) {
                            $this->request->get['path'] = $url[1];
                        } else {
                            $this->request->get['path'] .= '_' . $url[1];
                        }
                    }

                    if ($url[0] == 'manufacturer_id') {
                        $this->request->get['manufacturer_id'] = $url[1];
                    }

                    if ($url[0] == 'information_id') {
                        $this->request->get['information_id'] = $url[1];
                    }

                    if ($query->row['query'] && $url[0] != 'information_id' && $url[0] != 'manufacturer_id' && $url[0] != 'category_id' && $url[0] != 'product_id') {
                        $this->request->get['route'] = $query->row['query'];
                    }
                } else {
                    $this->request->get['route'] = 'error/not_found';

                    break;
                }
            }

            if (!isset($this->request->get['route'])) {
                if (isset($this->request->get['product_id'])) {
                    $this->request->get['route'] = 'product/product';
                } elseif (isset($this->request->get['path'])) {
                    $this->request->get['route'] = 'product/category';
                } elseif (isset($this->request->get['manufacturer_id'])) {
                    $this->request->get['route'] = 'product/manufacturer/info';
                } elseif (isset($this->request->get['information_id'])) {
                    $this->request->get['route'] = 'information/information';
                }
        }
    }
    }

    public function rewrite($link) {
        $url_info = parse_url(str_replace('&', '&', $link));

        $url = '';

        $data = array();

        parse_str($url_info['query'], $data);

        foreach ($data as $key => $value) {
            if (isset($data['route'])) {
                if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                    if ($query->num_rows && $query->row['keyword']) {
                        $url .= '/' . $query->row['keyword'];

                        unset($data[$key]);
                    }
                } elseif ($key == 'path') {
                    $categories = explode('_', $value);

                    foreach ($categories as $category) {
                        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = 'category_id=" . (int)$category . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                        if ($query->num_rows && $query->row['keyword']) {
                            $url .= '/' . $query->row['keyword'];
                        } else {
                            $url = '';

                            break;
                        }
                    }

                    unset($data[$key]);

                }
            }
        }

        if ($url) {
            unset($data['route']);

            $query = '';

            if ($data) {
                foreach ($data as $key => $value) {
                    $query .= '&' . rawurlencode((string)$key) . '=' . rawurlencode((is_array($value) ? http_build_query($value) : (string)$value));
                }

                if ($query) {
                    $query = '?' . str_replace('&', '&', trim($query, '&'));
                }
            }

            return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;
        } else {
            return $link;
        }
    }
}

</code>```

答:
In your code try this:

<?php
class ControllerStartupSeoUrl extends Controller {
    public function index() {
        // Add rewrite to url class
        if ($this->config->get('config_seo_url')) {
            $this->url->addRewrite($this);
        }

        // Decode URL
        if (isset($this->request->get['_route_'])) {
            $parts = explode('/', $this->request->get['_route_']);

            // remove any empty arrays from trailing
            if (utf8_strlen(end($parts)) == 0) {
                array_pop($parts);
            }

            foreach ($parts as $part) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE keyword = '" . $this->db->escape($part) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "'");

                if ($query->num_rows) {
                    $url = explode('=', $query->row['query']);

                    if ($url[0] == 'product_id') {
                        $this->request->get['product_id'] = $url[1];
                    }

                    if ($url[0] == 'category_id') {
                        if (!isset($this->request->get['path'])) {
                            $this->request->get['path'] = $url[1];
                        } else {
                            $this->request->get['path'] .= '_' . $url[1];
                        }
                    }

                    if ($url[0] == 'manufacturer_id') {
                        $this->request->get['manufacturer_id'] = $url[1];
                    }

                    if ($url[0] == 'information_id') {
                        $this->request->get['information_id'] = $url[1];
                    }

                    if ($query->row['query'] && $url[0] != 'information_id' && $url[0] != 'manufacturer_id' && $url[0] != 'category_id' && $url[0] != 'product_id') {
                        $this->request->get['route'] = $query->row['query'];
                    }
                } elseif ($part == 'brand') {
                    // don't send the user to 'not found page'
                } else {
                    $this->request->get['route'] = 'error/not_found';

                    break;
                }
            }

            if (!isset($this->request->get['route'])) {
                if (isset($this->request->get['product_id'])) {
                    $this->request->get['route'] = 'product/product';
                } elseif (isset($this->request->get['path'])) {
                    $this->request->get['route'] = 'product/category';
                } elseif (isset($this->request->get['manufacturer_id'])) {
                    $this->request->get['route'] = 'product/manufacturer/info';
                } elseif (isset($this->request->get['information_id'])) {
                    $this->request->get['route'] = 'information/information';
                }
        }
    }
    }

    public function rewrite($link) {
        $url_info = parse_url(str_replace('&', '&', $link));

        $url = '';

        $data = array();

        parse_str($url_info['query'], $data);

        foreach ($data as $key => $value) {
            if (isset($data['route'])) {
                if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                    if ($query->num_rows && $query->row['keyword']) {
                        //add brands to the url
                        if ($key == 'manufacturer_id') {
                            $url .= '/brand';
                        }
                        $url .= '/' . $query->row['keyword'];

                        unset($data[$key]);
                    }
                } elseif ($key == 'path') {
                    $categories = explode('_', $value);

                    foreach ($categories as $category) {
                        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = 'category_id=" . (int)$category . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                        if ($query->num_rows && $query->row['keyword']) {
                            $url .= '/' . $query->row['keyword'];
                        } else {
                            $url = '';

                            break;
                        }
                    }

                    unset($data[$key]);

                }
            }
        }

        if ($url) {
            unset($data['route']);

            $query = '';

            if ($data) {
                foreach ($data as $key => $value) {
                    $query .= '&' . rawurlencode((string)$key) . '=' . rawurlencode((is_array($value) ? http_build_query($value) : (string)$value));
                }

                if ($query) {
                    $query = '?' . str_replace('&', '&', trim($query, '&'));
                }
            }

            return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;
        } else {
            return $link;
        }
    }
}
```

Body:
I need to do nesting links like site.com/brands/brandName/productName. Now it's like site.com/brandName/productName.

I've tried .htaccess and add '/brands' in seo_url.php and it's doesn't work. In seo url option of a brand, I've added 'brands/bmw' and received 404.
Should I rewrite a controller or seo_url.php differently?

OpenCart v3.0.2.0

<?php
class ControllerStartupSeoUrl extends Controller {
    public function index() {
        // Add rewrite to url class
        if ($this->config->get('config_seo_url')) {
            $this->url->addRewrite($this);
        }

        // Decode URL
        if (isset($this->request->get['_route_'])) {
            $parts = explode('/', $this->request->get['_route_']);

            // remove any empty arrays from trailing
            if (utf8_strlen(end($parts)) == 0) {
                array_pop($parts);
            }

            foreach ($parts as $part) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE keyword = '" . $this->db->escape($part) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "'");

                if ($query->num_rows) {
                    $url = explode('=', $query->row['query']);

                    if ($url[0] == 'product_id') {
                        $this->request->get['product_id'] = $url[1];
                    }

                    if ($url[0] == 'category_id') {
                        if (!isset($this->request->get['path'])) {
                            $this->request->get['path'] = $url[1];
                        } else {
                            $this->request->get['path'] .= '_' . $url[1];
                        }
                    }

                    if ($url[0] == 'manufacturer_id') {
                        $this->request->get['manufacturer_id'] = $url[1];
                    }

                    if ($url[0] == 'information_id') {
                        $this->request->get['information_id'] = $url[1];
                    }

                    if ($query->row['query'] && $url[0] != 'information_id' && $url[0] != 'manufacturer_id' && $url[0] != 'category_id' && $url[0] != 'product_id') {
                        $this->request->get['route'] = $query->row['query'];
                    }
                } else {
                    $this->request->get['route'] = 'error/not_found';

                    break;
                }
            }

            if (!isset($this->request->get['route'])) {
                if (isset($this->request->get['product_id'])) {
                    $this->request->get['route'] = 'product/product';
                } elseif (isset($this->request->get['path'])) {
                    $this->request->get['route'] = 'product/category';
                } elseif (isset($this->request->get['manufacturer_id'])) {
                    $this->request->get['route'] = 'product/manufacturer/info';
                } elseif (isset($this->request->get['information_id'])) {
                    $this->request->get['route'] = 'information/information';
                }
        }
    }
    }

    public function rewrite($link) {
        $url_info = parse_url(str_replace('&', '&', $link));

        $url = '';

        $data = array();

        parse_str($url_info['query'], $data);

        foreach ($data as $key => $value) {
            if (isset($data['route'])) {
                if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                    if ($query->num_rows && $query->row['keyword']) {
                        $url .= '/' . $query->row['keyword'];

                        unset($data[$key]);
                    }
                } elseif ($key == 'path') {
                    $categories = explode('_', $value);

                    foreach ($categories as $category) {
                        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = 'category_id=" . (int)$category . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                        if ($query->num_rows && $query->row['keyword']) {
                            $url .= '/' . $query->row['keyword'];
                        } else {
                            $url = '';

                            break;
                        }
                    }

                    unset($data[$key]);

                }
            }
        }

        if ($url) {
            unset($data['route']);

            $query = '';

            if ($data) {
                foreach ($data as $key => $value) {
                    $query .= '&' . rawurlencode((string)$key) . '=' . rawurlencode((is_array($value) ? http_build_query($value) : (string)$value));
                }

                if ($query) {
                    $query = '?' . str_replace('&', '&', trim($query, '&'));
                }
            }

            return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;
        } else {
            return $link;
        }
    }
}

Body:
In your code try this:

<?php
class ControllerStartupSeoUrl extends Controller {
    public function index() {
        // Add rewrite to url class
        if ($this->config->get('config_seo_url')) {
            $this->url->addRewrite($this);
        }

        // Decode URL
        if (isset($this->request->get['_route_'])) {
            $parts = explode('/', $this->request->get['_route_']);

            // remove any empty arrays from trailing
            if (utf8_strlen(end($parts)) == 0) {
                array_pop($parts);
            }

            foreach ($parts as $part) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE keyword = '" . $this->db->escape($part) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "'");

                if ($query->num_rows) {
                    $url = explode('=', $query->row['query']);

                    if ($url[0] == 'product_id') {
                        $this->request->get['product_id'] = $url[1];
                    }

                    if ($url[0] == 'category_id') {
                        if (!isset($this->request->get['path'])) {
                            $this->request->get['path'] = $url[1];
                        } else {
                            $this->request->get['path'] .= '_' . $url[1];
                        }
                    }

                    if ($url[0] == 'manufacturer_id') {
                        $this->request->get['manufacturer_id'] = $url[1];
                    }

                    if ($url[0] == 'information_id') {
                        $this->request->get['information_id'] = $url[1];
                    }

                    if ($query->row['query'] && $url[0] != 'information_id' && $url[0] != 'manufacturer_id' && $url[0] != 'category_id' && $url[0] != 'product_id') {
                        $this->request->get['route'] = $query->row['query'];
                    }
                } elseif ($part == 'brand') {
                    // don't send the user to 'not found page'
                } else {
                    $this->request->get['route'] = 'error/not_found';

                    break;
                }
            }

            if (!isset($this->request->get['route'])) {
                if (isset($this->request->get['product_id'])) {
                    $this->request->get['route'] = 'product/product';
                } elseif (isset($this->request->get['path'])) {
                    $this->request->get['route'] = 'product/category';
                } elseif (isset($this->request->get['manufacturer_id'])) {
                    $this->request->get['route'] = 'product/manufacturer/info';
                } elseif (isset($this->request->get['information_id'])) {
                    $this->request->get['route'] = 'information/information';
                }
        }
    }
    }

    public function rewrite($link) {
        $url_info = parse_url(str_replace('&amp;', '&', $link));

        $url = '';

        $data = array();

        parse_str($url_info['query'], $data);

        foreach ($data as $key => $value) {
            if (isset($data['route'])) {
                if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                    if ($query->num_rows && $query->row['keyword']) {
                        //add brands to the url
                        if ($key == 'manufacturer_id') {
                            $url .= '/brand';
                        }
                        $url .= '/' . $query->row['keyword'];

                        unset($data[$key]);
                    }
                } elseif ($key == 'path') {
                    $categories = explode('_', $value);

                    foreach ($categories as $category) {
                        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = 'category_id=" . (int)$category . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

                        if ($query->num_rows && $query->row['keyword']) {
                            $url .= '/' . $query->row['keyword'];
                        } else {
                            $url = '';

                            break;
                        }
                    }

                    unset($data[$key]);

                }
            }
        }

        if ($url) {
            unset($data['route']);

            $query = '';

            if ($data) {
                foreach ($data as $key => $value) {
                    $query .= '&' . rawurlencode((string)$key) . '=' . rawurlencode((is_array($value) ? http_build_query($value) : (string)$value));
                }

                if ($query) {
                    $query = '?' . str_replace('&', '&amp;', trim($query, '&'));
                }
            }

            return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;
        } else {
            return $link;
        }
    }
}


来源: stackexchange

问:
How to properly handle zero bit width case?
When I write generic module, I often encounter 0-bit width case.

```<code>module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
    always_comb begin
        y = x[WIDTH - 1 : 0];
    end
endmodule
</code>```

For example, the above module extracts lowest WIDTH bits from x.
When WIDTH is 0, output is don't care.
However, when the module is instantiated with WIDTH 0, I get the following error in Modelsim:

```<code># ** Fatal: (vsim-3373) test.sv(8): Range of part-select [-1:0] into 'x' [31:0] is reversed.
</code>```

I tried the following code hoping for the bad part to be optimized out at compile time, but the error remains.

```<code>if (WIDTH == 0) y = 0;
else y = x[WIDTH - 1 : 0];
</code>```

Is there any remedy to this situation?

答:
Your procedural code needs to compile, even if the branch with the bad range is never taken.

```<code>module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
    always_comb
       if (WIDTH == 0) y = 'x;
       else y = x[WIDTH - 1 + (WIDTH==0): 0];
endmodule
</code>```

You could also do

```<code>module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
if (WIDTH==0)
  assign y = 'x;
else
  assign  y = x[WIDTH - 1: 0];
endmodule
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I write generic module, I often encounter 0-bit width case.

module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
    always_comb begin
        y = x[WIDTH - 1 : 0];
    end
endmodule

For example, the above module extracts lowest WIDTH bits from x.
When WIDTH is 0, output is don't care.
However, when the module is instantiated with WIDTH 0, I get the following error in Modelsim:

# ** Fatal: (vsim-3373) test.sv(8): Range of part-select [-1:0] into 'x' [31:0] is reversed.

I tried the following code hoping for the bad part to be optimized out at compile time, but the error remains.

if (WIDTH == 0) y = 0;
else y = x[WIDTH - 1 : 0];

Is there any remedy to this situation?

Body:
Your procedural code needs to compile, even if the branch with the bad range is never taken.

module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
    always_comb
       if (WIDTH == 0) y = 'x;
       else y = x[WIDTH - 1 + (WIDTH==0): 0];
endmodule

You could also do

module test #(
    parameter WIDTH
) (
    input logic [31 : 0] x,
    output logic [31 : 0] y
);
if (WIDTH==0)
  assign y = 'x;
else
  assign  y = x[WIDTH - 1: 0];
endmodule


问:
how to convert a tuple in to a 2D matrix
I a have tuple a with the shape of (3,1) and I would like to construct a 2D matrix X with the dimension(3,2). After X is constructed, there is a need to multiply X'*X which is supposed to be in the shape of (2,2)

enter image description here

答:
```<code>import numpy as np
thistuple = (1, 2, 3)
arr=np.ones(shape=(len(thistuple),2))

tuple_index=0
for i in range(0,len(arr)):
  for j in range(0,len(arr[0])):
    if(tuple_index>=len(thistuple)):
        break
    arr[i][j]=thistuple[tuple_index]
    tuple_index+=1

rez = arr.T
result = np.dot(rez,arr)
print(result)
</code>```

The above code will work for an tuple of shape n*1 in python.

Body:
import numpy as np
thistuple = (1, 2, 3)
arr=np.ones(shape=(len(thistuple),2))

tuple_index=0
for i in range(0,len(arr)):
  for j in range(0,len(arr[0])):
    if(tuple_index>=len(thistuple)):
        break
    arr[i][j]=thistuple[tuple_index]
    tuple_index+=1

rez = arr.T
result = np.dot(rez,arr)
print(result)

The above code will work for an tuple of shape n*1 in python.


问:
Search records having comma seperated values that contains any element from the given list
I have a domain class Schedule with a property 'days' holding comma separated values like '2,5,6,8,9'.

```<code>Class Schedule {
   String days
   ...
}

Schedule schedule1 = new Schedule(days :'2,5,6,8,9')
schedule1.save()

Schedule schedule2 = new Schedule(days :'1,5,9,13')
schedule2.save()
</code>```

I need to get the list of the schedules having any day from the given list say [2,8,11].

Output: [schedule1]

How do I write the criteria query or HQL for the same. We can prefix & suffix the days with comma like ',2,5,6,8,9,' if that helps.

Thanks,

答:
In MySQL there is a SET datatype and FIND_IN_SET function, but I've never used that with Grails. Some databases have support for standard SQL2003 ARRAY datatype for storing arrays in a field. It's possible to map them using hibernate usertypes (which are supported in Grails).

If you are using MySQL, FIND_IN_SET query should work with the Criteria API sqlRestriction:
http://grails.org/doc/latest/api/grails/orm/HibernateCriteriaBuilder.html#sqlRestriction(java.lang.String)
Using SET+FIND_IN_SET makes the queries a bit more efficient than like queries if you care about performance and have a real requirement to do denormalization.

ContentLicense: CC BY-SA 3.0

Body:
I have a domain class Schedule with a property 'days' holding comma separated values like '2,5,6,8,9'.

Class Schedule {
   String days
   ...
}

Schedule schedule1 = new Schedule(days :'2,5,6,8,9')
schedule1.save()

Schedule schedule2 = new Schedule(days :'1,5,9,13')
schedule2.save()

I need to get the list of the schedules having any day from the given list say [2,8,11].

Output: [schedule1]

How do I write the criteria query or HQL for the same. We can prefix & suffix the days with comma like ',2,5,6,8,9,' if that helps.

Thanks,


问:
Set default value for a field while populating POJO using Bean Utils
I am trying to populate the fields of a POJO using BeanUtilsBean.populate(object, fieldNameVSfieldValueMap) method.

My POJO looks like :

```<code>class POJO{
  Integer intField;
  Double doubleField
  String str;
}
</code>```

Currently I have a HashMap that contains a map between the field name and field value.

Now with the following code:

```<code>POJO obj = new POJO();
Map<String,String> map = new HashMap<>();
map.put("intField", "1");
map.put("doubleField", "1.1");
BeanUtilsBean.populate(obj, map)

</code>```

With the above code in my POJO object obj, the fields intField and doubleField get populated with the values 1 and 1.1 respectively which is as expected.

The problem with this is that, the string field str get null assigned to it as there was no entry in the hashmap for str and null is default value for String.
But I want was an explicit way to set my custom value to a field when they are not mentioned in the map.
For this example lets say I want to set str to "john" as there is not entry for str in the map.
Edit 1:
And also that should be specific to the field type. So if there are other fields in POJO and they are of String type, then for all those String fields, for whom entry is not there in the Map should be populated with John.

Edit 2: The POJO is defined in a different project that I dont have commit access to, so set default values in the POJO itself is not a solution to me.

答:
Basically you could do:

```<code>Map<String, String> map = new HashMap<>() {  // new HashMap<String, String> perhaps
    @Override
    public String get(Object key} {
        return super.getOrDefault(key, "john");
    }
}
</code>```

If you want different defaults per field, use a local map, prefilled with defaults.

Then you should make your own class.

Body:
I am trying to populate the fields of a POJO using BeanUtilsBean.populate(object, fieldNameVSfieldValueMap) method.

My POJO looks like :

class POJO{
  Integer intField;
  Double doubleField
  String str;
}

Currently I have a HashMap that contains a map between the field name and field value.

Now with the following code:

POJO obj = new POJO();
Map<String,String> map = new HashMap<>();
map.put("intField", "1");
map.put("doubleField", "1.1");
BeanUtilsBean.populate(obj, map)

With the above code in my POJO object obj, the fields intField and doubleField get populated with the values 1 and 1.1 respectively which is as expected.

The problem with this is that, the string field str get null assigned to it as there was no entry in the hashmap for str and null is default value for String.
But I want was an explicit way to set my custom value to a field when they are not mentioned in the map.
For this example lets say I want to set str to "john" as there is not entry for str in the map.
Edit 1:
And also that should be specific to the field type. So if there are other fields in POJO and they are of String type, then for all those String fields, for whom entry is not there in the Map should be populated with John.

Edit 2: The POJO is defined in a different project that I dont have commit access to, so set default values in the POJO itself is not a solution to me.

Body:
Basically you could do:

Map<String, String> map = new HashMap<>() {  // new HashMap<String, String> perhaps
    @Override
    public String get(Object key} {
        return super.getOrDefault(key, "john");
    }
}

If you want different defaults per field, use a local map, prefilled with defaults.

Then you should make your own class.


问:
Eaten by the net? Crawler survival under this website using python
I am making web-crawler to get information from http://www.caam.org.cn/hyzc, but it showed me HTTP Error 302, and I cannot fix it.
https://imgur.com/a/W0cykim
The picture gives you a rough idea about the special layout of this website in that when you are browsing it, it will pop out a window, telling you that the website is accelerating, for the reason that there are so many people online, and then direct you to that website. As a result, when I use web-crawler, all I get is the information on this window, but nothing on this website. I think this is a good way for the website keeper to get rid of our web crawlers. So I want to ask for your help to get useful information from this website

At first, I used requests of python for my web crawler, and I only got information on that window, the results are shown here: https://imgur.com/a/GLcpdZn
And then I forbad website redirect, I got HTTP Error 303, shown:
https://imgur.com/a/6YtaVOt

This is the latest code I used:

python

```<code>import requests
def getpage(url):
    try:
        r= requests.get(url, headers={'User-Agent':'Mozilla/5.0'}, timeout=10)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "try again"
url = "http://www.caam.org.cn/hyzc"
print(getpage(url))
</code>```

The expected outcome of this question is to get useful information from the website http://www.caam.org.cn/hyzc. We may need to deal with the window popped out.

答:
I added something to delay the closure of my web crawl and this worked. So I want to share my lines in case you meet similar problem in the future:

python

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = Options()
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://www.caam.org.cn')
body = driver.find_element_by_tag_name("body")
wait = WebDriverWait(driver, 5, poll_frequency=0.05)
wait.until(EC.staleness_of(body))
print(driver.page_source)
driver.close()
</code>```

Body:
I am making web-crawler to get information from http://www.caam.org.cn/hyzc, but it showed me HTTP Error 302, and I cannot fix it.
https://imgur.com/a/W0cykim
The picture gives you a rough idea about the special layout of this website in that when you are browsing it, it will pop out a window, telling you that the website is accelerating, for the reason that there are so many people online, and then direct you to that website. As a result, when I use web-crawler, all I get is the information on this window, but nothing on this website. I think this is a good way for the website keeper to get rid of our web crawlers. So I want to ask for your help to get useful information from this website

At first, I used requests of python for my web crawler, and I only got information on that window, the results are shown here: https://imgur.com/a/GLcpdZn
And then I forbad website redirect, I got HTTP Error 303, shown:
https://imgur.com/a/6YtaVOt

This is the latest code I used:

python

import requests
def getpage(url):
    try:
        r= requests.get(url, headers={'User-Agent':'Mozilla/5.0'}, timeout=10)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "try again"
url = "http://www.caam.org.cn/hyzc"
print(getpage(url))

The expected outcome of this question is to get useful information from the website http://www.caam.org.cn/hyzc. We may need to deal with the window popped out.

Body:
I added something to delay the closure of my web crawl and this worked. So I want to share my lines in case you meet similar problem in the future:

python

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = Options()
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://www.caam.org.cn')
body = driver.find_element_by_tag_name("body")
wait = WebDriverWait(driver, 5, poll_frequency=0.05)
wait.until(EC.staleness_of(body))
print(driver.page_source)
driver.close()


问:
How to Display a Custom Field Value of a Taxonomy in Post Page?
This seems very straight forward, but I can't get it to work even after going through the documentation (and a number of questions in this site) multiple times.

I have a custom post type called comic with a taxonomy field (type radio button) called book. The book taxonomy has a text field called book_title. I'm trying to display the value of book_title in single-comic.php.

This is what I've done so far:

```<code><?php
$term = get_field('book');
if( $term ): ?>
<h1><?php echo $term->book_title; ?></h1>
<?php endif; ?>
</code>```

This results in an empty h1 element, which suggests that $term returns true. Also, echoing $term returns 9 which I believe is the number of fields (default and custom) associated with book taxonomy. This means that I'm getting the correct object. I'm just unable to use it to display the values of its fields.

答:
You will get array in a multi dimensional format so you cannot fetch directly like you have implemented. To fetch respective field you need to loop the $terms array. Please try below snippet. Hope it works.</p>

```<code><?php

$terms = get_the_terms(get_the_ID(), 'book');

if( $terms ): ?>

    <?php foreach( $terms as $term ): ?>

        <h1><?php echo $term->book_title; ?></h1>

    <?php endforeach; ?>

<?php endif; ?>
</code>```

Body:
This seems very straight forward, but I can't get it to work even after going through the documentation (and a number of questions in this site) multiple times.

I have a custom post type called comic with a taxonomy field (type radio button) called book. The book taxonomy has a text field called book_title. I'm trying to display the value of book_title in single-comic.php.

This is what I've done so far:

<?php
$term = get_field('book');
if( $term ): ?>

<?php echo $term->book_title; ?>

<?php endif; ?>

This results in an empty h1 element, which suggests that $term returns true. Also, echoing $term returns 9 which I believe is the number of fields (default and custom) associated with book taxonomy. This means that I'm getting the correct object. I'm just unable to use it to display the values of its fields.

Body:
You will get array in a multi dimensional format so you cannot fetch directly like you have implemented. To fetch respective field you need to loop the $terms array. Please try below snippet. Hope it works.

<?php

$terms = get_the_terms(get_the_ID(), 'book');

if( $terms ): ?>

    <?php foreach( $terms as $term ): ?>

        <h1><?php echo $term->book_title; ?></h1>

    <?php endforeach; ?>

<?php endif; ?>


问:
Set parent's state from child
My custom component should pass data to parent which is react-admin <Create>
I have came across some questions already and found that I can't simply set state from child to parent.

The problem is that this component should work like the default react-admin components (ex. ). It means when I submit the form It gets data from that component.

I have already tried addField()

This is my custom component (child):

```<code>import React from "react";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";
import { fetchUtils } from 'react-admin';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import { DataService } from '../routes/api';
import PropTypes from 'prop-types';
import { resources as rsrc } from '../resources';

const divStyle = {
  marginTop: '16px',
  marginBottom: '8px',
};

const inputStyle = {
  width: '256px',
}

export default class MultipleSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectOptions: [],
      selectedValues: [],
      selectedValue: null,
    };
  }

  getRoles() {
   // get data from api
  }

  getAllOptions() {
    // get some additional data from API
  }

  createRelationRecord(id) {
    // create relation record (for ex. User's Role)
  }

  deleteRelationRecord(id) {
    // delete relation record
  }

  componentDidMount() {
      this.getRoles();
      this.getAllOptions();
  }

  renderSelectOptions = () => {
    return this.state.selectOptions.map((dt, i) => (
      <MenuItem key={dt.id} value={dt.id}>
        {dt.value}
      </MenuItem>
    ));
  };

  handleChange = event => {
    this.setState({ selectedValue: event.target.value });

    // If record doesn't exist
    if (this.state.selectedValue != event.nativeEvent.target.dataset.value) {
      this.createRelationRecord(event.nativeEvent.target.dataset.value);
    }

    if (this.state.selectedValues.includes(Number(event.nativeEvent.target.dataset.value))) {
      this.deleteRelationRecord(event.nativeEvent.target.dataset.value);
    } else {
      this.createRelationRecord(event.nativeEvent.target.dataset.value);
    }
  };

  selectboxType() {
    if (this.props.multiple) {
      return true;
    }
    return false;
  }

  getSelected() {
    if (this.selectboxType()) {
      return this.state.selectedValues;
    }
    return this.state.selectedValue;
  }

  render() {
    return (
      <div style={divStyle}>
        <FormControl>
            <InputLabel htmlFor={this.props.label}>{this.props.label}</InputLabel>
            <Select
              multiple={this.selectboxType()}
              style={inputStyle}
              value={this.getSelected()}
              onChange={this.handleChange}
            >
              {this.renderSelectOptions()}
            </Select>
        </FormControl>
      </div>
    );
  }
}
</code>```

Parent (create form):

```<code>export const ServerCreate = props => (
   <Create {...props}>
      <SimpleForm>
         <TextInput source="Name" validate={required()} />
         <ReferrenceSelectBox label="ServerType" multiple={false} source="ServerTypeId" reference="ServerType"></ReferrenceSelectBox>
         <TextInput source="Barcode" validate={required()} />
      </SimpleForm>
   </Create>
);
</code>```

It works with handleChange to achieve the data update. Now I need to save the selected data in Create form, but handleChange will not help me, because the object is not created yet and I cannot set attribute of non-existent record.

So my question is how can I pass value/values from my component to Create? How to set parent's state?

答:
Your ServerCreate doesn't have any state, but if it did, you need to pass a function which can update its state to the child component as a prop.

Generally speaking, you should probably lift the state higher up the component tree

Title: Set parent's state from child

Body:
My custom component should pass data to parent which is react-admin <Create>
I have came across some questions already and found that I can't simply set state from child to parent.

The problem is that this component should work like the default react-admin components (ex. ). It means when I submit the form It gets data from that component.

I have already tried addField()

This is my custom component (child):

import React from "react";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";
import { fetchUtils } from 'react-admin';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import { DataService } from '../routes/api';
import PropTypes from 'prop-types';
import { resources as rsrc } from '../resources';

const divStyle = {
  marginTop: '16px',
  marginBottom: '8px',
};

const inputStyle = {
  width: '256px',
}

export default class MultipleSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectOptions: [],
      selectedValues: [],
      selectedValue: null,
    };
  }

  getRoles() {
   // get data from api
  }

  getAllOptions() {
    // get some additional data from API
  }

  createRelationRecord(id) {
    // create relation record (for ex. User's Role)
  }

  deleteRelationRecord(id) {
    // delete relation record
  }

  componentDidMount() {
      this.getRoles();
      this.getAllOptions();
  }

  renderSelectOptions = () => {
    return this.state.selectOptions.map((dt, i) => (
      <MenuItem key={dt.id} value={dt.id}>
        {dt.value}
      </MenuItem>
    ));
  };

  handleChange = event => {
    this.setState({ selectedValue: event.target.value });

    // If record doesn't exist
    if (this.state.selectedValue != event.nativeEvent.target.dataset.value) {
      this.createRelationRecord(event.nativeEvent.target.dataset.value);
    }

    if (this.state.selectedValues.includes(Number(event.nativeEvent.target.dataset.value))) {
      this.deleteRelationRecord(event.nativeEvent.target.dataset.value);
    } else {
      this.createRelationRecord(event.nativeEvent.target.dataset.value);
    }
  };

  selectboxType() {
    if (this.props.multiple) {
      return true;
    }
    return false;
  }

  getSelected() {
    if (this.selectboxType()) {
      return this.state.selectedValues;
    }
    return this.state.selectedValue;
  }

  render() {
    return (

        <FormControl>
            <InputLabel htmlFor={this.props.label}>{this.props.label}</InputLabel>
            <Select
              multiple={this.selectboxType()}
              style={inputStyle}
              value={this.getSelected()}
              onChange={this.handleChange}
            >
              {this.renderSelectOptions()}
            </Select>
        </FormControl>

    );
  }
}

Parent (create form):

export const ServerCreate = props => (
   <Create {...props}>
      <SimpleForm>
         <TextInput source="Name" validate={required()} />
         <ReferrenceSelectBox label="ServerType" multiple={false} source="ServerTypeId" reference="ServerType"></ReferrenceSelectBox>
         <TextInput source="Barcode" validate={required()} />
      </SimpleForm>
   </Create>
);

It works with handleChange to achieve the data update. Now I need to save the selected data in Create form, but handleChange will not help me, because the object is not created yet and I cannot set attribute of non-existent record.

So my question is how can I pass value/values from my component to Create? How to set parent's state?


问:
Cloudformation-created Autoscaling group timeout
I'm experimenting with cloudformation/autoscaling groups to provision our build agents. These take a loong time to provision, and I'm using Lifecycle hooks to signal readiness after a node is finished installing its dependencies, which may take as long as 90 minutes after it comes online.

My LifeCycleHook is configured with HeartbeatTimeout: 7200, and this seems to work fine. However, I get the impression that Cloudformation will only wait 60 minutes for the ASG to stabilize before it gives up. Are there other timeouts besides the HeartbeatTimeout that I should set in order to allow my nodes enough time to go thru their installation process?

(I realize this is an edge case)

UPDATE: As I worked more with this I realize there are two separate methods of controlling the state of an "Autoscale Instance" - lifecycle hooks and "cloudformation signals". It seems that the problem is that cloudformation is completely unaware of the lifecycle hook being in a wait state. I looked into replacing my logic by using cfn signals, but it seems that on Rolling Updates the max timeout ("PauseTime") setting that can be configured is one hour.

All in all, there doesn't seem to be a way to reliably emit status during instance deployment if the deployment takes more than one hour. I've forwarded this to aws support to see what they say.

答:
Huh? Why not just send the cfn-signal early to confirm ASG's rolling update policy. That or just remove it altogether.

That, then call LifeCycleHook when you are done with bootstrapping. When you call LifeCycleHook with ABANDON, the instance will be terminated too?


问:
Sails 1.0 cannot access autogenerated associated entity routes
I have an association between Client and Budget as follows:

```<code>//Client.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    name: {
      type: 'string'
    },
    phone: {
      type: 'string',
      unique: true
    },
    email: {
      type: 'string',
      unique: true
    },
    budgets: {
      collection: 'budget',
      via: 'client'
    },
  }
};

// Budget.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    client: {
      model: 'client'
    },
    budgetItems: {
      type: 'json'
    }
  }
};
</code>```

So, POST is working for both entities so I can create both of them, but:

```<code> GET /budget/1
</code>```

returns the budget and the id of the associated client.

```<code> GET /budget/1/client
</code>```

returns the client id without populating(as i've seen in documentation it should be populated).

```<code> GET /client/1
</code>```

returns the client attributes and there is not a field related with budgets.

```<code> GET /client/1/budgets
</code>```

returns 404 NOT FOUND

I'm following this and this official documentation

So what I could be missing?

Is just generating one direction associations, and I've compared with official documentation and third party examples and my code looks fine.

Thanks in advance!

Update:

I still looking for troubles and if I run sails with --silly option it shows there is the following route available:

Binding route ::  get /client/:parentid/budgets POLICY: localize

  Binding route ::  get /client/:parentid/budgets POLICY: isauth

  Binding route ::  get /client/:parentid/budgets BLUEPRINT: populate

but if I try to access returns a 404 Not Found and console shows the following error, thrown by populate.js from Sails core code:

verbo: In populate blueprint action: Specified parent record (1)
  does not have a budgets.

Update2:

Debugging with sails console I've seen the association is generated properly. Given Client.findOne({id: 1}).populate('budgets').then((client)=>{console.log(client)}) print the client attributes and the associated Budgets but still return 404 Not Found when: GET /client/1/budgets

答:
thanks to SailsJS team we've found the problem and it was related with a third party package and just had to remove it from my project.
It was sails-hook-deep-orm who's owner has been warned. I hope someone with the same issue will reach this post.

Thanks u all anyway!!

The issue is available there

Body:
I have an association between Client and Budget as follows:

//Client.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    name: {
      type: 'string'
    },
    phone: {
      type: 'string',
      unique: true
    },
    email: {
      type: 'string',
      unique: true
    },
    budgets: {
      collection: 'budget',
      via: 'client'
    },
  }
};

// Budget.js
module.exports = {
  primaryKey: 'id',

  attributes: {
    id: {
      type: 'number',
      unique: true,
      autoIncrement: true
    },
    client: {
      model: 'client'
    },
    budgetItems: {
      type: 'json'
    }
  }
};

So, POST is working for both entities so I can create both of them, but:

 GET /budget/1

returns the budget and the id of the associated client.

 GET /budget/1/client

returns the client id without populating(as i've seen in documentation it should be populated).

 GET /client/1

returns the client attributes and there is not a field related with budgets.

 GET /client/1/budgets

returns 404 NOT FOUND

I'm following this and this official documentation

So what I could be missing?

Is just generating one direction associations, and I've compared with official documentation and third party examples and my code looks fine.

Thanks in advance!

Update:

I still looking for troubles and if I run sails with --silly option it shows there is the following route available:

Binding route ::  get /client/:parentid/budgets POLICY: localize

  Binding route ::  get /client/:parentid/budgets POLICY: isauth

  Binding route ::  get /client/:parentid/budgets BLUEPRINT: populate

but if I try to access returns a 404 Not Found and console shows the following error, thrown by populate.js from Sails core code:

verbo: In populate blueprint action: Specified parent record (1)
  does not have a budgets.

Update2:

Debugging with sails console I've seen the association is generated properly. Given Client.findOne({id: 1}).populate('budgets').then((client)=>{console.log(client)}) print the client attributes and the associated Budgets but still return 404 Not Found when: GET /client/1/budgets


问:
need to remove the last zeros in line
need to read a file. check for the zeros in the last of each line . if the last digit is zero I want to delete it .please help me for this </p>

```<code>input="temp.txt"
while IFS= read -r line
do
echo "output    :$line"

if [[ $line == 0$ ]]; then
  echo " blash "
  else
    echo "anotherblash"
  fi

done < "$input"
</code>```

答:
While the solution given by John1024 in the comment is the right way to go, if you prefer to follow your original approach, it does not make sense to compare [[  $line == 0$ ]], because this would just check whether the line consists of the digit zero, forllowed by a dollar sign. Instead, you would have to do a regular expression match, i.e.

```<code>if [[ $line =~ 0$ ]]
</code>```

This would yield true, if the line ends in a zero.

Another possibility is to stick with globbing and write the condition as

```<code>if [[ $line == *0 ]]
</code>```

Note that within [[ ... ]], a =~ does regexp matching and a == does wildcard matching (i.e. via globbing).

Title: need to remove the last zeros in line

Body:
need to read a file. check for the zeros in the last of each line . if the last digit is zero I want to delete it .please help me for this

input="temp.txt"
while IFS= read -r line
do
echo "output    :$line"

if [[ $line == 0$ ]]; then
  echo " blash "
  else
    echo "anotherblash"
  fi

done < "$input"

Body:
While the solution given by John1024 in the comment is the right way to go, if you prefer to follow your original approach, it does not make sense to compare [[  $line == 0$ ]], because this would just check whether the line consists of the digit zero, forllowed by a dollar sign. Instead, you would have to do a regular expression match, i.e.

if [[ $line =~ 0$ ]]

This would yield true, if the line ends in a zero.

Another possibility is to stick with globbing and write the condition as

if [[ $line == *0 ]]

Note that within [[ ... ]], a =~ does regexp matching and a == does wildcard matching (i.e. via globbing).


问:
How do i make onClick and href work together?
I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

```<code><li><a href="#someSectionOfThePage" onClick={someFunction}>GO TO SECTION</a></li>
</code>```

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.

答:
Although it is not advisable but if you still want to use both then this might do the trick:

```<code>someFunction= ()=>{
  window.location.href("#someSectionOfThePage");
  //do your onClick stuff here
};

<li>
  <span onClick={this.someFunction}>GO TO SECTION</span>
</li>

</code>```

Hope this helps!!

Body:
I have an a element which has his own href and it works perfectly. The problem is that besides an href element i want to make an onClick function, but when i do so, the href is ignored:

GO TO SECTION

Using this syntax, the someFunction runs, but i'm not being redirected to #someSectionOfThePage.

Body:
Although it is not advisable but if you still want to use both then this might do the trick:

someFunction= ()=>{
  window.location.href("#someSectionOfThePage");
  //do your onClick stuff here
};

<li>
  <span onClick={this.someFunction}>GO TO SECTION</span>
</li>

Hope this helps!!


问:
Replace guava Fluent Iterables with Streams
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

```<code>public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}
</code>```

I tried with this solution:

```<code>public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}
</code>```

how to do that without casting the return Stream?

答:
You forgot to check if your elements are even of type T. I.e. you have to filter those elements out first:

```<code>return filter.stream()
             .filter(classType::isInstance) // only keep elements of type T
             .map(classType::cast)          // safely cast from Object to T
             .collect(Collectors.toList()); // collect into a List<T>
</code>```

Class#isInstance() also directly takes care of null values, so you don't have to use filter(Object::nonNull).

Body:
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}

I tried with this solution:

public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}

how to do that without casting the return Stream?

Body:
You forgot to check if your elements are even of type T. I.e. you have to filter those elements out first:

return filter.stream()
             .filter(classType::isInstance) // only keep elements of type T
             .map(classType::cast)          // safely cast from Object to T
             .collect(Collectors.toList()); // collect into a List<T>

Class#isInstance() also directly takes care of null values, so you don't have to use filter(Object::nonNull).


问:
Collect errors from Chrome extension and send report
Is possible to send an error report from my Chrome Extension to my server?

or at least log somewhere in local to request that info to the user?

EDIT

I mean the errors logged by the Chrome extension (when we are in developer mode). That is: errors not catched by my code

答:
You can use any error reporting tool as usual.
https://sentry.io
https://www.bugsnag.com/</p>


问:
RESTful collections & controlling member details
I have come across this issue a few times now, and each time I make a fruitless search to come up with a satisfying answer.

We have a collection resource which returns a representation of the member URIs, as well as a Link header field with the same URIs (and a custom relation type). Often we find that we need specific data from each member in the collection.

At one extreme, we can have the collection return nothing but the member URIs; the client must then query each URI in turn to determine the required data from each member.

At the other extreme, we return all of the details we might want on the collection. Neither of these is perfect; the first can result in a large number of API calls, and the second may return a lot of potentially unneeded information.

Of the two extremes I favour the second in our case, since we rarely use this for more than one sutiation. However, for a more general approach, I wondered if anyone had a nice way of dynamically specifying which details should be included for each member of the collection? I guess a query string parameter would be most appropriate, but I don't want to break the self-descriptiveness of the resource.

答: Sounds like you're trying to reinvent PROPFIND (RFC 4918, Section 9.1).</p>

ContentLicense: CC BY-SA 2.5


问:
How to retrieve entities with a subset of related entities?
I have two entities in a one-to-many relation:
Meter (1) -> (n) Reading

I believe my two entities are set up correctly to provide the relation, so assume that.

I wish to retrieve Meters with related Readings but because there may be many Readings per Meter, I wish to limit it by eg Reading.Date. Another option could be to read at most X Readings per Meter.

How can I do that in EF.Core?

答:
What I think the other answer missed is that you are asking for a subset of the related entities, i.e. not the entire collection of related entities.

If you want to be selective about the related entities that are fetched, you cannot just rely on an Include statement (or implicit lazy loading), because these are set up to load all related entities.

There is no selective Include. But you can make an inclusive Select:

```<code>DateTime filterDate = DateTime.Now;

var myData = db.Meters
               .Select(m => new
                            {
                                Meter = m,
                                Readings = m.Readings.Where(r => r.Date == filterDate)
                            })
               .ToList();
</code>```

Remarks

I used an anonymous type, but you can of course also use a concrete DTO class.

Where(r => r.Date == filterDate) can be improved (checking for the Date component, or a range), this is just a simple example. You can use whatever filter criteria you want here.

Notice that you do not need an Include statement for this. A Select (on a yet unenumerated IQueryable) does not need an explicit Include because the Select itself is already aware of what data you want to fetch.

I suggest not putting the subset of related entities in the meter.Readings nav prop. This is going to lead to confusion down the line as to whether this list is a subset or the full set, and EF may actually register this as a change when you call SaceChanges(). Nav props should not be used as storage space for collection with the same type but a different functional meaning.

Body:
What I think the other answer missed is that you are asking for a subset of the related entities, i.e. not the entire collection of related entities.

If you want to be selective about the related entities that are fetched, you cannot just rely on an Include statement (or implicit lazy loading), because these are set up to load all related entities.

There is no selective Include. But you can make an inclusive Select:

DateTime filterDate = DateTime.Now;

var myData = db.Meters
               .Select(m => new
                            {
                                Meter = m,
                                Readings = m.Readings.Where(r => r.Date == filterDate)
                            })
               .ToList();

Remarks

I used an anonymous type, but you can of course also use a concrete DTO class.

Where(r => r.Date == filterDate) can be improved (checking for the Date component, or a range), this is just a simple example. You can use whatever filter criteria you want here.

Notice that you do not need an Include statement for this. A Select (on a yet unenumerated IQueryable) does not need an explicit Include because the Select itself is already aware of what data you want to fetch.

I suggest not putting the subset of related entities in the meter.Readings nav prop. This is going to lead to confusion down the line as to whether this list is a subset or the full set, and EF may actually register this as a change when you call SaceChanges(). Nav props should not be used as storage space for collection with the same type but a different functional meaning.


问:
Where to store html code for jQuery?
In some scripts long html blocks are added to selector. For example

```<code>$("#test").prepend($('<div id="tester">..long html tags..</div>').hide().fadeIn(2000));
</code>```

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.

答: have you had a look at jquery templates?</p>

Title: Where to store html code for jQuery?

Body:
In some scripts long html blocks are added to selector. For example

$("#test").prepend($('
..long html tags..
').hide().fadeIn(2000));

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.


问:
How to insert space between a number and a character /string using regex in javascript
How to insert space between a number and string / character

I have a regex question.

How do I insert a space between a numeric character and a letter.

For example:

```<code>var sentence = "It contains 37mg of salt"
</code>```

I want the output to be:

```<code>It contains 37 mg of salt.
</code>```

答:
You can match the number using (\d+) and add a white space in the replaced string in front of the matched number

var sentence = "It contains 37mg of salt"
let res = sentence.replace(/(\d+)/g,"$1 ")
console.log(res)```

Body:
How to insert space between a number and string / character

I have a regex question.

How do I insert a space between a numeric character and a letter.

For example:

var sentence = "It contains 37mg of salt"

I want the output to be:

It contains 37 mg of salt.


问:
Convert a plain public key to PEM
I have generated an EC key pair using Prime-256v1 from a trusted application and export the public key to Normal OS. Key size is 65 bytes. The public key is  in plain format (only key hex).

The exported public key needs to be given to a library (third party). The library expects the public key in PEM format.

After searching for some time, my understanding is first convert from plain key to DER format, and then convert the result to PEM. But I have not been able to find any APIs for the conversion from plain key to DER or PEM.

Found this API which  PEM_ASN1_write((i2d_of_void*)i2d_PUBKEY,PEM_STRING_PUBLIC,outfile,ctx->cert->key->public_key,NULL,NULL,0,NULL,NULL); which convert from a file pointer. But I am not able to do file operations as not file storage possible. I am getting public key in a buffer.

I am doing this in C program, if any sample code or API's to convert plain hex key to PEM.

Thanks in advance

答:
The value you provided in a comment 4bb5f0c58cc71806ec4d228b730dd252947e679cce05f71d434787fe228f14c799cf8965780bb308aa722ac179bfa5fd57592a72cbdcfe89ab61ad5d77251186d is the wrong length. It is 129 hex digits, aka nibbles, but an encoded point for prime256v1 (aka secp256r1 or P-256) must either be 65 octets beginning with 04 (uncompressed) or 33 octets beginning with 02 or 03 (compressed). When a hex string (or decimal or octal for that matter) represents an integer, you can remove or add leading zeros without changing the number, but an EC point is not an integer.

You say your code is providing 65 bytes which is correct for uncompressed. Use that.

Unlike most other PK algorithms, OpenSSL does not have an algorithm-specific DER (and thus PEM) format for ECC, so anything accurately described as wanting a PEM publickey (and not a certificate, which is the conventional way of transmitting a publickey) must be using the X.509/PKIX SubjectPublicKeyInfo format, which OpenSSL names PUBKEY (as shown in Shane's answer) and maps from or to an EVP_PKEY structure in the program. To construct this from the raw public point, you must first combine it with the curve identification to form an actual EC publickey, and then identify that as EC to form a generic publickey, and write it. OpenSSL can do I/O (including PEM) to and from memory using a BIO of type 'mem', without any file(s). (And making this firmly a programming question and not a commandline question, which would really be offtopic and belong in another Stack, although many are asked here anyway.)

```<code>/* SO #56218946 */
#include <stdio.h>
#include <stdlib.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#ifdef _WIN32
#include <openssl/applink.c>
#endif

void err (const char *label){  // for test; improve for real code
  fprintf (stderr, "Error in %s:\n", label);
  ERR_print_errors_fp (stderr);
  exit (1);
}

int main (void) //(int argc, char**argv)
{
  ERR_load_crypto_strings(); /* or SSL_load_error_strings */
  //OPENSSL_add_all_algorithms_noconf(); /* for PKCS#8 */

  // test data -- replace for real use
  char hex [] = "04bb5f0c58cc71806ec4d228b730dd252947e679cce05f71d434787fe228f14c799cf8965780bb308aa722ac179bfa5fd57592a72cbdcfe89ab61ad5d77251186d";
  unsigned char raw [65]; for( int i = 0; i < 65; i++ ){ sscanf(hex+2*i, "%2hhx", raw+i); }

  EC_KEY *eck = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); /* or OBJ_txt2nid("prime256v1") */
  if( !eck ) err("ECCnewbyname");
  EC_KEY_set_asn1_flag(eck, OPENSSL_EC_NAMED_CURVE); /* needed below 1.1.0 */
  const unsigned char *ptr = raw;
  if( !o2i_ECPublicKey (&eck, &ptr, sizeof(raw)) ) err("o2iECPublic=point");
  EVP_PKEY * pkey = EVP_PKEY_new();
  if( !EVP_PKEY_assign_EC_KEY(pkey, eck) ) err("PKEYassign");

  BIO *bio = BIO_new(BIO_s_mem());
  if( !PEM_write_bio_PUBKEY (bio, pkey) ) err("PEMwrite");
  char *pem = NULL; long len = BIO_get_mem_data (bio, &pem);
  fwrite (pem, 1, len, stdout); // for test; for real use as needed
  return 0;
}
</code>```

(ADDED) Alternatively, since X9.62 point encoding is fixed size for a given curve, the DER-encoded SPKI structure for a given curve actually consists of a fixed header followed by the point value, so you could instead concatenate with that fixed header and do generic PEM conversion: output dashes-BEGIN line, output base64 with line breaks, output dashes-END line. Although it is not hard to work out the header if one knows how ASN.1 works, a shortcut is to generate the SPKI encoding for a dummy key with e.g. openssl ecparam -genkey -name prime256v1 -outform der and remove the last 65 bytes (or 33 if compressed using -conv_form). Compare to the Java variants at Loading raw 64-byte long ECDSA public key in Java .

Title: Convert a plain public key to PEM

Body:
The value you provided in a comment 4bb5f0c58cc71806ec4d228b730dd252947e679cce05f71d434787fe228f14c799cf8965780bb308aa722ac179bfa5fd57592a72cbdcfe89ab61ad5d77251186d is the wrong length. It is 129 hex digits, aka nibbles, but an encoded point for prime256v1 (aka secp256r1 or P-256) must either be 65 octets beginning with 04 (uncompressed) or 33 octets beginning with 02 or 03 (compressed). When a hex string (or decimal or octal for that matter) represents an integer, you can remove or add leading zeros without changing the number, but an EC point is not an integer.

You say your code is providing 65 bytes which is correct for uncompressed. Use that.

Unlike most other PK algorithms, OpenSSL does not have an algorithm-specific DER (and thus PEM) format for ECC, so anything accurately described as wanting a PEM publickey (and not a certificate, which is the conventional way of transmitting a publickey) must be using the X.509/PKIX SubjectPublicKeyInfo format, which OpenSSL names PUBKEY (as shown in Shane's answer) and maps from or to an EVP_PKEY structure in the program. To construct this from the raw public point, you must first combine it with the curve identification to form an actual EC publickey, and then identify that as EC to form a generic publickey, and write it. OpenSSL can do I/O (including PEM) to and from memory using a BIO of type 'mem', without any file(s). (And making this firmly a programming question and not a commandline question, which would really be offtopic and belong in another Stack, although many are asked here anyway.)

/* SO #56218946 */
#include <stdio.h>
#include <stdlib.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#ifdef _WIN32
#include <openssl/applink.c>
#endif

void err (const char *label){  // for test; improve for real code
  fprintf (stderr, "Error in %s:\n", label);
  ERR_print_errors_fp (stderr);
  exit (1);
}

int main (void) //(int argc, char**argv)
{
  ERR_load_crypto_strings(); /* or SSL_load_error_strings */
  //OPENSSL_add_all_algorithms_noconf(); /* for PKCS#8 */

  // test data -- replace for real use
  char hex [] = "04bb5f0c58cc71806ec4d228b730dd252947e679cce05f71d434787fe228f14c799cf8965780bb308aa722ac179bfa5fd57592a72cbdcfe89ab61ad5d77251186d";
  unsigned char raw [65]; for( int i = 0; i < 65; i++ ){ sscanf(hex+2*i, "%2hhx", raw+i); }

  EC_KEY *eck = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); /* or OBJ_txt2nid("prime256v1") */
  if( !eck ) err("ECCnewbyname");
  EC_KEY_set_asn1_flag(eck, OPENSSL_EC_NAMED_CURVE); /* needed below 1.1.0 */
  const unsigned char *ptr = raw;
  if( !o2i_ECPublicKey (&eck, &ptr, sizeof(raw)) ) err("o2iECPublic=point");
  EVP_PKEY * pkey = EVP_PKEY_new();
  if( !EVP_PKEY_assign_EC_KEY(pkey, eck) ) err("PKEYassign");

  BIO *bio = BIO_new(BIO_s_mem());
  if( !PEM_write_bio_PUBKEY (bio, pkey) ) err("PEMwrite");
  char *pem = NULL; long len = BIO_get_mem_data (bio, &pem);
  fwrite (pem, 1, len, stdout); // for test; for real use as needed
  return 0;
}

(ADDED) Alternatively, since X9.62 point encoding is fixed size for a given curve, the DER-encoded SPKI structure for a given curve actually consists of a fixed header followed by the point value, so you could instead concatenate with that fixed header and do generic PEM conversion: output dashes-BEGIN line, output base64 with line breaks, output dashes-END line. Although it is not hard to work out the header if one knows how ASN.1 works, a shortcut is to generate the SPKI encoding for a dummy key with e.g. openssl ecparam -genkey -name prime256v1 -outform der and remove the last 65 bytes (or 33 if compressed using -conv_form). Compare to the Java variants at Loading raw 64-byte long ECDSA public key in Java .


问:
How do you run a python file from another python file?
Im trying to run another file from my tkinter login system but i cant find the way to do it

Ive tried import file

```<code>if (p == '123') and (u == 'test'):
    import correct
</code>```

Im trying to run the file when those are true

答:
One hacky way to do it, if you really have to is this:

with open("correct.py", "r") as f:
    exec(f.read())
```

But you should avoid doing this if possible. Normally it is better import the file and run a function from it.

Body:
Im trying to run another file from my tkinter login system but i cant find the way to do it

Ive tried import file

if (p == '123') and (u == 'test'):
    import correct

Im trying to run the file when those are true

Body:
One hacky way to do it, if you really have to is this:

with open("correct.py", "r") as f:
    exec(f.read())

But you should avoid doing this if possible. Normally it is better import the file and run a function from it.


问:
number input always trigger change event
I have a issue with Angulars change event on numeric input. It doesn't always trigger when i click the increment or decrament buttons, actualy it triggers once then it will trigger only after input losses hover.

My question is if there is some way to prevent this from happening or some replacement for change event.

some ground for testing:
stackblitz

答:
as mentioned in coment's the best way of doing this is to use (input) event.

Like this:

<input type="number" (input)="action()">


问:
C++ Matrix Class - Suggestions
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

```<code>template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix<U>&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix<U>&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}
</code>```

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.

答: If speed is what you have in mind, don't implement a matrix library yourself but use Boost libraries, I've used them in some projects and do pretty well on both 32 and 64 bit architectures</p>

Title: C++ Matrix Class - Suggestions

Body:
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.


问:
Find and change the value of JAVA_HOME in centos/wildfly docker image
I'm just starting out with docker, so this may be a conceptual mistake -

I downloaded the centos/wildfly image from Docker Hub and wanted to change the JDK version of this server.

However, I couldn't find the JAVA_HOME value anywhere in the wildfly config files, and there isn't any java folder in usr

For this setup and image, where is it pulling the JDK path from ? Is there a way to access it and hopefully change it ?

答:
If look into the official repository of centos/wildly, you will find something like

```<code>RUN yum -y install tar java-1.7.0-openjdk-devel
</code>```

wildfly/centos7/Dockerfile

So you do not need to modify the existing image, just build your own image be updating JDK version in Dockerfile, build it and run the container from your own image.

Create your own Dockerfile and run the below command that's it.

```<code>docker build --tag=centos/wildfly-admin-jdk-1.8 .

docker run -it -p 9990:9990 centos/wildfly-admin-jdk-1.8
</code>```

So here is the Dockerfile with JDK-1.8.0

```<code># Use latest Fedora image as the base
FROM centos:latest
MAINTAINER http://www.centos.org

LABEL Vendor="CentOS"
LABEL License=GPLv2
LABEL Version=8.2.0.Final

# Update base image
RUN yum -y update && yum clean all

# xmlstarlet is useful when modifying attributes/elements
# saxon can be used to execute configuration transformation using XSLT
# augeas is a great tool to edit any configuration files (XML too)
# bsdtar can be used to unpack zip files using pipes
RUN yum -y install tar java-1.8.0-openjdk-devel saxon \
augeas bsdtar shadow-utils && yum clean all

# Set the WILDFLY_VERSION env variable
ENV WILDFLY_VERSION 8.2.0.Final

# Create the wildfly user and group
RUN groupadd -r wildfly -g 433 && useradd -u 431 -r -g wildfly -d /opt/wildfly -s /sbin/nologin -c "WildFly user" wildfly

# Create directory to extract tar file to
RUN mkdir /opt/wildfly-$WILDFLY_VERSION

# Add the WildFly distribution to /opt, and make wildfly the owner of the extracted tar content
RUN cd /opt && curl http://download.jboss.org/wildfly/$WILDFLY_VERSION/wildfly-$WILDFLY_VERSION.tar.gz | tar zx && chown -R wildfly:wildfly /opt/wildfly-$WILDFLY_VERSION

# Make sure the distribution is available from a well-known place
RUN ln -s /opt/wildfly-$WILDFLY_VERSION /opt/wildfly && chown -R wildfly:wildfly /opt/wildfly

# Set the JBOSS_HOME env variable
ENV JBOSS_HOME /opt/wildfly

# Expose the ports we're interested in
EXPOSE 8080 9990

# Run everything below as the wildfly user
USER wildfly

# Set the default command to run on boot
# This will boot WildFly in the standalone mode and bind to all interface
CMD ["/opt/wildfly/bin/standalone.sh", "-c", "standalone-full.xml", "-b", "0.0.0.0", "-bmanagement", "0.0.0.0"]
</code>```

Body:
If look into the official repository of centos/wildly, you will find something like

RUN yum -y install tar java-1.7.0-openjdk-devel

wildfly/centos7/Dockerfile

So you do not need to modify the existing image, just build your own image be updating JDK version in Dockerfile, build it and run the container from your own image.

Create your own Dockerfile and run the below command that's it.

docker build --tag=centos/wildfly-admin-jdk-1.8 .

docker run -it -p 9990:9990 centos/wildfly-admin-jdk-1.8

So here is the Dockerfile with JDK-1.8.0

# Use latest Fedora image as the base
FROM centos:latest
MAINTAINER http://www.centos.org

LABEL Vendor="CentOS"
LABEL License=GPLv2
LABEL Version=8.2.0.Final

# Update base image
RUN yum -y update && yum clean all

# xmlstarlet is useful when modifying attributes/elements
# saxon can be used to execute configuration transformation using XSLT
# augeas is a great tool to edit any configuration files (XML too)
# bsdtar can be used to unpack zip files using pipes
RUN yum -y install tar java-1.8.0-openjdk-devel saxon \
augeas bsdtar shadow-utils && yum clean all

# Set the WILDFLY_VERSION env variable
ENV WILDFLY_VERSION 8.2.0.Final

# Create the wildfly user and group
RUN groupadd -r wildfly -g 433 && useradd -u 431 -r -g wildfly -d /opt/wildfly -s /sbin/nologin -c "WildFly user" wildfly

# Create directory to extract tar file to
RUN mkdir /opt/wildfly-$WILDFLY_VERSION

# Add the WildFly distribution to /opt, and make wildfly the owner of the extracted tar content
RUN cd /opt && curl http://download.jboss.org/wildfly/$WILDFLY_VERSION/wildfly-$WILDFLY_VERSION.tar.gz | tar zx && chown -R wildfly:wildfly /opt/wildfly-$WILDFLY_VERSION

# Make sure the distribution is available from a well-known place
RUN ln -s /opt/wildfly-$WILDFLY_VERSION /opt/wildfly && chown -R wildfly:wildfly /opt/wildfly

# Set the JBOSS_HOME env variable
ENV JBOSS_HOME /opt/wildfly

# Expose the ports we're interested in
EXPOSE 8080 9990

# Run everything below as the wildfly user
USER wildfly

# Set the default command to run on boot
# This will boot WildFly in the standalone mode and bind to all interface
CMD ["/opt/wildfly/bin/standalone.sh", "-c", "standalone-full.xml", "-b", "0.0.0.0", "-bmanagement", "0.0.0.0"]


答:
Match a number, lookahead for a letter, then replace with the number with a space after it:

var sentence = "It contains 37mg of salt";
const result = sentence.replace(/\d(?=[a-z])/i, '$& ');
console.log(result);```

Title: How to insert space between a number and a character /string using regex in javascript


问:
How I remove controllers name from the route (URL)?
How I remove controllers name from the route (URL)?

```<code>Example :

Existing Url: https://localhost:3000/home/contact_us

I want this URL https://localhost:3000/contact_us
</code>```

so how can I do that?

Route.rb

get "home/contact_us", to: "home#contact_us", as: :contact_us

答:
try

get "contact_us", to: "home#contact_us", as: :contact_us

Body:
How I remove controllers name from the route (URL)?

Example :

Existing Url: https://localhost:3000/home/contact_us

I want this URL https://localhost:3000/contact_us

so how can I do that?

Route.rb

get "home/contact_us", to: "home#contact_us", as: :contact_us


问:
How to get the content of the element using explicit wait instead of sleep() using Selenium and Java
I'm trying to get the content of an element. I've implemented an explicit wait of 20 seconds before the statement of getting content. But I can't get the content. I can get the content of the element if I use sleep() for 2 seconds. The code I tried is:

```<code>WebDriverWait wait1 = new WebDriverWait(driver,20);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath")));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is :
</code>```

The code with sleep():

```<code>WebDriverWait wait1 = new WebDriverWait(driver,20);
Thread.sleep(2000);
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is : $0.00
</code>```

I'm not getting the value if I use implicit wait also. It is recommended not to use sleep(). Using explicit wait is always the best practice. Why am I not getting the content of the element using explicit wait?

答:
What is the error you get? It seems like the element doesn't load properly. There may be some animations going on such as a popup modal closing, table loading etc. Usually, it is ok to put sleeps if you know how long these kinds of animations take.

You can also try fluentwait, but if there are animations going on, you may still get exceptions such as driver not being able to click on an element.

FluentWait:

```<code>Wait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(timeout))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class)
    .ignoring(StaleElementReferenceException.class);
</code>```

Body:
I'm trying to get the content of an element. I've implemented an explicit wait of 20 seconds before the statement of getting content. But I can't get the content. I can get the content of the element if I use sleep() for 2 seconds. The code I tried is:

WebDriverWait wait1 = new WebDriverWait(driver,20);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath")));
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is :

The code with sleep():

WebDriverWait wait1 = new WebDriverWait(driver,20);
Thread.sleep(2000);
String value = driver.findElement(By.xpath("xpath")).getAttribute("text-content");
System.out.println("Value is : " + value);

Output - Value is : $0.00

I'm not getting the value if I use implicit wait also. It is recommended not to use sleep(). Using explicit wait is always the best practice. Why am I not getting the content of the element using explicit wait?

Body:
What is the error you get? It seems like the element doesn't load properly. There may be some animations going on such as a popup modal closing, table loading etc. Usually, it is ok to put sleeps if you know how long these kinds of animations take.

You can also try fluentwait, but if there are animations going on, you may still get exceptions such as driver not being able to click on an element.

FluentWait:

Wait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(timeout))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class)
    .ignoring(StaleElementReferenceException.class);


问:
STM32 (using Mbed online) showing delay at higher analog input frequency
I am new to the use of controllers.
I am setting up a STM32F769 Controller(Using Mbed online compiler), my target is to get a PWM output which changes its frequency according to an analog input. I did some basic coding but there is a problem. When i check the output on oscilloscope with analog input 1Hz frequency, its working perfectly, but when i check it with 100Hz analog input there is delay in the output, and i get wrong values. I do not understand why, because this board is faster(216 MHZ) and i should not face such issue. (If someone could also explain, is it possible to use the board at 216MHz or other max frequency? and how?)

1st time user

```<code>{
 meas_r=0;
 for(int i=1;i<=1024;i++)
 {
    meas_r = meas_r+analog_value.read();
 }
 meas_r=meas_r/1024;
 meas_v = meas_r * 3300;
 out_freq=50000+(meas_v*50);
 pulse.period( 1.0 / out_freq);
 }
}
</code>```

It should be working on 100Hz analog input as it works on 1 Hz.

答:
216MHz might be the maximum clock frequency at which your processor can operate, however it does not mean that it can input/output that much frequency from its ports.

The delays are caused by time it takes to read analog values and compute required math operations. You are using multiple multiplications and divisions which are more complex than adding and subtracting for almost any hardware device. Obviously, you are using library/libraries as well (pulse.period(), analog_value.read()), there are some hidden computations on top of those multiplications and divisions. Finally, it is possible that your device is working with other stuffs as well (only you know about this). All those computations need time. At lower frequencies you might not be able to notice the delay, however when the frequency is high enough, the delays can be noticed. Also consider time required to read the analog values many times.

Wrong signal and period is due to the delays and some other uncertainties. If the processor is working with other tasks as well, then it will be hard to predict time it takes to finish them all. As the processor executes the instructions line by line and waits for previous computation to finish before the new one starts, it causes some uncertainty in timing. Data path and frequency of peripheral devices (getting input from peripherals) play crucial role in timing uncertainty and delays.

If timing and accuracy is really important in solving the problem you have, and if you can't solve the problem with DSP, MPU, MCU, CPU, GPU, etc. I would suggest you to use an FPGA to solve the problem.

Body:
I am new to the use of controllers.
I am setting up a STM32F769 Controller(Using Mbed online compiler), my target is to get a PWM output which changes its frequency according to an analog input. I did some basic coding but there is a problem. When i check the output on oscilloscope with analog input 1Hz frequency, its working perfectly, but when i check it with 100Hz analog input there is delay in the output, and i get wrong values. I do not understand why, because this board is faster(216 MHZ) and i should not face such issue. (If someone could also explain, is it possible to use the board at 216MHz or other max frequency? and how?)

1st time user

{
 meas_r=0;
 for(int i=1;i<=1024;i++)
 {
    meas_r = meas_r+analog_value.read();
 }
 meas_r=meas_r/1024;
 meas_v = meas_r * 3300;
 out_freq=50000+(meas_v*50);
 pulse.period( 1.0 / out_freq);
 }
}

It should be working on 100Hz analog input as it works on 1 Hz.


答:
Use initialization lists when initializing contructor args:

```<code> Matrix(int _r,int _c)
    {
        r=_r;c=_c;
</code>```

..

should be:

```<code> Matrix(int _r,int _c) : r(_r), c(_c)
    {
        ....
</code>```

Title: C++ Matrix Class - Suggestions

Body:
Use initialization lists when initializing contructor args:

 Matrix(int _r,int _c)
    {
        r=_r;c=_c;

..

should be:

 Matrix(int _r,int _c) : r(_r), c(_c)
    {
        ....


问:
I have made a category and want to make sub category, how can I add dynamically?
I made a form in which I have titlte, image, pdf, content and category and all are working fine, but I want to add submenu in my form and also want to make this dynamic so can show all sub-menu on my website.</p>

答:
You must have to intruduce a key parent_id with categories table.

And in category model do create the relation like this.

```<code>class Category extends Model
{

    public $fillable = ['title','parent_id'];

    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function childs() {
        return $this->hasMany('App\Category','parent_id','id') ;
    }
}
</code>```

Here you can find the complete example..https://itsolutionstuff.com/post/laravel-5-category-treeview-hierarchical-structure-example-with-demoexample.html

Hopefully this could help you.

Body:
You must have to intruduce a key parent_id with categories table.

And in category model do create the relation like this.

class Category extends Model
{

    public $fillable = ['title','parent_id'];

    /**
     * Get the index name for the model.
     *
     * @return string
    */
    public function childs() {
        return $this->hasMany('App\Category','parent_id','id') ;
    }
}

Here you can find the complete example..https://itsolutionstuff.com/post/laravel-5-category-treeview-hierarchical-structure-example-with-demoexample.html

Hopefully this could help you.


问:
Modal Screen Post Result this Modal Screen
I'm doing Post via Modal PopUp. I want to show the returned value again on the same Modal PopUp. How can I do that ?</p>

```<code> [HttpPost]
    public ActionResult ResetPassword(Param_Login login)
    {
        ViewBag.ResetPassword = true;
        DataSet ds = new DataSet();
        List<SqlParameter> parameters = new List<SqlParameter>()
        {
            new SqlParameter("EmailAdress",login.EmailAdress),
        };

        ds = DataManager.RunSP_ReturnDS("sp_Set_Web_ResetPassword", parameters);

        if (ds.Tables[0].Rows[0]["ResultId"].ToString() == "1")
        {
            ViewBag.Hata = false;
        }
        else
        {
            ViewBag.Hata = true;
        }
        ViewBag.Mesaj = ds.Tables[0].Rows[0]["ResultMessage"].ToString();
        ModelState.Clear();
        return View();
    }
</code>```

答:
You need to use Jquery ajax to avoid postback , and then retrieve the result in a partial view, replace the html in a div tag.

$.ajax
                ({
                    type: "POST",
                    url: '@Url.Action("ResetPassword", "ResetPassword")',
                    data: { dd: dd },
                    contentType: "application/json; charset=utf-8",
                    async: true,
                    cache: false,
                    traditional: true,
                    dataType: "html",
                    success: function (response) {
                        $("#div").html(response);
                    }
                });

Body:
I'm doing Post via Modal PopUp. I want to show the returned value again on the same Modal PopUp. How can I do that ?

 [HttpPost]
    public ActionResult ResetPassword(Param_Login login)
    {
        ViewBag.ResetPassword = true;
        DataSet ds = new DataSet();
        List<SqlParameter> parameters = new List<SqlParameter>()
        {
            new SqlParameter("EmailAdress",login.EmailAdress),
        };

        ds = DataManager.RunSP_ReturnDS("sp_Set_Web_ResetPassword", parameters);

        if (ds.Tables[0].Rows[0]["ResultId"].ToString() == "1")
        {
            ViewBag.Hata = false;
        }
        else
        {
            ViewBag.Hata = true;
        }
        ViewBag.Mesaj = ds.Tables[0].Rows[0]["ResultMessage"].ToString();
        ModelState.Clear();
        return View();
    }