答:
I've tested this out and it works. It's much the same as the other answers though.

```<code>select messages.sender_id as users from (
    select t.id1, t.id2, t.start, messages.sender_id as initiator,
    messages.recipient_id as replier from (
        select greatest(sender_id, recipient_id) as id1,
        least(sender_id, recipient_id) as id2, min(Created_at) as start
        from messages group by id1, id2
    ) as t left join messages on messages.Created_at = t.start
    and ((messages.sender_id = t.id1 and messages.receiver_id = t.id2)
    or (messages.sender_id = t.id2 and messages.receiver_id = t.id1))
) as t inner join messages on messages.sender_id = t.replier
and messages.recipient_id = t.initiator
and messages.Created_at < date_add(t.start, interval 1 day)
group by users;
</code>```

The innermost query finds conversations by grouping messages by the two users involved, and finds the start of that conversation by taking the minimum Created_at.

The middle query finds the initiator and replier by looking up the first message in the conversation.

The outside query finds messages from the replier to the initiator (which are therefore in that conversation) within one day of the start of it, and groups by users so that they each appear only once (even if involved in multiple conversations).

Title: Get users who replied the first message of the conversation within 24hours

Body:
I need to find the users who replied the first message of the conversation (one to one conversation) within 24hours. I have a messages table where all data are stored.

Table: messages

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01
5  | 1002      | 500          | Hi there     | 2017-03-22 10:10:10
6  | 1002      | 500          | Can you meet?| 2017-03-22 10:15:32
7  | 500       | 1002         | Yes          | 2017-03-22 10:20:30
8  | 1003      | 600          | Hello world  | 2017-03-23 01:00:00
9  | 1004      | 700          | Hi           | 2017-03-23 08:10:10
10 | 700       | 1004         | hello        | 2017-03-26 22:00:00

Expected result:

users
256
500

Example: Conversation between user 1001 and 256.

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01

Here 2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10 is the first replied message of the conversation and its replied within 24 hours.

Body:
I've tested this out and it works. It's much the same as the other answers though.

select messages.sender_id as users from (
    select t.id1, t.id2, t.start, messages.sender_id as initiator,
    messages.recipient_id as replier from (
        select greatest(sender_id, recipient_id) as id1,
        least(sender_id, recipient_id) as id2, min(Created_at) as start
        from messages group by id1, id2
    ) as t left join messages on messages.Created_at = t.start
    and ((messages.sender_id = t.id1 and messages.receiver_id = t.id2)
    or (messages.sender_id = t.id2 and messages.receiver_id = t.id1))
) as t inner join messages on messages.sender_id = t.replier
and messages.recipient_id = t.initiator
and messages.Created_at < date_add(t.start, interval 1 day)
group by users;

The innermost query finds conversations by grouping messages by the two users involved, and finds the start of that conversation by taking the minimum Created_at.

The middle query finds the initiator and replier by looking up the first message in the conversation.

The outside query finds messages from the replier to the initiator (which are therefore in that conversation) within one day of the start of it, and groups by users so that they each appear only once (even if involved in multiple conversations).


来源: stackexchange

问:
How do I return JSON data to Riot.js from Node.js express server?
I'm developing a web application with Riot.js on client side and Node.js express on server side.
Riot.js can mount JSON data and can use for rendering HTML. Actually I have some JSON data on server side, and want to use them with Riot.js.

Currently my express server's code is quite simple.

```<code>  var express = require('express'),
      serveIndex = require('serve-index'),
      app = express();

  app.use(express.static(__dirname + '/public'));
  app.use(serveIndex(__dirname + '/public'));
  app.listen(3000);
</code>```

I think HTML template is helpful for my question. But I couldn't find answer with Riot.js, how do I use and render data from server?

Node & Express - How do I send a page AND some JS data to the browser in a single request?

I know how I mount data if the data is on client side like this:

```<code>    <script>
      riot.mount('my_hoge', {
        data: [
          { name: 'A', url: 'xxxx'},
          { name: 'B', url: 'yyy', isActive: true},
          { name: 'C', url: 'zzzz'}
        ]                                                                                })
   </script>
</code>```

environment

Node.js v5.3.0

express v4.13.3

答:
In one of their examples, they use fetch API to get data from a server.

```<code>window.fetch('http://api.fixer.io/latest?base=USD')
  .then(function(response) { return response.json() })
  .then(function(data) {
    var rates = Object.keys(data.rates)
      .map(function (key) { return { title: key, price: data.rates[key] }})
      .sort(function(a, b) { return a.price - b.price })
    self.update({ rates: rates })
})
</code>```

link to the repo

ContentLicense: CC BY-SA 3.0

Body:
I'm developing a web application with Riot.js on client side and Node.js express on server side.
Riot.js can mount JSON data and can use for rendering HTML. Actually I have some JSON data on server side, and want to use them with Riot.js.

Currently my express server's code is quite simple.

  var express = require('express'),
      serveIndex = require('serve-index'),
      app = express();

  app.use(express.static(__dirname + '/public'));
  app.use(serveIndex(__dirname + '/public'));
  app.listen(3000);

I think HTML template is helpful for my question. But I couldn't find answer with Riot.js, how do I use and render data from server?

Node & Express - How do I send a page AND some JS data to the browser in a single request?

I know how I mount data if the data is on client side like this:

environment

Node.js v5.3.0

express v4.13.3

Body:
In one of their examples, they use fetch API to get data from a server.

window.fetch('http://api.fixer.io/latest?base=USD')
  .then(function(response) { return response.json() })
  .then(function(data) {
    var rates = Object.keys(data.rates)
      .map(function (key) { return { title: key, price: data.rates[key] }})
      .sort(function(a, b) { return a.price - b.price })
    self.update({ rates: rates })
})

link to the repo


问:
Scala Akka actors, ask pattern, dead letters encountered while sending reply
I am trying to send a request to remote actor using ask pattern. The local actor recieves some value and it performs some task on it and updates it.
Then when local actor try to send back the updated value to remote actor , error occurs while sending. How should i handle this error?

Error:
[INFO] [03/31/2017 17:28:18.383] [ClientSystem-akka.actor.default-dispatcher-3] [akka://ClientSystem/deadLetters]
Message [check.package$Rcvdcxt] from Actor[akka://ClientSystem/user/localA1#1050660737] to Actor[akka://ClientSystem/deadLetters] was not delivered.
[1] dead letters encountered.

```<code>Remote Actor:

class RemoteActor() extends Actor {

    def receive = {

    case TaskFromLocal() =>{
        implicit val timeout: Timeout = 15000
        val currentSender = sender
        val f1 = currentSender ? RemoteActor.rtree.cxtA
            f1.onComplete{
            case Success(Rcvdcxt(cxtA))=>
                println("Success"+cxtA)
            case Success(s) =>
                    println("Success :"+s)
            case Failure(ex) =>
                    println("failure:"+ex)
            }
        }

  case _ => println("unknown msg")
  }
}
object RemoteActor{

    def createRndCxtC(count: Int):List[CxtC] = (for (i <- 1 to count) yield CxtC(Random.nextString(5), Random.nextInt())).toList
    def createRndCxtB(count: Int): List[CxtB] = (for (i <- 1 to count) yield CxtB(createRndCxtC(count), Random.nextInt())).toList
    def createRndCxtA(count: Int): List[CxtA] = (for (i <- 1 to count) yield CxtA(createRndCxtC(count), 5)).toList
    var rtree = RCxt(createRndCxtA(1),createRndCxtB(2),1,"")

    def main(args: Array[String]) {
        val configFile = getClass.getClassLoader.getResource("remote_application.conf").getFile
        val config = ConfigFactory.parseFile(new File(configFile))
        val system = ActorSystem("RemoteSystem" , config)
        val remoteActor = system.actorOf(Props[RemoteActor], name="remote")
        println("remote is ready")
   }
 }

Local Actor :

class LocalActorA extends Actor{

  @throws[Exception](classOf[Exception])
  val remoteActor = context.actorSelection("akka.tcp://RemoteSystem@127.0.0.1:5150/user/remote")

  def receive = {

    case TaskLA1(taskA) =>  {

    implicit val timeout: Timeout = 15000
      val rCxt = remoteActor ? TaskFromLocal()
      val currentSender = sender
      rCxt.onComplete{
            case Success(Rcvdcxt(cxtA))=>
              println("Success"+cxtA)
              println("Sender: "+ sender)
              currentSender ! Rcvdcxt(cxtA)

            case Success(s)=>
              println("Got nothing from Remote"+s)
              currentSender ! "Failuree"

            case Failure(ex) =>
              println("Failure in getting remote")
              currentSender ! "Failure"
            }
    }
  }
}

object LocalActorA {

    def createRndCxtC(count: Int):List[CxtC] = (for (i <- 1 to count) yield CxtC(Random.nextString(5), Random.nextInt())).toList
    def createRndCxtB(count: Int): List[CxtB] = (for (i <- 1 to count) yield CxtB(createRndCxtC(count), Random.nextInt())).toList
    def createRndCxtA(count: Int): List[CxtA] = (for (i <- 1 to count) yield CxtA(createRndCxtC(count), 3)).toList
    var tree = RCxt(createRndCxtA(2),createRndCxtB(2),1,"")

   def main(args: Array[String]) {
    val configFile = getClass.getClassLoader.getResource("local_application.conf").getFile
    val config = ConfigFactory.parseFile(new File(configFile))
    val system = ActorSystem("ClientSystem",config)
    val localActorA1 = system.actorOf(Props[LocalActorA], name="localA1")
    println("LocalActor A tree : "+tree)
    localActorA1 ! TaskLA1(new DummySum())
   }
}
</code>```

答:
Since you didn't post all the code I can't really tell exactly the error, but my best guess is related to the fact that you are calling sender in the onComplete in the LocalActor. This is unsafe and should be avoided at all costs. Instead, do something similar with the remote actor:

class LocalActor {
  def receive = {
    case TaskLA1(taskA) =>
      val currentSender = sender
      rCxt.onComplete {
        case Success(Rcvdcxt(cxtA))=>
          currentSender ! Rcvdcxt(cxtA)
          ...
      }
  }
}
```

Body:
I am trying to send a request to remote actor using ask pattern. The local actor recieves some value and it performs some task on it and updates it.
Then when local actor try to send back the updated value to remote actor , error occurs while sending. How should i handle this error?

Error:
[INFO] [03/31/2017 17:28:18.383] [ClientSystem-akka.actor.default-dispatcher-3] [akka://ClientSystem/deadLetters]
Message [check.package$Rcvdcxt] from Actor[akka://ClientSystem/user/localA1#1050660737] to Actor[akka://ClientSystem/deadLetters] was not delivered.
[1] dead letters encountered.

Remote Actor:

class RemoteActor() extends Actor {

    def receive = {

    case TaskFromLocal() =>{
        implicit val timeout: Timeout = 15000
        val currentSender = sender
        val f1 = currentSender ? RemoteActor.rtree.cxtA
            f1.onComplete{
            case Success(Rcvdcxt(cxtA))=>
                println("Success"+cxtA)
            case Success(s) =>
                    println("Success :"+s)
            case Failure(ex) =>
                    println("failure:"+ex)
            }
        }

  case _ => println("unknown msg")
  }
}
object RemoteActor{

    def createRndCxtC(count: Int):List[CxtC] = (for (i <- 1 to count) yield CxtC(Random.nextString(5), Random.nextInt())).toList
    def createRndCxtB(count: Int): List[CxtB] = (for (i <- 1 to count) yield CxtB(createRndCxtC(count), Random.nextInt())).toList
    def createRndCxtA(count: Int): List[CxtA] = (for (i <- 1 to count) yield CxtA(createRndCxtC(count), 5)).toList
    var rtree = RCxt(createRndCxtA(1),createRndCxtB(2),1,"")

    def main(args: Array[String]) {
        val configFile = getClass.getClassLoader.getResource("remote_application.conf").getFile
        val config = ConfigFactory.parseFile(new File(configFile))
        val system = ActorSystem("RemoteSystem" , config)
        val remoteActor = system.actorOf(Props[RemoteActor], name="remote")
        println("remote is ready")
   }
 }

Local Actor :

class LocalActorA extends Actor{

  @throws[Exception](classOf[Exception])
  val remoteActor = context.actorSelection("akka.tcp://RemoteSystem@127.0.0.1:5150/user/remote")

  def receive = {

    case TaskLA1(taskA) =>  {

    implicit val timeout: Timeout = 15000
      val rCxt = remoteActor ? TaskFromLocal()
      val currentSender = sender
      rCxt.onComplete{
            case Success(Rcvdcxt(cxtA))=>
              println("Success"+cxtA)
              println("Sender: "+ sender)
              currentSender ! Rcvdcxt(cxtA)

            case Success(s)=>
              println("Got nothing from Remote"+s)
              currentSender ! "Failuree"

            case Failure(ex) =>
              println("Failure in getting remote")
              currentSender ! "Failure"
            }
    }
  }
}

object LocalActorA {

    def createRndCxtC(count: Int):List[CxtC] = (for (i <- 1 to count) yield CxtC(Random.nextString(5), Random.nextInt())).toList
    def createRndCxtB(count: Int): List[CxtB] = (for (i <- 1 to count) yield CxtB(createRndCxtC(count), Random.nextInt())).toList
    def createRndCxtA(count: Int): List[CxtA] = (for (i <- 1 to count) yield CxtA(createRndCxtC(count), 3)).toList
    var tree = RCxt(createRndCxtA(2),createRndCxtB(2),1,"")

   def main(args: Array[String]) {
    val configFile = getClass.getClassLoader.getResource("local_application.conf").getFile
    val config = ConfigFactory.parseFile(new File(configFile))
    val system = ActorSystem("ClientSystem",config)
    val localActorA1 = system.actorOf(Props[LocalActorA], name="localA1")
    println("LocalActor A tree : "+tree)
    localActorA1 ! TaskLA1(new DummySum())
   }
}


问:
Corona/Lua Runtime Error
So recently I was adding "Tune" analytics to my app and when I tested on Corona Simulator everything worked just fine.
 But when I made apk build to android, I launched app and just on launch I got this error:

http://imgur.com/TUjhhE7

Can someone please help? I think that some problem is in build.settings

Whole "Tune" documentation:

https://developers.tune.com/sdk/corona-plugin-quick-start/

Thanks!

答:
Maybe try this

Activate Tune plugin in marketplace

Post Analytics Plugins - which to choose for now? suggest use of Google Analytics plugin (Tune plugin is incompatible with GPGS plugin)

Title: Corona/Lua Runtime Error


问:
how to write java 8 Comparator for Map values inside Map.Entry
Here is what I have, I want to sort in descending a the value in the entry.

```<code>Map<String, Outer> outer = Input
                          .entrySet()
                          .stream
                          .collect(toMap(Map.Entry::getKey, entry->{
                           List<Outer> inner = entry
                                    .getValue()
                                    .stream()
                                    .sorted(Comparator.comparingDouble(???))
                              })) ... (more lines of code.)
</code>```

How to write a Comparator with sorted.
If want to do the following inside sorted

```<code>if (o1.getSomething() > o2.getSomething())
     return -1;
if (o1.getSomething() < o2.getSomething())
     return 1;
return 0;
</code>```

After getting the List and sorting it works for me.

```<code>inner.sort((Outer o1, Outer o2) -> {
if (o1.getSomething() > o2.getSomething())
         return -1;
    if (o1.getSomething() < o2.getSomething())
         return 1;
    return 0;
});
</code>```

But is there a way to use stream.sorted( " use the same comparator logic here") inside entry.

Entry is an ArrayList, with bunch of values.

```<code>entry:[{w:1},{w:2},{w:3},{w:4}];
</code>```

So I want to reverse sort this, to be as follows:

```<code>entry:[{w:4},{w:3},{w:2},{w:1}];
</code>```

so the final list I get is a sorted in reverse order one.

sry for the confusion.

答:
If you're just trying to get the values of the Map and place them into a sorted List, you could do the following:

```<code>Map<String, Element> elMap = new HashMap<>();
elMap.put("3", new Element("3"));
elMap.put("2", new Element("2"));
elMap.put("1", new Element("1"));

List<Element> elList = elMap.values()
        .stream()
        .sorted((e1, e2) -> {
            return e1.getSortField().compareTo(e2.getSortField());
        })
        .collect(Collectors.toList());
System.out.println(elList);
</code>```

In here, Element is a simple POJO with a single String field called sortField. sorted() takes a Comparator. Which is a functional interface with 2 parameters and an int return type. Which was ok for the given lambda.

You could also let your element implement Comparable. Then you could do:

```<code>List<Element> elList = elMap.values()
        .stream()
        .sorted()
        .collect(Collectors.toList());
</code>```

With the Element implementing the correct Interface

```<code>static class Element implements Comparable<Element> {
    //Constructor, field, getters
    @Override
    public int compareTo(Element o) {
        return this.sortField.compareTo(o.sortField);
    }
}
</code>```

EDIT:

its a list inside the Map, that I am trying to sort. And trying to sort it in the chain itself.

This could be interpreted as the following:

```<code>Map<String, List<Element>> collected = elMap.entrySet()
        .stream()
        .peek(entry -> System.out.println("Performing arbitrary Map operations"))
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
            return entry.getValue()
                    .stream()
                    .sorted(Comparator.comparingDouble(Element::getWeight))
                    .collect(Collectors.toList());
        }));

collected.entrySet()
        .forEach(entry -> {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        });
</code>```

You stream over the ´Map.entrySet()´ and do whatever you want with it. When collecting it back into a different Map as per your question, you can stream and collect your List again with the examples from above.

Body:
Here is what I have, I want to sort in descending a the value in the entry.

Map<String, Outer> outer = Input
                          .entrySet()
                          .stream
                          .collect(toMap(Map.Entry::getKey, entry->{
                           List<Outer> inner = entry
                                    .getValue()
                                    .stream()
                                    .sorted(Comparator.comparingDouble(???))
                              })) ... (more lines of code.)

How to write a Comparator with sorted.
If want to do the following inside sorted

if (o1.getSomething() > o2.getSomething())
     return -1;
if (o1.getSomething() < o2.getSomething())
     return 1;
return 0;

After getting the List and sorting it works for me.

inner.sort((Outer o1, Outer o2) -> {
if (o1.getSomething() > o2.getSomething())
         return -1;
    if (o1.getSomething() < o2.getSomething())
         return 1;
    return 0;
});

But is there a way to use stream.sorted( " use the same comparator logic here") inside entry.

Entry is an ArrayList, with bunch of values.

entry:[{w:1},{w:2},{w:3},{w:4}];

So I want to reverse sort this, to be as follows:

entry:[{w:4},{w:3},{w:2},{w:1}];

so the final list I get is a sorted in reverse order one.

sry for the confusion.

Body:
If you're just trying to get the values of the Map and place them into a sorted List, you could do the following:

Map<String, Element> elMap = new HashMap<>();
elMap.put("3", new Element("3"));
elMap.put("2", new Element("2"));
elMap.put("1", new Element("1"));

List<Element> elList = elMap.values()
        .stream()
        .sorted((e1, e2) -> {
            return e1.getSortField().compareTo(e2.getSortField());
        })
        .collect(Collectors.toList());
System.out.println(elList);

In here, Element is a simple POJO with a single String field called sortField. sorted() takes a Comparator. Which is a functional interface with 2 parameters and an int return type. Which was ok for the given lambda.

You could also let your element implement Comparable. Then you could do:

List<Element> elList = elMap.values()
        .stream()
        .sorted()
        .collect(Collectors.toList());

With the Element implementing the correct Interface

static class Element implements Comparable<Element> {
    //Constructor, field, getters
    @Override
    public int compareTo(Element o) {
        return this.sortField.compareTo(o.sortField);
    }
}

EDIT:

its a list inside the Map, that I am trying to sort. And trying to sort it in the chain itself.

This could be interpreted as the following:

Map<String, List<Element>> collected = elMap.entrySet()
        .stream()
        .peek(entry -> System.out.println("Performing arbitrary Map operations"))
        .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
            return entry.getValue()
                    .stream()
                    .sorted(Comparator.comparingDouble(Element::getWeight))
                    .collect(Collectors.toList());
        }));

collected.entrySet()
        .forEach(entry -> {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        });

You stream over the ´Map.entrySet()´ and do whatever you want with it. When collecting it back into a different Map as per your question, you can stream and collect your List again with the examples from above.


问:
WindowsForms - searching for "Parameters" in a RichTextBox
I want to read some user input from a richtextbox in WindowsForms.

I want the user, to write text by a specific format, example:

```<code>string text = "[3,true]#[5,false]#[9,false]"; // users input from the textfield
</code>```

So what I want, is a List of strings.

```<code>List<Tuple<string, string>> tempList = new List<Tuple<string, string>>();
</code>```

This list is filled by the values above

```<code>tempList .Add(new Tuple<string, string>("3", "true"));
tempList.Add(new Tuple<string, string>("5", "false"));
tempList.Add(new Tuple<string, string>("9", "false"));
</code>```

And I do not really know, how to search substrings from a big text.

This is what I got so far:

```<code>private string FindNeighbourInText(string source, string start, string end)
{
    int startPos;
    int endPos;
    if (source.Contains(start) && source.Contains(end))
    {
        startPos = source.IndexOf(start, 0) + start.Length;
        endPos = source.IndexOf(end, startPos);
        return source.Substring(startPos, endPos - startPos);
    }
    else
        return string.Empty;
}
</code>```

But it seems, that this is not the correct thing, I am looking for.

答:
This is an ideal job for Regular Expressions.
You can use this pattern to capture all the variables, with named groups for the number and value \[(?<number>.*?),(?<value>.*?)\].

It looks for strings of characters between [ and ].
Those characters are made up of the pattern (characters),(characters).
The characters before the comma are placed in a group named number, and the ones after the comma are named value.

Then it is just a matter of looping through all the matches and looking at the value of the captured named groups.

In code it would look like this:

```<code>void Main()
{
    var data = "[3,true]#[5,false]#[9,false]";
    var pattern = new Regex(@"\[(?<number>.*?),(?<value>.*?)\]");

    foreach (Match match in pattern.Matches(data))
    {
        Console.WriteLine($"{match.Groups["number"]} = {match.Groups["value"]}" );
    }
}
</code>```

It produces the following output:

```<code>3 = true
5 = false
9 = false
</code>```

Here is a Fiddle for it.

Body:
I want to read some user input from a richtextbox in WindowsForms.

I want the user, to write text by a specific format, example:

string text = "[3,true]#[5,false]#[9,false]"; // users input from the textfield

So what I want, is a List of strings.

List<Tuple<string, string>> tempList = new List<Tuple<string, string>>();

This list is filled by the values above

tempList .Add(new Tuple<string, string>("3", "true"));
tempList.Add(new Tuple<string, string>("5", "false"));
tempList.Add(new Tuple<string, string>("9", "false"));

And I do not really know, how to search substrings from a big text.

This is what I got so far:

private string FindNeighbourInText(string source, string start, string end)
{
    int startPos;
    int endPos;
    if (source.Contains(start) && source.Contains(end))
    {
        startPos = source.IndexOf(start, 0) + start.Length;
        endPos = source.IndexOf(end, startPos);
        return source.Substring(startPos, endPos - startPos);
    }
    else
        return string.Empty;
}

But it seems, that this is not the correct thing, I am looking for.

Body:
This is an ideal job for Regular Expressions.
You can use this pattern to capture all the variables, with named groups for the number and value \[(?<number>.*?),(?<value>.*?)\].

It looks for strings of characters between [ and ].
Those characters are made up of the pattern (characters),(characters).
The characters before the comma are placed in a group named number, and the ones after the comma are named value.

Then it is just a matter of looping through all the matches and looking at the value of the captured named groups.

In code it would look like this:

void Main()
{
    var data = "[3,true]#[5,false]#[9,false]";
    var pattern = new Regex(@"\[(?<number>.*?),(?<value>.*?)\]");

    foreach (Match match in pattern.Matches(data))
    {
        Console.WriteLine($"{match.Groups["number"]} = {match.Groups["value"]}" );
    }
}

It produces the following output:

3 = true
5 = false
9 = false

Here is a Fiddle for it.


答:
You can define the Comparator and then use stream.sorted() as shown below with inline comments:

```<code>//Define comparator Lamda exp for Outer class
Comparator<Outer> outerComparator = (o1, o2) -> {
         if (o1.getValue() > o2.getValue())
                return -1;
          else if (o1.getValue() < o2.getValue())
                return 1;
            else
              return 0;
   };

Map<String, Outer> output = Input.entrySet(). //get elements
        stream(). //get elements
        sorted( //sort elements by passsing outerComparator
        Map.Entry.<String, Outer>comparingByValue(outerComparator)
        .reversed())//reverse for descending order
        .collect(Collectors.toMap(Map.Entry::getKey,
        Map.Entry::getValue));//collect to Map object
</code>```

Title: how to write java 8 Comparator for Map values inside Map.Entry

Body:
You can define the Comparator and then use stream.sorted() as shown below with inline comments:

//Define comparator Lamda exp for Outer class
Comparator<Outer> outerComparator = (o1, o2) -> {
         if (o1.getValue() > o2.getValue())
                return -1;
          else if (o1.getValue() < o2.getValue())
                return 1;
            else
              return 0;
   };

Map<String, Outer> output = Input.entrySet(). //get elements
        stream(). //get elements
        sorted( //sort elements by passsing outerComparator
        Map.Entry.<String, Outer>comparingByValue(outerComparator)
        .reversed())//reverse for descending order
        .collect(Collectors.toMap(Map.Entry::getKey,
        Map.Entry::getValue));//collect to Map object


问:
How to include a .lib file dynamically?
I've got a problem with my project. I am developing it on Qt Creator, and I need to add a .lib file to my project. So, I wrote this line in my .pro :

```<code>LIBS += "C:\My_Path\My_Project\lib\file.lib"
</code>```

This is working fine. My only issue is that I need to write the entire path to the .lib file. Since it's a group project, it needs to be compilable on other computers without changing the path to this file every times.

I tried many syntaxes, like :

```<code>LIBS += -L"lib/" -l"file.lib"
</code>```

or

```<code>LIBS += "lib\file.lib"
</code>```

or

```<code>LIBS += "file.lib"
</code>```

(putting the .lib file at the root and adding it to the project in Qt Creator)

None of them works :/

I also tried to add the .lib file in a QResource file but a syntax like this one :

```<code>LIBS += ":/lib/file.lib"
</code>```

in a .pro file doesn't seem to work...

I am now running out of ideas :(

Help please :)

答:
From your tries I guess you want to link to the library using relative path which should work just fine by default.

Try this:

```<code>LIBS += -L$$relative/directory/path -llibname
</code>```

If it does not work, then you might want to try setting multiple INCLUDEPATH. :/

ContentLicense: CC BY-SA 2.5

Title: How to include a .lib file dynamically?

Body:
I've got a problem with my project. I am developing it on Qt Creator, and I need to add a .lib file to my project. So, I wrote this line in my .pro :

LIBS += "C:\My_Path\My_Project\lib\file.lib"

This is working fine. My only issue is that I need to write the entire path to the .lib file. Since it's a group project, it needs to be compilable on other computers without changing the path to this file every times.

I tried many syntaxes, like :

LIBS += -L"lib/" -l"file.lib"

or

LIBS += "lib\file.lib"

or

LIBS += "file.lib"

(putting the .lib file at the root and adding it to the project in Qt Creator)

None of them works :/

I also tried to add the .lib file in a QResource file but a syntax like this one :

LIBS += ":/lib/file.lib"

in a .pro file doesn't seem to work...

I am now running out of ideas :(

Help please :)

Body:
From your tries I guess you want to link to the library using relative path which should work just fine by default.

Try this:

LIBS += -L$$relative/directory/path -llibname

If it does not work, then you might want to try setting multiple INCLUDEPATH. :/


问:
Deserialize JSON to C# - Values from Checkboxes
I'm attempting to send form values over AJAX to a C# web service. Then, using JavaScriptSerializer.Deserialize, convert the JSON to a C# class. Below is the class:

```<code>[Serializable]
[DataContract(Name = "PostParameters")]
public class TagData
{
    public TagData()
    {
    }

    [DataMember(Name = "TargetId")]
    public string TargetId { get; set; }
    [DataMember(Name = "TargetType")]
    public string TargetType { get; set; }
    [DataMember(Name = "Tags")]
    public List<string> Tags { get; set; }
}
</code>```

Here is the method being called:

```<code>[WebMethod]
public string UpdateTags(string PostParameters)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var tagData = serializer.Deserialize<TagData>(PostParameters);
}
</code>```

This works when more than one checkbox is checked. The Tags property is successfully populated. However, when less than two items are checked, there is a conversion error. The serializer cannot convert the single string value to a List object.

Here is how the JSON is sent with one checkbox checked:
    {"Tags":"14","TargetId":"36946","TargetType":"Officer"}

Here is how the JSON is sent with more than one checkbox checked:
    {"Tags":["12","5","2"],"TargetId":"36946","TargetType":"Officer"}

I attempted changing the Tags property in my C# class to a string array:
    public string[] Tags { get; set; }
however, this resulted in the JSON not being mapped at all.

I also attempted adding [] to the checkbox input names like so:
    <input type="checkbox" name="tags[]" />

This sent the JSON across as so, with one checkbox checked:
    {"Tags[0]":"14","TargetId":"36946","TargetType":"Officer"}

and more than one checkboxes checked:    {"Tags[0]":"14","Tags[1]":"19","TargetId":"36946","TargetType":"Officer"}

This seems like it would work with the string array property, but it won't map for either that or the List property. The Tags property will always be null because it's unable to map.

UPDATE - Here's where the JSON is generated

```<code>var params = $.toJSON({ 'PostParameters': JSON.stringify($inputs.serializeObject()) });
</code>```

and here's the serializeObject() function:

```<code>serializeObject: function () {
    var obj = {},
    names = {};

    $.each(this.serializeArray(), function (i, o) {
        var n = o.name,
        v = o.value;

        if (n.includes('[]')) {
            names.n = !names.n ? 1 : names.n + 1;
            var indx = names.n - 1;
            n = n.replace('[]', '[' + indx + ']');
        }

        obj[n] = obj[n] === undefined ? v
          : $.isArray(obj[n]) ? obj[n].concat(v)
          : [obj[n], v];
    });

    return obj;
}
</code>```

Any help is appreciated.

答:
edit you client side code to send an array of one element in case of one checkbox is selected

JSON with one checkbox checked:

{"Tags":["14"],"TargetId":"36946","TargetType":"Officer"}

Body:
I'm attempting to send form values over AJAX to a C# web service. Then, using JavaScriptSerializer.Deserialize, convert the JSON to a C# class. Below is the class:

[Serializable]
[DataContract(Name = "PostParameters")]
public class TagData
{
    public TagData()
    {
    }

    [DataMember(Name = "TargetId")]
    public string TargetId { get; set; }
    [DataMember(Name = "TargetType")]
    public string TargetType { get; set; }
    [DataMember(Name = "Tags")]
    public List<string> Tags { get; set; }
}

Here is the method being called:

[WebMethod]
public string UpdateTags(string PostParameters)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var tagData = serializer.Deserialize<TagData>(PostParameters);
}

This works when more than one checkbox is checked. The Tags property is successfully populated. However, when less than two items are checked, there is a conversion error. The serializer cannot convert the single string value to a List object.

Here is how the JSON is sent with one checkbox checked:
    {"Tags":"14","TargetId":"36946","TargetType":"Officer"}

Here is how the JSON is sent with more than one checkbox checked:
    {"Tags":["12","5","2"],"TargetId":"36946","TargetType":"Officer"}

I attempted changing the Tags property in my C# class to a string array:
    public string[] Tags { get; set; }
however, this resulted in the JSON not being mapped at all.

I also attempted adding [] to the checkbox input names like so:
    <input type="checkbox" name="tags[]" />

This sent the JSON across as so, with one checkbox checked:
    {"Tags[0]":"14","TargetId":"36946","TargetType":"Officer"}

and more than one checkboxes checked:    {"Tags[0]":"14","Tags[1]":"19","TargetId":"36946","TargetType":"Officer"}

This seems like it would work with the string array property, but it won't map for either that or the List property. The Tags property will always be null because it's unable to map.

UPDATE - Here's where the JSON is generated

var params = $.toJSON({ 'PostParameters': JSON.stringify($inputs.serializeObject()) });

and here's the serializeObject() function:

serializeObject: function () {
    var obj = {},
    names = {};

    $.each(this.serializeArray(), function (i, o) {
        var n = o.name,
        v = o.value;

        if (n.includes('[]')) {
            names.n = !names.n ? 1 : names.n + 1;
            var indx = names.n - 1;
            n = n.replace('[]', '[' + indx + ']');
        }

        obj[n] = obj[n] === undefined ? v
          : $.isArray(obj[n]) ? obj[n].concat(v)
          : [obj[n], v];
    });

    return obj;
}

Any help is appreciated.


问:
No data when auto submitted
I have the below following :

```<code><form action=\"http://example.co.uk/order\" method=\"post\" id=\"vouchertwo\" >
  <input type=\"hidden\" id=\"discount_name\" name=\"discount_name\" value=\"123549\">
  <input type=\"hidden\" name=\"submitDiscount\">
  <button type=\"submit\" name=\"submitAddDiscount\" class=\"button btn btn-default button-small\"><span>OK</span></button>
  </fieldset>
</form>
</code>```

Currently running in php (thus the ) for now.

If I click the "OK" button manually, the voucher code 123549 is passed onto the cart and applied.

However, if I use:

```<code><script>
window.onload = function(){

document.getElementById(\"vouchertwo\").submit();
}
</script>
</code>```

to trigger the form, no value is passed along.

Any ideas what I am missing?

答:
Took your form as-is, added a button outside the form to test submitting programmatically, works fine. The slashes are causing all sorts of issues, but that's PHP for you...

Of course, without actually submitting the form to someplace, we get a weird error. As a sample, I've created an event listener for the submit function on the form. When the form's button is clicked, the form.submit is triggered, but when I call the form.submit(), it is not. A small gotcha, but worth noting.

/***
 * Created a dummy button that, when clicked,
 *   submits the full form.
 ***/
var myDummyButton = document.getElementById("dummyBtn");
var myForm = document.getElementById("vouchertwo");

myDummyButton.addEventListener("click", function(evt){
  evt.preventDefault();
  document.getElementById("vouchertwo").submit();
})

myForm.addEventListener("submit", function(evt){
  evt.preventDefault();
  console.log(this);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" method="post" id="vouchertwo">
  <input type="hidden" id="discount_name" name="discount_name" value="123549">
  <input type="hidden" name="submitDiscount">
  <button type="submit" name="submitAddDiscount" class="button btn btn-default button-small"><span>OK</span></button>
</form>

<input type="button" id="dummyBtn" value="Do it!" /></code>```

Now, there is a way to have both functions run the same functionality: rather than using form.submit(), use formElement.submitButtonElement.click(). By doing this, both methods will actually trigger the submit listener of the form. Take a look at this option:

/***
 * Created a dummy button that, when clicked,
 *   submits the full form.
 ***/
var myDummyButton = document.getElementById("dummyBtn");
var myForm = document.getElementById("vouchertwo");

myDummyButton.addEventListener("click", function(evt){
  evt.preventDefault();
  document.querySelector("#vouchertwo button").click();
})

myForm.addEventListener("submit", function(evt){
  evt.preventDefault();
  console.log(this.querySelector("#discount_name").value );
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" method="post" id="vouchertwo">
  <input type="hidden" id="discount_name" name="discount_name" value="123549">
  <input type="hidden" name="submitDiscount">
  <button type="submit" name="submitAddDiscount" class="button btn btn-default button-small"><span>OK</span></button>
</form>

<input type="button" id="dummyBtn" value="Do it!" /></code>```

Title: No data when auto submitted

Body:
I have the below following :

<form action=\"http://example.co.uk/order\" method=\"post\" id=\"vouchertwo\" >
  <input type=\"hidden\" id=\"discount_name\" name=\"discount_name\" value=\"123549\">
  <input type=\"hidden\" name=\"submitDiscount\">
  <button type=\"submit\" name=\"submitAddDiscount\" class=\"button btn btn-default button-small\">OK</button>
  </fieldset>
</form>

Currently running in php (thus the ) for now.

If I click the "OK" button manually, the voucher code 123549 is passed onto the cart and applied.

However, if I use:

to trigger the form, no value is passed along.

Any ideas what I am missing?

Body:
Took your form as-is, added a button outside the form to test submitting programmatically, works fine. The slashes are causing all sorts of issues, but that's PHP for you...

Of course, without actually submitting the form to someplace, we get a weird error. As a sample, I've created an event listener for the submit function on the form. When the form's button is clicked, the form.submit is triggered, but when I call the form.submit(), it is not. A small gotcha, but worth noting.

/***
 * Created a dummy button that, when clicked,
 *   submits the full form.
 ***/
var myDummyButton = document.getElementById("dummyBtn");
var myForm = document.getElementById("vouchertwo");

myDummyButton.addEventListener("click", function(evt){
  evt.preventDefault();
  document.getElementById("vouchertwo").submit();
})

myForm.addEventListener("submit", function(evt){
  evt.preventDefault();
  console.log(this);
})

<form action="#" method="post" id="vouchertwo">
  <input type="hidden" id="discount_name" name="discount_name" value="123549">
  <input type="hidden" name="submitDiscount">
  <button type="submit" name="submitAddDiscount" class="button btn btn-default button-small"><span>OK</span></button>
</form>

<input type="button" id="dummyBtn" value="Do it!" />

Now, there is a way to have both functions run the same functionality: rather than using form.submit(), use formElement.submitButtonElement.click(). By doing this, both methods will actually trigger the submit listener of the form. Take a look at this option:

/***
 * Created a dummy button that, when clicked,
 *   submits the full form.
 ***/
var myDummyButton = document.getElementById("dummyBtn");
var myForm = document.getElementById("vouchertwo");

myDummyButton.addEventListener("click", function(evt){
  evt.preventDefault();
  document.querySelector("#vouchertwo button").click();
})

myForm.addEventListener("submit", function(evt){
  evt.preventDefault();
  console.log(this.querySelector("#discount_name").value );
})

<form action="#" method="post" id="vouchertwo">
  <input type="hidden" id="discount_name" name="discount_name" value="123549">
  <input type="hidden" name="submitDiscount">
  <button type="submit" name="submitAddDiscount" class="button btn btn-default button-small"><span>OK</span></button>
</form>

<input type="button" id="dummyBtn" value="Do it!" />


问:
C memory leak that i can't find at all
So everything is fine with the program but i get a very annoying memory leak. I am sitting in front of my computer for couple hours and can figure it out.

We have 2 struck very simple, one struct is a double linked list and one is a hash table that stores that double linked list.

Now i am inserting a key and a data into the double linked list here is the function.

```<code>void htable_insert(htable* ht, int key, int data) {
    // TODO: Insert a new entry with the given key and data
    // Overwrite the old data if the key already exists, duplicate keys are not allowed
    ht_entry *new_node;
    ht_entry *head;
    ht_entry *it;
    int sameKey;
    int bucketPosition;

    new_node = (ht_entry*)malloc(1*sizeof(ht_entry));
    bucketPosition = key % ht->size;
    sameKey = 0;

    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next)
    {
      if(it->key == key) {
        it->data = data;
        sameKey = 1;
        free(new_node);
        new_node = NULL;
        break;

      }
    }

    if(!sameKey && new_node) {
      head = ht->entries[bucketPosition];
      if (head == NULL) {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        new_node->prev = NULL;
        ht->entries[bucketPosition] = new_node;
        new_node = NULL;

      } else {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        // new_node->prev = head;
        head->prev = new_node;
        head = new_node;
        ht->entries[bucketPosition] = head;

      }
    }
    // free(new_node);
    new_node = NULL;
    printf("%s\n %d", "INSERT:", key);
    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next){
      printf("it->key: %d\nit->data: %d\n", it->key, it->data);
    }

    printf("%s\n", "-------------------------------");

}
</code>```

Here is my valgrind message:

```<code>==10692== Memcheck, a memory error detector
==10692== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==10692== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==10692== Command: ./chain_hash_table.out
==10692==
==10692==
==10692== HEAP SUMMARY:
==10692==     in use at exit: 72 bytes in 3 blocks
==10692==   total heap usage: 10 allocs, 7 frees, 376 bytes allocated
==10692==
==10692== 24 bytes in 1 blocks are definitely lost in loss record 2 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400BD2: main (main.c:14)
==10692==
==10692== 48 (24 direct, 24 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400C25: main (main.c:18)
==10692==
==10692== LEAK SUMMARY:
==10692==    definitely lost: 48 bytes in 2 blocks
==10692==    indirectly lost: 24 bytes in 1 blocks
==10692==      possibly lost: 0 bytes in 0 blocks
==10692==    still reachable: 0 bytes in 0 blocks
==10692==         suppressed: 0 bytes in 0 blocks
==10692==
==10692== For counts of detected and suppressed errors, rerun with: -v
==10692== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
</code>```

And what i know it is always for first table insertion that is why it says at line main(18) for the rest after the first insertion there is no leaks.

Thank you guys for your time and help :)

答:
Check the break statement in the loop, it breaks on the first iteration
 and it does not deallocate the node.

The break should be placed inside the for loop.

Title: C memory leak that i can't find at all

Body:
So everything is fine with the program but i get a very annoying memory leak. I am sitting in front of my computer for couple hours and can figure it out.

We have 2 struck very simple, one struct is a double linked list and one is a hash table that stores that double linked list.

Now i am inserting a key and a data into the double linked list here is the function.

void htable_insert(htable* ht, int key, int data) {
    // TODO: Insert a new entry with the given key and data
    // Overwrite the old data if the key already exists, duplicate keys are not allowed
    ht_entry *new_node;
    ht_entry *head;
    ht_entry *it;
    int sameKey;
    int bucketPosition;

    new_node = (ht_entry*)malloc(1*sizeof(ht_entry));
    bucketPosition = key % ht->size;
    sameKey = 0;

    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next)
    {
      if(it->key == key) {
        it->data = data;
        sameKey = 1;
        free(new_node);
        new_node = NULL;
        break;

      }
    }

    if(!sameKey && new_node) {
      head = ht->entries[bucketPosition];
      if (head == NULL) {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        new_node->prev = NULL;
        ht->entries[bucketPosition] = new_node;
        new_node = NULL;

      } else {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        // new_node->prev = head;
        head->prev = new_node;
        head = new_node;
        ht->entries[bucketPosition] = head;

      }
    }
    // free(new_node);
    new_node = NULL;
    printf("%s\n %d", "INSERT:", key);
    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next){
      printf("it->key: %d\nit->data: %d\n", it->key, it->data);
    }

    printf("%s\n", "-------------------------------");

}

Here is my valgrind message:

==10692== Memcheck, a memory error detector
==10692== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==10692== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==10692== Command: ./chain_hash_table.out
==10692==
==10692==
==10692== HEAP SUMMARY:
==10692==     in use at exit: 72 bytes in 3 blocks
==10692==   total heap usage: 10 allocs, 7 frees, 376 bytes allocated
==10692==
==10692== 24 bytes in 1 blocks are definitely lost in loss record 2 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400BD2: main (main.c:14)
==10692==
==10692== 48 (24 direct, 24 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400C25: main (main.c:18)
==10692==
==10692== LEAK SUMMARY:
==10692==    definitely lost: 48 bytes in 2 blocks
==10692==    indirectly lost: 24 bytes in 1 blocks
==10692==      possibly lost: 0 bytes in 0 blocks
==10692==    still reachable: 0 bytes in 0 blocks
==10692==         suppressed: 0 bytes in 0 blocks
==10692==
==10692== For counts of detected and suppressed errors, rerun with: -v
==10692== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

And what i know it is always for first table insertion that is why it says at line main(18) for the rest after the first insertion there is no leaks.

Thank you guys for your time and help :)


问:
Pushing Object to array does not reflect at ng-repeat
I am updating an array by pushing the Json object returned by MVC controller to an array in Angular JS controller.

Following is the code sports-controller.js

```<code>portsApp.controller("SportsController", ["$scope","$http",function ($scope,$http) {
    $scope.data = { id: "rehmat" };
    $scope.sports = [];
    $scope.selectedSport ={};
    $scope.sportsObj = {};

    $scope.SportsModel = {};

    $scope.sport = {};

    $scope.remoteUrlRequestFn = function (str) {
        return { term: str };
    };

    function genericSuccess(res) {
        return res.data; // yes, really.
    }
    $scope.selectedSport = function (selected) {
        $scope.sport =
            {
            title: selected.originalObject.name,
            parent_id: selected.originalObject.parent,
            sports_id: selected.originalObject.sports_id,
            user_id: selected.originalObject.uid

        }
        $http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
            $scope.sports.push(genericSuccess(data).sport);
            console.log($scope.sports);
        });

    }

    $scope.UpdateSport = function (id) {
        if(id > 0)
        {
            $http.post("/usersports/update_sports", { user_sport_id: id }).then(function (data,status,headers,config){

                if(data.Success)
                {
                   alert(data.Message)
                }else
                {
                    alert(data.Message)
                }

            })
        }
    }

}
])
</code>```

VIEW :

```<code><div class="container sports-c" ng-app="SportsApp" >
    <!--ADD SPORTS TEXT-->
    <div class="col-lg-12" ng-controller="SportsController">
        {{sports}}
        <div class="add-sports-text  ">

            <h1 style="text-align:center;" class="animated jello">ADD SPORTS</h1>
            <hr style="width:30%">
            <p>
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
            </p>
        </div>
        <div class="form-group" style="text-align:center;">
            <label for="search" style="text-align:center;"> SEARCH</label>
            <angucomplete-alt id="sports_input_box"
                              placeholder="Search Sports"
                              pause="400"
                              selected-object="selectedSport"
                              remote-url="/ajax/getSports"
                              remote-url-request-formatter="remoteUrlRequestFn"
                              remote-url-data-field="items"
                              title-field="name"
                              minlength="2"
                              input-class="form-control input-custom" />

            @*<input type="Search" placeholder="SEARCH" class="form-control input-custom" id="sports_input_box">*@
        </div>
    </div>
    <div class="col-lg-12">
        <div class="table-responsive">
           {{sports.length}}
             <table class="table  table-bordered " id="sports-table">
                 <tr>
                        <td>ID</td>
                        <td>SPORTS NAME</td>
                        <td>SELECT SKILL LEVEL</td>

                        <td>ACTION</td>
                    </tr>
                <tbody>
                    <tr ng-repeat="item in sports">
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td style="position: relative;top: 10px;">
                            <select class="example" name="" ng-change="updatePlayerSkill(item.id)" ng-bind="SportsModel.skill_level">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                            </select>
                        </td>
                        <td class="icons-tab">
                            <a href=""><i class="fa fa-check-square-o" aria-hidden="true" ng-click="UpdateSport(item.id)"></i></a>
                            <a href=""><i class="fa fa-trash-o" aria-hidden="true" ng-click="RemoveSport(item.id)"></i></a>
                        </td>
                    </tr>
                    <tr ng-show="sports.length === 0"><td colspan="5">No Sports Added</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

What is a possible solution for this since I am updating the array by pushing the elements and its not reflecting?

I am using Angular Js 1.6, any help would be really appreciated.

please check the image

答:
The error is caused because from what I see in angucomplete-alt library, the selected parameter can be null. You need to handle that:

```<code>$scope.countrySelected = function(selected) {
  if (selected) {
    window.alert('You have selected ' + selected.title);
  } else {
    console.log('cleared');
  }
};
</code>```

Regarding your primary question. Using asynchronus requests, it could happen that you go out of Angular $digest cycle. Try to wrap array.push with $scope.applyAsync() to refresh the view.

Body:
I am updating an array by pushing the Json object returned by MVC controller to an array in Angular JS controller.

Following is the code sports-controller.js

portsApp.controller("SportsController", ["$scope","$http",function ($scope,$http) {
    $scope.data = { id: "rehmat" };
    $scope.sports = [];
    $scope.selectedSport ={};
    $scope.sportsObj = {};

    $scope.SportsModel = {};

    $scope.sport = {};

    $scope.remoteUrlRequestFn = function (str) {
        return { term: str };
    };

    function genericSuccess(res) {
        return res.data; // yes, really.
    }
    $scope.selectedSport = function (selected) {
        $scope.sport =
            {
            title: selected.originalObject.name,
            parent_id: selected.originalObject.parent,
            sports_id: selected.originalObject.sports_id,
            user_id: selected.originalObject.uid

        }
        $http.post("/usersports/post_sport", $scope.sport).then(function (data, status, headers, config) {
            $scope.sports.push(genericSuccess(data).sport);
            console.log($scope.sports);
        });

    }

    $scope.UpdateSport = function (id) {
        if(id > 0)
        {
            $http.post("/usersports/update_sports", { user_sport_id: id }).then(function (data,status,headers,config){

                if(data.Success)
                {
                   alert(data.Message)
                }else
                {
                    alert(data.Message)
                }

            })
        }
    }

}
])

VIEW :

        {{sports}}

ADD SPORTS

                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,

             SEARCH
            <angucomplete-alt id="sports_input_box"
                              placeholder="Search Sports"
                              pause="400"
                              selected-object="selectedSport"
                              remote-url="/ajax/getSports"
                              remote-url-request-formatter="remoteUrlRequestFn"
                              remote-url-data-field="items"
                              title-field="name"
                              minlength="2"
                              input-class="form-control input-custom" />

            @*<input type="Search" placeholder="SEARCH" class="form-control input-custom" id="sports_input_box">*@

           {{sports.length}}

                        ID
                        SPORTS NAME
                        SELECT SKILL LEVEL

                        ACTION

                        {{item.id}}
                        {{item.name}}

                            <select class="example" name="" ng-change="updatePlayerSkill(item.id)" ng-bind="SportsModel.skill_level">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                            </select>

No Sports Added

What is a possible solution for this since I am updating the array by pushing the elements and its not reflecting?

I am using Angular Js 1.6, any help would be really appreciated.

please check the image

Body:
The error is caused because from what I see in angucomplete-alt library, the selected parameter can be null. You need to handle that:

$scope.countrySelected = function(selected) {
  if (selected) {
    window.alert('You have selected ' + selected.title);
  } else {
    console.log('cleared');
  }
};

Regarding your primary question. Using asynchronus requests, it could happen that you go out of Angular $digest cycle. Try to wrap array.push with $scope.applyAsync() to refresh the view.


问:
How to use cache for a rails project in Gitlab CI?
I've been trying to leverage Gitlab Ci's cache for my ruby on rails application but so far haven't had any luck, my application is using shared runners, maybe that's the issue?

Here are the contents of my .gitlab-ci.yml

```<code>services:
  - postgres:latest

rspec:
  stage: test
  script:
    - apt-get update -qy
    - apt-get install -y nodejs
    - gem install bundler
    - bundle check --path vendor/bundle || bundle install --path vendor/bundle --jobs $(nproc)
    - cp config/database.gitlab-ci.yml config/database.yml
    - RAILS_ENV=test bundle exec rake db:create db:schema:load
    - bundle exec rspec
  cache:
    paths:
      - vendor/bundle
  tags:
    - ruby
    - postgres
</code>```

When my tests run I do see the runner checking for cached content, but it never restores it:

```<code>gitlab-ci-multi-runner 1.1.3 (a470667)
Using Docker executor with image ruby:2.1 ...
Pulling docker image postgres:latest ...
Starting service postgres:latest ...
Waiting for services to be up and running...
Pulling docker image ruby:2.1 ...

Running on runner-8a2f473d-project-1129003-concurrent-0 via runner-8a2f473d-machine-1462982763-a9a70bd7-digital-ocean-4gb...
Cloning repository...
Cloning into '/builds/foo/bar'...
Checking out 30ea1b5f as master...
Note: checking out '30ea1b5f036808f7e27bfa32e939c1f591343ba6'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 30ea1b5... Fix width of tables contained in table-scroll divs
Checking cache for rspec/master...

$ apt-get update -qy
</code>```

And when the build is about to finish I do see it trying to create the cache:

```<code>Creating cache rspec/master...
vendor/bundle: found 8917 matching files
</code>```

Any ideas?

答: The cache actually started working properly a few weeks after I posted this question, no changes to my configuration were required. I believe it had to do with an update gitlab rolled out.</p>

Body:
I've been trying to leverage Gitlab Ci's cache for my ruby on rails application but so far haven't had any luck, my application is using shared runners, maybe that's the issue?

Here are the contents of my .gitlab-ci.yml

services:
  - postgres:latest

rspec:
  stage: test
  script:
    - apt-get update -qy
    - apt-get install -y nodejs
    - gem install bundler
    - bundle check --path vendor/bundle || bundle install --path vendor/bundle --jobs $(nproc)
    - cp config/database.gitlab-ci.yml config/database.yml
    - RAILS_ENV=test bundle exec rake db:create db:schema:load
    - bundle exec rspec
  cache:
    paths:
      - vendor/bundle
  tags:
    - ruby
    - postgres

When my tests run I do see the runner checking for cached content, but it never restores it:

gitlab-ci-multi-runner 1.1.3 (a470667)
Using Docker executor with image ruby:2.1 ...
Pulling docker image postgres:latest ...
Starting service postgres:latest ...
Waiting for services to be up and running...
Pulling docker image ruby:2.1 ...

Running on runner-8a2f473d-project-1129003-concurrent-0 via runner-8a2f473d-machine-1462982763-a9a70bd7-digital-ocean-4gb...
Cloning repository...
Cloning into '/builds/foo/bar'...
Checking out 30ea1b5f as master...
Note: checking out '30ea1b5f036808f7e27bfa32e939c1f591343ba6'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 30ea1b5... Fix width of tables contained in table-scroll divs
Checking cache for rspec/master...

$ apt-get update -qy

And when the build is about to finish I do see it trying to create the cache:

Creating cache rspec/master...
vendor/bundle: found 8917 matching files

Any ideas?


问:
UINavigationBar color changes unexpectedly
In my current UINavigationController, the viewControllers stack looks like this.
1 -> 2 -> 3.  Before transitioning from the 2nd to the 3rd controller however, I pop the 2nd one first so that when the 3rd controller is popped, the 1st controller is on top.

```<code>[self.navigationController popViewControllerAnimated:NO];
[self.navigationController pushViewController:controller animated:YES ] ;
</code>```

But somehow doing this changes the navigationBar's color from the original blue default to the black style.  Explicitly setting the barStyle to UIBarStyleDefault in the new controller's viewWillAppear or viewWillDisappear has no effect.  What's stranger, if I set the barStyle at all, even the 1 -> 2 transition will cause the bar color to change to black.

By the end of writing this post, I realized that the following code fixed it.

```<code>navBar.barStyle = UIBarStyleDefault-1;
</code>```

Why would I need to subtract 1 from the default to actually obtain the default color?

答:
I would not pop the second, just push the 3rd. And when you dismiss the 3rd use

```<code>[self.parentViewController.parentViewController popViewControllerAnimated:YES];
</code>```

This for me reaches back and cleans up the stack and leaves me on controller 1 without showing controller 2, with all normal attributes.

Body:
In my current UINavigationController, the viewControllers stack looks like this.
1 -> 2 -> 3.  Before transitioning from the 2nd to the 3rd controller however, I pop the 2nd one first so that when the 3rd controller is popped, the 1st controller is on top.

[self.navigationController popViewControllerAnimated:NO];
[self.navigationController pushViewController:controller animated:YES ] ;

But somehow doing this changes the navigationBar's color from the original blue default to the black style.  Explicitly setting the barStyle to UIBarStyleDefault in the new controller's viewWillAppear or viewWillDisappear has no effect.  What's stranger, if I set the barStyle at all, even the 1 -> 2 transition will cause the bar color to change to black.

By the end of writing this post, I realized that the following code fixed it.

navBar.barStyle = UIBarStyleDefault-1;

Why would I need to subtract 1 from the default to actually obtain the default color?

Body:
I would not pop the second, just push the 3rd. And when you dismiss the 3rd use

[self.parentViewController.parentViewController popViewControllerAnimated:YES];

This for me reaches back and cleans up the stack and leaves me on controller 1 without showing controller 2, with all normal attributes.


问:
What is the possible way to return a whole string in matlab
I want to return a string saying 'sunday' in MATLAB. I have the following code:

```<code>function name = dayname(a)
    value = rem(a,7);

    if value == 0
        name = disp('munday');
    end
end
</code>```

the return value should be stored in name however I am getting the following error:

Too many output arguments

What am I doing wrong and how do I return a string in MATLAB?

答:
The issue is that disp does not return an output argument, it simply displays the input on the command line.

If you want to return a string, then simply assign the string to the output variable

```<code>function name = dayname(a)
    value = rem(a, 7);

    if value == 0
        name = 'munday';
    end

    %...
end
</code>```

A better way to do this would be to create a cell array of all of the names and then index into that

```<code>function name = dayname(a)
    names = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'};

    index = rem(a, 7) + 1;

    name = names{index};
end
</code>```

Body:
I want to return a string saying 'sunday' in MATLAB. I have the following code:

function name = dayname(a)
    value = rem(a,7);

    if value == 0
        name = disp('munday');
    end
end

the return value should be stored in name however I am getting the following error:

Too many output arguments

What am I doing wrong and how do I return a string in MATLAB?

Body:
The issue is that disp does not return an output argument, it simply displays the input on the command line.

If you want to return a string, then simply assign the string to the output variable

function name = dayname(a)
    value = rem(a, 7);

    if value == 0
        name = 'munday';
    end

    %...
end

A better way to do this would be to create a cell array of all of the names and then index into that

function name = dayname(a)
    names = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'};

    index = rem(a, 7) + 1;

    name = names{index};
end


问:
react/mobX : best practice
I'm fairly new to React and MobX. I've read/watched a lot tutorials on react and react in combination with MobX.

I need to create a form, where a user can select (autocomplete) a product. I'm using react-select to do this. When a user selects a product, the interface needs to update another select with locations for the selected product (wich I didn't implement yet, but it will use the options from the location observable).

Are there any 'best practices' on how to set up the communication between the react elements and MobX?

The 'findProduct' and the 'findLocationAllocationData ' are definded as an action. is this correct?

Thanks for your help!

```<code>    const {observable, action} = mobx;
    const {observer}           = mobxReact;

    class MyStore {
      product = observable({value: null});
      locations= observable({value: null,options: [],disabled: true});

      findProduct = action((input, callback) => {
        //ajax call to get products
        // JSON object as an example

        callback(null, {
          options: [{key: 1, value: 1, label: 'product a'},
            {key: 2, value: 2, label: 'product b'}
          ],
          complete: true
        })
      });

      findLocationAllocationData = action(() => {
          if (null === this.product.value) {
            return;
          }

          //ajax-call to get the locations and to update the location observable options
        }
    }
</code>```

And the react stuff:

```<code> class Well extends React.Component {
        render() {
          return (
            <div className = "well" >
              <span className = "well-legend" > {this.props.legend} < /span>
              {this.props.children}
           </div>
         );
      }
    }

    class FormGroup extends React.Component {
      render() {
        return (
        <div className = "form-group" >
            <label htmlFor = {this.props.labelFor} >
              {this.props.label}
            </label>
            {this.props.children}
        </div>
      );
    }
    }

    const ProductSelect = observer(class ProductSelect extends React.Component {
      onChange = (e = null) => {
        this.props.store.product.value = null !== e ? e.value : null;
        this.props.store.findLocationAllocationData();
      };

      getOptions = (input, callback) => {
        this.props.store.findProduct(input, callback);
      };

      render() {
        const product = this.props.store.product;

        return (
        <Select.Async
          id = "product"
          name = "product"
          className = "requiredField"
          loadOptions = {this.getOptions}
          onChange = {this.onChange}
          value = { product.value}
          />
        );
      }
    });

const MyForm = observer(class MyForm extends React.Component {
  render() {
    const store = this.props.store;

    return (
      <div>
        <form >
          <Well legend="Step 1 - Product">
            <div className="row">
              <div className="col-md-4">
                <FormGroup label="Product" labelFor="product">
                  <ProductSelect store={store} />
                </FormGroup>
              </div>
            </div>
        </Well>
     </form>
    </div>
    )
  }
});

const myStore = new MyStore();

ReactDOM.render(
    <MyForm store={myStore}/>, document.getElementById('root')
);
</code>```

答:
Your actions functions are fine but you must be aware: actions only affects the currently running function. You may want to create a callback action like findLocationAllocationData-callback and findProduct-callback

More info here

MobX is not an architecture you can structure your code as you wish there are no best practices. You may want to separate your actions and your API calls.

You can take a look for this repo for inspiration.

Title: react/mobX : best practice

Body:
I'm fairly new to React and MobX. I've read/watched a lot tutorials on react and react in combination with MobX.

I need to create a form, where a user can select (autocomplete) a product. I'm using react-select to do this. When a user selects a product, the interface needs to update another select with locations for the selected product (wich I didn't implement yet, but it will use the options from the location observable).

Are there any 'best practices' on how to set up the communication between the react elements and MobX?

The 'findProduct' and the 'findLocationAllocationData ' are definded as an action. is this correct?

Thanks for your help!

    const {observable, action} = mobx;
    const {observer}           = mobxReact;

    class MyStore {
      product = observable({value: null});
      locations= observable({value: null,options: [],disabled: true});

      findProduct = action((input, callback) => {
        //ajax call to get products
        // JSON object as an example

        callback(null, {
          options: [{key: 1, value: 1, label: 'product a'},
            {key: 2, value: 2, label: 'product b'}
          ],
          complete: true
        })
      });

      findLocationAllocationData = action(() => {
          if (null === this.product.value) {
            return;
          }

          //ajax-call to get the locations and to update the location observable options
        }
    }

And the react stuff:

 class Well extends React.Component {
        render() {
          return (

               {this.props.legend}
              {this.props.children}

         );
      }
    }

    class FormGroup extends React.Component {
      render() {
        return (

              {this.props.label}

            {this.props.children}

      );
    }
    }

    const ProductSelect = observer(class ProductSelect extends React.Component {
      onChange = (e = null) => {
        this.props.store.product.value = null !== e ? e.value : null;
        this.props.store.findLocationAllocationData();
      };

      getOptions = (input, callback) => {
        this.props.store.findProduct(input, callback);
      };

      render() {
        const product = this.props.store.product;

        return (
        <Select.Async
          id = "product"
          name = "product"
          className = "requiredField"
          loadOptions = {this.getOptions}
          onChange = {this.onChange}
          value = { product.value}
          />
        );
      }
    });

const MyForm = observer(class MyForm extends React.Component {
  render() {
    const store = this.props.store;

    return (

        <form >
          <Well legend="Step 1 - Product">

                <FormGroup label="Product" labelFor="product">
                  <ProductSelect store={store} />
                </FormGroup>

        </Well>
     </form>

    )
  }
});

const myStore = new MyStore();

ReactDOM.render(
    <MyForm store={myStore}/>, document.getElementById('root')
);


问:
Can I use python with statement for conditional execution?
I'm trying to write code that supports the following semantics:

```<code>with scope('action_name') as s:
  do_something()
  ...
do_some_other_stuff()
</code>```

The scope, among other things (setup, cleanup) should decide if this section should run.

For instance, if the user configured the program to bypass 'action_name' than, after Scope() is evaluated do_some_other_stuff() will be executed without calling do_something() first.

I tried to do it using this context manager:

```<code>@contextmanager
def scope(action):
  if action != 'bypass':
    yield
</code>```

but got RuntimeError: generator didn't yield exception (when action is 'bypass').

I am looking for a way to support this without falling back to the more verbose optional implementation:

```<code>with scope('action_name') as s:
  if s.should_run():
    do_something()
    ...
do_some_other_stuff()
</code>```

Does anyone know how I can achieve this?

Thanks!

P.S. I am using python2.7

EDIT:

The solution doesn't necessarily have to rely on with statements. I just didn't know exactly how to express it without it. In essence, I want something in the form of a context (supporting setup and automatic cleanup, unrelated to the contained logic) and allowing for conditional execution based on parameters passed to the setup method and selected in the configuration.

I also thought about a possible solution using decorators. Example:

```<code>@scope('action_name') # if 'action_name' in allowed actions, do:
                      #   setup()
                      #   do_action_name()
                      #   cleanup()
                      # otherwise return
def do_action_name()
  do_something()
</code>```

but I don't want to enforce too much of the internal structure (i.e., how the code is divided to functions) based on these scopes.

Does anybody have some creative ideas?

答: I don't think this can be done. I tried implementing a context manager as a class and there's just no way to force the block to raise an exception which would subsequently be squelched by the __exit__() method.

Body:
I'm trying to write code that supports the following semantics:

with scope('action_name') as s:
  do_something()
  ...
do_some_other_stuff()

The scope, among other things (setup, cleanup) should decide if this section should run.

For instance, if the user configured the program to bypass 'action_name' than, after Scope() is evaluated do_some_other_stuff() will be executed without calling do_something() first.

I tried to do it using this context manager:

@contextmanager
def scope(action):
  if action != 'bypass':
    yield

but got RuntimeError: generator didn't yield exception (when action is 'bypass').

I am looking for a way to support this without falling back to the more verbose optional implementation:

with scope('action_name') as s:
  if s.should_run():
    do_something()
    ...
do_some_other_stuff()

Does anyone know how I can achieve this?

Thanks!

P.S. I am using python2.7

EDIT:

The solution doesn't necessarily have to rely on with statements. I just didn't know exactly how to express it without it. In essence, I want something in the form of a context (supporting setup and automatic cleanup, unrelated to the contained logic) and allowing for conditional execution based on parameters passed to the setup method and selected in the configuration.

I also thought about a possible solution using decorators. Example:

@scope('action_name') # if 'action_name' in allowed actions, do:
                      #   setup()
                      #   do_action_name()
                      #   cleanup()
                      # otherwise return
def do_action_name()
  do_something()

but I don't want to enforce too much of the internal structure (i.e., how the code is divided to functions) based on these scopes.

Does anybody have some creative ideas?


问:
Wrong variable posts via mysql_query
I have a table gquestions with columns id,answer,date. I'm trying to update string in table with this HTML form and PHP queries:

HTML

```<code><form action="/reply" method="post">
    <textarea name="answer"></textarea><br>
    <input type="submit" value="Reply">
</form>
</code>```

PHP

```<code>$p_answer = $_POST["answer"];
$time = time();
mysql_query("UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'");
echo "UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'";
</code>```

Okay, in form I'm typing in textarea Test and clicking Reply and get this result in page:

UPDATE gquestions SET answer='Test' AND date='1490982467' id='1'

but in table I get 0 instead of Test in answer column. Why I'm getting 0 in my column?

答:
Change

```<code>UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'
</code>```

To

```<code>UPDATE gquestions SET answer='$p_answer', date='$time' WHERE id='1'
</code>```

Title: Wrong variable posts via mysql_query

Body:
I have a table gquestions with columns id,answer,date. I'm trying to update string in table with this HTML form and PHP queries:

HTML

<form action="/reply" method="post">
    <textarea name="answer"></textarea>

    <input type="submit" value="Reply">
</form>

PHP

$p_answer = $_POST["answer"];
$time = time();
mysql_query("UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'");
echo "UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'";

Okay, in form I'm typing in textarea Test and clicking Reply and get this result in page:

UPDATE gquestions SET answer='Test' AND date='1490982467' id='1'

but in table I get 0 instead of Test in answer column. Why I'm getting 0 in my column?

Body:
Change

UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'

To

UPDATE gquestions SET answer='$p_answer', date='$time' WHERE id='1'


问:
How to extend the Date class
I'm making an angular2 application and all the dates i get back from my controller are in this format "2017-02-2700:00:00". I would like to extend the js Date object so that i remove the T from the string when i make a new object and it still acts as a date object. The current way I'm trying to achieve this is not working. The IDate object i made that extends the Date object  is just showing up as a null object instead of an date object. Anyone know whats going on and how to fix it. I'm willing to use es6 js instead of typescript if it cant be done in typescript. I saw the post about extending the Date object, but that modifies the date object, i was hoping to have my own object called IDate that was the same as Date but with a few more methods. Ill mark that the answer if that is the only way this can be done.

```<code>export class IDate extends Date {
    constructor() {
        super();
    }
    value;
    toDate(value: string): Date {
        value.replace("T", " ");
        return new Date(value);
    }
    getvalue() {
        return this.value;
    }
}

    let t = new IDate();
    let d = new Date();
    console.log(t);
    console.log(d);
</code>```

console

```<code> IDate {}
 Fri Mar 31 2017 11:53:59 GMT-0500 (Central Daylight Time)
</code>```

答:
You can only extend native (built-in) types in this way if you target es6.

If you can't target es6 then you need to workaround it: Extending built-ins like Error, Array, and Map may no longer work.

More info on this:

How do I extend a host object (e.g. Error) in TypeScript

Can not extend built in types

Custom error class in TypeScript

While not all of these talk about extending Date, the problem is still exactly the same.

Title: How to extend the Date class

Body:
I'm making an angular2 application and all the dates i get back from my controller are in this format "2017-02-2700:00:00". I would like to extend the js Date object so that i remove the T from the string when i make a new object and it still acts as a date object. The current way I'm trying to achieve this is not working. The IDate object i made that extends the Date object  is just showing up as a null object instead of an date object. Anyone know whats going on and how to fix it. I'm willing to use es6 js instead of typescript if it cant be done in typescript. I saw the post about extending the Date object, but that modifies the date object, i was hoping to have my own object called IDate that was the same as Date but with a few more methods. Ill mark that the answer if that is the only way this can be done.

export class IDate extends Date {
    constructor() {
        super();
    }
    value;
    toDate(value: string): Date {
        value.replace("T", " ");
        return new Date(value);
    }
    getvalue() {
        return this.value;
    }
}

    let t = new IDate();
    let d = new Date();
    console.log(t);
    console.log(d);

console

 IDate {}
 Fri Mar 31 2017 11:53:59 GMT-0500 (Central Daylight Time)


答:
column type is different, maybe int change it to varchar or text for answer column.

your query is wrong

```<code>"UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'"
</code>```

should be  there shouldn't and

```<code>"UPDATE gquestions SET answer='$p_answer',date='$time' WHERE id='1'"
</code>```

Title: Wrong variable posts via mysql_query

Body:
column type is different, maybe int change it to varchar or text for answer column.

your query is wrong

"UPDATE gquestions SET answer='$p_answer' AND date='$time' WHERE id='1'"

should be  there shouldn't and

"UPDATE gquestions SET answer='$p_answer',date='$time' WHERE id='1'"


问:
Calling a function in Django after saving a model
Context: I'm making a blog. This blog stores information on articles in a database via a Django model. I have a FileField in said model that takes an archive of all the assets that go with this file. I add articles through the admin site.

I want to call a function that unpacks this file immediately after the the object is saved to the model. Where would I write this function?

答:
Maybe you can use post_save signal in your app/model:

https://docs.djangoproject.com/en/1.10/ref/signals/#post-save


问:
Using <= and >= in XSLT
I would like to use <= and >= when comparing values in <xsl:if test="">. How to do that?

Update:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

<html>
    <body>
        <h1>Average classsize per user and module</h1>
        <table border="1">

            <tr>
                <th>User Email</th>
                <th>Module Code</th>
                <th>Average Value</th>
            </tr>
            <xsl:apply-templates select="//classsize" />
        </table>
    </body>
</html>

</xsl:template>

<xsl:template match="average">
    <xsl:choose>
        <xsl:when test=". < 1">
            <td style="background-color: red;"><xsl:value-of select="." /></td>
        </xsl:when>

        <xsl:when test="1 <= . < 2">
            <td style="background-color: blue;"><xsl:value-of select="." /></td>
        </xsl:when>

        <xsl:when test="2 <= . < 3">
            <td style="background-color: yellow;"><xsl:value-of select="." /></td>
        </xsl:when>

        <xsl:otherwise>
            <td style="background-color: white;"><xsl:value-of select="." /></td>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="//classsize">
    <tr>
        <td><xsl:value-of select="email" /></td>
        <td><xsl:value-of select="modulecode" /></td>
        <xsl:apply-templates select="average" />
    </tr>
</xsl:template>

</xsl:stylesheet>
</code>```

```<code>average < 1 - in red
1 <= average < 2 - in blue
2 <= average < 3 - in yellow
average >= 3 - white
</code>```

答:
In addidtion to @Oded's correct answer:

.1. There is never any need to escape the > operator in XSLT. Just write: >

.2. One can avoid escaping the < operator.

Instead of:

```<code>  x < y
</code>```

you can write:

```<code>not(x >= y)
</code>```

Instead of:

```<code>1 <= . and . < 2
</code>```

you can write:

```<code>2 > . and not(1 > .)
</code>```

.3. In XPath 1.0 the < and > operators are not defined on strings (only on numbers).

Finally, this is actually an XPath 1.0 question.

Title: Using <= and >= in XSLT

Body:
I would like to use <= and >= when comparing values in <xsl:if test="">. How to do that?

Update:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

Average classsize per user and module

                User Email
                Module Code
                Average Value

            <xsl:apply-templates select="//classsize" />

</xsl:template>

<xsl:template match="average">
    <xsl:choose>
        <xsl:when test=". < 1">
            <xsl:value-of select="." />
        </xsl:when>

        <xsl:when test="1 <= . < 2">
            <xsl:value-of select="." />
        </xsl:when>

        <xsl:when test="2 <= . < 3">
            <xsl:value-of select="." />
        </xsl:when>

        <xsl:otherwise>
            <xsl:value-of select="." />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="//classsize">

        <xsl:value-of select="email" />
        <xsl:value-of select="modulecode" />
        <xsl:apply-templates select="average" />

</xsl:template>

</xsl:stylesheet>

average < 1 - in red
1 <= average < 2 - in blue
2 <= average < 3 - in yellow
average >= 3 - white

Body:
In addidtion to @Oded's correct answer:

.1. There is never any need to escape the > operator in XSLT. Just write: >

.2. One can avoid escaping the < operator.

Instead of:

  x &lt; y

you can write:

not(x >= y)

Instead of:

1 &lt;= . and . &lt; 2

you can write:

2 > . and not(1 > .)

.3. In XPath 1.0 the < and > operators are not defined on strings (only on numbers).

Finally, this is actually an XPath 1.0 question.


问:
How to compile Java code after Clojure code in leiningen
In my Leiningen project:

```<code>(defproject com.stackoverflow.clojure/tests "0.1.0-SNAPSHOT"
  :description "Tests of Clojure test-framework."
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [instaparse "1.3.4"]]
  :aot [com.stackoverflow.clojure.testGenClass]
  :source-paths      ["src/main/clojure"]
  :java-source-paths ["src/main/java"]
  :test-paths        ["src/test/clojure"]
  :java-test-paths   ["src/test/java"]
  )
</code>```

I'm generating Java-classes with gen-class:

```<code>(ns com.stackoverflow.clojure.testGenClass
  (:gen-class
     :name com.stackoverflow.clojure.TestGenClass
     :implements [com.stackoverflow.clojure.TestGenClassInterface]
     :prefix "java-"))

(def ^:private pre "START: ")

(defn java-addToString [this text post]
  (str pre text post))
</code>```

which I want to use in Java:

```<code>package com.stackoverflow.clojure;

public class TestGenClassTest {

    private TestGenClassTest() {
    }

    public static void main(String[] args) {
        TestGenClassInterface gc = new TestGenClass();
        System.out.println(gc.addToString("Called from Java!", " :END"));
    }
}
</code>```

Starting lein compile throws the following error:

```<code>Compiling 4 source files to /home/eddy/workspace/TestSkripts/target/classes
/home/eddy/workspace/TestSkripts/src/main/java/com/stackoverflow/clojure/TestGenClassTest.java:9: error: cannot find symbol
        TestGenClassInterface gc = new TestGenClass();
                                       ^
  symbol:   class TestGenClass
  location: class TestGenClassTest
1 error
</code>```

It seems to me, that during compilation of the Java-code (here: TestGenClassTest) the Class is not available. What I usually did is

commenting out those parts that use the gen-class generated class (here TestGenClass)

run lein compile (to generate the class-file)

then taking the outcommented code in again

and run lein compile again.

I' sure there is a better way, that makes all manual steps redundat.

答:
Here is a sample project.clj from a project where the clojure code relies on Java code, and AOT compiles so that it is available to upstream tests Java code. So here we have three layers of compilation dependencies: Java → Clojure → Java and it all works:

```<code>(defproject myproject "0.1.0-SNAPSHOT"
  :min-lein-version "2.0.0"
  :source-paths      ["src/clojure"]/
  :java-source-paths ["src/java"]
  :javac-options     ["-target" "1.8" "-source" "1.8"]
  :dependencies [[org.clojure/clojure "1.8.0"]]
  :aot [the class that java-test needs]
  :profiles {:java-tests-compile
    {:java-source-paths ["src/java-test"]}}
  :aliases {
    "java-tests" ["do" "compile," "with-profile" "java-tests-compile" "javac," "run" "-m" "myorg.myProject.java-test-code"]
    "all-tests" ["do" "test," "java-tests"]
  })

; https://github.com/technomancy/leiningen/issues/847#issuecomment-289943710
</code>```

The upstream java tests code finds all it needs when it compiles and runs. (The upstream java layer in the project where this sample comes from just happens to be java tests code, but there's nothing here that is specific to tests code, the technique should work generically, when you want Java code to use your gen-class generated clojure code).

The original question's code is just missing the profile and alias parts shown here, that tell leiningen how to compile the Java, after clojure compilation. This is needed because by default, in the current versions  of leiningen, leiningen compiles Java before it compiles clojure; it does not attempt to order the compilation of source files across languages.

So in this solution, we add another compilation step as a separate leiningen task, through the use of an alias. Having this configuration, we only need to issue lein java-tests which first compiles clojure, then the upper-stream Java layer. Voila.

P.S. maybe we can even override lein's compile task rather than add a new task, but that was not worth the play for me...

Body:
In my Leiningen project:

(defproject com.stackoverflow.clojure/tests "0.1.0-SNAPSHOT"
  :description "Tests of Clojure test-framework."
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [instaparse "1.3.4"]]
  :aot [com.stackoverflow.clojure.testGenClass]
  :source-paths      ["src/main/clojure"]
  :java-source-paths ["src/main/java"]
  :test-paths        ["src/test/clojure"]
  :java-test-paths   ["src/test/java"]
  )

I'm generating Java-classes with gen-class:

(ns com.stackoverflow.clojure.testGenClass
  (:gen-class
     :name com.stackoverflow.clojure.TestGenClass
     :implements [com.stackoverflow.clojure.TestGenClassInterface]
     :prefix "java-"))

(def ^:private pre "START: ")

(defn java-addToString [this text post]
  (str pre text post))

which I want to use in Java:

package com.stackoverflow.clojure;

public class TestGenClassTest {

    private TestGenClassTest() {
    }

    public static void main(String[] args) {
        TestGenClassInterface gc = new TestGenClass();
        System.out.println(gc.addToString("Called from Java!", " :END"));
    }
}

Starting lein compile throws the following error:

Compiling 4 source files to /home/eddy/workspace/TestSkripts/target/classes
/home/eddy/workspace/TestSkripts/src/main/java/com/stackoverflow/clojure/TestGenClassTest.java:9: error: cannot find symbol
        TestGenClassInterface gc = new TestGenClass();
                                       ^
  symbol:   class TestGenClass
  location: class TestGenClassTest
1 error

It seems to me, that during compilation of the Java-code (here: TestGenClassTest) the Class is not available. What I usually did is

commenting out those parts that use the gen-class generated class (here TestGenClass)

run lein compile (to generate the class-file)

then taking the outcommented code in again

and run lein compile again.

I' sure there is a better way, that makes all manual steps redundat.

Body:
Here is a sample project.clj from a project where the clojure code relies on Java code, and AOT compiles so that it is available to upstream tests Java code. So here we have three layers of compilation dependencies: Java → Clojure → Java and it all works:

(defproject myproject "0.1.0-SNAPSHOT"
  :min-lein-version "2.0.0"
  :source-paths      ["src/clojure"]/
  :java-source-paths ["src/java"]
  :javac-options     ["-target" "1.8" "-source" "1.8"]
  :dependencies [[org.clojure/clojure "1.8.0"]]
  :aot [the class that java-test needs]
  :profiles {:java-tests-compile
    {:java-source-paths ["src/java-test"]}}
  :aliases {
    "java-tests" ["do" "compile," "with-profile" "java-tests-compile" "javac," "run" "-m" "myorg.myProject.java-test-code"]
    "all-tests" ["do" "test," "java-tests"]
  })

; https://github.com/technomancy/leiningen/issues/847#issuecomment-289943710

The upstream java tests code finds all it needs when it compiles and runs. (The upstream java layer in the project where this sample comes from just happens to be java tests code, but there's nothing here that is specific to tests code, the technique should work generically, when you want Java code to use your gen-class generated clojure code).

The original question's code is just missing the profile and alias parts shown here, that tell leiningen how to compile the Java, after clojure compilation. This is needed because by default, in the current versions  of leiningen, leiningen compiles Java before it compiles clojure; it does not attempt to order the compilation of source files across languages.

So in this solution, we add another compilation step as a separate leiningen task, through the use of an alias. Having this configuration, we only need to issue lein java-tests which first compiles clojure, then the upper-stream Java layer. Voila.

P.S. maybe we can even override lein's compile task rather than add a new task, but that was not worth the play for me...