问:
Avoiding [weak self] for simple operations?
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

```<code>final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}
</code>```

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?

答:
If you are worried about reference cycles, you usually don't get one when using URL requests. The thing is that the URL request finishes sooner or later (after several minutes) and you controller gets released. The reference cycle is only temporary and it won't cause a memory leak.

The question is whether you want to keep the controller in memory even if the user has already closed the controller and it won't be ever shown again. It won't probably cause any problems but it's still wasteful. You are holding to memory you don't need and that cannot be reused.

Also note that you might actually want to cancel the running request when the controller is dismissed to avoid sending/receiving data that is not necessary anymore.

In my opinion, you shouldn't worry that much about reference cycles and think more about ownership. A strong reference means that something is owned. The request has no reason to "own" the controller. It's the other way around - the controller owns and manages the request. If there is no ownership, I would use weak just for clarity.

Body:
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?


来源: stackexchange

问:
Can't convert a tf.data.Dataset object to a numpy iterator
I am using Tensorflow 1.14.0 and tensorflow_datasets 1.2.0

When trying to run the following code

```<code>import tensorflow as tf
import tensorflow_datasets as tfds

smallnorb = tfds.load("smallnorb")
smallnorb_train, smallnorb_test = smallnorb["train"], smallnorb["test"]
assert isinstance(smallnorb_train, tf.data.Dataset)
smallnorb_train = smallnorb_train.as_numpy_iterator()
</code>```

I get the following error

```<code>AttributeError: 'DatasetV1Adapter' object has no attribute 'as_numpy_iterator'
</code>```

According to the tensorflow_datasets docs this should work.

Why won't it? And why am I getting a DatasetV1Adapter object in the first place?

答:
As @szymon mentioned, tensorflow-1.14 does not support the as_numpy_iterator. You should move your code to tf>=2.0

A handy tip which I frequently use is firing up a REPL python shell in one of the bash shells and use dir(tf.data.Dataset) to list all the attributes & methods that can be called from that object. You can further use the help(tf.data.Dataset.xxx) for parameters and return values of that method.

```<code>>>> import tensorflow as tf
>>> dir(tf.data.Dataset)
... <output>

>>> help(tf.data.Dataset.from_tensor_slices)
... and so on
</code>```

If you do the same, you'll find that as_numpy_iterator won't be present in the dir(tf.data.Dataset) list output, hence the error.

ContentLicense: CC BY-SA 4.0

Body:
I am using Tensorflow 1.14.0 and tensorflow_datasets 1.2.0

When trying to run the following code

import tensorflow as tf
import tensorflow_datasets as tfds

smallnorb = tfds.load("smallnorb")
smallnorb_train, smallnorb_test = smallnorb["train"], smallnorb["test"]
assert isinstance(smallnorb_train, tf.data.Dataset)
smallnorb_train = smallnorb_train.as_numpy_iterator()

I get the following error

AttributeError: 'DatasetV1Adapter' object has no attribute 'as_numpy_iterator'

According to the tensorflow_datasets docs this should work.

Why won't it? And why am I getting a DatasetV1Adapter object in the first place?

Body:
As @szymon mentioned, tensorflow-1.14 does not support the as_numpy_iterator. You should move your code to tf>=2.0

A handy tip which I frequently use is firing up a REPL python shell in one of the bash shells and use dir(tf.data.Dataset) to list all the attributes & methods that can be called from that object. You can further use the help(tf.data.Dataset.xxx) for parameters and return values of that method.

>>> import tensorflow as tf
>>> dir(tf.data.Dataset)
... <output>

>>> help(tf.data.Dataset.from_tensor_slices)
... and so on

If you do the same, you'll find that as_numpy_iterator won't be present in the dir(tf.data.Dataset) list output, hence the error.


问:
bxSlider - onSlideAfter
```<code>paramsSlider = {
        slideWidth: 76,
        slideMargin: 10,
        minSlides: 1,
        maxSlides: 10,
        pager: false,
        controls: true,
        moveSlides: 5,

        onSlideAfter: function($slideElement, oldIndex, newIndex) {
            let count = Math.floor(this.getSlideCount()/5)-1;
        }
    };
</code>```

how can I get the value moveSlides inside the function onSlideAfter?
if I try to apply like a this.moveSlides, I get undefined

maybe I don’t understand something, but if I try this way, I get undefined again

```<code>countSlides: 5;
paramsSlider = {
    slideWidth: 76,
    slideMargin: 10,
    minSlides: 1,
    maxSlides: 10,
    pager: false,
    controls: true,
    moveSlides: this.countSlides,
    onSlideAfter: function($slideElement, oldIndex, newIndex) {
        console.log(this.countSlides)
    },
}
</code>```

答:
You could write a getter for it.

const paramsSlider = {
  slideWidth: 76,
  slideMargin: 10,
  minSlides: 1,
  maxSlides: 10,
  pager: false,
  controls: true,
  moveSlides: 5,
  get moveSlidesVal() {
    return this.moveSlides;
  },
  onSlideAfter: function() {
    let count = Math.floor(this.getSlideCount() / 5) - 1;
    count += this.moveSlidesVal;
    return count;
  },
  getSlideCount: function() {
    return 100; // sample value
  }
};

document.write(paramsSlider.onSlideAfter()); // 24 expected```

Title: bxSlider - onSlideAfter

Body:
paramsSlider = {
        slideWidth: 76,
        slideMargin: 10,
        minSlides: 1,
        maxSlides: 10,
        pager: false,
        controls: true,
        moveSlides: 5,

        onSlideAfter: function($slideElement, oldIndex, newIndex) {
            let count = Math.floor(this.getSlideCount()/5)-1;
        }
    };

how can I get the value moveSlides inside the function onSlideAfter?
if I try to apply like a this.moveSlides, I get undefined

maybe I don’t understand something, but if I try this way, I get undefined again

countSlides: 5;
paramsSlider = {
    slideWidth: 76,
    slideMargin: 10,
    minSlides: 1,
    maxSlides: 10,
    pager: false,
    controls: true,
    moveSlides: this.countSlides,
    onSlideAfter: function($slideElement, oldIndex, newIndex) {
        console.log(this.countSlides)
    },
}


问:
SQL get single row based on multiple condition after group by
Need help with creating query for below case :

Suppose I have a Table with following records

```<code>Name      Date        Time   Category CategoryKey
John      10/20/2012  10:00  Low       2
Sam       10/20/2012  10:00  High      4
Harry     10/20/2012  10:00  Medium    1
Michael   10/20/2012  10:00  Grey      3
Rob       10/22/2013  11:00  Low       2
Marry     10/23/2014  12:00  Low       2
Richard   10/23/2014  12:00  Grey      3
Jack      10/24/2015  1:30   High      4
</code>```

Then If there are multiple Names for same date and time then force select only one record based on following logic and stop when any 1 of the following condition is met.

```<code>If Category is Medium then take name
Else If Category is High then take name
Else If Category is Low then take name
Else If Category is Grey then take name
</code>```

So that the Final result will be

```<code>Name      Date        Time   Category CategoryKey

Harry     10/20/2012  10:00  Medium    1
Rob       10/22/2013  11:00  Low       2
Marry     10/23/2014  12:00  Low       2
Jack      10/24/2015  1:30   High      4
</code>```

答:
The simplest method is row_number():

```<code>select t.*
from (select t.*,
             row_number() over (partition by date, time
                                order by (case category when 'Medium' then 1 when 'High' then 2 when 'Low' then 3 when 'Grey' then 4 else 5 end)
                               ) as seqnum
      from t
     ) t
where seqnum = 1;
</code>```

It can be convenient to use string functions here:

```<code>             row_number() over (partition by date, time
                                order by charindex(category, 'Medium,High,Low,Grey')
                               ) as seqnum
</code>```

This works for your case, but you need to be a little careful that all values are included and that none "contain" another value.

Body:
Need help with creating query for below case :

Suppose I have a Table with following records

Name      Date        Time   Category CategoryKey
John      10/20/2012  10:00  Low       2
Sam       10/20/2012  10:00  High      4
Harry     10/20/2012  10:00  Medium    1
Michael   10/20/2012  10:00  Grey      3
Rob       10/22/2013  11:00  Low       2
Marry     10/23/2014  12:00  Low       2
Richard   10/23/2014  12:00  Grey      3
Jack      10/24/2015  1:30   High      4

Then If there are multiple Names for same date and time then force select only one record based on following logic and stop when any 1 of the following condition is met.

If Category is Medium then take name
Else If Category is High then take name
Else If Category is Low then take name
Else If Category is Grey then take name

So that the Final result will be

Name      Date        Time   Category CategoryKey

Harry     10/20/2012  10:00  Medium    1
Rob       10/22/2013  11:00  Low       2
Marry     10/23/2014  12:00  Low       2
Jack      10/24/2015  1:30   High      4

Body:
The simplest method is row_number():

select t.*
from (select t.*,
             row_number() over (partition by date, time
                                order by (case category when 'Medium' then 1 when 'High' then 2 when 'Low' then 3 when 'Grey' then 4 else 5 end)
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

It can be convenient to use string functions here:

             row_number() over (partition by date, time
                                order by charindex(category, 'Medium,High,Low,Grey')
                               ) as seqnum

This works for your case, but you need to be a little careful that all values are included and that none "contain" another value.


问:
python reading csv, text inside comma inside a column having double double inverted comma "" text,text2 ""causing split with the comma
Well I have been sent a csv by othe system with comma as the delimiter. one row has one column with sample values as:
,""ABC. & XYZ (CfdfB,afGgM)_0110"" , .
This row cause of this column is causing error.
While debugging Now when I read this using python and printed row, this particular value is printed as:
'ABC. & XYZ (CfdfB', ' afGgM)_0110""'
so this valus is getting split, reason being double of " and a comma in between.

code used is:

```<code>    with open(abccsv, "r",  newline='',encoding="UTF-8") as file:
        reader = csv.reader(file, quotechar='"', delimiter=",",quoting=csv.QUOTE_ALL)
        # counter = 0
        for row in reader:
            print(row)

</code>```

答: Try a different delimiter than comma. It's splitting because it's using comma as it's delimiter for CSV files. Try tab or something else.</p>

Body:
Well I have been sent a csv by othe system with comma as the delimiter. one row has one column with sample values as:
,""ABC. & XYZ (CfdfB,afGgM)_0110"" , .
This row cause of this column is causing error.
While debugging Now when I read this using python and printed row, this particular value is printed as:
'ABC. & XYZ (CfdfB', ' afGgM)_0110""'
so this valus is getting split, reason being double of " and a comma in between.

code used is:

    with open(abccsv, "r",  newline='',encoding="UTF-8") as file:
        reader = csv.reader(file, quotechar='"', delimiter=",",quoting=csv.QUOTE_ALL)
        # counter = 0
        for row in reader:
            print(row)


问:
Seekbar not working in Chrome
I have uploaded a video to my Windows Storage and noticed, that the seekbar (of the default Chrome's html5 player) is not working. Url of that video is:

http://portalvhdsrwglplr5bdc2k.blob.core.windows.net/vdepot/uploads/video/file/167/surfer-girl-35094486.mp4

Please note: Seekbar is not working when video download is in progress or it's 100% the first time. If video has been downloaded by chrome player and you refresh the page, seekbar works fine.

I'm a video encoding newbie thus i'm not sure if that's the problem with the video, with browser or maybe with windows azure in some way? I also can't find anything about that topic in google.

答:
The issue here is that a brand new AZURE storage account default implementation does not support supplying the correct headers "Accept-Ranges: bytes" in the HTTP response for the HTTP 206 Partial Content

To fix this you will need to set the DefaultServiceVersion for your storage account to version 2013-08-15 or later. In their documentation, they say this was officially supported in version 2011-08-18, but in my testing, I do not see it until I set it to version 2013-08-15. In the end, I just updated it to the latest version 2019-02-02. I will show you how to do that in a moment.

With that said here are some steps you can take to test and verify this and then how to fix it.

Create a brand new AZURE storage account, add a new container and then upload an MP4 to that container. To see the default headers for your MP4 run the following curl command

```<code>curl -I https://<StorageAccount>.blob.core.windows.net/<YourContainer>/<Your>.mp4
</code>```

Here are the headers you should see your response

```<code>HTTP/1.1 200 OK
Content-Length: 8655515
Content-Type: video/mp4
Last-Modified: Fri, 29 Nov 2019 21:45:12 GMT
ETag: 0x8D7751569DECA07
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: cc44ae3e-b01e-00b5-2337-e4372d000000
x-ms-version: 2009-09-19
x-ms-lease-status: unlocked
x-ms-blob-type: BlockBlob
Access-Control-Expose-Headers: x-ms-request-id,Server,x-ms-version,Content-Type,Last-Modified,ETag,x-ms-lease-status,x-ms-blob-type,Content-Length,Date,Transfer-Encoding
Access-Control-Allow-Origin: *
Date: Sat, 15 Feb 2020 19:36:37 GMT
</code>```

You will see that the following header is missing is

```<code>Accept-Ranges: bytes
</code>```

You can then verify this header will return when you run the following curl command

```<code>curl -I -H x-ms-version:2013-08-15 https://<StorageAccount>.blob.core.windows.net/<YourContainer>/<Your>.mp4
</code>```

To permanently set the storage account version I used LinqPad and the following code with a reference to the Windows.Azure.Storage Nuget Pacakge

```<code>var connectionString = "DefaultEndpointsProtocol=https;AccountName=<YourAcountName>;AccountKey=<YourAccountKey>;";
var storageAccount = CloudStorageAccount.Parse(connectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var props = await blobClient.GetServicePropertiesAsync();
props.Dump(); /* Here you will see that the DefaultServiceVersion is null*/
props.DefaultServiceVersion = "2019-02-02";
await blobClient.SetServicePropertiesAsync(props);
</code>```

The first time you run this you will see that the DefaultServiceVersion is null. If you run this a second time you will then see the DefaultServiceVersion will be the version you set.

If you then run the curl command again.

```<code>curl -I https://<StorageAccount>.blob.core.windows.net/<YourContainer>/<Your>.mp4
</code>```

You will see the following headers, which now includes the "Accept-Ranges: bytes" header and your seek will work.

```<code>HTTP/1.1 200 OK
Content-Length: 8655515
Content-Type: video/mp4
Last-Modified: Fri, 29 Nov 2019 21:45:12 GMT
Accept-Ranges: bytes
ETag: "0x8D7751569DECA07"
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: b95228de-f01e-0135-4596-e5d2d2000000
x-ms-version: 2019-02-02
x-ms-creation-time: Fri, 29 Nov 2019 21:45:12 GMT
x-ms-lease-status: unlocked
x-ms-lease-state: available
x-ms-blob-type: BlockBlob
x-ms-server-encrypted: true
x-ms-access-tier: Hot
x-ms-access-tier-inferred: true
Date: Mon, 17 Feb 2020 13:33:00 GMT
</code>```

ContentLicense: CC BY-SA 3.0

Title: Seekbar not working in Chrome

Body:
The issue here is that a brand new AZURE storage account default implementation does not support supplying the correct headers "Accept-Ranges: bytes" in the HTTP response for the HTTP 206 Partial Content

To fix this you will need to set the DefaultServiceVersion for your storage account to version 2013-08-15 or later. In their documentation, they say this was officially supported in version 2011-08-18, but in my testing, I do not see it until I set it to version 2013-08-15. In the end, I just updated it to the latest version 2019-02-02. I will show you how to do that in a moment.

With that said here are some steps you can take to test and verify this and then how to fix it.

Create a brand new AZURE storage account, add a new container and then upload an MP4 to that container. To see the default headers for your MP4 run the following curl command

curl -I https://<StorageAccount>.blob.core.windows.net/<YourContainer>/<Your>.mp4

Here are the headers you should see your response

HTTP/1.1 200 OK
Content-Length: 8655515
Content-Type: video/mp4
Last-Modified: Fri, 29 Nov 2019 21:45:12 GMT
ETag: 0x8D7751569DECA07
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: cc44ae3e-b01e-00b5-2337-e4372d000000
x-ms-version: 2009-09-19
x-ms-lease-status: unlocked
x-ms-blob-type: BlockBlob
Access-Control-Expose-Headers: x-ms-request-id,Server,x-ms-version,Content-Type,Last-Modified,ETag,x-ms-lease-status,x-ms-blob-type,Content-Length,Date,Transfer-Encoding
Access-Control-Allow-Origin: *
Date: Sat, 15 Feb 2020 19:36:37 GMT

You will see that the following header is missing is

Accept-Ranges: bytes

You can then verify this header will return when you run the following curl command

curl -I -H x-ms-version:2013-08-15 https://<StorageAccount>.blob.core.windows.net/<YourContainer>/<Your>.mp4

To permanently set the storage account version I used LinqPad and the following code with a reference to the Windows.Azure.Storage Nuget Pacakge

var connectionString = "DefaultEndpointsProtocol=https;AccountName=<YourAcountName>;AccountKey=<YourAccountKey>;";
var storageAccount = CloudStorageAccount.Parse(connectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var props = await blobClient.GetServicePropertiesAsync();
props.Dump(); /* Here you will see that the DefaultServiceVersion is null*/
props.DefaultServiceVersion = "2019-02-02";
await blobClient.SetServicePropertiesAsync(props);

The first time you run this you will see that the DefaultServiceVersion is null. If you run this a second time you will then see the DefaultServiceVersion will be the version you set.

If you then run the curl command again.

curl -I https://<StorageAccount>.blob.core.windows.net/<YourContainer>/<Your>.mp4

You will see the following headers, which now includes the "Accept-Ranges: bytes" header and your seek will work.

HTTP/1.1 200 OK
Content-Length: 8655515
Content-Type: video/mp4
Last-Modified: Fri, 29 Nov 2019 21:45:12 GMT
Accept-Ranges: bytes
ETag: "0x8D7751569DECA07"
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: b95228de-f01e-0135-4596-e5d2d2000000
x-ms-version: 2019-02-02
x-ms-creation-time: Fri, 29 Nov 2019 21:45:12 GMT
x-ms-lease-status: unlocked
x-ms-lease-state: available
x-ms-blob-type: BlockBlob
x-ms-server-encrypted: true
x-ms-access-tier: Hot
x-ms-access-tier-inferred: true
Date: Mon, 17 Feb 2020 13:33:00 GMT


问:
Powermockito NotAMockException even though object is a mock
I am trying to mock Uri.parse() to always return a mocked Uri object. Unfortunately I am told, that the object I try to return is not a mocked object, but I am unable to understand why.

My code:

```<code>package com.example.recyclerview;

import android.net.Uri;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Uri.class})
public class SimpleExampleTest {

    @Test
    public void setup(){
        PowerMockito.mockStatic(Uri.class);
        Uri uri = mock(Uri.class);
        try {
            // this line causes the error
            PowerMockito.when(Uri.class, "parse", anyString()).thenReturn(uri);
            // also tried line below, but still got the same error:
            // PowerMockito.doReturn(uri).when(Uri.class, "parse", anyString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

</code>```

My build.gradle:

```<code>// Unit Tests
    //jUnit
    testImplementation 'junit:junit:4.12'
    //Mockito
    testImplementation 'org.mockito:mockito-core:2.8.9'
    // Mockito mock okHttp Response (and probably other final classes)
    testImplementation 'org.mockito:mockito-inline:2.13.0'
    // Json for mockito
    testImplementation 'org.json:json:20140107'
    // Instant executor rule
    testImplementation "androidx.arch.core:core-testing:2.1.0"
    // PowerMockito to extend Mockito for static methods
    testImplementation "org.powermock:powermock-api-mockito2:2.0.5"
    testImplementation "org.powermock:powermock-module-junit4:2.0.5"
</code>```

This is the error I get:

```<code>org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class
</code>```

答:
The error seemed to be related to Mockito/Powermockito problems.
To solve this issue I had to use these Mockito versions:

```<code>testImplementation 'org.mockito:mockito-core:2.23.4'

testImplementation "org.powermock:powermock-api-mockito2:2.0.0"
testImplementation "org.powermock:powermock-module-junit4:2.0.0"
</code>```

See also the discussion here:
https://github.com/powermock/powermock/issues/992#issuecomment-537439824

Body:
I am trying to mock Uri.parse() to always return a mocked Uri object. Unfortunately I am told, that the object I try to return is not a mocked object, but I am unable to understand why.

My code:

package com.example.recyclerview;

import android.net.Uri;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Uri.class})
public class SimpleExampleTest {

    @Test
    public void setup(){
        PowerMockito.mockStatic(Uri.class);
        Uri uri = mock(Uri.class);
        try {
            // this line causes the error
            PowerMockito.when(Uri.class, "parse", anyString()).thenReturn(uri);
            // also tried line below, but still got the same error:
            // PowerMockito.doReturn(uri).when(Uri.class, "parse", anyString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

My build.gradle:

// Unit Tests
    //jUnit
    testImplementation 'junit:junit:4.12'
    //Mockito
    testImplementation 'org.mockito:mockito-core:2.8.9'
    // Mockito mock okHttp Response (and probably other final classes)
    testImplementation 'org.mockito:mockito-inline:2.13.0'
    // Json for mockito
    testImplementation 'org.json:json:20140107'
    // Instant executor rule
    testImplementation "androidx.arch.core:core-testing:2.1.0"
    // PowerMockito to extend Mockito for static methods
    testImplementation "org.powermock:powermock-api-mockito2:2.0.5"
    testImplementation "org.powermock:powermock-module-junit4:2.0.5"

This is the error I get:

org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class

Body:
The error seemed to be related to Mockito/Powermockito problems.
To solve this issue I had to use these Mockito versions:

testImplementation 'org.mockito:mockito-core:2.23.4'

testImplementation "org.powermock:powermock-api-mockito2:2.0.0"
testImplementation "org.powermock:powermock-module-junit4:2.0.0"

See also the discussion here:
https://github.com/powermock/powermock/issues/992#issuecomment-537439824


问:
Why must a variable be declared in a for loop initialization?

int v = 0;

for (v; v<2; v++) {
    ...

}
```

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?

答:
You don't have to declare a variable in the ForInit.

As others have pointed out, you can simply omit the ForInit; but you can also use a list of statement expressions there.

For example, you can create new class instances, invoke methods and assign/increment/decrement variables:

```<code>int v;
for (new String(), "".toString(), v = 0, v++;;);
</code>```

(This example is nonsensical, but legal)

However, you cannot mix these statement expressions with local variable declarations.

Body:
int v = 0;

for (v; v<2; v++) {
    ...

}

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?

Body:
You don't have to declare a variable in the ForInit.

As others have pointed out, you can simply omit the ForInit; but you can also use a list of statement expressions there.

For example, you can create new class instances, invoke methods and assign/increment/decrement variables:

int v;
for (new String(), "".toString(), v = 0, v++;;);

(This example is nonsensical, but legal)

However, you cannot mix these statement expressions with local variable declarations.


问:
CATransiton Flicker w/ background animations
I am using a CATransition to shuffle CALayer's in and out of a UIView (the UIView isn't fullscreen.)  The new layer enters from the right and the old layer leaves to the left.  The CAlayer's have their contents properties set to CGImageRefs.  Here is what I believe to be the pertinent code:

```<code>CATransition *transition = [CATransition animation];

transition.duration = transitionTime;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;

transition.delegate = self;
[view.layer addAnimation:transition forKey:nil];

// onDeck is the layer stage-right and is about to enter
[view.layer addSublayer:onDeck];

// onStage is the layer currently in the middle of the view and is exiting
if (onStage)
   [onStage removeFromSuperlayer];
</code>```

This animation occurs, there is a 1 second pause, and then a new image is animated in etc, etc.  This works beautifully in the simulator but on my 2nd generation iPod Touch, there are occasional hiccups in the animation.  Specifically, the layer being animated in will flicker on top of the currently displayed layer.  These flickers are not consistent but are noticeable.

What I've narrowed down to be the likely culprit(s) are the background animations I have going on behind this transition.  There are a few dozen CAlayer's flying in and out of the full-screen view in the background.  When I remove these background animations or set the animation duration for the transition to a much higher duration (2 seconds +) the animation performs fine (I'd like the animation time to be 0.75 seconds.)

My first thought (which seems to be backed up by the above observations) is that I am pushing CoreAnimation (at least for my iPod) too hard and need to compromise.  Why I am having trouble accepting this is that the scene renders very nicely (little to no lag) aside from this occasional flicker.

If anyone has any input on this issue, or CoreAnimation optimization in general, I'd be very much appreciative!

Thanks for reading

Update:

Had a chance to test this on an iPhone 4 and the flickering never occurred.  Additionally, CoreAnimation instrument confirmed that, on my 2nd generation iPod Touch, I am consistently getting high 40s to low/mid 50s in FPS.

答:
Just a guess: have you tried managing your CATransactions at all?

You might try bracketing your modifications to the scene like this:

```<code>[ CATransaction begin ]
... your animations ...
[ CATransaction commit ] ;
</code>```

Body:
I am using a CATransition to shuffle CALayer's in and out of a UIView (the UIView isn't fullscreen.)  The new layer enters from the right and the old layer leaves to the left.  The CAlayer's have their contents properties set to CGImageRefs.  Here is what I believe to be the pertinent code:

CATransition *transition = [CATransition animation];

transition.duration = transitionTime;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;

transition.delegate = self;
[view.layer addAnimation:transition forKey:nil];

// onDeck is the layer stage-right and is about to enter
[view.layer addSublayer:onDeck];

// onStage is the layer currently in the middle of the view and is exiting
if (onStage)
   [onStage removeFromSuperlayer];

This animation occurs, there is a 1 second pause, and then a new image is animated in etc, etc.  This works beautifully in the simulator but on my 2nd generation iPod Touch, there are occasional hiccups in the animation.  Specifically, the layer being animated in will flicker on top of the currently displayed layer.  These flickers are not consistent but are noticeable.

What I've narrowed down to be the likely culprit(s) are the background animations I have going on behind this transition.  There are a few dozen CAlayer's flying in and out of the full-screen view in the background.  When I remove these background animations or set the animation duration for the transition to a much higher duration (2 seconds +) the animation performs fine (I'd like the animation time to be 0.75 seconds.)

My first thought (which seems to be backed up by the above observations) is that I am pushing CoreAnimation (at least for my iPod) too hard and need to compromise.  Why I am having trouble accepting this is that the scene renders very nicely (little to no lag) aside from this occasional flicker.

If anyone has any input on this issue, or CoreAnimation optimization in general, I'd be very much appreciative!

Thanks for reading

Update:

Had a chance to test this on an iPhone 4 and the flickering never occurred.  Additionally, CoreAnimation instrument confirmed that, on my 2nd generation iPod Touch, I am consistently getting high 40s to low/mid 50s in FPS.

Body:
Just a guess: have you tried managing your CATransactions at all?

You might try bracketing your modifications to the scene like this:

[ CATransaction begin ]
... your animations ...
[ CATransaction commit ] ;


问:
Using Linq to iterate groups and change property with condition
I want to iterate through each group and set "IsQualified= true" for only first student whose "University= OPQ". (Example: Emity in Group 2, Jacob in Group 3, White in Group 5)

What I tried

```<code>        var results= StudentsList
            .GroupBy(x => x.GroupID)
            .Where(x => x.Any(y => y.University == "OPQ"))
            .FirstOrDefault
            .ToList();

      results.ForEach(x => x.IsQualified = true);

      foreach(var item in results){if (item.IsQualified== true){
      Console.WriteLine("Group " + item.GroupID + " , " + item.Student);}}
</code>```

This does completely the opposite. I change "IsQualified=True" for all items in the 1st group! That's not what I want.

My Code:

```<code>List<StudentInfo> StudentsList = new List<StudentInfo>();

// Group 1
StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="John", University="abc", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="Jack", University="def", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Peter", University="abc", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", GroupID = 1, IsQualified=false} );

// Group 2
StudentsList.Add( new StudentInfo { Student="Donald", University="def", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", GroupID = 2, IsQualified=false} );

// Group 3
StudentsList.Add( new StudentInfo { Student="Adam", University="yub", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Saint", University="abc", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", GroupID = 3, IsQualified=false} );

// Group 4
StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", GroupID = 4, IsQualified=false} );

// Group 5
StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", GroupID = 5, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="White", University="OPQ", GroupID = 5, IsQualified=false} );
</code>```

答:
```<code> var results = StudentsList.Where(x => x.University == "OPQ").GroupBy(x => x.GroupID).ToList();
            foreach (var item in results)
            {
                Console.WriteLine("Group " + item.Key + " , " + item.FirstOrDefault().Student);
            }
</code>```

You should first filter students by university, and then group by groupID. You will get a structure in which the key is the group number, and the value is a list of StudentInfo objects. From this list you need to choose the first student.

Body:
I want to iterate through each group and set "IsQualified= true" for only first student whose "University= OPQ". (Example: Emity in Group 2, Jacob in Group 3, White in Group 5)

What I tried

        var results= StudentsList
            .GroupBy(x => x.GroupID)
            .Where(x => x.Any(y => y.University == "OPQ"))
            .FirstOrDefault
            .ToList();

      results.ForEach(x => x.IsQualified = true);

      foreach(var item in results){if (item.IsQualified== true){
      Console.WriteLine("Group " + item.GroupID + " , " + item.Student);}}

This does completely the opposite. I change "IsQualified=True" for all items in the 1st group! That's not what I want.

My Code:

List<StudentInfo> StudentsList = new List<StudentInfo>();

// Group 1
StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="John", University="abc", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="Jack", University="def", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Peter", University="abc", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", GroupID = 1, IsQualified=false} );

// Group 2
StudentsList.Add( new StudentInfo { Student="Donald", University="def", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", GroupID = 2, IsQualified=false} );

// Group 3
StudentsList.Add( new StudentInfo { Student="Adam", University="yub", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Saint", University="abc", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", GroupID = 3, IsQualified=false} );

// Group 4
StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", GroupID = 4, IsQualified=false} );

// Group 5
StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", GroupID = 5, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="White", University="OPQ", GroupID = 5, IsQualified=false} );

Body:
 var results = StudentsList.Where(x => x.University == "OPQ").GroupBy(x => x.GroupID).ToList();
            foreach (var item in results)
            {
                Console.WriteLine("Group " + item.Key + " , " + item.FirstOrDefault().Student);
            }

You should first filter students by university, and then group by groupID. You will get a structure in which the key is the group number, and the value is a list of StudentInfo objects. From this list you need to choose the first student.


问:
How to deploy a war file in GlassFish 4 server Using Jenkins
I am using Jenkins to deploy a war file in GlassFish 4 server.But unable to deploy
war file in Glassfish 4 server.

I am following below process.

But it gives following error at the build time.

ERROR: Build step failed with exception
  org.codehaus.cargo.util.CargoException: Cannot create the
  DeploymentManager     at
  org.codehaus.cargo.container.spi.deployer.AbstractJsr88Deployer.getDeploymentManager(AbstractJsr88Deployer.java:356)
    at
  org.codehaus.cargo.container.spi.deployer.AbstractJsr88Deployer.redeploy(AbstractJsr88Deployer.java:192)
    at
  hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:77)
    at
  hudson.plugins.deploy.CargoContainerAdapter$DeployCallable.invoke(CargoContainerAdapter.java:147)
    at
  hudson.plugins.deploy.CargoContainerAdapter$DeployCallable.invoke(CargoContainerAdapter.java:117)
    at hudson.FilePath.act(FilePath.java:1047)  at
  hudson.FilePath.act(FilePath.java:1025)   at
  hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:114)
    at
  hudson.plugins.deploy.PasswordProtectedAdapterCargo.redeploy(PasswordProtectedAdapterCargo.java:93)
    at
  hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:64)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at
  hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:744)
    at
  hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:690)
    at hudson.model.Build$BuildExecution.post2(Build.java:186)  at
  hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:635)
    at hudson.model.Run.execute(Run.java:1819)  at
  hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)   at
  hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429) Caused by:
  javax.enterprise.deploy.spi.exceptions.DeploymentManagerCreationException:
  Could not get DeploymentManager; No registered DeploymentFactory
  handles this URI  at
  javax.enterprise.deploy.shared.factories.DeploymentFactoryManager.getDeploymentManager(DeploymentFactoryManager.java:117)
    at
  org.codehaus.cargo.container.glassfish.GlassFish3xRemoteDeployer.getDeploymentManager(GlassFish3xRemoteDeployer.java:82)
    at
  org.codehaus.cargo.container.spi.deployer.AbstractJsr88Deployer.getDeploymentManager(AbstractJsr88Deployer.java:352)
    ... 18 more
  javax.enterprise.deploy.spi.exceptions.DeploymentManagerCreationException:
  Could not get DeploymentManager; No registered DeploymentFactory
  handles this URI  at
  javax.enterprise.deploy.shared.factories.DeploymentFactoryManager.getDeploymentManager(DeploymentFactoryManager.java:117)
    at
  org.codehaus.cargo.container.glassfish.GlassFish3xRemoteDeployer.getDeploymentManager(GlassFish3xRemoteDeployer.java:82)
    at
  org.codehaus.cargo.container.spi.deployer.AbstractJsr88Deployer.getDeploymentManager(AbstractJsr88Deployer.java:352)
    at
  org.codehaus.cargo.container.spi.deployer.AbstractJsr88Deployer.redeploy(AbstractJsr88Deployer.java:192)
    at
  hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:77)
    at
  hudson.plugins.deploy.CargoContainerAdapter$DeployCallable.invoke(CargoContainerAdapter.java:147)
    at
  hudson.plugins.deploy.CargoContainerAdapter$DeployCallable.invoke(CargoContainerAdapter.java:117)
    at hudson.FilePath.act(FilePath.java:1047)  at
  hudson.FilePath.act(FilePath.java:1025)   at
  hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:114)
    at
  hudson.plugins.deploy.PasswordProtectedAdapterCargo.redeploy(PasswordProtectedAdapterCargo.java:93)
    at
  hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:64)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at
  hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:744)
    at
  hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:690)
    at hudson.model.Build$BuildExecution.post2(Build.java:186)  at
  hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:635)
    at hudson.model.Run.execute(Run.java:1819)  at
  hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)   at
  hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429) Build step 'Deploy
  war/ear to a container' marked build as failure Finished: FAILURE

答:
Example using Windows batchfile

```<code>@ECHO OFF
:: BAT START GLASSFISH 5 SERVER
ECHO ============================
ECHO STOPING GLASSFISH 5
ECHO ============================
tasklist | find /i "java.exe" && taskkill /im java.exe /F || echo process "java.exe" not running.
ECHO ============================
ECHO NETWORK INFO
ECHO ============================
ipconfig | findstr IPv4
ECHO ============================
ECHO STARTING GLASSFISH 5
ECHO ============================
ECHO Please wait...
ping 127.0.0.1 -n 10 > nul
net start domain1
ECHO Please wait... Restarting Server
ping 127.0.0.1 -n 90 > nul
exit  0
</code>```

Running The batchfile:

```<code>asadmin --echo=true --host=localhost --port=4848 --user=admin --passwordfile=C:\FilePassGF\passwordfile.txt --secure=false deploy --name "NameWar" --contextroot "NameWar" --force=true "C:\Jenkinshome\deploys\$JOB_NAME\$BUILD_NUMBER\Target-1.0.war"
</code>```

Body:
Example using Windows batchfile

@ECHO OFF
:: BAT START GLASSFISH 5 SERVER
ECHO ============================
ECHO STOPING GLASSFISH 5
ECHO ============================
tasklist | find /i "java.exe" && taskkill /im java.exe /F || echo process "java.exe" not running.
ECHO ============================
ECHO NETWORK INFO
ECHO ============================
ipconfig | findstr IPv4
ECHO ============================
ECHO STARTING GLASSFISH 5
ECHO ============================
ECHO Please wait...
ping 127.0.0.1 -n 10 > nul
net start domain1
ECHO Please wait... Restarting Server
ping 127.0.0.1 -n 90 > nul
exit  0

Running The batchfile:

asadmin --echo=true --host=localhost --port=4848 --user=admin --passwordfile=C:\FilePassGF\passwordfile.txt --secure=false deploy --name "NameWar" --contextroot "NameWar" --force=true "C:\Jenkinshome\deploys\$JOB_NAME\$BUILD_NUMBER\Target-1.0.war"


问:
Regular expression to discard "
I have the next regular expression: /i18n(-?).*="(.*)"/g for javascript.

I use https://www.regextester.com to check.

```<code><button i18n="@@user.button" data-test="download-confirmation_ok">
<a i18n-href="@@link.url" href="https://www.aaaa.es" target="_blank">
<div i18n="@@link.text">www.aaaa.es</div>
</code>```

I don't like data-test="download-confirmation_ok" and href="https://www.aaaa.es" target="_blank":
https://imgur.com/sQZQXzZ

I only want i18n or i18n-* text between "TEXT".

How can I discard rest of the tetx?

Thank.

答:
HTML should really never be processed with regular expressions for a host of reasons. If I understand correctly that you only wish to keep attributes that begin with i18n or i18n-, then use a DOMParser:

let html = `<button i18n="@@user.button" data-test="download-confirmation_ok">
i18n-href="@@link.url" href="https://www.aaaa.es" target="_blank">

www.aaaa.es
`;

let parser = new DOMParser();
let doc = parser.parseFromString(html, 'text/html');
var allTags = doc.querySelectorAll("*");
for (let i = 0; i < allTags.length; i++) {
    let aTag = allTags[i];
    for (let j = aTag.attributes.length - 1; j >= 0; j--) {
        let name = aTag.attributes[j].name;
        if (!/^i18n-?/.test(name)) {
            aTag.removeAttribute(name);
        }
    }
}
html = doc.body.innerHTML;
console.log(html);```

Title: Regular expression to discard "

Body:
I have the next regular expression: /i18n(-?).*="(.*)"/g for javascript.

I use https://www.regextester.com to check.

<button i18n="@@user.button" data-test="download-confirmation_ok">

www.aaaa.es

I don't like data-test="download-confirmation_ok" and href="https://www.aaaa.es" target="_blank":
https://imgur.com/sQZQXzZ

I only want i18n or i18n-* text between "TEXT".

How can I discard rest of the tetx?

Thank.

Body:
HTML should really never be processed with regular expressions for a host of reasons. If I understand correctly that you only wish to keep attributes that begin with i18n or i18n-, then use a DOMParser:

let html = `<button i18n="@@user.button" data-test="download-confirmation_ok">
<a i18n-href="@@link.url" href="https://www.aaaa.es" target="_blank">
<div i18n="@@link.text">www.aaaa.es</div>`;

let parser = new DOMParser();
let doc = parser.parseFromString(html, 'text/html');
var allTags = doc.querySelectorAll("*");
for (let i = 0; i < allTags.length; i++) {
    let aTag = allTags[i];
    for (let j = aTag.attributes.length - 1; j >= 0; j--) {
        let name = aTag.attributes[j].name;
        if (!/^i18n-?/.test(name)) {
            aTag.removeAttribute(name);
        }
    }
}
html = doc.body.innerHTML;
console.log(html);


问:
What does the ?. syntax mean in JavaScript?
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

```<code>{cart?.widgets?.items.map(widget => (
        <div className="billing-details__box" key={widget.id}>
          <p className="m-0">{widget.name}</p>
          <p className="my-0">{widget.value} $</p>
        </div>
 ))}
</code>```

My concern with above code is whether cart?.widgets?.items will raise any error or not.

答:
I couldn't confirm if this syntax correct or not.

It is correct TypeScript code, and is correct JavaScript depending on what engine you're running it in. Chrome (V8) supports this syntax already (see caniuse.com).

Here you can read more about the proposal to add this syntax to a future JS spec.

What is it?

This syntax is called the optional chaining operator, and it allows you to access properties that may or may not exist on an object without having to check for the properties existence no matter how deep the property access expression is.

For example, say we have some object like so:

```<code>const user = {
  details: {
    name: "SpongeBob SquarePants"
  },
  repo: null
};
</code>```

And we want to get their name and, if it exists, some property user.repo.url. We can use the optional chaining operator to get both without having to worry whether repo is an object or not:

```<code>console.log(user.details.name) //=> "SpongeBob SquarePants"
console.log(user.repo.url) //=> undefined
</code>```

It also works for function calls. For example, say when user.repo has a value we know it will be a function that returns a string. However, sometimes, as above, it may not be a function. We can do the following to call the function if it exists, but the code will not throw an error if the value at user.repo.url is not a function:

```<code>console.log(user.repo?.url()) //=> undefined
</code>```

Without optional chaining operator?

You can achieve the similar behaviour to the optional chaining operator by explicitly checking the truthiness of each object property in the chain of properties that you are accessing.

This can be done either by taking advantage of JavaScript's short-circuit evaluation behaviour, or more obviously with the ternary operator.

It would look something like this:

function getItems_shortCircuit(obj) {
  return obj && obj.widgets && obj.widgets.items
}

function getItems_ternary(obj) {
  return obj
    ? obj.widgets
      ? obj.widgets.items
        ? obj.widgets.items
        : null
      : null
    : null
}

let cart = {
  widgets: null
}

console.log(getItems_shortCircuit(cart)) //=> null

cart.widgets = {
  items: ["a", "b"]
}

console.log(getItems_ternary(cart)) //=> ["a", "b"]```

My concern with above code is whether cart?.widgets?.items will raise any error or not.

It depends on whether the project is using TypeScript, which supports optional chaining (?.) out-of-the-box. You can read about it in the TypeScript documentation.

If you are not using TypeScript then you must compile your application using some ESNext compiler such as Babel, which has the @babel/plugin-proposal-optional-chaining plugin.

Body:
I came across this C# like code in a React project. I couldn't confirm if this syntax correct or not. I didn't find any recent ES version release to support this syntax. In current scenario I'm not authorized to execute and check this code.

I tried testing this syntax in browse console and encountered error:

{cart?.widgets?.items.map(widget => (

{widget.name}

{widget.value} $

 ))}

My concern with above code is whether cart?.widgets?.items will raise any error or not.

Body:
I couldn't confirm if this syntax correct or not.

It is correct TypeScript code, and is correct JavaScript depending on what engine you're running it in. Chrome (V8) supports this syntax already (see caniuse.com).

Here you can read more about the proposal to add this syntax to a future JS spec.

What is it?

This syntax is called the optional chaining operator, and it allows you to access properties that may or may not exist on an object without having to check for the properties existence no matter how deep the property access expression is.

For example, say we have some object like so:

const user = {
  details: {
    name: "SpongeBob SquarePants"
  },
  repo: null
};

And we want to get their name and, if it exists, some property user.repo.url. We can use the optional chaining operator to get both without having to worry whether repo is an object or not:

console.log(user.details.name) //=> "SpongeBob SquarePants"
console.log(user.repo.url) //=> undefined

It also works for function calls. For example, say when user.repo has a value we know it will be a function that returns a string. However, sometimes, as above, it may not be a function. We can do the following to call the function if it exists, but the code will not throw an error if the value at user.repo.url is not a function:

console.log(user.repo?.url()) //=> undefined

Without optional chaining operator?

You can achieve the similar behaviour to the optional chaining operator by explicitly checking the truthiness of each object property in the chain of properties that you are accessing.

This can be done either by taking advantage of JavaScript's short-circuit evaluation behaviour, or more obviously with the ternary operator.

It would look something like this:

function getItems_shortCircuit(obj) {
  return obj && obj.widgets && obj.widgets.items
}

function getItems_ternary(obj) {
  return obj
    ? obj.widgets
      ? obj.widgets.items
        ? obj.widgets.items
        : null
      : null
    : null
}

let cart = {
  widgets: null
}

console.log(getItems_shortCircuit(cart)) //=> null

cart.widgets = {
  items: ["a", "b"]
}

console.log(getItems_ternary(cart)) //=> ["a", "b"]

My concern with above code is whether cart?.widgets?.items will raise any error or not.

It depends on whether the project is using TypeScript, which supports optional chaining (?.) out-of-the-box. You can read about it in the TypeScript documentation.

If you are not using TypeScript then you must compile your application using some ESNext compiler such as Babel, which has the @babel/plugin-proposal-optional-chaining plugin.


问:
How to share files across git repositories?
I have several applications across sub domains on various servers. Each application has its own Git repository. Each application uses several shared files. Essentially, my repositories overlap.

How is this situation best handled with multiple editors of multiple projects?

答:
As long as the multiple projects are pushing their changes to the submodule up to the shared location, yeah they can all makes changes to the shared resource.  That said, if one of them needs theirs to be 'special' they'll have to branch the submodule.

https://git-scm.com/book/en/v2/Git-Tools-Submodules

This walks you through a super project with submodules, editing the submodule from within the super project and pushing it back up.  It also shows the one danger which is silently overwriting changes if you run a git submodule update and you had local unpushed changes on master branch.

Specifically, somewhere you've got a shared folder 'folder' - you'll need to remove this from all the git projects, but create a new git repo somewhere with the current contents as the initial commit.  Then you'll git submodule <repo> folder; git submodule update in all the projects which will now share it.  They'll all be able to push changes up to the shared repo, and will be able to pull down each other's changes.


问:
How to setup Swagger for PowerApps correctly?
This is my Azure function I want to connect to my PowerApps

```<code>        [FunctionName("ConvertMe")]
    public static IActionResult RunAsync
        ([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
    {
        log.LogInformation($"Received a Request");
        ConvertMe Converter = new ConvertMe();

        string test1 = req.Query["image1"];
        string test2 = req.Query["image2"];

        MagickImage _Main = new MagickImage(Convert.FromBase64String(test1), MagickFormat.Png);
        MagickImage _Overlay = new MagickImage(Convert.FromBase64String(test2), MagickFormat.Png);

        using (MemoryStream memory = new MemoryStream())
        {
            Converter.ComebineBitmap(_Main, _Overlay).Write(memory, MagickFormat.Png);
            memory.Position = 0;
            return new FileContentResult(memory.ToArray(),"image/png");
        }

    }
</code>```

Its already working on local but I want to use it in PowerApps.
How do I get my return value to Swagger ?

My current swagger file

```<code>    {
  "swagger": "2.0",
  "info": {
    "version": "1.0.0",
    "title": "MyAzureFunction"
  },
  "host": "xxx",
  "paths": {
    "/api/ConvertMe": {
      "get": {
        "description": "Calls my azure function over https",
        "operationId": "ConvertMe",
        "parameters": [
          {
            "name": "code",
            "in": "query",
            "description": "code",
            "default": "code",
            "type": "string"
          },
          {
            "name": "image1",
            "in": "query",
            "required": true,
            "type": "string"
          },
          {
            "name": "image2",
            "in": "query",
            "required": true,
            "type": "string"
          },

        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "schema": {
              "title": "The response of the api.",
              "type": "string"
            }
          }
        }
      }
    }
  }
}
</code>```

Ive never worked with swagger but ive already found out, the best is to work with base64 string.

答: Microsoft has a tutorial for creating an OpenAPI definition from a server-less API. If you follow the steps laid out you will eventually get to the Download the OpenAPI definition step, which is what you can use to import into powerapps to make your custom connector.</p>

Body:
This is my Azure function I want to connect to my PowerApps

        [FunctionName("ConvertMe")]
    public static IActionResult RunAsync
        ([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
    {
        log.LogInformation($"Received a Request");
        ConvertMe Converter = new ConvertMe();

        string test1 = req.Query["image1"];
        string test2 = req.Query["image2"];

        MagickImage _Main = new MagickImage(Convert.FromBase64String(test1), MagickFormat.Png);
        MagickImage _Overlay = new MagickImage(Convert.FromBase64String(test2), MagickFormat.Png);

        using (MemoryStream memory = new MemoryStream())
        {
            Converter.ComebineBitmap(_Main, _Overlay).Write(memory, MagickFormat.Png);
            memory.Position = 0;
            return new FileContentResult(memory.ToArray(),"image/png");
        }

    }

Its already working on local but I want to use it in PowerApps.
How do I get my return value to Swagger ?

My current swagger file

    {
  "swagger": "2.0",
  "info": {
    "version": "1.0.0",
    "title": "MyAzureFunction"
  },
  "host": "xxx",
  "paths": {
    "/api/ConvertMe": {
      "get": {
        "description": "Calls my azure function over https",
        "operationId": "ConvertMe",
        "parameters": [
          {
            "name": "code",
            "in": "query",
            "description": "code",
            "default": "code",
            "type": "string"
          },
          {
            "name": "image1",
            "in": "query",
            "required": true,
            "type": "string"
          },
          {
            "name": "image2",
            "in": "query",
            "required": true,
            "type": "string"
          },

        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "schema": {
              "title": "The response of the api.",
              "type": "string"
            }
          }
        }
      }
    }
  }
}

Ive never worked with swagger but ive already found out, the best is to work with base64 string.


问:
pandas copy value from one column to another if condition is met
I have a dataframe:

```<code>df =
col1  col2  col3
1      2     3
1      4     6
3      7     2
</code>```

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

```<code>new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2
</code>```

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?

Body:
I have a dataframe:

df =
col1  col2  col3
1      2     3
1      4     6
3      7     2

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

new_df =
col1  col2  col3
3      2     3
6      4     6
3      7     2

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?

Body: df.loc[df["col1"] < 2, "col1"] = df["col3"]


问:
PrintWindow function makes mistake in notepad.exe
PrintWindow function in Win32API could capture the image of a program. By the following code we can get the copy of the screenshot in clipboard.

```<code>#define _WIN32_WINNT    0x0501
#include <windows.h>
#include <iostream>
using namespace std;

WCHAR programName[] = L"Notepad";

int main()
{
    HWND hwnd = FindWindow(programName, NULL);
    if (hwnd == NULL)
    {
        cerr << "Cannot find window" << endl;
        return -1;
    }

    WINDOWINFO wi;
    wi.cbSize = sizeof(WINDOWINFO);
    GetWindowInfo(hwnd, &wi);

    RECT rc = {
        wi.rcClient.left - wi.rcWindow.left,
        wi.rcClient.top - wi.rcWindow.top,
        wi.rcClient.right - wi.rcWindow.left,
        wi.rcClient.bottom - wi.rcWindow.top
    };

    HDC hdcScreen = GetDC(NULL);
    HDC hdc = CreateCompatibleDC(hdcScreen);
    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen,
        wi.rcWindow.right - wi.rcWindow.left,
        wi.rcWindow.bottom - wi.rcWindow.top);
    SelectObject(hdc, hbmp);

    HBITMAP hbmp2 = CreateCompatibleBitmap(hdcScreen,
        wi.rcClient.right - wi.rcClient.left,
        wi.rcClient.bottom - wi.rcClient.top);
    HDC hdc2 = CreateCompatibleDC(hdcScreen);
    SelectObject(hdc2, hbmp2);

    PrintWindow(hwnd, hdc, 0);

    BitBlt(hdc2,
        0, 0, rc.right - rc.left, rc.bottom - rc.top,
        hdc,
        rc.left, rc.top,
        SRCCOPY);

    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_BITMAP, hbmp2);
    CloseClipboard();

    DeleteDC(hdc);
    DeleteObject(hbmp);

    DeleteDC(hdc2);
    DeleteObject(hbmp2);

    ReleaseDC(NULL, hdcScreen);

    cout << "Success" << endl;

    return 0;
}
</code>```

When I use the code to capture a screenshot, it works but returns a wrong picture into my clipboard. Like this:
My screenshot of notepad.exe

It seems like part of the notepad program. But why it is just the part of the program. I tried other programs and they works well. Is there any bugs in notepad or win32api?

答:
You only get the client area. This code gets the whole window:</p>

```<code>HWND hwnd = FindWindow(programName, nullptr);
if (hwnd == nullptr)
    return -1;

WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
GetWindowInfo(hwnd, &wi);

const LONG w = wi.rcWindow.right - wi.rcWindow.left;
const LONG h = wi.rcWindow.bottom - wi.rcWindow.top;

HDC hdcScreen = GetDC(nullptr);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, w, h);
SelectObject(hdc, hbmp);

PrintWindow(hwnd, hdc, 0); // or use PW_RENDERFULLCONTENT
BitBlt(hdc, 0, 0, w, h, hdc, 0, 0, SRCCOPY);

OpenClipboard(nullptr);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp);
CloseClipboard();

DeleteDC(hdc);
DeleteObject(hbmp);

ReleaseDC(nullptr, hdcScreen);
return 0;
</code>```

Body:
PrintWindow function in Win32API could capture the image of a program. By the following code we can get the copy of the screenshot in clipboard.

#define _WIN32_WINNT    0x0501
#include <windows.h>
#include <iostream>
using namespace std;

WCHAR programName[] = L"Notepad";

int main()
{
    HWND hwnd = FindWindow(programName, NULL);
    if (hwnd == NULL)
    {
        cerr << "Cannot find window" << endl;
        return -1;
    }

    WINDOWINFO wi;
    wi.cbSize = sizeof(WINDOWINFO);
    GetWindowInfo(hwnd, &wi);

    RECT rc = {
        wi.rcClient.left - wi.rcWindow.left,
        wi.rcClient.top - wi.rcWindow.top,
        wi.rcClient.right - wi.rcWindow.left,
        wi.rcClient.bottom - wi.rcWindow.top
    };

    HDC hdcScreen = GetDC(NULL);
    HDC hdc = CreateCompatibleDC(hdcScreen);
    HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen,
        wi.rcWindow.right - wi.rcWindow.left,
        wi.rcWindow.bottom - wi.rcWindow.top);
    SelectObject(hdc, hbmp);

    HBITMAP hbmp2 = CreateCompatibleBitmap(hdcScreen,
        wi.rcClient.right - wi.rcClient.left,
        wi.rcClient.bottom - wi.rcClient.top);
    HDC hdc2 = CreateCompatibleDC(hdcScreen);
    SelectObject(hdc2, hbmp2);

    PrintWindow(hwnd, hdc, 0);

    BitBlt(hdc2,
        0, 0, rc.right - rc.left, rc.bottom - rc.top,
        hdc,
        rc.left, rc.top,
        SRCCOPY);

    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_BITMAP, hbmp2);
    CloseClipboard();

    DeleteDC(hdc);
    DeleteObject(hbmp);

    DeleteDC(hdc2);
    DeleteObject(hbmp2);

    ReleaseDC(NULL, hdcScreen);

    cout << "Success" << endl;

    return 0;
}

When I use the code to capture a screenshot, it works but returns a wrong picture into my clipboard. Like this:
My screenshot of notepad.exe

It seems like part of the notepad program. But why it is just the part of the program. I tried other programs and they works well. Is there any bugs in notepad or win32api?

Body:
You only get the client area. This code gets the whole window:

HWND hwnd = FindWindow(programName, nullptr);
if (hwnd == nullptr)
    return -1;

WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
GetWindowInfo(hwnd, &wi);

const LONG w = wi.rcWindow.right - wi.rcWindow.left;
const LONG h = wi.rcWindow.bottom - wi.rcWindow.top;

HDC hdcScreen = GetDC(nullptr);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, w, h);
SelectObject(hdc, hbmp);

PrintWindow(hwnd, hdc, 0); // or use PW_RENDERFULLCONTENT
BitBlt(hdc, 0, 0, w, h, hdc, 0, 0, SRCCOPY);

OpenClipboard(nullptr);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp);
CloseClipboard();

DeleteDC(hdc);
DeleteObject(hbmp);

ReleaseDC(nullptr, hdcScreen);
return 0;


问:
Newbie Question About Running a Process On a New Thread
So far my apps have been pretty simple, but now I'm finding I need to run a process on a separate thread, so this is an xCode 101 question asking how I do that.

I want to run a process that runs when the app launches, so I want to execute it in AppDelegate.applicationDidFinishLaunching.

From what I've read, I think this is all I need to do, but please correct me if I'm wrong.

```<code>// *** AppDelegate.m ****

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [NSThread detachNewThreadSelector:@selector([XMLParser parseXML:])
        toTarget:self
        withObject:requestStr];

}

// *** XMLParser.m ***

-(void)parseXML {

    // Dunno why NSAutoreleasePool is needed but apparently it is

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // . . . my code

    [pool release];

}

}
</code>```

答:
There is some problem i think, @selector expects a selector not a method call. So the correct one should be like this

```<code>- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [NSThread detachNewThreadSelector:@selector(parseXML:)
        toTarget:objXMLParser
        withObject:requestStr];

}

//here the taget is the object whose selector you are passing. so you can't use self there as parseXML: is the method of XMLParser class

// *** XMLParser.m ***

-(void)parseXML {

    // Dunno why NSAutoreleasePool is needed but apparently it is

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // . . . my code

    [pool release];

}
</code>```

// Autorelease pool is needed as it is a separate thread, and your code might use some cocoa or your own calls/methods/code that autoreleases an object that's why you have to keep an auto release pool for those autoreleased objects. if your code doesn't use any [obj autorelease] statement or doesn't auto release an object in that case you can omit auto release pool statements, but it's a good practice to keep it.

Body:
So far my apps have been pretty simple, but now I'm finding I need to run a process on a separate thread, so this is an xCode 101 question asking how I do that.

I want to run a process that runs when the app launches, so I want to execute it in AppDelegate.applicationDidFinishLaunching.

From what I've read, I think this is all I need to do, but please correct me if I'm wrong.

// *** AppDelegate.m ****

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [NSThread detachNewThreadSelector:@selector([XMLParser parseXML:])
        toTarget:self
        withObject:requestStr];

}

// *** XMLParser.m ***

-(void)parseXML {

    // Dunno why NSAutoreleasePool is needed but apparently it is

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // . . . my code

    [pool release];

}

}

Body:
There is some problem i think, @selector expects a selector not a method call. So the correct one should be like this

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [NSThread detachNewThreadSelector:@selector(parseXML:)
        toTarget:objXMLParser
        withObject:requestStr];

}

//here the taget is the object whose selector you are passing. so you can't use self there as parseXML: is the method of XMLParser class

// *** XMLParser.m ***

-(void)parseXML {

    // Dunno why NSAutoreleasePool is needed but apparently it is

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // . . . my code

    [pool release];

}

// Autorelease pool is needed as it is a separate thread, and your code might use some cocoa or your own calls/methods/code that autoreleases an object that's why you have to keep an auto release pool for those autoreleased objects. if your code doesn't use any [obj autorelease] statement or doesn't auto release an object in that case you can omit auto release pool statements, but it's a good practice to keep it.


答:
As mentioned by @anky_91 use np.where to update the 'col1' values:

```<code>df['col1'] = np.where(df['col1'] < df['col2'], df['col3'], df['col1'])
</code>```

Title: pandas copy value from one column to another if condition is met

Body:
As mentioned by @anky_91 use np.where to update the 'col1' values:

df['col1'] = np.where(df['col1'] < df['col2'], df['col3'], df['col1'])


问:
Try alternative html files in Nginx
I have a small VueJS app which is located in index.html. For SEO value I've also started generating a lot of static html files in subfolders. The problem is that Nginx only routes my requests to index.html, and not to these static html files.

I'd like all requests to for instance mydomain.com/podcast/test-podcast/first-episode.html to serve /podcast/test-podcast/first-episode.html

What directive do I need to add in Nginx to add such a rule?

Here's my conf file:

```<code>server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /usr/share/nginx/html;

  index index.html;

  server_name localhost;

  try_files $uri $uri/ /index.html?q=$uri&$args;

  location / {
    try_files $uri $uri/ @rewrites;
  }

  location @rewrites {
    rewrite ^(.+)$ /index.html last;
  }

  location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    # Some basic cache-control for static files to be sent to the browser
    expires max;
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
  }

}
</code>```

答:
Long work but not impossible; For each page you will need to create a NGinx rules

```<code>...

location /podcast/test-podcast/first-episode.html {
    root    /usr/share/nginx/html/podcast/test-podcast/
    index   first-episode.html
}

location /blabla/seo-roxx/example.html {
    root    /blabla/seo-roxx/example/
    index   example.html
}

...
</code>```

You may want to rethink you SEO strategie to avoid doing it in NGinx.

Title: Try alternative html files in Nginx

Body:
I have a small VueJS app which is located in index.html. For SEO value I've also started generating a lot of static html files in subfolders. The problem is that Nginx only routes my requests to index.html, and not to these static html files.

I'd like all requests to for instance mydomain.com/podcast/test-podcast/first-episode.html to serve /podcast/test-podcast/first-episode.html

What directive do I need to add in Nginx to add such a rule?

Here's my conf file:

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  root /usr/share/nginx/html;

  index index.html;

  server_name localhost;

  try_files $uri $uri/ /index.html?q=$uri&$args;

  location / {
    try_files $uri $uri/ @rewrites;
  }

  location @rewrites {
    rewrite ^(.+)$ /index.html last;
  }

  location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    # Some basic cache-control for static files to be sent to the browser
    expires max;
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
  }

}

Body:
Long work but not impossible; For each page you will need to create a NGinx rules

...

location /podcast/test-podcast/first-episode.html {
    root    /usr/share/nginx/html/podcast/test-podcast/
    index   first-episode.html
}

location /blabla/seo-roxx/example.html {
    root    /blabla/seo-roxx/example/
    index   example.html
}

...

You may want to rethink you SEO strategie to avoid doing it in NGinx.


问:
wkhtmltopdf --page-width and --page-height not working
I'm using wkhtmltopdf in windows to create a custom sticker, so I need it to render a specific paper size. According to the documentation, I should use --page-width and --page-height but none of them seems to have any effect, however when I tried -s it does change the paper size. This is my command:

```<code>wkhtmltopdf -g --page-width 10 -L 0 -R 0 -T 0 -B 0 sticker.html sticker.pdf
</code>```

I've also tried to set the units like 10px, 10mm or 10in, and tried with different width. No error or message given, everything works but page size is still A4. What am I doing wrong?

答: I finally redownloaded and reinstalled the previous version of wkhtmltopdf and it worked. I guess that must have been some kind of installation problem.</p>

Body:
I'm using wkhtmltopdf in windows to create a custom sticker, so I need it to render a specific paper size. According to the documentation, I should use --page-width and --page-height but none of them seems to have any effect, however when I tried -s it does change the paper size. This is my command:

wkhtmltopdf -g --page-width 10 -L 0 -R 0 -T 0 -B 0 sticker.html sticker.pdf

I've also tried to set the units like 10px, 10mm or 10in, and tried with different width. No error or message given, everything works but page size is still A4. What am I doing wrong?


问:
Css - Move first
 element at the end
i have this code:

        info@email.com
        info@pec.email.com

        9:00 - 13:00
        15:00 - 18:00 pm

        Main Street 22
        09030 Los Angeles CA

```

I want to move the first li tag to the end of the list. I mean the li tag that contains email addresses after the li tag that contains

Main Street 22
      09030 Los Angeles CA

For this operation i can't add classes manually, it is autogenerate code and i can use only css ( not javascript).

This is an horizontal list for a full screen view and a vertical list for mobile view

答:
You can use CSS flex-direction and then set the "order" for the li:first-child

ul.careplus-infolist {
    display: flex;
    flex-direction: column;
}

ul.careplus-infolist li:first-child {
  order: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="careplus-infolist">
<li>
    <i class="careplus-bgcolor-two fa fa-envelope"></i>
    <span>info@email.com</span>
    <span>info@pec.email.com</span>
</li>
<li>
    <i class="careplus-bgcolor-two fa fa-clock-o"></i>
    <span>9:00 - 13:00</span>
    <span>15:00 - 18:00 pm</span>
</li>
<li>
    <i class="careplus-bgcolor-two fa fa-map-marker"></i>
    Main Street 22
    09030 Los Angeles CA
</li>
</ul></code>```

Title: Css - Move first <li> element at the end

Body:
i have this code:

        info@email.com
        info@pec.email.com

        9:00 - 13:00
        15:00 - 18:00 pm

        Main Street 22
        09030 Los Angeles CA

I want to move the first li tag to the end of the list. I mean the li tag that contains email addresses after the li tag that contains

Main Street 22
      09030 Los Angeles CA

For this operation i can't add classes manually, it is autogenerate code and i can use only css ( not javascript).

This is an horizontal list for a full screen view and a vertical list for mobile view

Body:
You can use CSS flex-direction and then set the "order" for the li:first-child

ul.careplus-infolist {
    display: flex;
    flex-direction: column;
}

ul.careplus-infolist li:first-child {
  order: 3;
}

<ul class="careplus-infolist">
<li>
    <i class="careplus-bgcolor-two fa fa-envelope"></i>
    <span><a href="mailto:info@email.com" target="_blank">info@email.com</a></span>
    <span><a href="mailto:info@pec.email.com" target="_blank">info@pec.email.com</a></span>
</li>
<li>
    <i class="careplus-bgcolor-two fa fa-clock-o"></i>
    <span>9:00 - 13:00</span>
    <span>15:00 - 18:00 pm</span>
</li>
<li>
    <i class="careplus-bgcolor-two fa fa-map-marker"></i>
    Main Street 22
    09030 Los Angeles CA
</li>
</ul>


问:
JavaScript - remove duplicates algorithm efficiency
I have read a lot about this topic and I saw many different algorithms. I have stumbled across another solution which Im having a hard time to understand its efficiency compared to other algorithms, since its using a simple temporary object to hold the existing elements of the array. Is that a valid solution compared to the "old school" method using a sophisticated sorting method and comparison?

```<code> function removeDup(arr){
        var element,
                existObj= {},
                finalArr = [];

        for(var i=0;i<arr.length;i++){
            element = arr[i];
            if(!existObj[element]){
                finalArr.push(element);
                existObj[element] = true;
            }
        }
        return finalArr;
    }
    //console.log(removeDup([2,2,2,2,4534,5,7,3]));
    console.log(removeDup(["mike","john","alex","mike","john"]));
</code>```

A friend told me that the efficiency here cannot be clearly determined because i dont really know how was the temp object implemented.

答:
```<code>let existing = {};
let unicNumbers = [];
arr.forEach((item) => {
        if (!existing[item.id]) {
            unicNumbers.push(item);
            existing[item.id] = true;
        }
    })
</code>```

Body:
I have read a lot about this topic and I saw many different algorithms. I have stumbled across another solution which Im having a hard time to understand its efficiency compared to other algorithms, since its using a simple temporary object to hold the existing elements of the array. Is that a valid solution compared to the "old school" method using a sophisticated sorting method and comparison?

 function removeDup(arr){
        var element,
                existObj= {},
                finalArr = [];

        for(var i=0;i<arr.length;i++){
            element = arr[i];
            if(!existObj[element]){
                finalArr.push(element);
                existObj[element] = true;
            }
        }
        return finalArr;
    }
    //console.log(removeDup([2,2,2,2,4534,5,7,3]));
    console.log(removeDup(["mike","john","alex","mike","john"]));

A friend told me that the efficiency here cannot be clearly determined because i dont really know how was the temp object implemented.


问:
Most frequent word display
I have a problem because I only take 60 points per evaluation, I do not know how to display the lexicographic minimum if I have for example two words the same number of times.
I practically have to display the most common word in a text, if there are two words that appear the same number of times to display the lexicographic minimum.
I don't really know how to use HashMap to do this, a fix?
This is my code!</p>

```<code>import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
    Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(System.in));
        String currentLine = reader.readLine();
        while (currentLine != null) {
            String[] input = currentLine.replaceAll("[^a-zA-Z]", " ").toLowerCase().split(" ");
            currentLine.replace('\n', ' ');
            for (int i = 0; i < input.length; i++) {
                if (map.containsKey(input[i])) {
                    int count = map.get(input[i]);
                    map.put(input[i], count + 1);

                } else {
                    map.put(input[i], 1);
                }

            }
            currentLine = reader.readLine();
        }
        String mostRepeatedWord = null;
        int count = 0;
        for (Map.Entry < String, Integer > m: map.entrySet()) {
            if (m.getValue() > count) {
                mostRepeatedWord = m.getKey();
                count = m.getValue();
            }
            else if (m.getValue() == count) {
                mostRepeatedWord = m.getKey();
                count = m.getValue();
                if ()
            }
        }
        System.out.println(mostRepeatedWord);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
You could also compare the mostRepeatedWord with current key in case of a tie in the loop itself like below:

```<code>String mostRepeatedWord = null;
int count = 0;
for (Map.Entry < String, Integer > m: map.entrySet()) {
    if (m.getValue() > count) {
        mostRepeatedWord = m.getKey();
        count = m.getValue();
    } else if (m.getValue() == count) {
        String key = m.getKey();
        if ( key.compareTo(mostRepeatedWord) ) < 0 {
            mostRepeatedWord = key;
        }
    }
}
</code>```

Title: Most frequent word display

Body:
I have a problem because I only take 60 points per evaluation, I do not know how to display the lexicographic minimum if I have for example two words the same number of times.
I practically have to display the most common word in a text, if there are two words that appear the same number of times to display the lexicographic minimum.
I don't really know how to use HashMap to do this, a fix?
This is my code!

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
    Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(System.in));
        String currentLine = reader.readLine();
        while (currentLine != null) {
            String[] input = currentLine.replaceAll("[^a-zA-Z]", " ").toLowerCase().split(" ");
            currentLine.replace('\n', ' ');
            for (int i = 0; i < input.length; i++) {
                if (map.containsKey(input[i])) {
                    int count = map.get(input[i]);
                    map.put(input[i], count + 1);

                } else {
                    map.put(input[i], 1);
                }

            }
            currentLine = reader.readLine();
        }
        String mostRepeatedWord = null;
        int count = 0;
        for (Map.Entry < String, Integer > m: map.entrySet()) {
            if (m.getValue() > count) {
                mostRepeatedWord = m.getKey();
                count = m.getValue();
            }
            else if (m.getValue() == count) {
                mostRepeatedWord = m.getKey();
                count = m.getValue();
                if ()
            }
        }
        System.out.println(mostRepeatedWord);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Body:
You could also compare the mostRepeatedWord with current key in case of a tie in the loop itself like below:

String mostRepeatedWord = null;
int count = 0;
for (Map.Entry < String, Integer > m: map.entrySet()) {
    if (m.getValue() > count) {
        mostRepeatedWord = m.getKey();
        count = m.getValue();
    } else if (m.getValue() == count) {
        String key = m.getKey();
        if ( key.compareTo(mostRepeatedWord) ) < 0 {
            mostRepeatedWord = key;
        }
    }
}


问:
Facebook pixel purchase body event
I am trying to make an purchase facebookEvent which it takes an array of objects "Products" that contains the id and the quantity of each product on this array, what I am asking about here that I tried allot to looping into the array of products inside the payload of the event but the compiler has complained, could any one help by how to make the contents array responsive with the array of the whole product ?</p>

```<code>  //fbp
  (<any>window).fbq("track", "Purchase", {
    value: this.totalPrice,
    currency: "EGP",
    contents: [
      {
        // this should be applicable for every single item on the arrayOfProducts
        id: arrayOfProducts[0].id,
        quantity: arrayOfProducts[0].quantity
      }
    ],
    content_type: "product"
  });
</code>```

答:
What i mean by my questions is, how to push the whole arrayOfProducts instead of passing only the first item on the array ?

Use map

```<code>//fbp
  (<any>window).fbq("track", "Purchase", {
    value: this.totalPrice,
    currency: "EGP",
    contents: arrayOfProducts.map(function(item) {
        return {
           id: item.id,
           quantity: item.quantity
        }
    }),
    content_type: "product"
  });
</code>```

Title: Facebook pixel purchase body event

Body:
I am trying to make an purchase facebookEvent which it takes an array of objects "Products" that contains the id and the quantity of each product on this array, what I am asking about here that I tried allot to looping into the array of products inside the payload of the event but the compiler has complained, could any one help by how to make the contents array responsive with the array of the whole product ?

  //fbp
  (<any>window).fbq("track", "Purchase", {
    value: this.totalPrice,
    currency: "EGP",
    contents: [
      {
        // this should be applicable for every single item on the arrayOfProducts
        id: arrayOfProducts[0].id,
        quantity: arrayOfProducts[0].quantity
      }
    ],
    content_type: "product"
  });

Body:
What i mean by my questions is, how to push the whole arrayOfProducts instead of passing only the first item on the array ?

Use map

//fbp
  (<any>window).fbq("track", "Purchase", {
    value: this.totalPrice,
    currency: "EGP",
    contents: arrayOfProducts.map(function(item) {
        return {
           id: item.id,
           quantity: item.quantity
        }
    }),
    content_type: "product"
  });


问:
When clicking on the child don't consider the parent
I want some method to convince CSS that when I click on one of the children inside the parent element don't consider that I clicked also on the parent element.
I want you to try clicking on one of the children inside the parent.

  .parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent:active{
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">Click me</div>
   <div class="child">Click me</div>
</div></code>```

答:
Using Javascript, you can simply prevent triggering the :active on the parent, using preventDefault for mousedown event on the children:

document.querySelectorAll('.child').forEach(child =>
  child.addEventListener('mousedown', (event) => {
    event.preventDefault();
  })
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent {
  background: blue;
  padding: 20px;
  text-align: center;
  margin: 0 auto;
  height: 300px;
  width: 300px;
}

.parent:active {
  background: #ddd;
}

.child {
  background: red;
  float: left;
  padding: 5px;
  height: 150px;
  width: 150px;
  font-size: 4em;
}

.child:nth-child(odd) {
  background: pink;
}</code>```

Click me

Click me

```

Body:
I want some method to convince CSS that when I click on one of the children inside the parent element don't consider that I clicked also on the parent element.
I want you to try clicking on one of the children inside the parent.

  .parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent:active{
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }

Click me

Click me

Body:
Using Javascript, you can simply prevent triggering the :active on the parent, using preventDefault for mousedown event on the children:

document.querySelectorAll('.child').forEach(child =>
  child.addEventListener('mousedown', (event) => {
    event.preventDefault();
  })
);

.parent {
  background: blue;
  padding: 20px;
  text-align: center;
  margin: 0 auto;
  height: 300px;
  width: 300px;
}

.parent:active {
  background: #ddd;
}

.child {
  background: red;
  float: left;
  padding: 5px;
  height: 150px;
  width: 150px;
  font-size: 4em;
}

.child:nth-child(odd) {
  background: pink;
}

<div class="parent">
  <div class="child">Click me</div>
  <div class="child">Click me</div>
</div>


问:
How to move dropdown arrow left side instead of right side which is by default in flutter?
From the below code, I can customize only dropdown icon but I can't move to the left side. like this picture.

```<code>Widget testDropdown(){
    return DropdownButtonHideUnderline(
      child: DropdownButton<String>(
        items: <String>[
          'Item 1',
          'Item 2',
          'Item 3',
          'Item 4',
          'Item 5'
        ].map((String value) {
          return DropdownMenuItem(
            value: value,
            child: Text(value),
          );
        }).toList(),
        icon: Icon(
          Icons.keyboard_arrow_down,
          color: Colors.black,
        ),
        onChanged: (value) {
          print(value);
        },
      ),
    );
  }
</code>```

Thanks in Advance.

答:
wrap it with Directionality widget with textDirection: TextDirection.rtl property

```<code>  Widget testDropdown() {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          items: <String>['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'].map((String value) {
            return DropdownMenuItem(
              value: value,
              child: Text(value),
            );
          }).toList(),
          icon: Icon(
            Icons.keyboard_arrow_down,
            color: Colors.black,
          ),
          onChanged: (value) {
            print(value);
          },
        ),
      ),
    );
  }
</code>```

Body:
From the below code, I can customize only dropdown icon but I can't move to the left side. like this picture.

Widget testDropdown(){
    return DropdownButtonHideUnderline(
      child: DropdownButton<String>(
        items: <String>[
          'Item 1',
          'Item 2',
          'Item 3',
          'Item 4',
          'Item 5'
        ].map((String value) {
          return DropdownMenuItem(
            value: value,
            child: Text(value),
          );
        }).toList(),
        icon: Icon(
          Icons.keyboard_arrow_down,
          color: Colors.black,
        ),
        onChanged: (value) {
          print(value);
        },
      ),
    );
  }

Thanks in Advance.

Body:
wrap it with Directionality widget with textDirection: TextDirection.rtl property

  Widget testDropdown() {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          items: <String>['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'].map((String value) {
            return DropdownMenuItem(
              value: value,
              child: Text(value),
            );
          }).toList(),
          icon: Icon(
            Icons.keyboard_arrow_down,
            color: Colors.black,
          ),
          onChanged: (value) {
            print(value);
          },
        ),
      ),
    );
  }