问:
JEMETER Non-GUI : missing class com.thoughtworks.xstream.converters.ConversionException error
I am creating a JMeter test plan from scratch.
Here is my code:

```<code>public static void main(String[] args) throws Exception {

        StandardJMeterEngine jmeterEngine = new StandardJMeterEngine();
        JMeterUtils.setJMeterHome("/Users/myDir/Documents/JMeter/apache-jmeter-3.3");
        JMeterUtils.loadJMeterProperties("src/main/resources/jmeter.properties");
        JMeterUtils.initLocale();

        //create test plan
        TestPlan testPlan = new TestPlan();
        testPlan.setEnabled(true);
        testPlan.setName("Test Plan");

        //create thread group
        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setNumThreads(1);
        threadGroup.setRampUp(1);

        // create http sampler
        HTTPSampler httpSampler = new HTTPSampler();
        httpSampler.setProtocol("https");
        httpSampler.setDomain("myDomain.services.company.com");
        httpSampler.setPath("ims/login/v1/token");
        httpSampler.setMethod("POST");
        httpSampler.setFollowRedirects(true);
        httpSampler.setAutoRedirects(false);
        httpSampler.setUseKeepAlive(true);
        httpSampler.addArgument("client_id", "argValue1");
        httpSampler.addArgument("scope", "argValue2");
        httpSampler.addArgument("userName", "abc%2B249%40gmail.com");
        httpSampler.addArgument("password", "Abc123");

        //Add sampler to the thread group
        threadGroup.addTestElement(httpSampler);

        HashTree testPlanHashTree = new HashTree();
        testPlanHashTree.add(testPlan);
        testPlanHashTree.add(threadGroup);

        // Generating the JMX file
        SaveService.saveTree(testPlanHashTree, new FileOutputStream(JMeterUtils.getJMeterHome() + "/bin/Test2.jmx"));
    }
</code>```

When I execute this code my Test2.jmx is created.

Next I try to run Test2.jmx through non-GUI mode of Jmeter by using the following command:

./jmeter.sh -n -t Test2.jmx

Instead of running  my test plan Jmeter throws the following error:

```<code>Error in NonGUIDriver java.lang.IllegalArgumentException: Problem loading XML from:'/Users/chandrat/Documents/JMeter/apache-jmeter-3.3/bin/Test2.jmx', missing class com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       :
first-jmeter-class  : org.apache.jmeter.save.converters.HashTreeConverter.unmarshal(HashTreeConverter.java:67)
class               : org.apache.jmeter.save.ScriptWrapper
required-type       : org.apache.jmeter.threads.ThreadGroup
converter-type      : org.apache.jmeter.save.ScriptWrapperConverter
path                : /jmeterTestPlan/org.apache.jorphan.collections.HashTree/org.apache.jorphan.collections.HashTree/ThreadGroup
line number         : 6
version             : 3.3 r1808647
-------------------------------
</code>```

1) I am not sure how to resolve this? Cause-message is blank? What should I do so that my test plan gets executed without the error above?

2) Can you also take a look at my test plan generation code? Is that code right? Should the testGroup be added directly to the tree or to the test plan first and then the test plan should be added to the tree?

Here are the dependencies from my pom file, in case I am missing a jar.

```<code>  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_core</artifactId>
        <version>3.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>jorphan</artifactId>
        <version>3.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_http</artifactId>
        <version>3.3</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.7</version>
    </dependency>
    <dependency>
        <groupId>oro</groupId>
        <artifactId>oro</artifactId>
        <version>2.0.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avalon.framework</groupId>
        <artifactId>avalon-framework-api</artifactId>
        <version>4.3.1</version>
    </dependency>
  </dependencies>
</code>```

Please help. Thanks!

答:
In order to be able to open the generated test plan in JMeter GUI you need to define a little bit more properties, amend your code to look like:

```<code>public static void main(String[] args) throws Exception {

    StandardJMeterEngine jmeterEngine = new StandardJMeterEngine();
    JMeterUtils.setJMeterHome("/Users/myDir/Documents/JMeter/apache-jmeter-3.3");
    JMeterUtils.loadJMeterProperties("src/main/resources/jmeter.properties");
    JMeterUtils.initLocale();

    //create test plan
    TestPlan testPlan = new TestPlan();
    testPlan.setEnabled(true);
    testPlan.setName("Test Plan");
    testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
    testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
    testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

    LoopController loopController = new LoopController();
    loopController.setLoops(1);
    loopController.setFirst(true);
    loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
    loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
    loopController.initialize();

    //create thread group
    ThreadGroup threadGroup = new ThreadGroup();
    threadGroup.setNumThreads(1);
    threadGroup.setRampUp(1);
    threadGroup.setSamplerController(loopController);
    threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
    threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());

    // create http sampler
    HTTPSampler httpSampler = new HTTPSampler();
    httpSampler.setProtocol("https");
    httpSampler.setDomain("myDomain.services.company.com");
    httpSampler.setPath("ims/login/v1/token");
    httpSampler.setMethod("POST");
    httpSampler.setFollowRedirects(true);
    httpSampler.setAutoRedirects(false);
    httpSampler.setUseKeepAlive(true);
    httpSampler.addArgument("client_id", "argValue1");
    httpSampler.addArgument("scope", "argValue2");
    httpSampler.addArgument("userName", "abc%2B249%40gmail.com");
    httpSampler.addArgument("password", "Abc123");
    httpSampler.setProperty(TestElement.TEST_CLASS, HTTPSampler.class.getName());
    httpSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

    //Add sampler to the thread group

    HashTree testPlanHashTree = new HashTree();
    HashTree threadGroupHashTree = testPlanHashTree.add(testPlan, threadGroup);
    threadGroupHashTree.add(httpSampler);

    // Generating the JMX file
    SaveService.saveTree(testPlanHashTree, new FileOutputStream(JMeterUtils.getJMeterHome() + "/bin/Test2.jmx"));
}
</code>```

References:

JMeter API

Five Ways To Launch a JMeter Test without Using the JMeter GUI

jmeter-from-code example project

Body:
I am creating a JMeter test plan from scratch.
Here is my code:

public static void main(String[] args) throws Exception {

        StandardJMeterEngine jmeterEngine = new StandardJMeterEngine();
        JMeterUtils.setJMeterHome("/Users/myDir/Documents/JMeter/apache-jmeter-3.3");
        JMeterUtils.loadJMeterProperties("src/main/resources/jmeter.properties");
        JMeterUtils.initLocale();

        //create test plan
        TestPlan testPlan = new TestPlan();
        testPlan.setEnabled(true);
        testPlan.setName("Test Plan");

        //create thread group
        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setNumThreads(1);
        threadGroup.setRampUp(1);

        // create http sampler
        HTTPSampler httpSampler = new HTTPSampler();
        httpSampler.setProtocol("https");
        httpSampler.setDomain("myDomain.services.company.com");
        httpSampler.setPath("ims/login/v1/token");
        httpSampler.setMethod("POST");
        httpSampler.setFollowRedirects(true);
        httpSampler.setAutoRedirects(false);
        httpSampler.setUseKeepAlive(true);
        httpSampler.addArgument("client_id", "argValue1");
        httpSampler.addArgument("scope", "argValue2");
        httpSampler.addArgument("userName", "abc%2B249%40gmail.com");
        httpSampler.addArgument("password", "Abc123");

        //Add sampler to the thread group
        threadGroup.addTestElement(httpSampler);

        HashTree testPlanHashTree = new HashTree();
        testPlanHashTree.add(testPlan);
        testPlanHashTree.add(threadGroup);

        // Generating the JMX file
        SaveService.saveTree(testPlanHashTree, new FileOutputStream(JMeterUtils.getJMeterHome() + "/bin/Test2.jmx"));
    }

When I execute this code my Test2.jmx is created.

Next I try to run Test2.jmx through non-GUI mode of Jmeter by using the following command:

./jmeter.sh -n -t Test2.jmx

Instead of running  my test plan Jmeter throws the following error:

Error in NonGUIDriver java.lang.IllegalArgumentException: Problem loading XML from:'/Users/chandrat/Documents/JMeter/apache-jmeter-3.3/bin/Test2.jmx', missing class com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       :
first-jmeter-class  : org.apache.jmeter.save.converters.HashTreeConverter.unmarshal(HashTreeConverter.java:67)
class               : org.apache.jmeter.save.ScriptWrapper
required-type       : org.apache.jmeter.threads.ThreadGroup
converter-type      : org.apache.jmeter.save.ScriptWrapperConverter
path                : /jmeterTestPlan/org.apache.jorphan.collections.HashTree/org.apache.jorphan.collections.HashTree/ThreadGroup
line number         : 6
version             : 3.3 r1808647
-------------------------------

1) I am not sure how to resolve this? Cause-message is blank? What should I do so that my test plan gets executed without the error above?

2) Can you also take a look at my test plan generation code? Is that code right? Should the testGroup be added directly to the tree or to the test plan first and then the test plan should be added to the tree?

Here are the dependencies from my pom file, in case I am missing a jar.

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_core</artifactId>
        <version>3.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>jorphan</artifactId>
        <version>3.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_http</artifactId>
        <version>3.3</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.7</version>
    </dependency>
    <dependency>
        <groupId>oro</groupId>
        <artifactId>oro</artifactId>
        <version>2.0.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avalon.framework</groupId>
        <artifactId>avalon-framework-api</artifactId>
        <version>4.3.1</version>
    </dependency>
  </dependencies>

Please help. Thanks!

Body:
In order to be able to open the generated test plan in JMeter GUI you need to define a little bit more properties, amend your code to look like:

public static void main(String[] args) throws Exception {

    StandardJMeterEngine jmeterEngine = new StandardJMeterEngine();
    JMeterUtils.setJMeterHome("/Users/myDir/Documents/JMeter/apache-jmeter-3.3");
    JMeterUtils.loadJMeterProperties("src/main/resources/jmeter.properties");
    JMeterUtils.initLocale();

    //create test plan
    TestPlan testPlan = new TestPlan();
    testPlan.setEnabled(true);
    testPlan.setName("Test Plan");
    testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
    testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
    testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

    LoopController loopController = new LoopController();
    loopController.setLoops(1);
    loopController.setFirst(true);
    loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
    loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
    loopController.initialize();

    //create thread group
    ThreadGroup threadGroup = new ThreadGroup();
    threadGroup.setNumThreads(1);
    threadGroup.setRampUp(1);
    threadGroup.setSamplerController(loopController);
    threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
    threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());

    // create http sampler
    HTTPSampler httpSampler = new HTTPSampler();
    httpSampler.setProtocol("https");
    httpSampler.setDomain("myDomain.services.company.com");
    httpSampler.setPath("ims/login/v1/token");
    httpSampler.setMethod("POST");
    httpSampler.setFollowRedirects(true);
    httpSampler.setAutoRedirects(false);
    httpSampler.setUseKeepAlive(true);
    httpSampler.addArgument("client_id", "argValue1");
    httpSampler.addArgument("scope", "argValue2");
    httpSampler.addArgument("userName", "abc%2B249%40gmail.com");
    httpSampler.addArgument("password", "Abc123");
    httpSampler.setProperty(TestElement.TEST_CLASS, HTTPSampler.class.getName());
    httpSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

    //Add sampler to the thread group

    HashTree testPlanHashTree = new HashTree();
    HashTree threadGroupHashTree = testPlanHashTree.add(testPlan, threadGroup);
    threadGroupHashTree.add(httpSampler);

    // Generating the JMX file
    SaveService.saveTree(testPlanHashTree, new FileOutputStream(JMeterUtils.getJMeterHome() + "/bin/Test2.jmx"));
}

References:

JMeter API

Five Ways To Launch a JMeter Test without Using the JMeter GUI

jmeter-from-code example project


来源: stackexchange

问:
Redirect stdout and stderr to file permanently but keep printing them
By doing the following(1):

```<code> exec >> log_file
 exec 2>&1
 ls
</code>```

stdout and stderr is permanently redirected for the next commands but not anymore displayed on terminal. Here, ls output will be in log_file but not displayed in terminal

By doing the following(2):

```<code>command | tee log_file
</code>```

command output will be both in log_file and printed on terminal but this will work only for command and not for the next commands as method 1.

How to redirect permanently stdout and stderr output in a file for a given terminal like method 1 and, keep stdout and stderr printed on the terminal instance like method 2 ?

答:
Using tee and redirection combined:

```<code>(exec 2>&1) | tee file.txt
</code>```

Here's an example

```<code>[root@box ~]# (ll 2>&1) | tee tmp.txt
total 4
-rw-------. 1 root root 1007 Apr 26  2017 anaconda-ks.cfg
[root@box ~]# cat tmp.txt
total 4
-rw-------. 1 root root 1007 Apr 26  2017 anaconda-ks.cfg
</code>```

The reason the command is inside paranthesis is to keep the order of the prints, since stdout is buffered. It causes the ll command to be executed in a subshell, and then return the output of stdout + stderr in-order.

ContentLicense: CC BY-SA 3.0

Body:
By doing the following(1):

 exec >> log_file
 exec 2>&1
 ls

stdout and stderr is permanently redirected for the next commands but not anymore displayed on terminal. Here, ls output will be in log_file but not displayed in terminal

By doing the following(2):

command | tee log_file

command output will be both in log_file and printed on terminal but this will work only for command and not for the next commands as method 1.

How to redirect permanently stdout and stderr output in a file for a given terminal like method 1 and, keep stdout and stderr printed on the terminal instance like method 2 ?

Body:
Using tee and redirection combined:

(exec 2>&1) | tee file.txt

Here's an example

[root@box ~]# (ll 2>&1) | tee tmp.txt
total 4
-rw-------. 1 root root 1007 Apr 26  2017 anaconda-ks.cfg
[root@box ~]# cat tmp.txt
total 4
-rw-------. 1 root root 1007 Apr 26  2017 anaconda-ks.cfg

The reason the command is inside paranthesis is to keep the order of the prints, since stdout is buffered. It causes the ll command to be executed in a subshell, and then return the output of stdout + stderr in-order.


问:
How to fetch data without duplicating products after adding price and stocks
I have a problem in adding price, size and stocks. How can I add price, stocks and size without duplicating?

Here is my database structure:

tblproduct

tblextension

PS: tblproduct product_id and tblproduct_extension product_id are the same.

Here is the result after I add price, stocks and price. As you can see there are two 'Nike Lebron 15 Ghost'.

query

```<code>SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id;
</code>```

ajax

```<code>//Show modal for adding size, price and stocks
function add_product_extension() {
    $('#product_add_extension').click(function(e){
        var product_id = $('#product_id').val();
        var product_price = $('#product_price').val();
        var product_stocks = $('#product_stocks').val();
        var product_size = $('#product_size').val();
        $.ajax({
            type: 'POST',
            url: '../admin/class.php',
            data: {product_id:product_id,product_price:product_price,product_stocks:product_stocks,product_size:product_size},
            success:function(data) {
                $('#addSize').modal('hide');
            }
        });
    });
}
</code>```

class.php

```<code>    //Add size, price, stocks
    if(isset($_POST['product_id'])) {
        $product_price = $_POST['product_price'];
        $product_stocks = $_POST['product_stocks'];
        $product_size = $_POST['product_size'];
        $product_id = $_POST['product_id'];

        $insert_query = "INSERT INTO tblproduct_extension (product_stocks, product_price, product_size, product_id)VALUES('$product_stocks', '$product_price', '$product_size', '$product_id')";
        $query = mysqli_query($db_conn, $insert_query);
    }
</code>```

Code to display products

```<code>    //Get Products by ID
    function get_products() {
        GLOBAL $db_conn;
        $id = $_GET['id'];
        $search_query= "SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id WHERE tblproduct.segment_id='$id'";
        $query = mysqli_query($db_conn, $search_query);

        while ($row = mysqli_fetch_array($query)) {
            ?>
                <div class="products">
                    <a href="details.php?view_product=<?=$row['product_id']?>&id=<?=$row['segment_id']?>"><img class="img_product" src="../admin/<?=$row['product_image']?>" alt="<?=$row['product_name']?>"></a>
                    <?php if($row['product_stocks'] == 0) {?>
                        <span class="stock-label">SOLD OUT</span>
                    <?php } ?>
                    <h4><?=$row['product_name']?></h4>
                    <h3>₱<?=number_format($row['product_price'], 2)?></h3>
                </div>
            <?php
        }
        return $row;
    }
</code>```

答:
```<code>$search_query= "SELECT DISTINCT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id WHERE tblproduct.segment_id='$id'";
</code>```

The SELECT DISTINCT statement is used to return only distinct (different) values.

If you don't want duplicates you can trim them from your query.

Body:
I have a problem in adding price, size and stocks. How can I add price, stocks and size without duplicating?

Here is my database structure:

tblproduct

tblextension

PS: tblproduct product_id and tblproduct_extension product_id are the same.

Here is the result after I add price, stocks and price. As you can see there are two 'Nike Lebron 15 Ghost'.

query

SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id;

ajax

//Show modal for adding size, price and stocks
function add_product_extension() {
    $('#product_add_extension').click(function(e){
        var product_id = $('#product_id').val();
        var product_price = $('#product_price').val();
        var product_stocks = $('#product_stocks').val();
        var product_size = $('#product_size').val();
        $.ajax({
            type: 'POST',
            url: '../admin/class.php',
            data: {product_id:product_id,product_price:product_price,product_stocks:product_stocks,product_size:product_size},
            success:function(data) {
                $('#addSize').modal('hide');
            }
        });
    });
}

class.php

    //Add size, price, stocks
    if(isset($_POST['product_id'])) {
        $product_price = $_POST['product_price'];
        $product_stocks = $_POST['product_stocks'];
        $product_size = $_POST['product_size'];
        $product_id = $_POST['product_id'];

        $insert_query = "INSERT INTO tblproduct_extension (product_stocks, product_price, product_size, product_id)VALUES('$product_stocks', '$product_price', '$product_size', '$product_id')";
        $query = mysqli_query($db_conn, $insert_query);
    }

Code to display products

    //Get Products by ID
    function get_products() {
        GLOBAL $db_conn;
        $id = $_GET['id'];
        $search_query= "SELECT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id WHERE tblproduct.segment_id='$id'";
        $query = mysqli_query($db_conn, $search_query);

        while ($row = mysqli_fetch_array($query)) {
            ?>

                    <a href="details.php?view_product=<?=$row['product_id']?>&id=<?=$row['segment_id']?>"><img class="img_product" src="../admin/<?=$row['product_image']?>" alt="<?=$row['product_name']?>">
                    <?php if($row['product_stocks'] == 0) {?>
                        SOLD OUT
                    <?php } ?>

<?=$row['product_name']?>

₱<?=number_format($row['product_price'], 2)?>

            <?php
        }
        return $row;
    }

Body:
$search_query= "SELECT DISTINCT * FROM tblproduct LEFT JOIN tblproduct_extension ON tblproduct_extension.product_id = tblproduct.product_id WHERE tblproduct.segment_id='$id'";

The SELECT DISTINCT statement is used to return only distinct (different) values.

If you don't want duplicates you can trim them from your query.


问:
How to format the content of a Java Properties object when using a Stream?
The static method System.getProperties() returns a Properties object containing the System Properties as key-value pairs.

In the SO post How would I print the JVM's system properties using Java 8 and lambdas? Radiodef provided a solution which works fine, and it can be enhanced to also sort the output:

```<code>        System.getProperties()
                .entrySet()
                .stream()
                .map(e -> e.getKey() + ": " + e.getValue())
                .sorted()
                .forEach(System.out::println);
</code>```

Here is a small portion of the sorted output produced by that statement:

I tried unsucessfully to amend the statement above so that the property values in the output are left-aligned. Since java.vm.specification.version happens to be the longest System Properties key, the formatted presentation of the output shown above should look like this:

Obviously the tricky part is to somehow know the length of the longest key prior to formatting the output. Any suggestions on how to achieve this in a single statement using a Stream, or is it impossible?

Update:

I forgot to state in the original post that an additional constraint is that the solution should also work using a parallel stream. My apologies for the oversight.

答:
Just separate the steps.

Determine the maximum key length

Format all entries using the length

E.g.

```<code>int maxLen = System.getProperties().keySet()
    .stream().mapToInt(k -> ((String)k).length()).max().orElse(0);
String format = "%-"+maxLen+"s %s%n";
System.getProperties().forEach((k,v)->System.out.printf(format, k+":", v));
</code>```

Note that this also prints the colon left-aligned, as in your example output. When you want to sort this map and/or ensure that there is no modification between these two operations, you may use

```<code>@SuppressWarnings("unchecked") Map<String,String> map
                                   = new HashMap<>((Map)System.getProperties());
int maxLen = map.keySet().stream().mapToInt(String::length).max().orElse(0);
String format = "%-"+maxLen+"s %s%n";
map.entrySet().stream()
   .sorted(Map.Entry.comparingByKey())
   .forEach(e -> System.out.printf(format, e.getKey()+":", e.getValue()));
</code>```

It’s worth noting that all other solution are just using different tricks to hide the fact that there are at least two processing steps.

Stream.sort is a stateful intermediate operation. It will buffer the entire stream contents, then sort the buffer and only after that proceed with the downstream operation. This answer relies on the peek following the first sort operation to see the maximum before all other values, which isn’t even a guaranteed property. Whereas this answer does it the other way round, relies on peek having seen all values, before the subsequent sorted step passes any elements to the terminal operation.

Another, Collector based answer did two steps in one, calculating the maximum key length and accumulating all entries into a new map, but the printing of the formatted output still could only be done after the completion of the entire collect operation.

It is impossible to do this in one step, but if all you want, is to hide the fact that there are two steps, by letting the operation look like one statement, you can do this with the above solution as well:

```<code>((Map<String,String>)(Map)System.getProperties()).entrySet().stream()
   .collect(collectingAndThen(toMap(Map.Entry::getKey,Map.Entry::getValue), map -> {
        int maxLen = map.keySet().stream().mapToInt(String::length).max().orElse(0);
        String format = "%-"+maxLen+"s %s%n";
        map.entrySet().stream()
           .sorted(Map.Entry.comparingByKey())
           .forEach(e -> System.out.printf(format, e.getKey()+":", e.getValue()));
        return null;
   }));
</code>```

Body:
The static method System.getProperties() returns a Properties object containing the System Properties as key-value pairs.

In the SO post How would I print the JVM's system properties using Java 8 and lambdas? Radiodef provided a solution which works fine, and it can be enhanced to also sort the output:

        System.getProperties()
                .entrySet()
                .stream()
                .map(e -> e.getKey() + ": " + e.getValue())
                .sorted()
                .forEach(System.out::println);

Here is a small portion of the sorted output produced by that statement:

I tried unsucessfully to amend the statement above so that the property values in the output are left-aligned. Since java.vm.specification.version happens to be the longest System Properties key, the formatted presentation of the output shown above should look like this:

Obviously the tricky part is to somehow know the length of the longest key prior to formatting the output. Any suggestions on how to achieve this in a single statement using a Stream, or is it impossible?

Update:

I forgot to state in the original post that an additional constraint is that the solution should also work using a parallel stream. My apologies for the oversight.

Body:
Just separate the steps.

Determine the maximum key length

Format all entries using the length

E.g.

int maxLen = System.getProperties().keySet()
    .stream().mapToInt(k -> ((String)k).length()).max().orElse(0);
String format = "%-"+maxLen+"s %s%n";
System.getProperties().forEach((k,v)->System.out.printf(format, k+":", v));

Note that this also prints the colon left-aligned, as in your example output. When you want to sort this map and/or ensure that there is no modification between these two operations, you may use

@SuppressWarnings("unchecked") Map<String,String> map
                                   = new HashMap<>((Map)System.getProperties());
int maxLen = map.keySet().stream().mapToInt(String::length).max().orElse(0);
String format = "%-"+maxLen+"s %s%n";
map.entrySet().stream()
   .sorted(Map.Entry.comparingByKey())
   .forEach(e -> System.out.printf(format, e.getKey()+":", e.getValue()));

It’s worth noting that all other solution are just using different tricks to hide the fact that there are at least two processing steps.

Stream.sort is a stateful intermediate operation. It will buffer the entire stream contents, then sort the buffer and only after that proceed with the downstream operation. This answer relies on the peek following the first sort operation to see the maximum before all other values, which isn’t even a guaranteed property. Whereas this answer does it the other way round, relies on peek having seen all values, before the subsequent sorted step passes any elements to the terminal operation.

Another, Collector based answer did two steps in one, calculating the maximum key length and accumulating all entries into a new map, but the printing of the formatted output still could only be done after the completion of the entire collect operation.

It is impossible to do this in one step, but if all you want, is to hide the fact that there are two steps, by letting the operation look like one statement, you can do this with the above solution as well:

((Map<String,String>)(Map)System.getProperties()).entrySet().stream()
   .collect(collectingAndThen(toMap(Map.Entry::getKey,Map.Entry::getValue), map -> {
        int maxLen = map.keySet().stream().mapToInt(String::length).max().orElse(0);
        String format = "%-"+maxLen+"s %s%n";
        map.entrySet().stream()
           .sorted(Map.Entry.comparingByKey())
           .forEach(e -> System.out.printf(format, e.getKey()+":", e.getValue()));
        return null;
   }));


问:
How many times the last statement of a recursive function block gets executed?
Consider the below code snippet demonstrating recursion :

```<code><?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 10) {
      test();
    }
    echo "Count Value : ".$count--;
  }

  test();
?>
</code>```

Output of above code is as below :

```<code>1
2
3
4
5
6
7
8
9
10
Count Value : 10
Count Value : 9
Count Value : 8
Count Value : 7
Count Value : 6
Count Value : 5
Count Value : 4
Count Value : 3
Count Value : 2
Count Value : 1
</code>```

I expected the last code statement of the function test() i.e. echo "Count Value : ".$count--; will get execute only once when the if condition returns false upon $count = 10; and everything would be finish.

But unexpectedly, I'm getting it executed ten times with decreasing value of variable $count. I'm not understanding how it's happening? How is the code flow getting manipulated here unexpectedly?

As the recursive function call is made inside the if condition how can it get called subsequently for 10 more times even after failing the if condition?

Please explain me.

Note :  I haven't forgot to add else and I don't want it. Just explain why and how the last statement is getting executed only after printing nos. from 1 to 10 and only after the failing of if condition. When the if condition was returning true it was not getting executed. How?

答:
I think you forgot the else.

```<code><?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 10) {
      test(); // when this call is made, all the code bellow waits for it to return
    } else {
      echo "Count Value : ".$count--;
    }
  }

  test();
?>
</code>```

What happens is that every time you call test(), inside the if condition, the execution stops until the newly called test() returns. The test() function only returns when $count >= 10. which means that all hanging functions call will continue. What is a RECURSIVE Function in PHP?

Your code can be translated to something like this;

```<code><?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 10) {

      static $count = 1;

      $count++;
      echo $count."<br>";
      if($count < 10) {

        static $count = 2;

        $count++;
        echo $count."<br>";
        if($count < 10) {

          // ... the code repeats until the point when $count = 9

        } else {
          echo "Count Value : ".$count--;
        }

      } else {
        echo "Count Value : ".$count--;
      }

    } else {
      echo "Count Value : ".$count--;
    }
  }

  test();
?>
</code>```

Body:
Consider the below code snippet demonstrating recursion :

<?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."
";
    if($count < 10) {
      test();
    }
    echo "Count Value : ".$count--;
  }

  test();
?>

Output of above code is as below :

1
2
3
4
5
6
7
8
9
10
Count Value : 10
Count Value : 9
Count Value : 8
Count Value : 7
Count Value : 6
Count Value : 5
Count Value : 4
Count Value : 3
Count Value : 2
Count Value : 1

I expected the last code statement of the function test() i.e. echo "Count Value : ".$count--; will get execute only once when the if condition returns false upon $count = 10; and everything would be finish.

But unexpectedly, I'm getting it executed ten times with decreasing value of variable $count. I'm not understanding how it's happening? How is the code flow getting manipulated here unexpectedly?

As the recursive function call is made inside the if condition how can it get called subsequently for 10 more times even after failing the if condition?

Please explain me.

Note :  I haven't forgot to add else and I don't want it. Just explain why and how the last statement is getting executed only after printing nos. from 1 to 10 and only after the failing of if condition. When the if condition was returning true it was not getting executed. How?

Body:
I think you forgot the else.

<?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 10) {
      test(); // when this call is made, all the code bellow waits for it to return
    } else {
      echo "Count Value : ".$count--;
    }
  }

  test();
?>

What happens is that every time you call test(), inside the if condition, the execution stops until the newly called test() returns. The test() function only returns when $count >= 10. which means that all hanging functions call will continue. What is a RECURSIVE Function in PHP?

Your code can be translated to something like this;

<?php
  function test() {
    static $count = 0;

    $count++;
    echo $count."<br>";
    if($count < 10) {

      static $count = 1;

      $count++;
      echo $count."<br>";
      if($count < 10) {

        static $count = 2;

        $count++;
        echo $count."<br>";
        if($count < 10) {

          // ... the code repeats until the point when $count = 9

        } else {
          echo "Count Value : ".$count--;
        }

      } else {
        echo "Count Value : ".$count--;
      }

    } else {
      echo "Count Value : ".$count--;
    }
  }

  test();
?>


问:
Verification error after signing code in Qt bundle (CSSMERR_TP_NOT_TRUSTED, OSX)
I am trying to code-sign a desktop application binary for OSX Sierra with bought COMODO certificate.
I have a code-signing verification error CSSMERR_TP_NOT_TRUSTED at the end of the macdeployqt command run:

```<code>$ security unlock-keychain -p "$PASSWORD" /Users/user/Library/Keychains/login.keychain
$ ~/Qt5.8/5.8/clang_64/bin/macdeployqt app_name.app/ -codesign=(cat ~/keyid3) -verbose=4 -no-plugins # (1)
# (...)
Log: Finished codesigning  "app_name.app" with identity "118E862D88E30998B6C4BACB8ABCB1FBDEADBEEF"
ERROR: codesign verification error:
ERROR: "app_name.app: CSSMERR_TP_NOT_TRUSTED\nIn architecture: x86_64\n"
</code>```

The same happens when I try to use codesign utility directly on final bundle (I am giving the same certificate ID as the XCode does):

```<code>+ security unlock-keychain -p "$PASSWORD" /Users/user/Library/Keychains/login.keychain
+ export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
+ CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
+ /usr/bin/codesign --force --sign 118E862D88E30998B6C4BACB8ABCB1FBDEADBEEF --deep --timestamp=none '<build-path>/app_name'
+ /usr/bin/codesign --verify '<build-path>/app_name' -dv
Executable=<build-path>/app_name/Contents/MacOS/app_name
Identifier=$(PRODUCT_BUNDLE_IDENTIFIER)
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20100 size=19725 flags=0x0(none) hashes=611+3 location=embedded
Signature size=2359
Info.plist=not bound
TeamIdentifier=not set
Sealed Resources version=2 rules=13 files=2
Internal requirements count=1 size=104
+ /usr/bin/codesign --verify '<build-path>/app_name'
<build-path>/app_name: CSSMERR_TP_NOT_TRUSTED
In architecture: x86_64
+ spctl -a -v <build-path>/app_name
<build-path>/app_name/: CSSMERR_TP_NOT_TRUSTED
</code>```

Binary compiled and signed by XCode is accepted though by gatekeeper (I generate XCode project with CMake and then modify project properties to sign the binary - this however is not making a full bundle for me). I have used the same codesign command (copied from XCode's log) for signing.

I have already:

removed and imported the certificate,

allowed it to be used on all applications,

checked are the permissions system default,

checked for doubled certificates in the system.

I use qmake (Qt5.8) to create makefiles.
My bundle contents (after make, before macdeploy):

```<code>./Contents
./Contents/_CodeSignature
./Contents/_CodeSignature/CodeResources
./Contents/Info.plist
./Contents/MacOS
./Contents/MacOS/app_name
./Contents/PkgInfo
./Contents/Resources
./Contents/Resources/CS_icon.icns
./Contents/Resources/empty.lproj
</code>```

What should I do to make correct signed binary under OSX Sierra?

答:
Turned out the SSL reseller I was buying the certificate from has simply not updated his website, where he was claiming the certificate works with OSX. Perhaps it has until 10.9 release AFAIR.

The only way to code-sign and use the binaries on latest MacOSes is to buy proper, targeted certificate directly from Apple (e.g. the one targeted for IPhone/iOS will not work on MacOS and vice-versa).
I wish reseller's helpdesk would know about it before I had lost the time.

Body:
I am trying to code-sign a desktop application binary for OSX Sierra with bought COMODO certificate.
I have a code-signing verification error CSSMERR_TP_NOT_TRUSTED at the end of the macdeployqt command run:

$ security unlock-keychain -p "$PASSWORD" /Users/user/Library/Keychains/login.keychain
$ ~/Qt5.8/5.8/clang_64/bin/macdeployqt app_name.app/ -codesign=(cat ~/keyid3) -verbose=4 -no-plugins # (1)
# (...)
Log: Finished codesigning  "app_name.app" with identity "118E862D88E30998B6C4BACB8ABCB1FBDEADBEEF"
ERROR: codesign verification error:
ERROR: "app_name.app: CSSMERR_TP_NOT_TRUSTED\nIn architecture: x86_64\n"

The same happens when I try to use codesign utility directly on final bundle (I am giving the same certificate ID as the XCode does):

+ security unlock-keychain -p "$PASSWORD" /Users/user/Library/Keychains/login.keychain
+ export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
+ CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
+ /usr/bin/codesign --force --sign 118E862D88E30998B6C4BACB8ABCB1FBDEADBEEF --deep --timestamp=none '<build-path>/app_name'
+ /usr/bin/codesign --verify '<build-path>/app_name' -dv
Executable=<build-path>/app_name/Contents/MacOS/app_name
Identifier=$(PRODUCT_BUNDLE_IDENTIFIER)
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20100 size=19725 flags=0x0(none) hashes=611+3 location=embedded
Signature size=2359
Info.plist=not bound
TeamIdentifier=not set
Sealed Resources version=2 rules=13 files=2
Internal requirements count=1 size=104
+ /usr/bin/codesign --verify '<build-path>/app_name'
<build-path>/app_name: CSSMERR_TP_NOT_TRUSTED
In architecture: x86_64
+ spctl -a -v <build-path>/app_name
<build-path>/app_name/: CSSMERR_TP_NOT_TRUSTED

Binary compiled and signed by XCode is accepted though by gatekeeper (I generate XCode project with CMake and then modify project properties to sign the binary - this however is not making a full bundle for me). I have used the same codesign command (copied from XCode's log) for signing.

I have already:

removed and imported the certificate,

allowed it to be used on all applications,

checked are the permissions system default,

checked for doubled certificates in the system.

I use qmake (Qt5.8) to create makefiles.
My bundle contents (after make, before macdeploy):

./Contents
./Contents/_CodeSignature
./Contents/_CodeSignature/CodeResources
./Contents/Info.plist
./Contents/MacOS
./Contents/MacOS/app_name
./Contents/PkgInfo
./Contents/Resources
./Contents/Resources/CS_icon.icns
./Contents/Resources/empty.lproj

What should I do to make correct signed binary under OSX Sierra?


问:
Provided an image that is available locally already
I'm using React Native and Firebase in my app. And out of nowhere I just started recieving this error:

```<code>SyntaxError: Unexpected end of JSON input.
at doWrite(_stream_writable.js)
at Promise.resolve.then.then.then.catch.then.message
</code>```

and in my react packager it is pointing to this code:

```<code>    onProfilesChange = async (snap) => {
    var allProfilePromises = []
    snap.forEach((child) => {
      var profileId = child.val().profileId
      var alreadyAdded = this.state.profiles.some(x => x.id === profileId)

      if (alreadyAdded === false) {
        var profilePromise = this.registerOnProfileChanges(profileId)
        allProfilePromises.push(profilePromise)
      }
    })

    await Promise.all(allProfilePromises)

    var profileCount = snap.numChildren()
    this.setState({ profiles: this.state.profiles, loading: false, profileCount: profileCount })

    if (profileCount <= 0) {
      this.getUserName()
    }
  }
</code>```

which is being run when componentMount is called. Now the error is quite clear, but I don't know WHY it is being produced, nor how to get passed it. This code has worked for months without me changing anything to it.

Thank in advance.

答:
try clearing cache and restart the server...

```<code>cd android & gradlew clean & cd .. & rm -rf node_modules/ & npm cache clean --force & yarn install & react-native run-android
</code>```

you may want to use npm i instead of yarn install

Body:
I'm using React Native and Firebase in my app. And out of nowhere I just started recieving this error:

SyntaxError: Unexpected end of JSON input.
at doWrite(_stream_writable.js)
at Promise.resolve.then.then.then.catch.then.message

and in my react packager it is pointing to this code:

    onProfilesChange = async (snap) => {
    var allProfilePromises = []
    snap.forEach((child) => {
      var profileId = child.val().profileId
      var alreadyAdded = this.state.profiles.some(x => x.id === profileId)

      if (alreadyAdded === false) {
        var profilePromise = this.registerOnProfileChanges(profileId)
        allProfilePromises.push(profilePromise)
      }
    })

    await Promise.all(allProfilePromises)

    var profileCount = snap.numChildren()
    this.setState({ profiles: this.state.profiles, loading: false, profileCount: profileCount })

    if (profileCount <= 0) {
      this.getUserName()
    }
  }

which is being run when componentMount is called. Now the error is quite clear, but I don't know WHY it is being produced, nor how to get passed it. This code has worked for months without me changing anything to it.

Thank in advance.

Body:
try clearing cache and restart the server...

cd android & gradlew clean & cd .. & rm -rf node_modules/ & npm cache clean --force & yarn install & react-native run-android

you may want to use npm i instead of yarn install


问:
webpack-dev-server --open to a specific path?
how do I motivate webpack-dev-server, when started with the --open flag, to open my publicPath?

Currently it opens up a browser tab to http://localhost:3000, but I want it to directly open http://localhost:3000/app, which is my defined public path.

When I manually type http://localhost:3000/app after start up of webpack-dev-server, it works as expected.

Here is my webpack.config.js which works great so far:

```<code>const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

module.exports = {

  entry: {
    vendor: [
      'jquery',
      'angular'
    ],
    app: './src/app/index.module.js',
    libs: [
      './src/libs/pagination/dirPagination.js',
      './src/libs/sc-date-time/sc-date-time.js',
      './src/libs/msd-elastic.js',
      './src/libs/ng-textcomplete.js',
      './src/libs/highcharts/highslide-full.js',
      './src/libs/highcharts/Sankey.js'
    ]
  },

  output: {
    filename: '[name].bundle.js',
    chunkFilename: '[id].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/app/'
  },

  devtool: 'inline-source-map',

  devServer: {
    contentBase: './dist',
    host: 'localhost',
    port: '3000',
    inline: true,
    compress: true,
    proxy: {
      '/api/**': {
        target: 'http://10.189.1.159:8080',
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: true
      }
    }
  },

  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    alias: {
      angular: path.resolve(__dirname, 'node_modules/angular/index.js')
    }
  },

  module: {

    rules: [{
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: ['css-loader', 'postcss-loader']
      })
    }, {
      test: /\.scss$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {loader: 'css-loader', options: {sourceMap: true}},
          {loader: 'postcss-loader', options: {sourceMap: true}},
          {loader: 'sass-loader', options: {sourceMap: true}}
        ]
      })
    }, {
      test: /\.ts|\.js?$/,
      exclude: /node_modules/,
      loader: 'ts-loader'
    }, {
      test: /\.html$/,
      use: [
        {loader: 'ngtemplate-loader?relativeTo=' + (path.resolve(__dirname, 'src/app'))},
        {loader: 'html-loader'}
      ],
      exclude: path.resolve(__dirname, 'src/index.html')
    }, {
      test: /\.(jpe?g|gif|png|svg)$/,
      use: [
        {loader: 'file-loader?relativeTo=' + (path.resolve(__dirname, 'src/assets'))}
      ]
    }, {
      test: /.(ttf|otf|eot|woff(2)?)(\?[a-z0-9]+)?$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
          outputPath: 'fonts/'
        }
      }]
    }, {
      test: require.resolve('jquery'),
      use: [{
        loader: 'expose-loader',
        options: 'jQuery'
      }, {
        loader: 'expose-loader',
        options: '$'
      }]
    }, {
      test: require.resolve('angular'),
      use: [{
        loader: 'expose-loader',
        options: 'angular'
      }]
    }]

  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/index.html',
      chunks: ['manifest', 'vendor', 'app', 'libs']
    new CopyWebpackPlugin([{
      context: './src/assets/locales',
      from: '**/*',
      to: './assets/locales/'
    }])
  ]

};
</code>```

答:
v4

Use devServer.open:

npx webpack serve --open /app
```
<p>or</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  // ...
  devServer: {
    open: ['/app'],
   // ...
  },
}
</code>```

v3

Use devServer.openPage.

In your case the value would be /app.

You can also rewrite a bit of your config so you don't have to pass cli commands.

output: {
    publicPath: '/app', // deploy on server with /app/ folder name
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'public')
},

devServer: {
    contentBase: './dist',
    host: 'localhost',
    port: '3000',
    inline: true,
    compress: true,
    proxy: {
      '/api/**': {
        target: 'http://10.189.1.159:8080',
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: true
      }
    }
    open: true, // Here
    openPage: '/app' // And here
},
```

Body:
how do I motivate webpack-dev-server, when started with the --open flag, to open my publicPath?

Currently it opens up a browser tab to http://localhost:3000, but I want it to directly open http://localhost:3000/app, which is my defined public path.

When I manually type http://localhost:3000/app after start up of webpack-dev-server, it works as expected.

Here is my webpack.config.js which works great so far:

const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

module.exports = {

  entry: {
    vendor: [
      'jquery',
      'angular'
    ],
    app: './src/app/index.module.js',
    libs: [
      './src/libs/pagination/dirPagination.js',
      './src/libs/sc-date-time/sc-date-time.js',
      './src/libs/msd-elastic.js',
      './src/libs/ng-textcomplete.js',
      './src/libs/highcharts/highslide-full.js',
      './src/libs/highcharts/Sankey.js'
    ]
  },

  output: {
    filename: '[name].bundle.js',
    chunkFilename: '[id].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/app/'
  },

  devtool: 'inline-source-map',

  devServer: {
    contentBase: './dist',
    host: 'localhost',
    port: '3000',
    inline: true,
    compress: true,
    proxy: {
      '/api/**': {
        target: 'http://10.189.1.159:8080',
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: true
      }
    }
  },

  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    alias: {
      angular: path.resolve(__dirname, 'node_modules/angular/index.js')
    }
  },

  module: {

    rules: [{
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: ['css-loader', 'postcss-loader']
      })
    }, {
      test: /\.scss$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {loader: 'css-loader', options: {sourceMap: true}},
          {loader: 'postcss-loader', options: {sourceMap: true}},
          {loader: 'sass-loader', options: {sourceMap: true}}
        ]
      })
    }, {
      test: /\.ts|\.js?$/,
      exclude: /node_modules/,
      loader: 'ts-loader'
    }, {
      test: /\.html$/,
      use: [
        {loader: 'ngtemplate-loader?relativeTo=' + (path.resolve(__dirname, 'src/app'))},
        {loader: 'html-loader'}
      ],
      exclude: path.resolve(__dirname, 'src/index.html')
    }, {
      test: /\.(jpe?g|gif|png|svg)$/,
      use: [
        {loader: 'file-loader?relativeTo=' + (path.resolve(__dirname, 'src/assets'))}
      ]
    }, {
      test: /.(ttf|otf|eot|woff(2)?)(\?[a-z0-9]+)?$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
          outputPath: 'fonts/'
        }
      }]
    }, {
      test: require.resolve('jquery'),
      use: [{
        loader: 'expose-loader',
        options: 'jQuery'
      }, {
        loader: 'expose-loader',
        options: '$'
      }]
    }, {
      test: require.resolve('angular'),
      use: [{
        loader: 'expose-loader',
        options: 'angular'
      }]
    }]

  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/index.html',
      chunks: ['manifest', 'vendor', 'app', 'libs']
    new CopyWebpackPlugin([{
      context: './src/assets/locales',
      from: '**/*',
      to: './assets/locales/'
    }])
  ]

};

Body:
v4

Use devServer.open:

npx webpack serve --open /app

or

module.exports = {
  // ...
  devServer: {
    open: ['/app'],
   // ...
  },
}

v3

Use devServer.openPage.

In your case the value would be /app.

You can also rewrite a bit of your config so you don't have to pass cli commands.

output: {
    publicPath: '/app', // deploy on server with /app/ folder name
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'public')
},

devServer: {
    contentBase: './dist',
    host: 'localhost',
    port: '3000',
    inline: true,
    compress: true,
    proxy: {
      '/api/**': {
        target: 'http://10.189.1.159:8080',
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: true
      }
    }
    open: true, // Here
    openPage: '/app' // And here
},

ContentLicense: CC BY-SA 4.0


问:
What names can be used in plt.cm.get_cmap?
I have this code :

```<code>plt.scatter(data_projected[:,0],data_projected[:,1],c=digits.target
        ,edgecolors='none',alpha=0.5,cmap=plt.cm.get_cmap('nipy_spectral',10));
</code>```

My confusion comes from plt.cm.get_cmap('nipy_spectral',10). Sometimes there will be plt.cm.get_cmap('RdYlBu') instead.

Is the 'RdYlBu','nipy_spectral' the name of a color? And is there any other names to use instead?

Is there a list of all colors available?

I have read the document but it does not seem to help or I do not understand it.

答:
The first argument to plt.cm.get_cmap('nipy_spectral',10) is the name of a colormap. You can get a list of all available colormaps via

```<code>import matplotlib.cm
print(matplotlib.cm.cmap_d.keys())
</code>```

or you may have a look at the colormap reference.

Body:
I have this code :

plt.scatter(data_projected[:,0],data_projected[:,1],c=digits.target
        ,edgecolors='none',alpha=0.5,cmap=plt.cm.get_cmap('nipy_spectral',10));

My confusion comes from plt.cm.get_cmap('nipy_spectral',10). Sometimes there will be plt.cm.get_cmap('RdYlBu') instead.

Is the 'RdYlBu','nipy_spectral' the name of a color? And is there any other names to use instead?

Is there a list of all colors available?

I have read the document but it does not seem to help or I do not understand it.

Body:
The first argument to plt.cm.get_cmap('nipy_spectral',10) is the name of a colormap. You can get a list of all available colormaps via

import matplotlib.cm
print(matplotlib.cm.cmap_d.keys())

or you may have a look at the colormap reference.


问:
Trying to install OCI8 for PHP
I am trying to install the php (5.5) extension OCI8 for my Oracle 11g database. However upon doing sudo pecl install oci8-2.0.8 I get the following error:

[...] Build process completed successfully

Installing '/usr/lib/php/extensions/no-debug-non-zts-20121212/oci8.so'

ERROR: failed to write
  /usr/lib/php/extensions/no-debug-non-zts-20121212/oci8.so
  (copy(/usr/lib/php/extensions/no-debug-non-zts-20121212/oci8.so):
  failed to open stream: Operation not permitted)

Changing directories to the build path (tmp/pear/install/...) returns directory non-existent.

I am on Mac OSX El Capitan, I have followed these instructions, which noted PHP 5.4 not 5.5.

Not sure what to do anymore - it's one problem after another.

答:
XAMP 5.5.30-6-VC11 and oracle config

Download instantclient_11_2 and uzip to c:\instantclient_11_2 (make sure your xamp and instantclient both are same architechture x86 or 64-bit)

setup ENVIRONMENT PATH for c:\instantclient_11_2 before any oracle directory. Restart PC

download oci8 dll from http://pecl.php.net/package/oci8/2.0.6/windows

select 5.5 Thread Safe (TS) x64 from above link

unzip and copy all files to c:/xampp/php/ext directory

open php.ini remove (;) for extension=php_oci8.dll and save it

restart apache

look phpinfo and search for oci8 module if found and enabled then ok.

test with php oracle connection script .

Title: Trying to install OCI8 for PHP


问:
How to run function only in one div Angular 2
I have *ngFor with groups (its working), i need show "listofGroup" (in console works but in view no), in this specific group, my question is: how to run function in specific div in Angular2

my html groups

```<code><div *ngFor="group in groups">
  <h4>{{group.name}}</h4>
  //here I want to call function where shows list in this group
  //I wrote this but not working
  <ul (load)="readListsGroup(group._id)">
    <li *ngFor="let listGroup of listsInGroup">
      <span>{{listGroup.name}}</span>
    </li>
  </ul>
</div>
</code>```

答:
I am assuming that you set property listsInGroup in readListsGroup.

It is not working, because you are calling readListsGroup in div for loop.
That means that listsInGroup have value of first group, and immediate after that it have value of second group and so on. After div for loop is ended, listsInGroup contains last value (value of last group) and this value is bind to all divs. Am I write?

You can rewrite template as user184994 write:

```<code><div *ngFor="group in groups">
  <h4>{{group.name}}</h4>
  //here I want to call function where shows list in this group
  //I wrote this but not working
  <ul>
    <li *ngFor="let listGroup of readListsGroup(group)">
      <span>{{listGroup.name}}</span>
    </li>
  </ul>
</div>
</code>```

Code:

```<code>readListsGroup(group)
{
  const listsInGroup = findit();
  return listsInGroup;
}
</code>```

Body:
I have *ngFor with groups (its working), i need show "listofGroup" (in console works but in view no), in this specific group, my question is: how to run function in specific div in Angular2

my html groups

{{group.name}}

  //here I want to call function where shows list in this group
  //I wrote this but not working

      {{listGroup.name}}

Body:
I am assuming that you set property listsInGroup in readListsGroup.

It is not working, because you are calling readListsGroup in div for loop.
That means that listsInGroup have value of first group, and immediate after that it have value of second group and so on. After div for loop is ended, listsInGroup contains last value (value of last group) and this value is bind to all divs. Am I write?

You can rewrite template as user184994 write:

<div *ngFor="group in groups">
  <h4>{{group.name}}</h4>
  //here I want to call function where shows list in this group
  //I wrote this but not working
  <ul>
    <li *ngFor="let listGroup of readListsGroup(group)">
      <span>{{listGroup.name}}</span>
    </li>
  </ul>
</div>

Code:

readListsGroup(group)
{
  const listsInGroup = findit();
  return listsInGroup;
}


问:
Typescript Reference to external Module in Namespace
I'm trying to refer to an external module 'moment' in my namespace 'company.controllers'

```<code>namespace company.controllers {
    import { moment } from 'moment';

    'use strict'

    export class WidgetAdminDailyStatisticController extends Controller<company.data.AdminDailyStatisticViewModel> {
        customRepository: company.data.CustomRepository;
        searchDate: Date;

        static $inject: Array<string> = [
            'CustomRepository'
        ];
        constructor(
            customRepository: company.data.CustomRepository
        ) {
            super();

            this.customRepository = customRepository;
        }

        initialize(): void {
            this.searchDate = new Date();

            //let a: moment = new moment();

        }
    }
}
</code>```

I'm getting "Import declarations in a namespace cannot reference to a module"

How do I import moment and use in my typescript?

答:
You can import it outside the namespace:

```<code>import { moment } from 'moment';

namespace company.controllers {
    // ...
}
</code>```

... but you can't import a module in non-module scripts. If your namespace is not in a module, it's not possible. The solution is to use moment as a global variable, and to find (or write) another definition file for that global variable.

Body:
I'm trying to refer to an external module 'moment' in my namespace 'company.controllers'

namespace company.controllers {
    import { moment } from 'moment';

    'use strict'

    export class WidgetAdminDailyStatisticController extends Controller<company.data.AdminDailyStatisticViewModel> {
        customRepository: company.data.CustomRepository;
        searchDate: Date;

        static $inject: Array<string> = [
            'CustomRepository'
        ];
        constructor(
            customRepository: company.data.CustomRepository
        ) {
            super();

            this.customRepository = customRepository;
        }

        initialize(): void {
            this.searchDate = new Date();

            //let a: moment = new moment();

        }
    }
}

I'm getting "Import declarations in a namespace cannot reference to a module"

How do I import moment and use in my typescript?

Body:
You can import it outside the namespace:

import { moment } from 'moment';

namespace company.controllers {
    // ...
}

... but you can't import a module in non-module scripts. If your namespace is not in a module, it's not possible. The solution is to use moment as a global variable, and to find (or write) another definition file for that global variable.


问:
UIScrollView sometimes lose its scroll when changing the height of UITableView inside
I have simple UIScrollView with two subviews: UIView and UITableView set in vertical mode. Both of them have their own height constraint:

I set it like this:

```<code>tableViewHeightConstraint.constant = CGFloat(height) //height is calculated based on number of cells multiplied 130

calendarViewHeightConstraint.constant = UIApplication.shared.keyWindow!.rootViewController!.traitCollection.isIpad ? 630 : 470
</code>```

But sometimes when I scroll to the bottom, and then add a new cell to the table view and recalculate height it seems that scroll of scroll view is locked, and I can bouncing but the scroll disappear and I can only bouncing, although I know that I can scroll to the content above or below the current view on the screen. What may be the reason?

I really have to do this like this. There is no possibility to put my view inside table view header view.

This is where I recalculate height:

```<code>func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

        tableView.endUpdates()
        updateView()
        updateTableViewHeight()
}

private func updateTableViewHeight() {

    var height = goalFetchedResultsController.fetchedObjects!.count * 130

    height += 45

    if MyType.selected.hasMonthReport {
        height += 130
    }

    if MyType.selected.hasAnnualReport {
        height += 70
        height += 130
    }

    tableViewHeightConstraint.constant = CGFloat(height)
}
</code>```

New cell is added inside delegate of NSFetchedResultsController.

答:
I'm thinking you need to change your calculation way of height of TableView like,

```<code>var height = tablView.contentSize.heigh // You can do + or - here

// your other stuff of calculation.
tableViewHeightConstraint.constant = CGFloat(height)

self.view.layoutIfNeeded() // You need to call after change constraint.
</code>```

Body:
I have simple UIScrollView with two subviews: UIView and UITableView set in vertical mode. Both of them have their own height constraint:

I set it like this:

tableViewHeightConstraint.constant = CGFloat(height) //height is calculated based on number of cells multiplied 130

calendarViewHeightConstraint.constant = UIApplication.shared.keyWindow!.rootViewController!.traitCollection.isIpad ? 630 : 470

But sometimes when I scroll to the bottom, and then add a new cell to the table view and recalculate height it seems that scroll of scroll view is locked, and I can bouncing but the scroll disappear and I can only bouncing, although I know that I can scroll to the content above or below the current view on the screen. What may be the reason?

I really have to do this like this. There is no possibility to put my view inside table view header view.

This is where I recalculate height:

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

        tableView.endUpdates()
        updateView()
        updateTableViewHeight()
}

private func updateTableViewHeight() {

    var height = goalFetchedResultsController.fetchedObjects!.count * 130

    height += 45

    if MyType.selected.hasMonthReport {
        height += 130
    }

    if MyType.selected.hasAnnualReport {
        height += 70
        height += 130
    }

    tableViewHeightConstraint.constant = CGFloat(height)
}

New cell is added inside delegate of NSFetchedResultsController.

Body:
I'm thinking you need to change your calculation way of height of TableView like,

var height = tablView.contentSize.heigh // You can do + or - here

// your other stuff of calculation.
tableViewHeightConstraint.constant = CGFloat(height)

self.view.layoutIfNeeded() // You need to call after change constraint.


问:
Introduction to Testing Google Gadgets
I'm trying to create a simple google gadget and am encountering trouble right out the door. I've read the getting started guide top to bottom and feel like i'm still missing something.

Starting with the Hello World gadget they have provided, how do I begin editing and testing? I'm using the Google Gadget Editor with the preview tab. This works for simple html, but any javascript (such as an "alert") I embed doesn't work.

I can publish the gadget and add it to iGoogle. When I do this, my embeded javascript works. However there seems to be a good bit of caching and latency going on behind the scenes. Right now this process of editing, uploading, publishing, debugging is quite painful. Am I missing something obvious here? What is the "correct" way to develop and test a gadget? Is there a program that can run gadget code on my machine without having to go online?

答:
Try appending a query string to your gadget URL and then add it to your gmail or iGoogle page. Use a different query parameter every time you make changes to your gadget. Like for example:

```<code>www.mycompany.com/gadgets/main.xml?q=1234
</code>```

Google refreshes the cache every hour or so. So, adding a query string will force it to refresh the gadget immediately.

ContentLicense: CC BY-SA 2.5

Title: Introduction to Testing Google Gadgets

Body:
Try appending a query string to your gadget URL and then add it to your gmail or iGoogle page. Use a different query parameter every time you make changes to your gadget. Like for example:

www.mycompany.com/gadgets/main.xml?q=1234

Google refreshes the cache every hour or so. So, adding a query string will force it to refresh the gadget immediately.


问:
Android Studio Desugar: Transform Classes with Desugar for Debug fails
My Android Studio project recently stopped building properly. I do not know what caused this issue.
Here is what I tried

I tried to build my project with different Android Studio versions, i.e. stable and different Canary channel versions, no change

I changed SDK versions around. My project built properly with SDK 26, but now it does not, also not with SDK 27

I swapped build tools and Gradle versions around, my project built properly with Gradle plugin 3.1.0-alpha2 and build tools version 26.0.2. I tried many

I used the "Clean Project", "Invalidate Caches"... functions in Android Studio uncountable times

I deleted my build folders

I switched Proguard on and off

I tried fixing possible library issues, but all of it did not help

I think I actually changed everything back to the settings I used successfully before and my other projects with similar settings just build fine.

Full error code:

```<code>Error:java.lang.RuntimeException: com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:org.gradle.process.internal.ExecException: Process 'command '...\jre\bin\java.exe'' finished with non-zero exit value 1
</code>```

Problem description

I have no clue what could (have) cause(d) this issue and I am clueless about what to try next, which is the reason why I am asking you for help. I hope anyone has any other help than what I could find.

I tagged Firebase because I think that the library might be the crucial point of my problem, now the problem is that it will never explain the sudden stop. I use FirebaseUI in my application and tried the old working dependencies, but also upgrading Firebase and then using this guide to match the outdated UI library. I also removed FirebaseUI, but this did neither make a successful build.

答:
Did you try to use and clear the build cache that was introduced in AS 2.3?

e.g., my gradle.properties had

```<code>android.enableBuildCache=true
android.buildCacheDir=/tmp/android-build-cache
</code>```

and I had to clear /tmp/android-build-cache to fix the same Desugar error that I got.

Body:
My Android Studio project recently stopped building properly. I do not know what caused this issue.
Here is what I tried

I tried to build my project with different Android Studio versions, i.e. stable and different Canary channel versions, no change

I changed SDK versions around. My project built properly with SDK 26, but now it does not, also not with SDK 27

I swapped build tools and Gradle versions around, my project built properly with Gradle plugin 3.1.0-alpha2 and build tools version 26.0.2. I tried many

I used the "Clean Project", "Invalidate Caches"... functions in Android Studio uncountable times

I deleted my build folders

I switched Proguard on and off

I tried fixing possible library issues, but all of it did not help

I think I actually changed everything back to the settings I used successfully before and my other projects with similar settings just build fine.

Full error code:

Error:java.lang.RuntimeException: com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:java.lang.RuntimeException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}
Error:com.android.ide.common.process.ProcessException: Error while executing java process with main class com.google.devtools.build.android.desugar.Desugar with arguments {@...\app\build\intermediates\tmp\desugar_args165654356027684238}

Error:org.gradle.process.internal.ExecException: Process 'command '...\jre\bin\java.exe'' finished with non-zero exit value 1

Problem description

I have no clue what could (have) cause(d) this issue and I am clueless about what to try next, which is the reason why I am asking you for help. I hope anyone has any other help than what I could find.

I tagged Firebase because I think that the library might be the crucial point of my problem, now the problem is that it will never explain the sudden stop. I use FirebaseUI in my application and tried the old working dependencies, but also upgrading Firebase and then using this guide to match the outdated UI library. I also removed FirebaseUI, but this did neither make a successful build.

Body:
Did you try to use and clear the build cache that was introduced in AS 2.3?

e.g., my gradle.properties had

android.enableBuildCache=true
android.buildCacheDir=/tmp/android-build-cache

and I had to clear /tmp/android-build-cache to fix the same Desugar error that I got.


问:
How to make a Trello-like drag and drop board interface using Swift on IOS
I am fairly new to IOS(Iphone) Development using Swift and for my starting project, I want to make something very similar to Trello board but natively on IOS. I am wondering how can I create UIViews similar to "Boards" horizontally and embed it with ScrollView, also "Cards" that can be drag/drop on to different columns of "Boards". My Idea is to use Customized UITableView and make table sections as "Boards", table cells as "Cards". But how can I make it looks better like the one in Trello:

Or should I create the "Board" and "Card" in Nib?
Any suggestions would be much appreciated!

答:
There are very many ways on how to do this but for a beginner this may be quite challenging.

Your question is very broad but using table view I would try to do the following:

Create a system of table views which works without dragging and ensure everything works correctly and your data source is tidy (produce a high quality code). Ensure the table view cells have automatic dimensions.

Modify your cells so they are placeholders for views. Basically have a method like cell.setView(myCardView). The views should then be ported to separate XIB files or used as embedded view controllers. Ensure that setting a nil view on cell will create a placeholder cell (the one you see before you drop the card).

Add gesture recognizers to move cells, long press gesture should give you a nice touch where you will check states begin to grab and then changed whenever user moves his finger around. On grab you need to take the held view, add it as subview to view controller main view, convert its coordinates (UIView has methods for that) and animate its position to where the finger is. Also set nil to cell view. On change (user drags) simply reposition the view (without animations) to where the gesture position is.

Detect movements between cell position and table views while moving. You need to first check which table view you are in by checking horizontal position of the gesture recognizer (should be trivial). And then at which cell you are at by combining vertical position and table view visible cells (this one will prove a bit harder). If a table view is changed (from where it was) you need to remove the placeholder cell from previous table view and add it to a new table view. I a cell is swapped you need to reorder cells.

Once dropped, gesture ends or canceled you need to put the view into the placeholder cell. This should be reversed from picking it up; you need to convert the cell view frame to main view frame and animate the view frame to the one from cell. Then insert the view into cell without animations. Then update your data source so the card is in correct position.

This answer is very broad but it might give you enough to start and ask more specific questions if needed once you start your development.


问:
Lock a ToggleButton after checking
I have a GUI which is built with the MVVM-Pattern. In the View there is a Toggle-Button, which IsChecked property is bound to a bool property in the ViewModel.

Now it is only allowed to turn the ToggleButton (and the bool property in the ViewModel) from false to true over the View. A method resets the bool property in the ViewModel, so the user can switch the Toggle-Button again from false to true.

How can I lock the Toggle-Button in the View, without using the IsEnabled Property?

Thanks.

答:
What's wrong with using IsEnabled? Your users will quickly get frustrated if they click on what appears to be a regular toggle button and nothing happens.

If you realy want to go down this path, you could write something like this as the binding source for the button's IsChecked property.

```<code>    private bool _isToggleButtonChecked;

    public bool IsToggleButtonChecked
    {
        get { return _isToggleButtonChecked; }
        set
        {
            if (_isToggleButtonChecked)
                return;

            _isToggleButtonChecked = value;
            RaisePropertyChanged("IsToggleButtonChecked");
        }
    }

    private void ResetIsToggleButtonChecked()
    {
        _isToggleButtonChecked = false;
        RaisePropertyChanged("IsToggleButtonChecked");
    }
</code>```

Title: Lock a ToggleButton after checking

Body:
What's wrong with using IsEnabled? Your users will quickly get frustrated if they click on what appears to be a regular toggle button and nothing happens.

If you realy want to go down this path, you could write something like this as the binding source for the button's IsChecked property.

    private bool _isToggleButtonChecked;

    public bool IsToggleButtonChecked
    {
        get { return _isToggleButtonChecked; }
        set
        {
            if (_isToggleButtonChecked)
                return;

            _isToggleButtonChecked = value;
            RaisePropertyChanged("IsToggleButtonChecked");
        }
    }

    private void ResetIsToggleButtonChecked()
    {
        _isToggleButtonChecked = false;
        RaisePropertyChanged("IsToggleButtonChecked");
    }


问:
Linked List overload addition
I am trying to overload addition using Linked lists and have hit a wall. I am adding 2 linked lists together and each node is added individually but if I add two lists which contain 999 and 999 then it shows 181818 instead of the correct answer and I am kinda lost. It seems to work sometimes though like if I use 500 and 500.</p>

```<code>LinkedList LinkedList::operator+( LinkedList &obj)
{
    LinkedList sum;
    ListNode *nodePtr;
    ListNode *nodePtr2;

    nodePtr = head;
    nodePtr2 = obj.head;

    while (nodePtr && nodePtr2)
    {
        sum.appendNode(nodePtr->value + nodePtr2->value);//append node adds a new node containing the value at the end of the list.
        nodePtr = nodePtr->next;
        nodePtr2 = nodePtr2->next;
    }
    return sum;
}
</code>```

答:
From your code and your post, it appears that each linked list is a list of the digits of a number. You are trying to add two numbers by adding the matching list items of two linked lists. But this will fail pretty fast in at least 2 cases:

The two elements you add return a sum greater than 10 and they are in the middle of the number. In this case, you need to "carry the one", as we learned in 2nd grade. This will involve some more list work that you don't have here.

If the two numbers are of different length. The while loop will simply ignore the extra digits of the longer number.

And yes it works for 500 + 500 -- that doesn't violate either of the 2 cases I mentioned above.

So, I'd change your while loop to something like this:

```<code>int carryVal = 0;
while (...) {
    ...
    int sum = nodePtr->value + nodePtr2->value;
    int thisDigitVal = sum % 10 + carryVal; // First digit of the sum, plus any carry from previous digit
    sum.appendNode(thisDigitVal);
    carryVal = sum / 10; // carry for next digit (division by int will truncate -- thats what we want)
    ...
}
</code>```

Couple of notes:

You will probably have to change your while condition to work with numbers of different lengths and also to deal with any final carry.

This will only work with summing 2 numbers. For 3 or more, you will have to deal with the case where int thisDigitVal = sum % 10 + carryVal; returns a value > 9 and thus add another 1 to the carry for the next digit.

Title: Linked List overload addition

Body:
I am trying to overload addition using Linked lists and have hit a wall. I am adding 2 linked lists together and each node is added individually but if I add two lists which contain 999 and 999 then it shows 181818 instead of the correct answer and I am kinda lost. It seems to work sometimes though like if I use 500 and 500.

LinkedList LinkedList::operator+( LinkedList &obj)
{
    LinkedList sum;
    ListNode *nodePtr;
    ListNode *nodePtr2;

    nodePtr = head;
    nodePtr2 = obj.head;

    while (nodePtr && nodePtr2)
    {
        sum.appendNode(nodePtr->value + nodePtr2->value);//append node adds a new node containing the value at the end of the list.
        nodePtr = nodePtr->next;
        nodePtr2 = nodePtr2->next;
    }
    return sum;
}

Body:
From your code and your post, it appears that each linked list is a list of the digits of a number. You are trying to add two numbers by adding the matching list items of two linked lists. But this will fail pretty fast in at least 2 cases:

The two elements you add return a sum greater than 10 and they are in the middle of the number. In this case, you need to "carry the one", as we learned in 2nd grade. This will involve some more list work that you don't have here.

If the two numbers are of different length. The while loop will simply ignore the extra digits of the longer number.

And yes it works for 500 + 500 -- that doesn't violate either of the 2 cases I mentioned above.

So, I'd change your while loop to something like this:

int carryVal = 0;
while (...) {
    ...
    int sum = nodePtr->value + nodePtr2->value;
    int thisDigitVal = sum % 10 + carryVal; // First digit of the sum, plus any carry from previous digit
    sum.appendNode(thisDigitVal);
    carryVal = sum / 10; // carry for next digit (division by int will truncate -- thats what we want)
    ...
}

Couple of notes:

You will probably have to change your while condition to work with numbers of different lengths and also to deal with any final carry.

This will only work with summing 2 numbers. For 3 or more, you will have to deal with the case where int thisDigitVal = sum % 10 + carryVal; returns a value > 9 and thus add another 1 to the carry for the next digit.


问:
How to get particular object after compare particular key _id.$iod in javascript?
I am using mongoDB for storing the data and retrieving the data. So I am getting response data. I can get particular object from comparing name,But when I want to compare _id.$oid then it is giving me undefined. I am sharing my code.

```<code>   Array.prototype.getIndexBy = function (name, value) {
        for (var i = 0; i < this.length; i++) {
            if (this[i][name] == value) {
                return i;
            }
        }
        return -1;
    }

    var data = documents[documents.getIndexBy("_id.$oid", "33453223")]
    console.log("----------updates-------->",data);
</code>```

SAMPLE JSON

```<code>[
{"_id":{"$oid":"3426"},
"name":"peeter"
},
{"_id":{"$oid":"5a027"},
"name":"ken"
},
{"_id":{"$oid":"5999"},
"name":"karmal"
}
]
</code>```

I am able to compare with name, But I want to compare with _id.$oid, When I am taking _id.$oid then It is giving me undefined value. I want to compare only with _id. I am referring link

find the array index of an object with a specific key value in underscore

答:
If you are using lodash/underscore.js, you can use _.find

var users = [
  {"_id":{"$oid":"3426"},
  "name":"peeter"
  },
  {"_id":{"$oid":"5a027"},
  "name":"ken"
  },
  {"_id":{"$oid":"5999"},
  "name":"karmal"
  }
];

var index = _.find(users, function(o) { return o._id.$oid == '5999'; });

console.log(index);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

Body:
I am using mongoDB for storing the data and retrieving the data. So I am getting response data. I can get particular object from comparing name,But when I want to compare _id.$oid then it is giving me undefined. I am sharing my code.

   Array.prototype.getIndexBy = function (name, value) {
        for (var i = 0; i < this.length; i++) {
            if (this[i][name] == value) {
                return i;
            }
        }
        return -1;
    }

    var data = documents[documents.getIndexBy("_id.$oid", "33453223")]
    console.log("----------updates-------->",data);

SAMPLE JSON

[
{"_id":{"$oid":"3426"},
"name":"peeter"
},
{"_id":{"$oid":"5a027"},
"name":"ken"
},
{"_id":{"$oid":"5999"},
"name":"karmal"
}
]

I am able to compare with name, But I want to compare with _id.$oid, When I am taking _id.$oid then It is giving me undefined value. I want to compare only with _id. I am referring link

find the array index of an object with a specific key value in underscore

Body:
If you are using lodash/underscore.js, you can use _.find

var users = [
  {"_id":{"$oid":"3426"},
  "name":"peeter"
  },
  {"_id":{"$oid":"5a027"},
  "name":"ken"
  },
  {"_id":{"$oid":"5999"},
  "name":"karmal"
  }
];

var index = _.find(users, function(o) { return o._id.$oid == '5999'; });

console.log(index);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
How to use javax.smartcardio package on Android?
I'm wrote java console app with smartcardio.Everything worked perfect.Now I want to use this library in Android. As I know smartcardio does not supported in Android. I searched about in Google.If anyone knows how I can use this library in Android,or what's a alternative ?
Thanks</p>

答:
You cannot use smartcardio library in Android as you have already figured out. If your intention is to communicate to a Smart Card in contactless interface i would suggest you to take a look at the following library https://developer.android.com/reference/android/nfc/package-summary.html
https://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc.html

If your intention is to communicate to a SE you can take a look at
https://github.com/seek-for-android/pool/wiki/UsingSmartCardAPI


问:
distinct, max and group by query in sql
I have a dataset like:

```<code>list1     list2
a          e
a          e
b          w
a          e
a          r
b          c
</code>```

I want to find most frequent item in list2 grouped by list1.

```<code>list1     list2    max
  a         e       3
  b         w       1
</code>```

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

```<code>SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2
</code>```

答:
Supposing you are using Mysql, I think you could try a query like this one.

In the inner part of the query, ordinary count(*)/group by is made, ordering the results in descending order of count.

In the second part, I made a CROSS JOIN to initialize variables and define a CASE using variables to simulate ROW_NUMBER().

In the outer part results are filtered (only one row for each "group").

```<code>SELECT list1, list2, RC
FROM (SELECT A.*
    , CASE WHEN @gr1=list1 THEN @row_n:=@row_n+1 ELSE @row_n:=1 END AS RN
    , @gr1:=list1
    FROM (SELECT list1
             , list2
            , COUNT(*) AS RC
          FROM LIST
          GROUP BY list1, list2
          ORDER BY list1, RC DESC ) A
    CROSS JOIN (SELECT @row_n:=1, @gr1:='') B
    ) C
WHERE RN=1;
</code>```

Output:

```<code>list1   list2   RC
a       e       3
b       w       1
</code>```

Title: distinct, max and group by query in sql

Body:
I have a dataset like:

list1     list2
a          e
a          e
b          w
a          e
a          r
b          c

I want to find most frequent item in list2 grouped by list1.

list1     list2    max
  a         e       3
  b         w       1

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2

Body:
Supposing you are using Mysql, I think you could try a query like this one.

In the inner part of the query, ordinary count(*)/group by is made, ordering the results in descending order of count.

In the second part, I made a CROSS JOIN to initialize variables and define a CASE using variables to simulate ROW_NUMBER().

In the outer part results are filtered (only one row for each "group").

SELECT list1, list2, RC
FROM (SELECT A.*
    , CASE WHEN @gr1=list1 THEN @row_n:=@row_n+1 ELSE @row_n:=1 END AS RN
    , @gr1:=list1
    FROM (SELECT list1
             , list2
            , COUNT(*) AS RC
          FROM LIST
          GROUP BY list1, list2
          ORDER BY list1, RC DESC ) A
    CROSS JOIN (SELECT @row_n:=1, @gr1:='') B
    ) C
WHERE RN=1;

Output:

list1   list2   RC
a       e       3
b       w       1


问:
How to compare the same columns in different rows?
I have extracted data like below

```
Name   Session     CATEGORY   HT     WT     BMI
John   SESSION 1   OW         1.5    64.6   28.71
John   SESSION 3   OW         1.52   63.2   27.35
Eric   SESSION 1   OW         1.48   55.7   25.43
Eric   SESSION 3   OW         1.52   55.4   23.98
```

I would want it in the below format

```
Name  session_1_Category  Session_1_height  session_1_weight  session_1_BMI  session_3_Category  Session_3_height  session_3_weight  session_3_BMI
John  OW                  1.5               64.6              28.71          OW                  1.52              63.2              27.35
Eric  OW                  1.48              55.7              25.43          OW                  1.52              55.4              23.98
```

I'm using oracle database. Please help me with a SQL query to extract data in the above format.

答:
Here is another solution without using PIVOT tables and will work across platforms- </p>

```<code>SELECT NAME
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN CATEGORY END) AS session_1_Category
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS Session_1_height
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS session_1_weight
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS session_1_BMI
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_Category
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS Session_3_height
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_weight
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_BMI
FROM YOUR_TABLE
GROUP BY NAME
</code>```

Body:
I have extracted data like below

Name   Session     CATEGORY   HT     WT     BMI
John   SESSION 1   OW         1.5    64.6   28.71
John   SESSION 3   OW         1.52   63.2   27.35
Eric   SESSION 1   OW         1.48   55.7   25.43
Eric   SESSION 3   OW         1.52   55.4   23.98

I would want it in the below format

Name  session_1_Category  Session_1_height  session_1_weight  session_1_BMI  session_3_Category  Session_3_height  session_3_weight  session_3_BMI
John  OW                  1.5               64.6              28.71          OW                  1.52              63.2              27.35
Eric  OW                  1.48              55.7              25.43          OW                  1.52              55.4              23.98

I'm using oracle database. Please help me with a SQL query to extract data in the above format.

Body:
Here is another solution without using PIVOT tables and will work across platforms-

SELECT NAME
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN CATEGORY END) AS session_1_Category
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS Session_1_height
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS session_1_weight
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS session_1_BMI
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_Category
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS Session_3_height
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_weight
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_BMI
FROM YOUR_TABLE
GROUP BY NAME


问:
Tkinter Entry to accept Unicode text?
I have a Tkinter Entry widget and a Hungarian keyboard. When I press the ő button on the keyboard, the Entry widget displays õ. ű becomes û. (I haven't had this problem in other applications since Windows 3.1.)

Edit:

I do have two language settings on this computer and when I start changing them around, the problem disappears.

What can I do to make Tkinter handle my input correctly?

答:
There is a Tk ticket here:
Tk Ticket

Unfortunately, the issue might be TkInter only.

Would it be possible to get more details and make a test using plain Tcl/Tk ?
So, download a current tcl/tk starkit or distribution and try the script:

```<code>pack [entry .e]
</code>```

and look, if the problem is present there too ?

Please report to the tk ticket, anonymous login might be required there.

Title: Tkinter Entry to accept Unicode text?

Body:
There is a Tk ticket here:
Tk Ticket

Unfortunately, the issue might be TkInter only.

Would it be possible to get more details and make a test using plain Tcl/Tk ?
So, download a current tcl/tk starkit or distribution and try the script:

pack [entry .e]

and look, if the problem is present there too ?

Please report to the tk ticket, anonymous login might be required there.