问:
Declaration or Definition in C
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

```<code>int i;
</code>```

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

```<code>                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.
</code>```

答:
From the C99 spec:

A declaration of an identifier for an object that has file scope without an initializer, and
     without a storage-class specifier or with the storage-class specifier static, constitutes a
        tentative definition. If a translation unit contains one or more tentative definitions for an
           identifier, and the translation unit contains no external definition for that identifier, then
                the behavior is exactly as if the translation unit contains a file scope declaration of that
                 identifier, with the composite type as of the end of the translation unit, with an initializer
                  equal to 0.

So this is one case in which a simple declaration without an initializer can be a declaration.

Title: Declaration or Definition in C

Body:
From External Variables Wiki:

If neither the extern keyword nor an
  initialization value are present, the
  statement can be either a declaration
  or a definition. It is up to the
  compiler to analyse the modules of the
  program and decide.

I was not able to fully grasp the meaning of this statement with respect to C. For example, does it imply that:

int i;

is not necessarily a declaration (as I have been assuming until now), but could be a definition as well (by definition of Definition & Declaration on the same webpage, no puns intended)?

In a nutshell, is the above statement:
a. just a declaration, or
b. declaration +  definition?

Reference: Variable declaration and definition

Summary of answers received:

                         Declaration    Definition    Tentative Definition   Initialized
int i;   (inside a block)    Yes           Yes                No                No
int i=5; (inside a block)    Yes           Yes                No               Yes(to 5)
int i;   (otherwise)         Yes            No               Yes               Yes(to 0)
extern int i;                Yes            No                No                No

All definitions are declarations but not vice-versa.


来源: stackexchange

问:
Runtime.exec() issues with java when attempting to execute scripts, but certain commands work
I am attempting to have my java program execute a python script using

```<code>import java.lang.Runtime;
public class test
{
  public static void main(String[] args)
  {
  try
  {
    System.out.println("testing");
    Runtime.getRuntime().exec("/usr/bin/python print.py");
  }catch(Exception e){System.out.println("not working");}

  }
}
</code>```

However, nothing is shown on the terminal, (print.py simple prints "THIS IS WORKING"). In contrast to this, when I use

```<code>Runtime.getRuntime().exec("touch dog.txt");
</code>```

A file named dog.txt is created.

I also attempted to run

```<code>Runtime.getRuntime()exec("./shellscript.sh");
</code>```

Which is just a script that runs the touch command, that also did not work.

Not really sure what the issue is here, and even more interesting is that yesterday the java program was working as intended with no large changes to my computer in the time in between. Anybody have any ideas on whats going on?

I am not receiving any errors.

答:
I guess you have to wait to end of script execution.

```<code>    try {
        Process process = Runtime.getRuntime().exec("/usr/bin/python print.py");
        process.waitFor();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

You can try to read exitCode from process ;-)

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to have my java program execute a python script using

import java.lang.Runtime;
public class test
{
  public static void main(String[] args)
  {
  try
  {
    System.out.println("testing");
    Runtime.getRuntime().exec("/usr/bin/python print.py");
  }catch(Exception e){System.out.println("not working");}

  }
}

However, nothing is shown on the terminal, (print.py simple prints "THIS IS WORKING"). In contrast to this, when I use

Runtime.getRuntime().exec("touch dog.txt");

A file named dog.txt is created.

I also attempted to run

Runtime.getRuntime()exec("./shellscript.sh");

Which is just a script that runs the touch command, that also did not work.

Not really sure what the issue is here, and even more interesting is that yesterday the java program was working as intended with no large changes to my computer in the time in between. Anybody have any ideas on whats going on?

I am not receiving any errors.

Body:
I guess you have to wait to end of script execution.

    try {
        Process process = Runtime.getRuntime().exec("/usr/bin/python print.py");
        process.waitFor();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

You can try to read exitCode from process ;-)


问:
Redirect only Mobile devices with 51 Degrees
I'm using 51 Degrees in .NET on MVC and it's only just come to my attention that 51 degrees redirects Tablets as default with what it classes as IsMobile.

I only want to redirect mobile traffic, ie phones etc and not tablets. Tablets should be using my default "Desktop" layout.

Is there anyway I can use the (Lite) 51 Degrees to only redirect mobile traffic and not tablet traffic?

答:
A bit late to this but i'm one of the engineers over at 51Degrees. We now offer a free basic Cloud service that gives access to the "IsTablet" property. This can then be used to tailor your re-direct options.

A basic example of calling against this option would look like:

```<code>https://cloud.51degrees.com/api/v1/*LICENCE_KEY*/match?user-agent=iphone&Values=IsTablet
</code>```

Body:
A bit late to this but i'm one of the engineers over at 51Degrees. We now offer a free basic Cloud service that gives access to the "IsTablet" property. This can then be used to tailor your re-direct options.

A basic example of calling against this option would look like:

https://cloud.51degrees.com/api/v1/*LICENCE_KEY*/match?user-agent=iphone&Values=IsTablet


问:
Bottom fixed child div inside in another child div
I have  a small problem. I have two columns filled with dynamic text. Both are the same height according to bigger one. Now, I want another fixed div after the content of the bigger div. My html code is:

.parent {
  display: inline-flex;
  width: 100%;
}

.child1 {
  display: inline-block;
  background-color: #c5e997;
  width: 49%;
  position: relative;
}

.child2 {
  display: flex;
  position: absolute;
  bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">

  <div class="child1">
    Random text here Less dynamic text
    <div class="child2">
      Fixed
    </div>
  </div>

  <div class="child1">
    Random text here<br/> More
    <br/> Dynamic
    <br/> Text
    <br/> Here
    <div class="child2">
      Fixed
    </div>
  </div>

</div></code>```

So, any idea how to set the second div after the higher dynamic text?
In this moment, the "Fixed" text is displayed over the longest text.

L.E.: you can see the code here: https://jsfiddle.net/fte087p7/
Thank you!

答:
.parent {
  display: inline-flex;
  width: 100%;
}

.child1 {
  display: inline-block;
  background-color: #c5e997;
  width: 49%;
  position: relative;
  padding-bottom: 20px;
}

.child2 {
  display: flex;
  position: absolute;
  bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">

  <div class="child1">
    Random text here Less dynamic text
    <div class="child2">
      Text
    </div>
  </div>

  <div class="child1">
    Random text here
    <br/> More
    <br/> Dynamic
    <br/> Text
    <br/> Here
    <div class="child2">
      Fixed
    </div>
  </div>

</div></code>```

How about adding padding-bottom in .child1?

Body:
I have  a small problem. I have two columns filled with dynamic text. Both are the same height according to bigger one. Now, I want another fixed div after the content of the bigger div. My html code is:

.parent {
  display: inline-flex;
  width: 100%;
}

.child1 {
  display: inline-block;
  background-color: #c5e997;
  width: 49%;
  position: relative;
}

.child2 {
  display: flex;
  position: absolute;
  bottom: 0;
}

    Random text here Less dynamic text

      Fixed

    Random text here
 More

 Dynamic

 Text

 Here

      Fixed

So, any idea how to set the second div after the higher dynamic text?
In this moment, the "Fixed" text is displayed over the longest text.

L.E.: you can see the code here: https://jsfiddle.net/fte087p7/
Thank you!

Body:
.parent {
  display: inline-flex;
  width: 100%;
}

.child1 {
  display: inline-block;
  background-color: #c5e997;
  width: 49%;
  position: relative;
  padding-bottom: 20px;
}

.child2 {
  display: flex;
  position: absolute;
  bottom: 0;
}

<div class="parent">

  <div class="child1">
    Random text here Less dynamic text
    <div class="child2">
      Text
    </div>
  </div>

  <div class="child1">
    Random text here
    <br/> More
    <br/> Dynamic
    <br/> Text
    <br/> Here
    <div class="child2">
      Fixed
    </div>
  </div>

</div>

How about adding padding-bottom in .child1?


问:
Get top n records for each group of grouped results
The following is the simplest possible example, though any solution should be able to scale to however many n top results are needed:

Given a table like that below, with person, group, and age columns, how would you get the 2 oldest people in each group? (Ties within groups should not yield more results, but give the first 2 in alphabetical order)

```
+--------+-------+-----+
| Person | Group | Age |
+--------+-------+-----+
| Bob    | 1     | 32  |
| Jill   | 1     | 34  |
| Shawn  | 1     | 42  |
| Jake   | 2     | 29  |
| Paul   | 2     | 36  |
| Laura  | 2     | 39  |
+--------+-------+-----+
```

Desired result set:

```
+--------+-------+-----+
| Shawn  | 1     | 42  |
| Jill   | 1     | 34  |
| Laura  | 2     | 39  |
| Paul   | 2     | 36  |
+--------+-------+-----+
```

NOTE: This question builds on a previous one- Get records with max value for each group of grouped SQL results - for getting a single top row from each group, and which received a great MySQL-specific answer from @Bohemian:

```<code>select *
from (select * from mytable order by `Group`, Age desc, Person) x
group by `Group`
</code>```

Would love to be able to build off this, though I don't see how.

答:
Snuffin solution seems quite slow to execute when you've got plenty of rows and Mark Byers/Rick James and Bluefeet solutions doesn't work on my environnement (MySQL 5.6) because order by is applied after  execution of select, so here is a variant of Marc Byers/Rick James solutions to fix this issue (with an extra imbricated select):

```<code>select person, groupname, age
from
(
    select person, groupname, age,
    (@rn:=if(@prev = groupname, @rn +1, 1)) as rownumb,
    @prev:= groupname
    from
    (
        select person, groupname, age
        from persons
        order by groupname ,  age desc, person
    )   as sortedlist
    JOIN (select @prev:=NULL, @rn :=0) as vars
) as groupedlist
where rownumb<=2
order by groupname ,  age desc, person;
</code>```

I tried similar query on a table having 5 millions rows and it returns result in less than 3 seconds

Body:
The following is the simplest possible example, though any solution should be able to scale to however many n top results are needed:

Given a table like that below, with person, group, and age columns, how would you get the 2 oldest people in each group? (Ties within groups should not yield more results, but give the first 2 in alphabetical order)

+--------+-------+-----+
| Person | Group | Age |
+--------+-------+-----+
| Bob    | 1     | 32  |
| Jill   | 1     | 34  |
| Shawn  | 1     | 42  |
| Jake   | 2     | 29  |
| Paul   | 2     | 36  |
| Laura  | 2     | 39  |
+--------+-------+-----+

Desired result set:

+--------+-------+-----+
| Shawn  | 1     | 42  |
| Jill   | 1     | 34  |
| Laura  | 2     | 39  |
| Paul   | 2     | 36  |
+--------+-------+-----+

NOTE: This question builds on a previous one- Get records with max value for each group of grouped SQL results - for getting a single top row from each group, and which received a great MySQL-specific answer from @Bohemian:

select *
from (select * from mytable order by `Group`, Age desc, Person) x
group by `Group`

Would love to be able to build off this, though I don't see how.

Body:
Snuffin solution seems quite slow to execute when you've got plenty of rows and Mark Byers/Rick James and Bluefeet solutions doesn't work on my environnement (MySQL 5.6) because order by is applied after  execution of select, so here is a variant of Marc Byers/Rick James solutions to fix this issue (with an extra imbricated select):

select person, groupname, age
from
(
    select person, groupname, age,
    (@rn:=if(@prev = groupname, @rn +1, 1)) as rownumb,
    @prev:= groupname
    from
    (
        select person, groupname, age
        from persons
        order by groupname ,  age desc, person
    )   as sortedlist
    JOIN (select @prev:=NULL, @rn :=0) as vars
) as groupedlist
where rownumb<=2
order by groupname ,  age desc, person;

I tried similar query on a table having 5 millions rows and it returns result in less than 3 seconds


问:
Canvas getImageData().data return half image
I'm trying to generate a pixelated canvas from image source - but there is a strange behavior of the getImageData() function -
on images that are higher than my canvas I keep getting only the max height data [square of max-height * max-height].
is there anything I'm missing here?

```<code>function generatePixels(){
    const pixel_size = 10;
    const x = 0; const y = 0;
    const w = temp_ctx.canvas.width;
    const h = temp_ctx.canvas.height;

    let min_width = w,
    min_height = h,
    max_width = 0, max_height = 0;

    for (var j = y; j < (y+h); j += pixel_size) {
        for (var i = x; i < (x+w); i += pixel_size) {

            // get current pixel image data (x,y,10,10);
            var data = temp_ctx.getImageData(j, i, pixel_size, pixel_size).data;

            // draw pixel on rendered canvas
            rendered_ctx.fillStyle = '#' + (data[2] | (data[1] << 8) | (data[0] << 16) | (1 << 24)).toString(16).slice(1);
            rendered_ctx.fillRect((j + pixel_size), (i + pixel_size), 10, 10);

      }
    }
}
</code>```

You can find an example of the code here:
https://codepen.io/AceDesigns/pen/dZEmjZ

答:
Please find the workable code below. The issue is with the for loop condition.

for (var j = y; j < (y+h); j += pixel_size) {
        for (var i = x; i < (x+w); i += pixel_size) {

Body:
I'm trying to generate a pixelated canvas from image source - but there is a strange behavior of the getImageData() function -
on images that are higher than my canvas I keep getting only the max height data [square of max-height * max-height].
is there anything I'm missing here?

function generatePixels(){
    const pixel_size = 10;
    const x = 0; const y = 0;
    const w = temp_ctx.canvas.width;
    const h = temp_ctx.canvas.height;

    let min_width = w,
    min_height = h,
    max_width = 0, max_height = 0;

    for (var j = y; j < (y+h); j += pixel_size) {
        for (var i = x; i < (x+w); i += pixel_size) {

            // get current pixel image data (x,y,10,10);
            var data = temp_ctx.getImageData(j, i, pixel_size, pixel_size).data;

            // draw pixel on rendered canvas
            rendered_ctx.fillStyle = '#' + (data[2] | (data[1] << 8) | (data[0] << 16) | (1 << 24)).toString(16).slice(1);
            rendered_ctx.fillRect((j + pixel_size), (i + pixel_size), 10, 10);

      }
    }
}

You can find an example of the code here:
https://codepen.io/AceDesigns/pen/dZEmjZ


问:
Python, Stop a Thread
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

```<code>class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]
</code>```

答:
As I was saying in my comment, the easiest way is to use threading.Event to signal your thread when it should exit. That way you can expose the event and let other threads set it while you can check for its state from within your thread and exit on request.

In your case, it could be as simple as:

```<code>class Pinger(threading.Thread):

    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)
        self.kill = threading.Event()
        # the rest of your setup...

    # etc.

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while not self.kill.is_set():
            # do your pinging stuff

    # etc.
</code>```

Then whenever you want the thread stopped (like from your UI), just call on it: pinger_instance.kill.set() and you're done. Keep in mind, tho, that it will take some time for it to get killed due to the blocking os.system() call and due to the time.sleep() you have at the end of your Pinger.start_ping() method.

Title: Python, Stop a Thread

Body:
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]

Body:
As I was saying in my comment, the easiest way is to use threading.Event to signal your thread when it should exit. That way you can expose the event and let other threads set it while you can check for its state from within your thread and exit on request.

In your case, it could be as simple as:

class Pinger(threading.Thread):

    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)
        self.kill = threading.Event()
        # the rest of your setup...

    # etc.

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while not self.kill.is_set():
            # do your pinging stuff

    # etc.

Then whenever you want the thread stopped (like from your UI), just call on it: pinger_instance.kill.set() and you're done. Keep in mind, tho, that it will take some time for it to get killed due to the blocking os.system() call and due to the time.sleep() you have at the end of your Pinger.start_ping() method.


问:
Database relation problem
In my database I got a list of companies with columns CompanyId and Name.
Further on there is users and those users can add products.
Tables: user and user_products
There is no product table defining products, they are unique per user therefore "user_product"

When a user adds a product he types a name of a company. If that company name exists in the company table I want to make a connection to the company table instead of saving only the name on the user_product. So far so good.. I just store CompanyId in the user_product table.

The problem is when the user enters a name that doesn't exists in the company table. Instead of saving the name as varchar, I want to create a new record in a table called user_company.
The table got columns: UserCompanyId (PK), UserId, Name. If the combination Name and UserId already exists i will of course not create a new row, just reference to this id.

What should I do to maintain a good database design here.. Should i add this record and also a new column in user_product called UserCompanyId. So that either CompanyId or UserCompanyId is always set when adding a new row. It feels like this could be done in a better way. Anyone got any ideas?

I could of course only have one table "company" and have a column UserId which is null when it's a global company added by the system, or the UserId is actually set when a user has added a company name that didn't existed globally. This doesn't feel good either...

答:
Actually, I think you nailed it in your last paragraph.  A company is either defined by a user or isn't, so the userId makes sense as a nullable column.  This would also allow you to have a unique key on the company name, which allows you to use the database to enforce the fact that a company name can't be duplicated.

Your company table exists to define companies--which user (or whether a user) created the company is just information ABOUT a company.

ContentLicense: CC BY-SA 2.5

Title: Database relation problem


问:
Change select value in react.js
I need your help !

I'm on a project for my compagny and I should create a select field that can be duplicate with React. So, I have a little problem when I want to save my selection, if I refresh the page, the default option still the same (and not the selected one). There is my code for select.js:

```<code>import React, { Component, PropTypes } from 'react';

class Select extends React.Component {

  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(data) {
    this.setState({value:data.value});
  }

  render() {
    return (
        <label>
          <select className="widefat" name={this.props.name} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
    );
  }
}

export default Select;
</code>```

I change the default value :

When i change the select option

After a refresh

I think it's because in select.js It initialize the value to '' and don't save the selection but I don't know how to save the selection.

答:
After a long journey to search in documentation and in the depth of internet I found my answer. I forgot to add a "for" for my label. There is my final code : </p>

```<code>    import React, { Component, PropTypes } from 'react';

class Select extends React.Component {

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({value: this.props.value});
  }

  render() {
    return (
        <label htmlFor={this.props.id}>{this.props.label}
          <select defaultValue={this.props.value}  id={this.props.id} className="widefat" name={this.props.name} onChange={this.handleChange.bind(this)}>
            <option>Aucun</option>
            <option value="55">Option 2</option>
            <option value="126">Backend configuration & installation</option>
            <option value="125">Frontend integration</option>
            <option value="124">Graphic Design</option>
          </select>
        </label>
    );
  }
}

export default Select;
</code>```

Title: Change select value in react.js

Body:
I need your help !

I'm on a project for my compagny and I should create a select field that can be duplicate with React. So, I have a little problem when I want to save my selection, if I refresh the page, the default option still the same (and not the selected one). There is my code for select.js:

import React, { Component, PropTypes } from 'react';

class Select extends React.Component {

  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(data) {
    this.setState({value:data.value});
  }

  render() {
    return (

          <select className="widefat" name={this.props.name} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>

    );
  }
}

export default Select;

I change the default value :

When i change the select option

After a refresh

I think it's because in select.js It initialize the value to '' and don't save the selection but I don't know how to save the selection.

Body:
After a long journey to search in documentation and in the depth of internet I found my answer. I forgot to add a "for" for my label. There is my final code :

    import React, { Component, PropTypes } from 'react';

class Select extends React.Component {

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({value: this.props.value});
  }

  render() {
    return (
        <label htmlFor={this.props.id}>{this.props.label}
          <select defaultValue={this.props.value}  id={this.props.id} className="widefat" name={this.props.name} onChange={this.handleChange.bind(this)}>
            <option>Aucun</option>
            <option value="55">Option 2</option>
            <option value="126">Backend configuration & installation</option>
            <option value="125">Frontend integration</option>
            <option value="124">Graphic Design</option>
          </select>
        </label>
    );
  }
}

export default Select;


问:
odd even numbers alternate inverted triangle
I want to print the following pattern in java:

```<code>a+1357+1
b+246+2
a+13+3
b+2+4
</code>```

following is my code, but with this i can only print odd no. or only even no.s

```<code>public static void main(String[] args) {
    int rows = 7;
    for(int i = rows; i >= 1; i=i-2) {
       for(int j = 1; j <= i; j=j+2) {
           System.out.print(j + " ");
       }
       System.out.println();
    }
}
</code>```

答:
With only a few updates of your code (but not very readable):

```<code>    int rows = 7;
    for (int i = rows; i >= 1; i = i - 2) {
        System.out.print((((i + 1) % 4) == 0 ? "a" : "b") + " + ");
        for (int j = 1; j <= i; j = j + 2) {
            System.out.print((j + ((i + 2) % 4) / 2));
        }
        System.out.println(" + " + (10 - i) / 2);
    }
</code>```

But instead of using my code, I suggest you write down exactly how the "pattern" is defined and write new code based on your specification. These loops are not optimal.

Body:
I want to print the following pattern in java:

a+1357+1
b+246+2
a+13+3
b+2+4

following is my code, but with this i can only print odd no. or only even no.s

public static void main(String[] args) {
    int rows = 7;
    for(int i = rows; i >= 1; i=i-2) {
       for(int j = 1; j <= i; j=j+2) {
           System.out.print(j + " ");
       }
       System.out.println();
    }
}

Body:
With only a few updates of your code (but not very readable):

    int rows = 7;
    for (int i = rows; i >= 1; i = i - 2) {
        System.out.print((((i + 1) % 4) == 0 ? "a" : "b") + " + ");
        for (int j = 1; j <= i; j = j + 2) {
            System.out.print((j + ((i + 2) % 4) / 2));
        }
        System.out.println(" + " + (10 - i) / 2);
    }

But instead of using my code, I suggest you write down exactly how the "pattern" is defined and write new code based on your specification. These loops are not optimal.


问:
selenium aria-activedescendant multiple select box java
I need to automate the selection for a multidrop down box in selenium. The html code which comprises the dropdown is given below. The html code for each component is taken using firebug.

```<code><input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen346" tabindex="-1" placeholder="" style="width: 269px;" aria-activedescendant="select2-result-label-367">
</code>```

I have the aria-activedescendant="select2-result-label-367" value is changing when i change the select value in the list

enter image description here

enter image description here

答:
As per the HTML you have shared to select the multidrop down box you can use the following line of code :

```<code>driver.findElement(By.xpath("//li[@class='select2-search-field']//input[@class='select2-input' and contains(@id,'id_autogen')]")).click();
</code>```

Body:
I need to automate the selection for a multidrop down box in selenium. The html code which comprises the dropdown is given below. The html code for each component is taken using firebug.

<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen346" tabindex="-1" placeholder="" style="width: 269px;" aria-activedescendant="select2-result-label-367">

I have the aria-activedescendant="select2-result-label-367" value is changing when i change the select value in the list

enter image description here

enter image description here

Body:
As per the HTML you have shared to select the multidrop down box you can use the following line of code :

driver.findElement(By.xpath("//li[@class='select2-search-field']//input[@class='select2-input' and contains(@id,'id_autogen')]")).click();


问:
QLabel higlight searched word

I'm developing a Qt application and I'm trying to implement this feature where if you type a word all it's occurences in a QLabel get highlighted. I'm not sure how to do it. Is there a way for iterate through text in QLabel and change the background colour of certain word?

It can be done using in QTextEdit by using QTextEdit::ExtraSelection. But QLabel doesn't have this method.

So for example if the searched word is "sed" I want to get something like this in my QLabel:

答:
You can use Qt rich text to add some style to the subtext. You will need to search for it yourself in the text string and insert some HTML.

```<code>This is my <span style="background-color:yellow">text</span>
</code>```

An example to highlight a word into existing label (already containing the text) :

```<code>QString searchedWord = "sed";

QString txt = lbl->text();
txt.replace(QRegExp("\\b" + searchedWord + "\\b"),
            "<span style=\"background-color:yellow\">" + searchedWord + "</span>");
lbl->setText(txt);
</code>```

If you want to highlight more than one word, you will need to make a more specific RegExp.

Title: QLabel higlight searched word

Body:
You can use Qt rich text to add some style to the subtext. You will need to search for it yourself in the text string and insert some HTML.

This is my <span style="background-color:yellow">text</span>

An example to highlight a word into existing label (already containing the text) :

QString searchedWord = "sed";

QString txt = lbl->text();
txt.replace(QRegExp("\\b" + searchedWord + "\\b"),
            "<span style=\"background-color:yellow\">" + searchedWord + "</span>");
lbl->setText(txt);

If you want to highlight more than one word, you will need to make a more specific RegExp.


问:
Plugin with id 'com.android.application' not found. I have run some modules today and suddenly have got this message
I tried File -> Invalidate caches\Restart, that didn't help me.

Log:

16:05   Gradle sync started

16:05   Gradle sync failed: Plugin with id 'com.android.application' not found.
            Consult IDE log for more details (Help | Show Log) (34s 987ms)

build.gradle application

```<code>apply plugin: 'com.android.application'

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "ru.startandroid.androidlessons"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
your build.graddle in project level should look like below

```<code>buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

and gradle-wrapper.properties distributionUrl should be like:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
</code>```

Body:
I tried File -> Invalidate caches\Restart, that didn't help me.

Log:

16:05   Gradle sync started

16:05   Gradle sync failed: Plugin with id 'com.android.application' not found.
            Consult IDE log for more details (Help | Show Log) (34s 987ms)

build.gradle application

apply plugin: 'com.android.application'

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "ru.startandroid.androidlessons"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Body:
your build.graddle in project level should look like below

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

and gradle-wrapper.properties distributionUrl should be like:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip


问:
How to validate date in laravel
In validate method I have following :

```<code>$this->validate($request, ['test_date' => 'required|unique:test_db']);
</code>```

The test_date in test_db is stored as unix time.
On submission of form, I get $request->get('test_date') in mm/dd/Y

The unique validation does not work because I get date in mm/dd/Y which is different from db (unix time).

How to make it unique in this validation?

答:
Laravel Provide feature called Accessors and mutators.

Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances.

For more information visit: https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

Hope this will help you.

Title: How to validate date in laravel

Body:
In validate method I have following :

$this->validate($request, ['test_date' => 'required|unique:test_db']);

The test_date in test_db is stored as unix time.
On submission of form, I get $request->get('test_date') in mm/dd/Y

The unique validation does not work because I get date in mm/dd/Y which is different from db (unix time).

How to make it unique in this validation?


问:
How can I define multiple jobs dynamically in Spring Batch?
I have an application that uses Spring Batch to define a preset number of jobs, which are currently all defined in the XML.

We add more jobs over time which requires updating the XML, however these jobs are always based on the same parent and can easily be predetermined using a simple SQL query.

So I've been trying to switch to use some combination of XML configuration and Java-based configuration but am quickly getting confused.

Even though we have many jobs, each job definition falls into essentially one of two categories. All of the jobs inherit from one or the other parent job and are effectively identical, besides having different names. The job name is used in the process to select different data from the database.

I've come up with some code much like the following but have run into problems getting it to work.

Full disclaimer that I'm also not entirely sure I'm going about this in the right way. More on that in a second; first, the code:

```<code>@Configuration
@EnableBatchProcessing
public class DynamicJobConfigurer extends DefaultBatchConfigurer implements InitializingBean {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private JobRegistry jobRegistry;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private CustomJobDefinitionService customJobDefinitionService;

    private Flow injectedFlow1;
    private Flow injectedFlow2;

    public void setupJobs() throws DuplicateJobException {

        List<JobDefinition> jobDefinitions = customJobDefinitionService.getAllJobDefinitions();

        for (JobDefinition jobDefinition : jobDefinitions) {

            Job job = null;
            if (jobDefinition.getType() == 1) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow1).build()
                        .build();
            } else if (jobDefinition.getType() == 2) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow2).build()
                        .build();
            }

            if (job != null) {
                jobRegistry.register(new ReferenceJobFactory(job));
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setupJobs();
    }

    public void setInjectedFlow1(Flow injectedFlow1) {
        this.injectedFlow1 = injectedFlow1;
    }

    public void setInjectedFlow2(Flow injectedFlow2) {
        this.injectedFlow2 = injectedFlow2;
    }
}
</code>```

I have the flows that get injected defined in the XML, much like this:

```<code><batch:flow id="injectedFlow1">

    <batch:step id="InjectedFlow1.Step1" next="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step1" />
    </batch:step>

    <batch:step id="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step2" />
    </batch:step>

</batch:flow>
</code>```

So as you can see, I'm effectively kicking off the setupJobs() method (which is intended to dynamically create these job definitions) from the afterPropertiesSet() method of InitializingBean. I'm not sure that's right. It is running, but I'm not sure if there's a different entry point that's better intended for this purpose. Also I'm not sure what the point of the @Configuration annotation is to be honest.

The problem I'm currently running into is as soon as I call register() from JobRegistry, it throws the following IllegalStateException:

To use the default BatchConfigurer the context must contain no more than one DataSource, found 2.

Note: my project actually has two data sources defined. The first is the default dataSource bean which connects to the database that Spring Batch uses. The second data source is an external database, and this second one contains all the information I need to define my list of jobs. But the main one does use the default name "dataSource" so I'm not quite sure how else I can tell it to use that one.

答:
In my particular case, the solution was to actually eliminate the @Configuration
and @EnableBatchProcessing annotations from my class above. Something about these caused it to try and use the DefaultBatchConfigurer which fails when you have more than one data source defined (even if you've identified them clearly with "dataSource" as the primary and some other name for the secondary).

The @Configuration class in particular wasn't necessary because all it really does is lets your class get auto-instantiated without having to define it as a bean in the app context. But since I was doing that anyway this one was superfluous.

One of the downsides of removing @EnableBatchProcessing was that I could no longer auto-wire the JobBuilderFactory bean. So instead I just had to do to create it:

```<code>    JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
    factory.setDataSource(dataSource);
    factory.setTransactionManager(transactionManager);
    factory.afterPropertiesSet();
    jobRepository = factory.getObject();
    jobBuilderFactory = new JobBuilderFactory(jobRepository);
</code>```

Then it seems I was on the right track already by using jobRegistry.register(...) to define my jobs. So essentially once I removed those annotations above everything started working. I'm going to mark Sabir's answer as the correct one however because it helped me out.

Body:
I have an application that uses Spring Batch to define a preset number of jobs, which are currently all defined in the XML.

We add more jobs over time which requires updating the XML, however these jobs are always based on the same parent and can easily be predetermined using a simple SQL query.

So I've been trying to switch to use some combination of XML configuration and Java-based configuration but am quickly getting confused.

Even though we have many jobs, each job definition falls into essentially one of two categories. All of the jobs inherit from one or the other parent job and are effectively identical, besides having different names. The job name is used in the process to select different data from the database.

I've come up with some code much like the following but have run into problems getting it to work.

Full disclaimer that I'm also not entirely sure I'm going about this in the right way. More on that in a second; first, the code:

@Configuration
@EnableBatchProcessing
public class DynamicJobConfigurer extends DefaultBatchConfigurer implements InitializingBean {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private JobRegistry jobRegistry;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private CustomJobDefinitionService customJobDefinitionService;

    private Flow injectedFlow1;
    private Flow injectedFlow2;

    public void setupJobs() throws DuplicateJobException {

        List<JobDefinition> jobDefinitions = customJobDefinitionService.getAllJobDefinitions();

        for (JobDefinition jobDefinition : jobDefinitions) {

            Job job = null;
            if (jobDefinition.getType() == 1) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow1).build()
                        .build();
            } else if (jobDefinition.getType() == 2) {
                job = jobBuilderFactory.get(jobDefinition.getName())
                        .start(injectedFlow2).build()
                        .build();
            }

            if (job != null) {
                jobRegistry.register(new ReferenceJobFactory(job));
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setupJobs();
    }

    public void setInjectedFlow1(Flow injectedFlow1) {
        this.injectedFlow1 = injectedFlow1;
    }

    public void setInjectedFlow2(Flow injectedFlow2) {
        this.injectedFlow2 = injectedFlow2;
    }
}

I have the flows that get injected defined in the XML, much like this:

<batch:flow id="injectedFlow1">

    <batch:step id="InjectedFlow1.Step1" next="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step1" />
    </batch:step>

    <batch:step id="InjectedFlow1.Step2">
        <batch:flow parent="InjectedFlow.Step2" />
    </batch:step>

</batch:flow>

So as you can see, I'm effectively kicking off the setupJobs() method (which is intended to dynamically create these job definitions) from the afterPropertiesSet() method of InitializingBean. I'm not sure that's right. It is running, but I'm not sure if there's a different entry point that's better intended for this purpose. Also I'm not sure what the point of the @Configuration annotation is to be honest.

The problem I'm currently running into is as soon as I call register() from JobRegistry, it throws the following IllegalStateException:

To use the default BatchConfigurer the context must contain no more than one DataSource, found 2.

Note: my project actually has two data sources defined. The first is the default dataSource bean which connects to the database that Spring Batch uses. The second data source is an external database, and this second one contains all the information I need to define my list of jobs. But the main one does use the default name "dataSource" so I'm not quite sure how else I can tell it to use that one.

Body:
In my particular case, the solution was to actually eliminate the @Configuration
and @EnableBatchProcessing annotations from my class above. Something about these caused it to try and use the DefaultBatchConfigurer which fails when you have more than one data source defined (even if you've identified them clearly with "dataSource" as the primary and some other name for the secondary).

The @Configuration class in particular wasn't necessary because all it really does is lets your class get auto-instantiated without having to define it as a bean in the app context. But since I was doing that anyway this one was superfluous.

One of the downsides of removing @EnableBatchProcessing was that I could no longer auto-wire the JobBuilderFactory bean. So instead I just had to do to create it:

    JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
    factory.setDataSource(dataSource);
    factory.setTransactionManager(transactionManager);
    factory.afterPropertiesSet();
    jobRepository = factory.getObject();
    jobBuilderFactory = new JobBuilderFactory(jobRepository);

Then it seems I was on the right track already by using jobRegistry.register(...) to define my jobs. So essentially once I removed those annotations above everything started working. I'm going to mark Sabir's answer as the correct one however because it helped me out.


问:
How to limit content length response of simplified HTTP request in node?
I would like to setup the simplified HTTP request() client package to abort the download of HTTP resources that are too big.

Let's imagine request() is setup to download an url and the resource size is 5 Gigabytes. I would like request() to stop downloading after 10MB. Usually, when request gets an answer it gets all the HTTP headers and everything behind. Once you manipulate the data, you have already all the downloaded data.

In axios, there is a parameter called maxContentLength but I can't find anything similar for request().

I must also mention, that I don't it to catch an error but only download at least the headers and the beginning of the resource.

答:
As @Jackthomson pointed out in the answer of the first comment it can be done by using .on(data) If you want the headers you can take them from response and also you can check content-length header and not begin chunking.

From axios reference.

// maxContentLength defines the max size of the http response
  content allowed   maxContentLength: 2000,

This is how axios handles maxContentLength

```<code>var responseBuffer = [];
        stream.on('data', function handleStreamData(chunk) {
          responseBuffer.push(chunk);

          // make sure the content length is not over the maxContentLength if specified
          if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
            reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
              config, null, lastRequest));
          }
        });
</code>```

partial request equivalent

```<code>var request = require("request");

const MAX_CONTENT_LENGTH = 10000000;

var receivedLength = 0;

var req = request.get('http://de.releases.ubuntu.com/xenial/ubuntu-16.04.3-desktop-amd64.iso')
    .on('response', (response) => {
        if (response.headers['content-length'] && response.headers['content-length'] > MAX_CONTENT_LENGTH) {
            console.log("max content-length exceeded")
            req.abort();
        }
    })
    .on('data', (str) => {
        receivedLength += str.length;
        if (receivedLength > MAX_CONTENT_LENGTH) {
            console.log("max content-length exceeded")
            req.abort();
        }
    })
</code>```

Body:
As @Jackthomson pointed out in the answer of the first comment it can be done by using .on(data) If you want the headers you can take them from response and also you can check content-length header and not begin chunking.

From axios reference.

// maxContentLength defines the max size of the http response
  content allowed   maxContentLength: 2000,

This is how axios handles maxContentLength

var responseBuffer = [];
        stream.on('data', function handleStreamData(chunk) {
          responseBuffer.push(chunk);

          // make sure the content length is not over the maxContentLength if specified
          if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
            reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
              config, null, lastRequest));
          }
        });

partial request equivalent

var request = require("request");

const MAX_CONTENT_LENGTH = 10000000;

var receivedLength = 0;

var req = request.get('http://de.releases.ubuntu.com/xenial/ubuntu-16.04.3-desktop-amd64.iso')
    .on('response', (response) => {
        if (response.headers['content-length'] && response.headers['content-length'] > MAX_CONTENT_LENGTH) {
            console.log("max content-length exceeded")
            req.abort();
        }
    })
    .on('data', (str) => {
        receivedLength += str.length;
        if (receivedLength > MAX_CONTENT_LENGTH) {
            console.log("max content-length exceeded")
            req.abort();
        }
    })


问:
How to unhide a hidden table in PHPMyAdmin 4+?
I really thought there would be more answers on this already.  However, I'm using PhPMyAdmin 4.3, and I accidently clicked the light bulb to hide a table.  Now I can't find where to get it back.

Anyone??

Thanks.. sorry if this is obvious.

答: in version 4.7 of phpmyadmin, you would not see a lightbulb but instead you will see at the right side of the database name, a symbole resembling an "eye". click on it. it will open a window displaying a list of your hidden tables then you will see a "show". click on "show". that's all.</p>


问:
Parameters are not set inside NHibernate interceptor
I am trying to use interceptor to add WITH (NO LOCK) for some queries (not for all queries, so ReadUncommitted is not a choice).
Code looks like this:

```<code>var rawSql = sql.ToString();
if (!rawSql.Contains(IQueryOverExtensions.QueryHintNoLockString))
    return sql;

var noWhere = rawSql.Substring(0, rawSql.IndexOf(WhereKeyword, StringComparison.InvariantCulture));
var from = noWhere.Substring(noWhere.IndexOf(FromKeyword, StringComparison.InvariantCulture));
var fromWithNoLock = from.Replace("_ ", $"_ {WithNoLock} ");

var sqlWithNoLock = rawSql.Replace(from, fromWithNoLock);

return base.OnPrepareStatement(new SqlString(sqlWithNoLock));
</code>```

Here, I take part form FROM clause to WHERE clause and to each alias add WITH (NO LOCK)

The issue is, that the final SQL's parameters are all "?" and exception is thrown that SQL is not valid. Why parameters are not filled in and how to fix it?
Thanks in advance

答: Finally I got it. I had to get number of parameters by calling sql.GetParameterCount() and then replace all question marks with @p0, @p1, @p2, etc.</p>

Body:
I am trying to use interceptor to add WITH (NO LOCK) for some queries (not for all queries, so ReadUncommitted is not a choice).
Code looks like this:

var rawSql = sql.ToString();
if (!rawSql.Contains(IQueryOverExtensions.QueryHintNoLockString))
    return sql;

var noWhere = rawSql.Substring(0, rawSql.IndexOf(WhereKeyword, StringComparison.InvariantCulture));
var from = noWhere.Substring(noWhere.IndexOf(FromKeyword, StringComparison.InvariantCulture));
var fromWithNoLock = from.Replace("_ ", $"_ {WithNoLock} ");

var sqlWithNoLock = rawSql.Replace(from, fromWithNoLock);

return base.OnPrepareStatement(new SqlString(sqlWithNoLock));

Here, I take part form FROM clause to WHERE clause and to each alias add WITH (NO LOCK)

The issue is, that the final SQL's parameters are all "?" and exception is thrown that SQL is not valid. Why parameters are not filled in and how to fix it?
Thanks in advance


问:
Returning the argument from a list comprehension that's result satisfies <something>
It's a horrible title, I know; the basic explanation of what I mean is:

```<code>y=min([func(x) for x in range(z)])
</code>```

As is, y contains the value of the output of func(x_min). (x_min might not actually be the smaller value in the range).

Basically, I'm looking for a way to get x_min in this generic case in a more pythonic way. Any ideas?

UPDATE:
From SilentGhosts answer, (RTFM...), the equivalent of the above would be;

```<code>x_min=min(range(z),key=func)
</code>```

答:
Use key argument:

```<code>min(iterable, key=func)
</code>```

Body:
It's a horrible title, I know; the basic explanation of what I mean is:

y=min([func(x) for x in range(z)])

As is, y contains the value of the output of func(x_min). (x_min might not actually be the smaller value in the range).

Basically, I'm looking for a way to get x_min in this generic case in a more pythonic way. Any ideas?

UPDATE:
From SilentGhosts answer, (RTFM...), the equivalent of the above would be;

x_min=min(range(z),key=func)

Body:
Use key argument:

min(iterable, key=func)


问:
Choosing direction in DFS maze generation
I've recently implemented a DFS maze generation algorithm according to the standard procedure:

Fill a maze with walls

Choose a starting square

Choose a random neighbor and break the wall between that neighbor if that neighbor hasn't already been explored

Recursively generate the rest of the maze by starting at the neighbor

I've been told that I may be able to "aesthetically" improve the generated mazes by implementing a rule for choosing which neighbor to explore (north, south, east or west) that isn't just completely random, but I'm having a hard time wrapping my head around what kind of rule that would be. Are there any methods out there that involve choosing a direction non-randomly, or randomly with weights? I haven't been able to find any so far.

答:
Yes, there are many indeed.

DFS is uninformed search, so I would recommend having a look at informed search and how they are applicable to mazes.


问:
Jhipster 4 angular 4 ng2-file-upload return error 403 access forbidden becauze of CSRF
ng2-file-upload doesn't send CSRF access tokens alongside the upload request, so i get 403 access forbidden and my upload request is just rejected at once.</p>

答:
If you token gets changed more frequently, you can also set it per request. In the below example the CSRF token is taken from a cookie. This can be done in your component constructor.</p>

```<code>this.uploader = new FileUploader({ url: URL });
this.uploader.onBeforeUploadItem = (fileItem) => {
    fileItem.headers.push({name: 'X-XSRF-TOKEN', value: cookieService.getCookie('XSRF-TOKEN')});
    return fileItem;
};
</code>```

Body:
If you token gets changed more frequently, you can also set it per request. In the below example the CSRF token is taken from a cookie. This can be done in your component constructor.

this.uploader = new FileUploader({ url: URL });
this.uploader.onBeforeUploadItem = (fileItem) => {
    fileItem.headers.push({name: 'X-XSRF-TOKEN', value: cookieService.getCookie('XSRF-TOKEN')});
    return fileItem;
};


问:
How to do unit testing on timer functions on a microcontroller

I am new to the concept of unit testing, and I am currently trying to get more comfortable with it.

I have to do unit testing on a timer driver for a microcontroller written in C. Now, I heard that a unit test on a function should not depend on the outcome of another function. My problem is, how can we test a function that is supposed to stop a timer in these conditions ? Don't we need to start the timer, heck, we even need to initialize it !

I would like to know at which level we need to consider our unit test ; is it at the level of one function (in that case, we get the problem above), or is it at the level of the driver itself (in that case, we can use multiple functions of the driver in one unit test) ?

I would love to hear from more experienced people their feeling about this subject, as I feel I'm going nowhere at the moment.

答:
I would approach this as follows:

You can test each function independently to check that it adheres to its interface and handles out-of-bound values of parameters (if that is a requirement; the converse is that the requirement is with the caller not to call it out-of-bounds).

You can also do a code inspection on each function.

Then you can unit test the whole unit, in one way from the higher level routines: can it be called for intialization and set-up (wand here out-of-bounds conditions must be handled) and can any call-backs be called and are they called properly.

For hardware related elements you can either simulate it or create a dedicated hardware environment for the testing (test harness, test bed).


问:
How can I add common tags to all my Prometheus Metrics using the Java Client
My Java application exposes Prometheus metrics. I want to add extra tags to each metric so when they are scraped I can use those tags in a query.</p>

答:
The best way to add tags is to use the Prometheus service discovery. This keeps these tags out of your application code and keeps it from being concerned about where it exists.

However sometime if you absolutely need those extra tags (due to the service having extra insight that Prometheus service discovery isn't surfacing) you can't use the Java Simple Client (the Go client does support this though)

I turns out this feature is offered via a Micrometer feature called 'Common Tags' which wraps the Prometheus Java client. You setup your client so the tags are available via a config() call.

```<code>registry.config().commonTags("stack", "prod", "region", "us-east-1");
</code>```

Body:
The best way to add tags is to use the Prometheus service discovery. This keeps these tags out of your application code and keeps it from being concerned about where it exists.

However sometime if you absolutely need those extra tags (due to the service having extra insight that Prometheus service discovery isn't surfacing) you can't use the Java Simple Client (the Go client does support this though)

I turns out this feature is offered via a Micrometer feature called 'Common Tags' which wraps the Prometheus Java client. You setup your client so the tags are available via a config() call.

registry.config().commonTags("stack", "prod", "region", "us-east-1");


问:
Angular2 Update form value inside FormArray
I need update 'lat' and 'lon' values inside FormArray:

```<code>initRows() {
        return this._fb.group({
            address: "",
            lat: 0,
            lon: 0,
        });
   }

 initForm() {
        this.searchForm = this._fb.group({
        addresses: this._fb.array([this.initRows()]),
    });
</code>```

I need update them after callback:

```<code> this.someService.getData().subscribe(
                  (response) => {this.data = response.json()
                                 this.lon = this.data.x;
                                 this.lat = this.data.y;
                                // UPDATE MY 'lat' and 'lon'
                  },
                  (error) => console.log('ERROR: ' + error)
          );
</code>```

form.value object:

```<code>{

  "addresses": [
    {
      "address": {
        "text": "Weberweg, 58566, Kierspe, Nordrhein-Westfalen, DEU"
     },
      "lat": 0,
      "lon": 0
    },
     {
      "address": {
        "text": "Weberweg, 58566, Kierspe, Nordrhein-Westfalen, DEU"
     },
      "lat": 0,
      "lon": 0
    }
  ]
}
</code>```

P.S. 'lat' and 'lon' not an inputs, just data

答:
I'm not sure is it "right" way, but you can do this: </p>

```<code>    /* getter for addresses.
    get addresses() {
       this.seachForm.controls.addresses as FormArray;
    }

    /* function for loading data */
    public loadData() {
        this.someService.getData().subscribe(
           (response) => {
                          this.data = response.json()
                          this.lon = this.data.x; // it is global lon like I understood
                          this.lat = this.data.y; // it is global lat like I understood
                          this.addresses.controls.forEach((address) => {
                                 address.get('lat').setValue(this.lat);
                                 address.get('lon').setValue(this.lon);
                          }),
           (error) => console.log('ERROR: ' + error)
      );
}
</code>```

<p>Hope I got you right and this answer is helpful for you. </p>

Body:
I need update 'lat' and 'lon' values inside FormArray:

initRows() {
        return this._fb.group({
            address: "",
            lat: 0,
            lon: 0,
        });
   }

 initForm() {
        this.searchForm = this._fb.group({
        addresses: this._fb.array([this.initRows()]),
    });

I need update them after callback:

 this.someService.getData().subscribe(
                  (response) => {this.data = response.json()
                                 this.lon = this.data.x;
                                 this.lat = this.data.y;
                                // UPDATE MY 'lat' and 'lon'
                  },
                  (error) => console.log('ERROR: ' + error)
          );

form.value object:

{

  "addresses": [
    {
      "address": {
        "text": "Weberweg, 58566, Kierspe, Nordrhein-Westfalen, DEU"
     },
      "lat": 0,
      "lon": 0
    },
     {
      "address": {
        "text": "Weberweg, 58566, Kierspe, Nordrhein-Westfalen, DEU"
     },
      "lat": 0,
      "lon": 0
    }
  ]
}

P.S. 'lat' and 'lon' not an inputs, just data

Body:
I'm not sure is it "right" way, but you can do this:

    /* getter for addresses.
    get addresses() {
       this.seachForm.controls.addresses as FormArray;
    }

    /* function for loading data */
    public loadData() {
        this.someService.getData().subscribe(
           (response) => {
                          this.data = response.json()
                          this.lon = this.data.x; // it is global lon like I understood
                          this.lat = this.data.y; // it is global lat like I understood
                          this.addresses.controls.forEach((address) => {
                                 address.get('lat').setValue(this.lat);
                                 address.get('lon').setValue(this.lon);
                          }),
           (error) => console.log('ERROR: ' + error)
      );
}

Hope I got you right and this answer is helpful for you.


问:
Is it possible to apply refactoring using OmniPascal?
I've installed OmniPascal extension in Visual Studio Code to use it for coding in Delphi and I am loving it. Code completion, parameters hint, go to declarations, all working 100%! Nonetheless, I am missing the refactor commands like rename (CTRL+SHIFT+E). Is that already implemented in OmniPascal?</p>

答:
There are currently no refactoring tools implemented in OmniPascal. Rename and Extract method are planned for the future but there are other features that need to be implemented before OmniPascal can turn into a reliable refactoring tool.

As long as OmniPascal doesn't handle all language features correctly (like with-blocks or class helpers) the rename command would produce wrong results. You don't want to work with such a refactoring tool.


问:
Is it possible to run each layer in a cnn parallely in either caffe or tensorflow?
I want to run each layer of a trained CNN in parallel to reduce the computation time during forward propagation ( Basically I want to run the CNN for a real time application involving a camera without affecting the FPS too much ). I will keep an input queue and an output queue for each layer. Each layer can process a blob from input layer and dump it in the output layer ( This can logically be done in parallel ). Output queue for each layer will work as the Input Queue for the following layer. And then I will collect all the outputs from the output queue ( its going to be a binary label ) of the final layer and process them. So my question is that is it possible to run each layer of a CNN in parallel in either Caffe or Tensorflow to implement this.</p>

答:
Don't know about TF.<br>
About caffe - this sounds like a bad idea. Putting queues and sync mechanism between the layers will only slow you down (especially if you run on GPU and sync through CPU constructs). Caffe is design to perform the forward pass sequentially and to do it FAST. Why do you expect parallelism to help you run it faster? </p>

Body:
Don't know about TF.

About caffe - this sounds like a bad idea. Putting queues and sync mechanism between the layers will only slow you down (especially if you run on GPU and sync through CPU constructs). Caffe is design to perform the forward pass sequentially and to do it FAST. Why do you expect parallelism to help you run it faster?


问:
Internet Explorer 11 - AJAX Call not firing
I am stuck in the middle of a bug. I began to use BrowserStack to validate my current project against Windows IE and EDGE and I got a particular issue with IE 11.

I first got an issue that I solved which was that FormData did not have any .get() methods, and I used the NPM formdata-polyfill for that.

I am working on a native JS login form, using FormData and XMLHTTPRequest, and it seems that the AJAX call is not firing at all.

When clicking on the submit button, instead of sending to my particular login URL, the POST request is fired to the current page itself.

So, obviously, no event is catched and no JavaScript is executed.

My JavaScript is compiled using WebPack, and the lines I use to get the login form and attach proper events to it are the following :

```<code>    var formLogin = document.querySelector( "#form-login" );

    if ( formLogin !== null )
    {
        var email    = document.getElementById( "email" );

        formLogin.addEventListener( "submit", _.validateLoginForm );
        _.formInstance.init( formLogin );

        _.inputUtil.disableField( '#btn-submit-email' );
        _.inputUtil.disableField( '#btn-submit-password' );

        utils.addAndDispatchEvent( '#email', 'input', _.inputUtil.disableSubmitIfFieldIsEmpty( '#btn-submit-email' ) );
        utils.addAndDispatchEvent( '#password', 'input', _.inputUtil.disableSubmitIfFieldIsEmpty( '#btn-submit-password') );

        email.addEventListener( "invalid", _.onInvalidEmail );
    }
</code>```

```

The JS file is properly loaded to.

I do not get where it can come from as it works well on any others browsers ( including Edge after I got the polyfill ).

If you have any ideas, let me know !

Thanks for listening.

答:
My issue here was that I needed to override my call to different e.preventDefault()
by
e.preventDefault ? e.preventDefault() : ( e.returnValue = false );

Which is better supported on IE.

Got this information from the following post : event.preventDefault() function not working in IE

Then I got aditionnal issues with the Event and CustomEvent class not properly supported so I added a few polyfills by adding Babel Transpiler to avoid using ES2015 but compatible JS.

Still having some issues with supporting IE 11 completely but this one is fixed.

Body:
I am stuck in the middle of a bug. I began to use BrowserStack to validate my current project against Windows IE and EDGE and I got a particular issue with IE 11.

I first got an issue that I solved which was that FormData did not have any .get() methods, and I used the NPM formdata-polyfill for that.

I am working on a native JS login form, using FormData and XMLHTTPRequest, and it seems that the AJAX call is not firing at all.

When clicking on the submit button, instead of sending to my particular login URL, the POST request is fired to the current page itself.

So, obviously, no event is catched and no JavaScript is executed.

My JavaScript is compiled using WebPack, and the lines I use to get the login form and attach proper events to it are the following :

    var formLogin = document.querySelector( "#form-login" );

    if ( formLogin !== null )
    {
        var email    = document.getElementById( "email" );

        formLogin.addEventListener( "submit", _.validateLoginForm );
        _.formInstance.init( formLogin );

        _.inputUtil.disableField( '#btn-submit-email' );
        _.inputUtil.disableField( '#btn-submit-password' );

        utils.addAndDispatchEvent( '#email', 'input', _.inputUtil.disableSubmitIfFieldIsEmpty( '#btn-submit-email' ) );
        utils.addAndDispatchEvent( '#password', 'input', _.inputUtil.disableSubmitIfFieldIsEmpty( '#btn-submit-password') );

        email.addEventListener( "invalid", _.onInvalidEmail );
    }

```

The JS file is properly loaded to.

I do not get where it can come from as it works well on any others browsers ( including Edge after I got the polyfill ).

If you have any ideas, let me know !

Thanks for listening.


问:
IF_EX_ME_CD_TRIGGER not exist in ABAP 730
I'm trying to copy a project from an ABAP740's system to another 730, and I found that the interface class  IF_EX_ME_CD_TRIGGER doesn't exist in the 730 :

How can I fix this incompatibility ?

答:
It's not broken, each version brings new enhancements so this must be new in a version >7.30. The easiest thing to do it copy it from another system but honestly, I doubt if that is missing it will be the only thing missing.

So you have a couple of options,

look in the SAP marketplace and maybe just maybe it is included in a note that you can add to your system.

More then likely though I would say the development is not downward compatible if it is your own then create your own Z Interface or copy it from another system into this system.


问:
What would be the best approach for outlining or dropshadowing a font?
I'm not finding any support for dropshadow or outline of a font in Sprite Kit. For the dropshadow,  I'm guessing I could create a second SKLabelNode and offset it behind the other.

Is there some way that I could utilize a SKEffectNode for the outline or dropshadow ? Possibly make the SKLabelNode a child of the SKEffectNode ?

update :

I was able to get a decent dropshadow using a second SKLabelNode behind the first, that is black and offset. Still interested in other potential options, but that seems to work well.

答: Since iOS 11 SKLabelNode has attributedText property. You need to specify strokeColor, strokeWidth and don't forget font and foregroundColor.


问:
ReactJS: How to render rows dynamically

I am facing an issue to order the rows of a fetched API data dynamically, i.e if the rows data within the API is changed (+/- row) to render it automatically. I am trying to print the data fetched from an API into a table. Anyhow the columns are well printed dynamically, but the function that I am using for columns this.state.columns.map(( column, index ) => doesn't function in the same way for the rows. I think i am misleading the ES6 standard, but I am not sure. Here is how it's look like, if the rows are not hardcoded.

Here is my code sample:

```<code>class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: []
        }
    }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (
            <div id="container" className="container">
                <h1>Final Table with React JS</h1>
                <table className="table">
                    <thead>
                        <tr> {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( <th>{column}</th> )
                            }
                            )
                        }
                        </tr>
                    </thead>
                    <tbody> {
                        this.state.rows.map(( row ) => (
                            <tr>
                                <td>{row[0]}</td>
                                <td>{row[1]}</td>
                                <td>{row[2]}</td>
                                <td>{row[3]}</td>
                                <td>{row[4]}</td>
                                <td>{row[5]}</td>
                                <td>{row[6]}</td>
                                <td>{row[7]}</td>
                                <td>{row[8]}</td>
                                <td>{row[9]}</td>
                                <td>{row[10]}</td>
                                <td>{row[11]}</td>
                                <td>{row[12]}</td>
                                <td>{row[13]}</td>
                                <td>{row[14]}</td>
                                <td>{row[15]}</td>
                            </tr>
                        ) )
                    }
                    </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
</code>```

Instead, I was able to print the rows harcoded, if I give value to the 'td' elements, but I want to print it dynamically, in case the data within the API has been changed.

You are welcome to contribute directly to my Repo: Fetching API data into a table

Here is how looks like my example, when the rows values has been hardcoded within 'td' elements.

Any suggestions will be appreciated!

答:
Just as you are iterating over columns and rows you could add an additional loop for iterating over row cells.
For example:

```<code>this.state.rows.map(row => (
  <tr>{row.map(cell => (
    <td>{cell}</td>
   ))}
  </tr>
))
</code>```

Note that you probably want to add a key prop:

Keys help React identify which items have changed, are added, or are
  removed. Keys should be given to the elements inside the array to give
  the elements a stable identity

Title: ReactJS: How to render rows dynamically

Body:
I am facing an issue to order the rows of a fetched API data dynamically, i.e if the rows data within the API is changed (+/- row) to render it automatically. I am trying to print the data fetched from an API into a table. Anyhow the columns are well printed dynamically, but the function that I am using for columns this.state.columns.map(( column, index ) => doesn't function in the same way for the rows. I think i am misleading the ES6 standard, but I am not sure. Here is how it's look like, if the rows are not hardcoded.

Here is my code sample:

class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: []
        }
    }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (

Final Table with React JS

 {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( {column}	 )
                            }
                            )
                        }

 {
                        this.state.rows.map(( row ) => (

                                {row[0]}
                                {row[1]}
                                {row[2]}
                                {row[3]}
                                {row[4]}
                                {row[5]}
                                {row[6]}
                                {row[7]}
                                {row[8]}
                                {row[9]}
                                {row[10]}
                                {row[11]}
                                {row[12]}
                                {row[13]}
                                {row[14]}
                                {row[15]}

                        ) )
                    }

        )
    }
}

ReactDOM.render(
<App />
, document.querySelector( 'body' ) );

Instead, I was able to print the rows harcoded, if I give value to the 'td' elements, but I want to print it dynamically, in case the data within the API has been changed.

You are welcome to contribute directly to my Repo: Fetching API data into a table

Here is how looks like my example, when the rows values has been hardcoded within 'td' elements.

Any suggestions will be appreciated!

Body:
Just as you are iterating over columns and rows you could add an additional loop for iterating over row cells.
For example:

this.state.rows.map(row => (
  <tr>{row.map(cell => (
    <td>{cell}</td>
   ))}
  </tr>
))

Note that you probably want to add a key prop:

Keys help React identify which items have changed, are added, or are
  removed. Keys should be given to the elements inside the array to give
  the elements a stable identity


问:
Interview question: Check if one string is a rotation of other string
A friend of mine was asked the following question today at interview for the position of software developer:

Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ?

Example:

If s1 = "stackoverflow" then the following are some of its rotated versions:

```<code>"tackoverflows"
"ackoverflowst"
"overflowstack"
</code>```

where as "stackoverflwo" is not a rotated version.

The answer he gave was:

Take s2 and find the longest prefix that is a sub string of s1, that will give you the point of rotation. Once you find that point, break s2 at that point to get s2a and s2b, then just check if concatenate(s2a,s2b) == s1

It looks like a good solution to me and my friend. But the interviewer thought otherwise. He asked for a simpler solution. Please help me by telling how would you do this in Java/C/C++ ?

Thanks in advance.

答: Join string1 with string2 and use KMP algorithm to check whether string2 is present in newly formed string. Because time complexity of KMP is lesser than substr.

Body:
A friend of mine was asked the following question today at interview for the position of software developer:

Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ?

Example:

If s1 = "stackoverflow" then the following are some of its rotated versions:

"tackoverflows"
"ackoverflowst"
"overflowstack"

where as "stackoverflwo" is not a rotated version.

The answer he gave was:

Take s2 and find the longest prefix that is a sub string of s1, that will give you the point of rotation. Once you find that point, break s2 at that point to get s2a and s2b, then just check if concatenate(s2a,s2b) == s1

It looks like a good solution to me and my friend. But the interviewer thought otherwise. He asked for a simpler solution. Please help me by telling how would you do this in Java/C/C++ ?

Thanks in advance.


问:
how can I enforce english language in a git commit message?
Is it possible to enforce english in a commit message?

At the moment, git commit messages in our projects are a mix of 2 languages and the team keeps forgetting git messages good practices. Could we at least show a warning?

Thanks

答:
If you can find a program that looks at a block of text and tells you whether it believes that block of text to be in a language other than English, I suppose you could set up hooks.

Finding/recommending a tool that processes text in that way would be off-topic for SO; so I'll say only that I think it will be challenging.  But supposing you have one, you would have two options.  You could do one or both of the following:

First, you could create a pre-commit hook.  This is a hook that runs locally, and therefore must be set up by each developer.  (Which means it only gets run if the developer willingly cooperates.)  The advantage is that any problem gets caught right away.

Second, you could create a pre-receive hook on your shared repo(s) (e.g. typically origin), assuming it's hosted in a way that allows you to set up hooks.  This has the advantage that it can't be circumvented either by accident when setting up a new local repo, or by an uncooperative developer.  But, if a developer makes several commits with unacceptable messages locally and then tries to push, they'll have to do something like an interactive rebase to edit all of the messages before they can push.

You can use the two in combination, of course, so that the pre-receive hook enforces the rule's integrity in the shared repo, and the desire to avoid the need to rework gives developers an incentive to set up the local pre-commit hook as well.

If you want to pursue this, I'd recommend you look over the git hook documentation: https://git-scm.com/docs/githooks


问:
New Urls patterns and multiple variables with the same name
I'm using Django 2.0 type of urls, and I have urls with multiple variables in them, with the same name. I'm using also ClassBasedView

```<code>path('/companies/<int:pk>/products/<int:pk>/', AccountCompanyProductDetailView.as_view()
</code>```

I'm using pk because is the primary key and CBV will know how to use it (similar for other Model fields).

If I use other names, CBV will not know what to search.

In a CBV how can I get the parameters and know which is which. ?
How Django knows pk from which Model I need in each position ?

答:
Django does not know how to handle this. You need to rename your parameters and access them in your CBV.
This could look like the following:

urls.py:

```<code>path('/companies/<int:pk1>/products/<int:pk2>/', AccountCompanyProductDetailView.as_view())
</code>```

views.py:

```<code>class AccountCompanyProductDetailView(DetailView):
    model = Product

    def get_object(self):
        pk1 = self.kwargs['pk1']
        pk2 = self.kwargs['pk2']
        company = get_object_or_404(Company, pk=pk1)
        product = get_object_or_404(Product, pk=pk2)
        return product
</code>```

You would need to do this in other views too. Override the according methods like get_queryset. Access the kwargs as shown above.

Body:
I'm using Django 2.0 type of urls, and I have urls with multiple variables in them, with the same name. I'm using also ClassBasedView

path('/companies/<int:pk>/products/<int:pk>/', AccountCompanyProductDetailView.as_view()

I'm using pk because is the primary key and CBV will know how to use it (similar for other Model fields).

If I use other names, CBV will not know what to search.

In a CBV how can I get the parameters and know which is which. ?
How Django knows pk from which Model I need in each position ?

Body:
Django does not know how to handle this. You need to rename your parameters and access them in your CBV.
This could look like the following:

urls.py:

path('/companies/<int:pk1>/products/<int:pk2>/', AccountCompanyProductDetailView.as_view())

views.py:

class AccountCompanyProductDetailView(DetailView):
    model = Product

    def get_object(self):
        pk1 = self.kwargs['pk1']
        pk2 = self.kwargs['pk2']
        company = get_object_or_404(Company, pk=pk1)
        product = get_object_or_404(Product, pk=pk2)
        return product

You would need to do this in other views too. Override the according methods like get_queryset. Access the kwargs as shown above.


问:
Why does C++17 GCC compiler gives warning about undefined?
According to C++17, there is no guarantee for order of evaluation in following expression. It is called unspecified behaviour.

```<code>int i = 0;
std::cout<<i<<i++<<std::endl;
</code>```

C++17 GCC compiler gives following warning: Live Demo

```<code>prog.cc: In function 'int main()':
prog.cc:6:20: warning: operation on 'i' may be undefined [-Wsequence-point]
     std::cout<<i<<i++<<std::endl;
</code>```

I don't understand, in c++17 above express no longer undefined behaviour, then Why does compiler gives warning about undefined?

答:
Seems like gcc gives a warning because this is a corner case, or at least very close to being one. Portability seems to be one concern.

From the page https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this warning will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++.

The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at http://gcc.gnu.org/readings.html.

Body:
According to C++17, there is no guarantee for order of evaluation in following expression. It is called unspecified behaviour.

int i = 0;
std::cout<<i<<i++<<std::endl;

C++17 GCC compiler gives following warning: Live Demo

prog.cc: In function 'int main()':
prog.cc:6:20: warning: operation on 'i' may be undefined [-Wsequence-point]
     std::cout<<i<<i++<<std::endl;

I don't understand, in c++17 above express no longer undefined behaviour, then Why does compiler gives warning about undefined?


问:
Why am I not getting "Prevent this page from creating additional dialogs" as part of prompt window in Google Chrome?
When run the same on Microsoft edge I am able to see it.
What do I need to change in the settings of Chrome browser?enter image description here

This is my code:

```<code>alert("Hello from the JS file");
var age;
var ageroot;

age=prompt("Enter your age");
</code>```

答:
The issue has been mentioned here: https://productforums.google.com/forum/#!topic/chrome/drS39waj6ik;context-place=topicsearchin/chrome/Prevent$20this$20page$20from$20creating$20additional$20dialogs

And a bug is reported for the same: https://bugs.chromium.org/p/chromium/issues/detail?id=721138

Body:
When run the same on Microsoft edge I am able to see it.
What do I need to change in the settings of Chrome browser?enter image description here

This is my code:

alert("Hello from the JS file");
var age;
var ageroot;

age=prompt("Enter your age");


问:
How can we deal with different HTTP response from error?
I'm working on simple authentication with my backend.

My action can't handle try-catch and I have no idea why it's not working as I expected because it worked a month ago.

```<code>export const doAuthLogin = ( username, password ) => async dispatch => {
  console.log('passing action'); <- print 'passing action'
  let response = await axios.post(`${ROOT_URL}/rest-auth/login/`, {
    username,
    password,
  }); <- shows 400 error on console (Expo)

  console.log(response.status); <- print nothing // well 200 can prints status here
  console.log('doesn't work); <- print nothing

  if (response.status === 200) { <- doesn't execute
</code>```

答:
I think you have to specify that it's an async function in the upper function as well.

```<code>export const doAuthLogin = async (username, password) => async dispatch => {
</code>```

If that doesn't work, please create a jsfiddle/codepen with your entire codebase so we can investigate further.

Body:
I'm working on simple authentication with my backend.

My action can't handle try-catch and I have no idea why it's not working as I expected because it worked a month ago.

export const doAuthLogin = ( username, password ) => async dispatch => {
  console.log('passing action'); <- print 'passing action'
  let response = await axios.post(`${ROOT_URL}/rest-auth/login/`, {
    username,
    password,
  }); <- shows 400 error on console (Expo)

  console.log(response.status); <- print nothing // well 200 can prints status here
  console.log('doesn't work); <- print nothing

  if (response.status === 200) { <- doesn't execute

Body:
I think you have to specify that it's an async function in the upper function as well.

export const doAuthLogin = async (username, password) => async dispatch => {

If that doesn't work, please create a jsfiddle/codepen with your entire codebase so we can investigate further.


问:
Company name on iOS Setting page
After a long search I didn't find anything that explains how this work.

Anyone knows, how to set Company name to our app So that it can be visible on the iOS Settings page.

I think that certificate name doesn't linked to this.

答: It is not possible to set the company name in the iOS settings page.</p>

Title: Company name on iOS Setting page


问:
Run Jenkins parallel stages across different nodes using declarative syntax
Managed to successfully run integration tests in parallel on the same node and I now I would like to distribute them across different nodes. In the example below I want stages IT 1 and IT 2 to run on different nodes leaving IT 3 to run on the original node. Tried several combinations by using node as a parent of stage('IT 1') and node as a child but I get syntax errors for both. What is the proper syntax to achieve this?

```<code>pipeline {

  agent { label '!master' }

  stages {
    stage('Integration Tests') {
      parallel {
        stage('IT 1 (slow)') {
          steps {
            sh 'run-it-1.sh'
          }
        }
        stage('IT 2 (slow)') {
          steps {
            sh 'run-it-2.sh'
          }
        }
        stage('IT 3 (quick)') {
          steps {
            sh 'run-it-3.sh'
          }
        }
      }
    }
  }
}
</code>```

Edit: Using label instead of node works for declarative pipelines. Example below:

```<code>stage('IT 1 (slow)') {
  agent { label '!master' }
  steps {
    sh 'run-it-1.sh'
  }
}
</code>```

答:
Since Declarative version 1.2, you can directly declare the kind of agent you want to use for each parallel stages : https://jenkins.io/blog/2017/09/25/declarative-1/

Not tested this specific use case, but I assume that if you don't declare any agent{} for stage "IT 3", it will be executed on the original node.

Hopefully it helps.

Body:
Managed to successfully run integration tests in parallel on the same node and I now I would like to distribute them across different nodes. In the example below I want stages IT 1 and IT 2 to run on different nodes leaving IT 3 to run on the original node. Tried several combinations by using node as a parent of stage('IT 1') and node as a child but I get syntax errors for both. What is the proper syntax to achieve this?

pipeline {

  agent { label '!master' }

  stages {
    stage('Integration Tests') {
      parallel {
        stage('IT 1 (slow)') {
          steps {
            sh 'run-it-1.sh'
          }
        }
        stage('IT 2 (slow)') {
          steps {
            sh 'run-it-2.sh'
          }
        }
        stage('IT 3 (quick)') {
          steps {
            sh 'run-it-3.sh'
          }
        }
      }
    }
  }
}

Edit: Using label instead of node works for declarative pipelines. Example below:

stage('IT 1 (slow)') {
  agent { label '!master' }
  steps {
    sh 'run-it-1.sh'
  }
}