问:
Why Java Optional performance increase with number of chained calls?
I was recently asked about the performance of java 8 Optional. After some searching, I found this question and several blog posts, with contradicting answers. So I benchmarked it using JMH and I don't understand my findings.

Here is the gist of my benchmark code (full code is available on GitHub):

```<code>@State(Scope.Benchmark)
public class OptionalBenchmark {

  private Room room;

  @Param({ "empty", "small", "large", "full" })
  private String filling;

  @Setup
  public void setUp () {
    switch (filling) {
      case "empty":
        room = null;
        break;
      case "small":
        room = new Room(new Flat(new Floor(null)));
        break;
      case "large":
        room = new Room(new Flat(new Floor(new Building(new Block(new District(null))))));
        break;
      case "full":
        room = new Room(new Flat(new Floor(new Building(new Block(new District(new City(new Country("France"))))))));
        break;
      default:
        throw new IllegalStateException("Unsupported filling.");
    }
  }

  @Benchmark
  public String nullChecks () {
    if (room == null) {
      return null;
    }

    Flat flat = room.getFlat();
    if (flat == null) {
      return null;
    }

    Floor floor = flat.getFloor();
    if (floor == null) {
      return null;
    }

    Building building = floor.getBuilding();
    if (building == null) {
      return null;
    }

    Block block = building.getBlock();
    if (block == null) {
      return null;
    }

    District district = block.getDistrict();
    if (district == null) {
      return null;
    }

    City city = district.getCity();
    if (city == null) {
      return null;
    }

    Country country = city.getCountry();
    if (country == null) {
      return null;
    }

    return country.getName();
  }

  @Benchmark
  public String optionalsWithMethodRefs () {
    return Optional.ofNullable (room)
        .map (Room::getFlat)
        .map (Flat::getFloor)
        .map (Floor::getBuilding)
        .map (Building::getBlock)
        .map (Block::getDistrict)
        .map (District::getCity)
        .map (City::getCountry)
        .map (Country::getName)
        .orElse (null);
  }

  @Benchmark
  public String optionalsWithLambdas () {
    return Optional.ofNullable (room)
        .map (room -> room.getFlat ())
        .map (flat -> flat.getFloor ())
        .map (floor -> floor.getBuilding ())
        .map (building -> building.getBlock ())
        .map (block -> block.getDistrict ())
        .map (district -> district.getCity ())
        .map (city -> city.getCountry ())
        .map (country -> country.getName ())
        .orElse (null);
  }

}
</code>```

And the results I got were:

```<code>Benchmark                                  (filling)   Mode  Cnt           Score         Error  Units
OptionalBenchmark.nullChecks                   empty  thrpt  200   468835378.093 ±  895576.864  ops/s
OptionalBenchmark.nullChecks                   small  thrpt  200   306602013.907 ±  136966.520  ops/s
OptionalBenchmark.nullChecks                   large  thrpt  200   259996142.619 ±  307584.215  ops/s
OptionalBenchmark.nullChecks                    full  thrpt  200   275954974.981 ± 4154597.959  ops/s
OptionalBenchmark.optionalsWithLambdas         empty  thrpt  200   460491457.335 ±  322920.650  ops/s
OptionalBenchmark.optionalsWithLambdas         small  thrpt  200    98604468.453 ±   68320.074  ops/s
OptionalBenchmark.optionalsWithLambdas         large  thrpt  200    67648427.470 ±  206810.285  ops/s
OptionalBenchmark.optionalsWithLambdas          full  thrpt  200   167124820.392 ± 1229924.561  ops/s
OptionalBenchmark.optionalsWithMethodRefs      empty  thrpt  200   460690135.554 ±  273853.568  ops/s
OptionalBenchmark.optionalsWithMethodRefs      small  thrpt  200    98639064.680 ±   56848.805  ops/s
OptionalBenchmark.optionalsWithMethodRefs      large  thrpt  200    68138436.113 ±  158409.539  ops/s
OptionalBenchmark.optionalsWithMethodRefs       full  thrpt  200   169603006.971 ±   52646.423  ops/s
</code>```

First of all, when given a null reference, Optional and null checks behave pretty much the same. I guess this is because there is only one instance of Optional.empty (), so any .map () method call on it just returns itself.

When the given object is non-null and contains a chain of non-null attributes, however, a new Optional has to be instantiated on each call to .map (). Hence, performance degrade much more quickly than with null checks. Makes sense. Expect for my full filling, where the performance all of a sudden increase. So what is the magic going on here? Am I doing something wrong in my benchmark?

Edit

The parameters from my first run were the default from JMH: each benchmark was ran in 10 different forks, with 20 warmup iterations of 1s each, and then 20 measurement iterations of 1s each. I believe those value are sane, since I trust the libraries I use. However, since I was told I wasn’t warming up enough, here is the result of a longer test (200 warmup iterations and 200 measurement iteration for each of the 10 forks):

```<code># JMH version: 1.19
# VM version: JDK 1.8.0_152, VM 25.152-b16
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home/jre/bin/java
# VM options: <none>
# Warmup: 200 iterations, 1 s each
# Measurement: 200 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time

# Run complete. Total time: 17:49:25

Benchmark                                  (filling)   Mode   Cnt           Score         Error  Units
OptionalBenchmark.nullChecks                   empty  thrpt  2000   471803721.972 ±  116120.114  ops/s
OptionalBenchmark.nullChecks                   small  thrpt  2000   289181482.246 ± 3967502.916  ops/s
OptionalBenchmark.nullChecks                   large  thrpt  2000   260222478.406 ±  105074.121  ops/s
OptionalBenchmark.nullChecks                    full  thrpt  2000   282487728.710 ±   71214.637  ops/s
OptionalBenchmark.optionalsWithLambdas         empty  thrpt  2000   460931830.242 ±  335263.946  ops/s
OptionalBenchmark.optionalsWithLambdas         small  thrpt  2000    98688943.879 ±   20485.863  ops/s
OptionalBenchmark.optionalsWithLambdas         large  thrpt  2000    67262330.106 ±   50465.262  ops/s
OptionalBenchmark.optionalsWithLambdas          full  thrpt  2000   168070919.770 ±  352435.666  ops/s
OptionalBenchmark.optionalsWithMethodRefs      empty  thrpt  2000   460998599.579 ±   85063.337  ops/s
OptionalBenchmark.optionalsWithMethodRefs      small  thrpt  2000    98707338.408 ±   17231.648  ops/s
OptionalBenchmark.optionalsWithMethodRefs      large  thrpt  2000    68052673.021 ±   55285.427  ops/s
OptionalBenchmark.optionalsWithMethodRefs       full  thrpt  2000   169259067.479 ±  174402.212  ops/s
</code>```

As you can see, we have almost the same figures.

答:
Even such a powerful tool like JMH is not able to save from all benchmarking pitfalls.
I've found two different issues with this benchmark.

1.

HotSpot JIT compiler speculatively optimizes code basing on runtime profile. In the given "full" scenario Optional never sees null values. That's why Optional.ofNullable method (also called by Optional.map) happens to be optimized exclusively for non-null path which constructs a new non-empty Optional. In this case JIT is able to eliminate all short-lived allocations and perform all map operations without intermediate objects.

```<code>public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}
</code>```

In "small" and "large" scenarios the mapping sequence finally ends with Optional.empty(). That is, both branches of ofNullable method are compiled, and JIT is no longer able to eliminate allocations of intermediate Optional objects - data flow graph appears to be too complex for Escape Analysis to succeed.

Check it by running JMH with -prof gc, and you'll see that "small" allocates 48 bytes (3 Optionals) per iteration, "large" allocates 96 bytes (6 Optionals), and "full" allocates nothing.

```<code>Benchmark                                                      (filling)  Mode  Cnt     Score     Error   Units
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      empty  avgt    5    ≈ 10⁻⁶              B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      small  avgt    5    48,000 ±   0,001    B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      large  avgt    5    96,000 ±   0,001    B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm       full  avgt    5    ≈ 10⁻⁵              B/op
</code>```

If you replace new Country("France") with new Country(null), the opimization will also break, and "full" scenario will become expectedly slower than "small" and "large".

Alternatively, the following dummy loop added to setUp will also prevent from overoptimizing ofNullable making the benchmark results more realistic.

```<code>    for (int i = 0; i < 1000; i++) {
        Optional.ofNullable(null);
    }
</code>```

2.

Surprisingly, nullChecks benchmark also appears faster in "full" scenario. The reason here is class initialization barriers. Note that only "full" case initializes all related classes. In "small" and "large" cases nullChecks method refers to some classes that are not yet initialized. This prevents from compiling nullChecks efficiently.

If you explicitly initialize all the classes in setUp, e.g. by creating a dummy object, then "empty", "small" and "large" scenarios of nullChecks will become faster.

```<code>Room dummy = new Room(new Flat(new Floor(new Building(new Block(new District(new City(new Country("France"))))))))
</code>```

Body:
I was recently asked about the performance of java 8 Optional. After some searching, I found this question and several blog posts, with contradicting answers. So I benchmarked it using JMH and I don't understand my findings.

Here is the gist of my benchmark code (full code is available on GitHub):

@State(Scope.Benchmark)
public class OptionalBenchmark {

  private Room room;

  @Param({ "empty", "small", "large", "full" })
  private String filling;

  @Setup
  public void setUp () {
    switch (filling) {
      case "empty":
        room = null;
        break;
      case "small":
        room = new Room(new Flat(new Floor(null)));
        break;
      case "large":
        room = new Room(new Flat(new Floor(new Building(new Block(new District(null))))));
        break;
      case "full":
        room = new Room(new Flat(new Floor(new Building(new Block(new District(new City(new Country("France"))))))));
        break;
      default:
        throw new IllegalStateException("Unsupported filling.");
    }
  }

  @Benchmark
  public String nullChecks () {
    if (room == null) {
      return null;
    }

    Flat flat = room.getFlat();
    if (flat == null) {
      return null;
    }

    Floor floor = flat.getFloor();
    if (floor == null) {
      return null;
    }

    Building building = floor.getBuilding();
    if (building == null) {
      return null;
    }

    Block block = building.getBlock();
    if (block == null) {
      return null;
    }

    District district = block.getDistrict();
    if (district == null) {
      return null;
    }

    City city = district.getCity();
    if (city == null) {
      return null;
    }

    Country country = city.getCountry();
    if (country == null) {
      return null;
    }

    return country.getName();
  }

  @Benchmark
  public String optionalsWithMethodRefs () {
    return Optional.ofNullable (room)
        .map (Room::getFlat)
        .map (Flat::getFloor)
        .map (Floor::getBuilding)
        .map (Building::getBlock)
        .map (Block::getDistrict)
        .map (District::getCity)
        .map (City::getCountry)
        .map (Country::getName)
        .orElse (null);
  }

  @Benchmark
  public String optionalsWithLambdas () {
    return Optional.ofNullable (room)
        .map (room -> room.getFlat ())
        .map (flat -> flat.getFloor ())
        .map (floor -> floor.getBuilding ())
        .map (building -> building.getBlock ())
        .map (block -> block.getDistrict ())
        .map (district -> district.getCity ())
        .map (city -> city.getCountry ())
        .map (country -> country.getName ())
        .orElse (null);
  }

}

And the results I got were:

Benchmark                                  (filling)   Mode  Cnt           Score         Error  Units
OptionalBenchmark.nullChecks                   empty  thrpt  200   468835378.093 ±  895576.864  ops/s
OptionalBenchmark.nullChecks                   small  thrpt  200   306602013.907 ±  136966.520  ops/s
OptionalBenchmark.nullChecks                   large  thrpt  200   259996142.619 ±  307584.215  ops/s
OptionalBenchmark.nullChecks                    full  thrpt  200   275954974.981 ± 4154597.959  ops/s
OptionalBenchmark.optionalsWithLambdas         empty  thrpt  200   460491457.335 ±  322920.650  ops/s
OptionalBenchmark.optionalsWithLambdas         small  thrpt  200    98604468.453 ±   68320.074  ops/s
OptionalBenchmark.optionalsWithLambdas         large  thrpt  200    67648427.470 ±  206810.285  ops/s
OptionalBenchmark.optionalsWithLambdas          full  thrpt  200   167124820.392 ± 1229924.561  ops/s
OptionalBenchmark.optionalsWithMethodRefs      empty  thrpt  200   460690135.554 ±  273853.568  ops/s
OptionalBenchmark.optionalsWithMethodRefs      small  thrpt  200    98639064.680 ±   56848.805  ops/s
OptionalBenchmark.optionalsWithMethodRefs      large  thrpt  200    68138436.113 ±  158409.539  ops/s
OptionalBenchmark.optionalsWithMethodRefs       full  thrpt  200   169603006.971 ±   52646.423  ops/s

First of all, when given a null reference, Optional and null checks behave pretty much the same. I guess this is because there is only one instance of Optional.empty (), so any .map () method call on it just returns itself.

When the given object is non-null and contains a chain of non-null attributes, however, a new Optional has to be instantiated on each call to .map (). Hence, performance degrade much more quickly than with null checks. Makes sense. Expect for my full filling, where the performance all of a sudden increase. So what is the magic going on here? Am I doing something wrong in my benchmark?

Edit

The parameters from my first run were the default from JMH: each benchmark was ran in 10 different forks, with 20 warmup iterations of 1s each, and then 20 measurement iterations of 1s each. I believe those value are sane, since I trust the libraries I use. However, since I was told I wasn’t warming up enough, here is the result of a longer test (200 warmup iterations and 200 measurement iteration for each of the 10 forks):

# JMH version: 1.19
# VM version: JDK 1.8.0_152, VM 25.152-b16
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home/jre/bin/java
# VM options: <none>
# Warmup: 200 iterations, 1 s each
# Measurement: 200 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time

# Run complete. Total time: 17:49:25

Benchmark                                  (filling)   Mode   Cnt           Score         Error  Units
OptionalBenchmark.nullChecks                   empty  thrpt  2000   471803721.972 ±  116120.114  ops/s
OptionalBenchmark.nullChecks                   small  thrpt  2000   289181482.246 ± 3967502.916  ops/s
OptionalBenchmark.nullChecks                   large  thrpt  2000   260222478.406 ±  105074.121  ops/s
OptionalBenchmark.nullChecks                    full  thrpt  2000   282487728.710 ±   71214.637  ops/s
OptionalBenchmark.optionalsWithLambdas         empty  thrpt  2000   460931830.242 ±  335263.946  ops/s
OptionalBenchmark.optionalsWithLambdas         small  thrpt  2000    98688943.879 ±   20485.863  ops/s
OptionalBenchmark.optionalsWithLambdas         large  thrpt  2000    67262330.106 ±   50465.262  ops/s
OptionalBenchmark.optionalsWithLambdas          full  thrpt  2000   168070919.770 ±  352435.666  ops/s
OptionalBenchmark.optionalsWithMethodRefs      empty  thrpt  2000   460998599.579 ±   85063.337  ops/s
OptionalBenchmark.optionalsWithMethodRefs      small  thrpt  2000    98707338.408 ±   17231.648  ops/s
OptionalBenchmark.optionalsWithMethodRefs      large  thrpt  2000    68052673.021 ±   55285.427  ops/s
OptionalBenchmark.optionalsWithMethodRefs       full  thrpt  2000   169259067.479 ±  174402.212  ops/s

As you can see, we have almost the same figures.

Body:
Even such a powerful tool like JMH is not able to save from all benchmarking pitfalls.
I've found two different issues with this benchmark.

1.

HotSpot JIT compiler speculatively optimizes code basing on runtime profile. In the given "full" scenario Optional never sees null values. That's why Optional.ofNullable method (also called by Optional.map) happens to be optimized exclusively for non-null path which constructs a new non-empty Optional. In this case JIT is able to eliminate all short-lived allocations and perform all map operations without intermediate objects.

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

In "small" and "large" scenarios the mapping sequence finally ends with Optional.empty(). That is, both branches of ofNullable method are compiled, and JIT is no longer able to eliminate allocations of intermediate Optional objects - data flow graph appears to be too complex for Escape Analysis to succeed.

Check it by running JMH with -prof gc, and you'll see that "small" allocates 48 bytes (3 Optionals) per iteration, "large" allocates 96 bytes (6 Optionals), and "full" allocates nothing.

Benchmark                                                      (filling)  Mode  Cnt     Score     Error   Units
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      empty  avgt    5    ≈ 10⁻⁶              B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      small  avgt    5    48,000 ±   0,001    B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm      large  avgt    5    96,000 ±   0,001    B/op
OptionalBenchmark.optionalsWithMethodRefs:·gc.alloc.rate.norm       full  avgt    5    ≈ 10⁻⁵              B/op

If you replace new Country("France") with new Country(null), the opimization will also break, and "full" scenario will become expectedly slower than "small" and "large".

Alternatively, the following dummy loop added to setUp will also prevent from overoptimizing ofNullable making the benchmark results more realistic.

    for (int i = 0; i < 1000; i++) {
        Optional.ofNullable(null);
    }

2.

Surprisingly, nullChecks benchmark also appears faster in "full" scenario. The reason here is class initialization barriers. Note that only "full" case initializes all related classes. In "small" and "large" cases nullChecks method refers to some classes that are not yet initialized. This prevents from compiling nullChecks efficiently.

If you explicitly initialize all the classes in setUp, e.g. by creating a dummy object, then "empty", "small" and "large" scenarios of nullChecks will become faster.

Room dummy = new Room(new Flat(new Floor(new Building(new Block(new District(new City(new Country("France"))))))))


来源: stackexchange

问:
Unable to send mail via php mail()
I am unable to send an email via php's mail function.

This is the error I receive.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in D:\inetpub\vhosts\southernbatteries.com\httpdocs\includes\utils.php on line 6
Array ( [0] => [1] => Could not send mail, please try later... )

What exactly does this mean ? Does it mean there is not mail server installed on my webserver ? Is it possible to use a different mail server. E.g Gmails mail server to send the mail ?

答: If you want to run your own mail server (if this is a development environment for example) you could use mercury.</p>

ContentLicense: CC BY-SA 2.5

Title: Unable to send mail via php mail()


问:
Camel: detect Kafka wrong IP
I am configuring Kafka as a source in my RouteBuilder. My goal is to handle Kafka disconnection issues. My RouteBuilder is as follows:

```<code>new RouteBuilder() {
        public void configure() {
            onException(Exception.class).process(exchange -> {
                final Exception exception = exchange.getException();
                logger.error(exception.getMessage());
                // will do more processing here
            });
            from(String.format("kafka:%s?brokers=%s:%s", topicName, host, port)).bean(getMyService(), "myMethod")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    // some more processing
                }
            });
        }
    };
</code>```

I provided wrong host and port, and expected to see an exception. However, no exception is seen in the log, and the onException processing is not get called.
Any idea what I am doing wrong?

A similar problem can be reproduced by running https://github.com/apache/camel/blob/master/examples/camel-example-kafka/src/main/java/org/apache/camel/example/kafka/MessageConsumerClient.java locally without any Kafka server running. Doing so results in a constant flow of messages:

```<code>Connection to node -1 could not be established. Broker may not be available.
</code>```

Is there a way to have an exception thrown?
Any help would be appreciated.

答: OnException in the RouteBuilder will be triggered when you have a message to route, but since you are unable to connect to Kafka cluster you don't have that. That's why you don't see exception handled.</p>

ContentLicense: CC BY-SA 3.0

Title: Camel: detect Kafka wrong IP

Body:
I am configuring Kafka as a source in my RouteBuilder. My goal is to handle Kafka disconnection issues. My RouteBuilder is as follows:

new RouteBuilder() {
        public void configure() {
            onException(Exception.class).process(exchange -> {
                final Exception exception = exchange.getException();
                logger.error(exception.getMessage());
                // will do more processing here
            });
            from(String.format("kafka:%s?brokers=%s:%s", topicName, host, port)).bean(getMyService(), "myMethod")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    // some more processing
                }
            });
        }
    };

I provided wrong host and port, and expected to see an exception. However, no exception is seen in the log, and the onException processing is not get called.
Any idea what I am doing wrong?

A similar problem can be reproduced by running https://github.com/apache/camel/blob/master/examples/camel-example-kafka/src/main/java/org/apache/camel/example/kafka/MessageConsumerClient.java locally without any Kafka server running. Doing so results in a constant flow of messages:

Connection to node -1 could not be established. Broker may not be available.

Is there a way to have an exception thrown?
Any help would be appreciated.


问:
Kibana time delta between two fields
I have two fields as part of a log message saved in our ELK cluster:

```<code>"EventTime": "2015-07-28 17:03:20",
"EventReceivedTime": "2015-07-28 17:03:22"
</code>```

Is there a way to get the time difference between this fields (in this case 2 sec.) in each log message and display it trough Kibana3?

If its not possible a direct elasticsearch query would also work.

Thanks in advance!

答:
Looking at the docs: https://www.elastic.co/guide/en/elasticsearch/reference/5.0/modules-scripting-expression.html#_date_field_api

I would assume a date deduction would work since "Date fields are treated as the number of milliseconds since January 1, 1970":

```<code>doc['@timestamp'] - doc['lastUpdatedDate']
</code>```

It doesn't. At least not in elastic/kibana 6.0.0. I did get this to work with this very ugly hack:

```<code>((doc['@timestamp'].date.year - 2017) * 31536000 + doc['@timestamp'].date.monthOfYear * 86400 + doc['@timestamp'].date.dayOfMonth * 3600 + doc['@timestamp'].date.secondOfDay) - ((doc['lastUpdatedDate'].date.year - 2017) * 31536000 + doc['lastUpdatedDate'].date.monthOfYear * 86400 + doc['lastUpdatedDate'].date.dayOfMonth * 3600 + doc['lastUpdatedDate'].date.secondOfDay)
</code>```

I had to deduce 2017 from the year since the number otherwise overflows...

Title: Kibana time delta between two fields

Body:
I have two fields as part of a log message saved in our ELK cluster:

"EventTime": "2015-07-28 17:03:20",
"EventReceivedTime": "2015-07-28 17:03:22"

Is there a way to get the time difference between this fields (in this case 2 sec.) in each log message and display it trough Kibana3?

If its not possible a direct elasticsearch query would also work.

Thanks in advance!

Body:
Looking at the docs: https://www.elastic.co/guide/en/elasticsearch/reference/5.0/modules-scripting-expression.html#_date_field_api

I would assume a date deduction would work since "Date fields are treated as the number of milliseconds since January 1, 1970":

doc['@timestamp'] - doc['lastUpdatedDate']

It doesn't. At least not in elastic/kibana 6.0.0. I did get this to work with this very ugly hack:

((doc['@timestamp'].date.year - 2017) * 31536000 + doc['@timestamp'].date.monthOfYear * 86400 + doc['@timestamp'].date.dayOfMonth * 3600 + doc['@timestamp'].date.secondOfDay) - ((doc['lastUpdatedDate'].date.year - 2017) * 31536000 + doc['lastUpdatedDate'].date.monthOfYear * 86400 + doc['lastUpdatedDate'].date.dayOfMonth * 3600 + doc['lastUpdatedDate'].date.secondOfDay)

I had to deduce 2017 from the year since the number otherwise overflows...


问:
Make a button visible when service is stopped
I will do something when service stopped in my app

for example:
i have a countdown code in my service,and then i will when that countdown stopped random button set visible.

i don't know how i can do something by service,i can't set button in service's body so how i can set it?and where i should do it?

in this following code i wrote my countdown in //your code line but i don't know how i can set button visible when count down stopped

```<code>public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       strong text // your code
        return Service.START_FLAG_REDELIVERY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
</code>```

答: What you are trying to do is communicate between a running service and an Activity. There are multiple ways to do this. The most easiest would be to pass an event from the service and catch that event in the activity. You can implement it from scratch or use an Event Bus. I would recommend using this library EventBus. Using this library you can pass an object containing some info (about what happened in the service) to the activity and based on that you can perform the action you need. I'm not posting any code. Please try doing it yourself, it will be a good learning experience.   </p>

Body:
I will do something when service stopped in my app

for example:
i have a countdown code in my service,and then i will when that countdown stopped random button set visible.

i don't know how i can do something by service,i can't set button in service's body so how i can set it?and where i should do it?

in this following code i wrote my countdown in //your code line but i don't know how i can set button visible when count down stopped

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       strong text // your code
        return Service.START_FLAG_REDELIVERY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}


问:
Can I set a general-purpose (not spark.*) parameter when submitting a spark application?
A normal way to set a parameter in spark-submit is using --conf:

```<code>spark2-shell --conf "spark.nonexisting=true" --conf "failOnDataLoss=false"
</code>```

Unfortunately this only works for spark.* parameters and I need to set up other parameters which are simply ignored:

```<code>scala> spark.conf.getAll.filter(p => (p._1 contains "nonexisting") || (p._1 contains "failOnDataLoss"))
res3: scala.collection.immutable.Map[String,String] = Map(spark.nonexisting -> true)
</code>```

Of course, I can set anything during run-time, but in my case this is not an acceptable solution.

答:
You can either:

Use general purpose configuration tool like lightbend/config.

Introduce your own namespace in Spark configuration to avoid clashes with built ones, like:

```<code>--conf "spark.wrodionow.failOnDataLoss=false"
</code>```

For submitted programs, you can also use standard arguments:

```<code> spark-submit my.jar --some_option ... --other_option ...
</code>```

Body:
A normal way to set a parameter in spark-submit is using --conf:

spark2-shell --conf "spark.nonexisting=true" --conf "failOnDataLoss=false"

Unfortunately this only works for spark.* parameters and I need to set up other parameters which are simply ignored:

scala> spark.conf.getAll.filter(p => (p._1 contains "nonexisting") || (p._1 contains "failOnDataLoss"))
res3: scala.collection.immutable.Map[String,String] = Map(spark.nonexisting -> true)

Of course, I can set anything during run-time, but in my case this is not an acceptable solution.

Body:
You can either:

Use general purpose configuration tool like lightbend/config.

Introduce your own namespace in Spark configuration to avoid clashes with built ones, like:

--conf "spark.wrodionow.failOnDataLoss=false"

For submitted programs, you can also use standard arguments:

 spark-submit my.jar --some_option ... --other_option ...


问:
Eclipse XML formatter
What is a free alternative to the built-in Eclipse XML editor?

The one packaged with the IDE has two major problems with formatting:

The formatter tries to parse escaped char's as though they were unescaped. E.g. '<' is treated like '<' which causes the formatter to "stop".

White space between elements is not honored:

```<code><foo>   text </foo>
</code>```

will be formatted to:

```<code><foo>text</foo>
</code>```

We are using Eclipse 3.4.

Updates

Issue #1 is a known bug: Formatting issues with entities in XML files.

Apparently the white space formatting is intended functionality.  I have requested this be provided as an option or advise on fixing this in a plugin of my own, but as of yet, no answer.

答:
I have used XMLBuddy in the past
http://www.xmlbuddy.com/

before I reverted to OxygenXML but you have to pay for Oxygen.

Title: Eclipse XML formatter

Body:
What is a free alternative to the built-in Eclipse XML editor?

The one packaged with the IDE has two major problems with formatting:

The formatter tries to parse escaped char's as though they were unescaped. E.g. '<' is treated like '<' which causes the formatter to "stop".

White space between elements is not honored:

<foo>   text </foo>

will be formatted to:

<foo>text</foo>

We are using Eclipse 3.4.

Updates

Issue #1 is a known bug: Formatting issues with entities in XML files.

Apparently the white space formatting is intended functionality.  I have requested this be provided as an option or advise on fixing this in a plugin of my own, but as of yet, no answer.

LastEditorDisplayName: Roger Pate

OwnerDisplayName: durple


问:
aspnet.friendlyurls versus Url Rewriting
We're looking to ditch the old URL rewriting package we're currently using in our asp.net webforms application (UrlRewritingNet - it is out of support and development). In my research I've come across two potential replacements (I think) however I'm unclear if they are truly apples to apples in their essential functionality (as well as our existing functionality).

The first is friendlyUrls, if I add the NuGet package and get it configured, it looks like I can work with it and it will probably do all the redirecting and friendly urls that we need. It looks like it's pretty easy to use and we can code to put some routes in a DB and make it so we don't have to hard code everything into a config file.

The second is URL Rewrite 2.0 for IIS. It seems more like what we're currently using. It appears that everything is specified in the .config file. It also seems pretty involved to create rewrites.

We only have a couple of rewrites that seem that they may not be served easily by friendlyUrls (like http=>https, a 301 redirect from our old domain and a no-www => www) but it may also be I haven't looked into that aspect of friendlyUrls. (edit: Oh, and I guess we may get a request occasionally to go from a friendlyUrl to an outside website i.e. www.oursite.com/there => www.yoursite.com)

My question is, are these essentially the same thing, or am I missing something? Should I be using one, the other or both do and in what instances should I use one over the other? I can't seem to find a clear comparison of what each does/doesn't do for me, especially in comparison to the other.

答:
@mason Thanks for your comment, you pointed me in a good direction.

FriendlyUrl is just an extension of the routes built in to .Net (adding automatic routing) this will do much of our what our "rewriting" did. I would then use the routes.MapPageRoute to add specific additional page routes (i.e. we would like to get to page x via these additional friendly URLs). Finally, I need some kind of rewriting though if I want to do any external changes (i.e. the old domain to new domain).


问:
Return records where 2 columns don't match
I want to find records where two columns don't match. In order to do this I need to divide one of the columns by 100 (as it is in %).

My table:

```<code>|artno|artno2|Quantity_Percent|Quantity_pcs|
|1111 |aaaa  |       28       |    0,28    |
|1111 |bbbb  |        0,65    |    0,017   |
</code>```

Query:

```<code>Select artno, artno2, (Quantity_Percent / 100) as Percent, Quantity_pcs
From Table1
Where artno = '1111'
</code>```

Turns this in to:

```<code>|artno|artno2|     Percent    |Quantity_pcs|
|1111 |aaaa  |        0,28    |    0,28    |
|1111 |bbbb  |        0,0065  |    0,017   |
</code>```

So far so good; but if I want the query to return only the 2nd row where the  Quantity_Percent and Quantity_pcs columns don't match, how do I do that?

Thanks in advance.

SisU

答:
Just add that condition with and

 For Example With your query:

```<code>Select artno, artno2, (Quantity_Procent / 100) as Procent, Quantity_pcs
From Table1
Where artno = '1111' and Quantity_Procent != (Quntity_pcs*100);
</code>```

If you want that for all atno then put this Quantity_Procent != (Quntity_pcs*100) in your where condition.

Body:
I want to find records where two columns don't match. In order to do this I need to divide one of the columns by 100 (as it is in %).

My table:

|artno|artno2|Quantity_Percent|Quantity_pcs|
|1111 |aaaa  |       28       |    0,28    |
|1111 |bbbb  |        0,65    |    0,017   |

Query:

Select artno, artno2, (Quantity_Percent / 100) as Percent, Quantity_pcs
From Table1
Where artno = '1111'

Turns this in to:

|artno|artno2|     Percent    |Quantity_pcs|
|1111 |aaaa  |        0,28    |    0,28    |
|1111 |bbbb  |        0,0065  |    0,017   |

So far so good; but if I want the query to return only the 2nd row where the  Quantity_Percent and Quantity_pcs columns don't match, how do I do that?

Thanks in advance.

SisU

Body:
Just add that condition with and

 For Example With your query:

Select artno, artno2, (Quantity_Procent / 100) as Procent, Quantity_pcs
From Table1
Where artno = '1111' and Quantity_Procent != (Quntity_pcs*100);

If you want that for all atno then put this Quantity_Procent != (Quntity_pcs*100) in your where condition.


问:
Google Speech Recognition on video file
I wanna use Google Voice Service by not microphone but video file.
for example, A Video File is playing on my computer and Google Speech Recognition Program is recognizing the video's Audio stream.
ex) Auto caption function of Youtube.
How can I use G.S.R??</p>

答:
This is a great question, Google does provide a way of doing that through the Web Speech API. Here's a link to an example usage, and a demo site from Google here.

However, you would have to extract the audio from the video first and then feed the audio to the API.

There's also the Cloud Speech API, which is free up to a certain point. It can be found here.

Title: Google Speech Recognition on video file


问:
Why missing terminating " character is a warning?
When, for example,  we compile the following code:

```<code>printf("hello);
</code>```

we get a warning then an error about the missing " character. In my opinion, warnings inform us about a code that can be compiled but whose behaviour may be probably different from what the developper expects. Therefore my comprehension missed up two things:

Is there a complete code that can be compiled without errors while containing such a portion of code.

If such a code does not exist, why this missing character situation does not give us only an error (not a warning+error).

EDIT (I am doing my best to cope with off-topic votes recommendations):

1. Desired behavior : only one error diagnostic message, there is no need for a warning for the same thing.

Other related issues that do not let me accept the first answer:

2.1 Does printf_s() have the same issue? I tried to enable -c11 option with no success.

2.2 The historical reason to emit the warning does not seem to me to be plausible since why this double message was not used too in similar cases (old accepted constructions being forbidden in new c versions).

答:
In my opinion, warnings inform us about a code that can be compiled
  but whose behaviour may be probably different from what the developper
  expects. Therefore my comprehension missed up two things:

Your opinion is irrelevant here, and neither the C standard nor the C++ standard distinguish different categories of diagnostic messages.  That many compilers in fact do distinguish is an historically-based convention, albeit a widely observed one.  What ultimately matters is what your compiler means by such a distinction (if indeed it makes one).  On the other hand, and fortunately for you, GCC does adopt a convention similar to what you describe, as documented in its manual:

Errors report problems that make it impossible to compile your program. [...].

Warnings report other unusual conditions in your code that may indicate a problem, although compilation can (and does) proceed. [...]

(GCC 7.2 manual, section 13.9; the same or similar text appears also in earlier versions of the manual, back to at least v.4.)

Note well that the documentation frames the meaning of a warning slightly differently than you do: a GCC warning signals that compilation can proceed, but there is no assurance that it can complete successfully.  If indeed it ultimately cannot then I would expect GCC, pursuant to its documentation, to also issue an error diagnostic.  That is exactly what I observe with this test program, whether compiling as C or as C++:

```<code>#include <stdio.h>

int main(void) {
    printf("hello);
}
</code>```

I really think you are making far too much of the fact that GCC emits a warning in addition to an error in this case.  That's an implementation quirk of no particular significance.

Is there a complete code that can be compiled without errors while containing such a portion of code.

It depends on exactly what you mean by that.  Trivially, I could prefix the erroneous line in the above program with // to turn it into a comment, and that would make it perfectly valid C and C++ source.  There are manifold other ways I could add to the given source without removing anything to make it valid -- some of them would even produce a program in which a printf() call is in fact performed.

I suppose that what you really want to know is whether there is code that would elicit the warning from GCC but not the corresponding error.  To the best of my knowledge, modern GCC does not afford such code, but historically, GCC did allow it as an extension, in the form of embedded, unescaped newlines in string literals:

```<code>    printf("hello);
    Goodbye");
</code>```

That behavior was already deprecated in GCC 3.2, and it was removed as early as GCC 4 (current is 7.2).

If such a code does not exist, why this missing character situation does not give us only an error (not a warning+error).

We can only guess, but it seems plausible that it derives from the historical existence of the language extension described above.  And again, you are making far too much of this.  GCC emits two diagnostics about the same problem -- so what?  The ultimate purpose of the diagnostics is to help you figure out what is or may be wrong with your code, and the diagnostics GCC emits in this case do that job just fine.

Body:
When, for example,  we compile the following code:

printf("hello);

we get a warning then an error about the missing " character. In my opinion, warnings inform us about a code that can be compiled but whose behaviour may be probably different from what the developper expects. Therefore my comprehension missed up two things:

Is there a complete code that can be compiled without errors while containing such a portion of code.

If such a code does not exist, why this missing character situation does not give us only an error (not a warning+error).

EDIT (I am doing my best to cope with off-topic votes recommendations):

1. Desired behavior : only one error diagnostic message, there is no need for a warning for the same thing.

Other related issues that do not let me accept the first answer:

2.1 Does printf_s() have the same issue? I tried to enable -c11 option with no success.

2.2 The historical reason to emit the warning does not seem to me to be plausible since why this double message was not used too in similar cases (old accepted constructions being forbidden in new c versions).

Body:
In my opinion, warnings inform us about a code that can be compiled
  but whose behaviour may be probably different from what the developper
  expects. Therefore my comprehension missed up two things:

Your opinion is irrelevant here, and neither the C standard nor the C++ standard distinguish different categories of diagnostic messages.  That many compilers in fact do distinguish is an historically-based convention, albeit a widely observed one.  What ultimately matters is what your compiler means by such a distinction (if indeed it makes one).  On the other hand, and fortunately for you, GCC does adopt a convention similar to what you describe, as documented in its manual:

Errors report problems that make it impossible to compile your program. [...].

Warnings report other unusual conditions in your code that may indicate a problem, although compilation can (and does) proceed. [...]

(GCC 7.2 manual, section 13.9; the same or similar text appears also in earlier versions of the manual, back to at least v.4.)

Note well that the documentation frames the meaning of a warning slightly differently than you do: a GCC warning signals that compilation can proceed, but there is no assurance that it can complete successfully.  If indeed it ultimately cannot then I would expect GCC, pursuant to its documentation, to also issue an error diagnostic.  That is exactly what I observe with this test program, whether compiling as C or as C++:

#include <stdio.h>

int main(void) {
    printf("hello);
}

I really think you are making far too much of the fact that GCC emits a warning in addition to an error in this case.  That's an implementation quirk of no particular significance.

Is there a complete code that can be compiled without errors while containing such a portion of code.

It depends on exactly what you mean by that.  Trivially, I could prefix the erroneous line in the above program with // to turn it into a comment, and that would make it perfectly valid C and C++ source.  There are manifold other ways I could add to the given source without removing anything to make it valid -- some of them would even produce a program in which a printf() call is in fact performed.

I suppose that what you really want to know is whether there is code that would elicit the warning from GCC but not the corresponding error.  To the best of my knowledge, modern GCC does not afford such code, but historically, GCC did allow it as an extension, in the form of embedded, unescaped newlines in string literals:

    printf("hello);
    Goodbye");

That behavior was already deprecated in GCC 3.2, and it was removed as early as GCC 4 (current is 7.2).

If such a code does not exist, why this missing character situation does not give us only an error (not a warning+error).

We can only guess, but it seems plausible that it derives from the historical existence of the language extension described above.  And again, you are making far too much of this.  GCC emits two diagnostics about the same problem -- so what?  The ultimate purpose of the diagnostics is to help you figure out what is or may be wrong with your code, and the diagnostics GCC emits in this case do that job just fine.


答:
The condition you need to add to your WHERE clause is

```<code>AND Quantity_Percent <> Quantity_pcs * 100
</code>```

This condition replaces division with multiplication. In addition, you could exclude rows based on a threshold:

```<code>AND ABS(Quantity_Percent - Quantity_pcs * 100) > 1E-6
</code>```

Title: Return records where 2 columns don't match

Body:
The condition you need to add to your WHERE clause is

AND Quantity_Percent <> Quantity_pcs * 100

This condition replaces division with multiplication. In addition, you could exclude rows based on a threshold:

AND ABS(Quantity_Percent - Quantity_pcs * 100) > 1E-6


问:
separation of logic and UI in titanium (javascript)
i'm new to appcelerators titanium and javascript and i'm interested in coding an iphone app. i recognized that there is a need of "many" code for creating the UI. that's no problem so far, but i tend to separate that code from my application logic wisely. what are the best practices?

[update] tweetanium is a great example how to structure a titanium mobile application

答:
i'll have a try:

i tend to use the mvc-pattern for developing my application since implementing all stuff in one single js-file is quite ugly. so i decided to use one file for the view and all the stuff concering the look-and-feel, one file for the database handling (the controller), especially the sql-statements, and one file for the abstract data type (the model).

a short example:

view: viewConcerningObject.js

```<code>Ti.include('object.js');

var win = Ti.UI.currentWindow;
var myObject = new object();

var myObjectName = Ti.UI.createLabel({
   text:myObject.getName();
});

win.add(myObjectName);
</code>```

model: object.js

```<code>Ti.include('controllerConceringObject.js');

function object(){
   this.name = 'myInitialName';

   this.getName(){
      return this.name;
   };

   this.setName(newName){
      this.name = newName;
   };

   this.updateNameFromDb(){
      this.name = getNameFromDatabase();
   };

}
</code>```

controller: controllerConcerningObject.js

```<code>function getNameFromDataBase(){
   var db = Ti.Database('objects');
   var sql = 'SELECT name FROM objects';
   var recordset = db.execute(sql);
   var name  = recordset.field(0);
   recordset.close();
   db.close();
   return name;
};
</code>```

so the folder structure could be like this:

myProject: folderView(viewConcerningObject.js), folderModel(theDatabase.db,object.js), folderController(controllerConcerningObject.js).

Body:
i'll have a try:

i tend to use the mvc-pattern for developing my application since implementing all stuff in one single js-file is quite ugly. so i decided to use one file for the view and all the stuff concering the look-and-feel, one file for the database handling (the controller), especially the sql-statements, and one file for the abstract data type (the model).

a short example:

view: viewConcerningObject.js

Ti.include('object.js');

var win = Ti.UI.currentWindow;
var myObject = new object();

var myObjectName = Ti.UI.createLabel({
   text:myObject.getName();
});

win.add(myObjectName);

model: object.js

Ti.include('controllerConceringObject.js');

function object(){
   this.name = 'myInitialName';

   this.getName(){
      return this.name;
   };

   this.setName(newName){
      this.name = newName;
   };

   this.updateNameFromDb(){
      this.name = getNameFromDatabase();
   };

}

controller: controllerConcerningObject.js

function getNameFromDataBase(){
   var db = Ti.Database('objects');
   var sql = 'SELECT name FROM objects';
   var recordset = db.execute(sql);
   var name  = recordset.field(0);
   recordset.close();
   db.close();
   return name;
};

so the folder structure could be like this:

myProject: folderView(viewConcerningObject.js), folderModel(theDatabase.db,object.js), folderController(controllerConcerningObject.js).


问:
How to build a Markov's chain transition probability matrix
I am learning R on my own and I am having some troubles trying to build a transition probability matrix in Rstudio using the markovchain package. First I tried to calculate the transition probabilities of a DNA sequence.

```<code>ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT
</code>```

But how can the transition probability matrix be calculated in a sequence like this, I was thinking of using R indexes but I don't really know how to calculate those transition probabilities.

Is there a way of doing this in R?
I am guessing that the output of those probabilities in a matrix should be something like this:

```<code>     A    T    C    G
  A 0.60 0.10 0.10 0.20
  T 0.10 0.50 0.30 0.10
  C 0.05 0.20 0.70 0.05
  G 0.40 0.05 0.05 0.50
</code>```

答:
You can use the markovchain package for help with this. First, your data

```<code>seq <- "ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT"
</code>```

Then use the package

```<code>library(markovchain)
base_sequence <- strsplit(seq, "")[[1]]
mcX <- markovchainFit(base_sequence)$estimate
mcX

#           A         C         G         T
# A 0.3000000 0.2250000 0.2583333 0.2166667
# C 0.2857143 0.2619048 0.2380952 0.2142857
# G 0.3764706 0.1882353 0.2117647 0.2235294
# T 0.3068182 0.2159091 0.1818182 0.2954545
</code>```

Body:
I am learning R on my own and I am having some troubles trying to build a transition probability matrix in Rstudio using the markovchain package. First I tried to calculate the transition probabilities of a DNA sequence.

ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT

But how can the transition probability matrix be calculated in a sequence like this, I was thinking of using R indexes but I don't really know how to calculate those transition probabilities.

Is there a way of doing this in R?
I am guessing that the output of those probabilities in a matrix should be something like this:

     A    T    C    G
  A 0.60 0.10 0.10 0.20
  T 0.10 0.50 0.30 0.10
  C 0.05 0.20 0.70 0.05
  G 0.40 0.05 0.05 0.50

Body:
You can use the markovchain package for help with this. First, your data

seq <- "ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT"

Then use the package

library(markovchain)
base_sequence <- strsplit(seq, "")[[1]]
mcX <- markovchainFit(base_sequence)$estimate
mcX

#           A         C         G         T
# A 0.3000000 0.2250000 0.2583333 0.2166667
# C 0.2857143 0.2619048 0.2380952 0.2142857
# G 0.3764706 0.1882353 0.2117647 0.2235294
# T 0.3068182 0.2159091 0.1818182 0.2954545


问:
How to get HMAC with Crypto Web API
How can I get HMAC-SHA512(key, data) in the browser using Crypto Web API (window.crypto)?

Currently I am using CryptoJS library and it is pretty simple:

CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();

Result is 91c14b8d3bcd48be0488bfb8d96d52db6e5f07e5fc677ced2c12916dc87580961f422f9543c786eebfb5797bc3febf796b929efac5c83b4ec69228927f21a03a.

I want to get rid of extra dependencies and start using Crypto Web API instead. How can I get the same result with it?

答:
Answering my own question. The code below returns the same result as CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();

There are promises everywhere as WebCrypto is asynchronous:

```<code>// encoder to convert string to Uint8Array
var enc = new TextEncoder("utf-8");

window.crypto.subtle.importKey(
    "raw", // raw format of the key - should be Uint8Array
    enc.encode("mysecretkey"),
    { // algorithm details
        name: "HMAC",
        hash: {name: "SHA-512"}
    },
    false, // export = false
    ["sign", "verify"] // what this key can do
).then( key => {
    window.crypto.subtle.sign(
        "HMAC",
        key,
        enc.encode("myawesomedata")
    ).then(signature => {
        var b = new Uint8Array(signature);
        var str = Array.prototype.map.call(b, x => x.toString(16).padStart(2, '0')).join("")
        console.log(str);
    });
});
</code>```

Title: How to get HMAC with Crypto Web API

Body:
Answering my own question. The code below returns the same result as CryptoJS.HmacSHA512("myawesomedata", "mysecretkey").toString();

There are promises everywhere as WebCrypto is asynchronous:

// encoder to convert string to Uint8Array
var enc = new TextEncoder("utf-8");

window.crypto.subtle.importKey(
    "raw", // raw format of the key - should be Uint8Array
    enc.encode("mysecretkey"),
    { // algorithm details
        name: "HMAC",
        hash: {name: "SHA-512"}
    },
    false, // export = false
    ["sign", "verify"] // what this key can do
).then( key => {
    window.crypto.subtle.sign(
        "HMAC",
        key,
        enc.encode("myawesomedata")
    ).then(signature => {
        var b = new Uint8Array(signature);
        var str = Array.prototype.map.call(b, x => x.toString(16).padStart(2, '0')).join("")
        console.log(str);
    });
});

ContentLicense: CC BY-SA 4.0


问:
Select items from List of objects that are tuples
I have a class that looks like so;

```<code>class MessageEntry
{
    public Tuple<bool, int> MessageId;

    public Tuple<bool, DateTime> MessageDate { get; internal set; }
    public Tuple<bool, String> Subject { get; internal set; }
    public Tuple<bool, String> EmailFrom { get; internal set; }
    public Tuple<bool, String> EmailTo { get; internal set; }
    public Tuple<bool, String> EmailCC { get; internal set; }
    public Tuple<bool, String> EmailBCC { get; internal set; }
    public Tuple<bool, String> EmailDateSent { get; internal set; }
    public Tuple<bool, String> BodyHTML { get; internal set; }
}
</code>```

I then have a List<MessageEntry> - List<MessageEntry> test = new List<MessageEntry>.

How can I select all items frrom test where Item1 of the tuples is true?

答:
```<code>var result = test.Where(x => x.MessageDate.Item1 && x.Subject.Item1 && ....);
</code>```

Body:
I have a class that looks like so;

class MessageEntry
{
    public Tuple<bool, int> MessageId;

    public Tuple<bool, DateTime> MessageDate { get; internal set; }
    public Tuple<bool, String> Subject { get; internal set; }
    public Tuple<bool, String> EmailFrom { get; internal set; }
    public Tuple<bool, String> EmailTo { get; internal set; }
    public Tuple<bool, String> EmailCC { get; internal set; }
    public Tuple<bool, String> EmailBCC { get; internal set; }
    public Tuple<bool, String> EmailDateSent { get; internal set; }
    public Tuple<bool, String> BodyHTML { get; internal set; }
}

I then have a List<MessageEntry> - List<MessageEntry> test = new List<MessageEntry>.

How can I select all items frrom test where Item1 of the tuples is true?


问:
Grails custom validator for domain class
I have a restriction so there could be no more than
ConfigurationHolder.config.support.reminder.web.person.max object stored.
I didn't find how to add a validator which doesn't relate on particular property. So for now I implemented it in this way. Do you guys have any ideas how to make it better?

```<code>package support.reminder.web

import org.codehaus.groovy.grails.commons.ConfigurationHolder;

class Person {

    String firstName
    String lastName
    String email
    Date lastDutyDate

    static constraints = {
        firstName(blank: false)
        lastName(blank: false)
        email(blank: false, email: true)
        lastDutyDate(nullable: true)
        id validator: {val ->
        if (val)
            Person.count() <= ConfigurationHolder.config.support.reminder.web.person.max
        else
            Person.count() < ConfigurationHolder.config.support.reminder.web.person.max
    }
    }

    String toString() {
        "[$firstName $lastName, $email, $lastDutyDate]"
    }
}
</code>```

答: I don't have a better idea, but I do suggest that maybe you need to check for < not <=. I think that when validating your object, it has not yet been stored in the DB, so it will not be included in Person.count(). I reckon that <= would cause it to pass the validation then be saved, then you would be violating the rule.</p>

Body:
I have a restriction so there could be no more than
ConfigurationHolder.config.support.reminder.web.person.max object stored.
I didn't find how to add a validator which doesn't relate on particular property. So for now I implemented it in this way. Do you guys have any ideas how to make it better?

package support.reminder.web

import org.codehaus.groovy.grails.commons.ConfigurationHolder;

class Person {

    String firstName
    String lastName
    String email
    Date lastDutyDate

    static constraints = {
        firstName(blank: false)
        lastName(blank: false)
        email(blank: false, email: true)
        lastDutyDate(nullable: true)
        id validator: {val ->
        if (val)
            Person.count() <= ConfigurationHolder.config.support.reminder.web.person.max
        else
            Person.count() < ConfigurationHolder.config.support.reminder.web.person.max
    }
    }

    String toString() {
        "[$firstName $lastName, $email, $lastDutyDate]"
    }
}


问:
How to assign value in 2 Dimensional array
Creating a tile pattern

```<code>char t1[11][11];
int i=0;
int j=0;

int size = 10;
//Putting "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++)
{
    while(j=0)
    {
        t1[i][j] = '|';
    }
}

//Putting "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        t1[i][j] = '-';
    }
}

//PRINTING  "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++){
    while(j=0){
        printf("%c \n",t1[i][j]);
    }
    printf("\n");
}

//PRINTING "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        printf("%c "), t1[i][j];
    }
}
</code>```

So basically I want the output to be like the image given.
I declared an array with 11,11 size and I am trying to use loops to assign characters in the array. But for some reason it is not working.

I know I have to use loops so I drew the pattern on a paper and write down the array location and tried to assign using loops.

答:
When you are using

```<code>printf("%c \n", t1[i][j]);
</code>```

You are writing a character from the array and appending it with a  newline which will break your pattern.

Try changing your printing loops for this one

```<code> for (j = 0; j <= 10; ++j)
 {
   printf("%s\n" ,t1[j]);
 }
</code>```

As for writting the '@' characters I would do a loop like that

```<code>for (i = 1; i < 10; ++i)
{
  for (j = 1; j < 10; ++j)
  {
    if ((j == 1 || i == 1 || j == 9 || i == 9) || j == i)
      t1[i][j] = '@';
  }
}
</code>```

Body:
Creating a tile pattern

char t1[11][11];
int i=0;
int j=0;

int size = 10;
//Putting "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++)
{
    while(j=0)
    {
        t1[i][j] = '|';
    }
}

//Putting "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        t1[i][j] = '-';
    }
}

//PRINTING  "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++){
    while(j=0){
        printf("%c \n",t1[i][j]);
    }
    printf("\n");
}

//PRINTING "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        printf("%c "), t1[i][j];
    }
}

So basically I want the output to be like the image given.
I declared an array with 11,11 size and I am trying to use loops to assign characters in the array. But for some reason it is not working.

I know I have to use loops so I drew the pattern on a paper and write down the array location and tried to assign using loops.

Body:
When you are using

printf("%c \n", t1[i][j]);

You are writing a character from the array and appending it with a  newline which will break your pattern.

Try changing your printing loops for this one

 for (j = 0; j <= 10; ++j)
 {
   printf("%s\n" ,t1[j]);
 }

As for writting the '@' characters I would do a loop like that

for (i = 1; i < 10; ++i)
{
  for (j = 1; j < 10; ++j)
  {
    if ((j == 1 || i == 1 || j == 9 || i == 9) || j == i)
      t1[i][j] = '@';
  }
}


问:
Keep external script from loading a URL
I have a plugin for my website that adds a Disqus comment box to my articles. The plugin loads the Disqus script that adds the comment box, but it unfortunately also calls some URLs associated with ad tracking.

How do I prevent these URLs from being loaded?

Edit: I can't give code. The Disqus files are very large.

答:
Short answer: you cannot do that. If you want to add Disqus to your site then you have to concede to the fact that they will add their tracking data (why do you think they are providing this service for free).

Note: Currently, our large clients are really resenting the fact that they used Disqus for commenting, since they are now paying $99/month in order to hide the scammy ads that Disqus displays + it always adds its own tracking data.

Title: Keep external script from loading a URL


答:
You have a number of errors in your program. Let me list down some:

j = 0 assigns 0 to j, and j == 0 compares if j is equal to 0.

You haven't updated the i or j in inner while loops.

If you want to stick to the exact pattern shown in the picture, you have to eliminate \n from printf("%c \n", t1[i][j]);.

printf("%c "), t1[i][j]; doesn't print t1[i][j]. But printf("%c ", t1[i][j]); does.

You're not assigning @ character in the array anywhere.

Let's re-write your code:

Initialize the array:

```<code>char t1[11][11];
</code>```

Now, in a loop, assign each element in this 11 x 11 array a character according to the pattern.

```<code>for (int i = 0; i < 11; i++){
    for (int j = 0; j < 11; j++){

        // If its first or last column, then place a | at t1[i][j]
        if (j == 0 || j == 10){
            t1[i][j] = '|';
        }
        // Else If its the first or last row, then place a - at t1[i][j]
        else if (i == 0 || i == 10){
            t1[i][j] = '-';
        }
        // Else if its the second or second to last row/column
        // then place @ at t1[i][j]
        else if (i == 1 || i == 9 || j == 1 || j == 9){
            t1[i][j] = '@';
        }
        // Else if its the diagonal, then place a @ at t1[i][j]
        else if (i == j){
            t1[i][j] = '@';
        }
        // All remaining places would have a space.
        else{
            t1[i][j] = ' ';
        }
    }
}
</code>```

After this, every element in the array would have been initialized to some appropriate value. Now, print the whole array.

```<code>for (int i = 0; i < 11; i++){
    for (int j = 0; j < 11; j++){
        printf("%c\t", t1[i][j]);
    }
    printf("\n");
}
</code>```

See this code running live here.

Title: How to assign value in 2 Dimensional array

Body:
You have a number of errors in your program. Let me list down some:

j = 0 assigns 0 to j, and j == 0 compares if j is equal to 0.

You haven't updated the i or j in inner while loops.

If you want to stick to the exact pattern shown in the picture, you have to eliminate \n from printf("%c \n", t1[i][j]);.

printf("%c "), t1[i][j]; doesn't print t1[i][j]. But printf("%c ", t1[i][j]); does.

You're not assigning @ character in the array anywhere.

Let's re-write your code:

Initialize the array:

char t1[11][11];

Now, in a loop, assign each element in this 11 x 11 array a character according to the pattern.

for (int i = 0; i < 11; i++){
    for (int j = 0; j < 11; j++){

        // If its first or last column, then place a | at t1[i][j]
        if (j == 0 || j == 10){
            t1[i][j] = '|';
        }
        // Else If its the first or last row, then place a - at t1[i][j]
        else if (i == 0 || i == 10){
            t1[i][j] = '-';
        }
        // Else if its the second or second to last row/column
        // then place @ at t1[i][j]
        else if (i == 1 || i == 9 || j == 1 || j == 9){
            t1[i][j] = '@';
        }
        // Else if its the diagonal, then place a @ at t1[i][j]
        else if (i == j){
            t1[i][j] = '@';
        }
        // All remaining places would have a space.
        else{
            t1[i][j] = ' ';
        }
    }
}

After this, every element in the array would have been initialized to some appropriate value. Now, print the whole array.

for (int i = 0; i < 11; i++){
    for (int j = 0; j < 11; j++){
        printf("%c\t", t1[i][j]);
    }
    printf("\n");
}

See this code running live here.


问:
Extract values only from an array to encode them in JSON using PHP
This has probably been asked many times but I can't find a solution for my case.

This is my array :

```<code>$request=Array (
        [0] => Array ( [staName] => Auditorium Stravinsky 2m2c )
        [1] => Array ( [staName] => Geneva Arena )
        [2] => Array ( [staName] => Les Docks )
        [3] => Array ( [staName] => Kheops )
    )
</code>```

And i need an output as follows as JSON:

```<code>"Auditorium Stravinsky 2m2c ","Geneva Arena","Les Docks","Kheops"
</code>```

My current code is as follows:

```<code>    foreach($request as $value)
    {
        $names[]=$value;
    }

    $jsonValue = json_encode(array_values($names));

    print_r($jsonValue);
</code>```

And my current output is as follows in JSON format:

```<code>[{"staName":"Auditorium Stravinsky 2m2c "},{"staName":"Geneva Arena"},{"staName":"Les Docks"},{"staName":"Kheops"}]
</code>```

How can i stop "staName " from being outputed?

Many thanks in advance and please be considerate of my post as this is only the second one I make on this site.

答:
fist of all your array definition are not correct. and your output is simple string not a JSON

```<code><?php

$request=Array (
        0 => Array ( 'staName' => 'Auditorium Stravinsky 2m2c' ),
        1 => Array ( 'staName' => 'Geneva Arena' ) ,
        2 => Array ( 'staName' => 'Les Docks' ) ,
        3 => Array ( 'staName' => 'Kheops' )
    );

    $name = '';
    foreach($request as $value)
    {
        foreach($value as $value2)
        {
            $name = $name . ' ' . $value2;
        }

    }
    echo $name;
</code>```

Output

```<code>Auditorium Stravinsky 2m2c Geneva Arena Les Docks Kheops
</code>```

Body:
This has probably been asked many times but I can't find a solution for my case.

This is my array :

$request=Array (
        [0] => Array ( [staName] => Auditorium Stravinsky 2m2c )
        [1] => Array ( [staName] => Geneva Arena )
        [2] => Array ( [staName] => Les Docks )
        [3] => Array ( [staName] => Kheops )
    )

And i need an output as follows as JSON:

"Auditorium Stravinsky 2m2c ","Geneva Arena","Les Docks","Kheops"

My current code is as follows:

    foreach($request as $value)
    {
        $names[]=$value;
    }

    $jsonValue = json_encode(array_values($names));

    print_r($jsonValue);

And my current output is as follows in JSON format:

[{"staName":"Auditorium Stravinsky 2m2c "},{"staName":"Geneva Arena"},{"staName":"Les Docks"},{"staName":"Kheops"}]

How can i stop "staName " from being outputed?

Many thanks in advance and please be considerate of my post as this is only the second one I make on this site.

Body:
fist of all your array definition are not correct. and your output is simple string not a JSON

<?php

$request=Array (
        0 => Array ( 'staName' => 'Auditorium Stravinsky 2m2c' ),
        1 => Array ( 'staName' => 'Geneva Arena' ) ,
        2 => Array ( 'staName' => 'Les Docks' ) ,
        3 => Array ( 'staName' => 'Kheops' )
    );

    $name = '';
    foreach($request as $value)
    {
        foreach($value as $value2)
        {
            $name = $name . ' ' . $value2;
        }

    }
    echo $name;

Output

Auditorium Stravinsky 2m2c Geneva Arena Les Docks Kheops


问:
Can/Should I Use an Asynchronous Controller Here? (ASP.NET MVC 3)
I have this [HttpPost] action method:

```<code>[HttpPost]
public ActionResult AddReview(Review review)
{
   repository.Add(review);
   repository.Save();
   repository.UpdateSystemScoring(review.Id); // call SPROC with new Review ID.
   return View("Success", review);
}
</code>```

So, basically a user clicks a button, i add it to my database (via Entity Framework 4.0), save changes, and then i call a stored procedure with the identity field, which is that second last line of code.

This needs to be done after the review is saved (as the identity field is only created once Save is called, and EF persists the changes), and it is a system-wide calculation.

From the user point of view, he/she doesn't/shouldn't care that this calculation is happening.

This procedure can take anywhere from 0-20 seconds. It does not return anything.

Is this a candidate for an asynchronous controller?

Is there a way i can add the Review, and let another asynchronous controller handle the long-running SPROC call, so the user can be taken to the Success page immediately?

I must admit (partially ashamed of this): this is a rewrite of an existing system, and in the original system (ASP.NET Web Forms), i fired off another thread in order to achieve the above task - which is why i was wondering if the same principal can be applied to ASP.NET MVC 3.

I always try and avoid multi-threading in ASP.NET but user experience is the #1 priority, and i do not want the page timing out.

So - is this possible? Also happy to hear any other ideas. Also - i can't use triggers here, don't really want to go into too much detail why - but i can't.

答: I would fire a new thread (not from the thread pool) to perform this task and return immediately especially if you don't care about the results. Asynchronous controllers are useful in situations where most of the time is spent waiting for some other system to complete the task and you once this system completes the task your application is signaled to process the result. During the execution of the task no threads are consumed from your application. So in your scenario this task could be performed by SQL Server using the async versions of the BeginRead methods in ADO.NET. You could use this if you need the results back. If you don't firing a new thread would work just fine as before.</p>

Body:
I have this [HttpPost] action method:

[HttpPost]
public ActionResult AddReview(Review review)
{
   repository.Add(review);
   repository.Save();
   repository.UpdateSystemScoring(review.Id); // call SPROC with new Review ID.
   return View("Success", review);
}

So, basically a user clicks a button, i add it to my database (via Entity Framework 4.0), save changes, and then i call a stored procedure with the identity field, which is that second last line of code.

This needs to be done after the review is saved (as the identity field is only created once Save is called, and EF persists the changes), and it is a system-wide calculation.

From the user point of view, he/she doesn't/shouldn't care that this calculation is happening.

This procedure can take anywhere from 0-20 seconds. It does not return anything.

Is this a candidate for an asynchronous controller?

Is there a way i can add the Review, and let another asynchronous controller handle the long-running SPROC call, so the user can be taken to the Success page immediately?

I must admit (partially ashamed of this): this is a rewrite of an existing system, and in the original system (ASP.NET Web Forms), i fired off another thread in order to achieve the above task - which is why i was wondering if the same principal can be applied to ASP.NET MVC 3.

I always try and avoid multi-threading in ASP.NET but user experience is the #1 priority, and i do not want the page timing out.

So - is this possible? Also happy to hear any other ideas. Also - i can't use triggers here, don't really want to go into too much detail why - but i can't.


问:
Difference between queries with grouped
I'm new to mongodb, and I have 2 queries:
frist:

```<code>db.movies.aggregate([
    { "$match": {
        $and : [
        { "imdb.rating": { $lt: 7 }},
        {$and: [ {"genres": { "$ne": "Crime" } }, {"genres": { "$ne": "Horror" } }]},
        {$and: [ {"languages": { "$eq": "English" } }, {"languages": { "$eq": "Japanese" } }]},
        {$or: [ {"rated": { "$eq": "PG" } }, {"rated": { "$eq": "G" } }]}

        ]

                }
    }
]).itcount()
</code>```

The result its: 23

And now with this:

```<code>db.movies.aggregate([
    { "$match": {
         "imdb.rating": { $lt: 7 },
         $and: [ {"genres": { "$ne": "Crime" } }, {"genres": { "$ne": "Horror" } }],
         $or: [ {"rated": { "$eq": "PG" } }, {"rated": { "$eq": "G" } }],
         $and: [ {"languages": { "$eq": "English" } }, {"languages": { "$eq": "Japanese" } }]

                }
    }
]).itcount()
</code>```

The result its 25,

But now I can't understand what is the difference between two queries, can help with this?

答:
There is no functional difference.  $match implicitly is using $and when you provide more than one expression and a simple key:value expression is shorthand for key: {$eq: value} e.g.

```<code>$match: {a:3, b:"buzz"}
</code>```

is shorthand for:

```<code>$match: {$and: [{a:{$eq:3}}, {b:{$eq:"buzz"}} ] }
</code>```

Title: Difference between queries with grouped

Body:
I'm new to mongodb, and I have 2 queries:
frist:

db.movies.aggregate([
    { "$match": {
        $and : [
        { "imdb.rating": { $lt: 7 }},
        {$and: [ {"genres": { "$ne": "Crime" } }, {"genres": { "$ne": "Horror" } }]},
        {$and: [ {"languages": { "$eq": "English" } }, {"languages": { "$eq": "Japanese" } }]},
        {$or: [ {"rated": { "$eq": "PG" } }, {"rated": { "$eq": "G" } }]}

        ]

                }
    }
]).itcount()

The result its: 23

And now with this:

db.movies.aggregate([
    { "$match": {
         "imdb.rating": { $lt: 7 },
         $and: [ {"genres": { "$ne": "Crime" } }, {"genres": { "$ne": "Horror" } }],
         $or: [ {"rated": { "$eq": "PG" } }, {"rated": { "$eq": "G" } }],
         $and: [ {"languages": { "$eq": "English" } }, {"languages": { "$eq": "Japanese" } }]

                }
    }
]).itcount()

The result its 25,

But now I can't understand what is the difference between two queries, can help with this?

Body:
There is no functional difference.  $match implicitly is using $and when you provide more than one expression and a simple key:value expression is shorthand for key: {$eq: value} e.g.

$match: {a:3, b:"buzz"}

is shorthand for:

$match: {$and: [{a:{$eq:3}}, {b:{$eq:"buzz"}} ] }


问:
Facebook PHP SDK 4 - get last 5 posts
I am trying to get the last five posts.  I have created the following:

```<code>try {
    // Returns a `Facebook\FacebookResponse` object
    $response = $this->fb->get(
    '/'.$page_id.'/posts',
    $access_token
    );

} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$graphNode = $response->getGraphEdge();
echo "```";
print_r($graphNode);
echo "```";
exit;
</code>```

How can I limit the output?  For example, instead of 100 records being returned, I only want 5.  I know I need to use 'limit=5' but don't know where in above to place it.

Also, with the above script, I get a massive Facebook\GraphNodes\GraphEdge Object with all sorts of info.  No way to get a smaller more refined object just for posts (eg. title, body, picture, date)?

答:
As I told you in the comments, you need to add to the url you're calling all these parameters like the limit or the fields you want.

So it should be like

```<code>$response = $this->fb->get(
    '/'.$page_id.'/posts?fields=id,title,created_time&limit=5',
    $access_token
 );
</code>```

If you want to know which fields are available, you can use the documentation but this list may not be accurate based on which API version your using. Another way is to inspect the object before specifying the fields.

Title: Facebook PHP SDK 4 - get last 5 posts

Body:
I am trying to get the last five posts.  I have created the following:

try {
    // Returns a `Facebook\FacebookResponse` object
    $response = $this->fb->get(
    '/'.$page_id.'/posts',
    $access_token
    );

} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$graphNode = $response->getGraphEdge();
echo "
";
print_r($graphNode);
echo "
";
exit;

How can I limit the output?  For example, instead of 100 records being returned, I only want 5.  I know I need to use 'limit=5' but don't know where in above to place it.

Also, with the above script, I get a massive Facebook\GraphNodes\GraphEdge Object with all sorts of info.  No way to get a smaller more refined object just for posts (eg. title, body, picture, date)?

Body:
As I told you in the comments, you need to add to the url you're calling all these parameters like the limit or the fields you want.

So it should be like

$response = $this->fb->get(
    '/'.$page_id.'/posts?fields=id,title,created_time&amp;limit=5',
    $access_token
 );

If you want to know which fields are available, you can use the documentation but this list may not be accurate based on which API version your using. Another way is to inspect the object before specifying the fields.


问:
Datepicker: How to popup datepicker when click on edittext
I want to show datepicker popup window. I have found some examples but i am not getting it properly. I have one edittext and i want that when i click on edittext the datepicker dialog should popup and after setting the date, the date should show in edittext in dd/mm/yyyy format. PLease provide me sample code or good links.</p>

答:
USe this

```<code>your_edittext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {

                    final Calendar calendar = Calendar.getInstance();
                    int yy = calendar.get(Calendar.YEAR);
                    int mm = calendar.get(Calendar.MONTH);
                    int dd = calendar.get(Calendar.DAY_OF_MONTH);
                    DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear+1)
                                    + "/" + String.valueOf(year);
                            your_edittext.setText(date);
                        }
                    }, yy, mm, dd);
                    datePicker.show();
                }
            });
</code>```

Body:
USe this

your_edittext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {

                    final Calendar calendar = Calendar.getInstance();
                    int yy = calendar.get(Calendar.YEAR);
                    int mm = calendar.get(Calendar.MONTH);
                    int dd = calendar.get(Calendar.DAY_OF_MONTH);
                    DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear+1)
                                    + "/" + String.valueOf(year);
                            your_edittext.setText(date);
                        }
                    }, yy, mm, dd);
                    datePicker.show();
                }
            });


问:
Angular 5 uglifying build returns error
I updated my SPA from Angular 4 to Angular 5 with all dependencies. Works so far so good. The dev and prod builds work very well. No errors or warnings.

When I build the SPA with --prod flag, angular-cli uglifies the build. No errors from angular-cli. But when I open my SPA in my browser, I have an error and nothing happens. The page doesn't load at all (only loading spinner).

```<code>Uncaught Error: Unexpected value 'Ie' imported by the module 't'. Please add a @NgModule annotation.
at c (compiler.js:466)
at compiler.js:15088
at Array.forEach (<anonymous>)
at t.getNgModuleMetadata (compiler.js:15071)
at t.getNgModuleSummary (compiler.js:14998)
at compiler.js:15086
at Array.forEach (<anonymous>)
at t.getNgModuleMetadata (compiler.js:15071)
at t._loadModules (compiler.js:33486)
at t._compileModuleAndComponents (compiler.js:33447)
</code>```

Here is my package.json with all dependencies and my build script:

```<code>{
    "name": "broadcast-manager",
    "version": "0.1.0",
    "license": "MIT",
    "scripts": {
        "ng": "ng",
        "dev": "ng serve --dev --environment main --port 1337 --host 0.0.0.0 --proxy-config proxy.conf.json",
        "prod": "ng build --prod --environment main --aot false"
    },
    "private": true,
    "dependencies": {
        "@angular/animations": "^5.0.1",
        "@angular/cli": "^1.5.0",
        "@angular/common": "^5.0.1",
        "@angular/compiler": "^5.0.1",
        "@angular/compiler-cli": "^5.0.1",
        "@angular/core": "^5.0.1",
        "@angular/forms": "^5.0.1",
        "@angular/http": "^5.0.1",
        "@angular/platform-browser": "^5.0.1",
        "@angular/platform-browser-dynamic": "^5.0.1",
        "@angular/router": "^5.0.1",
        "@swimlane/ngx-charts": "^6.1.0",
        "@swimlane/ngx-datatable": "^11.0.4",
        "@types/jwt-decode": "^2.2.1",
        "@types/node": "^8.0.53",
        "bootstrap": "4.0.0-alpha.6",
        "codelyzer": "^4.0.1",
        "core-js": "^2.5.1",
        "d3": "^4.11.0",
        "jwt-decode": "2.2.0",
        "moment": "^2.19.2",
        "ng2-dnd": "^4.2.0",
        "ngx-bootstrap": "^2.0.0-beta.8",
        "ngx-chips": "^1.5.9",
        "node-sass": "^4.6.1",
        "protractor": "^5.2.0",
        "rxjs": "^5.5.2",
        "ts-node": "^3.3.0",
        "tslint": "^5.8.0",
        "typescript": "^2.6.1",
        "zone.js": "^0.8.18"
    },
    "devDependencies": {}
}
</code>```

And here is my .angular-cli.json

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "broadcast"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "../public/frontend",
      "assets": [
        "assets",
        ".htaccess",
        "favicon.ico",
        {
  "glob": "**/*",
  "input": "../node_modules/font-awesome/fonts/",
  "output": "./assets/fonts/"
}
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "prefix": "bm-",
      "environmentSource": "environments/environment.ts",
      "environments": {
        "main": "environments/environment.ts"
      }
    }
  ],
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    }
  ],
  "defaults": {
    "styleExt": "css",
    "component": {
    }
  },
  "warnings": {
    "typescriptMismatch": false
  }
}
</code>```

How can I debug what's happening/what's going wrong?

答:
I fixed the problem with following, easy solution, thanks to @Kevin RED.

Before:

```<code>"scripts": {
    "prod": "ng build --prod --aot false"
}
</code>```

After:

```<code>"scripts": {
    "prod": "ng build --prod --aot false --build-optimizer=false"
}
</code>```

I'm not sure right now what the functionality of build-optimizer is (npmjs-build-optimizer), but if I set it to true, I receive an error. Set on false and it works.

Title: Angular 5 uglifying build returns error

Body:
I updated my SPA from Angular 4 to Angular 5 with all dependencies. Works so far so good. The dev and prod builds work very well. No errors or warnings.

When I build the SPA with --prod flag, angular-cli uglifies the build. No errors from angular-cli. But when I open my SPA in my browser, I have an error and nothing happens. The page doesn't load at all (only loading spinner).

Uncaught Error: Unexpected value 'Ie' imported by the module 't'. Please add a @NgModule annotation.
at c (compiler.js:466)
at compiler.js:15088
at Array.forEach (<anonymous>)
at t.getNgModuleMetadata (compiler.js:15071)
at t.getNgModuleSummary (compiler.js:14998)
at compiler.js:15086
at Array.forEach (<anonymous>)
at t.getNgModuleMetadata (compiler.js:15071)
at t._loadModules (compiler.js:33486)
at t._compileModuleAndComponents (compiler.js:33447)

Here is my package.json with all dependencies and my build script:

{
    "name": "broadcast-manager",
    "version": "0.1.0",
    "license": "MIT",
    "scripts": {
        "ng": "ng",
        "dev": "ng serve --dev --environment main --port 1337 --host 0.0.0.0 --proxy-config proxy.conf.json",
        "prod": "ng build --prod --environment main --aot false"
    },
    "private": true,
    "dependencies": {
        "@angular/animations": "^5.0.1",
        "@angular/cli": "^1.5.0",
        "@angular/common": "^5.0.1",
        "@angular/compiler": "^5.0.1",
        "@angular/compiler-cli": "^5.0.1",
        "@angular/core": "^5.0.1",
        "@angular/forms": "^5.0.1",
        "@angular/http": "^5.0.1",
        "@angular/platform-browser": "^5.0.1",
        "@angular/platform-browser-dynamic": "^5.0.1",
        "@angular/router": "^5.0.1",
        "@swimlane/ngx-charts": "^6.1.0",
        "@swimlane/ngx-datatable": "^11.0.4",
        "@types/jwt-decode": "^2.2.1",
        "@types/node": "^8.0.53",
        "bootstrap": "4.0.0-alpha.6",
        "codelyzer": "^4.0.1",
        "core-js": "^2.5.1",
        "d3": "^4.11.0",
        "jwt-decode": "2.2.0",
        "moment": "^2.19.2",
        "ng2-dnd": "^4.2.0",
        "ngx-bootstrap": "^2.0.0-beta.8",
        "ngx-chips": "^1.5.9",
        "node-sass": "^4.6.1",
        "protractor": "^5.2.0",
        "rxjs": "^5.5.2",
        "ts-node": "^3.3.0",
        "tslint": "^5.8.0",
        "typescript": "^2.6.1",
        "zone.js": "^0.8.18"
    },
    "devDependencies": {}
}

And here is my .angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "broadcast"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "../public/frontend",
      "assets": [
        "assets",
        ".htaccess",
        "favicon.ico",
        {
  "glob": "**/*",
  "input": "../node_modules/font-awesome/fonts/",
  "output": "./assets/fonts/"
}
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "prefix": "bm-",
      "environmentSource": "environments/environment.ts",
      "environments": {
        "main": "environments/environment.ts"
      }
    }
  ],
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    }
  ],
  "defaults": {
    "styleExt": "css",
    "component": {
    }
  },
  "warnings": {
    "typescriptMismatch": false
  }
}

How can I debug what's happening/what's going wrong?

Body:
I fixed the problem with following, easy solution, thanks to @Kevin RED.

Before:

"scripts": {
    "prod": "ng build --prod --aot false"
}

After:

"scripts": {
    "prod": "ng build --prod --aot false --build-optimizer=false"
}

I'm not sure right now what the functionality of build-optimizer is (npmjs-build-optimizer), but if I set it to true, I receive an error. Set on false and it works.