问:
How to speed up Get-ChildItem in Powershell
Just wandering how could I speed up the Get-ChildItem in Powershell?

I have the following script to search for a file that created by today and copy it over to another folder.

```<code>$fromDirectory = "test_file_*.txt"
$fromDirectory = "c:\sour\"
$toDirectory = "c:\test\"

Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory
</code>```

Due to the folder that I search have 124,553 history files, it's take me age for the search. Does any know how could I improve my script to speed up my search and copy?

答:
I would try putting the Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} in an Array and then copying results from the Array.

```<code>$GrabFiles =@()
$GrabFiles =@( Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} )
Copy-Item -Path $GrabFiles -Destination $toDirectory }
</code>```

Body:
Just wandering how could I speed up the Get-ChildItem in Powershell?

I have the following script to search for a file that created by today and copy it over to another folder.

$fromDirectory = "test_file_*.txt"
$fromDirectory = "c:\sour\"
$toDirectory = "c:\test\"

Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory

Due to the folder that I search have 124,553 history files, it's take me age for the search. Does any know how could I improve my script to speed up my search and copy?

Body:
I would try putting the Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} in an Array and then copying results from the Array.

$GrabFiles =@()
$GrabFiles =@( Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} )
Copy-Item -Path $GrabFiles -Destination $toDirectory }


来源: stackexchange

问:
How do i change the text when i'm submitting
I'm not able to change the text at "Enter your age" to "your age is" when submitting. Is there way that when I submit the DOB the "Enter you age" changes to "your age is: X"?

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Birthday: <input type="date" name="bday" id="birth_date">
  <br><br>
</form>

<button onclick="myFunction()">view</button><br>
<h2>Enter your age</h2>
<p id="age"></p></code>```

答:
Update template to be

```<code> <h2 id="age">Enter your age</h2>
</code>```

And update script to be like this

```<code>document.getElementById("age").textContent = "Your Age is : " + calculatedValue;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm not able to change the text at "Enter your age" to "your age is" when submitting. Is there way that when I submit the DOB the "Enter you age" changes to "your age is: X"?

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}

<form>
  Birthday: <input type="date" name="bday" id="birth_date">

</form>

<button onclick="myFunction()">view</button>

Enter your age

Body:
Update template to be

 <h2 id="age">Enter your age</h2>

And update script to be like this

document.getElementById("age").textContent = "Your Age is : " + calculatedValue;


问:
Finding Prime numbers in a vector and print them in revers in another vector
here's the problem:
x is a vector with n elements.. build another vector, y, which will contain prime elements from x, but in reverse order.
My code. Don't know what I'm doing wrong.

答:
You can check my solution of this task:

```<code>#include <iostream>
#include <vector>
#include <algorithm>

bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}

std::vector<int> Primes(int n)
{
    std::vector<int> vec;
    for (int i = 0; i < n; ++i)
    {
        if (isPrime(i))
        {
            vec.push_back(i);
        }
    }
    std::reverse(vec.begin(), vec.end());
    return vec;
}

int main() {
    std::vector<int> primes = Primes(100);
    for (int i = 0; i < primes.size(); ++i)
    {
        std::cout << primes[i] << " ";
    }
}
</code>```

So, I have function that checks if the element in vector is prime. Also I created a function that creates a reversed vector of prime numbers. I hope I get it right because you said about vectors, however, you used arrays in your program.

The output of Primes(100) :

97 89 83 79 73 71 67 61 59 53 47 43 41 37 31 29 23 19 17 13 11 7 5 3 2

Body:
You can check my solution of this task:

#include <iostream>
#include <vector>
#include <algorithm>

bool isPrime(int num)
{
    bool isPrime = 1;
    if (num <= 0)
    {
        return 0;
    }
    if (num == 1)
    {
        return 0;
    }
    for (int i = 2; i <= sqrt(num); ++i)
    {
        if (num % i == 0)
        {
            isPrime = 0;
        }
    }

    return isPrime;
}

std::vector<int> Primes(int n)
{
    std::vector<int> vec;
    for (int i = 0; i < n; ++i)
    {
        if (isPrime(i))
        {
            vec.push_back(i);
        }
    }
    std::reverse(vec.begin(), vec.end());
    return vec;
}

int main() {
    std::vector<int> primes = Primes(100);
    for (int i = 0; i < primes.size(); ++i)
    {
        std::cout << primes[i] << " ";
    }
}

So, I have function that checks if the element in vector is prime. Also I created a function that creates a reversed vector of prime numbers. I hope I get it right because you said about vectors, however, you used arrays in your program.

The output of Primes(100) :

97 89 83 79 73 71 67 61 59 53 47 43 41 37 31 29 23 19 17 13 11 7 5 3 2


问:
Taking details from a map and saving it into another?
I have a map like this

```<code>map<string, pair< pair<int, int>, string> >
</code>```

what is the easiest way to get only the two strings and save into another map like this

```<code>map<string, string>
</code>```

?
I mean is there another way other than something like this??

```<code>    map<string, pair< pair<int, int>, string> >  info;
    map<string, pair< pair<int, int>, string> >::iterator i;
    map<string, string> something;

    for(i=info.begin(); i!=info.end(); ++i)
        something[*i).first] = ((*i).second).second;
</code>```

答:
The easiest way is to write simple for-loop that just works.

```<code>typedef pair<pair<int, int>, string> strange_pair_t;
typedef map<string, strange_pair_t> strange_type_t;
strange_type_t src_map;

map<string, string> dst_map;
for(strange_type_t::const_iterator it = src_map.begin(); it!=src_map.end(); ++it)
{
  dst_map.insert( make_pair( it->first, it->second.second ) );
}
</code>```

The tricky way ("one-liner"):

```<code>std::transform( src_map.begin(), src_map.end(), inserter(dst_map, dst_map.end()),
    boost::lambda::bind(
        boost::lambda::constructor<pair<string,string>>(),
        boost::lambda::bind( &strange_type_t::value_type::first, boost::lambda::_1 ),
        boost::lambda::bind( &strange_pair_t::second, boost::lambda::bind( &strange_type_t::value_type::second, boost::lambda::_1 ) )
    )
);
</code>```

C++0x way:

```<code>for_each( src_map.begin(), src_map.end(), [&dst_map](const strange_type_t::value_type& value) {
    dst_map.insert( make_pair( value.first, value.second.second ) ); } );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a map like this

map<string, pair< pair<int, int>, string> >

what is the easiest way to get only the two strings and save into another map like this

map<string, string>

?
I mean is there another way other than something like this??

    map<string, pair< pair<int, int>, string> >  info;
    map<string, pair< pair<int, int>, string> >::iterator i;
    map<string, string> something;

    for(i=info.begin(); i!=info.end(); ++i)
        something[*i).first] = ((*i).second).second;

Body:
The easiest way is to write simple for-loop that just works.

typedef pair<pair<int, int>, string> strange_pair_t;
typedef map<string, strange_pair_t> strange_type_t;
strange_type_t src_map;

map<string, string> dst_map;
for(strange_type_t::const_iterator it = src_map.begin(); it!=src_map.end(); ++it)
{
  dst_map.insert( make_pair( it->first, it->second.second ) );
}

The tricky way ("one-liner"):

std::transform( src_map.begin(), src_map.end(), inserter(dst_map, dst_map.end()),
    boost::lambda::bind(
        boost::lambda::constructor<pair<string,string>>(),
        boost::lambda::bind( &strange_type_t::value_type::first, boost::lambda::_1 ),
        boost::lambda::bind( &strange_pair_t::second, boost::lambda::bind( &strange_type_t::value_type::second, boost::lambda::_1 ) )
    )
);

C++0x way:

for_each( src_map.begin(), src_map.end(), [&dst_map](const strange_type_t::value_type& value) {
    dst_map.insert( make_pair( value.first, value.second.second ) ); } );


问:
How to convert String to LocalDate without using DateTimeFormatter
i have a date in String "2020-06-02"

now i have to convert it in LocalDate but without using DateTimeFormatter.

is it possible.

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate inputAdDate = LocalDate.parse(adDate, formatter);
</code>```

as of now my code looks like this. but i dont want to use DateTimeFormatter as it is not supported in API level below 26.

答:
Try this.

```<code>String date = "2020-06-02";
LocalDate localDate = LocalDate.parse(date);
</code>```

you need to import this package.

```<code>import java.time.LocalDate;
</code>```

Body:
i have a date in String "2020-06-02"

now i have to convert it in LocalDate but without using DateTimeFormatter.

is it possible.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate inputAdDate = LocalDate.parse(adDate, formatter);

as of now my code looks like this. but i dont want to use DateTimeFormatter as it is not supported in API level below 26.

Body:
Try this.

String date = "2020-06-02";
LocalDate localDate = LocalDate.parse(date);

you need to import this package.

import java.time.LocalDate;


问:
Time-based style changer how can I do it
Can someone explain me how to do a Time-based style changer in Javascript ? I've tried to do a test but it doesn't work. It only change the style when I manually modify in the code ">" to "<" in the if statement
This is the code I used</p>

```<code>var myDate = new Date();

        if(myDate.getHours() < 11.25) {

            document.getElementById('box').style.backgroundColor = "red";

        } else {

            document.getElementById('box').style.backgroundColor = "black";

        }
</code>```

答:
Try your condition as below. getHours will return integer value of hour while getMinutes will return integer value of minutes.

```<code>if (myDate.getHours() < 11 || (myDate.getHours() == 11 && myDate.getMinutes() < 15)) {
    // your code
}
</code>```

Body:
Can someone explain me how to do a Time-based style changer in Javascript ? I've tried to do a test but it doesn't work. It only change the style when I manually modify in the code ">" to "<" in the if statement
This is the code I used

var myDate = new Date();

        if(myDate.getHours() < 11.25) {

            document.getElementById('box').style.backgroundColor = "red";

        } else {

            document.getElementById('box').style.backgroundColor = "black";

        }

Body:
Try your condition as below. getHours will return integer value of hour while getMinutes will return integer value of minutes.

if (myDate.getHours() < 11 || (myDate.getHours() == 11 && myDate.getMinutes() < 15)) {
    // your code
}


问:
Date difference in years in PySpark dataframe
I come from Pandas background and new to Spark. I have a dataframe which has id, dob, age as columns. I want to get the age of the user from his dob (in some cases age column is NULL).

```<code>+----+------+----------+
| id | age  |   dob    |
+----+------+----------+
|  1 | 24   | NULL     |
|  2 | 25   | NULL     |
|  3 | NULL | 1/1/1973 |
|  4 | NULL | 6/6/1980 |
|  5 | 46   |          |
|  6 | NULL | 1/1/1971 |
+----+------+----------+
</code>```

I want a new column which will calculate age from dob and current date.

I tried this, but not getting any results from it:

```<code>df.withColumn("diff",
              datediff(to_date(lit("01-06-2020")),
                       to_date(unix_timestamp('dob', "dd-MM-yyyy").cast("timestamp")))).show()
</code>```

答:
I believe it is more appropriate to use months_between when it comes to year difference. we should use datediff only when if you need difference in days

Approach-

 val data =
      """
        | id | age  |   dob
        |  1 | 24   |
        |  2 | 25   |
        |  3 |      | 1/1/1973
        |  4 |      | 6/6/1980
        |  5 | 46   |
        |  6 |      | 1/1/1971
      """.stripMargin

    val stringDS = data.split(System.lineSeparator())
      .map(_.split("\\|").map(_.replaceAll("""^[ \t]+|[ \t]+$""", "")).mkString(","))
      .toSeq.toDS()
    val df = spark.read
      .option("sep", ",")
      .option("inferSchema", "true")
      .option("header", "true")
      .csv(stringDS)
    df.show(false)
    df.printSchema()

    /**
      * +---+----+--------+
      * |id |age |dob     |
      * +---+----+--------+
      * |1  |24  |null    |
      * |2  |25  |null    |
      * |3  |null|1/1/1973|
      * |4  |null|6/6/1980|
      * |5  |46  |null    |
      * |6  |null|1/1/1971|
      * +---+----+--------+
      *
      * root
      * |-- id: integer (nullable = true)
      * |-- age: integer (nullable = true)
      * |-- dob: string (nullable = true)
      */
```

<h2>Find age</h2>

<pre class="lang-scala prettyprint-override"><code>  df.withColumn("diff",
      coalesce(col("age"),
      round(months_between(current_date(),to_date(col("dob"), "d/M/yyyy"),true).divide(12),2)
      )
     ).show()

    /**
      * +---+----+--------+-----+
      * | id| age|     dob| diff|
      * +---+----+--------+-----+
      * |  1|  24|    null| 24.0|
      * |  2|  25|    null| 25.0|
      * |  3|null|1/1/1973|47.42|
      * |  4|null|6/6/1980|39.99|
      * |  5|  46|    null| 46.0|
      * |  6|null|1/1/1971|49.42|
      * +---+----+--------+-----+
      */
</code>```

round it to 0 if you want age in whole number

Body:
I come from Pandas background and new to Spark. I have a dataframe which has id, dob, age as columns. I want to get the age of the user from his dob (in some cases age column is NULL).

+----+------+----------+
| id | age  |   dob    |
+----+------+----------+
|  1 | 24   | NULL     |
|  2 | 25   | NULL     |
|  3 | NULL | 1/1/1973 |
|  4 | NULL | 6/6/1980 |
|  5 | 46   |          |
|  6 | NULL | 1/1/1971 |
+----+------+----------+

I want a new column which will calculate age from dob and current date.

I tried this, but not getting any results from it:

df.withColumn("diff",
              datediff(to_date(lit("01-06-2020")),
                       to_date(unix_timestamp('dob', "dd-MM-yyyy").cast("timestamp")))).show()

Body:
I believe it is more appropriate to use months_between when it comes to year difference. we should use datediff only when if you need difference in days

Approach-

 val data =
      """
        | id | age  |   dob
        |  1 | 24   |
        |  2 | 25   |
        |  3 |      | 1/1/1973
        |  4 |      | 6/6/1980
        |  5 | 46   |
        |  6 |      | 1/1/1971
      """.stripMargin

    val stringDS = data.split(System.lineSeparator())
      .map(_.split("\\|").map(_.replaceAll("""^[ \t]+|[ \t]+$""", "")).mkString(","))
      .toSeq.toDS()
    val df = spark.read
      .option("sep", ",")
      .option("inferSchema", "true")
      .option("header", "true")
      .csv(stringDS)
    df.show(false)
    df.printSchema()

    /**
      * +---+----+--------+
      * |id |age |dob     |
      * +---+----+--------+
      * |1  |24  |null    |
      * |2  |25  |null    |
      * |3  |null|1/1/1973|
      * |4  |null|6/6/1980|
      * |5  |46  |null    |
      * |6  |null|1/1/1971|
      * +---+----+--------+
      *
      * root
      * |-- id: integer (nullable = true)
      * |-- age: integer (nullable = true)
      * |-- dob: string (nullable = true)
      */

Find age

  df.withColumn("diff",
      coalesce(col("age"),
      round(months_between(current_date(),to_date(col("dob"), "d/M/yyyy"),true).divide(12),2)
      )
     ).show()

    /**
      * +---+----+--------+-----+
      * | id| age|     dob| diff|
      * +---+----+--------+-----+
      * |  1|  24|    null| 24.0|
      * |  2|  25|    null| 25.0|
      * |  3|null|1/1/1973|47.42|
      * |  4|null|6/6/1980|39.99|
      * |  5|  46|    null| 46.0|
      * |  6|null|1/1/1971|49.42|
      * +---+----+--------+-----+
      */

round it to 0 if you want age in whole number


问:
Java error :- "no suitable method found for sort(Student[],j)"
Hello guys I am new to java programming and while practising I encountered an error please help me solve this problem which I have stated above (title). I am also attaching my code here please fix this issue and thanks in advance :)

Code:

```<code>import java.util.Collections;
import java.util.Comparator;
class Student{
    public int marks;
    public String name;
    public Student(int marks, String name){
        this.marks = marks;
        this.name = name;
    }
    @Override
    public String toString(){
        return ("Name: " + this.name + " Marks: " + this.marks);
    }
}
public class j implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2){
        if (o1.marks < o2.marks)
            return 1;
        else
            return -1;
    }
    public static void main(String[] args) {
        Student[] array = new Student[2];
        array[0] = new Student(10, "varun");
        array[1] = new Student(20, "gupta");
        Collections.sort(array, new j());
        for (Student i : array)
            System.out.println(i);
    }
}
</code>```

答: You should change Collections.sort(array, new j()); to Arrays.sort(array, new j());</p>

Body:
Hello guys I am new to java programming and while practising I encountered an error please help me solve this problem which I have stated above (title). I am also attaching my code here please fix this issue and thanks in advance :)

Code:

import java.util.Collections;
import java.util.Comparator;
class Student{
    public int marks;
    public String name;
    public Student(int marks, String name){
        this.marks = marks;
        this.name = name;
    }
    @Override
    public String toString(){
        return ("Name: " + this.name + " Marks: " + this.marks);
    }
}
public class j implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2){
        if (o1.marks < o2.marks)
            return 1;
        else
            return -1;
    }
    public static void main(String[] args) {
        Student[] array = new Student[2];
        array[0] = new Student(10, "varun");
        array[1] = new Student(20, "gupta");
        Collections.sort(array, new j());
        for (Student i : array)
            System.out.println(i);
    }
}


问:
Check email address in twig
How can I check that a string is valid email address in twig template ?

For example, in this code:
{% set usernameType = (#Check user.username is email#) ? 'email' : 'number' %}

I need if user.username is a valid email address, usernameType set as email, otherwise set as number

答:
Twig is executed at the server side so if you want to validate email you should use javascript at client side like: https://stackoverflow.com/a/46181/4450882
in the server side you should use php or python to make this verification.
php validation: https://www.php.net/manual/fr/filter.examples.validation.php
python validation: https://pypi.org/project/validate_email/</p>

Title: Check email address in twig


问:
Could'nt load images from Firestore with Picasso in Android recyclerview
I'm trying to load images stored in my Firestore storage to the image view with RecyclerView of Android. Uploading image is not a problem and I configured same permission for upload and download.
But it only shows an image specified in the parameter of placeholder.

I searched several things which seem to be relevant with this issue. Then I found that the matter of the version of Picasso Library and change of with(context) to get().

I applied them to my code and tested.

with the version of Picasso for 2.5.2 then tried with(mContext).
Next I tried the version of Picasso for 2.71828 then tried get().

But both gives same result which can be confirmed here.

It seems to be this is not a matter of Picasso. But I couldn't find proper solution.

Anyone can help this out?

Source for onBindViewHolder in an imageAdapter.java

```<code>@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getName());
    Picasso.with(mContext)
            .load(uploadCurrent.getImageUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);

}
</code>```

As I mentioned above, get() replaced of with(mContext) already tried.

Please let me know if you need further information for this.

答:
im soryy for to much late but this is 100% worked fo me..
you just use imagPath in picaso to load image and done </p>

```<code>String imagpath="";

 FirebaseStorage storageReference = FirebaseStorage.getInstance();

        DatabaseReference mDatabase = null;
        UploadTask uploadTask;
        StorageReference riversRef = storageReference.getReference();
        final StorageReference imagesRef = riversRef.child("images/Avatars/"+getSaltString()+filePathh.getLastPathSegment());
        uploadTask = imagesRef.putFile(filePathh);

// Register observers to listen for when the download is done or if it fails
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
                // ...
                imagesRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String content = uri.toString();
                        String result = content.substring(content.indexOf("%") + 1, content.indexOf("?"));
                        result = result.substring(2);
                        if (content.length() > 0) {

                            imagepath=content;

                        }
                    }
                });

                //update session image path

            }
        });
</code>```

Body:
I'm trying to load images stored in my Firestore storage to the image view with RecyclerView of Android. Uploading image is not a problem and I configured same permission for upload and download.
But it only shows an image specified in the parameter of placeholder.

I searched several things which seem to be relevant with this issue. Then I found that the matter of the version of Picasso Library and change of with(context) to get().

I applied them to my code and tested.

with the version of Picasso for 2.5.2 then tried with(mContext).
Next I tried the version of Picasso for 2.71828 then tried get().

But both gives same result which can be confirmed here.

It seems to be this is not a matter of Picasso. But I couldn't find proper solution.

Anyone can help this out?

Source for onBindViewHolder in an imageAdapter.java

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getName());
    Picasso.with(mContext)
            .load(uploadCurrent.getImageUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);

}

As I mentioned above, get() replaced of with(mContext) already tried.

Please let me know if you need further information for this.

Body:
im soryy for to much late but this is 100% worked fo me..
you just use imagPath in picaso to load image and done

String imagpath="";

 FirebaseStorage storageReference = FirebaseStorage.getInstance();

        DatabaseReference mDatabase = null;
        UploadTask uploadTask;
        StorageReference riversRef = storageReference.getReference();
        final StorageReference imagesRef = riversRef.child("images/Avatars/"+getSaltString()+filePathh.getLastPathSegment());
        uploadTask = imagesRef.putFile(filePathh);

// Register observers to listen for when the download is done or if it fails
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
                // ...
                imagesRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String content = uri.toString();
                        String result = content.substring(content.indexOf("%") + 1, content.indexOf("?"));
                        result = result.substring(2);
                        if (content.length() > 0) {

                            imagepath=content;

                        }
                    }
                });

                //update session image path

            }
        });


问:
Recommendations for IPC between parent and child processes in .NET?
My .NET program needs to run an algorithm that makes heavy use of 3rd party libraries (32-bit), most of which are unmanaged code.  I want to drive the CPU as hard as I can, so the code runs several threads in parallel to divide up the work.

I find that running all these threads simultaneously results in temporary memory spikes, causing the process' virtual memory size to approach the 2 GB limit.  This memory is released back pretty quickly, but occasionally if enough threads enter the wrong sections of code at once, the process crosses the "red line" and either the unmanaged code or the .NET code encounters an out of memory error.  I can throttle back the number of threads but then my CPU usage is not as high as I would like.

I am thinking of creating worker processes rather than worker threads to help avoid the out of memory errors, since doing so would give each thread of execution its own 2 GB of virtual address space (my box has lots of RAM).  I am wondering what are the best/easiest methods to communicate the input and output between the processes in .NET?

The file system is an obvious choice.  I am used to shared memory, named pipes, and such from my UNIX background.  Is there a Windows or .NET specific mechanism I should use?

答:
Yes you are right. Breaking into several processes as opposed to threads will help, since every process will have its own 2GB virtual space (on 32-bit system).

Since you have lots of RAM, One other thing you can do (without need to have multiple processes) is use PAE (physical address extension) and then your process can address upwards of 8 GB . See here

As others have suggested you can use .NET remoting (if both client and server are .NET, can be local in same machine or remote).

PS: this answer is late, may be your requirement is done with, but i post it here for later use of this thread by other people.

ContentLicense: CC BY-SA 2.5


问:
"ValueError: Shapes (None, 1) and (None, 6) are incompatible"
I want to classify 6 different categories of x-ray scans, What's wrong with the code?

```<code>model = Sequential()

model.add(Conv2D(256, (3, 3), input_shape=X.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(256, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))

model.add(Dense(6))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X, y, batch_size=32, epochs=3, validation_split=0.1)
</code>```

The shapes of input are: (50, 50, 1)

Should I remove one of the MaxPooling layers?

I've seen it's good manners here to post the traceback aswell, so here it is:

```<code>Epoch 1/3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
(...)
ValueError: in user code:

    C:\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:532 train_step  **
        loss = self.compiled_loss(
    C:\Python38\lib\site-packages\tensorflow\python\keras\engine\compile_utils.py:205 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    C:\Python38\lib\site-packages\tensorflow\python\keras\losses.py:143 __call__
        losses = self.call(y_true, y_pred)
    C:\Python38\lib\site-packages\tensorflow\python\keras\losses.py:246 call
        return self.fn(y_true, y_pred, **self._fn_kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\keras\losses.py:1527 categorical_crossentropy
        return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
    C:\Python38\lib\site-packages\tensorflow\python\keras\backend.py:4561 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    C:\Python38\lib\site-packages\tensorflow\python\framework\tensor_shape.py:1117 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (None, 1) and (None, 6) are incompatible
</code>```

答:
to avoid misunderstandings and possible error I suggest you to reshape your target from (586,1) to (586,). you can simply do y = y.ravel()

you have to simply manage the correct loss

if you have 1D integer encoded target you can use sparse_categorical_crossentropy as loss function

```<code>X = np.random.randint(0,10, (1000,100))
y = np.random.randint(0,3, 1000)

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
</code>```

Otherwise, if you have one-hot encoded your target in order to have 2D shape (n_samples, n_class) you can use categorical_crossentropy

```<code>X = np.random.randint(0,10, (1000,100))
y = pd.get_dummies(np.random.randint(0,3, 1000)).values

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
</code>```

Body:
I want to classify 6 different categories of x-ray scans, What's wrong with the code?

model = Sequential()

model.add(Conv2D(256, (3, 3), input_shape=X.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(256, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))

model.add(Dense(6))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X, y, batch_size=32, epochs=3, validation_split=0.1)

The shapes of input are: (50, 50, 1)

Should I remove one of the MaxPooling layers?

I've seen it's good manners here to post the traceback aswell, so here it is:

Epoch 1/3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
(...)
ValueError: in user code:

    C:\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    C:\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py:532 train_step  **
        loss = self.compiled_loss(
    C:\Python38\lib\site-packages\tensorflow\python\keras\engine\compile_utils.py:205 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    C:\Python38\lib\site-packages\tensorflow\python\keras\losses.py:143 __call__
        losses = self.call(y_true, y_pred)
    C:\Python38\lib\site-packages\tensorflow\python\keras\losses.py:246 call
        return self.fn(y_true, y_pred, **self._fn_kwargs)
    C:\Python38\lib\site-packages\tensorflow\python\keras\losses.py:1527 categorical_crossentropy
        return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
    C:\Python38\lib\site-packages\tensorflow\python\keras\backend.py:4561 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    C:\Python38\lib\site-packages\tensorflow\python\framework\tensor_shape.py:1117 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (None, 1) and (None, 6) are incompatible

Body:
to avoid misunderstandings and possible error I suggest you to reshape your target from (586,1) to (586,). you can simply do y = y.ravel()

you have to simply manage the correct loss

if you have 1D integer encoded target you can use sparse_categorical_crossentropy as loss function

X = np.random.randint(0,10, (1000,100))
y = np.random.randint(0,3, 1000)

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)

Otherwise, if you have one-hot encoded your target in order to have 2D shape (n_samples, n_class) you can use categorical_crossentropy

X = np.random.randint(0,10, (1000,100))
y = pd.get_dummies(np.random.randint(0,3, 1000)).values

model = Sequential([
    Dense(128, input_dim = 100),
    Dense(3, activation='softmax'),
])
model.summary()
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)


问:
Kotlin/Java: should this singleton object have these sub-methods to check?
I have a singleton object, call it Bank. Bank has several methods, like addCustomer, addRent, etc. Each method has some parameters to do the job.

However, the precondition is that, some methods require me to check if that object, given by the parameter, exist, or does not exists (for example: when addCustomer, check if customerID is already in the database). So my class Bank looks like this, let's simplify it.

object Bank{
   //Some lists to store data here

   fun addCustomer(customerID: String){
   checkIfCustomerExist(customerID)
   // Do something here
   }

   private fun checkIfCustomerExist(customerID: String){
   // If customer is in list, throw exception
   }
}
```

So far so good.

However, my program has many lists and required functions, so it has a lot of utilities methods to check if exist/not exist. Is it ok, or what should I do to follow the design principles? I plan to create another singleton object Verification and implement all these check methods there. What are your thoughts?

答:
You should use dependency injection which is suggested design principle instead of having many object class. I personally user Dagger2 currently. object/singleton is waste of resources if there are many objects. Dependency injection also enables testable code. But, if you have few object classes and you think they are not waste of resource, then it should be ok.

```<code>@MyCustomizedScope
class Bank
@Inject
constructor(
// here any number of variables can come
val bankId: Int // bankId is unique over the existence of Bank class
){
     // todo
}
</code>```

In the example @MyCustomizedScope is used to define existence period of the Bank class. For example in android, @MyCustomizedScope could be bound to main screen where this class lives. In this case, it only lives as long as the screen exists. But if you declare it as an object the class exists until application dies which is unnecessary.

So, It is recommended to use dependency injection.

Body:
I have a singleton object, call it Bank. Bank has several methods, like addCustomer, addRent, etc. Each method has some parameters to do the job.

However, the precondition is that, some methods require me to check if that object, given by the parameter, exist, or does not exists (for example: when addCustomer, check if customerID is already in the database). So my class Bank looks like this, let's simplify it.

object Bank{
   //Some lists to store data here

   fun addCustomer(customerID: String){
   checkIfCustomerExist(customerID)
   // Do something here
   }

   private fun checkIfCustomerExist(customerID: String){
   // If customer is in list, throw exception
   }
}

So far so good.

However, my program has many lists and required functions, so it has a lot of utilities methods to check if exist/not exist. Is it ok, or what should I do to follow the design principles? I plan to create another singleton object Verification and implement all these check methods there. What are your thoughts?

Body:
You should use dependency injection which is suggested design principle instead of having many object class. I personally user Dagger2 currently. object/singleton is waste of resources if there are many objects. Dependency injection also enables testable code. But, if you have few object classes and you think they are not waste of resource, then it should be ok.

@MyCustomizedScope
class Bank
@Inject
constructor(
// here any number of variables can come
val bankId: Int // bankId is unique over the existence of Bank class
){
     // todo
}

In the example @MyCustomizedScope is used to define existence period of the Bank class. For example in android, @MyCustomizedScope could be bound to main screen where this class lives. In this case, it only lives as long as the screen exists. But if you declare it as an object the class exists until application dies which is unnecessary.

So, It is recommended to use dependency injection.


问:
editing messages with discord.py
I'm trying to edit my bots sent messages, but I'm getting an error

@client.command()
async def edit(ctx):
    message = await ctx.send('testing')
    time.sleep(0.3)
    message.edit(content='v2')
```
<p>Error:</p>
``` RuntimeWarning: coroutine 'Message.edit' was never awaited
  message.edit(content='v2')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
```

And by the way, is there any way of editing a message by simply having the message ID?

答:
time.sleep() is a blocking call, meaning that it pretty much screws up your script. What you'll instead want to use is await asyncio.sleep().

Also, edit() is a coroutine, so it needs to be awaited. Here is what your command should look like:

import asyncio # if you haven't already

@client.command()
async def edit(ctx):
    message = await ctx.send('testing')
    await asyncio.sleep(0.3)
    await message.edit(content='v2')
```

<p>To edit a message via ID, you'll need the channel that it came from:</p>

<pre class="lang-py prettyprint-override"><code>@client.command()
async def edit(ctx, msg_id: int = None, channel: discord.TextChannel = None):
    if not msg_id:
        channel = client.get_channel(112233445566778899) # the message's channel
        msg_id = 998877665544332211 # the message's id
    elif not channel:
        channel = ctx.channel
    msg = await channel.fetch_message(msg_id)
    await msg.edit(content="Some content!")
</code>```

The usage for this command would be !edit 112233445566778899 #message-channel-origin assuming that the prefix is !, and don't bother using the channel argument if the message is in the channel you're executing the command in.

References:

Message.edit()

asyncio.sleep()

Messageable.fetch_message()

Title: editing messages with discord.py

Body:
I'm trying to edit my bots sent messages, but I'm getting an error

@client.command()
async def edit(ctx):
    message = await ctx.send('testing')
    time.sleep(0.3)
    message.edit(content='v2')

Error:

 RuntimeWarning: coroutine 'Message.edit' was never awaited
  message.edit(content='v2')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

And by the way, is there any way of editing a message by simply having the message ID?

Body:
time.sleep() is a blocking call, meaning that it pretty much screws up your script. What you'll instead want to use is await asyncio.sleep().

Also, edit() is a coroutine, so it needs to be awaited. Here is what your command should look like:

import asyncio # if you haven't already

@client.command()
async def edit(ctx):
    message = await ctx.send('testing')
    await asyncio.sleep(0.3)
    await message.edit(content='v2')

To edit a message via ID, you'll need the channel that it came from:

@client.command()
async def edit(ctx, msg_id: int = None, channel: discord.TextChannel = None):
    if not msg_id:
        channel = client.get_channel(112233445566778899) # the message's channel
        msg_id = 998877665544332211 # the message's id
    elif not channel:
        channel = ctx.channel
    msg = await channel.fetch_message(msg_id)
    await msg.edit(content="Some content!")

The usage for this command would be !edit 112233445566778899 #message-channel-origin assuming that the prefix is !, and don't bother using the channel argument if the message is in the channel you're executing the command in.

References:

Message.edit()

asyncio.sleep()

Messageable.fetch_message()


问:
How to create a Webhook subscription for Azure Event-Grid
I wanted to prototype a service using azure event-grid and used the following resources to create a custom event-grid topic. I'm trying to add a webbook subscription but there is a mandatory field (system topic name) on the Azure Portal that's not explained in the docs, and cli fails with the error below.

CLI Error:
Deployment failed. Correlation ID: 9e13c3c8-4255-4a0c-b5b5-0a9419a385dd. The operation failed due to an internal server error. The initial state of the impacted resources (if any) are restored. Please try again in few minutes. If error still persists, report 698c81db-22a9-4e4a-91cf-55408b2b1486:6/2/2020 8:23:10 AM (UTC) to our forums for assistance or raise a support ticket .

Portal Error:
Creation of System Topic has failed with error: System topic creation is not enabled for topic type Microsoft.EventGrid.Topics

Resources:
https://learn.microsoft.com/en-us/azure/event-grid/scripts/event-grid-cli-create-custom-topic
https://learn.microsoft.com/en-us/azure/event-grid/scripts/event-grid-cli-subscribe-custom-topic
https://learn.microsoft.com/en-us/azure/event-grid/custom-event-quickstart-portal

I'm not sure what I'm doing wrong. Any help is much appreciated.

Thank you

答:
It looks like this is a bug on the portal. Based on the System topics in Azure Event Grid document:

System topic isn't applicable to custom topic scenarios, that is, Event Grid topics and Event Grid domains.

As a workaround, you can use any value for System Topic Name property to create the Event Subscription via the portal.

The following screen snippet shows a portal notifications during a process of the Event Subscription creating and deploying.


问:
Any difference between `(chan n)` and `(chan (buffer n))`?
As the title asks, is there any difference between (chan n) and (chan (buffer n)) when in use?

The question originates from the idea that I want to pull messages from a db (yeah, I do not want to use Kafka or RabbitMQ) and process them in order.

So the code segment looks like:

(defn processer [id]
  (let [ch (chan (buffer 1000))]  ;;(chan 1000) or (chan (buffer 1000))?
    (go-loop []
      (when-let [msg (<! ch)]
        (process-msg msg))
      (recur))
    ch))

(defn enqueue [id]
  (let [ch (processer id)]
    (go-loop []
      (let [msgs (take-100-msg-from-db id)]
        (if (seq msgs)
          (doseq [msg msgs]
            (>! ch msg))
          (<! (timeout 100))))
      (recur))))
```

In my testing, their behaviours do not differ.

答:
Yes, they are the same.

You can always look at the source:

```<code>(defn chan
  ([] (chan nil))
  ([buf-or-n] (chan buf-or-n nil))
  ([buf-or-n xform] (chan buf-or-n xform nil))
  ([buf-or-n xform ex-handler]
     (channels/chan (if (number? buf-or-n) (buffer buf-or-n) buf-or-n) xform ex-handler)))
</code>```

Body:
As the title asks, is there any difference between (chan n) and (chan (buffer n)) when in use?

The question originates from the idea that I want to pull messages from a db (yeah, I do not want to use Kafka or RabbitMQ) and process them in order.

So the code segment looks like:

(defn processer [id]
  (let [ch (chan (buffer 1000))]  ;;(chan 1000) or (chan (buffer 1000))?
    (go-loop []
      (when-let [msg (<! ch)]
        (process-msg msg))
      (recur))
    ch))

(defn enqueue [id]
  (let [ch (processer id)]
    (go-loop []
      (let [msgs (take-100-msg-from-db id)]
        (if (seq msgs)
          (doseq [msg msgs]
            (>! ch msg))
          (<! (timeout 100))))
      (recur))))

In my testing, their behaviours do not differ.

Body:
Yes, they are the same.

You can always look at the source:

(defn chan
  ([] (chan nil))
  ([buf-or-n] (chan buf-or-n nil))
  ([buf-or-n xform] (chan buf-or-n xform nil))
  ([buf-or-n xform ex-handler]
     (channels/chan (if (number? buf-or-n) (buffer buf-or-n) buf-or-n) xform ex-handler)))


问:
Photon: rejoin room
i am new to photon. And my problem is, Whenever i reconnect and rejoin the game using reconnectandrejoin(), the playerlist.length is 0.

Lets say that there are 2 players A and B. And when A rejoins after disconnecting, its playerlist is 0 and masterclient is null.
Similarly, in B the playerlist count does not add up to be 2 and remains 1 as if the player A has not connected.

Eventhough, the reconnectAndRejoin returns true.

If there is a tutorial about rejoining can you please direct me towards it, or can you please show be how to rejoin a player properly.

答: I answered on Photon's official public forums where this same question was asked, here.</p>

Title: Photon: rejoin room


问:
Unable to get element which is in under a Iframe in cypress
Am using this code
i have used each and every attribute but did not find </p>

<p>my html code pic </p>

```<code>cy.get('.gjs-frame')
.then(($iframe) => {
  const $body = $iframe.contents().find('body')
   cy.wrap($body)
   //cy.get('#v-app')
    //cy.get('.layout')
    //cy.get('.gjs-hovered')
    //.get('.v-application--wrap [data-gjs-type="wrapper"]')
   // .get('[data-gjs-type="wrapper"]')
    //.get('#v-app .v-application--wrap')
    //.get('.v-application--wrap')
   // .get('#v-mount').should('be.exist')

})
</code>```

答:
Refer: Working with iframes in Cypress</p>

```<code>const getIframeDocument = () => {
  return cy.get('iframe').its('0.contentDocument').should('exist')
};

const getIframeBody = () => {
  // get the document
  return getIframeDocument()
    .its('body').should('not.be.undefined')
    .then(cy.wrap);
}

getIframeBody().find(<selector>).should('contain', <content>);
</code>```

Body:
Am using this code
i have used each and every attribute but did not find

my html code pic

cy.get('.gjs-frame')
.then(($iframe) => {
  const $body = $iframe.contents().find('body')
   cy.wrap($body)
   //cy.get('#v-app')
    //cy.get('.layout')
    //cy.get('.gjs-hovered')
    //.get('.v-application--wrap [data-gjs-type="wrapper"]')
   // .get('[data-gjs-type="wrapper"]')
    //.get('#v-app .v-application--wrap')
    //.get('.v-application--wrap')
   // .get('#v-mount').should('be.exist')

})

Body:
Refer: Working with iframes in Cypress

const getIframeDocument = () => {
  return cy.get('iframe').its('0.contentDocument').should('exist')
};

const getIframeBody = () => {
  // get the document
  return getIframeDocument()
    .its('body').should('not.be.undefined')
    .then(cy.wrap);
}

getIframeBody().find(<selector>).should('contain', <content>);


问:
Selenium WebDriver based framework using POM with java
I am trying to write code to validate a webpage (Test Form with 3 required fields firstname, lastname, phone and 2 buttons submit and clear form) using POM with Selenium WebDriver with Java.

This is the code which I have written so far. I want to confirm whether I am going in the right way.

```<code>public class TestForm {
  WebDriver driver;

  By firstName=By.id("fname");
  By lastName=By.id("lname");
  By phoneno=By.id("phone");
  By submit=By.id("submit");
  By clearForm=By.xpath("//tagname[@type='button']");

  public TestForm(WebDriver driver)
  {
    this.driver=driver;
  }

  public void typeFirstName(String fname)
  {
    driver.findElement(firstName).sendKeys(fname);
  }

  public void typeLastName(String lname)
  {
    driver.findElement(lastName).sendKeys(lname);
  }

  public void typePhone(String phone)
  {
    driver.findElement(phoneno).sendKeys(phone);
  }

  public void clickSubmit()
  {
    driver.findElement(submit).click();
  }

  public void clickClearForm()
  {
    driver.findElement(clearForm).click();
  }

}
</code>```

```<code>public class VerifyTestForm {

  @Test
  public void verifyValidTestForm()
  {
    WebDriver driver=new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("url of the application");

    TestForm form=new TestForm(driver);
    form.typeFirstName("John");
    form.typeLastName("Adams");
    form.typePhone("1234567890");
    form.clickSubmit();
    form.clickClearForm();
    driver.quit();
  }
}
</code>```

答:
As your code is correct but it is not the way to implementing Page object Model.

You have to use concept of DataProvider to implement framework.

Make a excel sheet and extract the data by using DataProvider.

Make a new class file from where you can read your excel data.

Make a function which return 2d data of the file.

So By using this, The way to implement the framework.

Page object Model generally says that we should have to make the separate page of each module which we are using and return the reference of the last page.

Body:
I am trying to write code to validate a webpage (Test Form with 3 required fields firstname, lastname, phone and 2 buttons submit and clear form) using POM with Selenium WebDriver with Java.

This is the code which I have written so far. I want to confirm whether I am going in the right way.

public class TestForm {
  WebDriver driver;

  By firstName=By.id("fname");
  By lastName=By.id("lname");
  By phoneno=By.id("phone");
  By submit=By.id("submit");
  By clearForm=By.xpath("//tagname[@type='button']");

  public TestForm(WebDriver driver)
  {
    this.driver=driver;
  }

  public void typeFirstName(String fname)
  {
    driver.findElement(firstName).sendKeys(fname);
  }

  public void typeLastName(String lname)
  {
    driver.findElement(lastName).sendKeys(lname);
  }

  public void typePhone(String phone)
  {
    driver.findElement(phoneno).sendKeys(phone);
  }

  public void clickSubmit()
  {
    driver.findElement(submit).click();
  }

  public void clickClearForm()
  {
    driver.findElement(clearForm).click();
  }

}

public class VerifyTestForm {

  @Test
  public void verifyValidTestForm()
  {
    WebDriver driver=new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("url of the application");

    TestForm form=new TestForm(driver);
    form.typeFirstName("John");
    form.typeLastName("Adams");
    form.typePhone("1234567890");
    form.clickSubmit();
    form.clickClearForm();
    driver.quit();
  }
}


问:
How to check if an element has been removed from a Map
How can I check that an element has been properly removed from a Map in java?

Given:

```<code>ConcurrentHashMap<Integer,Object> myMap = new ConcurrentHashMap<>();
myMap.put(1, new Object());

myMap.remove(1);
</code>```

Is the below code the only way to check it?

```<code>myMap.contains(1);
</code>```

答:
remove() returns the removed object, or null if it is not present in the map:

Returns:

  the previous value associated with key, or null if there was no mapping for key.

```<code>Object removedObject = myMap.remove(1);
boolean wasRemoved = removedObject != null;
</code>```

In fact by using, contains(), the object might have been removed by another thread between the calls to remove() and contains(), if the map is shared between threads. That your question uses a ConcurrentHashMap hints that concurrency might be a case here.

Body:
How can I check that an element has been properly removed from a Map in java?

Given:

ConcurrentHashMap<Integer,Object> myMap = new ConcurrentHashMap<>();
myMap.put(1, new Object());

myMap.remove(1);

Is the below code the only way to check it?

myMap.contains(1);

Body:
remove() returns the removed object, or null if it is not present in the map:

Returns:

  the previous value associated with key, or null if there was no mapping for key.

Object removedObject = myMap.remove(1);
boolean wasRemoved = removedObject != null;

In fact by using, contains(), the object might have been removed by another thread between the calls to remove() and contains(), if the map is shared between threads. That your question uses a ConcurrentHashMap hints that concurrency might be a case here.


问:
Don't understand this TypeError while parsing json list
I have a json URL, I'm trying to parse it with Python, the output of the url looks like this:

```<code>"data": [
        {
            "config": {
                "add": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "append": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "http_method": null,
                "remove": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "rename": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "replace": {
                    "body": [],
                    "headers": [
                        "Host: jupyter.bbs-edsapp-p001.bbs.aphp.fr"
                    ],
                    "querystring": [],
                    "uri": null
                }
            },
            "consumer": null,
</code>```

My python script is :

```<code>import requests
import json

response = json.loads(requests.get("http://127.0.0.1:8001/services/6ca6c203-d3b6-46c7-94d6-cad435bbfd97/plugins").text)
for p in response['data']['config']['replace']:
    print('back: ' + headers[0])
    #print('name: ' + p['name'])
    #print(p['name'])
</code>```

I get this error:

for p in response['data']['config']['add']:
  TypeError: list indices must be integers or slices, not str.
```

答:
debug your code?</p>

```<code>In [1]: type(response)
Out[1]: dict

In [2]: response.get('data')
Out[2]:

In [3]: response.get('data').get('config')
Out[3]:

In [4]: response.get('data').get('config').get('replace')
Out[4]:
</code>```

Body:
I have a json URL, I'm trying to parse it with Python, the output of the url looks like this:

"data": [
        {
            "config": {
                "add": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "append": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "http_method": null,
                "remove": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "rename": {
                    "body": [],
                    "headers": [],
                    "querystring": []
                },
                "replace": {
                    "body": [],
                    "headers": [
                        "Host: jupyter.bbs-edsapp-p001.bbs.aphp.fr"
                    ],
                    "querystring": [],
                    "uri": null
                }
            },
            "consumer": null,

My python script is :

import requests
import json

response = json.loads(requests.get("http://127.0.0.1:8001/services/6ca6c203-d3b6-46c7-94d6-cad435bbfd97/plugins").text)
for p in response['data']['config']['replace']:
    print('back: ' + headers[0])
    #print('name: ' + p['name'])
    #print(p['name'])

I get this error:

for p in response['data']['config']['add']:
  TypeError: list indices must be integers or slices, not str.

Body:
debug your code?

In [1]: type(response)
Out[1]: dict

In [2]: response.get('data')
Out[2]:

In [3]: response.get('data').get('config')
Out[3]:

In [4]: response.get('data').get('config').get('replace')
Out[4]:


问:
Upload excel file to Dropbox or Google Drive?
I'm currently developing an application which creates an excel file(with apache poi) from the sqlite database in android. Everything is working well, except that I can't send the file to another app.
I implemented an fileprovider so I other apps can have permission to my file:

AndroidManifest.xml:

```<code><provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.ria.masterdetailnoten"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
</provider>
</code>```

file_paths.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="backup" path="backup/"/>
</paths>
</code>```

ExcelFile.java:

```<code>Uri uriFile = FileProvider.getUriForFile(ct, "com.example.ria.masterdetailnoten", backupFile);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setDataAndType(uriFile, "application/vnd.ms-excel");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.createChooser(intent, "Choose");
ct.startActivity(intent);
</code>```

I know for sure that my file is being created and I can read it again with Apache POI. So the only things which doesn't work is sending the intent to another app.

As an example if I choose Google Drive in the intent chooser then following error appears:
"Upload failed: request contained no data."

If I open it with the Mailbox App following error appears:
"Mailbox could not read the selected file"

I hope you can help me guys, I appreciate your help!

答: I've managed to work this out with intent.selector = Intent(Intent.ACTION_SEND).apply { data = Uri.parse("file:") }

Body:
I'm currently developing an application which creates an excel file(with apache poi) from the sqlite database in android. Everything is working well, except that I can't send the file to another app.
I implemented an fileprovider so I other apps can have permission to my file:

AndroidManifest.xml:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.ria.masterdetailnoten"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
</provider>

file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="backup" path="backup/"/>
</paths>

ExcelFile.java:

Uri uriFile = FileProvider.getUriForFile(ct, "com.example.ria.masterdetailnoten", backupFile);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setDataAndType(uriFile, "application/vnd.ms-excel");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.createChooser(intent, "Choose");
ct.startActivity(intent);

I know for sure that my file is being created and I can read it again with Apache POI. So the only things which doesn't work is sending the intent to another app.

As an example if I choose Google Drive in the intent chooser then following error appears:
"Upload failed: request contained no data."

If I open it with the Mailbox App following error appears:
"Mailbox could not read the selected file"

I hope you can help me guys, I appreciate your help!


问:
How to apply different icons & different text in android grid view tutorial?
Please tell me about how to change or apply different icons with different text in the android grid view tutorial. My code is

```<code>public class Home extends Activity
{
    //---the images to display---
    Integer[] imageIDs = {

    };

    GridView grid_main;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        grid_main = (GridView) findViewById(R.id.gridview);
        grid_main.setAdapter(new ImageAdapter(this));

        grid_main.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,
            View v, int position, long id)
            {
                Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();
            }
        });

    }

    public class ImageAdapter extends BaseAdapter
    {
        Context mContext;
        public static final int ACTIVITY_CREATE = 10;
        public ImageAdapter(Context c)
        {
            mContext = c;
        }

        //---returns the number of images---
        public int getCount() {
            return 12;
        }

        //---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent)
        {

            View v;
            if(convertView==null){
                LayoutInflater li = getLayoutInflater();
                v = li.inflate(R.layout.grid_item, null);
                TextView tv = (TextView)v.findViewById(R.id.icon_text1);
                tv.setText("Profile "+position);
                ImageView iv = (ImageView)v.findViewById(R.id.icon_image1);
                iv.setImageResource(R.drawable.bo_1);

            }
            else
            {
                v = convertView;
            }
            return v;
        }
    }
}
</code>```

This code is running perfectly but all the images nd text are same so i need to change it. please tell me how to do it ?
Any help would be appreciated!!

答:
Much, much, much better for ImageAdapter is:

```<code>public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                LayoutInflater li = getLayoutInflater();
                v = li.inflate(R.layout.grid_item, null);
                TextView tv = (TextView)v.findViewById(R.id.icon_text);
                tv.setText(mTextsIds[position]);
                ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
                iv.setImageResource(mThumbIds[position]);
            } else {
                v = (View) convertView;
            }
            return v;
        }

        // references to our images
        private Integer[] mThumbIds = {
                R.drawable.image1, R.drawable.image2,
                R.drawable.image3, R.drawable.image4
        };

        // references to our texts
        private String[] mTextsIds = {
                "Text 1", "Text 2", "Text 3", "Text 4"
        };
    }
</code>```

Please, note that images and texts are in variables mThumbIds and mTextsIds

The grid_item.xml is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget44"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_x="201px"
    android:layout_y="165px"
    android:gravity="center_horizontal"
    >

        <ImageView
            android:id="@+id/icon_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        />
        <TextView
            android:id="@+id/icon_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:gravity="center_horizontal"
            android:textColorHighlight="#656565"
        />
</LinearLayout>
</code>```

Body:
Please tell me about how to change or apply different icons with different text in the android grid view tutorial. My code is

public class Home extends Activity
{
    //---the images to display---
    Integer[] imageIDs = {

    };

    GridView grid_main;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        grid_main = (GridView) findViewById(R.id.gridview);
        grid_main.setAdapter(new ImageAdapter(this));

        grid_main.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,
            View v, int position, long id)
            {
                Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();
            }
        });

    }

    public class ImageAdapter extends BaseAdapter
    {
        Context mContext;
        public static final int ACTIVITY_CREATE = 10;
        public ImageAdapter(Context c)
        {
            mContext = c;
        }

        //---returns the number of images---
        public int getCount() {
            return 12;
        }

        //---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent)
        {

            View v;
            if(convertView==null){
                LayoutInflater li = getLayoutInflater();
                v = li.inflate(R.layout.grid_item, null);
                TextView tv = (TextView)v.findViewById(R.id.icon_text1);
                tv.setText("Profile "+position);
                ImageView iv = (ImageView)v.findViewById(R.id.icon_image1);
                iv.setImageResource(R.drawable.bo_1);

            }
            else
            {
                v = convertView;
            }
            return v;
        }
    }
}

This code is running perfectly but all the images nd text are same so i need to change it. please tell me how to do it ?
Any help would be appreciated!!

Body:
Much, much, much better for ImageAdapter is:

public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                LayoutInflater li = getLayoutInflater();
                v = li.inflate(R.layout.grid_item, null);
                TextView tv = (TextView)v.findViewById(R.id.icon_text);
                tv.setText(mTextsIds[position]);
                ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
                iv.setImageResource(mThumbIds[position]);
            } else {
                v = (View) convertView;
            }
            return v;
        }

        // references to our images
        private Integer[] mThumbIds = {
                R.drawable.image1, R.drawable.image2,
                R.drawable.image3, R.drawable.image4
        };

        // references to our texts
        private String[] mTextsIds = {
                "Text 1", "Text 2", "Text 3", "Text 4"
        };
    }

Please, note that images and texts are in variables mThumbIds and mTextsIds

The grid_item.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget44"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_x="201px"
    android:layout_y="165px"
    android:gravity="center_horizontal"
    >

        <ImageView
            android:id="@+id/icon_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        />
        <TextView
            android:id="@+id/icon_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:gravity="center_horizontal"
            android:textColorHighlight="#656565"
        />
</LinearLayout>


问:
ArrayList added item is replaced by the next item in for loop
I am facing a very strange situation. I add an object to an arrayList in a loop, but it is replaced by the next object. Actually second item is duplicated. ( It replaces the first item as well as inserts another object to the ArrayList.)

This is my code. I have done the debugging and included the comments where needed. Could someone point out why this happens? I am taking the object details from the database and those are working as expected.

```<code>public class Serv
{
    @Autowired
    GrpHeader objGrpHeader;

    @Autowired
    CompPesoOutgoingMsg objMsg;

    @Autowired
    OutwardMessage objOutwardMessage;

    public List<OutwardMessage> outgoingMessagesAsSingleTrx()
    {
        List<OutgoingMsg_Obj> trxList = myRepo.getTrx("5");
        List<OutwardMessage> myTrxList = new ArrayList<>();

        for (OutgoingMsg_Obj outgoingMsg : trxList)
        {
            BigDecimal trxAmt = outgoingMsg.getIntrBkSttlmAmt().getTrxn_amt();
            trxAmt = (trxAmt).divide(new BigDecimal(100));

            GrpHeader grpHeader = objGrpHeader;
            CompPesoOutgoingMsg outMsg2 = objMsg;
            OutwardMessage objOutwardMessage2 = objOutwardMessage;

            outgoingMsg.setRmtInf(objRmtInf);
            outgoingMsg.setPmtTpInf(objPmtTpInf);

            outMsg2.setHeader(grpHeader);
            outMsg2.setCdtTrfTxInf(Arrays.asList(outgoingMsg));
            objOutwardMessage2.setObjMsg(outMsg2);

            **//Here, Correct object details are printed**
            log.info("outwardMsg 100 {} ", objOutwardMessage2);

            //Add Item to the list
            myTrxList.add(objOutwardMessage2);

            for (OutwardMessage outwardMsgx : myTrxList)
            {
                //1. When this loop executed first time, first object details are printed
                //2. When printed second time, first added object is no more. And second added object is there twice.
                log.info("outwardMsg 101 {} ", outwardMsgx);
            }
        }
        return myTrxList;
    }
}
</code>```

答: You have a single reference. By setting the objOutwardMessage2to objOutwardMessageyou are just changing the data inside the reference.

Body:
I am facing a very strange situation. I add an object to an arrayList in a loop, but it is replaced by the next object. Actually second item is duplicated. ( It replaces the first item as well as inserts another object to the ArrayList.)

This is my code. I have done the debugging and included the comments where needed. Could someone point out why this happens? I am taking the object details from the database and those are working as expected.

public class Serv
{
    @Autowired
    GrpHeader objGrpHeader;

    @Autowired
    CompPesoOutgoingMsg objMsg;

    @Autowired
    OutwardMessage objOutwardMessage;

    public List<OutwardMessage> outgoingMessagesAsSingleTrx()
    {
        List<OutgoingMsg_Obj> trxList = myRepo.getTrx("5");
        List<OutwardMessage> myTrxList = new ArrayList<>();

        for (OutgoingMsg_Obj outgoingMsg : trxList)
        {
            BigDecimal trxAmt = outgoingMsg.getIntrBkSttlmAmt().getTrxn_amt();
            trxAmt = (trxAmt).divide(new BigDecimal(100));

            GrpHeader grpHeader = objGrpHeader;
            CompPesoOutgoingMsg outMsg2 = objMsg;
            OutwardMessage objOutwardMessage2 = objOutwardMessage;

            outgoingMsg.setRmtInf(objRmtInf);
            outgoingMsg.setPmtTpInf(objPmtTpInf);

            outMsg2.setHeader(grpHeader);
            outMsg2.setCdtTrfTxInf(Arrays.asList(outgoingMsg));
            objOutwardMessage2.setObjMsg(outMsg2);

            **//Here, Correct object details are printed**
            log.info("outwardMsg 100 {} ", objOutwardMessage2);

            //Add Item to the list
            myTrxList.add(objOutwardMessage2);

            for (OutwardMessage outwardMsgx : myTrxList)
            {
                //1. When this loop executed first time, first object details are printed
                //2. When printed second time, first added object is no more. And second added object is there twice.
                log.info("outwardMsg 101 {} ", outwardMsgx);
            }
        }
        return myTrxList;
    }
}


问:
How to select the only front-facing camera on Flutter
I want to select the only front-facing camera when opening Camera View at Flutter.
I searched but don't find how to resolve it.</p>

答:
Assuming you are using the this library : Camera</p>

```<code> final cameras = await availableCameras(); //get list of available cameras
 final frontCam = cameras[1]; //get the front camera and do what you want
</code>```

Body:
Assuming you are using the this library : Camera

 final cameras = await availableCameras(); //get list of available cameras
 final frontCam = cameras[1]; //get the front camera and do what you want


问:
How do i change the text when i'm submitting
I'm not able to change the text at "Enter your age" to "your age is" when submitting. Is there way that when I submit the DOB the "Enter you age" changes to "your age is: X"?

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Birthday: <input type="date" name="bday" id="birth_date">
  <br><br>
</form>

<button onclick="myFunction()">view</button><br>
<h2>Enter your age</h2>
<p id="age"></p></code>```

答:
You need to calculate your age a bit differently.
Maybe something like this:

```<code>function calculate_age(dobString) {
    var birthday = new Date(dobString),  //Year, month, day.
    today = new Date(),
    one_year = 1000*60*60*24*365;
    let yearValue = Math.floor( (today.getTime() - birthday.getTime() ) / one_year);

    let yearString = 'year'
    if (yearValue > 1){ yearString += "s" };

    document.getElementById("age").innerHTML = `Your Age is : ${yearValue} ${yearString}`;
}
</code>```

I created a fiddle for you to see it in action:

https://jsfiddle.net/cdrsfo82/

Body:
I'm not able to change the text at "Enter your age" to "your age is" when submitting. Is there way that when I submit the DOB the "Enter you age" changes to "your age is: X"?

function myFunction() {
  var dobString = document.getElementById("birth_date").value;
  var calculatedValue = calculate_age(dobString);
}

function calculate_age(dobString) {
  var diff_ms = Date.now() - Date.parse(dobString);
  var yearString = "";
  var yearValue = Math.floor(diff_ms / 31536000000);
  console.log("Years ", yearValue);

  if (yearValue > 1)
    yearString = " years";
  else
    yearString = " year";

  if (yearValue > 0)
    var calculatedValue = yearValue + yearString + " ";
  else if (yearValue == 0)
    var calculatedValue = monthValue + monthString + " ";

  document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
}

<form>
  Birthday: <input type="date" name="bday" id="birth_date">

</form>

<button onclick="myFunction()">view</button>

Enter your age

Body:
You need to calculate your age a bit differently.
Maybe something like this:

function calculate_age(dobString) {
    var birthday = new Date(dobString),  //Year, month, day.
    today = new Date(),
    one_year = 1000*60*60*24*365;
    let yearValue = Math.floor( (today.getTime() - birthday.getTime() ) / one_year);

    let yearString = 'year'
    if (yearValue > 1){ yearString += "s" };

    document.getElementById("age").innerHTML = `Your Age is : ${yearValue} ${yearString}`;
}

I created a fiddle for you to see it in action:

https://jsfiddle.net/cdrsfo82/


问:
Web Applications Converted To Desktop Applications
I have been reading some of the posts here, but haven't really seen the answers to my questions directly.  I am a web developer and need to integrate some of my web applications to some sort of desktop application.  For example, say a business has some kind of booking, it needs to be available offline (desktop in office/stores) and online, with the master database offline.  What I would like to know is the best way in doing something like this and different options.  If I can use web technology like PHP/MySQL and then use something like WinBinder to be able to handle all the work, then great, but from my research, I get the impression this is not a great approach.  PHP/MySQL is what I mainly use for backend development, however know some other languages, just haven't mastered them yet.

Can you guys suggest some methods of acheiving what I need and what languages, etc are the best?  Can I stick with web technologies, but create simple install packages so clients can install the application easily?

Thanks in advance for your help.

答:
Today, with the new browsers, you can store a local db inside the browser like you store a cookie,
my suggestion is to take some nice ui web framework like sproutecore or if you like php go for jqm php, and use it as desktop app, check the offline features that the frameworks offer before you start.</p>


问:
Dynamically swapping out or toggling visibility of controls
I have a TreeView in a form, that is dock-filled to a groupbox. The problem to solve is, that there is an operation that is run on a Task, which loads data from a server application. When this is running, there should be a progress indicator displayed in the location of the TreeView. That is, it should be shown instead of the TreeView, and take its place fully. The following is what the code for this looks like:

```<code>private async void preload_data(object sender, System.EventArgs args)
{
    try
    {
        // the treeView should be disabled/invisible at this point
        // make the CircularProgressBar enabled/visible

        // get the information from the server
        await Configuration.network.fetch_stuff();
    }
    catch (Exception ex)
    {
        // something bad happened
    }
    finally
    {
        // whatever happened, the treeView should be back
    }
}
</code>```

The CircularProgressBar (a third-party control) should appear as in the code above, and should replace the TreeView. It should fill the exact same space as the TreeView would, which is dock-filled. Below is a screenshot of this:

This form and all its controls have been designed in the designer, and I don't want to do it there, I want to do it programmatically. What is the best way to go about this? I have looked at examples of Controls.Remove() and Controls.Add(), but it's not clear if that fits this purpose.

答:
It is quite common to change the visual output while actions are running, like you do. Think of disabling buttons, to discourage operators to press the button again, or show something visually, to inform operators about the progress.

For simplicity, without the try-catch

```<code>private async Task PreloadDataAsync()
{
    this.ShowFetchingData(true);

    // start fetching data, do not await:
    var taskFetchData = Configuration.network.fetch_stuff();

    // while taskFetchData not completed, await some time
    TimeSpan updateTime = TimeSpan.FromSeconds(0.250);
    int progressCounter = 0;
    while (!taskFetchData.IsCompleted)
    {
        this.ShowProgress(progressCounter);
        var taskWait = Task.Delay(updateTime);
        await Task.WhenAny(new Task[] {taskFetchData, taskWait};
        // either taskFetchData.IsCompleted, or Delay time waited
        ++progressCounter;
    }

    this.ShowFetchingData(false);
}

private void ShowFetchindData(bool show)
{
    // disable/enable certain buttons, menu items, show progressbar?
    this.ButtonFetchData.Enabled = !show;
    this.MenuFetchData.Enabled = !show;
    this.ProgressBarFetchData.Visible = show;
}

private bool IsFetchingData => this.ProgressBarFetchData.Visible;

private void ShowProgress(int progress)
{
    this.ProgressBarFetchData.Position = progress;
}
</code>```

For simplicity, I've left out checks for the position in the progress bar, but you get the gist.

Usage:

```<code>private async void OnButtonFetchData(object sender, EventArgs e)
{
    await this.PreloadDataAsync();
}
</code>```

Room for improvement

The problem with this is that there is no timeout at all: if FetchStuff does not complete, you are in an endless wait. The method that microsoft proposes is the use of a CancellationToken. Almost every async method has an overload with a CancellationToken. Consider creating one yourself:

```<code>// existing method:
private async Task<MyData> fetch_Stuff()
{
    await this.fetch_stuff(CancellationToken.None);
}

// added method with CancellationToken
private async Task<MyData> fetch_Stuff(CancellationToken token)
{
    // Call async function overloads with the token,
    // Regularly check if cancellation requested

    while (!token.IsCancellationRequested)
    {
        ... // fetch some more data, without waiting too long
    }
}
</code>```

Instead of IsCancellationRequested, consider to throw an exception: ThrowIfCancellationRequested.

Usage:

```<code>private async Task PreloadDataAsync()
{
    // preloading should be finished within 30 seconds
    // let the cancellationTokenSource request cancel after 30 seconds
    TimeSpan maxPreloadTime = TimeSpan.FromSeconds(30);
    using (var cancellationTokenSource = new CancellationTokenSource(maxPreloadTime))
    {
         await PreloadDataAsync(cancellationTokenSource.Token);
    }
}
</code>```

The overload with CancellationToken:

```<code>private async Task PreloadDataAsync(CancellationToken token)
{
    this.ShowFetchingData(true);

    // execute code similar to above, use overloads that accept token:
    try
    {
        var taskFetchData = Configuration.network.fetch_stuff(token);
        TimeSpan updateTime = TimeSpan.FromSeconds(0.250);
        int progressCounter = 0;
        while (!taskFetchData.IsCompleted)
        {
            token.ThrowIfCancellationRequested();
            this.ShowProgress(progressCounter);
            var taskWait = Task.Delay(updateTime, token);
            await Task.WhenAny(new Task[] {taskFetchData, taskWait};
            // either taskFetchData.IsCompleted, or Delay time waited
            ++progressCounter;
        }
    }
    catch (TaskCancelledException exc)
    {
         this.ReportPreloadTimeout();
    }
    finally
    {
        this.ShowFetchingData(false);
    }
}
</code>```

Or if you want a button that cancels the task:

```<code>private CancellationTokenSource cancellationTokenSource = null;

private book IsPreloading => this.CancellationTokenSource != null;

private async Task StartStopPreload()
{
    if (!this.IsPreloading)
       StartPreload();
    else
       CancelPreload();
}

private async Task StartPreload()
{
    // preload not started yet; start it without timeout;
    try
        {
            this.cancellationTokenSource = new CancellationTokenSource();
            await PreloadDataAsync(this.cancellationTokenSource.Token);
        }
        catch (TaskCancelledException exc)
        {
            this.ReportPreloadCancelled();
        }
        finally
        {
            this.cancellationTokenSource.Dispose();
            this.cancellationTokenSource = null;
        }
    }
}
</code>```

The method where operators can stop preloading:

```<code>private async void StopPreload()
{
    this.cancellationTokenSource.Cancel();
    // the method that created this source will Dispose it and assign null
}
</code>```

All you have to do is create buttons / menu items to start / stop preloading

Body:
I have a TreeView in a form, that is dock-filled to a groupbox. The problem to solve is, that there is an operation that is run on a Task, which loads data from a server application. When this is running, there should be a progress indicator displayed in the location of the TreeView. That is, it should be shown instead of the TreeView, and take its place fully. The following is what the code for this looks like:

private async void preload_data(object sender, System.EventArgs args)
{
    try
    {
        // the treeView should be disabled/invisible at this point
        // make the CircularProgressBar enabled/visible

        // get the information from the server
        await Configuration.network.fetch_stuff();
    }
    catch (Exception ex)
    {
        // something bad happened
    }
    finally
    {
        // whatever happened, the treeView should be back
    }
}

The CircularProgressBar (a third-party control) should appear as in the code above, and should replace the TreeView. It should fill the exact same space as the TreeView would, which is dock-filled. Below is a screenshot of this:

This form and all its controls have been designed in the designer, and I don't want to do it there, I want to do it programmatically. What is the best way to go about this? I have looked at examples of Controls.Remove() and Controls.Add(), but it's not clear if that fits this purpose.

Body:
It is quite common to change the visual output while actions are running, like you do. Think of disabling buttons, to discourage operators to press the button again, or show something visually, to inform operators about the progress.

For simplicity, without the try-catch

private async Task PreloadDataAsync()
{
    this.ShowFetchingData(true);

    // start fetching data, do not await:
    var taskFetchData = Configuration.network.fetch_stuff();

    // while taskFetchData not completed, await some time
    TimeSpan updateTime = TimeSpan.FromSeconds(0.250);
    int progressCounter = 0;
    while (!taskFetchData.IsCompleted)
    {
        this.ShowProgress(progressCounter);
        var taskWait = Task.Delay(updateTime);
        await Task.WhenAny(new Task[] {taskFetchData, taskWait};
        // either taskFetchData.IsCompleted, or Delay time waited
        ++progressCounter;
    }

    this.ShowFetchingData(false);
}

private void ShowFetchindData(bool show)
{
    // disable/enable certain buttons, menu items, show progressbar?
    this.ButtonFetchData.Enabled = !show;
    this.MenuFetchData.Enabled = !show;
    this.ProgressBarFetchData.Visible = show;
}

private bool IsFetchingData => this.ProgressBarFetchData.Visible;

private void ShowProgress(int progress)
{
    this.ProgressBarFetchData.Position = progress;
}

For simplicity, I've left out checks for the position in the progress bar, but you get the gist.

Usage:

private async void OnButtonFetchData(object sender, EventArgs e)
{
    await this.PreloadDataAsync();
}

Room for improvement

The problem with this is that there is no timeout at all: if FetchStuff does not complete, you are in an endless wait. The method that microsoft proposes is the use of a CancellationToken. Almost every async method has an overload with a CancellationToken. Consider creating one yourself:

// existing method:
private async Task<MyData> fetch_Stuff()
{
    await this.fetch_stuff(CancellationToken.None);
}

// added method with CancellationToken
private async Task<MyData> fetch_Stuff(CancellationToken token)
{
    // Call async function overloads with the token,
    // Regularly check if cancellation requested

    while (!token.IsCancellationRequested)
    {
        ... // fetch some more data, without waiting too long
    }
}

Instead of IsCancellationRequested, consider to throw an exception: ThrowIfCancellationRequested.

Usage:

private async Task PreloadDataAsync()
{
    // preloading should be finished within 30 seconds
    // let the cancellationTokenSource request cancel after 30 seconds
    TimeSpan maxPreloadTime = TimeSpan.FromSeconds(30);
    using (var cancellationTokenSource = new CancellationTokenSource(maxPreloadTime))
    {
         await PreloadDataAsync(cancellationTokenSource.Token);
    }
}

The overload with CancellationToken:

private async Task PreloadDataAsync(CancellationToken token)
{
    this.ShowFetchingData(true);

    // execute code similar to above, use overloads that accept token:
    try
    {
        var taskFetchData = Configuration.network.fetch_stuff(token);
        TimeSpan updateTime = TimeSpan.FromSeconds(0.250);
        int progressCounter = 0;
        while (!taskFetchData.IsCompleted)
        {
            token.ThrowIfCancellationRequested();
            this.ShowProgress(progressCounter);
            var taskWait = Task.Delay(updateTime, token);
            await Task.WhenAny(new Task[] {taskFetchData, taskWait};
            // either taskFetchData.IsCompleted, or Delay time waited
            ++progressCounter;
        }
    }
    catch (TaskCancelledException exc)
    {
         this.ReportPreloadTimeout();
    }
    finally
    {
        this.ShowFetchingData(false);
    }
}

Or if you want a button that cancels the task:

private CancellationTokenSource cancellationTokenSource = null;

private book IsPreloading => this.CancellationTokenSource != null;

private async Task StartStopPreload()
{
    if (!this.IsPreloading)
       StartPreload();
    else
       CancelPreload();
}

private async Task StartPreload()
{
    // preload not started yet; start it without timeout;
    try
        {
            this.cancellationTokenSource = new CancellationTokenSource();
            await PreloadDataAsync(this.cancellationTokenSource.Token);
        }
        catch (TaskCancelledException exc)
        {
            this.ReportPreloadCancelled();
        }
        finally
        {
            this.cancellationTokenSource.Dispose();
            this.cancellationTokenSource = null;
        }
    }
}

The method where operators can stop preloading:

private async void StopPreload()
{
    this.cancellationTokenSource.Cancel();
    // the method that created this source will Dispose it and assign null
}

All you have to do is create buttons / menu items to start / stop preloading