问:
Swap index of an array with another using pointers, in C language
Could anyone help me with my solution to this code? I have to trade the index of an array with another, using pointers.  This was the solution I created`

```<code>double *swap_double_array_ptr(double *pi, int pos1, int pos2) {
         double *p = &pos1;
         double *q = &pos2;
         double aux=0;
         aux = *(pi + p);
         *(p + pi) = *(q+ pi);
         *(q + pi) = aux;
</code>```

}

The compiler says invalid operand. Can someone help me? I do not know any other solution. Please be gentle, I am new to pointers.
 Thank you.

答:
```<code>void swap_double_array_ptr(double *pi, int pos1, int pos2) {
         double aux;
         aux = *(pi + pos1);
         *(pos1 + pi) = *(pi+ pos2);
         *(pos2 + pi) = aux;
}
</code>```

You were doing it all wrong by using the adress of the index variables.

You were trying to add two pointers which is not defined in c.

aux = *(pi + p); pi+p -> Not allowed

To summarize and provide some points:-

Addition of two pointer variables not allowed.

Subtraction of two pointer variables is allowed. (offset calculation)

As it returns nothing you need to make the function's return type void.

Body:
Could anyone help me with my solution to this code? I have to trade the index of an array with another, using pointers.  This was the solution I created`

double *swap_double_array_ptr(double *pi, int pos1, int pos2) {
         double *p = &pos1;
         double *q = &pos2;
         double aux=0;
         aux = *(pi + p);
         *(p + pi) = *(q+ pi);
         *(q + pi) = aux;

}

The compiler says invalid operand. Can someone help me? I do not know any other solution. Please be gentle, I am new to pointers.
 Thank you.

Body:
void swap_double_array_ptr(double *pi, int pos1, int pos2) {
         double aux;
         aux = *(pi + pos1);
         *(pos1 + pi) = *(pi+ pos2);
         *(pos2 + pi) = aux;
}

You were doing it all wrong by using the adress of the index variables.

You were trying to add two pointers which is not defined in c.

aux = *(pi + p); pi+p -> Not allowed

To summarize and provide some points:-

Addition of two pointer variables not allowed.

Subtraction of two pointer variables is allowed. (offset calculation)

As it returns nothing you need to make the function's return type void.


来源: stackexchange

问:
Sort JavaScript array of Objects by two properties and given order
I have this JavaScript array of Objects:

```<code>data = [
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
]
</code>```

and I would like to sort it both by 'provider' (the three "This" before the three "All") and by 'measure' (first quartile, median, third quartile), so the resulting array will look like:

```<code>data = [
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
]
</code>```

I have written a function as an argument to .sort(), and it does return the array sorted by 'provider', but then when I feed it into the same function with measure as an argument (thankfully, first_quartile, median, third_quartile are already alphabetically sorted the way I want them) - the sorting gets broken. How can I go about doing it?

EDIT
The functions I have been using:

```<code>var compare_prv = function(a,b) {
  if (a.provider < b.provider){
    return 1;
  }
  return 0;
}

var compare_meas = function(a,b) {
  if (a.measure < b.measure){
    return -1;
  }
  return 0;
}
</code>```

答:
It sounds like you are doing:

```<code>data.sort(function(a, b) {
    //sort by provider
});

data.sort(function(a, b) {
    //sort by measure
});
</code>```

But what you want to do is:

```<code>data.sort(function(a, b) {
    //sort by provider, but if they are equal, sort by measure
});
</code>```

So something like

```<code>data.sort(function(a, b) {
    if (a.provider === b.provider) {
        return a.measure.localeCompare(b.measure);
    }
    return b.provider.localeCompare(a.provider);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this JavaScript array of Objects:

data = [
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
]

and I would like to sort it both by 'provider' (the three "This" before the three "All") and by 'measure' (first quartile, median, third quartile), so the resulting array will look like:

data = [
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
]

I have written a function as an argument to .sort(), and it does return the array sorted by 'provider', but then when I feed it into the same function with measure as an argument (thankfully, first_quartile, median, third_quartile are already alphabetically sorted the way I want them) - the sorting gets broken. How can I go about doing it?

EDIT
The functions I have been using:

var compare_prv = function(a,b) {
  if (a.provider < b.provider){
    return 1;
  }
  return 0;
}

var compare_meas = function(a,b) {
  if (a.measure < b.measure){
    return -1;
  }
  return 0;
}

Body:
It sounds like you are doing:

data.sort(function(a, b) {
    //sort by provider
});

data.sort(function(a, b) {
    //sort by measure
});

But what you want to do is:

data.sort(function(a, b) {
    //sort by provider, but if they are equal, sort by measure
});

So something like

data.sort(function(a, b) {
    if (a.provider === b.provider) {
        return a.measure.localeCompare(b.measure);
    }
    return b.provider.localeCompare(a.provider);
});


问:
ggnet2: edge.size by weight using negative values
I'm plotting a network using ggnet2. My network has weights that range from -1 to 1. I'm trying to find a work around for somehow coloring (or line typing) those values that are negative so I can distinguish them from those values that are positive.

Here is so sample data:

```<code>n <- data.frame(event1 = c(-0.2,0.8,0.4),
                event2 = c(0.34,-0.17,0.3),
                event3 = c(0.2,0.1,-0.73),
                row.names = letters[1:3])
net <- network(net,
              matrix.type = "bipartite",
              ignore.eval = FALSE,
              names.eval = "weights")
</code>```

Then when I go to plot it like so:

```<code>ggnet2(net,label = TRUE, edge.size = "weights")
</code>```

I get an error because of the negative values: Error in ggnet2(bip, label = TRUE, edge.size = "weights") :
  incorrect edge.size value

Does anyone have ideas of how to make those edges stand out in some way? I was thinking I could add another sig figure to each like a "1" at the end so I could out those values specifically but I can't figure out how to set the code to color specific edges or change the line type of specific edges. Thanks in advance!

答:
You can specify a color for negative and positive edges values. For example:

```<code>n <- data.frame(event1 = c(-0.2,0.8,0.4,0),
                event2 = c(0.34,-0.17,0.3,0),
                event3 = c(0.2,0.1,-0.73,0),
                row.names = letters[1:4])
net <- network(n,
              matrix.type = "bipartite",
              ignore.eval = FALSE,
              names.eval = "weights")

col = c("actor" = "grey", "event" = "gold")
set.edge.attribute(net, "color", ifelse(net %e% "weights" > 0, "green", "red"))
ggnet2(net, color = "mode", palette = col, label = TRUE, edge.color = "color")
</code>```

For more information and examples you can check here:
ggnet2: network visualization with ggplot2

Body:
I'm plotting a network using ggnet2. My network has weights that range from -1 to 1. I'm trying to find a work around for somehow coloring (or line typing) those values that are negative so I can distinguish them from those values that are positive.

Here is so sample data:

n <- data.frame(event1 = c(-0.2,0.8,0.4),
                event2 = c(0.34,-0.17,0.3),
                event3 = c(0.2,0.1,-0.73),
                row.names = letters[1:3])
net <- network(net,
              matrix.type = "bipartite",
              ignore.eval = FALSE,
              names.eval = "weights")

Then when I go to plot it like so:

ggnet2(net,label = TRUE, edge.size = "weights")

I get an error because of the negative values: Error in ggnet2(bip, label = TRUE, edge.size = "weights") :
  incorrect edge.size value

Does anyone have ideas of how to make those edges stand out in some way? I was thinking I could add another sig figure to each like a "1" at the end so I could out those values specifically but I can't figure out how to set the code to color specific edges or change the line type of specific edges. Thanks in advance!

Body:
You can specify a color for negative and positive edges values. For example:

n <- data.frame(event1 = c(-0.2,0.8,0.4,0),
                event2 = c(0.34,-0.17,0.3,0),
                event3 = c(0.2,0.1,-0.73,0),
                row.names = letters[1:4])
net <- network(n,
              matrix.type = "bipartite",
              ignore.eval = FALSE,
              names.eval = "weights")

col = c("actor" = "grey", "event" = "gold")
set.edge.attribute(net, "color", ifelse(net %e% "weights" > 0, "green", "red"))
ggnet2(net, color = "mode", palette = col, label = TRUE, edge.color = "color")

For more information and examples you can check here:
ggnet2: network visualization with ggplot2


问:
removeClass() is completely deleting elements from DOM
This is a build off of my previous question: Select a child of a child

I now have a
 within another
. The behavior is an expandable menu. I'm doing this by adding and removing classes. For some reason...on the sub list - it completely removes the
 elements from the DOM rather than just toggling it's classes. Why would it do that!?

You can see an example below:

$(function() {
  // main expansion element
  $(".expander").click(function() {
    var subShown = $("ul > li", this).hasClass("show");
    if (!subShown) {
      $(".indented", this).slideDown('100').addClass("show");
      $(".caret", this).addClass("reversedCaret");
    } else {
      $(".indented", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
    }
  });

  // sub expansion element
  $(".sub-expander, .caret").click(function() {
    var subSelectText = $(".sub-expander").text();
    if (subSelectText != "More") {
      $(".indented--sub", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
      $(".more-or-less").text("More");
    } else {
      $(".indented--sub", this).slideDown('100').addClass("show");
      $(".caret", this).removeClass("reversedCaret");
      $(".more-or-less").text("Show Less");
    }
  });

  // stop propagation on the link element within .expander class
  $(".indented").click(function(event) {
    event.stopPropagation();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}</code>```

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

      +

More

```

I'm giving it a separate classname to differentiate from the main section so that they don't show on initial open, so I'm not sure why it is behaving the way it is. It seems like there is a better way to go about this but I don't know what that would be.

UPDATE: was pointed out I did not have valid HTML. Fixed it following this thread. Still broken.

UPDATE #2: It seems like the problem is .text() - so it completely erases everything? I thought it just replaced the text node, and not all of it's children. I tried .html() but it does the same thing. What method do I use to just replace text then?

UPDATE #3 - one answer suggests I needed a more specific selector. I gave the list item a class of .more-or-less but doing that, it doesn't expand at all.

答:
You'd probably want to use a more strict selector.

In your example case you use .sub-expander to select the node of which you want to replace the text. This matches with the ul.sub-expander however.

Since you want it to replace the text of the li.sub-expander the simplest thing you could do would be to use a more specific selector:
$("li.sub-expander").text("Show Less"); or (better) give the node which contains the text you want to replace another classname, id or other identifier to prevent targeting a different element.

Body:
This is a build off of my previous question: Select a child of a child

I now have a
 within another
. The behavior is an expandable menu. I'm doing this by adding and removing classes. For some reason...on the sub list - it completely removes the
 elements from the DOM rather than just toggling it's classes. Why would it do that!?

You can see an example below:

$(function() {
  // main expansion element
  $(".expander").click(function() {
    var subShown = $("ul > li", this).hasClass("show");
    if (!subShown) {
      $(".indented", this).slideDown('100').addClass("show");
      $(".caret", this).addClass("reversedCaret");
    } else {
      $(".indented", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
    }
  });

  // sub expansion element
  $(".sub-expander, .caret").click(function() {
    var subSelectText = $(".sub-expander").text();
    if (subSelectText != "More") {
      $(".indented--sub", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
      $(".more-or-less").text("More");
    } else {
      $(".indented--sub", this).slideDown('100').addClass("show");
      $(".caret", this).removeClass("reversedCaret");
      $(".more-or-less").text("Show Less");
    }
  });

  // stop propagation on the link element within .expander class
  $(".indented").click(function(event) {
    event.stopPropagation();
  });
});

.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

      +

More

I'm giving it a separate classname to differentiate from the main section so that they don't show on initial open, so I'm not sure why it is behaving the way it is. It seems like there is a better way to go about this but I don't know what that would be.

UPDATE: was pointed out I did not have valid HTML. Fixed it following this thread. Still broken.

UPDATE #2: It seems like the problem is .text() - so it completely erases everything? I thought it just replaced the text node, and not all of it's children. I tried .html() but it does the same thing. What method do I use to just replace text then?

UPDATE #3 - one answer suggests I needed a more specific selector. I gave the list item a class of .more-or-less but doing that, it doesn't expand at all.


问:
How to select a button beside the gradient filter
I met a project that set the gradient filter to whole web page.

So I have implemented the filter like this.jsfiddle

HTML

```<code><div class="container">
   <button class="tag">Featured</button>
   <div id="grad1">
</div>
</code>```

CSS

```<code>#grad1 {
    height: 200px;
    background: red; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(red, yellow); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(red, yellow); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
    background: linear-gradient(red, yellow); /* Standard syntax (must be last) */
    opacity: 0.5;
}
.container {
   border: 1px solid #DDDDDD;
   width: 200px;
   height: 200px;
   position: relative;
}
.tag {
   float: left;
   position: absolute;
   left: 0px;
   top: 0px;
   background-color: #92AD40;
   padding: 5px;
   color: #FFFFFF;
   font-weight: bold;
}
</code>```

But the problem is button is not selectable in this case.
I have no sense how to make the button work.
How can I make button selectable and also show gradient above the button?

Finally UI should look like this.

答:
Check the fiddle. You have two issue 1. set button attribute type="button" and 2. .tag z-index should be 1. Because your button is absolute position.

UPDATE

I Update the fiddle. I think it will help you.

Body:
I met a project that set the gradient filter to whole web page.

So I have implemented the filter like this.jsfiddle

HTML

   <button class="tag">Featured</button>

CSS

#grad1 {
    height: 200px;
    background: red; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(red, yellow); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(red, yellow); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
    background: linear-gradient(red, yellow); /* Standard syntax (must be last) */
    opacity: 0.5;
}
.container {
   border: 1px solid #DDDDDD;
   width: 200px;
   height: 200px;
   position: relative;
}
.tag {
   float: left;
   position: absolute;
   left: 0px;
   top: 0px;
   background-color: #92AD40;
   padding: 5px;
   color: #FFFFFF;
   font-weight: bold;
}

But the problem is button is not selectable in this case.
I have no sense how to make the button work.
How can I make button selectable and also show gradient above the button?

Finally UI should look like this.


问:
Facebook Analytics DAU/MAU different numbers when changing time period
We're using FB analytics to check our DAU of paying users only, using a Segment.

When viewing the DAU graph for the period of 1/2017-10/2017, we get a graph of results.
But when extending the period to 1/2016-10/2017, the graph is completely different, the values of the same months (1/2017-10/2017) are more then doubled.

When clearing the segment the graph is stable regardless of time period chosen.

Is this a known issue when using segments?

Is there something we can do to fix it?

Is there a way to know which of the graphs is more accurate?

答:
This is expected behavior and it's not a matter of which graph is "more accurate" since you're looking at different segments of users in each case.

In the first case, all users who have made a purchase in 1/2017-10/2017 (10 months) are included in the segment. In the second case, all users who have made a purchase in 1/2016-10/2017 (22 months) are included in the segment.

So if you're looking at the number of DAU on, say, 2/1/2017, in the first case, all the users who used your app that day who made a purchase in a 10-month period are included. Whereas in the first case, all the users who used your app that day who made a purchase in a 22-month period are included. This explains why the numbers of users are more than doubled.

If you just want to see the number of unique users who made a purchase each day, you can do so in the Revenue, Dashboards or Events section by selecting the "purchase" event and "unique users" metric. These numbers will be stable regardless of the date range you select, since no event-based segment is applied.


答: first thing is, pointer addition is not allowed in C. only pointer subtraction is allowed in c. you are trying to do pi + p which is invalid.

Title: Swap index of an array with another using pointers, in C language


问:
java rmi server hostname
I have two RMI java applications:

server

```<code>System.setProperty("java.rmi.server.hostname", "0.tcp.ngrok.io");
System.setProperty("java.security.policy", "security.policy");
if (System.getSecurityManager() == null) {
    System.setSecurityManager(new SecurityManager());
}

Registry r = LocateRegistry.createRegistry(1099);
r.rebind("Calc", new CalculatorImpl());
</code>```

client

```<code>System.setProperty("java.rmi.server.hostname", "0.tcp.ngrok.io");
System.setProperty("java.security.policy", "security.policy");
Calculator c = (Calculator) Naming.lookup("//0.tcp.ngrok.io:18872"+"/Calc");
int sum = c.add(1, 5);
</code>```

Communication between the two is done with the help of Ngrok:

```<code>ngrok tcp 1099
</code>```

result

```<code>   Session Status                online
   Account                       nival (Plan: Free)
   Version                       2.2.8
   Region                        United States (us)
   Web Interface                 http://127.0.0.1:4040
   Forwarding                   tcp://0.tcp.ngrok.io:18872 -> localhost:1099

   Connections                   ttl     opn     rt1     rt5     p50     p90
                                  5       0       0.00    0.00    5.88    17.03
</code>```

My problem is :

```<code> RemoteException
 java.rmi.ConnectException: Connection refused to host: 0.tcp.ngrok.io; nested exception is:
 java.net.ConnectException: Connection timed out: connect
</code>```

I think the problem is at

```<code>System.setProperty("java.rmi.server.hostname","0.tcp.ngrok.io");
</code>```

what should I put on the server and client at "java.rmi.server.hostname"?

(Sorry for my bad english)

答:
In general it's only required on server side to show on what hostname exported stubs will be available to the world.

It is useful for example, when your server is in the intranet and listens on some interface lets say 192.168.2.1. NAT proxy can have ports forwarded to that host from internet. Normally RMI registry would report stubs being exported on address 192.168.2.1:someport. But obviously you cannot hit that address directly java.rmi.server.hostname comes in action. By setting that property, RMI registry will announce stubs being exported on given hostname insteed on actual intranet address, allowing clients to get to the stubs from outside world trough forwarded ports on NAT gateway.

So if your server is behind NAT, it should specify the domain that points to your NAT gateway from the Internet. If your server has external IP and its listening on that IP, then this property is not needed.

ContentLicense: CC BY-SA 4.0

Title: java rmi server hostname

Body:
I have two RMI java applications:

server

System.setProperty("java.rmi.server.hostname", "0.tcp.ngrok.io");
System.setProperty("java.security.policy", "security.policy");
if (System.getSecurityManager() == null) {
    System.setSecurityManager(new SecurityManager());
}

Registry r = LocateRegistry.createRegistry(1099);
r.rebind("Calc", new CalculatorImpl());

client

System.setProperty("java.rmi.server.hostname", "0.tcp.ngrok.io");
System.setProperty("java.security.policy", "security.policy");
Calculator c = (Calculator) Naming.lookup("//0.tcp.ngrok.io:18872"+"/Calc");
int sum = c.add(1, 5);

Communication between the two is done with the help of Ngrok:

ngrok tcp 1099

result

   Session Status                online
   Account                       nival (Plan: Free)
   Version                       2.2.8
   Region                        United States (us)
   Web Interface                 http://127.0.0.1:4040
   Forwarding                   tcp://0.tcp.ngrok.io:18872 -> localhost:1099

   Connections                   ttl     opn     rt1     rt5     p50     p90
                                  5       0       0.00    0.00    5.88    17.03

My problem is :

 RemoteException
 java.rmi.ConnectException: Connection refused to host: 0.tcp.ngrok.io; nested exception is:
 java.net.ConnectException: Connection timed out: connect

I think the problem is at

System.setProperty("java.rmi.server.hostname","0.tcp.ngrok.io");

what should I put on the server and client at "java.rmi.server.hostname"?

(Sorry for my bad english)


问:
How to Print Text In Web Assembly
Is there any way to print text onto the window directly in web assembly instead of having to pass string data into javascript, or print to the console?</p>

答: The answer is still no, and it will remain no. It is central to the design of Wasm that it does not have any built-in functionality that depends on a given environment (because it is intended to be embeddable in many different environments) or that gives Wasm code the capability to manipulate its environment other than through explicit imports (because that would break the ability to sandbox a Wasm module).</p>

Title: How to Print Text In Web Assembly


问:
Unable to make a component unmount
I have a little big personal project, and I figured out (after 3 months of code) that none of my components ever unmount.

I created a new-react-app to test in a brand new environment, and it didn't work either.

Here's my class :

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import Test from './Test'
import './App.css';

class App extends Component {

  constructor(props) {
    super(props)

    this.state = {
      test: true
    }

    this.test = this.test.bind(this)
  }

  test(){
    this.setState({
      test: !this.state.test
    })
  }

  render() {
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h1 className="App-title">Welcome to React</h1>
          </header>

          {this.state.test ? <Test /> :null}
          <button onClick={this.test}/>
        </div>
      )

  }
}

export default App;
</code>```

here's console's result

console

Thank you for your time !

EDIT : I discovered that in every class I always called componentSWillUnmount instead of componentWillUnmount... thanks everybody

答:
When you toggle the test state, your Test component does unmount. You maybe looking at some incorrect information. See the snippet below

class App extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      test: true
    }

    this.test = this.test.bind(this)
  }

  test(){
    this.setState({
      test: !this.state.test
    })
  }

  render() {
      return (

Welcome to React

            {this.state.test ? <Test /> :null}
  <button onClick={this.test}/>

      )

  }
}

class Test extends React.Component {
  componentDidMount() {
    console.log('mounted');
  }
  componentWillUnmount () {
   console.log('unmounting');
  }

  render() {
      return (

          Hello

      )

  }
}

ReactDOM.render(<App/>, document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/></code>```

Title: Unable to make a component unmount

Body:
I have a little big personal project, and I figured out (after 3 months of code) that none of my components ever unmount.

I created a new-react-app to test in a brand new environment, and it didn't work either.

Here's my class :

import React, { Component } from 'react';
import logo from './logo.svg';
import Test from './Test'
import './App.css';

class App extends Component {

  constructor(props) {
    super(props)

    this.state = {
      test: true
    }

    this.test = this.test.bind(this)
  }

  test(){
    this.setState({
      test: !this.state.test
    })
  }

  render() {
      return (

Welcome to React

          {this.state.test ? <Test /> :null}
          <button onClick={this.test}/>

      )

  }
}

export default App;

here's console's result

console

Thank you for your time !

EDIT : I discovered that in every class I always called componentSWillUnmount instead of componentWillUnmount... thanks everybody

Body:
When you toggle the test state, your Test component does unmount. You maybe looking at some incorrect information. See the snippet below

class App extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      test: true
    }

    this.test = this.test.bind(this)
  }

  test(){
    this.setState({
      test: !this.state.test
    })
  }

  render() {
      return (
        <div className="App">
          <header className="App-header">

            <h1 className="App-title">Welcome to React</h1>
          </header>

            {this.state.test ? <Test /> :null}
  <button onClick={this.test}/>
        </div>
      )

  }
}

class Test extends React.Component {
  componentDidMount() {
    console.log('mounted');
  }
  componentWillUnmount () {
   console.log('unmounting');
  }

  render() {
      return (
        <div className="test">
          Hello
        </div>
      )

  }
}

ReactDOM.render(<App/>, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>


问:
Facebook debugger can't find my og:image
Facebook can't seem to find the value I pass in meta og:image.

The url is: https://glouton.ca

And the debugger, even after I do recollect, I still have a warning.

```<code>The 'og:image' property should be explicitly provided, even if a value can be inferred from other tags.
</code>```

What am I doing wrong? I feel like it worked last week...

答:
Your current tags are valid. The problem is caching, either on their side, on yours or one somewhere in between, because they aren't getting the current version of your site.

I also inspected your page in the Facebook debugger, and found that they're using an outdated version of your page. The result they're collecting for your link is available here : (The link to access this is present around the bottom of the debugger page)

https://developers.facebook.com/tools/debug/echo/?q=https%3A%2F%2Fglouton.ca%2F

At the time of writing this message, the code looks like this :

```<code><!DOCTYPE html>
<html><body>
<p>tyle="height:100%">

</p>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<!-- Global site tag (gtag.js) - Google Analytics --><script async src="https://www.googletagmanager.com/gtag/js?id=UA-109094225-1"></script><script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'UA-109094225-1');
    </script><meta name="description" content="Glouton est un moteur de recherche intelligent qui permet de trouver des recettes par mot clé ou ingrédient. Des nouvelles recettes sont indexées automatiquement chaque jour.">
<meta charset="utf-8">
<meta property="og:url" content="https://glouton.ca">
<meta property="og:type" content="website">
<meta property="og:title" content="Glouton, les meilleures recettes du Québec">
<meta property="og:description" content="Glouton est un moteur de recherche intelligent qui permet de trouver des recettes par mot clé ou ingrédient. Des nouvelles recettes sont indexées automatiquement chaque jour.">
<meta property="og:image" content="https://glouton.ca/site/images/social.png">
</code>```

With that many errors in the file, no wonder their parser can't find the og:image correctly. You should check it out again in some time.

Body:
Facebook can't seem to find the value I pass in meta og:image.

The url is: https://glouton.ca

And the debugger, even after I do recollect, I still have a warning.

The 'og:image' property should be explicitly provided, even if a value can be inferred from other tags.

What am I doing wrong? I feel like it worked last week...

Body:
Your current tags are valid. The problem is caching, either on their side, on yours or one somewhere in between, because they aren't getting the current version of your site.

I also inspected your page in the Facebook debugger, and found that they're using an outdated version of your page. The result they're collecting for your link is available here : (The link to access this is present around the bottom of the debugger page)

https://developers.facebook.com/tools/debug/echo/?q=https%3A%2F%2Fglouton.ca%2F

At the time of writing this message, the code looks like this :

<!DOCTYPE html>
<html><body>
<p>tyle="height:100%"&gt;

</p>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<!-- Global site tag (gtag.js) - Google Analytics --><script async src="https://www.googletagmanager.com/gtag/js?id=UA-109094225-1"></script><script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'UA-109094225-1');
    </script><meta name="description" content="Glouton est un moteur de recherche intelligent qui permet de trouver des recettes par mot cl&eacute; ou ingr&eacute;dient. Des nouvelles recettes sont index&eacute;es automatiquement chaque jour.">
<meta charset="utf-8">
<meta property="og:url" content="https://glouton.ca">
<meta property="og:type" content="website">
<meta property="og:title" content="Glouton, les meilleures recettes du Qu&eacute;bec">
<meta property="og:description" content="Glouton est un moteur de recherche intelligent qui permet de trouver des recettes par mot cl&eacute; ou ingr&eacute;dient. Des nouvelles recettes sont index&eacute;es automatiquement chaque jour.">
<meta property="og:image" content="https://glouton.ca/site/images/social.png">

With that many errors in the file, no wonder their parser can't find the og:image correctly. You should check it out again in some time.


问:
CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error
I just upgraded from Angular 2 rc4 to rc6 and having troubles doing so.

I see the following error on my console:

```<code>Unhandled Promise rejection: Template parse errors:
'cl-header' is not a known element:
1. If 'cl-header' is an Angular component, then verify that it is part of this module.
2. If 'cl-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("<main>
    [ERROR ->]<cl-header>Loading Header...</cl-header>
    <div class="container-fluid">
      <cl-feedbackcontai"): AppComponent@1:4
</code>```

Here is my Header Component:

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

// own service
import { AuthenticationService } from '../../../services/authentication/authentication.service.ts';

import '../../../../../public/css/styles.css';

@Component({
  selector: 'cl-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent { // more code here... }
</code>```

Here is my Header Module:

```<code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA }      from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule }      from '@angular/common';
import { FormsModule }      from '@angular/forms';

import { HeaderComponent }  from './../../../components/util_components/header/header.component.ts';

@NgModule({
    declarations: [ HeaderComponent ],
    bootstrap:    [ HeaderComponent ],
    imports: [ RouterModule, CommonModule, FormsModule ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class HeaderModule { }
</code>```

I created a wrapper module called util module which imports the HeaderModule:

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

import {HeaderModule} from "./header/header.module";
// ...

@NgModule({
    declarations: [ ],
    bootstrap:    [ ],
    imports: [ HeaderModule]
})
export class UtilModule { }
</code>```

Which is finally imported by the AppModule:

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import {UtilModule} from "./modules/util_modules/util.module";
import {RoutingModule} from "./modules/routing_modules/routing.module";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }
</code>```

To my understanding I am following the instructions of the error message using the SCHEMA to surpress the error. But it seems not to work.
What am I doing wrong?
(I hope its nothing obvious I just don't see at the moment. Been spending the past 6 hours upgrading to this version...)

答:
That didn't work for me (using 2.0.0). What worked for me was importing RouterTestingModule instead.

I resolved this by importing RouterTestingModule in spec file.

```<code>import {
    RouterTestingModule
} from '@angular/router/testing';

  beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [
                App,
                AppState,
                Renderer,
                {provide: Router,  useClass: MockRouter }
            ],
            imports: [ RouterTestingModule ]
        });

    });
</code>```

Body:
I just upgraded from Angular 2 rc4 to rc6 and having troubles doing so.

I see the following error on my console:

Unhandled Promise rejection: Template parse errors:
'cl-header' is not a known element:
1. If 'cl-header' is an Angular component, then verify that it is part of this module.
2. If 'cl-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("
    [ERROR ->]<cl-header>Loading Header...</cl-header>

      <cl-feedbackcontai"): AppComponent@1:4

Here is my Header Component:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

// own service
import { AuthenticationService } from '../../../services/authentication/authentication.service.ts';

import '../../../../../public/css/styles.css';

@Component({
  selector: 'cl-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent { // more code here... }

Here is my Header Module:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA }      from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule }      from '@angular/common';
import { FormsModule }      from '@angular/forms';

import { HeaderComponent }  from './../../../components/util_components/header/header.component.ts';

@NgModule({
    declarations: [ HeaderComponent ],
    bootstrap:    [ HeaderComponent ],
    imports: [ RouterModule, CommonModule, FormsModule ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class HeaderModule { }

I created a wrapper module called util module which imports the HeaderModule:

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

import {HeaderModule} from "./header/header.module";
// ...

@NgModule({
    declarations: [ ],
    bootstrap:    [ ],
    imports: [ HeaderModule]
})
export class UtilModule { }

Which is finally imported by the AppModule:

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import {UtilModule} from "./modules/util_modules/util.module";
import {RoutingModule} from "./modules/routing_modules/routing.module";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }

To my understanding I am following the instructions of the error message using the SCHEMA to surpress the error. But it seems not to work.
What am I doing wrong?
(I hope its nothing obvious I just don't see at the moment. Been spending the past 6 hours upgrading to this version...)

Body:
That didn't work for me (using 2.0.0). What worked for me was importing RouterTestingModule instead.

I resolved this by importing RouterTestingModule in spec file.

import {
    RouterTestingModule
} from '@angular/router/testing';

  beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [
                App,
                AppState,
                Renderer,
                {provide: Router,  useClass: MockRouter }
            ],
            imports: [ RouterTestingModule ]
        });

    });


问:
Apache commons configuration reading properties in the format a.<no>.b
I have a properties file that says

```<code>window.1.height=100
window.1.width=80

window.2.height=50
window.2.width=30

window.3.height=150
window.3.width=100
</code>```

I am using the PropertiesConfiguration class and reading the properties.
How can I know the count of windows in the properties. Is therea pattern search

答:
I usually use something like

```<code>int i = 0;
String val;
for(;;) {
  val = props.get("foo" + i);
  if (null == val) {
     break;
  }
  //process val
}
</code>```

This places the constraint that the counter values must be contiguous.

ContentLicense: CC BY-SA 2.5

Body:
I have a properties file that says

window.1.height=100
window.1.width=80

window.2.height=50
window.2.width=30

window.3.height=150
window.3.width=100

I am using the PropertiesConfiguration class and reading the properties.
How can I know the count of windows in the properties. Is therea pattern search

Body:
I usually use something like

int i = 0;
String val;
for(;;) {
  val = props.get("foo" + i);
  if (null == val) {
     break;
  }
  //process val
}

This places the constraint that the counter values must be contiguous.


问:
How to run selenium testng jar file through command line
I am a newbie to Selenium and TestNG.

I have a Selenium testng project which uses gradle.
I want to run the jar file in cmd.
I have created an executable jar file and using "java -jar test.jar".

The problem which I am facing is, if there is a failed test case, the running of the jar file is stopped, I want it to cover through all the test cases even if there is a failed test case.

If I want to run the testng.xml the command is
"java -cp F:\Selenium\SampleTestNG\lib*;F:\Selenium\SampleTestNG\bin org.testng.TestNG testng.xml",
since I am using gradle, I dont have a separate folder for the testng-6.9.4.jar or selenium jar files.

Thank you

答: Try to use "Try and catch" to get those tests that are missing, map all the errors and use "Try and catch" as an optional approach to these errors</p>


答:
a
 tag is missing.
At the end of ur code.

Ur container isnt closing, so your button cant‘t be clicked.

Try to add just another closing tag.

Title: How to select a button beside the gradient filter

Body:
a </div> tag is missing.
At the end of ur code.

Ur container isnt closing, so your button cant‘t be clicked.

Try to add just another closing tag.


问:
Shoot object to mouse position direction
I want to force my object to my mouse position, I mean force it in direction between my object and mouse position, I use this code:

if(Input.GetKeyDown(KeyCode.Space))
{
    GetComponent<Rigidbody2D>().velocity = Vector2.zero;
    Vector2 direction = (Vector2)(transform.position - Input.mousePosition);
    direction.Normalize();

    this.GetComponent<Rigidbody2D>().AddForce(-direction, ForceMode2D.Impulse);
}
```

But it seems its not works correctly...

答:
This should work:</p>

```<code>    if(Input.GetKeyDown(KeyCode.Space))
    {
        this.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
        Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
        Vector2 direction = (Vector2)(Input.mousePosition-screenPoint);
        direction.Normalize();

        this.GetComponent<Rigidbody2D>().AddForce(direction, ForceMode2D.Impulse);
    }
</code>```

Body:
I want to force my object to my mouse position, I mean force it in direction between my object and mouse position, I use this code:

if(Input.GetKeyDown(KeyCode.Space))
{
    GetComponent<Rigidbody2D>().velocity = Vector2.zero;
    Vector2 direction = (Vector2)(transform.position - Input.mousePosition);
    direction.Normalize();

    this.GetComponent<Rigidbody2D>().AddForce(-direction, ForceMode2D.Impulse);
}

But it seems its not works correctly...

Body:
This should work:

    if(Input.GetKeyDown(KeyCode.Space))
    {
        this.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
        Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
        Vector2 direction = (Vector2)(Input.mousePosition-screenPoint);
        direction.Normalize();

        this.GetComponent<Rigidbody2D>().AddForce(direction, ForceMode2D.Impulse);
    }


问:
Django - How can I stop this repeat query?
So I am trying to retrieve a list of blog entries, which has a foreign key to the author:

In my view:

```<code>data = {'entries':Entry.objects.all()}
</code>```

Then in my template:

```<code><td valign="top">{{ entry.author }}</td>
</code>```

This is hitting the database once per entry to get the authors details. I understand this, but when the author is the same, is there any way to 'cache' the result? For example, if one entry has an author 'relationship' of 1, can I store the results so if any other entries have the same author 'relationship', it doesn't need to hit the database again?

I'm sure this must be possible but I can't find mention of it in the documentation :(

答: No. But you can use QuerySet.select_related() to pull in the FK information at the same time.

Body:
So I am trying to retrieve a list of blog entries, which has a foreign key to the author:

In my view:

data = {'entries':Entry.objects.all()}

Then in my template:

{{ entry.author }}

This is hitting the database once per entry to get the authors details. I understand this, but when the author is the same, is there any way to 'cache' the result? For example, if one entry has an author 'relationship' of 1, can I store the results so if any other entries have the same author 'relationship', it doesn't need to hit the database again?

I'm sure this must be possible but I can't find mention of it in the documentation :(


问:
What is an optimal method for isolating unrelated sets of data in neo4j?
I'm using neo4j to contain temporary datasets from different source systems.  My data consists of a few parent objects which each contain ~4-7 layers of child objects of varying types.  Total object count per dataset varies between 2,000 and 1.5 million. I'm using the python py2neo library, which has had good performance both during the data creation phase, and for passing through cypher queries for reporting.

I'd like to isolate datasets from unrelated systems for querying and purging purposes, but I'm worried about performance.  I have a few ideas, but it's not clear to me which are the most likely to be viable.

The easiest to implement (for my code) would be a top-level "project" object. That project object would then have a few direct children (via a relationship) and many indirect children.  I'm worried that when I want to filter by project, I'll have to use a relationship wildcard MATCH (pr:project)<-[:IN_PROJECT*7]-(c:child_object) distance, which seems to very expensive query-wise.

I could also make a direct relationship between the project object and every other object in the project. MATCH (pr:project)<-[:IN_PROJECT]-(c:child_object)This should be easier for writing queries, but I don't know what might happen when I have a single object with potentially millions of relationships.

Finally, I could set a project-id property on every single object in the dataset. MATCH (c:child_object {project-id:"A1B2C3"}) It seems to be a wasteful solution, but I think it might be better performance wise in the graph DB model.

Apologies if I mangled the sample Cypher queries / neo4j terminology.  I set aside this project for 6 weeks, and I'm a little rusty.

答:
If you have a finite set of datasets, you should consider using a dedicated label to specify the data source. In Neo4j's property graph data model, a node is allowed to have multiple labels.

```<code>MATCH (c:child_object:DataSourceA)
</code>```

Labels are always indexed, so performance should be better than that of your proposals 1-3. I also think this is a more elegant solution -- however, it will get tricky if you do not know the number of data sets up front. In the latter case, you might use something like

```<code>MATCH (c:child_object)
WHERE 'DataSourceA' IN labels(c)
</code>```

But this is more like a "full table scan", so performance-wise, you'll be better off using your approach 3 and building an index on project-id.

Body:
If you have a finite set of datasets, you should consider using a dedicated label to specify the data source. In Neo4j's property graph data model, a node is allowed to have multiple labels.

MATCH (c:child_object:DataSourceA)

Labels are always indexed, so performance should be better than that of your proposals 1-3. I also think this is a more elegant solution -- however, it will get tricky if you do not know the number of data sets up front. In the latter case, you might use something like

MATCH (c:child_object)
WHERE 'DataSourceA' IN labels(c)

But this is more like a "full table scan", so performance-wise, you'll be better off using your approach 3 and building an index on project-id.


问:
Django: Filtering Distinct Data
I'm trying to build a messaging app. Here's my model,

```<code>class Message(models.Model):
sender = models.ForeignKey(User, related_name="sender")
receiver = models.ForeignKey(User, related_name="receiver")
msg_content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is what I tried in view,

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')
</code>```

In my template,

```<code>{% for abc in data %}
    {{ abc.receiver }}<br />
{% endfor %}
</code>```

How can I print out the distinct users?

答:
With your db structure i was able to receive what your want only with such db query (not sure it can be reproduced in django orm):</p>

```<code>SELECT u.*, m.*
FROM auth_user u
  INNER JOIN (
     SELECT
       user_id,
       MAX(message_id) AS message_id
     FROM
       (
         SELECT
           m2.receiver_id AS user_id,
           MAX(id)        AS message_id
         FROM yourapp_message m2
         GROUP BY m2.receiver_id
         UNION
         SELECT
           m2.sender_id AS user_id,
           MAX(id)      AS message_id
         FROM yourapp_message m2
         GROUP BY m2.sender_id
       ) t
     GROUP BY user_id) t2 ON u.id = t2.user_id
  INNER JOIN yourapp_message m ON m.id = t2.message_id
ORDER BY m.id DESC
</code>```

Title: Django: Filtering Distinct Data

Body:
I'm trying to build a messaging app. Here's my model,

class Message(models.Model):
sender = models.ForeignKey(User, related_name="sender")
receiver = models.ForeignKey(User, related_name="receiver")
msg_content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in view,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')

In my template,

{% for abc in data %}
    {{ abc.receiver }}

{% endfor %}

How can I print out the distinct users?

Body:
With your db structure i was able to receive what your want only with such db query (not sure it can be reproduced in django orm):

SELECT u.*, m.*
FROM auth_user u
  INNER JOIN (
     SELECT
       user_id,
       MAX(message_id) AS message_id
     FROM
       (
         SELECT
           m2.receiver_id AS user_id,
           MAX(id)        AS message_id
         FROM yourapp_message m2
         GROUP BY m2.receiver_id
         UNION
         SELECT
           m2.sender_id AS user_id,
           MAX(id)      AS message_id
         FROM yourapp_message m2
         GROUP BY m2.sender_id
       ) t
     GROUP BY user_id) t2 ON u.id = t2.user_id
  INNER JOIN yourapp_message m ON m.id = t2.message_id
ORDER BY m.id DESC


问:
Using django name 'HttpResponse' is not defined
So brand new to Python, trying to get past this django error:

```<code>NameError at /hello/
name 'HttpResponse' is not defined
Request Method:
GET
Request URL:
http://localhost:61892/hello/
Django Version:
1.11.7
Exception Type:
NameError
Exception Value:
name 'HttpResponse' is not defined
Exception Location:
c:\users\mblaylock\source\repos\mysite\mysite\mysite\views.py in hello, line 6
Python Executable:
c:\users\mblaylock\source\repos\mysite\mysite\env\Scripts\python.exe
Python Version:
3.6.2
Python Path:
['c:\\users\\mblaylock\\source\\repos\\mysite\\mysite',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite\\env\\Scripts\\python36.zip',
 'C:\\Program Files\\Python36\\DLLs',
 'C:\\Program Files\\Python36\\lib',
 'C:\\Program Files\\Python36',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite\\env',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite\\env\\lib\\site-packages']
Server time:
Mon, 13 Nov 2017 18:09:39 +0000
</code>```

My code is:

```<code>class views(object):

    """description of class"""

    from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")
</code>```

Using Visual Studio for my IDE on Windows 10, if that matters.

Thanks in advance!

答:
Best approach in this situation is use single method to handle this request(you don't need any class based views here) which shouldn't be inside any class:

```<code>from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")
</code>```

If you want to use class based views you need to remember that
when you are importing something in class body it can be inaccessible in method. You should insert import at the top of python file or directly in method.

Body:
So brand new to Python, trying to get past this django error:

NameError at /hello/
name 'HttpResponse' is not defined
Request Method:
GET
Request URL:
http://localhost:61892/hello/
Django Version:
1.11.7
Exception Type:
NameError
Exception Value:
name 'HttpResponse' is not defined
Exception Location:
c:\users\mblaylock\source\repos\mysite\mysite\mysite\views.py in hello, line 6
Python Executable:
c:\users\mblaylock\source\repos\mysite\mysite\env\Scripts\python.exe
Python Version:
3.6.2
Python Path:
['c:\\users\\mblaylock\\source\\repos\\mysite\\mysite',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite\\env\\Scripts\\python36.zip',
 'C:\\Program Files\\Python36\\DLLs',
 'C:\\Program Files\\Python36\\lib',
 'C:\\Program Files\\Python36',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite\\env',
 'c:\\users\\mblaylock\\source\\repos\\mysite\\mysite\\env\\lib\\site-packages']
Server time:
Mon, 13 Nov 2017 18:09:39 +0000

My code is:

class views(object):

    """description of class"""

    from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")

Using Visual Studio for my IDE on Windows 10, if that matters.

Thanks in advance!

Body:
Best approach in this situation is use single method to handle this request(you don't need any class based views here) which shouldn't be inside any class:

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")

If you want to use class based views you need to remember that
when you are importing something in class body it can be inaccessible in method. You should insert import at the top of python file or directly in method.


问:
Swap index of an array with another using pointers, in C language
Could anyone help me with my solution to this code? I have to trade the index of an array with another, using pointers.  This was the solution I created`

```<code>double *swap_double_array_ptr(double *pi, int pos1, int pos2) {
         double *p = &pos1;
         double *q = &pos2;
         double aux=0;
         aux = *(pi + p);
         *(p + pi) = *(q+ pi);
         *(q + pi) = aux;
</code>```

}

The compiler says invalid operand. Can someone help me? I do not know any other solution. Please be gentle, I am new to pointers.
 Thank you.

答:
The operation of adding two pointers as in this expression statement

```<code>aux = *(pi + p);
        ^^^^^^
</code>```

is not defined in C.

And moreover the function returns nothing so its return type should be void.

It seems what you mean is the following

```<code>void swap_double_array_ptr( double *pi, int pos1, int pos2 )
{
         double aux = *(pi + pos1);
         *(pi + pos1) = *(pi + pos2);
         *(pi + pos2) = aux;
}
</code>```

Take into account that instead of the type int for the second and third parameters it is much better to use type size_t because in general the type int is not sufficient to store all possible indices of an array.

Body:
Could anyone help me with my solution to this code? I have to trade the index of an array with another, using pointers.  This was the solution I created`

double *swap_double_array_ptr(double *pi, int pos1, int pos2) {
         double *p = &pos1;
         double *q = &pos2;
         double aux=0;
         aux = *(pi + p);
         *(p + pi) = *(q+ pi);
         *(q + pi) = aux;

}

The compiler says invalid operand. Can someone help me? I do not know any other solution. Please be gentle, I am new to pointers.
 Thank you.

Body:
The operation of adding two pointers as in this expression statement

aux = *(pi + p);
        ^^^^^^

is not defined in C.

And moreover the function returns nothing so its return type should be void.

It seems what you mean is the following

void swap_double_array_ptr( double *pi, int pos1, int pos2 )
{
         double aux = *(pi + pos1);
         *(pi + pos1) = *(pi + pos2);
         *(pi + pos2) = aux;
}

Take into account that instead of the type int for the second and third parameters it is much better to use type size_t because in general the type int is not sufficient to store all possible indices of an array.


问:
why use xcode if monotouch is available?
if mono touch is available than why we should use mac environment(sdk,xcode+Interface Builder)?

what are the disadvantage of monotouch compare to xcode?

答: Every example, tutorial, and piece of documentation will be written in Objective-C, and mono will just be calling into Objective-C code under the hood. If you really feel like C# is worth mentally translating everything, and adding an extra layer in your code, go for it I guess.</p>


问:
Avoid Jquery to hide a message with display:none
hope I can find a way to show two messages when click on a link, I miss a message (Product Added) cause the display:none - it seems there is no way to keep visible the second message :(

This is my code:

```<code><script>
$(document).ready(function() {
$('.shop').click(function(){
$(this).next('.add-button .btn-bottom-linea a').text('Product Added').delay(3000).fadeOut(500);
$(this).text('Add another product').hide().delay(3500).fadeIn(500);
});
});
</script>

<a href="#0" class="shop add-button btn-bottom-line">Add Product</a>
</code>```

答:
Your selector is wrong... it should be element first and then the class

```<code>.next('.add-button .btn-bottom-linea a')
</code>```

should actually be

```<code> .next('a.add-button')   // since once class selector is enough
</code>```

here is a working example

$(document).ready(function(){
    $('.shop').click(function(){
  $(this).next('a.btn-bottom-line').text('Product    Added').delay(3000).fadeOut(500);

  $(this).text('Add anthr product').delay(3500).fadeIn(500);
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Add Product

Add Product</code>```

Body:
hope I can find a way to show two messages when click on a link, I miss a message (Product Added) cause the display:none - it seems there is no way to keep visible the second message :(

This is my code:

Add Product

Body:
Your selector is wrong... it should be element first and then the class

.next('.add-button .btn-bottom-linea a')

should actually be

 .next('a.add-button')   // since once class selector is enough

here is a working example

$(document).ready(function(){
    $('.shop').click(function(){
  $(this).next('a.btn-bottom-line').text('Product    Added').delay(3000).fadeOut(500);

  $(this).text('Add anthr product').delay(3500).fadeIn(500);
 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#0" class="shop add-button btn-bottom-line">Add Product</a>

<a href="#0" class="shop add-button btn-bottom-line">Add Product</a>


问:
Uploading venv folder on github
Is it necessary to upload venv folder that itself contains 100's of files along with other folders and files of the same project to GitHub?  </p>

答:
You don't have to do that. What you can do is :

Remember your project python version.

Generate your Django project dependencies file requirement.txt.

-Create requirement.txt file use: pipreqs /path/to/your/project/ (I recommend pipreqs, it creates a project level requirement.txt file. You can also use pip freeze or other commands)

-Install all dependencies from it: pip install -r requirements.txt, make sure pip belongs to your virtualenv python other than OS default pip

Then you can easily install a brand new virtual env and install all dependencies.

Title: Uploading venv folder on github


问:
Web Service for SQL server
Note: This question is not an Error in code question its a general question for information on Web-Service connecting to the database.

I am new to development and I need to know why should you use web service to talk to live database? I created a page and when I took it to my boss he said you are going to need to talk to the database through web service and I just want to know  what is the difference between normal data access layer and going through web service?

答:
why should you use web service to talk to live database?

Well, in short to provide abstraction. Without web service your client/consumer have to be smart enough to know how to deal with business model(s), interact with DB and convert the DB entities to your application model(s).

With service you are abstracting out this all stuff and thus your client has to only know how to call the service, pass the required parameters and what to get in return. That's it. It's kind a providing a simplified interface to your client (Facade Pattern)

Title: Web Service for SQL server


问:
Best way to make PostgreSQL backups
I have a site that uses PostgreSQL. All content that I provide in my site is created at a development environment (this happens because it's webcrawler content). The only information created at the production environment is information about the users.

I need to find a good way to update data stored at production. May I restore to production only the tables updated at development environment and PostgreSQL will update this records at production or the best way would be to backup the users information at production, insert them at development and restore the whole database at production?

Thank you

答:
You can use pg_dump to export the data just from the non-user tables in the development environment and pg_restore to bring that into prod.

The -t switch will let you pick specific tables.

```<code>pg_dump -d <database_name> -t <table_name>
</code>```

https://www.postgresql.org/docs/current/static/app-pgdump.html

Title: Best way to make PostgreSQL backups

Body:
You can use pg_dump to export the data just from the non-user tables in the development environment and pg_restore to bring that into prod.

The -t switch will let you pick specific tables.

pg_dump -d <database_name> -t <table_name>

https://www.postgresql.org/docs/current/static/app-pgdump.html


问:
(ng2-charts, angular) Doughnut chart not showing up after AOT? (but filltext is working)
The doughnut chart has always worked for me until the last few days. I don't know what changed, but for some reason the actual doughnut doesn't show up after AOT build but does in development mode. I see the difference in the html, but don't know why they are different. The legend and filltext percentage that I draw in the middle of the doughnut still show up, its just the doughnut that isn't visible. I verified that the data being passed in is the exact same. Super weird. don't know why it all of the sudden would've changed. Here are the images of the working and non-working html.

Working:

Not Working: (After AOT build)

Notice how the working doughnut has an iframe and the non-visible doughnut does not.

答: I figured out the culprit. I had "title: 100%" in the chart options which was causing the graph to not be drawn on the AOT build. I was messing with this when I was figuring out how to get the text drawn in the middle of the doughnut and forgot to remove it. The fact that it worked locally but didn't work after the AOT build doesn't make any sense to me. Removing that option makes it work on both builds though.</p>


问:
Is it faster to do two lookups on primary keys or one lookup on a non-primary key?
I'm creating a table in cassandra for users. Users have both a unique user_id and a unique display_name.

My table currently resembles:

```<code>create table user (user_id text primary key,
    display_name text,
    joined timestamp,
    last_seen timestamp,
    ...);
</code>```

When a new user creates an account I need to check if the display name they enter is already someone else's. What's the fastest way I can do this?

This project is primarily a learning project for me, I want to experiment with some NoSQL concepts in a semi-real-world situation.

My own thoughts are that using two tables like this:

```<code>create table user (user_id text primary key,
    display_name text,
    joined timestamp,
    last_seen timestamp,
    ...);

create table user_by_display_name (display_name text primary key, user_id text);
</code>```

And then looking up in user_by_display_name for existence of a username will be faster than looking up in user where display_name = ?. Is this a correct assumption?

I feel that two lookups on primary keys, user_by_display_name where display_name = ? and then another lookup using the user_id in user might be slower than the single user where display_name = ? lookup if I need the information about that user.

答:
Your assumption is correct, you will want to denormalize as described.  You design your queries first and then build the tables.

Your table should look like

```<code>CREATE TABLE users (
  user_id text,
  display_name text,
  last_seen timestamp,
  PRIMARY KEY(user_id)
WITH ...);

CREATE TABLE users_by_display_name (
  display_name text,
  user_id text,
  last_seen timestamp,
  PRIMARY KEY(display_name);
</code>```

This way you do 1 lookup.  Writes are cheap, reads are expensive.  Avoid reads when possible.  That said, your partitions are 1 row and you're doing a lookup in a Key value database.  Your second select wouldn't be terribly expensive either.

You could create a second table as described.  Depending on the version of cassandra you're running alternatively you could also create a MATERIALIZED VIEW from your user table to achieve this same lookup. These are something you wouldn't want to use if you're updating the last_seen property frequently as they'll do delete's when rows are updated.  So maybe limit it to just display->userId.

Once you have the lookup setup you still have to worry about race conditions where two users steal the same username.  In this case you might consider Light weight transactions.  That said, you want to avoid doing these frequently as they are expensive.

LWT do come with some issues though, like they're not "true" transactions and they're slower than a standard read/write.  Just make sure you know what you're getting.

Body:
I'm creating a table in cassandra for users. Users have both a unique user_id and a unique display_name.

My table currently resembles:

create table user (user_id text primary key,
    display_name text,
    joined timestamp,
    last_seen timestamp,
    ...);

When a new user creates an account I need to check if the display name they enter is already someone else's. What's the fastest way I can do this?

This project is primarily a learning project for me, I want to experiment with some NoSQL concepts in a semi-real-world situation.

My own thoughts are that using two tables like this:

create table user (user_id text primary key,
    display_name text,
    joined timestamp,
    last_seen timestamp,
    ...);

create table user_by_display_name (display_name text primary key, user_id text);

And then looking up in user_by_display_name for existence of a username will be faster than looking up in user where display_name = ?. Is this a correct assumption?

I feel that two lookups on primary keys, user_by_display_name where display_name = ? and then another lookup using the user_id in user might be slower than the single user where display_name = ? lookup if I need the information about that user.

Body:
Your assumption is correct, you will want to denormalize as described.  You design your queries first and then build the tables.

Your table should look like

CREATE TABLE users (
  user_id text,
  display_name text,
  last_seen timestamp,
  PRIMARY KEY(user_id)
WITH ...);

CREATE TABLE users_by_display_name (
  display_name text,
  user_id text,
  last_seen timestamp,
  PRIMARY KEY(display_name);

This way you do 1 lookup.  Writes are cheap, reads are expensive.  Avoid reads when possible.  That said, your partitions are 1 row and you're doing a lookup in a Key value database.  Your second select wouldn't be terribly expensive either.

You could create a second table as described.  Depending on the version of cassandra you're running alternatively you could also create a MATERIALIZED VIEW from your user table to achieve this same lookup. These are something you wouldn't want to use if you're updating the last_seen property frequently as they'll do delete's when rows are updated.  So maybe limit it to just display->userId.

Once you have the lookup setup you still have to worry about race conditions where two users steal the same username.  In this case you might consider Light weight transactions.  That said, you want to avoid doing these frequently as they are expensive.

LWT do come with some issues though, like they're not "true" transactions and they're slower than a standard read/write.  Just make sure you know what you're getting.


问:
How do I assemble pieces of HTML into a DOMDocument?
It appears that loadHTML and loadHTMLFile for a files representing sections of an HTML document seem to fill in html and body tags for each section, as revealed when I output with the following:

```<code>$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$elements = $doc->getElementsByTagName('*');

if( !is_null($elements) ) {
    foreach( $elements as $element ) {
        echo "<br/>". $element->nodeName. ": ";

        $nodes = $element->childNodes;
        foreach( $nodes as $node ) {
            echo $node->nodeValue. "\n";
        }
    }
}
</code>```

Since I plan to assemble these parts into the larger document within my own code, and I've been instructed to use DOMDocument to do it, what can I do to prevent this behavior?

答:
This is part of several modifications the HTML parser module of libxml makes to the document in order to work with broken HTML. It only occurs when using loadHTML and loadHTMLFile on partial markup. If you know the partial is valid X(HT)ML, use load and loadXML instead.

You could use

```<code>$doc->saveXml($doc->getElementsByTagName('body')->item(0));
</code>```

to dump the outerHTML of the body element, e.g. anything else and strip the body element with str_replace or extract the inner html with substr.

```<code>$html = '<p>I am a fragment</p>';
$dom = new DOMDocument;
$dom->loadHTML($html); // added html and body tags
echo substr(
    $dom->saveXml(
        $dom->getElementsByTagName('body')->item(0)
    ),
    6, -7
);
// <p>I am a fragment</p>
</code>```

Note that this will use XHTML compliant markup, so
 would become
. As of PHP 5.3.5, there is no way to pass a node to saveHTML(). A bug request has been filed.

Body:
It appears that loadHTML and loadHTMLFile for a files representing sections of an HTML document seem to fill in html and body tags for each section, as revealed when I output with the following:

$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$elements = $doc->getElementsByTagName('*');

if( !is_null($elements) ) {
    foreach( $elements as $element ) {
        echo "
". $element->nodeName. ": ";

        $nodes = $element->childNodes;
        foreach( $nodes as $node ) {
            echo $node->nodeValue. "\n";
        }
    }
}

Since I plan to assemble these parts into the larger document within my own code, and I've been instructed to use DOMDocument to do it, what can I do to prevent this behavior?

Body:
This is part of several modifications the HTML parser module of libxml makes to the document in order to work with broken HTML. It only occurs when using loadHTML and loadHTMLFile on partial markup. If you know the partial is valid X(HT)ML, use load and loadXML instead.

You could use

$doc->saveXml($doc->getElementsByTagName('body')->item(0));

to dump the outerHTML of the body element, e.g. <body>anything else</body> and strip the body element with str_replace or extract the inner html with substr.

$html = '<p>I am a fragment</p>';
$dom = new DOMDocument;
$dom->loadHTML($html); // added html and body tags
echo substr(
    $dom->saveXml(
        $dom->getElementsByTagName('body')->item(0)
    ),
    6, -7
);
// <p>I am a fragment</p>

Note that this will use XHTML compliant markup, so <br> would become <br/>. As of PHP 5.3.5, there is no way to pass a node to saveHTML(). A bug request has been filed.


问:
Error locating module for declaration in ASP.NET Core angular
Getting error when tries to generate new angular components using command

ng g component login-form

Error locating module for declaration. No module files found.

I think angular CLI its throwing error since out of the box angular template in ASP.NET Core is has different file names, Please suggest alternative way to generate angular components in ASP.NET Core projects.

答:
First of all after installing angular cli globally:

npm install @angular/cli@latest -g

You have to first create an angular project outside your main project with this command:

ng new hello-world

Now, go to project directory and copy .angular-cli.json file into the root of your main dot net core project.
Then you have to edit this part of the file:

"root" : "src"  change to  "root" : "ClientApp"

Next, you have to install angularCli dev in your root of your project:

cd DotNetCoreProject

npm install @angular/cli@latest --save-dev

Everythings was done!

Now, go to your component directory of your project:

cd ClientApp/app/components

and make your component in component directory in terminal:

ng g c MyComponent --module='app.module.browser.ts'
hope that was usefull...


答: There's no reason to have that class views line there. Remove it.

Title: Using django name 'HttpResponse' is not defined


问:
How to configure TSLint one-line for some rules and the opposite for others?
There is the one-line config where I can force the code, for example, else to go in the same line as the if's }.

```<code>"one-line": [
  true,
  "check-open-brace",
  "check-catch",
  "check-else",
  "check-finally",
  "check-whitespace"
],
</code>```

What I want to do is keep these two as one-line

```<code>"one-line": [
  true,
  "check-open-brace",
  "check-whitespace"
],
</code>```

but force others to go in a separated line

```<code>"check-catch",
"check-else",
"check-finally",
</code>```

So I can force

```<code>if () {
}
else {
}
</code>```

I'm currently using TSLint@3.9.0. How can I set this up?

答:
There is tslint-eslint-rules packege, which makes possible to run (some) of the eslint rules in tslint. Luckily, the brace-style rule is implemented and your brace-style can be enforced by:

```<code>"brace-style": ["error", "stroustrup"]
</code>```

(I didn't tried it, it is possible that it requires some tweaking)

Body:
There is the one-line config where I can force the code, for example, else to go in the same line as the if's }.

"one-line": [
  true,
  "check-open-brace",
  "check-catch",
  "check-else",
  "check-finally",
  "check-whitespace"
],

What I want to do is keep these two as one-line

"one-line": [
  true,
  "check-open-brace",
  "check-whitespace"
],

but force others to go in a separated line

"check-catch",
"check-else",
"check-finally",

So I can force

if () {
}
else {
}

I'm currently using TSLint@3.9.0. How can I set this up?

Body:
There is tslint-eslint-rules packege, which makes possible to run (some) of the eslint rules in tslint. Luckily, the brace-style rule is implemented and your brace-style can be enforced by:

"brace-style": ["error", "stroustrup"]

(I didn't tried it, it is possible that it requires some tweaking)


问:
How do I generate dynamic and static libraries from OpenSSL?
From this Compilation and Installation on the OpenSSL wiki... I understand that when you use the shared option you get a shared object and when you use no-shared, you only get the static library.

How can I get the static library and the shared object building OpenSSL only once?

答:
shared is the default, and results in both shared and static libraries
being built. Only if you specify no-shared will the shared libraries not be built.


问:
PHP Error Array to string conversion
I have class Router which has array of routes property

```<code><?php
class Router
{
    private $routes = [];

    function setRoutes(array $routes)
    {
        $this->$routes = $routes;
    }
}
?>
</code>```

In other File routes.php :

```<code><?php
$routes = [
    'users' => 'users.php',
    'comments' => 'comments.php'
];
?>
</code>```

And I use it like :

```<code><?php
require __DIR__ .'/Data.php';
require __DIR__ .'/Router.php';
require __DIR__ .'/../routes.php';

$router = new Router;
$router->setRoutes($routes);
$url = $_SERVER['REQUEST_URI'];
?>
</code>```

But I'm getting

Notice: Array to string conversion in /../XAMPP/xamppfiles/htdocs/TestPro/core/Router.php

Why this error is occurring ?

答:
You problem is the use of private variable in the class, you need change the class for:

```<code>class Router {

    private $routes = array();

    function setRoutes(array $routes){
</code>```

$this->routes = $routes;

```<code>    }

}
</code>```

Title: PHP Error Array to string conversion

Body:
I have class Router which has array of routes property

<?php
class Router
{
    private $routes = [];

    function setRoutes(array $routes)
    {
        $this->$routes = $routes;
    }
}
?>

In other File routes.php :

<?php
$routes = [
    'users' => 'users.php',
    'comments' => 'comments.php'
];
?>

And I use it like :

<?php
require __DIR__ .'/Data.php';
require __DIR__ .'/Router.php';
require __DIR__ .'/../routes.php';

$router = new Router;
$router->setRoutes($routes);
$url = $_SERVER['REQUEST_URI'];
?>

But I'm getting

Notice: Array to string conversion in /../XAMPP/xamppfiles/htdocs/TestPro/core/Router.php

Why this error is occurring ?

Body:
You problem is the use of private variable in the class, you need change the class for:

class Router {

    private $routes = array();

    function setRoutes(array $routes){

$this->routes = $routes;

    }

}


问:
bash: will the read command recive input from an empty command?
new to bash. i want a "while read line" loop the gets input from a command-in this case, grep. i want the read to read each line the grep returns and insert it as a string to the "line" var. in case the grep returns no results, i still want it to enter the loop so i can printf something and then continue. will it work? here's the code segement:

```<code>while read -r line: do

    ...(irrelevent)...

        done<$(grep $id ${arrpre[$j]}.course)
</code>```

${arrpre[$j]}.course is the name of the file. tnx for the help!

答:
[I]n case the grep returns no results, i still want it to enter the loop so i can printf something and then continue. will it work?

No.  If you're piping the output of a command (i.e. grep) into the while loop, and that command produces no output at all, then read will see end-of-file on its first execution.  read returns a failure code when it encounters end-of-file, which will cause the loop to terminate without its body being executed.  If this were not the case then you would have an extra iteration of the while loop in every case, whether there was any data to read or not.

But you can explicitly record whether the loop body is ever executed, and afterward take appropriate action.  For example:

```<code>empty=1
while read -r line: do
  empty=0
  #  ...
done < $(grep $id ${arrpre[$j]}.course)

if [ $empty -eq 1 ]; then
  # ... stuff to do in the event of empty grep output
fi
</code>```

Body:
new to bash. i want a "while read line" loop the gets input from a command-in this case, grep. i want the read to read each line the grep returns and insert it as a string to the "line" var. in case the grep returns no results, i still want it to enter the loop so i can printf something and then continue. will it work? here's the code segement:

while read -r line: do

    ...(irrelevent)...

        done<$(grep $id ${arrpre[$j]}.course)

${arrpre[$j]}.course is the name of the file. tnx for the help!

Body:
[I]n case the grep returns no results, i still want it to enter the loop so i can printf something and then continue. will it work?

No.  If you're piping the output of a command (i.e. grep) into the while loop, and that command produces no output at all, then read will see end-of-file on its first execution.  read returns a failure code when it encounters end-of-file, which will cause the loop to terminate without its body being executed.  If this were not the case then you would have an extra iteration of the while loop in every case, whether there was any data to read or not.

But you can explicitly record whether the loop body is ever executed, and afterward take appropriate action.  For example:

empty=1
while read -r line: do
  empty=0
  #  ...
done < $(grep $id ${arrpre[$j]}.course)

if [ $empty -eq 1 ]; then
  # ... stuff to do in the event of empty grep output
fi


问:
Styling the cancel button in a UISearchBar
I have a UISearchBar that has a cancel button (it's displayed using -(void)setShowsCancelButton:animated). I've changed the tintColor of the search bar like this in an attempt to get a grayish searchbar:

```<code>UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
searchBar.tintColor = [UIColor colorWithWhite:0.8 alpha:1.0];
</code>```

This is what it looks like now - notice how the cancel button is also gray: http://twitpic.com/c0hte

Is there a way to set the color of the cancel button separately so it looks more like this: http://twitpic.com/c0i6q

答:
For iOS 11 and Swift 4.
Create a subclass of UISearchController.
Override method:</p>

```<code>override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("layout")
        if let btn = searchBar.subviews[0].subviews[2] as? UIButton {
            btn.frame = CGRect(x: 306, y: 20, width: 53, height: 30)
        }
}
</code>```

Body:
I have a UISearchBar that has a cancel button (it's displayed using -(void)setShowsCancelButton:animated). I've changed the tintColor of the search bar like this in an attempt to get a grayish searchbar:

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
searchBar.tintColor = [UIColor colorWithWhite:0.8 alpha:1.0];

This is what it looks like now - notice how the cancel button is also gray: http://twitpic.com/c0hte

Is there a way to set the color of the cancel button separately so it looks more like this: http://twitpic.com/c0i6q

Body:
For iOS 11 and Swift 4.
Create a subclass of UISearchController.
Override method:

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("layout")
        if let btn = searchBar.subviews[0].subviews[2] as? UIButton {
            btn.frame = CGRect(x: 306, y: 20, width: 53, height: 30)
        }
}


问:
How to pass result to HTML in Mojolicious?
I need to pass the result of
Mojo::mysql
to $variable in HTML

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

use Mojolicious::Lite;
use Mojo::mysql;

helper mysql => sub {
    state $pg = Mojo::mysql->new( 'mysql://mysql://sri:s3cret@localhost/db' )
};

get '/index' => sub {
    my $c  = shift;
    my $db = $c->mysql->db;
    $db->query( 'select now() as time' )->hash;
};

app->start;

__DATA__

@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= $db %></body>
</html>`
</code>```

I need to pass the result of $db to index, but I don't know how to this.

答:
You never rendered your index template. To do so, call the render method on your controller. Any variables in your stash (or other arguments to the render function) are turned into variables in your template.

So we would have something like this:

```<code>get '/index' => sub {
    my $c  = shift;
    ...
    my $result = $db->query(...)->hash;
    return $c->render(template => 'index', result => $result);
};

...

__DATA__

@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= dumper $result %></body>
</html>
</code>```

(Here I've used the dumper helper so that the hash ref produces useful output, not just HASH(0x123abc).)

Further reading:

Mojolicious::Guides::Rendering

render() in Mojolicious::Controller

Body:
I need to pass the result of
Mojo::mysql
to $variable in HTML

#!/usr/bin/env perl

use Mojolicious::Lite;
use Mojo::mysql;

helper mysql => sub {
    state $pg = Mojo::mysql->new( 'mysql://mysql://sri:s3cret@localhost/db' )
};

get '/index' => sub {
    my $c  = shift;
    my $db = $c->mysql->db;
    $db->query( 'select now() as time' )->hash;
};

app->start;

__DATA__

@@ index.html.ep
<!DOCTYPE html>

<title><%= title %></title>
<%= $db %>
`

I need to pass the result of $db to index, but I don't know how to this.

Body:
You never rendered your index template. To do so, call the render method on your controller. Any variables in your stash (or other arguments to the render function) are turned into variables in your template.

So we would have something like this:

get '/index' => sub {
    my $c  = shift;
    ...
    my $result = $db->query(...)->hash;
    return $c->render(template => 'index', result => $result);
};

...

__DATA__

@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= dumper $result %></body>
</html>

(Here I've used the dumper helper so that the hash ref produces useful output, not just HASH(0x123abc).)

Further reading:

Mojolicious::Guides::Rendering

render() in Mojolicious::Controller


问:
How to indicate in a human readable way that a function is returned within a function in scala?
As a beginner in scala, I have written a method in scala that returns another function:

```<code>def foo(fnords: Seq[Fnord]): Poit => Boolean {
  (poit: Poit) => {
      fnords.contains(poit.fnord)
  }
}
</code>```

I noticed that I was often confused by my own line of codes wondering why I would return

```<code>fnords.contains(poit.fnord)
</code>```

even though I in fact correctly return the entire function:

```<code>(poit: Poit) => {
  fnords.contains(poit.fnord)
}
</code>```

I am wondering if one can make it more explicit to the human eye that a callable is returned or if this is something one has to become used to when writing scala.

Possible ways I found was using the return explicitly, which then the linter warns against via "Return keyword is redundant":

```<code>def foo(fnords: Seq[Fnord]): Poit => Boolean {
  return (poit: Poit) => {
      fnords.contains(poit.fnord)
  }
}
</code>```

I know that I could store the function inside a variable, yet it also feels like doing an explicit return without writing return:

```<code>def foo(fnords: Seq[Fnord]): Poit => Boolean {
  val filterFunction = (poit: Poit) => {
      fnords.contains(poit.fnord)
  }

  filterFunction
}
</code>```

Is there another way to provide feedback that a callable is returned in scala?

答:
You can write it either as function

```<code>def foo(fnords: Seq[Fnord]): Poit => Boolean =
    (poit: Poit) => fnords.contains(poit.fnord)
</code>```

or just

```<code>def foo(fnords: Seq[Fnord]): Poit => Boolean =
    poit => fnords.contains(poit.fnord)
</code>```

or as method

```<code>def foo(fnords: Seq[Fnord])(poit: Poit): Boolean =
    fnords.contains(poit.fnord)
</code>```

and use it

```<code>val f: Poit => Boolean = foo(Seq(fnord))
f(poit)
</code>```

To my taste

```<code>def foo(fnords: Seq[Fnord]): Poit => Boolean = {
  val filterFunction = (poit: Poit) => fnords.contains(poit.fnord)

  filterFunction
}
</code>```

is ok.

Body:
As a beginner in scala, I have written a method in scala that returns another function:

def foo(fnords: Seq[Fnord]): Poit => Boolean {
  (poit: Poit) => {
      fnords.contains(poit.fnord)
  }
}

I noticed that I was often confused by my own line of codes wondering why I would return

fnords.contains(poit.fnord)

even though I in fact correctly return the entire function:

(poit: Poit) => {
  fnords.contains(poit.fnord)
}

I am wondering if one can make it more explicit to the human eye that a callable is returned or if this is something one has to become used to when writing scala.

Possible ways I found was using the return explicitly, which then the linter warns against via "Return keyword is redundant":

def foo(fnords: Seq[Fnord]): Poit => Boolean {
  return (poit: Poit) => {
      fnords.contains(poit.fnord)
  }
}

I know that I could store the function inside a variable, yet it also feels like doing an explicit return without writing return:

def foo(fnords: Seq[Fnord]): Poit => Boolean {
  val filterFunction = (poit: Poit) => {
      fnords.contains(poit.fnord)
  }

  filterFunction
}

Is there another way to provide feedback that a callable is returned in scala?

Body:
You can write it either as function

def foo(fnords: Seq[Fnord]): Poit => Boolean =
    (poit: Poit) => fnords.contains(poit.fnord)

or just

def foo(fnords: Seq[Fnord]): Poit => Boolean =
    poit => fnords.contains(poit.fnord)

or as method

def foo(fnords: Seq[Fnord])(poit: Poit): Boolean =
    fnords.contains(poit.fnord)

and use it

val f: Poit => Boolean = foo(Seq(fnord))
f(poit)

To my taste

def foo(fnords: Seq[Fnord]): Poit => Boolean = {
  val filterFunction = (poit: Poit) => fnords.contains(poit.fnord)

  filterFunction
}

is ok.


问:
configuring language in Bootstrap Date Range Picker
I am using the Bootstrap Date Range Picker provided and explained In this page I added all the library using the cdn, I mean this:

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css" />

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />
```

But the thing is that I need all in spanish and I don´t see a piece of code to configurate it. How should I do it?

答:
I made an 'pt-br' example based on @davidkonrad's comment

```<code>$('input[name="daterange"]').daterangepicker({
"locale": {
    "format": "DD/MM/YYYY",
    "separator": " - ",
    "applyLabel": "Aplicar",
    "cancelLabel": "Cancelar",
    "fromLabel": "De",
    "toLabel": "Até",
    "customRangeLabel": "Custom",
    "daysOfWeek": [
        "Dom",
        "Seg",
        "Ter",
        "Qua",
        "Qui",
        "Sex",
        "Sáb"
    ],
    "monthNames": [
        "Janeiro",
        "Fevereiro",
        "Março",
        "Abril",
        "Maio",
        "Junho",
        "Julho",
        "Agosto",
        "Setembro",
        "Outubro",
        "Novembro",
        "Dezembro"
    ],
    "firstDay": 0
}});
</code>```

https://jsfiddle.net/joaopedroraldi/d7bmppga/55

Body:
I am using the Bootstrap Date Range Picker provided and explained In this page I added all the library using the cdn, I mean this:

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css" />

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

But the thing is that I need all in spanish and I don´t see a piece of code to configurate it. How should I do it?

Body:
I made an 'pt-br' example based on @davidkonrad's comment

$('input[name="daterange"]').daterangepicker({
"locale": {
    "format": "DD/MM/YYYY",
    "separator": " - ",
    "applyLabel": "Aplicar",
    "cancelLabel": "Cancelar",
    "fromLabel": "De",
    "toLabel": "Até",
    "customRangeLabel": "Custom",
    "daysOfWeek": [
        "Dom",
        "Seg",
        "Ter",
        "Qua",
        "Qui",
        "Sex",
        "Sáb"
    ],
    "monthNames": [
        "Janeiro",
        "Fevereiro",
        "Março",
        "Abril",
        "Maio",
        "Junho",
        "Julho",
        "Agosto",
        "Setembro",
        "Outubro",
        "Novembro",
        "Dezembro"
    ],
    "firstDay": 0
}});

https://jsfiddle.net/joaopedroraldi/d7bmppga/55


问:
scanf_s doesn't work visual studio
```<code>#include <windows.h>
#include <stdio.h>
#define WIN32_LEAN_AND_MEAN
</code>```

vis studio 2017,
doesn't matter what i do,

```<code>int main(){
    char c = 's';
    scanf_s(" %c", &c, 1);
}
</code>```

simple program, changing scanf_s line to

```<code>scanf_s("%c", &c, 1);
</code>```

again to,

```<code>scanf_s("%1c", &c, 1);
</code>```

etc nothing works I get a debug error

```<code>scanf_s(" %1c", &c, sizeof(c));
</code>```

again, error, I don't know what the problem is

```<code>scanf_s("%c",&c);
</code>```

it brings me to this line in debugger:

```<code>{
    return __stdio_common_vfscanf(
        _CRT_INTERNAL_LOCAL_SCANF_OPTIONS | _CRT_INTERNAL_SCANF_SECURECRT,
        _Stream, _Format, _Locale, _ArgList);
}
#endif
</code>```

答: I created a new project and it fixed the problem</p>

Title: scanf_s doesn't work visual studio

Body:
#include <windows.h>
#include <stdio.h>
#define WIN32_LEAN_AND_MEAN

vis studio 2017,
doesn't matter what i do,

int main(){
    char c = 's';
    scanf_s(" %c", &c, 1);
}

simple program, changing scanf_s line to

scanf_s("%c", &c, 1);

again to,

scanf_s("%1c", &c, 1);

etc nothing works I get a debug error

scanf_s(" %1c", &c, sizeof(c));

again, error, I don't know what the problem is

scanf_s("%c",&c);

it brings me to this line in debugger:

{
    return __stdio_common_vfscanf(
        _CRT_INTERNAL_LOCAL_SCANF_OPTIONS | _CRT_INTERNAL_SCANF_SECURECRT,
        _Stream, _Format, _Locale, _ArgList);
}
#endif