问:
Compare 2 integers in a do while loop
Write a program that has the user enter integers between 0 and 9999 until the user enters some integer twice.  Program should to the console window how many distinct integers were entered.

How do i make the condition for the while loop? Or how do i compare if 2 integers entered by user in a do while loop are equal?

```<code>int n1,n2,count=0;
do {
     Scanner kb = new Scanner(System.in);
     System.out.print("Enter an int: ");
     n1= kb.nextInt();
     n2= kb.nextInt();
     count++;
} while(n1 != n2);
System.out.println("you entered " + count + "times");
</code>```

This is why i tried

答:
If you use set you could implement it as follows:

```<code>package com.company;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {

    public static void main (String[]args) {

        Scanner in = new Scanner(System.in);
        Set<Integer> set = new HashSet<>();

        System.out.print("Enter your number: ");

        while (set.add(in.nextInt())){
            System.out.print("Enter next number: ");
        }

        System.out.println("There are " + set.size() + " distinct numbers entered into a set.");

    }
}
</code>```

Set add() method returns true if set didn't contain added element and element was successfully added, or false if Set already contained entered element and the element wasn't added. So we ask user for numbers until he enters one that is already contained in a Set (he entered it before) then we break from the loop and print out the size of elements in the Set, which will be the number of distinct elements user entered.

Title: Compare 2 integers in a do while loop

Body:
Write a program that has the user enter integers between 0 and 9999 until the user enters some integer twice.  Program should to the console window how many distinct integers were entered.

How do i make the condition for the while loop? Or how do i compare if 2 integers entered by user in a do while loop are equal?

int n1,n2,count=0;
do {
     Scanner kb = new Scanner(System.in);
     System.out.print("Enter an int: ");
     n1= kb.nextInt();
     n2= kb.nextInt();
     count++;
} while(n1 != n2);
System.out.println("you entered " + count + "times");

This is why i tried

Body:
If you use set you could implement it as follows:

package com.company;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {

    public static void main (String[]args) {

        Scanner in = new Scanner(System.in);
        Set<Integer> set = new HashSet<>();

        System.out.print("Enter your number: ");

        while (set.add(in.nextInt())){
            System.out.print("Enter next number: ");
        }

        System.out.println("There are " + set.size() + " distinct numbers entered into a set.");

    }
}

Set add() method returns true if set didn't contain added element and element was successfully added, or false if Set already contained entered element and the element wasn't added. So we ask user for numbers until he enters one that is already contained in a Set (he entered it before) then we break from the loop and print out the size of elements in the Set, which will be the number of distinct elements user entered.


来源: stackexchange

问:
If value is in another dataframe, replace multiple columns with NA
I have two data.frames like this:

```<code>#df1
ID     a1      a2     a3      b1      b2      b3     Date
3xy    Evan    Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    Mark    Seth   12/5

#df2
Name
Evan
Mark
</code>```

If a name from any of the "a" columns appears in df2$Name, I want to replace all of the "a" columns with NA. Same for the "b" columns. My desired output would look like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      NA     NA     Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    NA       NA      NA     12/5
</code>```

I've found several other posts that appear to be on similar topics, but I haven't found a way to get this to work. I've been able to replace the names in df1 that appear in df2 with NA using the code below, but haven't figured out how to replace the other columns that begin with the same letter:

```<code>df1[apply(df1, 2, function(df1) df1 %in% df2$Name)] <- NA
</code>```

Gives me an output like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    NA      Seth   12/5
</code>```

I also keep trying different ifelse statements, but no success.

答:
Here is a dplyr/tidyr approach

```<code>library(dplyr)
library(tidyr)

df1= df1%>% gather(Type, Names, -c(ID, Date)) %>%
  mutate(type2 = gsub("\\d", "", Type)) %>%
  group_by(type2, ID) %>%
  mutate(names2 = ifelse(any(Names %in% df2$Name), "", Names),
         Names = ifelse(names2 == "", NA, Names)) %>%
  ungroup() %>%
  select(-type2, -names2)
</code>```

which results in a (long format)

```<code>       ID   Date  Type Names
   <fctr> <fctr> <chr> <chr>
 1  3xy     12/3    a1  <NA>
 2  4lm     12/5    a1  John
 3  3xy     12/3    a2  <NA>
 4  4lm     12/5    a2  Bill
 5  3xy     12/3    a3  <NA>
 6  4lm     12/5    a3   Sue
 7  3xy     12/3    b1   Ben
 8  4lm     12/5    b1  <NA>
 9  3xy     12/3    b2   Bob
10  4lm     12/5    b2  <NA>
11  3xy     12/3    b3  Alex
12  4lm     12/5    b3  <NA>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two data.frames like this:

#df1
ID     a1      a2     a3      b1      b2      b3     Date
3xy    Evan    Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    Mark    Seth   12/5

#df2
Name
Evan
Mark

If a name from any of the "a" columns appears in df2$Name, I want to replace all of the "a" columns with NA. Same for the "b" columns. My desired output would look like this:

ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      NA     NA     Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    NA       NA      NA     12/5

I've found several other posts that appear to be on similar topics, but I haven't found a way to get this to work. I've been able to replace the names in df1 that appear in df2 with NA using the code below, but haven't figured out how to replace the other columns that begin with the same letter:

df1[apply(df1, 2, function(df1) df1 %in% df2$Name)] <- NA

Gives me an output like this:

ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    NA      Seth   12/5

I also keep trying different ifelse statements, but no success.

Body:
Here is a dplyr/tidyr approach

library(dplyr)
library(tidyr)

df1= df1%>% gather(Type, Names, -c(ID, Date)) %>%
  mutate(type2 = gsub("\\d", "", Type)) %>%
  group_by(type2, ID) %>%
  mutate(names2 = ifelse(any(Names %in% df2$Name), "", Names),
         Names = ifelse(names2 == "", NA, Names)) %>%
  ungroup() %>%
  select(-type2, -names2)

which results in a (long format)

       ID   Date  Type Names
   <fctr> <fctr> <chr> <chr>
 1  3xy     12/3    a1  <NA>
 2  4lm     12/5    a1  John
 3  3xy     12/3    a2  <NA>
 4  4lm     12/5    a2  Bill
 5  3xy     12/3    a3  <NA>
 6  4lm     12/5    a3   Sue
 7  3xy     12/3    b1   Ben
 8  4lm     12/5    b1  <NA>
 9  3xy     12/3    b2   Bob
10  4lm     12/5    b2  <NA>
11  3xy     12/3    b3  Alex
12  4lm     12/5    b3  <NA>


问:
CSS: Box Shadow Effect on Scalene Triangle PseudoElement
I am trying to create a box shadow around a scalene triangle that exists as a pseudo element, as shown below. I have tried many ways but cannot seem to get an even shadow below my image.

I have tried putting a second scalene triangle pseudo element with slightly larger dimensions that is grey but since there is no gradient or shadow effect, it is not what I am looking for.

Does anyone have any solutions?

Would really appreciate some ideas; perhaps there is a way to get a border gradient effect on a second pseudo element and underlay it?

.box {
  height: 100px;
  width: 100px;
  background: blue;
  position: relative;
  box-shadow: 0 40px 5px 0 rgba(0, 0, 0, 0.50);
}

.box:after {
  content: '';
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  border-left: 20px solid transparent;
  border-right: 80px solid transparent;
  border-top: 30px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style='width: 300px;height:300px;background: white;'>
  <div class='box'>
  </div>
</div></code>```

答:
You can have a look on this fiddle I have made: https://jsfiddle.net/1fwrn3wh/1/.

The steps you need to do:

Add a :before pseudo element which the same size of :after element

Slightly move :before element downward

Add the filter with blur aspect

Then it will alike the shadow ;)

For your quick editing, you can add this CSS into your file:

```<code>.box:before {
  content: '';
  position: absolute;
  top: 105%;
  left: 0;
  right: 0;
  border-left: 20px solid transparent;
  border-right: 80px solid transparent;
  border-top: 30px solid rgba(0, 0, 0, 0.5);
  filter: blur(2px);
}
</code>```

And then change the box-shadow of the original box:

```<code>box-shadow: 0 5px 5px 0 rgba(0,0,0,0.50);
</code>```

Cheer ;)

Body:
You can have a look on this fiddle I have made: https://jsfiddle.net/1fwrn3wh/1/.

The steps you need to do:

Add a :before pseudo element which the same size of :after element

Slightly move :before element downward

Add the filter with blur aspect

Then it will alike the shadow ;)

For your quick editing, you can add this CSS into your file:

.box:before {
  content: '';
  position: absolute;
  top: 105%;
  left: 0;
  right: 0;
  border-left: 20px solid transparent;
  border-right: 80px solid transparent;
  border-top: 30px solid rgba(0, 0, 0, 0.5);
  filter: blur(2px);
}

And then change the box-shadow of the original box:

box-shadow: 0 5px 5px 0 rgba(0,0,0,0.50);

Cheer ;)


问:
PHP Loop calculations, get previous value and add current
I am trying to get previous value for current loop for some calculations.
As a starting point lets describe what does the code.

Outer loop generates month names

$forecast_correction is a loop for correcting some values

The idea is to make a forecast/prediction for the months having the base cost and default percentage for the months.

This is the logic for the loop. January is the starting month, we set there the base $price but next month( February ) should be January * $default_percent,
March should be February * $default_percent etc. all should include corrections.

When it comes to the corrections we got two variables

```<code>$percentage = (!empty($modified_percentage)) ? $modified_percentage : $default_percent;
$month_cost = $price * $percentage + $correction_cost;
</code>```

Percentage can change if outer loop month($m) equals to correction array $month, else its the default value.
Month cost is a basic calculation.

```<code>  +----------+---------------+------------+------------+------------+------------+-------------+-------------+-------------+-------------+------------+------------+
  |   jan    |      feb      |    mar     |    apr     |    may     |    june    |    july     |    augu     |    sept     |     oct     |    nov     |    dece    |
  +----------+---------------+------------+------------+------------+------------+-------------+-------------+-------------+-------------+------------+------------+
  | 41290.65 | 41290.65*1.03 | feb * 1.03 | mar * 1.03 | apr * 1.03 | may * 1.03 | june * 1.03 | july * 1.03 | augu * 1.03 | sept * 1.03 | oct * 1.03 | nov * 1.03 |
  +----------+---------------+------------+------------+------------+------------+-------------+-------------+-------------+-------------+------------+------------+
</code>```

Code snippet

```<code><?PHP
$forecast_correction = array(
    array(
        'month' => '2',
        'add' => 150.00,
        'substract' => 0.00,
        'final' => 150.00,
        'percent' => 1.02
    ),
    array(
        'month' => '3',
        'add' => 0.00,
        'substract' => 250.00,
        'final' => -250.00,
        'percent' => NULL
    ),
    array(
        'month' => '4',
        'add' => 0.00,
        'substract' => 0.00,
        'final' => 0.00,
        'percent' => 0.15
    )
);
$price               = 41290.65;
$default_percent     = 1.03;

for ($m = 1; $m <= 12; ++$m) {
    $correction_cost     = 0;
    $modified_percentage = null;
    foreach ($forecast_correction as $correction) {

        if ($m == $correction['month']) {
            $correction_cost = $correction['final'];
            if (!empty($correction['percent'])) {
                $modified_percentage = $correction['percent'];
            }
        }
    }
    ;
    $percentage = (!empty($modified_percentage)) ? $modified_percentage : $default_percent;
    $month_cost = $price * $percentage + $correction_cost;

    echo date('F', mktime(0, 0, 0, $m, 1)) . " :: $month_cost :: " . $correction_cost . "  :: " . $percentage . "% \n";
}
</code>```

Question and desired output

Question : How to implement the February = January * percentage logic in this particular example to have all the results properly calculated with the correction array.

Desired output ( can be plain text, array whatever. )

```<code>Month : Cost
</code>```

If you need future clarification don't hesitate to ask, I am quite stuck with this one.

MCVE sandbox

http://sandbox.onlinephpfunctions.com/code/0c705ab721c6160813b98d133d8a1b7ff876cdca

答:
I think with a couple of minor modifications your example code will do what you want.

I renamed $price to $base_month_cost, where it is initially defined:

```<code>$base_month_cost     = 41290.65;
</code>```

and where it is used to calculate $month_cost in the outer loop:

```<code>$month_cost = $base_month_cost * $percentage + $correction_cost;
</code>```

Then, after the line (above) that calculates $month_cost, I added a new line to redefine $base_month_cost:

```<code>$base_month_cost = $month_cost;// set here for use in next iteration
</code>```

This means that the $month_cost for each successive month is based on the previous month's $month_cost.

You also want to ensure that the no percentage increase is applied when calculating the $month_cost for January. I can think of two approaches to this problem:

You could add January to the $forecast_correction array with a 'percent' value of 1 (so the initial $base_month_cost gets multiplied by 1, and is unchanged).

You could add some additional logic within the for loop, either to set $percentage to 1 if $m == 1, or to do a different calculation of $month_cost, ignoring $percentage if $m == 1.

I think the first approach is cleaner.

Hopefully this is what you're looking for. When I ran it for a test with my modifications, I noticed that the percent value for April is 0.15 in your example, which significantly reduces the $month_cost for that (and successive months).

Body:
I am trying to get previous value for current loop for some calculations.
As a starting point lets describe what does the code.

Outer loop generates month names

$forecast_correction is a loop for correcting some values

The idea is to make a forecast/prediction for the months having the base cost and default percentage for the months.

This is the logic for the loop. January is the starting month, we set there the base $price but next month( February ) should be January * $default_percent,
March should be February * $default_percent etc. all should include corrections.

When it comes to the corrections we got two variables

$percentage = (!empty($modified_percentage)) ? $modified_percentage : $default_percent;
$month_cost = $price * $percentage + $correction_cost;

Percentage can change if outer loop month($m) equals to correction array $month, else its the default value.
Month cost is a basic calculation.

  +----------+---------------+------------+------------+------------+------------+-------------+-------------+-------------+-------------+------------+------------+
  |   jan    |      feb      |    mar     |    apr     |    may     |    june    |    july     |    augu     |    sept     |     oct     |    nov     |    dece    |
  +----------+---------------+------------+------------+------------+------------+-------------+-------------+-------------+-------------+------------+------------+
  | 41290.65 | 41290.65*1.03 | feb * 1.03 | mar * 1.03 | apr * 1.03 | may * 1.03 | june * 1.03 | july * 1.03 | augu * 1.03 | sept * 1.03 | oct * 1.03 | nov * 1.03 |
  +----------+---------------+------------+------------+------------+------------+-------------+-------------+-------------+-------------+------------+------------+

Code snippet

<?PHP
$forecast_correction = array(
    array(
        'month' => '2',
        'add' => 150.00,
        'substract' => 0.00,
        'final' => 150.00,
        'percent' => 1.02
    ),
    array(
        'month' => '3',
        'add' => 0.00,
        'substract' => 250.00,
        'final' => -250.00,
        'percent' => NULL
    ),
    array(
        'month' => '4',
        'add' => 0.00,
        'substract' => 0.00,
        'final' => 0.00,
        'percent' => 0.15
    )
);
$price               = 41290.65;
$default_percent     = 1.03;

for ($m = 1; $m <= 12; ++$m) {
    $correction_cost     = 0;
    $modified_percentage = null;
    foreach ($forecast_correction as $correction) {

        if ($m == $correction['month']) {
            $correction_cost = $correction['final'];
            if (!empty($correction['percent'])) {
                $modified_percentage = $correction['percent'];
            }
        }
    }
    ;
    $percentage = (!empty($modified_percentage)) ? $modified_percentage : $default_percent;
    $month_cost = $price * $percentage + $correction_cost;

    echo date('F', mktime(0, 0, 0, $m, 1)) . " :: $month_cost :: " . $correction_cost . "  :: " . $percentage . "% \n";
}

Question and desired output

Question : How to implement the February = January * percentage logic in this particular example to have all the results properly calculated with the correction array.

Desired output ( can be plain text, array whatever. )

Month : Cost

If you need future clarification don't hesitate to ask, I am quite stuck with this one.

MCVE sandbox

http://sandbox.onlinephpfunctions.com/code/0c705ab721c6160813b98d133d8a1b7ff876cdca

Body:
I think with a couple of minor modifications your example code will do what you want.

I renamed $price to $base_month_cost, where it is initially defined:

$base_month_cost     = 41290.65;

and where it is used to calculate $month_cost in the outer loop:

$month_cost = $base_month_cost * $percentage + $correction_cost;

Then, after the line (above) that calculates $month_cost, I added a new line to redefine $base_month_cost:

$base_month_cost = $month_cost;// set here for use in next iteration

This means that the $month_cost for each successive month is based on the previous month's $month_cost.

You also want to ensure that the no percentage increase is applied when calculating the $month_cost for January. I can think of two approaches to this problem:

You could add January to the $forecast_correction array with a 'percent' value of 1 (so the initial $base_month_cost gets multiplied by 1, and is unchanged).

You could add some additional logic within the for loop, either to set $percentage to 1 if $m == 1, or to do a different calculation of $month_cost, ignoring $percentage if $m == 1.

I think the first approach is cleaner.

Hopefully this is what you're looking for. When I ran it for a test with my modifications, I noticed that the percent value for April is 0.15 in your example, which significantly reduces the $month_cost for that (and successive months).


问:
angular/express api/mongodb update issue
working with a full MEAN stack.
trying to write data to a "notes" array in my mongodb document id #1.

mongo document:

```<code>> db.contacts.find().pretty()
{
"_id" : ObjectId("5a294af85e96746421bf35f1"),
"id" : 1,
"type" : "dealer",
"name" : "ken yoder",
"company" : "kens sales",
"phone" : "817-403-9767",
"notes" : [
    {
        "date" : "Thu Dec 07 2017 08:15:37 GMT-0600 (CST)",
        "by" : "@me",
        "note" : "this is a note"
    },
    {
        "date" : "Thu Dec 07 2017 08:16:31 GMT-0600 (CST)",
        "by" : "@donny",
        "note" : "bla bla bla mumford and sons"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:03 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another note"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:29 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another notey note note"
    }
],
"setNotes" : {
    "date" : "Thu Dec 07 2017 10:52:09 GMT-0600 (CST)",
    "by" : "@kale",
    "note" : "hhsdihufiudhsiuhdshuifds"
}
}
</code>```

express code:

```<code>app.get('/newNote/:noteFor/:noteCount/:noteBy/:note/', function (req, res) {
        var setNotes = "notes."+req.params.noteCount;
        db.collection('contacts').update({ id:req.params.noteFor }, { $set: { setNotes : {date: Date(), by: req.params.noteBy, note: req.params.note} }}, function(err, res) {
                if (err) throw err;
                console.log("notefor: "+req.params.noteFor+" noteCount: "+setNotes+" noteBy: "+req.params.noteBy+" note: "+req.params.note);
                console.log(res.result.nModified + " for " + req.params.noteFor + " updated");
        });
});
</code>```

if i run this code as it sits, i get nothing, no insert, no errors.
- if i change the update id from "req.params.id" to "1", i get an insert but...
- instead of using my "setNotes" variable (which outputs "notes.4") for the $set identifier, it created a new object called "setNotes".

```<code>API URL: /newNote/1/4/@kale/this is a note test
</code>```

答:
first read express api basics, http://expressjs.com/en/4x/api.html. from question  there is noting in req.params.id , instead of id req.params contain four keys (noteFor, noteCount, noteBy and note ). also you override res varible by result of query notice   function(err, res) {.........

```<code> db.collection('contacts').update(
    { id:req.params.id },
    { $set:
        { setNotes : {date: Date(), by: req.params.noteBy, note: req.params.note} }
    },
    {
        // if noting found then stop create new document with values of $set
        upsert:false
        //  result should be updated document
        new:true
    },
    function(err, result) {
        console.log(err, result)
    })
</code>```

Body:
working with a full MEAN stack.
trying to write data to a "notes" array in my mongodb document id #1.

mongo document:

> db.contacts.find().pretty()
{
"_id" : ObjectId("5a294af85e96746421bf35f1"),
"id" : 1,
"type" : "dealer",
"name" : "ken yoder",
"company" : "kens sales",
"phone" : "817-403-9767",
"notes" : [
    {
        "date" : "Thu Dec 07 2017 08:15:37 GMT-0600 (CST)",
        "by" : "@me",
        "note" : "this is a note"
    },
    {
        "date" : "Thu Dec 07 2017 08:16:31 GMT-0600 (CST)",
        "by" : "@donny",
        "note" : "bla bla bla mumford and sons"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:03 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another note"
    },
    {
        "date" : "Thu Dec 07 2017 08:34:29 GMT-0600 (CST)",
        "by" : "@ken",
        "note" : "test with another notey note note"
    }
],
"setNotes" : {
    "date" : "Thu Dec 07 2017 10:52:09 GMT-0600 (CST)",
    "by" : "@kale",
    "note" : "hhsdihufiudhsiuhdshuifds"
}
}

express code:

app.get('/newNote/:noteFor/:noteCount/:noteBy/:note/', function (req, res) {
        var setNotes = "notes."+req.params.noteCount;
        db.collection('contacts').update({ id:req.params.noteFor }, { $set: { setNotes : {date: Date(), by: req.params.noteBy, note: req.params.note} }}, function(err, res) {
                if (err) throw err;
                console.log("notefor: "+req.params.noteFor+" noteCount: "+setNotes+" noteBy: "+req.params.noteBy+" note: "+req.params.note);
                console.log(res.result.nModified + " for " + req.params.noteFor + " updated");
        });
});

if i run this code as it sits, i get nothing, no insert, no errors.
- if i change the update id from "req.params.id" to "1", i get an insert but...
- instead of using my "setNotes" variable (which outputs "notes.4") for the $set identifier, it created a new object called "setNotes".

API URL: /newNote/1/4/@kale/this is a note test

Body:
first read express api basics, http://expressjs.com/en/4x/api.html. from question  there is noting in req.params.id , instead of id req.params contain four keys (noteFor, noteCount, noteBy and note ). also you override res varible by result of query notice   function(err, res) {.........

 db.collection('contacts').update(
    { id:req.params.id },
    { $set:
        { setNotes : {date: Date(), by: req.params.noteBy, note: req.params.note} }
    },
    {
        // if noting found then stop create new document with values of $set
        upsert:false
        //  result should be updated document
        new:true
    },
    function(err, result) {
        console.log(err, result)
    })


问:
Edit source code of Impress odp file
I want to edit the source code of an Impress file (.odp) but when I open it is just machine coded.

I want to do it because when I converted files from PowerPoint to an Impress File some parts got mixed up. Like for example footer and numbering can't be changed globally. So by editing the source code, I hope to be able to use find/replace in a Text Editor.

答:
LibreOffice formats are zipped archives primarily containing XML files.  So unzip the .odp and then edit content.xml.

When finished, zip it back up, making sure to zip it from the correct directory (the one that contains content.xml).

Documentation: https://help.libreoffice.org/Common/XML_File_Formats#XML_file_structure.

Title: Edit source code of Impress odp file


问:
How can I target the src attribute of the img element using jQuery?
You can target an id with jQuery using $("#yourId"), but how can I target the src attribute of the img element since it's not an id. I want to link the api's images link directly.

I have a

var ico = data.weather[0].icon

I want ico in src"" using jquery.

答:
You can use JQuery selectors, http://api.jquery.com/category/selectors/

Here is the sample HTML

```<code><img src='imgUrl'/>
<img src='imgUrl2'/>
<img src='imgUrl3'/>
<img src='notIncluedimgUrl'/>
<ul id ="Result"></ul>
</code>```

And here is the working JQuery

```<code>$(function(){
    $('img[src^="imgUrl"]').each(function(i, e){
    $("#Result").append("<li>" + $(e).prop("src") + "</li>");
  });
});
</code>```

And here is the result:

file:///C:/Users/rcv/Desktop/imgUrl

file:///C:/Users/rcv/Desktop/imgUrl2

file:///C:/Users/rcv/Desktop/imgUrl3

I have uploaded to JSFiddle, so you can run it.

https://jsfiddle.net/j5eyzqr3/1/

Body:
You can use JQuery selectors, http://api.jquery.com/category/selectors/

Here is the sample HTML

<img src='imgUrl'/>
<img src='imgUrl2'/>
<img src='imgUrl3'/>
<img src='notIncluedimgUrl'/>
<ul id ="Result"></ul>

And here is the working JQuery

$(function(){
    $('img[src^="imgUrl"]').each(function(i, e){
    $("#Result").append("<li>" + $(e).prop("src") + "</li>");
  });
});

And here is the result:

file:///C:/Users/rcv/Desktop/imgUrl

file:///C:/Users/rcv/Desktop/imgUrl2

file:///C:/Users/rcv/Desktop/imgUrl3

I have uploaded to JSFiddle, so you can run it.

https://jsfiddle.net/j5eyzqr3/1/


问:
I cant cast in onclicklistener
I have 2 simple different classes that one extends another.
my first class is:

```<code>public class MyObject {}
</code>```

without something in it.

and another:

```<code>public class People extends MyObject{
public  String UserId;

public void setUserId(String userId) {
    UserId = userId;
}

public String getUserId() {
    return UserId;
}
}
</code>```

I was going to cast myobject to people in my adapter and in onBindViewHolder method,and I could do it well and worked,as below:

```<code>   @Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {

        final People people = (People) array.get(position);
        //array is:ArrayList<MyObject> array
        ...}
</code>```

but the problem is when I'm going to do this cast in the same class but in onclicklistener like this:

```<code>holder.rlsearchitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            People people1= (People) savedPeopleArray.get(i);
            //savedPeopleArray is:ArrayList<MyObject> savedPeopleArray
            ....
            }
        });
</code>```

I get this error:

```<code>com.example.qa.setGet.MyObject cannot be cast to com.example.qa.setGet.People
</code>```

why do I get this error even though I used this cast before and it worked?!

答:
The only explanation i could think on why this happening is, you actually have MyObject inside that list, and not People.

Try adding

```<code>if ( savedPeopleArray.get(i) instanceof People )
</code>```

probably you instantiate a MyObject only. At least the only explanation i could think of. How are you filling that list ?

Title: I cant cast in onclicklistener

Body:
I have 2 simple different classes that one extends another.
my first class is:

public class MyObject {}

without something in it.

and another:

public class People extends MyObject{
public  String UserId;

public void setUserId(String userId) {
    UserId = userId;
}

public String getUserId() {
    return UserId;
}
}

I was going to cast myobject to people in my adapter and in onBindViewHolder method,and I could do it well and worked,as below:

   @Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {

        final People people = (People) array.get(position);
        //array is:ArrayList<MyObject> array
        ...}

but the problem is when I'm going to do this cast in the same class but in onclicklistener like this:

holder.rlsearchitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            People people1= (People) savedPeopleArray.get(i);
            //savedPeopleArray is:ArrayList<MyObject> savedPeopleArray
            ....
            }
        });

I get this error:

com.example.qa.setGet.MyObject cannot be cast to com.example.qa.setGet.People

why do I get this error even though I used this cast before and it worked?!

Body:
The only explanation i could think on why this happening is, you actually have MyObject inside that list, and not People.

Try adding

if ( savedPeopleArray.get(i) instanceof People )

probably you instantiate a MyObject only. At least the only explanation i could think of. How are you filling that list ?


问:
Bind Command for MenuItem in DataTemplate without Tag
I want to bind a command in my ViewModel to a menuItem which is in DataTemplate. I can do that with using Tag. Is there any method which can do the same task but without using tag.

```<code><Window.Resources>
    <DataTemplate x:Key="StudentListBoxItemTemplate">
        <StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
            <TextBlock Text="{Binding Name}"/>
            <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Trigger" Command="{Binding PlacementTarget.Tag.TriggerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                </ContextMenu>
            </StackPanel.ContextMenu>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ListBox
        ItemsSource="{Binding StudentList}"
        ItemTemplate="{StaticResource StudentListBoxItemTemplate}">
    </ListBox>
</StackPanel>
</code>```

My ViewModel

```<code>public class MainViewModel {
    public ICommand TriggerCommand { ... }
    public ObservableList<Student> StudentList { ... }
}
</code>```

答:
One way would be to get the context menu collection presentation defined in your viewmodel, which will contain the header string and command action (maybe with predicate).

The viewmodel creates an observable collection of the contextmenu items and the view binds that to ContextMenu itemssource and sets the displaymember path to header string.

ContentLicense: CC BY-SA 2.5

Body:
I want to bind a command in my ViewModel to a menuItem which is in DataTemplate. I can do that with using Tag. Is there any method which can do the same task but without using tag.

<Window.Resources>
    <DataTemplate x:Key="StudentListBoxItemTemplate">
        <StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
            <TextBlock Text="{Binding Name}"/>
            <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Trigger" Command="{Binding PlacementTarget.Tag.TriggerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                </ContextMenu>
            </StackPanel.ContextMenu>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ListBox
        ItemsSource="{Binding StudentList}"
        ItemTemplate="{StaticResource StudentListBoxItemTemplate}">
    </ListBox>
</StackPanel>

My ViewModel

public class MainViewModel {
    public ICommand TriggerCommand { ... }
    public ObservableList<Student> StudentList { ... }
}


问:
How do I hide/show a DIV inside a grid ItemTemplate?
I want to set individual DIVs inside a grid visible/hidden programmatically like so, but it isn't working. How would you fix this code?

```<code>            foreach (DataGridItem dgItem in dgW.Items)
            {

                HtmlGenericControl dvGoodRow =
                    (HtmlGenericControl)dgItem.FindControl("dvGoodRow");
                HtmlGenericControl dvBadRow =
                    (HtmlGenericControl)dgItem.FindControl("dvBadRow");

                dvGoodRow.Visible = true;
                dvBadRow.Visible = false;
            }
</code>```

Debug sessions show that the Visible attribute I set above does take effect at least in my watch window, but visually on the browser I see no change. I have a grid like the one below:

```<code><asp:datagrid id="dgW" AutoGenerateColumns="False" ShowHeader="False" ShowFooter="False" runat="server" DataKeyField="SID" CellPadding="0" GridLines="None" AllowSorting="True" OnItemDataBound="dgW_ItemDataBound">
    <HeaderStyle />
    <FooterStyle>
    </FooterStyle>
    <Columns>
        <asp:TemplateColumn HeaderText="SID" SortExpression="SID">
            <ItemTemplate>
                <asp:Label ID="lblSID" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SID") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="Extension" SortExpression="ExtensionStopDate">
            <ItemTemplate>
                <asp:Label id="lblExtensionStopDate" Runat="server" text='<%# String.Format("{0:MM/dd/yyyy}", DataBinder.Eval(Container.DataItem, "ExtensionStopDate"))%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
            <ItemTemplate>
                <div id="dvGoodRow" runat="server" hidden>
                    <div>
                        <asp:Label runat="server" ID="lblGoodRow">
                            <i id="icnGoodRow" runat="server"></i>
                        </asp:Label>
                    </div>
                </div>
                <div id="dvBadRow" runat="server" hidden>
                    <div>
                        <asp:Label runat="server" ID="lblBadRow">
                            <i id="icnBadRow" runat="server"></i>
                        </asp:Label>
                    </div>
                </div>
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:datagrid>
</code>```

答:
Remove that 'hidden' property and use visible

```<code><div id="dvGoodRow" runat="server" visible="false">

<div id="dvBadRow" runat="server" visible="false">
</code>```

Body:
I want to set individual DIVs inside a grid visible/hidden programmatically like so, but it isn't working. How would you fix this code?

            foreach (DataGridItem dgItem in dgW.Items)
            {

                HtmlGenericControl dvGoodRow =
                    (HtmlGenericControl)dgItem.FindControl("dvGoodRow");
                HtmlGenericControl dvBadRow =
                    (HtmlGenericControl)dgItem.FindControl("dvBadRow");

                dvGoodRow.Visible = true;
                dvBadRow.Visible = false;
            }

Debug sessions show that the Visible attribute I set above does take effect at least in my watch window, but visually on the browser I see no change. I have a grid like the one below:

<asp:datagrid id="dgW" AutoGenerateColumns="False" ShowHeader="False" ShowFooter="False" runat="server" DataKeyField="SID" CellPadding="0" GridLines="None" AllowSorting="True" OnItemDataBound="dgW_ItemDataBound">
    <HeaderStyle />
    <FooterStyle>
    </FooterStyle>
    <Columns>
        <asp:TemplateColumn HeaderText="SID" SortExpression="SID">
            <ItemTemplate>
                <asp:Label ID="lblSID" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SID") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn HeaderText="Extension" SortExpression="ExtensionStopDate">
            <ItemTemplate>
                <asp:Label id="lblExtensionStopDate" Runat="server" text='<%# String.Format("{0:MM/dd/yyyy}", DataBinder.Eval(Container.DataItem, "ExtensionStopDate"))%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
            </FooterTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
            <ItemTemplate>

                        <asp:Label runat="server" ID="lblGoodRow">

                        </asp:Label>

                        <asp:Label runat="server" ID="lblBadRow">

                        </asp:Label>

            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:datagrid>

Body:
Remove that 'hidden' property and use visible

<div id="dvGoodRow" runat="server" visible="false">

<div id="dvBadRow" runat="server" visible="false">


问:
create_Task(): The application called an interface that was marshalled for a different thread
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

```<code>auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });
</code>```

The postOptimation routine includes the line:

```<code>backwordCheckBox->IsChecked = params->backwards;
</code>```

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks

答:
Good suggestion from Sornel!  Here's what worked:

Code inside postOptimation:

```<code>Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
    ref new Windows::UI::Core::DispatchedHandler([this]()
{

    backwordCheckBox->IsChecked = params->backwards;

}));
</code>```

Body:
I have a UWP UI that calls native code that takes a while to execute.  Upon completion, the UI needs updating.  This is my code:

auto runOpti = create_task([this] { runOptimation(); });
runOpti.then([this]{postOptimation(); });

The postOptimation routine includes the line:

backwordCheckBox->IsChecked = params->backwards;

Executing this like gives the error in the title.

How do I get the postOptimation to run in the UI thread?

Thanks

Body:
Good suggestion from Sornel!  Here's what worked:

Code inside postOptimation:

Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High,
    ref new Windows::UI::Core::DispatchedHandler([this]()
{

    backwordCheckBox->IsChecked = params->backwards;

}));


问:
Why do dates change in DATEDIF when I add a new row o data?
I am trying to create an athlete database, using input from the athletes, via a Google Form, which links to a spreadsheet.

Each question on the form corresponds to a matching column on the spreadsheet. Apart from the fact that I don't seem to be able to direct replies directly into the spreadsheet (they appear in a separate sheet) everything works acceptably...

However - and there's always a however - I want the athlete's Date of Birth to generate their current age, so I include another column, which - using DATEDIF - gives this figure.

The column isn't on the form, so I have to create it separately for each new entry - currently well over 700 athletes on the database and more to come.

Here's my problem... I have manually linked the DATEDIF formula for every single athlete, using their DoB cell and the A1 cell as TODAY. They all work.

Until I add another entry. Then, below that new entry, although DATEDIF seems able to keep track of the DoB cell for every athlete displaced by the new row, it also adds a row to TODAY, so A1 becomes A2, A3 if there are two new entries, and so on.

Rather than making every single cell in column A into TODAY, is there a way to apply the DATEDIF formula to stop changing A1 as my reference?

This is the formula I am using: =DATEDIF(H2,A1,"Y") my dates are all in dd/mm/yyyy format. The athlete DoBs are all in column H, TODAY is always A1...

This is so far above my head, I seem to have created a beast that I cannot tame, other than by inserting new rows and then re-pointing hundreds of DATEDIF formulae to the correct TODAY cell. And life is too short for that!

Any help greatly appreciated...

答:
Short answer

Use

=DATEDIF(H2,$A$1,"Y") or

=DATEDIF(H2,TODAY(),"Y")

Explanation

Google Sheets references could be relative or absolute. A1 is a relative reference, $A$1 is an absolute reference.

By the other hand, you could use a function as a function parameter.


问:
dplyr: want to add only 1 y column during a join, not all y columns
I need to join a table with itself in order to realize inheritance of a value in one column, as follows:
There are two types of rows, base and dep (for "dependent").
All rows have a key, but dep rows also have a basekey referring to a base row. There is a column val and any number of other columns.

My goal: Obtain all dep rows, with their val replaced by the val of the corresponding base row.

Here is an example:

```<code>library(tidyverse)

tb = tribble(
    ~key, ~type, ~basekey, ~val, ~col5, ~colN,
    "a", "base", NA,       17,   1,      100,
    "b", "base", NA,       21,   4,      130,
    "d", "dep",  "a",      NA,   11,     320,
    "g", "dep",  "a",      NA,   14,     420,
    "n", "dep",  "a",      NA,   13,     230,
    "y", "dep",  "b",      NA,   66,     665
)
</code>```

My actual data has a few hundred rows and N=20 columns, so runtime or memory performance is not an issue, but operations requiring a complete column list should be avoided.

sqldf

Previously, I used the sqldf package, which can express my requirement nicely:

```<code>sqldf("select tb.*, tb2.val as baseval
       from tb, tb as tb2
       where tb2.key = tb.basekey")
</code>```

The result is almost exactly what I want; I only need to map baseval to val or live with the longer name (which is OK for me):

```<code>  key type basekey val col5 colN baseval
1   d  dep       a  NA   11  320      17
2   g  dep       a  NA   14  420      17
3   n  dep       a  NA   13  230      17
4   y  dep       b  NA   66  665      21
</code>```

dplyr

But then I started learning ggplot2 and encountered the tidyverse.
After some reading, I decided to throw myself into its arms and rework my code according to its readable and tidy style.

readr and tibble worked like a charm, but with dplyr I am not yet entirely happy; my use case appears to be one that is not supported well (maybe it's just that my thinking is not taking the best route yet).

I need to do a left join, but although all I want is the val column, there appears to be no method (as of dplyr 0.7.4) for suppressing the others:

```<code>tbj = left_join(filter(tb, type=='dep'), tb, by=c(basekey='key'))
</code>```

which gives me this:

```<code># A tibble: 4 x 11
    key type.x basekey val.x col5.x colN.x type.y basekey.y val.y col5.y colN.y
  <chr>  <chr>   <chr> <dbl>  <dbl>  <dbl>  <chr>     <chr> <dbl>  <dbl>  <dbl>
1     d    dep       a    NA     11    320   base      <NA>    17      1    100
2     g    dep       a    NA     14    420   base      <NA>    17      1    100
3     n    dep       a    NA     13    230   base      <NA>    17      1    100
4     y    dep       b    NA     66    665   base      <NA>    21      4    130
</code>```

Whew! To get what I want, I now need to

Map val.y to val.

Kick out all the other *.y columns

Kick out val.x

Rename the other *.x columns to remove the suffix

This sounds laborious.
How to do it best?
Is this even the right approach or is there a more dplyr-ish way to achieve my goal?

答:
If I understand your question, how about the following approach with dplyr: Remove val from the dep subset, since it's empty anyway. Then, keep only key and val in the base subset, rename key to basekey and join. Then post-join renaming isn't needed and you don't get any extra columns.

```<code>tb %>%
  filter(type=="dep") %>% select(-val) %>%
  left_join(tb %>% filter(type=="base") %>% select(basekey=key, val))
</code>```

```<code>    key  type basekey  col5  colN   val
  <chr> <chr>   <chr> <dbl> <dbl> <dbl>
1     d   dep       a    11   320    17
2     g   dep       a    14   420    17
3     n   dep       a    13   230    17
4     y   dep       b    66   665    21
</code>```

Body:
I need to join a table with itself in order to realize inheritance of a value in one column, as follows:
There are two types of rows, base and dep (for "dependent").
All rows have a key, but dep rows also have a basekey referring to a base row. There is a column val and any number of other columns.

My goal: Obtain all dep rows, with their val replaced by the val of the corresponding base row.

Here is an example:

library(tidyverse)

tb = tribble(
    ~key, ~type, ~basekey, ~val, ~col5, ~colN,
    "a", "base", NA,       17,   1,      100,
    "b", "base", NA,       21,   4,      130,
    "d", "dep",  "a",      NA,   11,     320,
    "g", "dep",  "a",      NA,   14,     420,
    "n", "dep",  "a",      NA,   13,     230,
    "y", "dep",  "b",      NA,   66,     665
)

My actual data has a few hundred rows and N=20 columns, so runtime or memory performance is not an issue, but operations requiring a complete column list should be avoided.

sqldf

Previously, I used the sqldf package, which can express my requirement nicely:

sqldf("select tb.*, tb2.val as baseval
       from tb, tb as tb2
       where tb2.key = tb.basekey")

The result is almost exactly what I want; I only need to map baseval to val or live with the longer name (which is OK for me):

  key type basekey val col5 colN baseval
1   d  dep       a  NA   11  320      17
2   g  dep       a  NA   14  420      17
3   n  dep       a  NA   13  230      17
4   y  dep       b  NA   66  665      21

dplyr

But then I started learning ggplot2 and encountered the tidyverse.
After some reading, I decided to throw myself into its arms and rework my code according to its readable and tidy style.

readr and tibble worked like a charm, but with dplyr I am not yet entirely happy; my use case appears to be one that is not supported well (maybe it's just that my thinking is not taking the best route yet).

I need to do a left join, but although all I want is the val column, there appears to be no method (as of dplyr 0.7.4) for suppressing the others:

tbj = left_join(filter(tb, type=='dep'), tb, by=c(basekey='key'))

which gives me this:

# A tibble: 4 x 11
    key type.x basekey val.x col5.x colN.x type.y basekey.y val.y col5.y colN.y
  <chr>  <chr>   <chr> <dbl>  <dbl>  <dbl>  <chr>     <chr> <dbl>  <dbl>  <dbl>
1     d    dep       a    NA     11    320   base      <NA>    17      1    100
2     g    dep       a    NA     14    420   base      <NA>    17      1    100
3     n    dep       a    NA     13    230   base      <NA>    17      1    100
4     y    dep       b    NA     66    665   base      <NA>    21      4    130

Whew! To get what I want, I now need to

Map val.y to val.

Kick out all the other *.y columns

Kick out val.x

Rename the other *.x columns to remove the suffix

This sounds laborious.
How to do it best?
Is this even the right approach or is there a more dplyr-ish way to achieve my goal?

Body:
If I understand your question, how about the following approach with dplyr: Remove val from the dep subset, since it's empty anyway. Then, keep only key and val in the base subset, rename key to basekey and join. Then post-join renaming isn't needed and you don't get any extra columns.

tb %>%
  filter(type=="dep") %>% select(-val) %>%
  left_join(tb %>% filter(type=="base") %>% select(basekey=key, val))

    key  type basekey  col5  colN   val
  <chr> <chr>   <chr> <dbl> <dbl> <dbl>
1     d   dep       a    11   320    17
2     g   dep       a    14   420    17
3     n   dep       a    13   230    17
4     y   dep       b    66   665    21


问:
Using VC++ 10 Compiler with Visual Studio 2005
I've just installed Windows SDK 7.1. It also came with VC++ 10 Compiler but I have installed Visual Studio 2005. Does that mean i can integrate it with Visual Studio 2005 Or Do I need Visual Studio 2010 IDE?</p>

答: No, VS2010 came with SDK version 7.0A.  The installer for 7.1 should automatically make it use the version.  But I'm fairly sure that won't happen for VS2005.  I think, it's been a while since I used a machine that had it installed.  You can set the directories it searches with Tools + Options, Projects and Solutions, VC++ Directories.  I wouldn't do this myself btw, not much point in installing an old version unless to maintain old projects.</p>


问:
Programmatically navigate using React router
With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls this.context.transitionTo(...).

I want to do a navigation. Not from a link, but from a dropdown selection (as an example). How can I do this in code? What is this.context?

I saw the Navigation mixin, but can I do this without mixins?

答:
Maybe not the best solution, but it gets the job done:

import { Link } from 'react-router-dom';

// Create functional component Post
export default Post = () => (

        <button className="button delete-post" onClick={() => {
            // ... delete post
            // then redirect, without page reload, by triggering a hidden Link
            document.querySelector('.trigger.go-home').click();
        }}>Delete Post</button>

        <Link to="/" className="trigger go-home hidden"></Link>

);
```

Basically, logic tied to one action (in this case a post deletion) will end up calling a trigger for redirect. This is not ideal, because you will add a DOM node 'trigger' to your markup just so you can conveniently call it when needed. Also, you will directly interact with the DOM, which in a React component may not be desired.

Still, this type of redirect is not required that often. So one or two extra, hidden links in your component markup would not hurt that much, especially if you give them meaningful names.

ContentLicense: CC BY-SA 4.0

Body:
Maybe not the best solution, but it gets the job done:

import { Link } from 'react-router-dom';

// Create functional component Post
export default Post = () => (
    <div className="component post">

        <button className="button delete-post" onClick={() => {
            // ... delete post
            // then redirect, without page reload, by triggering a hidden Link
            document.querySelector('.trigger.go-home').click();
        }}>Delete Post</button>

        <Link to="/" className="trigger go-home hidden"></Link>

    </div>
);

Basically, logic tied to one action (in this case a post deletion) will end up calling a trigger for redirect. This is not ideal, because you will add a DOM node 'trigger' to your markup just so you can conveniently call it when needed. Also, you will directly interact with the DOM, which in a React component may not be desired.

Still, this type of redirect is not required that often. So one or two extra, hidden links in your component markup would not hurt that much, especially if you give them meaningful names.


问:
tel: & callto html not working with iphone for service numbers like *000#
Hi I'm trying to make mobile website that contains service link as the following:

```<code><a href="tel:*000#">*000#</a>
</code>```

I tried to encode the special characters & htmlentetries with no results, The call box appears but there is no action after you click call.

答:
From Apple's documentation:

To prevent users from maliciously redirecting phone calls or changing the behavior of a phone or account, the Phone app supports most, but not all, of the special characters in the tel scheme. Specifically, if a URL contains the * or # characters, the Phone app does not attempt to dial the corresponding phone number.

https://developer.apple.com/library/content/featuredarticles/iPhoneURLScheme_Reference/PhoneLinks/PhoneLinks.html

Body:
Hi I'm trying to make mobile website that contains service link as the following:

*000#

I tried to encode the special characters & htmlentetries with no results, The call box appears but there is no action after you click call.


问:
Ext. news: get news id in controller
I want to place a new plugin (from own extension) on the news detail page, which shows me news from related categories.

My problem is: How to get the news id in my new plugin controller.

```<code>$arguments = $this->request->getArguments();
</code>```

does not work.

Has anybody an idea?

答: You need to use GeneralUtility::_GET for that </p>

Title: Ext. news: get news id in controller

Body:
I want to place a new plugin (from own extension) on the news detail page, which shows me news from related categories.

My problem is: How to get the news id in my new plugin controller.

$arguments = $this->request->getArguments();

does not work.

Has anybody an idea?


问:
Is it safe using `$` as an identifier in C/C++?
Is it safe to use $ character as part of identifier in C/C++?
Like this,

```<code>int $a = 10;
struct $b;
class $c;

void $d();
</code>```

答: No; it is a non-standard extension in some compilers.</p>

Body:
Is it safe to use $ character as part of identifier in C/C++?
Like this,

int $a = 10;
struct $b;
class $c;

void $d();


问:
How can i save json data in mongoose
This is my json data I want to save it in a mongoose database but I am confused how to design my mongoose schema.

data is { 'posts[0][commentId]': '0',
  'posts[0][id]': '1',
  'posts[0][postName]': 'hi',
  'posts[0][img]': '',
  'posts[0][postBy]': ' Neeraj',
  'posts[1][commentId]': '0',
  'posts[1][id]': '2',
  'posts[1][postName]': 'hii',
  'posts[1][img]': '',
  'posts[1][postBy]': ' Neeraj',
  'posts[1][comments][0][commentId]': '1',
  'posts[1][comments][0][commentValue]': 'hlo how are u???',
  'posts[1][comments][0][commentBy]': ' Neeraj',
  'posts[1][comments][0][upCounter]': '5',
  'posts[1][comments][0][downCounter]': '6' }```
</div>
</div>
</p>

<p>this is my Post schema but i dont know how to actually design it.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var postSchema=new Schema({
    posts:[{
         commentId:  Number ,

    comments : [{
      commentBy : String,
        commentId  : String,
        commentValue:String,
        date:Date,
        downCounter:Number,
        upCounter:Number
    }],
id:String,
img:String,
postBy:String,
postDate:Date,
postName:String
}]
});</code>```

答:
You can store JSON to database directly:</p>

```<code>var post_schema = mongoose.Schema({data : JSON});
var post_model = mongoose.model('collection_name', post_schema);

var newData = new post_model({data : <json_object>});

//saving json schema to mongodb

newData.save(function(err){
    if (err) {
               throw err;
    }
    console.log('INSERTED!');
});
</code>```

Title: How can i save json data in mongoose

Body:
This is my json data I want to save it in a mongoose database but I am confused how to design my mongoose schema.

data is { 'posts[0][commentId]': '0',
  'posts[0][id]': '1',
  'posts[0][postName]': 'hi',
  'posts[0][img]': '',
  'posts[0][postBy]': ' Neeraj',
  'posts[1][commentId]': '0',
  'posts[1][id]': '2',
  'posts[1][postName]': 'hii',
  'posts[1][img]': '',
  'posts[1][postBy]': ' Neeraj',
  'posts[1][comments][0][commentId]': '1',
  'posts[1][comments][0][commentValue]': 'hlo how are u???',
  'posts[1][comments][0][commentBy]': ' Neeraj',
  'posts[1][comments][0][upCounter]': '5',
  'posts[1][comments][0][downCounter]': '6' }

this is my Post schema but i dont know how to actually design it.

var postSchema=new Schema({
    posts:[{
         commentId:  Number ,

    comments : [{
      commentBy : String,
        commentId  : String,
        commentValue:String,
        date:Date,
        downCounter:Number,
        upCounter:Number
    }],
id:String,
img:String,
postBy:String,
postDate:Date,
postName:String
}]
});

Body:
You can store JSON to database directly:

var post_schema = mongoose.Schema({data : JSON});
var post_model = mongoose.model('collection_name', post_schema);

var newData = new post_model({data : <json_object>});

//saving json schema to mongodb

newData.save(function(err){
    if (err) {
               throw err;
    }
    console.log('INSERTED!');
});


问:
Login change in to signup
I have created a HTML5 registration form,is it possible for it to check the email address(inserted first) if it's already used to ask only for password(login) and if it's not to insert other fields needed for signup? using php,js or others.</p>

答:
```<code>  <form id="signin_student" class="form-signin" method="post">
        <h3 class="form-signin-heading"><i class="icon-lock"></i> Register </h3>
        <input type="text" class="input-block-level" id="username" name="username" placeholder="NISN" required>
        <input type="text" class="input-block-level" id="firstname" name="firstname" placeholder="Nama Depan" required>
        <input type="text" class="input-block-level" id="lastname" name="lastname" placeholder="Nama Belakang" required>
        <label>Kelas</label>
        <select name="class_id" class="input-block-level span5">
            <option>Pilih Kelas</option>
            <?php
            $query = mysql_query("select * from class order by class_name ")or die(mysql_error());
            while($row = mysql_fetch_array($query)){
            ?>
            <option value="<?php  echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
            <?php
            }
            ?>
        </select>
        <input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
        <input type="password" class="input-block-level" id="cpassword" name="cpassword" placeholder="Tulis Ulang Password" required>
        <button title="Klik untuk Daftar" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-check icon-large"></i> Daftar</button>
        </form>

  <script>
        jQuery(document).ready(function(){
        jQuery("#signin_student").submit(function(e){
                e.preventDefault();

                    var password = jQuery('#password').val();
                    var cpassword = jQuery('#cpassword').val();

                if (password == cpassword){
                var formData = jQuery(this).serialize();
                $.ajax({
                    type: "POST",
                    url: "student_signup.php",
                    data: formData,
                    success: function(html){
                    if(html=='true')
                    {

                    var delay = 2000;
                        setTimeout(function(){ window.location = 'siswa/index.php'  }, delay);
                    }else if(html=='false'){
                        { header: 'Data in DB is Not Found' });
                    }
                    }

                });

                }else
                    {
                    $.jGrowl("student does not found in the database", { header: 'Sign Up Failed' });
                    }
            });
        });
        </script>
</code>```

and file signup.php

```<code>    <?php
     mysql_select_db('db',mysql_connect('localhost','root',''))or die(mysql_error());
            session_start();
            $username = $_POST['username'];
            $password = $_POST['password'];
            $firstname = $_POST['firstname'];
            $lastname = $_POST['lastname'];
            $class_id = $_POST['class_id'];

            $query = mysql_query("select * from student where username='$username' and firstname='$firstname' and lastname='$lastname' and class_id = '$class_id'")or die(mysql_error());
            $row = mysql_fetch_array($query);
            $id = $row['student_id'];

            $count = mysql_num_rows($query);
            if ($count > 0){
                mysql_query("update student set password = '$password', status = 'Registered' where student_id = '$id'")or die(mysql_error());
                $_SESSION['id']=$id;
                echo 'true';
            }else{
            echo 'false';
            }
            ?>
</code>```

Title: Login change in to signup

Body:
  <form id="signin_student" class="form-signin" method="post">
        <h3 class="form-signin-heading"><i class="icon-lock"></i> Register </h3>
        <input type="text" class="input-block-level" id="username" name="username" placeholder="NISN" required>
        <input type="text" class="input-block-level" id="firstname" name="firstname" placeholder="Nama Depan" required>
        <input type="text" class="input-block-level" id="lastname" name="lastname" placeholder="Nama Belakang" required>
        <label>Kelas</label>
        <select name="class_id" class="input-block-level span5">
            <option>Pilih Kelas</option>
            <?php
            $query = mysql_query("select * from class order by class_name ")or die(mysql_error());
            while($row = mysql_fetch_array($query)){
            ?>
            <option value="<?php  echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
            <?php
            }
            ?>
        </select>
        <input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
        <input type="password" class="input-block-level" id="cpassword" name="cpassword" placeholder="Tulis Ulang Password" required>
        <button title="Klik untuk Daftar" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-check icon-large"></i> Daftar</button>
        </form>

  <script>
        jQuery(document).ready(function(){
        jQuery("#signin_student").submit(function(e){
                e.preventDefault();

                    var password = jQuery('#password').val();
                    var cpassword = jQuery('#cpassword').val();

                if (password == cpassword){
                var formData = jQuery(this).serialize();
                $.ajax({
                    type: "POST",
                    url: "student_signup.php",
                    data: formData,
                    success: function(html){
                    if(html=='true')
                    {

                    var delay = 2000;
                        setTimeout(function(){ window.location = 'siswa/index.php'  }, delay);
                    }else if(html=='false'){
                        { header: 'Data in DB is Not Found' });
                    }
                    }

                });

                }else
                    {
                    $.jGrowl("student does not found in the database", { header: 'Sign Up Failed' });
                    }
            });
        });
        </script>

and file signup.php

    <?php
     mysql_select_db('db',mysql_connect('localhost','root',''))or die(mysql_error());
            session_start();
            $username = $_POST['username'];
            $password = $_POST['password'];
            $firstname = $_POST['firstname'];
            $lastname = $_POST['lastname'];
            $class_id = $_POST['class_id'];

            $query = mysql_query("select * from student where username='$username' and firstname='$firstname' and lastname='$lastname' and class_id = '$class_id'")or die(mysql_error());
            $row = mysql_fetch_array($query);
            $id = $row['student_id'];

            $count = mysql_num_rows($query);
            if ($count > 0){
                mysql_query("update student set password = '$password', status = 'Registered' where student_id = '$id'")or die(mysql_error());
                $_SESSION['id']=$id;
                echo 'true';
            }else{
            echo 'false';
            }
            ?>


问:
Set class to active on additional li elements upon navbar click
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

```<code>$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>

</ul>
</code>```

Now I have similar items at the top of the page presented as a connected circle:

```<code><div class="connected-line">
  <ul>
    <li class="active">1
      <p> System </p>
    </li>
    <li id="hosts">2
      <p> Hosts </p>
    </li>
    <li>3
      <p> Cards </p>
    </li>
    <li>4
      <p> Devices </p>
    </li>
  </ul>
</div>
</code>```

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

答:
It is best not you have two elements with the same id attribute.  This is because native functions such as getElementById will never be able to select the second instance of the element with that id.

That being said to get your demo to work I changed the js to use classes instead of ids on the second set of elements.  This can be achieved in many other ways as well:

```<code>$(document).ready(function() {
  $(".nav li").click(function() {
    $('li').removeClass("active");
    $(this).removeClass("active");
    $(this).addClass("active");
    const clickedId = $(this).children()[0].id;
    $(`.${clickedId}`).addClass('active');
  });
});
</code>```

and then in the html

```<code><div class="connected-line">
  <ul>
    <li class="system-settings">1
      <p> System </p>
    </li>
    <li class="hosts">2
      <p> Hosts </p>
    </li>
    <li class="card-range">3
      <p> Cards </p>
    </li>
    <li class="pinpads">4
      <p> Devices </p>
    </li>
    <li class="xmls">5
      <p> Lanes </p>
    </li>
  </ul>
</div>

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>
</ul>
</code>```

Body:
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

    System Settings

    Hosts

    Cards

    Printer

    Pinpad

Now I have similar items at the top of the page presented as a connected circle:

1

 System

2

 Hosts

3

 Cards

4

 Devices

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

Body:
It is best not you have two elements with the same id attribute.  This is because native functions such as getElementById will never be able to select the second instance of the element with that id.

That being said to get your demo to work I changed the js to use classes instead of ids on the second set of elements.  This can be achieved in many other ways as well:

$(document).ready(function() {
  $(".nav li").click(function() {
    $('li').removeClass("active");
    $(this).removeClass("active");
    $(this).addClass("active");
    const clickedId = $(this).children()[0].id;
    $(`.${clickedId}`).addClass('active');
  });
});

and then in the html

<div class="connected-line">
  <ul>
    <li class="system-settings">1
      <p> System </p>
    </li>
    <li class="hosts">2
      <p> Hosts </p>
    </li>
    <li class="card-range">3
      <p> Cards </p>
    </li>
    <li class="pinpads">4
      <p> Devices </p>
    </li>
    <li class="xmls">5
      <p> Lanes </p>
    </li>
  </ul>
</div>

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>
</ul>


问:
google cloud libs not working on Colaboratory
I wanted to test some code interacting with GCS that I have running locally today. My plan is to:

save a service account JSON file in GDrive

download it to Colaboratory's 'local' /tmp

!export GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>

storage_client = storage.Client('my-project')
and play with different methods / properties.

I installed !pip install --upgrade google-cloud but when testing bullet 4 (expecting an authentication error), I get a message re dependencies issues:

```<code>ContextualVersionConflictTraceback (most recent call last)
<ipython-input-13-7346ac058842> in <module>()
----> 1 from google.cloud import storage
  2
  3
  4 # Authenticate to GCS.
  5 from google.colab import auth

/usr/local/lib/python2.7/dist-packages/google/cloud/storage/__init__.py in <module>()
 33
 34 from pkg_resources import get_distribution
---> 35 __version__ = get_distribution('google-cloud-storage').version
 36
 37 from google.cloud.storage.batch import Batch

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in get_distribution(dist)
554         dist = Requirement.parse(dist)
555     if isinstance(dist, Requirement):
--> 556         dist = get_provider(dist)
557     if not isinstance(dist, Distribution):
558         raise TypeError("Expected string, Requirement, or Distribution", dist)

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in get_provider(moduleOrReq)
428     """Return an IResourceProvider for the named module or requirement"""
429     if isinstance(moduleOrReq, Requirement):
--> 430         return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
431     try:
432         module = sys.modules[moduleOrReq]

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in require(self, *requirements)
970         included, even if they were already activated in this working set.
971         """
--> 972         needed = self.resolve(parse_requirements(requirements))
973
974         for dist in needed:

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in resolve(self, requirements, env, installer, replace_conflicting, extras)
861                 # Oops, the "best" so far conflicts with a dependency
862                 dependent_req = required_by[req]
--> 863                 raise VersionConflict(dist, req).with_context(dependent_req)
864
865             # push the new requirements onto the stack

ContextualVersionConflict: (google-cloud-core 0.27.1 (/usr/local/lib/python2.7/dist-packages), Requirement.parse('google-cloud-core<0.29dev,>=0.28.0'), set(['google-cloud-storage']))
</code>```

I have not tried in Datalab but Colaboratory is so much more convenient.

答:
So there are two issues/questions here:

Can I use service account credentials? I suspect things will just work, but you're getting tripped up by something else first.

Why am I getting an error importing google.cloud.storage? The issue here is the following: we load some subset of google.cloud libraries at startup. You then do an upgrade, and attempt to load the newly installed libraries, which are conflicting with the ones already loaded.

The quickest fix is to just restart your kernel after installation (ctrl-m .), at which point things should load just fine.

Body:
I wanted to test some code interacting with GCS that I have running locally today. My plan is to:

save a service account JSON file in GDrive

download it to Colaboratory's 'local' /tmp

!export GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>

storage_client = storage.Client('my-project')
and play with different methods / properties.

I installed !pip install --upgrade google-cloud but when testing bullet 4 (expecting an authentication error), I get a message re dependencies issues:

ContextualVersionConflictTraceback (most recent call last)
<ipython-input-13-7346ac058842> in <module>()
----> 1 from google.cloud import storage
  2
  3
  4 # Authenticate to GCS.
  5 from google.colab import auth

/usr/local/lib/python2.7/dist-packages/google/cloud/storage/__init__.py in <module>()
 33
 34 from pkg_resources import get_distribution
---> 35 __version__ = get_distribution('google-cloud-storage').version
 36
 37 from google.cloud.storage.batch import Batch

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in get_distribution(dist)
554         dist = Requirement.parse(dist)
555     if isinstance(dist, Requirement):
--> 556         dist = get_provider(dist)
557     if not isinstance(dist, Distribution):
558         raise TypeError("Expected string, Requirement, or Distribution", dist)

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in get_provider(moduleOrReq)
428     """Return an IResourceProvider for the named module or requirement"""
429     if isinstance(moduleOrReq, Requirement):
--> 430         return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
431     try:
432         module = sys.modules[moduleOrReq]

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in require(self, *requirements)
970         included, even if they were already activated in this working set.
971         """
--> 972         needed = self.resolve(parse_requirements(requirements))
973
974         for dist in needed:

/usr/lib/python2.7/dist-packages/pkg_resources/__init__.pyc in resolve(self, requirements, env, installer, replace_conflicting, extras)
861                 # Oops, the "best" so far conflicts with a dependency
862                 dependent_req = required_by[req]
--> 863                 raise VersionConflict(dist, req).with_context(dependent_req)
864
865             # push the new requirements onto the stack

ContextualVersionConflict: (google-cloud-core 0.27.1 (/usr/local/lib/python2.7/dist-packages), Requirement.parse('google-cloud-core<0.29dev,>=0.28.0'), set(['google-cloud-storage']))

I have not tried in Datalab but Colaboratory is so much more convenient.


问:
send parameter through before_action
I am using a before action to execute an action called "can_accede" (this is in my aplication_controller) before accessing my index view, this action will look for a record to verify if the user can access my index view, but I need to send a parameter to that action to know what record to look for.

this is my "can_accede" action

```<code>def can_accede
  @can_accede = current_usuario.try(:perfiles).find_by_Descripcion(params[:Module_name]).try(:Listar)
  if @can_accede != true
    redirect_to root_path, alert: "you don't have permission."
  end
end
</code>```

this is my before_action:

```<code>before_action :can_accede, only: [:index]
</code>```

it is possible to send to the action can_accede through the before_action a parameter param [: Module_name]?

答:
The params object will be available in the method, so you can simply call params[:whatever] in can_accede.

FWIW, you should look into an authorization gem to unify your methods of authorization. Pundit and CanCanCan are good options.

Title: send parameter through before_action

Body:
I am using a before action to execute an action called "can_accede" (this is in my aplication_controller) before accessing my index view, this action will look for a record to verify if the user can access my index view, but I need to send a parameter to that action to know what record to look for.

this is my "can_accede" action

def can_accede
  @can_accede = current_usuario.try(:perfiles).find_by_Descripcion(params[:Module_name]).try(:Listar)
  if @can_accede != true
    redirect_to root_path, alert: "you don't have permission."
  end
end

this is my before_action:

before_action :can_accede, only: [:index]

it is possible to send to the action can_accede through the before_action a parameter param [: Module_name]?


问:
Why is processing a sorted array faster than processing an unsorted array?
In this C++ code, sorting the data (before the timed region) makes the primary loop ~6x faster:

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster.
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;
    for (unsigned i = 0; i < 100000; ++i)
    {
        for (unsigned c = 0; c < arraySize; ++c)
        {   // Primary loop.
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    double elapsedTime = static_cast<double>(clock()-start) / CLOCKS_PER_SEC;

    std::cout << elapsedTime << '\n';
    std::cout << "sum = " << sum << '\n';
}
```
<ul>
<li>Without <code>std::sort(data, data + arraySize);</code>, the code runs in 11.54 seconds.</li>
<li>With the sorted data, the code runs in 1.93 seconds.</li>
</ul>
<p>(Sorting itself takes more time than this one pass over the array, so it's not actually worth doing if we needed to calculate this for an unknown array.)</p>
<hr />
<p>Initially, I thought this might be just a language or compiler anomaly, so I tried Java:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.Random;

public class Main
{
    public static void main(String[] args)
    {
        // Generate data
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;

        // !!! With this, the next loop runs faster
        Arrays.sort(data);

        // Test
        long start = System.nanoTime();
        long sum = 0;
        for (int i = 0; i < 100000; ++i)
        {
            for (int c = 0; c < arraySize; ++c)
            {   // Primary loop.
                if (data[c] >= 128)
                    sum += data[c];
            }
        }

        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);
    }
}
</code>```

With a similar but less extreme result.

My first thought was that sorting brings the data into the cache, but that's silly because the array was just generated.

What is going on?

Why is processing a sorted array faster than processing an unsorted array?

The code is summing up some independent terms, so the order should not matter.

Related / follow-up Q&As about the same effect with different/later compilers and options:

Why is processing an unsorted array the same speed as processing a sorted array with modern x86-64 clang?

gcc optimization flag -O3 makes code slower than -O2

答:
Sorted arrays are processed faster than an unsorted array, due to a phenomena called branch prediction.

The branch predictor is a digital circuit (in computer architecture) trying to predict which way a branch will go, improving the flow in the instruction pipeline. The circuit/computer predicts the next step and executes it.

Making a wrong prediction leads to going back to the previous step, and executing with another prediction. Assuming the prediction is correct, the code will continue to the next step. A wrong prediction results in repeating the same step, until a correct prediction occurs.

The answer to your question is very simple.

In an unsorted array, the computer makes multiple predictions, leading to an increased chance of errors.
Whereas, in a sorted array, the computer makes fewer predictions, reducing the chance of errors.
Making more predictions requires more time.

Sorted Array: Straight Road

____________________________________________________________________________________
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
```
<p>Unsorted Array: Curved Road</p>
```______   ________
|     |__|
```
<p>Branch prediction: Guessing/predicting which road is straight and following it without checking</p>
```___________________________________________ Straight road
 |_________________________________________|Longer road
```

Although both the roads reach the same destination, the straight road is shorter, and the other is longer. If then you choose the other by mistake, there is no turning back, and so you will waste some extra time if you choose the longer road. This is similar to what happens in the computer, and I hope this helped you understand better.

Also I want to cite @Simon_Weaver from the comments:

It doesn’t make fewer predictions - it makes fewer incorrect predictions. It still has to predict for each time through the loop...

Body:
In this C++ code, sorting the data (before the timed region) makes the primary loop ~6x faster:

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster.
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;
    for (unsigned i = 0; i < 100000; ++i)
    {
        for (unsigned c = 0; c < arraySize; ++c)
        {   // Primary loop.
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    double elapsedTime = static_cast<double>(clock()-start) / CLOCKS_PER_SEC;

    std::cout << elapsedTime << '\n';
    std::cout << "sum = " << sum << '\n';
}

Without std::sort(data, data + arraySize);, the code runs in 11.54 seconds.

With the sorted data, the code runs in 1.93 seconds.

(Sorting itself takes more time than this one pass over the array, so it's not actually worth doing if we needed to calculate this for an unknown array.)

Initially, I thought this might be just a language or compiler anomaly, so I tried Java:

import java.util.Arrays;
import java.util.Random;

public class Main
{
    public static void main(String[] args)
    {
        // Generate data
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;

        // !!! With this, the next loop runs faster
        Arrays.sort(data);

        // Test
        long start = System.nanoTime();
        long sum = 0;
        for (int i = 0; i < 100000; ++i)
        {
            for (int c = 0; c < arraySize; ++c)
            {   // Primary loop.
                if (data[c] >= 128)
                    sum += data[c];
            }
        }

        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);
    }
}

With a similar but less extreme result.

My first thought was that sorting brings the data into the cache, but that's silly because the array was just generated.

What is going on?

Why is processing a sorted array faster than processing an unsorted array?

The code is summing up some independent terms, so the order should not matter.

Related / follow-up Q&As about the same effect with different/later compilers and options:

Why is processing an unsorted array the same speed as processing a sorted array with modern x86-64 clang?

gcc optimization flag -O3 makes code slower than -O2

Body:
Sorted arrays are processed faster than an unsorted array, due to a phenomena called branch prediction.

The branch predictor is a digital circuit (in computer architecture) trying to predict which way a branch will go, improving the flow in the instruction pipeline. The circuit/computer predicts the next step and executes it.

Making a wrong prediction leads to going back to the previous step, and executing with another prediction. Assuming the prediction is correct, the code will continue to the next step. A wrong prediction results in repeating the same step, until a correct prediction occurs.

The answer to your question is very simple.

In an unsorted array, the computer makes multiple predictions, leading to an increased chance of errors.
Whereas, in a sorted array, the computer makes fewer predictions, reducing the chance of errors.
Making more predictions requires more time.

Sorted Array: Straight Road

____________________________________________________________________________________
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT

Unsorted Array: Curved Road

______   ________
|     |__|

Branch prediction: Guessing/predicting which road is straight and following it without checking

___________________________________________ Straight road
 |_________________________________________|Longer road

Although both the roads reach the same destination, the straight road is shorter, and the other is longer. If then you choose the other by mistake, there is no turning back, and so you will waste some extra time if you choose the longer road. This is similar to what happens in the computer, and I hope this helped you understand better.

Also I want to cite @Simon_Weaver from the comments:

It doesn’t make fewer predictions - it makes fewer incorrect predictions. It still has to predict for each time through the loop...


问:
Excel VBA - use the if and countif to clear(not delete) the duplicate cell expect the first item
I have two workbooks. one is report.xls, another one is AT.xlsm.

In report.xls, there has the sheet called "Service".

In AT.xlsm, there has the sheet called "Worksheet".

Thanks for the help of @mooseman, it can use the VBA to copy the column B,C,F,J,E,D expect first row of report to the column A,C,D,E,F,H of AT.

After copy the data from the report to AT, i want to remove the duplicate cell(just clear the content of the cell) expect the first item that use the VBA. I know that use the if and countif can work out.

Would you please tell me how to use the if and countif in the VBA to remove the duplicate cell(just clear the content of the cell) expect the first item ?

Thank you very much.

```<code> Sub add_click()

Dim sDirectory As String
Dim sFilename As String
Dim sheet As Worksheet
Dim total As Integer
Dim lastRow As Long
Dim sImportFile As String
Dim totalactive As Integer
Dim readsheetName As String
Dim destsheetName As String

readsheetName = "Service"
destsheetName = "Worksheet"

addWSn = 0
Application.ScreenUpdating = False
Application.DisplayAlerts = False
sDirectory = ActiveWorkbook.Path
sFilename = sDirectory + "\*.xl??"

sImportFile = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open report")
If sImportFile = "False" Then
    MsgBox ("No File")
    Exit Sub
End If

'set destination workbook and worksheet
Set wb2 = ThisWorkbook
Set wsw = wb2.Sheets(destsheetName)
lastRow = wsw.Cells(wsw.Rows.Count, "D").End(xlUp).Row
lastRow = lastRow + 2
Set wb = Workbooks.Open(sImportFile)
Set wss = wb.Sheets(readsheetName)

wss.Range(wss.Cells(2, 2), wss.Cells(wss.Range("B" & wss.Rows.Count).End(xlUp).Row, 2)).Copy
wsw.Cells(lastRow, 1).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 3), wss.Cells(wss.Range("C" & wss.Rows.Count).End(xlUp).Row, 3)).Copy
wsw.Cells(lastRow, 3).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 6), wss.Cells(wss.Range("F" & wss.Rows.Count).End(xlUp).Row, 6)).Copy
wsw.Cells(lastRow, 4).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 10), wss.Cells(wss.Range("J" & wss.Rows.Count).End(xlUp).Row, 10)).Copy
wsw.Cells(lastRow, 5).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 5), wss.Cells(wss.Range("E" & wss.Rows.Count).End(xlUp).Row, 5)).Copy
wsw.Cells(lastRow, 6).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 4), wss.Cells(wss.Range("D" & wss.Rows.Count).End(xlUp).Row, 4)).Copy
wsw.Cells(lastRow, 8).PasteSpecial Paste:=xlPasteValues

wsw.Range(wsw.Cells(lastRow, 6), wsw.Cells(wsw.Range("F" & wsw.Rows.Count).End(xlUp).Row, 6)).Replace What:="[S]", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
wsw.Columns("E:K").HorizontalAlignment = xlRight

'close excel file
Workbooks.Open (sImportFile)
ActiveWorkbook.Close SaveChanges:=False
End Sub
</code>```

Updated:
@ Maldred
The result is partly worked, it can some clear the content of some duplicate.

答:
The below VBA code will work for you, tested and working

```<code>Sub RemoveItems()

   Dim i As Long
   ' Starting on second line
   i = 2
   With ActiveSheet
      Do While (Not (.Range("A" & i).Value = ""))
      Debug.Print .Range("A" & i).Value
         If (.Range("A" & i).Value = .Range("A" & (i - 1)).Value) Then
            .Range("A" & i).ClearContents
         End If
         ' Increment the loop
         i = i + 1
      Loop
   End With

End Sub
</code>```

Please ask if you have questions or issues using it

Body:
I have two workbooks. one is report.xls, another one is AT.xlsm.

In report.xls, there has the sheet called "Service".

In AT.xlsm, there has the sheet called "Worksheet".

Thanks for the help of @mooseman, it can use the VBA to copy the column B,C,F,J,E,D expect first row of report to the column A,C,D,E,F,H of AT.

After copy the data from the report to AT, i want to remove the duplicate cell(just clear the content of the cell) expect the first item that use the VBA. I know that use the if and countif can work out.

Would you please tell me how to use the if and countif in the VBA to remove the duplicate cell(just clear the content of the cell) expect the first item ?

Thank you very much.

 Sub add_click()

Dim sDirectory As String
Dim sFilename As String
Dim sheet As Worksheet
Dim total As Integer
Dim lastRow As Long
Dim sImportFile As String
Dim totalactive As Integer
Dim readsheetName As String
Dim destsheetName As String

readsheetName = "Service"
destsheetName = "Worksheet"

addWSn = 0
Application.ScreenUpdating = False
Application.DisplayAlerts = False
sDirectory = ActiveWorkbook.Path
sFilename = sDirectory + "\*.xl??"

sImportFile = Application.GetOpenFilename(FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open report")
If sImportFile = "False" Then
    MsgBox ("No File")
    Exit Sub
End If

'set destination workbook and worksheet
Set wb2 = ThisWorkbook
Set wsw = wb2.Sheets(destsheetName)
lastRow = wsw.Cells(wsw.Rows.Count, "D").End(xlUp).Row
lastRow = lastRow + 2
Set wb = Workbooks.Open(sImportFile)
Set wss = wb.Sheets(readsheetName)

wss.Range(wss.Cells(2, 2), wss.Cells(wss.Range("B" & wss.Rows.Count).End(xlUp).Row, 2)).Copy
wsw.Cells(lastRow, 1).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 3), wss.Cells(wss.Range("C" & wss.Rows.Count).End(xlUp).Row, 3)).Copy
wsw.Cells(lastRow, 3).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 6), wss.Cells(wss.Range("F" & wss.Rows.Count).End(xlUp).Row, 6)).Copy
wsw.Cells(lastRow, 4).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 10), wss.Cells(wss.Range("J" & wss.Rows.Count).End(xlUp).Row, 10)).Copy
wsw.Cells(lastRow, 5).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 5), wss.Cells(wss.Range("E" & wss.Rows.Count).End(xlUp).Row, 5)).Copy
wsw.Cells(lastRow, 6).PasteSpecial Paste:=xlPasteValues

wss.Range(wss.Cells(2, 4), wss.Cells(wss.Range("D" & wss.Rows.Count).End(xlUp).Row, 4)).Copy
wsw.Cells(lastRow, 8).PasteSpecial Paste:=xlPasteValues

wsw.Range(wsw.Cells(lastRow, 6), wsw.Cells(wsw.Range("F" & wsw.Rows.Count).End(xlUp).Row, 6)).Replace What:="[S]", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
wsw.Columns("E:K").HorizontalAlignment = xlRight

'close excel file
Workbooks.Open (sImportFile)
ActiveWorkbook.Close SaveChanges:=False
End Sub

Updated:
@ Maldred
The result is partly worked, it can some clear the content of some duplicate.

Body:
The below VBA code will work for you, tested and working

Sub RemoveItems()

   Dim i As Long
   ' Starting on second line
   i = 2
   With ActiveSheet
      Do While (Not (.Range("A" & i).Value = ""))
      Debug.Print .Range("A" & i).Value
         If (.Range("A" & i).Value = .Range("A" & (i - 1)).Value) Then
            .Range("A" & i).ClearContents
         End If
         ' Increment the loop
         i = i + 1
      Loop
   End With

End Sub

Please ask if you have questions or issues using it