问:
React Native: Android: Cannot generate signed APK
```<code>Execution failed for task ':app:packageRelease'.
Failed to read key my-key-alias from store
"/Users/MichaelLeung/GHRepos/MyApp/android/app/my-release-
key.keystore": Keystore was tampered with, or password was incorrect
</code>```

I'm positive my password is correct; I've gone through the steps that Facebook lists on the React Native docs multiple times.

答:
So if you were trying to generate a signed APK and used a no ASCII letter, you'd probably get this error.

Execution failed for task ':app:packageRelease'.

com.android.ide.common.signing.KeytoolException: Failed to read key my-key-alias from store "/Users/.../.../.../android/app/my-release-key.keystore":
  keystore password was incorrect

I couldn't find a way to reset the old password.

Thankfully there is a work around, using the Android Studio.

First I had to remove all the code from gradle.properties and build.gradle,
(that I had to add according to the docs..

This solution is from a a comment here: Keystore password was incorrect
"I am facing the same issue. Using Build -> Generate Signed APK in android studio works, but putting the config in build.gradle doesn't."

Then use the "signing/keytool UI that's part of Android Studio", which can be found in Build -> Generate Signed Bundle/APK ...

There you can create a new key store password and a key password WHICH HAVE TO BE THE SAME!!!

Note after finishing, Android Studio saves the app-release.apk file in android -> app -> release.

Happy coding :)

Body:
Execution failed for task ':app:packageRelease'.
Failed to read key my-key-alias from store
"/Users/MichaelLeung/GHRepos/MyApp/android/app/my-release-
key.keystore": Keystore was tampered with, or password was incorrect

I'm positive my password is correct; I've gone through the steps that Facebook lists on the React Native docs multiple times.


来源: stackexchange

问:
Extract string value of an ENUM in a Typescript Object
I have an Enum:

```<code>export enum DistanceMeasure {
Miles, Kilometers
</code>```

}

To use in a user object:

```<code>export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff
</code>```

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

```<code>      console.log(user.DistanceMeasure);
</code>```

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

```<code>      console.log(user.DistanceMeasure[0]);
</code>```

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

答:
That should be DistanceMeasure[user.DistanceMeasure], as in the following snippet:

```<code>enum DistanceMeasure {
    Miles, Kilometers
}

class User {
    DistanceMeasure:　DistanceMeasure;
}

const user = new User();
user.DistanceMeasure = 0;

console.log(DistanceMeasure[user.DistanceMeasure]); // Miles
</code>```

What's contributing greatly to the confusion is that fact that you're not following naming conventions, and thus end up with properties that have the same name as your enum.

ContentLicense: CC BY-SA 4.0

Body:
I have an Enum:

export enum DistanceMeasure {
Miles, Kilometers

}

To use in a user object:

export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

      console.log(user.DistanceMeasure);

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

      console.log(user.DistanceMeasure[0]);

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

Body:
That should be DistanceMeasure[user.DistanceMeasure], as in the following snippet:

enum DistanceMeasure {
    Miles, Kilometers
}

class User {
    DistanceMeasure:　DistanceMeasure;
}

const user = new User();
user.DistanceMeasure = 0;

console.log(DistanceMeasure[user.DistanceMeasure]); // Miles

What's contributing greatly to the confusion is that fact that you're not following naming conventions, and thus end up with properties that have the same name as your enum.


问:
How to set ROBOT_LIBRARY_SCOPE dynamically in Robot framework
Is there a way to define ROBOT_LIBRARY_SCOPE = 'GLOBAL' when creating tests dynamically ?

Currently I have to define ROBOT_LIBRARY_SCOPE in the class of my library, but I'd like to have it defined during the creation of the test case.

For example, I tried by adding to the imported Library - a class property:

```<code>suite.resource.imports.library('MyLib.py')
suite.resource.imports[-1].__class__.ROBOT_LIBRARY_SCOPE = 'GLOBAL'
# or with set attribute:
setattr(suite.resource.imports[-1].__class__, 'ROBOT_LIBRARY_SCOPE', 'GLOBAL')
</code>```

And I also tried to add a class property to the created TestCase:

```<code>testCase = suite.tests.create('MyTest')
testCase.__class__.ROBOT_LIBRARY_SCOPE = 'GLOBAL'
# or with set attribute:
setattr(testCase.__class__, 'ROBOT_LIBRARY_SCOPE', 'GLOBAL')

</code>```

But during test runtime, these class properties have no effect on the actual ROBOT_LIBRARY_SCOPE.

答:
I've suggested an implementation to set ROBOT_LIBRARY_SCOPE when importing custom libraries:
https://github.com/manosnoam/robotframework/commit/98f62c4b29d399cdc16b39bb61e10f835c27c48e

Once my patch is merged, you'll be able to call for example:

```<code>suite.resource.imports.library('YourLib.py', scope='TEST SUITE')
</code>```

Instead of setting ROBOT_LIBRARY_SCOPE in YourLib class:

 ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

Body:
Is there a way to define ROBOT_LIBRARY_SCOPE = 'GLOBAL' when creating tests dynamically ?

Currently I have to define ROBOT_LIBRARY_SCOPE in the class of my library, but I'd like to have it defined during the creation of the test case.

For example, I tried by adding to the imported Library - a class property:

suite.resource.imports.library('MyLib.py')
suite.resource.imports[-1].__class__.ROBOT_LIBRARY_SCOPE = 'GLOBAL'
# or with set attribute:
setattr(suite.resource.imports[-1].__class__, 'ROBOT_LIBRARY_SCOPE', 'GLOBAL')

And I also tried to add a class property to the created TestCase:

testCase = suite.tests.create('MyTest')
testCase.__class__.ROBOT_LIBRARY_SCOPE = 'GLOBAL'
# or with set attribute:
setattr(testCase.__class__, 'ROBOT_LIBRARY_SCOPE', 'GLOBAL')

But during test runtime, these class properties have no effect on the actual ROBOT_LIBRARY_SCOPE.

Body:
I've suggested an implementation to set ROBOT_LIBRARY_SCOPE when importing custom libraries:
https://github.com/manosnoam/robotframework/commit/98f62c4b29d399cdc16b39bb61e10f835c27c48e

Once my patch is merged, you'll be able to call for example:

suite.resource.imports.library('YourLib.py', scope='TEST SUITE')

Instead of setting ROBOT_LIBRARY_SCOPE in YourLib class:

 ROBOT_LIBRARY_SCOPE = 'TEST SUITE'


问:
Set default value for a field while populating POJO using Bean Utils
I am trying to populate the fields of a POJO using BeanUtilsBean.populate(object, fieldNameVSfieldValueMap) method.

My POJO looks like :

```<code>class POJO{
  Integer intField;
  Double doubleField
  String str;
}
</code>```

Currently I have a HashMap that contains a map between the field name and field value.

Now with the following code:

```<code>POJO obj = new POJO();
Map<String,String> map = new HashMap<>();
map.put("intField", "1");
map.put("doubleField", "1.1");
BeanUtilsBean.populate(obj, map)

</code>```

With the above code in my POJO object obj, the fields intField and doubleField get populated with the values 1 and 1.1 respectively which is as expected.

The problem with this is that, the string field str get null assigned to it as there was no entry in the hashmap for str and null is default value for String.
But I want was an explicit way to set my custom value to a field when they are not mentioned in the map.
For this example lets say I want to set str to "john" as there is not entry for str in the map.
Edit 1:
And also that should be specific to the field type. So if there are other fields in POJO and they are of String type, then for all those String fields, for whom entry is not there in the Map should be populated with John.

Edit 2: The POJO is defined in a different project that I dont have commit access to, so set default values in the POJO itself is not a solution to me.

答: Try using the org.apache.commons.beanutils.BeanUtilsBean class with aid of the org.apache.commons.beanutils.ConvertUtilsBean class</p>

Body:
I am trying to populate the fields of a POJO using BeanUtilsBean.populate(object, fieldNameVSfieldValueMap) method.

My POJO looks like :

class POJO{
  Integer intField;
  Double doubleField
  String str;
}

Currently I have a HashMap that contains a map between the field name and field value.

Now with the following code:

POJO obj = new POJO();
Map<String,String> map = new HashMap<>();
map.put("intField", "1");
map.put("doubleField", "1.1");
BeanUtilsBean.populate(obj, map)

With the above code in my POJO object obj, the fields intField and doubleField get populated with the values 1 and 1.1 respectively which is as expected.

The problem with this is that, the string field str get null assigned to it as there was no entry in the hashmap for str and null is default value for String.
But I want was an explicit way to set my custom value to a field when they are not mentioned in the map.
For this example lets say I want to set str to "john" as there is not entry for str in the map.
Edit 1:
And also that should be specific to the field type. So if there are other fields in POJO and they are of String type, then for all those String fields, for whom entry is not there in the Map should be populated with John.

Edit 2: The POJO is defined in a different project that I dont have commit access to, so set default values in the POJO itself is not a solution to me.


问:
Could anyone verify the correctness of getting a md5 hash using this method?
```<code>        MessageDigest m=MessageDigest.getInstance("MD5");
        StringBuffer sb = new StringBuffer();
        if(nodeName!=null) sb.append(nodeName);
        if(nodeParentName!=null) sb.append(nodeParentName);
        if(nodeParentFieldName!=null) sb.append(nodeParentFieldName);
        if(nodeRelationName!=null) sb.append(nodeRelationName);
        if(nodeViewName!=null) sb.append(nodeViewName);
        if(treeName!=null) sb.append(treeName);
        if(nodeValue!=null && nodeValue.trim().length()>0) sb.append(nodeValue);
        if(considerParentHash) sb.append(parentHash);
        m.update(sb.toString().getBytes("UTF-8"),0,sb.toString().length());
        BigInteger i = new BigInteger(1,m.digest());
        hash = String.format("%1$032X", i);
</code>```

The idea behind these lines of code is that we append all the values of a class/model into a StringBuilder and then return the padded hash of that (the Java implementation returns md5 hashes that are lenght 30 or 31, so the last line formats the hash to be padded with 0s).

I can verify that this works, but I have a feeling it fails at one point (our application fails and I believe this to be the probable cause).

Can anyone see a reason why this wouldn't work? Are there any workarounds to make this code less prone to errors (e.g. removing the need for the strings to be UTF-8).

答:
One possible problem is here:

```<code>m.update(sb.toString().getBytes("UTF-8"),0,sb.toString().length());
</code>```

As said by Robing Green, the UTF-8 encoding can produce a byte[] which is longer than your original string (it will do this exactly when the String contains non-ASCII characters). In this case, you are only hashing the start of your String.

Better write it like this:

```<code>m.update(sb.toString().getBytes("UTF-8"));
</code>```

Of course, this would not cause an exception, simply another hash than would be produced otherwise, if you have non-ASCII-characters in your string. You should try to brew your failure down to an SSCCE, like lesmana recommended.

ContentLicense: CC BY-SA 3.0

Body:
        MessageDigest m=MessageDigest.getInstance("MD5");
        StringBuffer sb = new StringBuffer();
        if(nodeName!=null) sb.append(nodeName);
        if(nodeParentName!=null) sb.append(nodeParentName);
        if(nodeParentFieldName!=null) sb.append(nodeParentFieldName);
        if(nodeRelationName!=null) sb.append(nodeRelationName);
        if(nodeViewName!=null) sb.append(nodeViewName);
        if(treeName!=null) sb.append(treeName);
        if(nodeValue!=null && nodeValue.trim().length()>0) sb.append(nodeValue);
        if(considerParentHash) sb.append(parentHash);
        m.update(sb.toString().getBytes("UTF-8"),0,sb.toString().length());
        BigInteger i = new BigInteger(1,m.digest());
        hash = String.format("%1$032X", i);

The idea behind these lines of code is that we append all the values of a class/model into a StringBuilder and then return the padded hash of that (the Java implementation returns md5 hashes that are lenght 30 or 31, so the last line formats the hash to be padded with 0s).

I can verify that this works, but I have a feeling it fails at one point (our application fails and I believe this to be the probable cause).

Can anyone see a reason why this wouldn't work? Are there any workarounds to make this code less prone to errors (e.g. removing the need for the strings to be UTF-8).

Body:
One possible problem is here:

m.update(sb.toString().getBytes("UTF-8"),0,sb.toString().length());

As said by Robing Green, the UTF-8 encoding can produce a byte[] which is longer than your original string (it will do this exactly when the String contains non-ASCII characters). In this case, you are only hashing the start of your String.

Better write it like this:

m.update(sb.toString().getBytes("UTF-8"));

Of course, this would not cause an exception, simply another hash than would be produced otherwise, if you have non-ASCII-characters in your string. You should try to brew your failure down to an SSCCE, like lesmana recommended.


问:
How to prevent change detection on scroll? ( Angular )
I have a large component, and I would like to avoid unnecessary change detections to increase performance.

I added changeDetection: ChangeDetectionStrategy.OnPush to the @Component.

I would like to update the style of an element if it is scrolled. Unfortunately Angular runs the change detection, every time I scroll that element.

I tried to add an event listener to the native element to avoid this, but the change detection is still running again when I scroll:

```<code>@ViewChild('my_element') my_element_ref: ElementRef;

ngOnInit() {
    this.my_element_ref.nativeElement.addEventListener('scroll', this.updateStyle);
}

ngAfterViewChecked() {
    console.log('check');
}
</code>```

The ngAfterViewChecked is called even if this.updateStyle is an empty function.
But if I comment out this.my_element_ref.nativeElement.addEventListener('scroll', this.onScroll), then ngAfterViewChecked is not called anymore.

How is it possible to call a function when an element is scrolled, but avoid Angular's change detection?

答:
I would suggest you use ngZone.runOutsideAngular.</p>

```<code>constructor (private zone : NgZone) {}
ngAfterViewInit () : any {
    this.zone.runOutsideAngular(() => {
      window.addEventListener('scroll', (e)=> {
        console.log( 'scroll event fired' );
      });
    });
  }
</code>```

Body:
I have a large component, and I would like to avoid unnecessary change detections to increase performance.

I added changeDetection: ChangeDetectionStrategy.OnPush to the @Component.

I would like to update the style of an element if it is scrolled. Unfortunately Angular runs the change detection, every time I scroll that element.

I tried to add an event listener to the native element to avoid this, but the change detection is still running again when I scroll:

@ViewChild('my_element') my_element_ref: ElementRef;

ngOnInit() {
    this.my_element_ref.nativeElement.addEventListener('scroll', this.updateStyle);
}

ngAfterViewChecked() {
    console.log('check');
}

The ngAfterViewChecked is called even if this.updateStyle is an empty function.
But if I comment out this.my_element_ref.nativeElement.addEventListener('scroll', this.onScroll), then ngAfterViewChecked is not called anymore.

How is it possible to call a function when an element is scrolled, but avoid Angular's change detection?

Body:
I would suggest you use ngZone.runOutsideAngular.

constructor (private zone : NgZone) {}
ngAfterViewInit () : any {
    this.zone.runOutsideAngular(() => {
      window.addEventListener('scroll', (e)=> {
        console.log( 'scroll event fired' );
      });
    });
  }


问:
Handling errors in contact form - Get the right finction
I have created a form using material-ui with React.
I have got some issues with my submit method.
I am displaying a snackbar to inform user of the success of submission, and also a snackbar to alert the user that required fields are missing.
My issue is in case user didn't fill all fields, but after a second attempt finally makes it with success. My alert snackbar is still appearing but I want to show the success snackbar. Not sure what I need to change in my method.</p>

```<code> submit = () => {
    const {
      firstName,
      lastName,
      email,
      phone,
      date,
      time,
      projectStages,
      projectDescription,
      budgets,
      mainObjectives,
      applicationTypes,
    } = this.state
    // eslint-disable-next-line max-len
    if (lastName && firstName && email && phone) {
      this.setState({
        lastName,
        firstName,
        email,
        phone,
        date,
        time,
        projectStages,
        projectDescription,
        budgets,
        mainObjectives,
        applicationTypes,
      })
      document.getElementById('snackbar').style.display = 'block'
      setTimeout(() => {
        this.setState({ open: false })
      }, 2000)
      // eslint-disable-next-line max-len
      this.saveMessage(firstName, lastName, phone, email, date, time, projectStages, projectDescription, budgets, mainObjectives, applicationTypes)
    } else {
      document.getElementById('snackbar').style.display = 'block'
      document.getElementById('snackbar').style.backgroundColor = 'red'
      document.getElementById('snackbar').textContent = 'Please fill in all required fields'
      setTimeout(() => {
        document.getElementById('snackbar').style.display = 'none'
      }, 2000)
    }
  }
</code>```

答:
Clear your timer before set it again</p>

```<code>timer && clearTimeout(timer);
</code>```

Body:
I have created a form using material-ui with React.
I have got some issues with my submit method.
I am displaying a snackbar to inform user of the success of submission, and also a snackbar to alert the user that required fields are missing.
My issue is in case user didn't fill all fields, but after a second attempt finally makes it with success. My alert snackbar is still appearing but I want to show the success snackbar. Not sure what I need to change in my method.

 submit = () => {
    const {
      firstName,
      lastName,
      email,
      phone,
      date,
      time,
      projectStages,
      projectDescription,
      budgets,
      mainObjectives,
      applicationTypes,
    } = this.state
    // eslint-disable-next-line max-len
    if (lastName && firstName && email && phone) {
      this.setState({
        lastName,
        firstName,
        email,
        phone,
        date,
        time,
        projectStages,
        projectDescription,
        budgets,
        mainObjectives,
        applicationTypes,
      })
      document.getElementById('snackbar').style.display = 'block'
      setTimeout(() => {
        this.setState({ open: false })
      }, 2000)
      // eslint-disable-next-line max-len
      this.saveMessage(firstName, lastName, phone, email, date, time, projectStages, projectDescription, budgets, mainObjectives, applicationTypes)
    } else {
      document.getElementById('snackbar').style.display = 'block'
      document.getElementById('snackbar').style.backgroundColor = 'red'
      document.getElementById('snackbar').textContent = 'Please fill in all required fields'
      setTimeout(() => {
        document.getElementById('snackbar').style.display = 'none'
      }, 2000)
    }
  }

Body:
Clear your timer before set it again

timer && clearTimeout(timer);


答:
just inject NgZone in your constructor and then subscribe to an event like this:

```<code>this.ngZone.runOutsideAngular(() => {
  ....addEventListener('...);
});
</code>```

keep in mind that change detection will not be called in this case, so you won't be able to change styles with template binding. It should be changed by native javascript or using Renderer2

Title: How to prevent change detection on scroll? ( Angular )

Body:
just inject NgZone in your constructor and then subscribe to an event like this:

this.ngZone.runOutsideAngular(() => {
  ....addEventListener('...);
});

keep in mind that change detection will not be called in this case, so you won't be able to change styles with template binding. It should be changed by native javascript or using Renderer2


问:
iOS camera preview color temperature
Is it somehow possible to get the white balance color temperature (and tint) from a camera preview or from a saved picture?

I am able to get other exposure values in real time based on this SO thread, like f-stop, exposure time, ISO, etc. The white balance always returns just 0, probably meaning "auto white balance". When I save an image from live preview the EXIF data has the white balance still just a zero.

I need to get the white balance color temperature in Kelvins the image/live camera preview was balanced to. I read some stuff about hidden APIs to get/set color temperature, but I cannot use hidden APIs. Any ideas if/how is this possible on iOS 7? Thank you.

答:
It seems like it's possible to get values with the current API, you can check this out if you're still interested.
https://developer.apple.com/documentation/avfoundation/avcapturedevice/whitebalancetemperatureandtintvalues</p>

Title: iOS camera preview color temperature


问:
MVC2: SQL Server table --> Excel Spreadsheet
is there an easy way to export a SQL Server table into a xls spreadsheet?

Thanks

答:
found a nice and easy solution

http://blog.wiredworx.co.uk/website-and-seo/c-tutorials-and-tips-visual-studio/exporting-to-an-excel-file-from-asp-net-mvc/


问:
Calculate direct dependencies among values of a dataframe in R
A data frame is given and the objective is to calculate the direct dependency value between two columns of the data frame.

```<code>c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10
</code>```

what we are looking for is that to get the direct dependency relations, for example, for aand b this value is ab - ba = 20.
The final result should be like this:

```<code>c1  c2   N     DepValue
a    b   30    ab - ba = 20
a    c   5     ac - ca = 0
a    d   10    ad- 0 = 10
c    a   5     ca - ac= 0
b    a   10    ba - ab = 20
</code>```

Thank you for your help.

答:
An idea via base R is to sort columns c1 and c2, split based on those values and subtract N, i.e.

```<code>i1 <- paste(pmin(df$c1, df$c2), pmax(df$c1, df$c2))
i1
#[1] "a b" "a c" "a d" "a c" "a b"

do.call(rbind, lapply(split(df, i1), function(i) {i['DepValue'] <- Reduce(`-`, i$N); i}))
#      c1 c2  N DepValue
#a b.1  a  b 30       20
#a b.5  b  a 10       20
#a c.2  a  c  5        0
#a c.4  c  a  5        0
#a d    a  d 10       10
</code>```

Body:
A data frame is given and the objective is to calculate the direct dependency value between two columns of the data frame.

c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10

what we are looking for is that to get the direct dependency relations, for example, for aand b this value is ab - ba = 20.
The final result should be like this:

c1  c2   N     DepValue
a    b   30    ab - ba = 20
a    c   5     ac - ca = 0
a    d   10    ad- 0 = 10
c    a   5     ca - ac= 0
b    a   10    ba - ab = 20

Thank you for your help.

Body:
An idea via base R is to sort columns c1 and c2, split based on those values and subtract N, i.e.

i1 <- paste(pmin(df$c1, df$c2), pmax(df$c1, df$c2))
i1
#[1] "a b" "a c" "a d" "a c" "a b"

do.call(rbind, lapply(split(df, i1), function(i) {i['DepValue'] <- Reduce(`-`, i$N); i}))
#      c1 c2  N DepValue
#a b.1  a  b 30       20
#a b.5  b  a 10       20
#a c.2  a  c  5        0
#a c.4  c  a  5        0
#a d    a  d 10       10


答:
You might want to look at ChangeDetectorRef API.
Specifically you would detach the change detection for the component using detach() (maybe in the constructor like below) and then mark component for change in your scroll function via markForCheck().

  constructor(public cd: ChangeDetectorRef) {
    this.cd.detach();
  }```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>this.cd.markForCheck(); </code>```

Below links for your reference.

https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f

https://angular.io/api/core/ChangeDetectorRef

Body:
You might want to look at ChangeDetectorRef API.
Specifically you would detach the change detection for the component using detach() (maybe in the constructor like below) and then mark component for change in your scroll function via markForCheck().

  constructor(public cd: ChangeDetectorRef) {
    this.cd.detach();
  }

this.cd.markForCheck();

Below links for your reference.

https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f

https://angular.io/api/core/ChangeDetectorRef


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

答:
I would use a collections.deque.

```<code>from collections import deque
SAMPLE = 3
data = deque(maxlen=SAMPLE)
while True:
    distance = misura() # GETTING THE REAL DISTANCE IN CM
    print "Distanza : %.2f" % distanza

    data.append(distance)
    avg_distance = sum(data)/SAMPLE # <- HERE I NEED SOMETHING ELEGANT

    ... # rest as before
</code>```

The deque is fixed length so you're only sampling the latest three. If you want to change the sampling period you only have to change one variable.

If you want to run this in a tight loop (ie, removing the 1.5s sleep), you could hold the sum in a variable to remove the O(n) operation each loop (even if it's not really an issue for only 3 elements). Something like:

```<code>total -= data.popleft()
total += distance

data.append(distance)
average = total / 3
</code>```

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
I would use a collections.deque.

from collections import deque
SAMPLE = 3
data = deque(maxlen=SAMPLE)
while True:
    distance = misura() # GETTING THE REAL DISTANCE IN CM
    print "Distanza : %.2f" % distanza

    data.append(distance)
    avg_distance = sum(data)/SAMPLE # <- HERE I NEED SOMETHING ELEGANT

    ... # rest as before

The deque is fixed length so you're only sampling the latest three. If you want to change the sampling period you only have to change one variable.

If you want to run this in a tight loop (ie, removing the 1.5s sleep), you could hold the sum in a variable to remove the O(n) operation each loop (even if it's not really an issue for only 3 elements). Something like:

total -= data.popleft()
total += distance

data.append(distance)
average = total / 3


问:
Using DTOs properly in a Restful web service
I am developing a restful web service using spring framework. I have a few questions on how to use DTOs properly in my project.

First of all, I saw a lot of code examples on using DTOs and there is always a one to one mapping with entities. For User entity we have UserDto, For Country, we have CountryDto and etc. I think this is not flexible at all. For every service, I need two DTOs for input and output. is that ok?

If I define two DTOs for each service, Can I name them with request and response suffixes? For example for createUser service, I have two DTO objects called CreateUserRequest and CreateUserResponse.

Some services have no outputs(Just a status code) or inputs(Just an Id in URL). Should I Define an empty DTO for them or not? If I don't define a DTO in these scenarios, it is a bit confusing because sometimes you define two DTOs for service and sometimes just one.

Should I map path variables like /users/{id} to DTO objects too? for example instead of:

```<code>@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") Long id)
</code>```

do something like:

```<code>@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") GetUserRequest request)
</code>```

答:
Follow this pattern :

```<code>@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUser(@PathVariable long id) {
        ResponseEntity<User> response = null;
        try {
            User user = userService.getUser(id);
            response = new ResponseEntity<User>(user, HttpStatus.OK);
        } catch (ApplicationException ex) {
            response = new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return response;
    }
</code>```

Don't create a url like this : /users/{id}

Create a url like this - /{id} - this will give more abstraction.

Body:
I am developing a restful web service using spring framework. I have a few questions on how to use DTOs properly in my project.

First of all, I saw a lot of code examples on using DTOs and there is always a one to one mapping with entities. For User entity we have UserDto, For Country, we have CountryDto and etc. I think this is not flexible at all. For every service, I need two DTOs for input and output. is that ok?

If I define two DTOs for each service, Can I name them with request and response suffixes? For example for createUser service, I have two DTO objects called CreateUserRequest and CreateUserResponse.

Some services have no outputs(Just a status code) or inputs(Just an Id in URL). Should I Define an empty DTO for them or not? If I don't define a DTO in these scenarios, it is a bit confusing because sometimes you define two DTOs for service and sometimes just one.

Should I map path variables like /users/{id} to DTO objects too? for example instead of:

@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") Long id)

do something like:

@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") GetUserRequest request)

Body:
Follow this pattern :

@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUser(@PathVariable long id) {
        ResponseEntity<User> response = null;
        try {
            User user = userService.getUser(id);
            response = new ResponseEntity<User>(user, HttpStatus.OK);
        } catch (ApplicationException ex) {
            response = new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return response;
    }

Don't create a url like this : /users/{id}

Create a url like this - /{id} - this will give more abstraction.


问:
How configure maven-war-plugin for tomcat
I can not generate proper WAR file for Tomcat.

I am using MAVEN 3.6.1, Java 12.0.1 and IDE Eclipse. My app is working fine when I run it in eclipse (Run as > Spring Boot App) but the problem is when I am trying to run my WAR file after generate it.

I am doing java -jar .war  and I am getting:

```<code>Error: Could not find or load main class com.blw.linemanager.Application
Caused by: java.lang.ClassNotFoundException: com.blw.linemanager.Application
</code>```

I was googling and reading stackoverflow cause I found many post about it but still can not run it. What I am doing wrong?

After some reading I figured out that I have some how configure maven-war-plugin (am I right?) and in pom I did some changes but it does not help.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>bwl</groupId>
    <artifactId>LineManager</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.3.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-utils</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <properties>
        <start-class>com.blw.linemanager.Application</start-class>
        <maven.compiler.source>12</maven.compiler.source>
        <maven.compiler.target>12</maven.compiler.target>
    </properties>

    <build>
        <finalName>LineManager</finalName>
        <outputDirectory>${project.build.directory}</outputDirectory>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <release>12</release>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/META-INF</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${basedir}/src/main/resources/META-INF</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <archive>
                        <manifest>
                            <classpathPrefix>${project.build.directory}/WEB-INF/classes</classpathPrefix>
                            <addClasspath>true</addClasspath>
                            <mainClass>com.blw.linemanager.Application</mainClass>
                        </manifest>
                        <manifestFile>${project.build.directory}/META-INF/MANIFEST.MF</manifestFile>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
```

<p>Also because on the beginning I was getting error 'no main manifest attribute' I add it and now it looks like this</p>

```Manifest-Version: 1.0
Created-By: Apache Maven ${maven.version}
Build-Jdk: ${java.version}
```

<p>Is my way of think wrong? Should I be able to run .war file as java -jar .war or this is missunderstanding?</p>

<pre class="lang-java prettyprint-override"><code>@SpringBootApplication
public class Application extends org.springframework.boot.web.support.SpringBootServletInitializer {
    public static void main(String [] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.run(args);
    }

    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

}
</code>```

答:
Add packaging type with version detail in pom.xml like

```<code><packaging>jar</packaging>
</code>```

or

```<code><packaging>war</packaging>
</code>```

Then, append build tag to define name of jar / war like,

```<code><build>
    <finalName>YOUR-APP_NAME</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

Then, run your application with goal

clean package

to create jar/war in target folder.

Rename your war file to ROOT like ROOT.war

Last step to copy your created jar/war in tomcat webapps folder and start tomcat.

Body:
I can not generate proper WAR file for Tomcat.

I am using MAVEN 3.6.1, Java 12.0.1 and IDE Eclipse. My app is working fine when I run it in eclipse (Run as > Spring Boot App) but the problem is when I am trying to run my WAR file after generate it.

I am doing java -jar .war  and I am getting:

Error: Could not find or load main class com.blw.linemanager.Application
Caused by: java.lang.ClassNotFoundException: com.blw.linemanager.Application

I was googling and reading stackoverflow cause I found many post about it but still can not run it. What I am doing wrong?

After some reading I figured out that I have some how configure maven-war-plugin (am I right?) and in pom I did some changes but it does not help.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>bwl</groupId>
    <artifactId>LineManager</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.3.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-utils</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <properties>
        <start-class>com.blw.linemanager.Application</start-class>
        <maven.compiler.source>12</maven.compiler.source>
        <maven.compiler.target>12</maven.compiler.target>
    </properties>

    <build>
        <finalName>LineManager</finalName>
        <outputDirectory>${project.build.directory}</outputDirectory>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <release>12</release>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/META-INF</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>${basedir}/src/main/resources/META-INF</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <archive>
                        <manifest>
                            <classpathPrefix>${project.build.directory}/WEB-INF/classes</classpathPrefix>
                            <addClasspath>true</addClasspath>
                            <mainClass>com.blw.linemanager.Application</mainClass>
                        </manifest>
                        <manifestFile>${project.build.directory}/META-INF/MANIFEST.MF</manifestFile>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Also because on the beginning I was getting error 'no main manifest attribute' I add it and now it looks like this

Manifest-Version: 1.0
Created-By: Apache Maven ${maven.version}
Build-Jdk: ${java.version}

Is my way of think wrong? Should I be able to run .war file as java -jar .war or this is missunderstanding?

@SpringBootApplication
public class Application extends org.springframework.boot.web.support.SpringBootServletInitializer {
    public static void main(String [] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.run(args);
    }

    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

}

Body:
Add packaging type with version detail in pom.xml like

<packaging>jar</packaging>

or

<packaging>war</packaging>

Then, append build tag to define name of jar / war like,

<build>
    <finalName>YOUR-APP_NAME</finalName>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Then, run your application with goal

clean package

to create jar/war in target folder.

Rename your war file to ROOT like ROOT.war

Last step to copy your created jar/war in tomcat webapps folder and start tomcat.


问:
mysql select ids from one table which are not found in another table under certain conditions
Using the following two (simplified) table structures I'd like to find all DISTINCT session_id values that appear in TABLE1 where flag = yes that DO NOT appear in TABLE2 where progress = 11.

TABLE1 has no duplicate session_id values.

TABLE1

```<code>id_table1 | session_id | flag
------------------------------
1         | abcd       | yes
2         | efgh       | no
3         | ijkl       | yes
4         | mnop       | yes
5         | vwxyz      | yes
</code>```

TABLE2

```<code>id_table2 | session_id | progress
---------------------------------
1         | abcd       | 3
2         | efgh       | 11
3         | ijkl       | 2
4         | ijkl       | 7
5         | mnop       | 11
6         | vwxyz      | 10
7         | vwxyz      | 11
</code>```

The expected results here are:

```<code>abcd
ijkl
</code>```

答:
```<code>select distinct session_id
from table1 where session_id not in (select session_id from table2) and flag='yes'
</code>```

Body:
Using the following two (simplified) table structures I'd like to find all DISTINCT session_id values that appear in TABLE1 where flag = yes that DO NOT appear in TABLE2 where progress = 11.

TABLE1 has no duplicate session_id values.

TABLE1

id_table1 | session_id | flag
------------------------------
1         | abcd       | yes
2         | efgh       | no
3         | ijkl       | yes
4         | mnop       | yes
5         | vwxyz      | yes

TABLE2

id_table2 | session_id | progress
---------------------------------
1         | abcd       | 3
2         | efgh       | 11
3         | ijkl       | 2
4         | ijkl       | 7
5         | mnop       | 11
6         | vwxyz      | 10
7         | vwxyz      | 11

The expected results here are:

abcd
ijkl


问:
Laravel mail automation
I'm developing an invoicing system in order to collect payments from customers. Once I create an invoice, an email including invoice details will be sent to the customers with payment link. I want to re-generate payment token(once it expires) and send renewed payment link to the customers, and want to automate the process.

I created a Job called renewingInvoiceLinks and inside the handle method, I wrote code to retrieve all invoices with expired links and create new token and send new link. In App->Console->Kernel.php scheduled the job as following. I referred Laravel Docs but did not get the flow properly to dispatch the Job.

```<code>protected function schedule(Schedule $schedule)
{
    $schedule->job(new renewingInvoiceLinks, 'renewingInvoiceLinks')->daily();
}
</code>```

Things I want to get clear.

Whether using Job to do the requirement is correct or not? If not what is the perfect way to do it.

How to dispatch the Job? (Where I need to call the dispatch method?)

答:
I think the question is quite subjective and opinionated, but here is how I'd do it:

Whenever the payment link is updated, I would fire a custom PaymentLinkUpdated event. You can either fire this event in the place(s) where you update the link, or you listen for the saving event on the affected model and fire the PaymentLinkUpdated event only when the original value is different from the updated one.

A custom event listener will listen for the update of payment links and will send out the email containing the payment details and link. This event listener should be a queued one so that emails are sent in the background and do not block the UI.

A scheduled job will check for expired payment links and will update the affected records, casting a PaymentLinkUpdated event where necessary. This will trigger step 2 (which is automatically queued again).

This way, you'd have all the logic implemented only once and sending mails would not be duplicated. If you have to send a different mail when the payment link is renewed, you can either do so in the event listener or you have to change your strategy entirely.

Title: Laravel mail automation

Body:
I'm developing an invoicing system in order to collect payments from customers. Once I create an invoice, an email including invoice details will be sent to the customers with payment link. I want to re-generate payment token(once it expires) and send renewed payment link to the customers, and want to automate the process.

I created a Job called renewingInvoiceLinks and inside the handle method, I wrote code to retrieve all invoices with expired links and create new token and send new link. In App->Console->Kernel.php scheduled the job as following. I referred Laravel Docs but did not get the flow properly to dispatch the Job.

protected function schedule(Schedule $schedule)
{
    $schedule->job(new renewingInvoiceLinks, 'renewingInvoiceLinks')->daily();
}

Things I want to get clear.

Whether using Job to do the requirement is correct or not? If not what is the perfect way to do it.

How to dispatch the Job? (Where I need to call the dispatch method?)


问:
Type-stable do-blocks in julia
I want to read data from a file with a do-block. Using a do-block it is quite important because I need to be sure that the file gets properly closed even if an error occurs during the reading of the file. The data in the file should be converted to the a type provided as argument. My real use case is to use NetCDF files, but I can reproduce the type stability issue with plain text file.

Assume, there is a file file.txt with the content 123, which can be created with:

```<code> write("file.txt","123")
</code>```

When I load the file without a do-block as follows, the result is type stable:

```<code>function loadfile1(T)
    f = open("file.txt")
    data = parse(T,readline(f))
    close(f)
    return data
end
</code>```

@code_warntype infers correctly that I get Float32 as a result:

```<code>@code_warntype loadfile1(Float32)
Body::Float32
[...]
</code>```

However, the following variant:

```<code>function loadfile2(T)
    f = open("file.txt") do f
        return parse(T,readline(f))
    end
end
</code>```

produces a type-unstable code:

```<code> @code_warntype loadfile2(Float32)
Body::Any
9 1 ─ %1 = %new(getfield(Main, Symbol("##842#843")){DataType}, T)::getfield(Main, Symbol("##842#843")){DataType}                                                                                │
  │   %2 = Main.open::Core.Compiler.Const(open, false)                                                                                │
  │   %3 = invoke Base.:(#open#294)($(QuoteNode(Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}()))::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}, %2::Function, %1::getfield(Main, Symbol("##842#843")){DataType}, "file.txt"::String)::Any
  └──      return %3
</code>```

How could I modify the function loadfile2 (with a do-block) and still get a type-stable result?

答:
It works to move T to a type specification in the signature:

```<code>function loadfile2(::Type{T}) where T
    f = open("file.txt") do f
        return parse(T,readline(f))
    end
end
</code>```

This way T is known at compile time.

Title: Type-stable do-blocks in julia

Body:
I want to read data from a file with a do-block. Using a do-block it is quite important because I need to be sure that the file gets properly closed even if an error occurs during the reading of the file. The data in the file should be converted to the a type provided as argument. My real use case is to use NetCDF files, but I can reproduce the type stability issue with plain text file.

Assume, there is a file file.txt with the content 123, which can be created with:

 write("file.txt","123")

When I load the file without a do-block as follows, the result is type stable:

function loadfile1(T)
    f = open("file.txt")
    data = parse(T,readline(f))
    close(f)
    return data
end

@code_warntype infers correctly that I get Float32 as a result:

@code_warntype loadfile1(Float32)
Body::Float32
[...]

However, the following variant:

function loadfile2(T)
    f = open("file.txt") do f
        return parse(T,readline(f))
    end
end

produces a type-unstable code:

 @code_warntype loadfile2(Float32)
Body::Any
9 1 ─ %1 = %new(getfield(Main, Symbol("##842#843")){DataType}, T)::getfield(Main, Symbol("##842#843")){DataType}                                                                                │
  │   %2 = Main.open::Core.Compiler.Const(open, false)                                                                                │
  │   %3 = invoke Base.:(#open#294)($(QuoteNode(Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}()))::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}, %2::Function, %1::getfield(Main, Symbol("##842#843")){DataType}, "file.txt"::String)::Any
  └──      return %3

How could I modify the function loadfile2 (with a do-block) and still get a type-stable result?

Body:
It works to move T to a type specification in the signature:

function loadfile2(::Type{T}) where T
    f = open("file.txt") do f
        return parse(T,readline(f))
    end
end

This way T is known at compile time.


问:
How to find right "div" to web scrape with python
I cant seem to "inspect" the right function for beautiful soup to function. I am trying to follow these guides but I cant seem to get past this point.

https://www.youtube.com/watch?v=XQgXKtPSzUI&t=119s
Web scraping with Python

I am trying to webscrape a website to compare four vehicles by Safety features, Maintenance cost, and Price point. I am using spyder (python 3.6)

```<code>import bs4
from urllib import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.edmunds.com/car-comparisons/?
veh1=401768437&veh2=401753723&veh3=401780798&veh4=401768504'

# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div", {"class":"feature-field-value"})

filename = "car_comparison.csv"
f = open(filename, "W")

Headers = "Title, product_name, shipping\n"
f.write(headers)

for container in containers:
brand = container.div.div.a.img["title"]

title_container = container.findAll("a", {"class":"vehicle-title f16-nm f14
lh22-nm lh18 pv2 sserif-2 tr-text minh90"})
product_name = title_container[0].text

shipping_container = container.findAll("li",{"class":"price-ship"})
shipping_container[0].text.strip()

print("Title: " + title)
print("product_name: " + product_name)
print("shipping: " + shipping)

f.write( brand + "," +product_name.replace(",", "|") + "," + shipping +
"\n")

f.close()

#Criteria 1
#safety = Warranty, Basic?
#Maintence Cost = Maintence
#Price = Base MSRP
</code>```

I know I have to change quite a bit but right now I just want it to run without getting errors

runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')
Traceback (most recent call last):

File "", line 1, in
    runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py", line 2, in
    from urllib import urlopen as uReq

ImportError: cannot import name 'urlopen'

答:
Try the following code:

```<code>import bs4
from urllib import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.caranddriver.com/car-comparison-tool?chromeIDs=404121,402727,403989,403148'

# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")
containers = page_soup.findAll("div", {
    "class": "w50p "
})
</code>```

I think you are trying to fetch the car comparisons, IMHO this might not work, since

this won't work in the command line as the site will throw unsupported browser;

IMHO the div is not the element to look for, after comparison of the cars in the site (too many of them). Try the document.getElementsByTagName('cd-view-car-card') in the debugger console to see 4 items (where last item is the "Add Car" item). Inside this cd-view-car-card, there is a single div with 2 children, the second child (div) contains all the relevant information (as per the current site design).

Hope this helps

Body:
I cant seem to "inspect" the right function for beautiful soup to function. I am trying to follow these guides but I cant seem to get past this point.

https://www.youtube.com/watch?v=XQgXKtPSzUI&t=119s
Web scraping with Python

I am trying to webscrape a website to compare four vehicles by Safety features, Maintenance cost, and Price point. I am using spyder (python 3.6)

import bs4
from urllib import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.edmunds.com/car-comparisons/?
veh1=401768437&veh2=401753723&veh3=401780798&veh4=401768504'

# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div", {"class":"feature-field-value"})

filename = "car_comparison.csv"
f = open(filename, "W")

Headers = "Title, product_name, shipping\n"
f.write(headers)

for container in containers:
brand = container.div.div.a.img["title"]

title_container = container.findAll("a", {"class":"vehicle-title f16-nm f14
lh22-nm lh18 pv2 sserif-2 tr-text minh90"})
product_name = title_container[0].text

shipping_container = container.findAll("li",{"class":"price-ship"})
shipping_container[0].text.strip()

print("Title: " + title)
print("product_name: " + product_name)
print("shipping: " + shipping)

f.write( brand + "," +product_name.replace(",", "|") + "," + shipping +
"\n")

f.close()

#Criteria 1
#safety = Warranty, Basic?
#Maintence Cost = Maintence
#Price = Base MSRP

I know I have to change quite a bit but right now I just want it to run without getting errors

runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')
Traceback (most recent call last):

File "", line 1, in
    runfile('C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py', wdir='C:/Users/st.s.mahathirath.ctr/.spyder-py3')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/st.s.mahathirath.ctr/.spyder-py3/temp.py", line 2, in
    from urllib import urlopen as uReq

ImportError: cannot import name 'urlopen'

Body:
Try the following code:

import bs4
from urllib import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://www.caranddriver.com/car-comparison-tool?chromeIDs=404121,402727,403989,403148'

# opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")
containers = page_soup.findAll("div", {
    "class": "w50p "
})

I think you are trying to fetch the car comparisons, IMHO this might not work, since

this won't work in the command line as the site will throw unsupported browser;

IMHO the div is not the element to look for, after comparison of the cars in the site (too many of them). Try the document.getElementsByTagName('cd-view-car-card') in the debugger console to see 4 items (where last item is the "Add Car" item). Inside this cd-view-car-card, there is a single div with 2 children, the second child (div) contains all the relevant information (as per the current site design).

Hope this helps


问:
How to create elements on behalf of an given number?
A normal order has orderlines. A pre order has no orderlines but does tell me how many I could expect te receive. The application that is receiving the orders can handle orders with orderlines. Because we are now also using pre orders I'd like to create the same amount of empty orderlines that's in the pre order so the application can accept the edi.

I've already created a check to see if its a order with orderlines or a pre order.

Example incoming code, in this case 'amount 3' means there should be 3 order lines:

```<code><WarehouseOutboundOrder>
    <Amount>3</Amount>
    <OrderDate>27-05-2019 13:22</OrderDate>
    <CreationReason>E01_NEW_PREORDER</CreationReason>
</WarehouseOutboundOrder>
</code>```

Expected outgoing code:

```<code><WarehouseOutboundOrder>
    <Amount>3</Amount>
    <OrderDate>27-05-2019 13:22</OrderDate>
    <CreationReason>E01_NEW_PREORDER</CreationReason>
    <WarehouseOutboundOrderLine>
        <Quantity></Quantity>
        <Description></Description>
    </WarehouseOutboundOrderLine>
    <WarehouseOutboundOrderLine>
        <Quantity></Quantity>
        <Description></Description>
    </WarehouseOutboundOrderLine>
    <WarehouseOutboundOrderLine>
        <Quantity></Quantity>
        <Description></Description>
    </WarehouseOutboundOrderLine>
</WarehouseOutboundOrder>
</code>```

How can I achieve this using xslt?

答:
How about:

XSLT 2.0

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="WarehouseOutboundOrder">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <xsl:for-each select="1 to Amount">
            <WarehouseOutboundOrderLine>
                <Quantity/>
                <Description/>
            </WarehouseOutboundOrderLine>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Demo: https://xsltfiddle.liberty-development.net/gWvjQfM

Body:
A normal order has orderlines. A pre order has no orderlines but does tell me how many I could expect te receive. The application that is receiving the orders can handle orders with orderlines. Because we are now also using pre orders I'd like to create the same amount of empty orderlines that's in the pre order so the application can accept the edi.

I've already created a check to see if its a order with orderlines or a pre order.

Example incoming code, in this case 'amount 3' means there should be 3 order lines:

<WarehouseOutboundOrder>
    <Amount>3</Amount>
    <OrderDate>27-05-2019 13:22</OrderDate>
    <CreationReason>E01_NEW_PREORDER</CreationReason>
</WarehouseOutboundOrder>

Expected outgoing code:

<WarehouseOutboundOrder>
    <Amount>3</Amount>
    <OrderDate>27-05-2019 13:22</OrderDate>
    <CreationReason>E01_NEW_PREORDER</CreationReason>
    <WarehouseOutboundOrderLine>
        <Quantity></Quantity>
        <Description></Description>
    </WarehouseOutboundOrderLine>
    <WarehouseOutboundOrderLine>
        <Quantity></Quantity>
        <Description></Description>
    </WarehouseOutboundOrderLine>
    <WarehouseOutboundOrderLine>
        <Quantity></Quantity>
        <Description></Description>
    </WarehouseOutboundOrderLine>
</WarehouseOutboundOrder>

How can I achieve this using xslt?

Body:
How about:

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="WarehouseOutboundOrder">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <xsl:for-each select="1 to Amount">
            <WarehouseOutboundOrderLine>
                <Quantity/>
                <Description/>
            </WarehouseOutboundOrderLine>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Demo: https://xsltfiddle.liberty-development.net/gWvjQfM


问:
Error in building opencv with ffmpeg
I installed ffmpeg according to this article. ffmpeg installation was ok.
Now I build opencv with ffmpeg support and I have some errors.
The errors are

```<code>/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1484:21: error: ‘CODEC_FLAG_GLOBAL_HEADER’ was not declared in this scope
         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
                     ^
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In function ‘int icv_av_write_frame_FFMPEG(AVFormatContext*, AVStream*, uint8_t*, uint32_t, AVFrame*)’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1512:30: error: ‘AVFMT_RAWPICTURE’ was not declared in this scope
     if (oc->oformat->flags & AVFMT_RAWPICTURE) {
                              ^
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In member function ‘void CvVideoWriter_FFMPEG::close()’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1686:35: error: ‘AVFMT_RAWPICTURE’ was not declared in this scope
         if( (oc->oformat->flags & AVFMT_RAWPICTURE) == 0 )
                                   ^
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In member function ‘bool CvVideoWriter_FFMPEG::open(const char*, int, double, int, int, bool)’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1920:32: error: ‘AVFMT_RAWPICTURE’ was not declared in this scope
     if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
                                ^
In file included from /home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg.cpp:45:0:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In static member function ‘static AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext*, AVCodecID, int, int, int, double, AVPixelFormat)’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:2214:25: error: ‘CODEC_FLAG_GLOBAL_HEADER’ was not declared in this scope
             c->flags |= CODEC_FLAG_GLOBAL_HEADER;
                         ^
modules/highgui/CMakeFiles/opencv_highgui.dir/build.make:230: recipe for target 'modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_ffmpeg.cpp.o' failed
make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_ffmpeg.cpp.o] Error 1
CMakeFiles/Makefile2:2349: recipe for target 'modules/highgui/CMakeFiles/opencv_highgui.dir/all' failed
</code>```

What could be wrong?

答:
in opencv:0/2.4 there is no modules/videoio directory! to get that old version (2.4.13-r3) to compile with newest media-video/ffmpeg on gentoo (4.1.3) I had to add above changes to modules/highgui/src/cap_ffmpeg_api.hpp with this
patch:

```<code>--- opencv-2.4.13/modules/highgui/src/cap_ffmpeg_api.hpp        2019-05-27 13:28:05.736339890 +0200
+++ opencv-2.4.13-new/modules/highgui/src/cap_ffmpeg_api.hpp    2019-05-27 13:27:48.787198507 +0200
@@ -12,6 +12,10 @@
 #define OPENCV_FFMPEG_API
 #endif

+#define AV_CODEC_FLAG_GLOBAL_HEADER (1 << 22)
+#define CODEC_FLAG_GLOBAL_HEADER
AV_CODEC_FLAG_GLOBAL_HEADER
+#define AVFMT_RAWPICTURE 0x0020
+
 enum
 {
     CV_FFMPEG_CAP_PROP_POS_MSEC=0,
</code>```

(i.e. I created the path and file /etc/portage/patches/media-libs/opencv-2.4.13-r3/old-ffmpeg.patch with that contents.)
in defense to gentoo, I should mention, the new media-libs/opencv:0/3.4.1 is also available, as is the old media-video/ffmpeg-3.4.5, so I could alternatively also play around with masking out versions or file a bug for developers to do that for me...

Title: Error in building opencv with ffmpeg

Body:
I installed ffmpeg according to this article. ffmpeg installation was ok.
Now I build opencv with ffmpeg support and I have some errors.
The errors are

/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1484:21: error: ‘CODEC_FLAG_GLOBAL_HEADER’ was not declared in this scope
         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
                     ^
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In function ‘int icv_av_write_frame_FFMPEG(AVFormatContext*, AVStream*, uint8_t*, uint32_t, AVFrame*)’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1512:30: error: ‘AVFMT_RAWPICTURE’ was not declared in this scope
     if (oc->oformat->flags & AVFMT_RAWPICTURE) {
                              ^
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In member function ‘void CvVideoWriter_FFMPEG::close()’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1686:35: error: ‘AVFMT_RAWPICTURE’ was not declared in this scope
         if( (oc->oformat->flags & AVFMT_RAWPICTURE) == 0 )
                                   ^
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In member function ‘bool CvVideoWriter_FFMPEG::open(const char*, int, double, int, int, bool)’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:1920:32: error: ‘AVFMT_RAWPICTURE’ was not declared in this scope
     if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
                                ^
In file included from /home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg.cpp:45:0:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp: In static member function ‘static AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext*, AVCodecID, int, int, int, double, AVPixelFormat)’:
/home/coie/Softwares/Libraries/opencv-2.4.13.3/modules/highgui/src/cap_ffmpeg_impl.hpp:2214:25: error: ‘CODEC_FLAG_GLOBAL_HEADER’ was not declared in this scope
             c->flags |= CODEC_FLAG_GLOBAL_HEADER;
                         ^
modules/highgui/CMakeFiles/opencv_highgui.dir/build.make:230: recipe for target 'modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_ffmpeg.cpp.o' failed
make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_ffmpeg.cpp.o] Error 1
CMakeFiles/Makefile2:2349: recipe for target 'modules/highgui/CMakeFiles/opencv_highgui.dir/all' failed

What could be wrong?

Body:
in opencv:0/2.4 there is no modules/videoio directory! to get that old version (2.4.13-r3) to compile with newest media-video/ffmpeg on gentoo (4.1.3) I had to add above changes to modules/highgui/src/cap_ffmpeg_api.hpp with this
patch:

--- opencv-2.4.13/modules/highgui/src/cap_ffmpeg_api.hpp        2019-05-27 13:28:05.736339890 +0200
+++ opencv-2.4.13-new/modules/highgui/src/cap_ffmpeg_api.hpp    2019-05-27 13:27:48.787198507 +0200
@@ -12,6 +12,10 @@
 #define OPENCV_FFMPEG_API
 #endif

+#define AV_CODEC_FLAG_GLOBAL_HEADER (1 << 22)
+#define CODEC_FLAG_GLOBAL_HEADER
AV_CODEC_FLAG_GLOBAL_HEADER
+#define AVFMT_RAWPICTURE 0x0020
+
 enum
 {
     CV_FFMPEG_CAP_PROP_POS_MSEC=0,

(i.e. I created the path and file /etc/portage/patches/media-libs/opencv-2.4.13-r3/old-ffmpeg.patch with that contents.)
in defense to gentoo, I should mention, the new media-libs/opencv:0/3.4.1 is also available, as is the old media-video/ffmpeg-3.4.5, so I could alternatively also play around with masking out versions or file a bug for developers to do that for me...


问:
Extract string value of an ENUM in a Typescript Object
I have an Enum:

```<code>export enum DistanceMeasure {
Miles, Kilometers
</code>```

}

To use in a user object:

```<code>export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff
</code>```

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

```<code>      console.log(user.DistanceMeasure);
</code>```

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

```<code>      console.log(user.DistanceMeasure[0]);
</code>```

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

答:
Have a look at String Enum in the Typscript documentation

```<code>enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}
</code>```

And i suggest to look into this so u understand how they work

Body:
I have an Enum:

export enum DistanceMeasure {
Miles, Kilometers

}

To use in a user object:

export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

      console.log(user.DistanceMeasure);

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

      console.log(user.DistanceMeasure[0]);

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

Body:
Have a look at String Enum in the Typscript documentation

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

And i suggest to look into this so u understand how they work


问:
Return series from specific value within pandas df
I am trying to return a series that contains some addition from specific values in a pandas df. Specifically, for the df below. I want to add all the X's with all the Y's. These aren't in any specific order though.

```<code>import pandas as pd

d = ({
    'Item' : ['X','Y','Z','X','Z','Y','Z'],
    'Value' : [10,11,20,21,10,30,31],
     })

df = pd.DataFrame(data=d)

Xs = df.loc[df['Item'] == 'X', 'Value']
Ys = df.loc[df['Item'] == 'Y', 'Value']

Out = Xs + Ys
</code>```

Intended Output:

```<code>21
51
</code>```

答:
I preferred @jezrael answer but I want to share my thought.</p>

```<code>Xs = df.loc[df['Item'] == 'X', 'Value'].tolist()
Ys = df.loc[df['Item'] == 'Y', 'Value'].tolist()

Out = pd.Series(list(map(sum, zip(Xs, Ys))))

print(Out)
</code>```

Body:
I am trying to return a series that contains some addition from specific values in a pandas df. Specifically, for the df below. I want to add all the X's with all the Y's. These aren't in any specific order though.

import pandas as pd

d = ({
    'Item' : ['X','Y','Z','X','Z','Y','Z'],
    'Value' : [10,11,20,21,10,30,31],
     })

df = pd.DataFrame(data=d)

Xs = df.loc[df['Item'] == 'X', 'Value']
Ys = df.loc[df['Item'] == 'Y', 'Value']

Out = Xs + Ys

Intended Output:

21
51

Body:
I preferred @jezrael answer but I want to share my thought.

Xs = df.loc[df['Item'] == 'X', 'Value'].tolist()
Ys = df.loc[df['Item'] == 'Y', 'Value'].tolist()

Out = pd.Series(list(map(sum, zip(Xs, Ys))))

print(Out)


问:
onGetSentenceSuggestions suggestions are always empty
I'm trying to use google's spell checker service for OCR post processing.

I'm running a tutorial downloaded from github:
https://github.com/tutsplus/Android-SpellingCheckerFramework/blob/master/Spellings/app/src/main/java/com/hathy/spellings/SpellingsClient.java#L4

(I also tried other versions and read all posts I could find online on this issue).

No matter what I do the suggestions always return empty.
I see the same behavior both on emulator and on my Samsung phone.

What am I missing? It seems as if the dictionary it is using is empty..

答:
Samsung devices return empty suggestions unfortunately, but there shouldn't be a problem with emulators. I just tested this on the latest Q emulator:

```<code>val tsm = getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE) as TextServicesManager
val spellCheck = tsm.newSpellCheckerSession(null, null, ...listener..., true)
spellCheck.getSentenceSuggestions(arrayOf(TextInfo("hllo")), 3)
</code>```

and got suggestions hello, bolo, hook

Body:
Samsung devices return empty suggestions unfortunately, but there shouldn't be a problem with emulators. I just tested this on the latest Q emulator:

val tsm = getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE) as TextServicesManager
val spellCheck = tsm.newSpellCheckerSession(null, null, ...listener..., true)
spellCheck.getSentenceSuggestions(arrayOf(TextInfo("hllo")), 3)

and got suggestions hello, bolo, hook


问:
ArangoDB - Backup and restore all data
My aim is to create the arango database dump (with all the users and passwords, permissions, databases, collections, roles and so on) and then make a full restore of this data on the other arango server (that was installed from scratch and empty).

I am using the one-node configuration, arangodb version is 3.4.4 [linux].

On origin I make a dump of every database:

```<code>USER=root
PASSWORD=***
for db in $(arangosh --server.username "$USER" --server.password "$PASSWORD" --javascript.execute-string "db._databases().forEach(function(db) { print(db); });")
do
  arangodump --output-directory /tmp/dump/"$db" --overwrite true --server.username "$USER" --server.password "$PASSWORD" --include-system-collections --server.database "$db"
done
</code>```

Then I move the created folders to the empty arangodb server on this server go with:

```<code>arangorestore --input-directory "/tmp/dump/_system/"
arangorestore --input-directory "/tmp/dump/collection/"
arangorestore --input-directory "/tmp/dump/collection2/"
...one by one
</code>```

The result if very far my expectations, I just get the collections in _system database for the root user (no other users, no databases).

What am I doing wrong? How can I make the full backup and restore?

Thanks in advance.

答:
arangorestore needs to be told to which database to restore the data to. This can be achieved by providing the --server.database option in the same way as it can be done for arangodump.
If no value is provided for --server.database it will default to _system, meaning the subsequent invocations of arangorestore will each overwrite the previous data in the _system database.

If the target databases do not exist yet on the backup server, it is possible to create them on the fly using the option --create-database true.
Additionally, to restore system collections, arangorestore needs to be given the option --include-system-collections true.

That means, if your databases are really named "collection" and "collection2", your restore commands should look as follows:

```<code>arangorestore --input-directory "/tmp/dump/_system/" --server.database "_system" --include-system-collections true --create-database true
arangorestore --input-directory "/tmp/dump/collection/" --server.database "collection" --include-system-collections true --create-database true
arangorestore --input-directory "/tmp/dump/collection2/" --server.database "collection2" --include-system-collections true --create-database true
</code>```

Please also note that with ArangoDB 3.5 there is an option --all-databases for both arangodump and arangorestore, which should greatly simplify the backup and restore process.

Title: ArangoDB - Backup and restore all data

Body:
My aim is to create the arango database dump (with all the users and passwords, permissions, databases, collections, roles and so on) and then make a full restore of this data on the other arango server (that was installed from scratch and empty).

I am using the one-node configuration, arangodb version is 3.4.4 [linux].

On origin I make a dump of every database:

USER=root
PASSWORD=***
for db in $(arangosh --server.username "$USER" --server.password "$PASSWORD" --javascript.execute-string "db._databases().forEach(function(db) { print(db); });")
do
  arangodump --output-directory /tmp/dump/"$db" --overwrite true --server.username "$USER" --server.password "$PASSWORD" --include-system-collections --server.database "$db"
done

Then I move the created folders to the empty arangodb server on this server go with:

arangorestore --input-directory "/tmp/dump/_system/"
arangorestore --input-directory "/tmp/dump/collection/"
arangorestore --input-directory "/tmp/dump/collection2/"
...one by one

The result if very far my expectations, I just get the collections in _system database for the root user (no other users, no databases).

What am I doing wrong? How can I make the full backup and restore?

Thanks in advance.

Body:
arangorestore needs to be told to which database to restore the data to. This can be achieved by providing the --server.database option in the same way as it can be done for arangodump.
If no value is provided for --server.database it will default to _system, meaning the subsequent invocations of arangorestore will each overwrite the previous data in the _system database.

If the target databases do not exist yet on the backup server, it is possible to create them on the fly using the option --create-database true.
Additionally, to restore system collections, arangorestore needs to be given the option --include-system-collections true.

That means, if your databases are really named "collection" and "collection2", your restore commands should look as follows:

arangorestore --input-directory "/tmp/dump/_system/" --server.database "_system" --include-system-collections true --create-database true
arangorestore --input-directory "/tmp/dump/collection/" --server.database "collection" --include-system-collections true --create-database true
arangorestore --input-directory "/tmp/dump/collection2/" --server.database "collection2" --include-system-collections true --create-database true

Please also note that with ArangoDB 3.5 there is an option --all-databases for both arangodump and arangorestore, which should greatly simplify the backup and restore process.


问:
Puppeteer: Cannot find element loaded by Javascript
I've been using Puppeteer to scrape some websites, and it works well when the element I need is in the DOM; however I can't get it to work when the element is loaded via Javascript. E.g. please see my code below. More specifically, the page.waitForSelector always triggers a timeout error. I've tried a page.screenshot and the resulting image does show a fully loaded page, which contains this .evTextFont element.

How can I modify this code to successfully retrieve the .evTextFont element?

I've tried both Puppeteer versions 1.11 and 1.17, but am getting the same problem for both

Thanks a lot

Adapted from here

```<code>const puppeteer = require('puppeteer');
const URL = 'https://www.paintbar.com.au/events-1/moments-in-moonlight';

puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }).then(async browser => {
    const page = await browser.newPage();
    await page.setViewport({width: 1200, height: 600})
    await page.goto(URL, {waitUntil: 'networkidle0'});
    await page.waitForSelector('.evTextFont');
    await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});
    // await page.screenshot({ path: './image.jpg', type: 'jpeg' });

    const result = await page.evaluate(() => {
        try {
            var data = [];

            $('.evTextFont').each(function() {
                const title = $(this).text();
                data.push({
                    'title' : title,
                });
            });
            return data;

        } catch(err) {
            console.log(err.toString());
        }
    });

    await browser.close();

    for(var i = 0; i < result.length; i++) {
        console.log('Data: ' + result[i].title);
    }

    process.exit();
}).catch(function(error) {
    console.error(error);
    process.exit();
});
</code>```

答:
It happens because the event you're looking for is shown inside of an iframe element, from another site, so you need to find that iframe first and then do operation on it.

```<code>await page.goto(URL, {waitUntil: 'networkidle0'});

// Looking for the iframe with the event
const frame = (await page.frames()).find(f => f.url().includes("events.wix.com"));

// Then do work as before, but on that frame
await frame.waitForSelector('.evTextFont');
await frame.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});

const result = await frame.evaluate(() => {...})
</code>```

Body:
I've been using Puppeteer to scrape some websites, and it works well when the element I need is in the DOM; however I can't get it to work when the element is loaded via Javascript. E.g. please see my code below. More specifically, the page.waitForSelector always triggers a timeout error. I've tried a page.screenshot and the resulting image does show a fully loaded page, which contains this .evTextFont element.

How can I modify this code to successfully retrieve the .evTextFont element?

I've tried both Puppeteer versions 1.11 and 1.17, but am getting the same problem for both

Thanks a lot

Adapted from here

const puppeteer = require('puppeteer');
const URL = 'https://www.paintbar.com.au/events-1/moments-in-moonlight';

puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }).then(async browser => {
    const page = await browser.newPage();
    await page.setViewport({width: 1200, height: 600})
    await page.goto(URL, {waitUntil: 'networkidle0'});
    await page.waitForSelector('.evTextFont');
    await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});
    // await page.screenshot({ path: './image.jpg', type: 'jpeg' });

    const result = await page.evaluate(() => {
        try {
            var data = [];

            $('.evTextFont').each(function() {
                const title = $(this).text();
                data.push({
                    'title' : title,
                });
            });
            return data;

        } catch(err) {
            console.log(err.toString());
        }
    });

    await browser.close();

    for(var i = 0; i < result.length; i++) {
        console.log('Data: ' + result[i].title);
    }

    process.exit();
}).catch(function(error) {
    console.error(error);
    process.exit();
});

Body:
It happens because the event you're looking for is shown inside of an iframe element, from another site, so you need to find that iframe first and then do operation on it.

await page.goto(URL, {waitUntil: 'networkidle0'});

// Looking for the iframe with the event
const frame = (await page.frames()).find(f => f.url().includes("events.wix.com"));

// Then do work as before, but on that frame
await frame.waitForSelector('.evTextFont');
await frame.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});

const result = await frame.evaluate(() => {...})


问:
How to escape single quote in ARM template
Given the following resource in an AzureRM template, how would one encode the single quote in the commandToExecute part?

{
  "type": "Microsoft.Compute/virtualMachines/extensions",
  "name": "[concat(variables('vmNameMaster'), copyIndex(), '/sethost')]",
  "apiVersion": "2015-06-15",
  "location": "[resourceGroup().location]",
  "copy": {
      "name": "extensionLoopNode",
      "count": "[variables('masterCount')]"
  },
  "dependsOn": [
      "[concat('Microsoft.Compute/virtualMachines/', variables('vmNameMaster'), copyIndex(),'/extensions/DockerExtension')]"
  ],
  "properties": {
    "publisher": "Microsoft.OSTCExtensions",
    "type": "CustomScriptForLinux",
    "typeHandlerVersion": "1.4",
    "settings": {
      "fileUris": [ ],
      "commandToExecute": "[concat('/bin/bash -c \'echo \"export DOCKER_HOST=:2375\" >> /home/', parameters('adminUsername') ,'/.profile\'')]",
      "timestamp": 123456789
    }
  }
},
```

答:
In DevOps release pipeline, for APIM policy, use & quote; to escape quotes within an expression, </p>

```<code><when condition='@(context.Variables.GetValueOrDefault<bool>("isAuthOk"))' />
</code>```

Body:
In DevOps release pipeline, for APIM policy, use & quote; to escape quotes within an expression,

<when condition='@(context.Variables.GetValueOrDefault&lt;bool&gt;(&quot;isAuthOk&quot;))' />


问:
Run-time error '1004': Method 'Range' of object '_Worksheet' failed after saving the file
The code I'm trying to write should simply check the different price book entries in my companies system. It should take a purchase order from the past and check which would have been the cheapest price book entry for a specific minimum order quantety.
Before doing that the code defines a Range PBRange which then should be sorted to work with 'if' clauses afterwards.
When defining the PBRange the error 1004 occurs.

When I save and reopen the file a message pops up that there was a problem found with some content in the file. After asking me to recover it the code doesn't work anymore.
The strange thing is that the code worked perfectly fine in the beginning.

```<code>Public PBRange As Range
Public PO As Worksheet
Public PB As Worksheet

Sub CheapestPrice()

Dim LastRowPO As Long
Dim LastRowPB As Long

Dim i As Long
Dim j As Long

Set PO = Worksheets("Purchase Orders")
Set PB = Worksheets("Price Book")

'!!!Here the error occurs!!!
Set PBRange = PB.Range("A1", Range("A1").End(xlDown).End(xlToRight))
</code>```

The code after is just an if else combination with two for loops to work through the 2 worksheets. This should work perfeclty fine.

I expect a range to sort afterwards with different criteria.

答:
You could try:</p>

```<code>Option Explicit

Public PBRange As Range
Public PO As Worksheet, PB As Worksheet

Sub test()
    Dim LastRowA As Long

    With ThisWorkbook
        Set PO = .Worksheets("Purchase Orders")
        Set PB = .Worksheets("Price Book")
    End With

    With PB
        'Find Sheet PB & Column A last row
        LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row
        'With out using LastRowA variable
        Set PBRange = .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        'Using LastRowA variable
        Set PBRange = .Range("A1:A" & LastRowA)
    End With

End Sub
</code>```

Body:
The code I'm trying to write should simply check the different price book entries in my companies system. It should take a purchase order from the past and check which would have been the cheapest price book entry for a specific minimum order quantety.
Before doing that the code defines a Range PBRange which then should be sorted to work with 'if' clauses afterwards.
When defining the PBRange the error 1004 occurs.

When I save and reopen the file a message pops up that there was a problem found with some content in the file. After asking me to recover it the code doesn't work anymore.
The strange thing is that the code worked perfectly fine in the beginning.

Public PBRange As Range
Public PO As Worksheet
Public PB As Worksheet

Sub CheapestPrice()

Dim LastRowPO As Long
Dim LastRowPB As Long

Dim i As Long
Dim j As Long

Set PO = Worksheets("Purchase Orders")
Set PB = Worksheets("Price Book")

'!!!Here the error occurs!!!
Set PBRange = PB.Range("A1", Range("A1").End(xlDown).End(xlToRight))

The code after is just an if else combination with two for loops to work through the 2 worksheets. This should work perfeclty fine.

I expect a range to sort afterwards with different criteria.

Body:
You could try:

Option Explicit

Public PBRange As Range
Public PO As Worksheet, PB As Worksheet

Sub test()
    Dim LastRowA As Long

    With ThisWorkbook
        Set PO = .Worksheets("Purchase Orders")
        Set PB = .Worksheets("Price Book")
    End With

    With PB
        'Find Sheet PB & Column A last row
        LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row
        'With out using LastRowA variable
        Set PBRange = .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        'Using LastRowA variable
        Set PBRange = .Range("A1:A" & LastRowA)
    End With

End Sub


问:
How to add a custom culture (en-cn) to Azure AppService (WebApp)?
I have a task to add a new custom culture (en-cn). There isn't a problem from coding side and I used CultureAndRegionInfoBuilder for this but I can't create this culture on the Azure AppService, Register method throws an exception and requires extra-permissions.

Have you met something similar?

答:
According to your description, I think you want to make your app globalization and localization via CultureAndRegionInfoBuilder Class in .NET Framework. However, as the figure below, it requires sysglobl.dll which is a system call that can not be used in Azure App Service (WebApp).

The reason is Win32k.sys (User32/GDI32) Restrictions said in Azure Web App sandbox, as below.

To fix it, you can consider to use other solution to support internationalization (i18n) in your ASP.NET website. Please refer to the blog Understanding Globalization and Localization in .NET to realize it.