问:
integrate() gives totally wrong number
integrate() gives horribly wrong answer:

```<code>integrate(function (x) dnorm(x, -5, 0.07), -Inf, Inf, subdivisions = 10000L)
# 2.127372e-23 with absolute error < 3.8e-23
</code>```

The return value should obviously be 1 (normal distrubution integrates to 1), but integrate() returns ridiculously small number, with wrong error reporting, and no warning...

Any ideas?

This seems the default integrate() is horribly buggy... and I just found this by chance! Is there any reliable R package to compute numerical integration?

EDIT: I tried package pracma and I see the same problem! :

```<code>require(pracma)
integral(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
# For infinite domains Gauss integration is applied!
# [1] 0
</code>```

EDIT: Hmm... digging deeper, it seems that he has trouble to find the very narrow domain for the function which is numerically > 0. When I set the limits  to certain (very close to 0, 1) quantiles, it starts to work:

```<code>integral(function (x) dnorm(x, -5, 0.07), qnorm(1e-10, -5, 0.07), qnorm(1 - 1e-10, -5, 0.07))
</code>```

But anyway, this is quite horrible gotcha... wonder if there is any remedy for this.

答:
Expanding a little further on @r2evan's and @Limey's comments:

@Limey: for very general problems like this, there is simply no way to guarantee a generic solution.

One way to solve such problem is to use more knowledge of the properties of the integrand (@r2evans's answer); the answer referenced by @Limey goes into detail for a different problem.

One "gotcha" that you may not have thought of is that trying out a bunch of generic methods, tuning settings, etc. may mislead you into concluding that some settings/methods are generically better than the first one you tried that failed to get the right answer. (Methods that work may work better because they're generically better, but trying them on one example doesn't prove it!)

As an example, the description of pcubature() (in ?cubature::pcubature says

This algorithm is often superior to h-adaptive integration for
       smooth integrands in a few (<=3) dimensions, but is a poor choice
       in higher dimensions or for non-smooth integrands.

However, recall that pcubature() happens to fail for your example, which is a smooth low-dimensional case - exactly where pcubature() is supposed to perform better - which suggests that it may be just luck that hcubature() works and pcubature() doesn't in this case.

An illustration of how sensitive the results can be to parameters (lower/upper limits in this case):

```<code>library(emdbook)
cc <- curve3d(integrate( dnorm, mean=-5, sd=0.07,
        lower=x, upper=y, subdivisions=1000L)$value,
       xlim=c(-30,-10), ylim=c(0,30), n = c(61, 61),
       sys3d="image", col=c("black", "white"),
    xlab="lower", ylab="upper")
</code>```

White squares are successful (integral=1), black squares are bad (integral=0).

Title: integrate() gives totally wrong number

Body:
integrate() gives horribly wrong answer:

integrate(function (x) dnorm(x, -5, 0.07), -Inf, Inf, subdivisions = 10000L)
# 2.127372e-23 with absolute error < 3.8e-23

The return value should obviously be 1 (normal distrubution integrates to 1), but integrate() returns ridiculously small number, with wrong error reporting, and no warning...

Any ideas?

This seems the default integrate() is horribly buggy... and I just found this by chance! Is there any reliable R package to compute numerical integration?

EDIT: I tried package pracma and I see the same problem! :

require(pracma)
integral(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
# For infinite domains Gauss integration is applied!
# [1] 0

EDIT: Hmm... digging deeper, it seems that he has trouble to find the very narrow domain for the function which is numerically > 0. When I set the limits  to certain (very close to 0, 1) quantiles, it starts to work:

integral(function (x) dnorm(x, -5, 0.07), qnorm(1e-10, -5, 0.07), qnorm(1 - 1e-10, -5, 0.07))

But anyway, this is quite horrible gotcha... wonder if there is any remedy for this.

Body:
Expanding a little further on @r2evan's and @Limey's comments:

@Limey: for very general problems like this, there is simply no way to guarantee a generic solution.

One way to solve such problem is to use more knowledge of the properties of the integrand (@r2evans's answer); the answer referenced by @Limey goes into detail for a different problem.

One "gotcha" that you may not have thought of is that trying out a bunch of generic methods, tuning settings, etc. may mislead you into concluding that some settings/methods are generically better than the first one you tried that failed to get the right answer. (Methods that work may work better because they're generically better, but trying them on one example doesn't prove it!)

As an example, the description of pcubature() (in ?cubature::pcubature says

This algorithm is often superior to h-adaptive integration for
       smooth integrands in a few (<=3) dimensions, but is a poor choice
       in higher dimensions or for non-smooth integrands.

However, recall that pcubature() happens to fail for your example, which is a smooth low-dimensional case - exactly where pcubature() is supposed to perform better - which suggests that it may be just luck that hcubature() works and pcubature() doesn't in this case.

An illustration of how sensitive the results can be to parameters (lower/upper limits in this case):

library(emdbook)
cc <- curve3d(integrate( dnorm, mean=-5, sd=0.07,
        lower=x, upper=y, subdivisions=1000L)$value,
       xlim=c(-30,-10), ylim=c(0,30), n = c(61, 61),
       sys3d="image", col=c("black", "white"),
    xlab="lower", ylab="upper")

White squares are successful (integral=1), black squares are bad (integral=0).


来源: stackexchange

问:
How can I compare numbers from a list only with the next number (neighbor)?
All I want to do is to compare the first number from a list with the second number from the same list, the second one with the third one, and so on.

input:

```<code>lst = [1,2,3,2,1]
</code>```

output:

```<code>result = ["Lower", "Lower", "Higher", "Higher"]
</code>```

(1 is lower than 2, 2 is lower than 3, 3 is higher than 2, 2 is higher than 1)

It's kinda ugly (a list comprehension would be great), but my approach for that would be:

```<code>lst = [1,2,3,2,1]
result = []
x = 0

try:
    for i in range(len(lst)):
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
except IndexError:
    print(result)
    print("Out of range")
</code>```

答:
Use zip() to iterate over list:

```<code>lst = [1,2,3,2,1]

out = []
for a, b in zip(lst, lst[1:]):
    out.append('Higher' if a > b else 'Lower')

print(out)
</code>```

Prints:

```<code>['Lower', 'Lower', 'Higher', 'Higher']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
All I want to do is to compare the first number from a list with the second number from the same list, the second one with the third one, and so on.

input:

lst = [1,2,3,2,1]

output:

result = ["Lower", "Lower", "Higher", "Higher"]

(1 is lower than 2, 2 is lower than 3, 3 is higher than 2, 2 is higher than 1)

It's kinda ugly (a list comprehension would be great), but my approach for that would be:

lst = [1,2,3,2,1]
result = []
x = 0

try:
    for i in range(len(lst)):
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
except IndexError:
    print(result)
    print("Out of range")

Body:
Use zip() to iterate over list:

lst = [1,2,3,2,1]

out = []
for a, b in zip(lst, lst[1:]):
    out.append('Higher' if a > b else 'Lower')

print(out)

Prints:

['Lower', 'Lower', 'Higher', 'Higher']


问:
Zend bootstrap, including javascript files for certain pages only
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

```<code>->appendFile('http://myurl.com/js/formscript.js');
</code>```

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

```<code>$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;
</code>```

and this would be in my bootstrap

```<code>if ($view->formscript)
</code>```

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?

答:
Your idea to set a flag - something like $view->hasForm - in your view seems like a pretty reasonable approach. But as others have noted, it shouldn't be the form itself that attempts to set the flag since it doesn't really have access to view object until rendering time.

Instead, wherever you place a form into your view - probably in a controller, perhaps even in a front controller plugin - simply set your flag there.

Then your view script or layout can call $this->headScript()->appendFile() if the flag has been set.

ContentLicense: CC BY-SA 3.0

Body:
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

->appendFile('http://myurl.com/js/formscript.js');

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;

and this would be in my bootstrap

if ($view->formscript)

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?


问:
Remove consecutive duplicates from a list using yield generator?
i'm trying to compress a list using generator:

examples

```<code>[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]
</code>```

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

```<code>test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]

ans = compress(test)
for x in ans:
    print(ans)
</code>```

but i keep getting

generator object compress at 0x00000254D383C820.
why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

答:
One more solution: go through the combination of the list and the same list shifted by one (in other words, by the pairs of consecutive items) and select the second item from each pair where the first (previous) item differs from the second (next) item:

```<code>l = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]
[l[0]] + [y for x,y in zip(l, l[1:]) if x!=y]
#[5, 4, 5, 6, 5, 7, 8, 0]
</code>```

Incidentally, this is one of the fastest solutions presented so far.

Body:
i'm trying to compress a list using generator:

examples

[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]

ans = compress(test)
for x in ans:
    print(ans)

but i keep getting

generator object compress at 0x00000254D383C820.
why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

Body:
One more solution: go through the combination of the list and the same list shifted by one (in other words, by the pairs of consecutive items) and select the second item from each pair where the first (previous) item differs from the second (next) item:

l = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]
[l[0]] + [y for x,y in zip(l, l[1:]) if x!=y]
#[5, 4, 5, 6, 5, 7, 8, 0]

Incidentally, this is one of the fastest solutions presented so far.


问:
Operation returned an invalid status code 'NotFound' Xamarin forms and Azure CustomVision
Whenever var result = await endpoint.ClassifyImageAsync(myProjectID, "Iteration2", photo.GetStream()); is called an error, stating Operation returned an invalid status code 'NotFound' Xamarin forms and Azure CustomVision occurs. I have tried to follow the tutorials on Custom Visions docs and I believe myProjectID, endpoint and prediction key are correct. I am using the using the Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction; package for my code.

Things to note:

When I run my endpoint link in a browser it gives an error 404(has very similar error results to this error, could be correlated?)

I am storing keys and endpoint url in strings not environment variables.

```<code>namespace CustomVisionTesting
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {

        string predictionKey = "2l013000c2355b718ng04aca6a540d5d";

        string ENDPOINT = "https://realcustomvisionservice.cognitiveservices.azure.com/customvision/v3.0/Prediction/7bfir91a-m9vj-mp3k-bk34-jfkbi4jcjs24/detect/iterations/Iteration2/image";

        public MainPage()
        {
            InitializeComponent();
        }

        async void Button_Clicked(System.Object sender, System.EventArgs e)
        {

            var options = new StoreCameraMediaOptions();

            var photo = await CrossMedia.Current.TakePhotoAsync(options);

            CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient()
            {
                ApiKey = predictionKey,
                Endpoint = ENDPOINT

            };

            Guid myProjectID = Guid.Parse("7bfir91a-m9vj-mp3k-bk34-jfkbi4jcjs24");

            var result = await endpoint.ClassifyImageAsync(myProjectID, "Iteration2", photo.GetStream());

        }

    }
</code>```

答:
Your endpoint value is incorrect: as you are using the package, you have to pass the "root" endpoint which is valid for all Custom vision prediction operations.
The endpoint that you provided is the full endpoint to do a "Detect" operation.

In you case, replace the following

```<code>string ENDPOINT = "https://realcustomvisionservice.cognitiveservices.azure.com/customvision/v3.0/Prediction/7bfir91a-m9vj-mp3k-bk34-jfkbi4jcjs24/detect/iterations/Iteration2/image";
</code>```

by

```<code>string ENDPOINT = "https://realcustomvisionservice.cognitiveservices.azure.com";
</code>```

It is the package that you are using which is in charge to append additional url details

Body:
Whenever var result = await endpoint.ClassifyImageAsync(myProjectID, "Iteration2", photo.GetStream()); is called an error, stating Operation returned an invalid status code 'NotFound' Xamarin forms and Azure CustomVision occurs. I have tried to follow the tutorials on Custom Visions docs and I believe myProjectID, endpoint and prediction key are correct. I am using the using the Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction; package for my code.

Things to note:

When I run my endpoint link in a browser it gives an error 404(has very similar error results to this error, could be correlated?)

I am storing keys and endpoint url in strings not environment variables.

namespace CustomVisionTesting
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {

        string predictionKey = "2l013000c2355b718ng04aca6a540d5d";

        string ENDPOINT = "https://realcustomvisionservice.cognitiveservices.azure.com/customvision/v3.0/Prediction/7bfir91a-m9vj-mp3k-bk34-jfkbi4jcjs24/detect/iterations/Iteration2/image";

        public MainPage()
        {
            InitializeComponent();
        }

        async void Button_Clicked(System.Object sender, System.EventArgs e)
        {

            var options = new StoreCameraMediaOptions();

            var photo = await CrossMedia.Current.TakePhotoAsync(options);

            CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient()
            {
                ApiKey = predictionKey,
                Endpoint = ENDPOINT

            };

            Guid myProjectID = Guid.Parse("7bfir91a-m9vj-mp3k-bk34-jfkbi4jcjs24");

            var result = await endpoint.ClassifyImageAsync(myProjectID, "Iteration2", photo.GetStream());

        }

    }

Body:
Your endpoint value is incorrect: as you are using the package, you have to pass the "root" endpoint which is valid for all Custom vision prediction operations.
The endpoint that you provided is the full endpoint to do a "Detect" operation.

In you case, replace the following

string ENDPOINT = "https://realcustomvisionservice.cognitiveservices.azure.com/customvision/v3.0/Prediction/7bfir91a-m9vj-mp3k-bk34-jfkbi4jcjs24/detect/iterations/Iteration2/image";

by

string ENDPOINT = "https://realcustomvisionservice.cognitiveservices.azure.com";

It is the package that you are using which is in charge to append additional url details


问:
Python Perfect Numbers
So I am supposed to write a Python program that will identify and print all the perfect numbers in some closed interval [ 2, n ], one per line. We only have to use nested while loops/ if-else statements. I did it somehow using a for loop, but can't figure out the same using a while loop. I'd appreciate your help if you could show me how to translate my code into a while loop. Thanks guys. Here's what I have:</p>

```<code>limit = int(input("enter upper limit for perfect number search: "))

for n in range(2, limit + 1):
    sum = 0
    for divisor in range(1, n):
        if not n % divisor:
            sum += divisor
        if sum == n:
            print(n, "is a perfect number")
</code>```

答:
I am sharing this codes for alternative. Perfect number is of the form  [2^{n-1}(2^{n}-1)] where 2^{n}-1 and n both are prime numbers.</p>

```<code>for num in range(2,101):
if all(num%i!=0 for i in range(2,num)):
    num_2=num*2-1
    for num_2 in range(2,101):
        if all(num_2%i!=0 for i in range(2,num_2)):
            MükemmelSayı=2**(num-1)*(2**num-1)
            print(MükemmelSayı)
            break
        break
</code>```

Title: Python Perfect Numbers

Body:
So I am supposed to write a Python program that will identify and print all the perfect numbers in some closed interval [ 2, n ], one per line. We only have to use nested while loops/ if-else statements. I did it somehow using a for loop, but can't figure out the same using a while loop. I'd appreciate your help if you could show me how to translate my code into a while loop. Thanks guys. Here's what I have:

limit = int(input("enter upper limit for perfect number search: "))

for n in range(2, limit + 1):
    sum = 0
    for divisor in range(1, n):
        if not n % divisor:
            sum += divisor
        if sum == n:
            print(n, "is a perfect number")

Body:
I am sharing this codes for alternative. Perfect number is of the form  [2^{n-1}(2^{n}-1)] where 2^{n}-1 and n both are prime numbers.

for num in range(2,101):
if all(num%i!=0 for i in range(2,num)):
    num_2=num*2-1
    for num_2 in range(2,101):
        if all(num_2%i!=0 for i in range(2,num_2)):
            MükemmelSayı=2**(num-1)*(2**num-1)
            print(MükemmelSayı)
            break
        break


答:
Here it is as a list comprehension</p>

```<code>['Higher' if lst[i] > lst[i + 1] else 'Lower' for i in range(len(lst) - 1)]
</code>```

Title: How can I compare numbers from a list only with the next number (neighbor)?

Body:
Here it is as a list comprehension

['Higher' if lst[i] > lst[i + 1] else 'Lower' for i in range(len(lst) - 1)]


问:
how to load user data into an input?
I'm trying to get the data of the logged in user to be loaded into the entries, but I don't know how to do that. Do I have to use something similar like innerText?

code HTML:

```<code><form>
        <h2 align="center">Setting</h2>
        <div class="form-group row">
            <label for="uidInput" class="col-sm-1 col-form-label">Uid</label>
            <div class="col-sm-4">
                <input type="text" class="form-control teste" id="uidInput" placeholder="uidInput">
            </div>
            <label for="emailInput" class="col-sm-1 col-form-label">Email</label>
            <div class="col-sm-4">
                <input type="email" class="form-control" id="emailInput">
            </div>
        </div>
        <div class="form-group row">
            <label for="nameInput" class="col-sm-1 col-form-label">Name</label>
            <div class="col-sm-4">
                <input type="text" class="form-control" id="nameInput">
            </div>
            <label for="passwordInput" class="col-sm-1 col-form-label">Password</label>
            <div class="col-sm-4">
                <input type="password" class="form-control" id="passwordInput">
            </div>
        </div>
        <div class="form-group row">
            <label for="surnameInput" class="col-sm-1 col-form-label">Surname</label>
            <div class="col-sm-4">
                <input type="text" class="form-control" id="surnameInput">
            </div>
        </div>
        <div class="form-group row">
            <label for="numberInput" class="col-sm-1 col-form-label">document number</label>
            <div class="col-sm-4">
                <input type="text" class="form-control" id="numberInput">
            </div>
        </div>
    </form>
</code>```

code js:

```<code>firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
    var name = snapshot.val().name;
    var surname = snapshot.val().surname;
    var documentNumber = snapshot.val().documentNumber;
    var email = snapshot.val().email;
    var password = snapshot.val().password;
</code>```

答:
If you want to show the values you read from the database into the HTML, you can indeed set the inner text of the elements with something like:</p>

```<code>firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
    var name = snapshot.val().name;
    var surname = snapshot.val().surname;
    var documentNumber = snapshot.val().documentNumber;
    var email = snapshot.val().email;
    var password = snapshot.val().password;

    document.querySelection('#emailInput').textContent = email;
    document.querySelection('#nameInput').textContent = name;
    document.querySelection('#passwordInput').textContent = password;
    document.querySelection('#surnameInput').textContent = surname;
    document.querySelection('#numberInput').textContent = documentNumber;
})
</code>```

Title: how to load user data into an input?

Body:
I'm trying to get the data of the logged in user to be loaded into the entries, but I don't know how to do that. Do I have to use something similar like innerText?

code HTML:

<form>

Setting

            Uid

                <input type="text" class="form-control teste" id="uidInput" placeholder="uidInput">

            Email

                <input type="email" class="form-control" id="emailInput">

            Name

                <input type="text" class="form-control" id="nameInput">

            Password

                <input type="password" class="form-control" id="passwordInput">

            Surname

                <input type="text" class="form-control" id="surnameInput">

            document number

                <input type="text" class="form-control" id="numberInput">

    </form>

code js:

firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
    var name = snapshot.val().name;
    var surname = snapshot.val().surname;
    var documentNumber = snapshot.val().documentNumber;
    var email = snapshot.val().email;
    var password = snapshot.val().password;

Body:
If you want to show the values you read from the database into the HTML, you can indeed set the inner text of the elements with something like:

firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
    var name = snapshot.val().name;
    var surname = snapshot.val().surname;
    var documentNumber = snapshot.val().documentNumber;
    var email = snapshot.val().email;
    var password = snapshot.val().password;

    document.querySelection('#emailInput').textContent = email;
    document.querySelection('#nameInput').textContent = name;
    document.querySelection('#passwordInput').textContent = password;
    document.querySelection('#surnameInput').textContent = surname;
    document.querySelection('#numberInput').textContent = documentNumber;
})


问:
Advice on Web Service or related technology
I am developing a system that must be able to receive an XML  messages (preferably without SOAP envelope) from other's company external system through the internet. I am not sure what technology is external system written in.
The developers from the external company must create a XML sending feature. I would like to minimazie their effort.
Is WCF good choice for that?

The OS will be either Windows XP with IIS 5.1 or Windows Server 2003 with IIS 6.0.
.NET Framework is 3.5.

Thanks.

答:
WCF is a very high level of abstraction in terms of implementing services over HTTP (and even other protocols like TCP). There are two options in your case

WCF REST service : As you are expecting custom XML to be passed around in HTML payload. this can be a option but only in case you can visualize the service as resource oriented.

Custom HTTP handlers : These are very low level in the whole abstraction stack of various components of ASP.NET. Which allows much more flexibility in implementing custom XML passing over HTTP but would require much more code as compared to WCF


问:
SwiftUI and FetchRequest : delay the reordering of a list
I have written an application displaying a list of students. I use a List of NavigationLink for that purpose. The students are ordered by one of their properties questionAskedClass which is an integer. All this information is stored within CoreData.

```<code>@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Student.entity(),
    sortDescriptors: [NSSortDescriptor(keyPath: \Student.questionAskedClass,
                                       ascending: true)])
var students: FetchedResults<Student>

var body: some View {
  NavigationView {
    List {
      ForEach(students) {student in
        NavigationLink(destination: StudentView(student: student)) {
          HStack {
            VStack(alignment: .leading) {
              Text("\(student.firstName)").font(.headline).foregroundColor(Color.black)
              Text("\(student.lastName)").font(.headline).foregroundColor(Color.gray)
            }
          }
        }
      }
    }
  }
}
</code>```

When I press the name of the students, I switch to a new view called StudentView where I can get more information about the student and where I can update the property questionAskedClass

```<code>struct StudentView: View {
  @Environment(\.managedObjectContext) var managedObjectContext

  func askQuestion() {
    self.managedObjectContext.performAndWait {
      self.student.questionAskedClass += 1
      try? self.managedObjectContext.save()
    }
  }
}
</code>```

Unfortunately, when I change that property, the ordering of the initial list is changed and I am taken away from the StudentView. The framework seems to get the feeling that the list needs to be reordered. But I just want this list to be reordered when I go back to the list. Not immediately when I change the value of questionAskedClass.

What can I do to mitigate this problem?

Thanks for your help.

答:
You can try creating a simple NSFetchRequest<Student> and use the result of this fetch to update your students list.

```<code>@State var students: [Student] = []

fun refresh() {
    let fetchRequest = NSFetchRequest<Student>(entityName: "Student")
    students = try? managedObjectContext.fetch(fetchRequest) ?? []
}
</code>```

You can trigger this refresh in onAppear so the list will be updated every time the View appears:

```<code>NavigationView {
    ...
}.onAppear {
    self.refresh()
}
</code>```

Alternatively you can save your context in onAppear of the main view instead of StudentView:

```<code>struct StudentView: View {
    func askQuestion() {
        self.student.questionAskedClass += 1
    }
}

NavigationView {
    ...
}.onAppear {
    try? self.managedObjectContext.save()
}
</code>```

If you want your data to persist when the app is terminated, add this function in AppDelegate (assuming your persistentContainer is declared there:

```<code>func applicationWillTerminate(_ application: UIApplication) {
    try? persistentContainer.viewContext.save()
}
</code>```

Body:
I have written an application displaying a list of students. I use a List of NavigationLink for that purpose. The students are ordered by one of their properties questionAskedClass which is an integer. All this information is stored within CoreData.

@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Student.entity(),
    sortDescriptors: [NSSortDescriptor(keyPath: \Student.questionAskedClass,
                                       ascending: true)])
var students: FetchedResults<Student>

var body: some View {
  NavigationView {
    List {
      ForEach(students) {student in
        NavigationLink(destination: StudentView(student: student)) {
          HStack {
            VStack(alignment: .leading) {
              Text("\(student.firstName)").font(.headline).foregroundColor(Color.black)
              Text("\(student.lastName)").font(.headline).foregroundColor(Color.gray)
            }
          }
        }
      }
    }
  }
}

When I press the name of the students, I switch to a new view called StudentView where I can get more information about the student and where I can update the property questionAskedClass

struct StudentView: View {
  @Environment(\.managedObjectContext) var managedObjectContext

  func askQuestion() {
    self.managedObjectContext.performAndWait {
      self.student.questionAskedClass += 1
      try? self.managedObjectContext.save()
    }
  }
}

Unfortunately, when I change that property, the ordering of the initial list is changed and I am taken away from the StudentView. The framework seems to get the feeling that the list needs to be reordered. But I just want this list to be reordered when I go back to the list. Not immediately when I change the value of questionAskedClass.

What can I do to mitigate this problem?

Thanks for your help.

Body:
You can try creating a simple NSFetchRequest<Student> and use the result of this fetch to update your students list.

@State var students: [Student] = []

fun refresh() {
    let fetchRequest = NSFetchRequest<Student>(entityName: "Student")
    students = try? managedObjectContext.fetch(fetchRequest) ?? []
}

You can trigger this refresh in onAppear so the list will be updated every time the View appears:

NavigationView {
    ...
}.onAppear {
    self.refresh()
}

Alternatively you can save your context in onAppear of the main view instead of StudentView:

struct StudentView: View {
    func askQuestion() {
        self.student.questionAskedClass += 1
    }
}

NavigationView {
    ...
}.onAppear {
    try? self.managedObjectContext.save()
}

If you want your data to persist when the app is terminated, add this function in AppDelegate (assuming your persistentContainer is declared there:

func applicationWillTerminate(_ application: UIApplication) {
    try? persistentContainer.viewContext.save()
}


问:
cURL error 60: SSL certificate problem: certificate has expired
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

```<code>cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1
</code>```

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.
</code>```

My curl code -

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
</code>```

答:
A permanent solution would be to reissue the SSL certificate from your provider and reinstall it on your server.

The reissued certificate would update the CA bundle.

Cheers!

Body:
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.

My curl code -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);


问:
Terraform 403 Forbidden Error while executing terraform plan
We are currently using S3 as our backend for preserving the tf state file. While executing terraform plan we are receiving the below error:

Error: Forbidden: Forbidden
        status code: 403, request id: 18CB0EA827E6FE0F, host id: 8p0TMjzvooEBPNakoRsO3RtbARk01KY1KK3z93Lwyvh1Nx6sw4PpRyfoqNKyG2ryMNAHsdCJ39E=
```

<p>We have enabled the debug mode and below is the error message we have noticed.</p>

<pre class="lang-sh prettyprint-override"><code>2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: Accept-Encoding: gzip
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: -----------------------------------------------------
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalRefresh, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalSequence, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [TRACE] [walkRefresh] Exiting eval tree: aws_s3_bucket_object.xxxxxx
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx: dynamic subgraph encountered errors
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete
</code>```

We have tried reverting the code and tfstate file to a working version and tried. Also, deleted the tfstate file locally as well. Still the same error.

s3 bucket policy is as below:

{
            "Sid": "DelegateS3Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxxxxx:role/Administrator"
            },
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectTagging"
            ],
            "Resource": [
                "arn:aws:s3:::xxxxxx/*",
                "arn:aws:s3:::xxxxxx"
            ]
        }
```

The same role is being assumed by terraform for execution and still it fails. I have emptied the bucket policy as well and tried but didn't see any success. I understand it is something to do with the bucket policy itself, but not sure how to fix it.

Any pointers to fix this issue is highly appreciated.

答:
The issue is fixed now. We have performed a s3 copy action prior to this which had copied all the s3 objects from account A to account B. The issue here is copy command always moves objects along with the same user permissions which made the current user role not able to access these newly copied objects resulting in Forbidden 403 error.

We have cleared all the objects in this bucket and run the aws sync command instead of cp which fixed the issue for us. Thank you Alain for the elaborated explanation. Those surely helped us in fixing this issue.

This helped us point to right issue.

Steps followed:

Backup all the s3 objects.

Empty the bucket.

Run terraform plan.

Once the changes are made to the bucket, run aws sync command.

Body:
We are currently using S3 as our backend for preserving the tf state file. While executing terraform plan we are receiving the below error:

Error: Forbidden: Forbidden
        status code: 403, request id: 18CB0EA827E6FE0F, host id: 8p0TMjzvooEBPNakoRsO3RtbARk01KY1KK3z93Lwyvh1Nx6sw4PpRyfoqNKyG2ryMNAHsdCJ39E=

We have enabled the debug mode and below is the error message we have noticed.

2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: Accept-Encoding: gzip
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4:
2020-05-31T20:02:20.842+0400 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: -----------------------------------------------------
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalRefresh, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [ERROR] <root>: eval: *terraform.EvalSequence, err: Forbidden: Forbidden
        status code: 403, request id: 2AB56118732D7165, host id: 5sM6IwjkufaDg1bt5Swh5vcQD2hd3fSf9UqAtlL4hVzVaGPRQgvs1V8S3e/h3ta0gkRcGI7GvBM=
2020/05/31 20:02:20 [TRACE] [walkRefresh] Exiting eval tree: aws_s3_bucket_object.xxxxxx
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx: dynamic subgraph encountered errors
2020/05/31 20:02:20 [TRACE] vertex "aws_s3_bucket_object.xxxxxx": visit complete

We have tried reverting the code and tfstate file to a working version and tried. Also, deleted the tfstate file locally as well. Still the same error.

s3 bucket policy is as below:

{
            "Sid": "DelegateS3Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxxxxx:role/Administrator"
            },
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectTagging"
            ],
            "Resource": [
                "arn:aws:s3:::xxxxxx/*",
                "arn:aws:s3:::xxxxxx"
            ]
        }

The same role is being assumed by terraform for execution and still it fails. I have emptied the bucket policy as well and tried but didn't see any success. I understand it is something to do with the bucket policy itself, but not sure how to fix it.

Any pointers to fix this issue is highly appreciated.


问:
Add object to start of dictionary
I am making a group chatting app and I have images associated with the users, so whenever they say something, their image is displayed next to it. I wrote the server in python and the client will be an iOS app. I use a dictionary to store all of the message/image pairs. Whenever my iOS app sends a command to the server (msg:<message), the dictionary adds the image and message to the dictionary like so:dictionary[message] = imageName, which is converted to lists then strings to be sent off in a socket. I would like to add the incoming messages to the start of the dictionary, instead of the end. Something like

```<code>#When added to end:
dictionary = {"hello":image3.png}
#new message
dictionary = {"hello":image3.png, "i like py":image1.png}

#When added to start:
dictionary = {"hello":image3.png}
#new message
dictionary = {"i like py":image1.png, "hello":image3.png}
</code>```

Is there any way to add the object to the start of the dictionary?

答:
As others have pointed out, there is no "order" in a dictionary. However, if you are like me and just need a temporary (/ hacky) workaround that works for your purposes. There is a way to do this.

You can iterate the dictionary, and append the item at the beginning of the iteration process. This seemed to work for me.

The relevant part is where new_fields is declared. I am including the rest for context.

userprofile_json = Path(__file__).parents[2] / f"data/seed-data/user-profile.json"

    with open(userprofile_json) as f:
        user_profiles = json.load(f)

    for user_profile in user_profiles:

        new_fields = {
            'user':  user_profile['fields']['username'],
        }
        for k, v in user_profile['fields'].items():
            new_fields[k] = v

        user_profile['fields'] = new_fields

    with open(userprofile_json, 'w') as f:
        json.dump(user_profiles, f, indent=4)

```

Title: Add object to start of dictionary

Body:
I am making a group chatting app and I have images associated with the users, so whenever they say something, their image is displayed next to it. I wrote the server in python and the client will be an iOS app. I use a dictionary to store all of the message/image pairs. Whenever my iOS app sends a command to the server (msg:<message), the dictionary adds the image and message to the dictionary like so:dictionary[message] = imageName, which is converted to lists then strings to be sent off in a socket. I would like to add the incoming messages to the start of the dictionary, instead of the end. Something like

#When added to end:
dictionary = {"hello":image3.png}
#new message
dictionary = {"hello":image3.png, "i like py":image1.png}

#When added to start:
dictionary = {"hello":image3.png}
#new message
dictionary = {"i like py":image1.png, "hello":image3.png}

Is there any way to add the object to the start of the dictionary?


问:
Placing text between question parts in exam class
I'm trying to prepare some exams in LaTeX, and am hoping to be able to have multi-part questions where some of the parts have their own preamble, which I'm having difficulty with.

As an example of how I'd like it to appear (dots just used to indent):

1) Here is some preable for the question that will apply throughout.

...a) Here is the first part of the question.

...Here is some further preamble that will apply for part b and part c.

...b) Here is the second part of the question.

...c) Here it the third part of the question.

...Here is some final preamble for the last part of the question.

...d) Here is the final part of the question.

I'm struggling to find a way to insert the preambles in. Currently I'm having to settle for inserting the preambles into the relevant following parts but this is less than ideal:

```<code>\documentclass{exam}
\begin{document}
\begin{questions}
\question
Here is some preamble for the question that will apply throughout.
\begin{parts}
\part
Here is the first part of the question.
\part
Here is some further preamble that will apply for part b and c. Here is the second part of the question.
\part
Here is the third part of the question.
\part
Here us some final preamble for the last part of the question. Here is the final part of the question.
\end{parts}
\end{questions}
\end{document}
</code>```

I'm hoping there might be a way to effectively 'pause' the parts environment and return to the questions environment only - is there?

I do know that I can end parts and restart, manually overriding the starting part, but this feels like a total bodge and I thought there must be a better way.

Many thanks!

答:
You can use the \uplevel macro or the EnvUplevel environment to place instructions between the parts of your question:

```<code>\documentclass{exam}
\begin{document}
\begin{questions}
\question
Here is some preamble for the question that will apply throughout.
\begin{parts}
\part
Here is the first part of the question.

\uplevel{test}

\part
Here is some further preamble that will apply for part b and c. Here is the second part of the question.
\part
Here is the third part of the question.

\begin{EnvUplevel}
test
\end{EnvUplevel}
\part
Here us some final preamble for the last part of the question. Here is the final part of the question.
\end{parts}
\end{questions}
\end{document}
</code>```

Body:
I'm trying to prepare some exams in LaTeX, and am hoping to be able to have multi-part questions where some of the parts have their own preamble, which I'm having difficulty with.

As an example of how I'd like it to appear (dots just used to indent):

1) Here is some preable for the question that will apply throughout.

...a) Here is the first part of the question.

...Here is some further preamble that will apply for part b and part c.

...b) Here is the second part of the question.

...c) Here it the third part of the question.

...Here is some final preamble for the last part of the question.

...d) Here is the final part of the question.

I'm struggling to find a way to insert the preambles in. Currently I'm having to settle for inserting the preambles into the relevant following parts but this is less than ideal:

\documentclass{exam}
\begin{document}
\begin{questions}
\question
Here is some preamble for the question that will apply throughout.
\begin{parts}
\part
Here is the first part of the question.
\part
Here is some further preamble that will apply for part b and c. Here is the second part of the question.
\part
Here is the third part of the question.
\part
Here us some final preamble for the last part of the question. Here is the final part of the question.
\end{parts}
\end{questions}
\end{document}

I'm hoping there might be a way to effectively 'pause' the parts environment and return to the questions environment only - is there?

I do know that I can end parts and restart, manually overriding the starting part, but this feels like a total bodge and I thought there must be a better way.

Many thanks!

Body:
You can use the \uplevel macro or the EnvUplevel environment to place instructions between the parts of your question:

\documentclass{exam}
\begin{document}
\begin{questions}
\question
Here is some preamble for the question that will apply throughout.
\begin{parts}
\part
Here is the first part of the question.

\uplevel{test}

\part
Here is some further preamble that will apply for part b and c. Here is the second part of the question.
\part
Here is the third part of the question.

\begin{EnvUplevel}
test
\end{EnvUplevel}
\part
Here us some final preamble for the last part of the question. Here is the final part of the question.
\end{parts}
\end{questions}
\end{document}


答:
Not a list comprehension, but perhaps more clear for non-pythonians:</p>

```<code>lst = [1,2,3,2,1]
result = []
x = 0

for i in range(len(lst)-1):
  comp_result = "Higher" if lst[i] > lst[i+1] else "Lower"
  result.append(comp_result)

print(result)
</code>```

Body:
All I want to do is to compare the first number from a list with the second number from the same list, the second one with the third one, and so on.

input:

lst = [1,2,3,2,1]

output:

result = ["Lower", "Lower", "Higher", "Higher"]

(1 is lower than 2, 2 is lower than 3, 3 is higher than 2, 2 is higher than 1)

It's kinda ugly (a list comprehension would be great), but my approach for that would be:

lst = [1,2,3,2,1]
result = []
x = 0

try:
    for i in range(len(lst)):
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
except IndexError:
    print(result)
    print("Out of range")

Body:
Not a list comprehension, but perhaps more clear for non-pythonians:

lst = [1,2,3,2,1]
result = []
x = 0

for i in range(len(lst)-1):
  comp_result = "Higher" if lst[i] > lst[i+1] else "Lower"
  result.append(comp_result)

print(result)


问:
Add a suffix to each dataframe in a list?
I have a list that contains several dataframes. I would like to add a suffix to each of the names of the dataframes, so that when I call the function

```<code>list2env()
</code>```

and extract the dataframes their name has the suffix added before.
How can I do that?

Sample Data

```<code>df1 <- as.data.frame(matrix(data = c(1,2,3)))
df2 <- as.data.frame(matrix(data = c(1,2,3)))
lst <- list(df1,df2)
</code>```

答:
If we need to automatically get a named list, use mget with a pattern argument in the ls.  In the below code, we are getting the value of objects with names that start (^) with substring 'df' followed by one or more digits (\\d+) till the end ($) of the string.

```<code>lst1 <- mget(ls(pattern = '^df\\d+$'))
</code>```

Now, if we use list2env on the list created, it would update the same objects in the global environment

```<code>list2env(lapply(lst1, transform, new = V1 + 3), .GlobalEnv)
</code>```

And if we need to create new objects, just change the name of the lst1

```<code>names(lst1) <- paste0(names(lst1), "_2018")
list2env(lapply(lst1, transform, new = V1 + 3), .GlobalEnv)
</code>```

Body:
I have a list that contains several dataframes. I would like to add a suffix to each of the names of the dataframes, so that when I call the function

list2env()

and extract the dataframes their name has the suffix added before.
How can I do that?

Sample Data

df1 <- as.data.frame(matrix(data = c(1,2,3)))
df2 <- as.data.frame(matrix(data = c(1,2,3)))
lst <- list(df1,df2)

Body:
If we need to automatically get a named list, use mget with a pattern argument in the ls.  In the below code, we are getting the value of objects with names that start (^) with substring 'df' followed by one or more digits (\\d+) till the end ($) of the string.

lst1 <- mget(ls(pattern = '^df\\d+$'))

Now, if we use list2env on the list created, it would update the same objects in the global environment

list2env(lapply(lst1, transform, new = V1 + 3), .GlobalEnv)

And if we need to create new objects, just change the name of the lst1

names(lst1) <- paste0(names(lst1), "_2018")
list2env(lapply(lst1, transform, new = V1 + 3), .GlobalEnv)


问:
How to print runs scored by a batsmen in a scoreboard format webelements through CSS selector using Selenium and Java
I want to just print runs scored by all batsman during the cricket match in selenium using CSS selector. All rows have same classname and the runs are in 3rd row so I used CSS selector to select 3rd row only, but I am not able to print runs. Here is my code:</p>

```<code>package SomeBasicAutomationPractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class tableGrid_Practice {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "G:\\AutomationPractice\\src\\drivers\\chromedriver.exe");
        WebDriver driver= new ChromeDriver();
        driver.get("http://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
        Thread.sleep(5000);
        WebElement table=driver.findElement(By.cssSelector("div[class='cb-col cb-col-100 cb-ltst-wgt-hdr']"));

        int count=table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).size();
        System.out.println(count);
        for(int i=0;i<count;i++)
        {
            //table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i);
            System.out.println(table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i));

        }
    }
}
</code>```

答:
To print the print runs scored by all batsman during the first innings within the website https://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017 you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use the following css-selectors based Locator Strategy:

Code Block:

```<code>driver.get("https://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
List<WebElement> runs = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.ng-scope#innings_1>div div div.text-bold:nth-child(3)")));
  for(WebElement run:runs) { System.out.println(run.getText()); }
driver.quit();
</code>```

Console Output:

```<code>R
51
19
32
1
3
1
6
0
1
2
4
</code>```

Alternative using Java 8 stream()

As an alternative you can use Java8 stream() and map() as follows:

Code Block:

```<code>driver.get("https://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.ng-scope#innings_1>div div div.text-bold:nth-child(3)"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));
</code>```

Console Output:

```<code>[R, 51, 19, 32, 1, 3, 1, 6, 0, 1, 2, 4]
</code>```

Reference

You can find a relavant discussion in:

How to extract the dynamic values of the id attributes of the table elements using Selenium and Java

Body:
I want to just print runs scored by all batsman during the cricket match in selenium using CSS selector. All rows have same classname and the runs are in 3rd row so I used CSS selector to select 3rd row only, but I am not able to print runs. Here is my code:

package SomeBasicAutomationPractice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class tableGrid_Practice {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "G:\\AutomationPractice\\src\\drivers\\chromedriver.exe");
        WebDriver driver= new ChromeDriver();
        driver.get("http://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
        Thread.sleep(5000);
        WebElement table=driver.findElement(By.cssSelector("div[class='cb-col cb-col-100 cb-ltst-wgt-hdr']"));

        int count=table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).size();
        System.out.println(count);
        for(int i=0;i<count;i++)
        {
            //table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i);
            System.out.println(table.findElements(By.cssSelector("div[classname='cb-col cb-col-100 cb-scrd-itms'] div:nth-child(3)")).get(i));

        }
    }
}

Body:
To print the print runs scored by all batsman during the first innings within the website https://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017 you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use the following css-selectors based Locator Strategy:

Code Block:

driver.get("https://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
List<WebElement> runs = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.ng-scope#innings_1>div div div.text-bold:nth-child(3)")));
  for(WebElement run:runs) { System.out.println(run.getText()); }
driver.quit();

Console Output:

R
51
19
32
1
3
1
6
0
1
2
4

Alternative using Java 8 stream()

As an alternative you can use Java8 stream() and map() as follows:

Code Block:

driver.get("https://www.cricbuzz.com/live-cricket-scorecard/18970/pak-vs-sl-2nd-t20i-pakistan-v-sri-lanka-in-uae-2017");
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.ng-scope#innings_1>div div div.text-bold:nth-child(3)"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));

Console Output:

[R, 51, 19, 32, 1, 3, 1, 6, 0, 1, 2, 4]

Reference

You can find a relavant discussion in:

How to extract the dynamic values of the id attributes of the table elements using Selenium and Java


问:
Adding legend to a multiple column graph in R
I have been trying desperately to add a legend to a graph I wanted to produce, following many of the answers to previous questions, but have until now been unsuccessful.

Could anybody explain to me what I have to add to the following line of code to get a legend (or possibly also explain why it doesn't generate it automatically (in ELI5 mode - I really could not grasp the aes() argument))? :-)

```<code>ggplot(dfm_hl, aes(stringr::str_wrap(document, 15), group = 1)) +
  geom_point(aes(y = positive), color = "darkred") +
  geom_point(aes(y = negative), color = "steelblue") +
  geom_line(aes(y = positive), color = "darkred") +
  geom_line(aes(y = negative), color = "steelblue") +
  labs(title="Sentiment Across Industries", y="Sentiment (%)", x="Industry") +
  theme(text = element_text(size=8), axis.text.x = element_text(angle = 0, hjust = 0.5))
</code>```

Dataframe in question 1
Output I have been getting2

答:
hey bud Run everything in the console and you should be able to use:</p>

```<code>legend(x = 0, y = -1, legend = c("item1", "item2"), col = c("black", "red"),
       pch = c(1, 16))
</code>```

Body:
I have been trying desperately to add a legend to a graph I wanted to produce, following many of the answers to previous questions, but have until now been unsuccessful.

Could anybody explain to me what I have to add to the following line of code to get a legend (or possibly also explain why it doesn't generate it automatically (in ELI5 mode - I really could not grasp the aes() argument))? :-)

ggplot(dfm_hl, aes(stringr::str_wrap(document, 15), group = 1)) +
  geom_point(aes(y = positive), color = "darkred") +
  geom_point(aes(y = negative), color = "steelblue") +
  geom_line(aes(y = positive), color = "darkred") +
  geom_line(aes(y = negative), color = "steelblue") +
  labs(title="Sentiment Across Industries", y="Sentiment (%)", x="Industry") +
  theme(text = element_text(size=8), axis.text.x = element_text(angle = 0, hjust = 0.5))

Dataframe in question 1
Output I have been getting2

Body:
hey bud Run everything in the console and you should be able to use:

legend(x = 0, y = -1, legend = c("item1", "item2"), col = c("black", "red"),
       pch = c(1, 16))


问:
How to publish correctly on github?
I'm having problem publishing my web project on github even after I have set to master branch in settings that allows to be published, got a green tick, yet its shows 404.
Image of my github repository or go to https://github.com/harnystiles/Website

The asset folder takes in all my css, js, font etc

答: Rename your Index.html to index.html and that should fix the problem.</p>

Title: How to publish correctly on github?


问:
problems with asynchronous data recording
there is a function code:

```<code>function fillingDataInCategory(categories, url) {
  let categoriesData = [];
  for (let i = 0; i < categories.length; i++) {
    conn.query(`SELECT product_id
                FROM products
                WHERE product_category_id = ${categories[i].id}`, (err, productInCategory) => {
      if(err) {
        console.log(err);
        fs.writeFileSync('api-reports-error-log.txt',
          `${fs.readFileSync('api-reports-error-log.txt')}\n${url}: ${err} ${new Date().toLocaleDateString()}`);
      } else {
        console.log(productInCategory);
        categoriesData.push({category: categories[i].id, productInCategory: productInCategory.length});
      }
    });
  }
}
</code>```

The problem is that an empty categoriesData array is returned due to asynchronous writing.
I haven't worked with asynchrony much, so I'll be happy to get any help.

答:
I don't see a return at the end of your function, but I assume you want to return categoryData

I think that you are currently calling your function like this:

```<code>  function myFunc() {
    // Do stuff
    let categoriesData = fillingDataInCategory(categories, "myurl");
    console.log(categoriesData);
    // Do stuff
  }
</code>```

First of all, I advise you to use forEach instead of for();

I suggest you to use a promise. And as you do multiple query in one function, use Promise.all

If the library you use to make your mysql calls allows it, use promises directly, but if it only allows you to make callbacks, convert that callback to a promise like this:

```<code>
function makeRequest(categorie) {
    return new Promise((resolve, reject) => {
       conn.query(`SELECT product_id FROM products WHERE product_category_id = ${categorie.id}`, (err, productInCategory) => {
            if (err) {
                reject(err) //reject at error
            } else {
                resolve({category: categorie.id, productInCategory: productInCategory /* You can put your .length here */}); //resolve with your result
            }
       });
    });
}
</code>```

Here are the code that i wrote for you. I simulate your call do conn.query() with a delay of 1 sec

```<code>const fs = require('fs');

/* SIMULATE conn.query async call */

let conn = {
    query: (text, callback) => {
        setTimeout(callback(null, [1, 2, 3, 4] /* Return an fake array of result of length 4 */), 1000);
    }
}

function makeRequest(categorie) {
    return new Promise((resolve, reject) => {
       conn.query(`SELECT product_id FROM products WHERE product_category_id = ${categorie.id}`, (err, productInCategory) => {
            if (err) {
                reject(err) //reject at error
            } else {
                resolve({category: categorie.id, productInCategory: productInCategory.length}); //resolve with your result
            }
       });
    });
}

function fillingDataInCategory(categories, url) {
    return new Promise((resolve, reject) => {
        let promiseList = [] //Make a array to fill with pending promise
        categories.forEach((categorie) => {
            promiseList.push(makeRequest(categorie)); // Adding a new pending request with the categorie inside the array
        })
        resolve(Promise.all(promiseList)); // Promise.all return a promise that take a list of pending promise
    });
}

function myFunc() {
    fillingDataInCategory([{id: 1}, {id: 2}, {id: 3}], "myurl").then((categorieData) => {
        console.log(categorieData); //Now you get the resolve of the Promise.all
        //Do your post work
    }).catch((err) => { // If one of all the requests of the Promise.all array throw an error, then all requests fails
        //Do error stuffs
    });
    // Do stuff
}

myFunc();
</code>```

and i get this :

```<code>➜  node test-stackoverflow.js
[
  { category: 1, productInCategory: 4 },
  { category: 2, productInCategory: 4 },
  { category: 3, productInCategory: 4 }
]
</code>```

Body:
there is a function code:

function fillingDataInCategory(categories, url) {
  let categoriesData = [];
  for (let i = 0; i < categories.length; i++) {
    conn.query(`SELECT product_id
                FROM products
                WHERE product_category_id = ${categories[i].id}`, (err, productInCategory) => {
      if(err) {
        console.log(err);
        fs.writeFileSync('api-reports-error-log.txt',
          `${fs.readFileSync('api-reports-error-log.txt')}\n${url}: ${err} ${new Date().toLocaleDateString()}`);
      } else {
        console.log(productInCategory);
        categoriesData.push({category: categories[i].id, productInCategory: productInCategory.length});
      }
    });
  }
}

The problem is that an empty categoriesData array is returned due to asynchronous writing.
I haven't worked with asynchrony much, so I'll be happy to get any help.

Body:
I don't see a return at the end of your function, but I assume you want to return categoryData

I think that you are currently calling your function like this:

  function myFunc() {
    // Do stuff
    let categoriesData = fillingDataInCategory(categories, "myurl");
    console.log(categoriesData);
    // Do stuff
  }

First of all, I advise you to use forEach instead of for();

I suggest you to use a promise. And as you do multiple query in one function, use Promise.all

If the library you use to make your mysql calls allows it, use promises directly, but if it only allows you to make callbacks, convert that callback to a promise like this:

function makeRequest(categorie) {
    return new Promise((resolve, reject) => {
       conn.query(`SELECT product_id FROM products WHERE product_category_id = ${categorie.id}`, (err, productInCategory) => {
            if (err) {
                reject(err) //reject at error
            } else {
                resolve({category: categorie.id, productInCategory: productInCategory /* You can put your .length here */}); //resolve with your result
            }
       });
    });
}

Here are the code that i wrote for you. I simulate your call do conn.query() with a delay of 1 sec

const fs = require('fs');

/* SIMULATE conn.query async call */

let conn = {
    query: (text, callback) => {
        setTimeout(callback(null, [1, 2, 3, 4] /* Return an fake array of result of length 4 */), 1000);
    }
}

function makeRequest(categorie) {
    return new Promise((resolve, reject) => {
       conn.query(`SELECT product_id FROM products WHERE product_category_id = ${categorie.id}`, (err, productInCategory) => {
            if (err) {
                reject(err) //reject at error
            } else {
                resolve({category: categorie.id, productInCategory: productInCategory.length}); //resolve with your result
            }
       });
    });
}

function fillingDataInCategory(categories, url) {
    return new Promise((resolve, reject) => {
        let promiseList = [] //Make a array to fill with pending promise
        categories.forEach((categorie) => {
            promiseList.push(makeRequest(categorie)); // Adding a new pending request with the categorie inside the array
        })
        resolve(Promise.all(promiseList)); // Promise.all return a promise that take a list of pending promise
    });
}

function myFunc() {
    fillingDataInCategory([{id: 1}, {id: 2}, {id: 3}], "myurl").then((categorieData) => {
        console.log(categorieData); //Now you get the resolve of the Promise.all
        //Do your post work
    }).catch((err) => { // If one of all the requests of the Promise.all array throw an error, then all requests fails
        //Do error stuffs
    });
    // Do stuff
}

myFunc();

and i get this :

➜  node test-stackoverflow.js
[
  { category: 1, productInCategory: 4 },
  { category: 2, productInCategory: 4 },
  { category: 3, productInCategory: 4 }
]


问:
Python variable's value doesn't get changed outside the function
I'm working on a school project. I made a test version of my program, because I'm new to Python and I only have experience with C#, so I'm still learning te basics. My problem is the following:
Before the function "Fill_Array()" I declared a variable (" max_element_var") that is supposed to store the max number of elements that can be stored in the array ("content_array"). Later in the function I change it's value to the input of the console, which happens, and the function runs as it should, the only problem being is that outside the function the value of " max_element_var" stays "None". What should I do in order to fix this?</p>

```<code>#__Test__#
def Test():
    class Que:
        def __init__(self, content, max_element ,actual_elements):
            self.content = content
            self.max_element = max_element
            self.actual_elements = actual_elements

    max_element_var = None
    content_array = []
    def Fill_array():
        print("What should be the max number of elements that can be stored in the array? (Type in an integer!)")
        max_element_var = int(input())
        if(max_element_var>0):
             import random
             random_var = random.randrange(0,max_element_var)
             for x in range(max_element_var-random_var):
                 content_array.append(x)
        else:
            print("It has to be more than 0!")
            Fill_array()
    Fill_array()

    actual_elements_var = len(content_array)

    que = Que (content_array, max_element_var, actual_elements_var)

    print("Content: ", que.content)
    print("Max number of elements: ", que.max_element)
    print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
    print("Which version should be used? (Type in the number!)")
    print("1 - Test")
    print("2 - Full")
    answer = int(input())
    if(answer == 1):
        Test()
        Version_selector()
    elif(answer == 2):
        Full()
        Version_selector()
#__Version_selector__#
Version_selector()
</code>```

答:
In python variables are automatically created as local, in the scope of the function which used them alone.
To solve your problem you may either
(1) return the variable, passing it from one function the other explicitly.
(2) declare it as global so all functions have access to it.

More about scopes here and here.

Body:
I'm working on a school project. I made a test version of my program, because I'm new to Python and I only have experience with C#, so I'm still learning te basics. My problem is the following:
Before the function "Fill_Array()" I declared a variable (" max_element_var") that is supposed to store the max number of elements that can be stored in the array ("content_array"). Later in the function I change it's value to the input of the console, which happens, and the function runs as it should, the only problem being is that outside the function the value of " max_element_var" stays "None". What should I do in order to fix this?

#__Test__#
def Test():
    class Que:
        def __init__(self, content, max_element ,actual_elements):
            self.content = content
            self.max_element = max_element
            self.actual_elements = actual_elements

    max_element_var = None
    content_array = []
    def Fill_array():
        print("What should be the max number of elements that can be stored in the array? (Type in an integer!)")
        max_element_var = int(input())
        if(max_element_var>0):
             import random
             random_var = random.randrange(0,max_element_var)
             for x in range(max_element_var-random_var):
                 content_array.append(x)
        else:
            print("It has to be more than 0!")
            Fill_array()
    Fill_array()

    actual_elements_var = len(content_array)

    que = Que (content_array, max_element_var, actual_elements_var)

    print("Content: ", que.content)
    print("Max number of elements: ", que.max_element)
    print("Actual number of elements: ", que.actual_elements)
#__Test__#

#__Full__#
def Full():
    pass
#__Full__#

#__Version_selector__#
def Version_selector():
    print("Which version should be used? (Type in the number!)")
    print("1 - Test")
    print("2 - Full")
    answer = int(input())
    if(answer == 1):
        Test()
        Version_selector()
    elif(answer == 2):
        Full()
        Version_selector()
#__Version_selector__#
Version_selector()


答:
Consider the following code. In the code below you persumably change the value of x but in fact there is a big difference between the x inside the function and outside. The x inside the function is a local variable and will "disappear" once the function ends. If you want to save the value of x you must use return x and save the outcome to a variable. For example, See the function a_saving_example(x)

you may also use a global variable though some say it is  bad practice and it is better to use return in your function.

```<code>def times_two(x):
    x = x * 2

x = 5
print(x)
times_two(x)
print(x)

</code>```

output:

```<code>5
5
</code>```

saving example:

```<code>def a_saving_example(x):
    x = x * 2
    return x

x = 5
print(x)
x = a_saving_example(x)
print(x)
</code>```

output:

```<code>5
10
</code>```

Title: Python variable's value doesn't get changed outside the function

Body:
Consider the following code. In the code below you persumably change the value of x but in fact there is a big difference between the x inside the function and outside. The x inside the function is a local variable and will "disappear" once the function ends. If you want to save the value of x you must use return x and save the outcome to a variable. For example, See the function a_saving_example(x)

you may also use a global variable though some say it is  bad practice and it is better to use return in your function.

def times_two(x):
    x = x * 2

x = 5
print(x)
times_two(x)
print(x)

output:

5
5

saving example:

def a_saving_example(x):
    x = x * 2
    return x

x = 5
print(x)
x = a_saving_example(x)
print(x)

output:

5
10


问:
How can I stop Xcode 3.2.6 defaulting to the iPad Simulator? Is this new behaviour?
It seems like every time I launch an Xcode project or 'Clean all Targets' the Active Executable resets to the iPad simulator.

Prior to the Xcode 3.2.6 release Xcode was defaulting to the iPhone Simulator or remembered my previous Active Executable... I've never noticed this behaviour because I generally do iPhone work. This has been bothering me sine the latest Xcode update (iOS 4.3 release) and is really irritating.

Similar questions/answers suggest setting the 'Targeted Device Family' of my Target to 'iPhone' - this has been done.

Is this new behaviour?

Is there anyway to change the default 'Active Executable'?

答:
I finally solved this problem myself.

First, install new version of xCode, which is xCode 4.

Then set project scheme to iphone simulator and run app in xCode several times.

And re-install xCode 3 and the problem will be gone away!


问:
How can I compare numbers from a list only with the next number (neighbor)?
All I want to do is to compare the first number from a list with the second number from the same list, the second one with the third one, and so on.

input:

```<code>lst = [1,2,3,2,1]
</code>```

output:

```<code>result = ["Lower", "Lower", "Higher", "Higher"]
</code>```

(1 is lower than 2, 2 is lower than 3, 3 is higher than 2, 2 is higher than 1)

It's kinda ugly (a list comprehension would be great), but my approach for that would be:

```<code>lst = [1,2,3,2,1]
result = []
x = 0

try:
    for i in range(len(lst)):
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
except IndexError:
    print(result)
    print("Out of range")
</code>```

答:
You have the right idea with the try/except paradigm, but you are wrapping the entire loop in a try block. What you want instead is to ignore only the indices for which the IndexError occurs. So try this:

```<code>lst = [1,2,3,2,1]
result = []
x = 0

for i in range(len(lst)):
    try:
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
    except IndexError:
        print(result)
        print("Out of range")
</code>```

Since you're comparing numbers in pairs, you know that your output list will have one fewer entry than the input list. Each index of the output list describes the relationship between the corresponding element in the input list and the next element in the input list.

```<code>lst = [1,2,3,2,1]
result = []
for i in range(len(lst)-1):
    a = lst[i]
    b = lst[i+1]

    if a<b:
        result.append("Lower")
    else:
        result.append("Higher")
</code>```

Of course, you can do the whole thing as a one-liner

```<code>result = [("Lower", "Higher")[lst[i]>lst[i+1]] for i in range(len(lst)-1)]
</code>```

Or the even terser:

```<code>result = [("Lower", "Higher")[a>b] for a,b in zip(lst, lst[1:])]
</code>```

Body:
You have the right idea with the try/except paradigm, but you are wrapping the entire loop in a try block. What you want instead is to ignore only the indices for which the IndexError occurs. So try this:

lst = [1,2,3,2,1]
result = []
x = 0

for i in range(len(lst)):
    try:
        if lst[x] > lst[x+1]:
            result.append("Higher")
            #print("Higher")
        else:
            result.append("Lower")
            #print("Lower")
        x = x+1
    except IndexError:
        print(result)
        print("Out of range")

Since you're comparing numbers in pairs, you know that your output list will have one fewer entry than the input list. Each index of the output list describes the relationship between the corresponding element in the input list and the next element in the input list.

lst = [1,2,3,2,1]
result = []
for i in range(len(lst)-1):
    a = lst[i]
    b = lst[i+1]

    if a<b:
        result.append("Lower")
    else:
        result.append("Higher")

Of course, you can do the whole thing as a one-liner

result = [("Lower", "Higher")[lst[i]>lst[i+1]] for i in range(len(lst)-1)]

Or the even terser:

result = [("Lower", "Higher")[a>b] for a,b in zip(lst, lst[1:])]


问:
Print preview from multiple iframes?
I have several iframes in a page. I want to show in a print preview all the iframe contents as snapshots of iframes. I used window.print() for individual iframes, and it's working fine, but how do I do it for multiple frames?

答:
YES it is possible to get the content of all iframes to be printed into the parent window. I achieved it with this code.

```<code><script>

pages =[] // initiate an empty list here

function printPage() {

var frames = document.getElementsByTagName('iframe');
// get all the iframes and loop over them
// then push their innerHTML into the list
for (var i = 0; i < frames.length; i++){
        pages.push(frames[i].contentWindow.document.body.innerHTML);
    ;
}
if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the iframes innerHTML
    window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
    window.print();
}
else {
// do nothing
}

}
</code>```

with this solution you even avoid the problem of the iframe being cut off if it exceeds one page.

Plus, you get only one print dialogue box instead to print all the pages.

In your parent page HTML you will have the code below to call the printPage function.

```<code><input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />
</code>```

Title: Print preview from multiple iframes?

Body:
YES it is possible to get the content of all iframes to be printed into the parent window. I achieved it with this code.

<script>

pages =[] // initiate an empty list here

function printPage() {

var frames = document.getElementsByTagName('iframe');
// get all the iframes and loop over them
// then push their innerHTML into the list
for (var i = 0; i < frames.length; i++){
        pages.push(frames[i].contentWindow.document.body.innerHTML);
    ;
}
if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the iframes innerHTML
    window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
    window.print();
}
else {
// do nothing
}

}

with this solution you even avoid the problem of the iframe being cut off if it exceeds one page.

Plus, you get only one print dialogue box instead to print all the pages.

In your parent page HTML you will have the code below to call the printPage function.

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />


问:
HTML - Background-color not changing for navbar
Apologies for the rather stupid question. I am quite new to creating HTML web pages and I am just working on a basic homepage. I can't get the navbar background-color to change to any color but the :hover and the .active appear to work. I have been stuck on this for a couple of days looking it up on internet and moving code around to see whether it makes a difference...

Please excuse all the mistakes I probably would have made and thanks in advance!

I just get a bit demotivated when I hit a wall that seems rather simple.

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        Home
        Services
        News and Events
        Contact
        About
        Data Protection

```

答: Problem seems to occur because you are using comment for HTML  in CSS part of the page

Body:
Problem seems to occur because you are using comment for HTML <!-- Menu CSS --> in CSS part of the page <style>. Same problem is in beginning of your style.

You should use CSS comments in <style> sections:

/* This is a CSS comment */

When you type a HTML comment instead of CSS one, it will break whole style only for the following selector. Rest of the code won't be affected.

Also, when I remove that comment, navigation bar is still not looking as it should.
This is because your navigation links <a> are set to display: inline as it is their default. You must change this to display: inline-block so it will still be in line but will take some space (square)

.header {
  position: sticky;
  top: 0;
}

.topnav {
  overflow: hidden;
  background-color: gray;
  display: block;
}

.topnav a {
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;

  /* You should use inline-block to make navigation links take some   space */
  display: inline-block;
}

.topnav a:hover {
  background-color: Yellow;
  color: black;
}

.topnav a.active {
  background-color: red;
  color: blue;
}

<div class="header">

  <div class="topnav">
      <a class="active" href="#home">Home</a>
      <a href="#services">Services</a>
      <a href="#news">News and Events</a>
      <a href="#contact">Contact</a>
      <a href="#about">About</a>
      <a href="#data">Data Protection</a>
 </div>

</div>

Please refer to these references

Inline-block
CSS comments


问:
Get first x items from FileInfo
I have a FileInfo in C# that looks like this:

```<code>        DirectoryInfo dir = new DirectoryInfo(folder);
        FileInfo[] files = dir.GetFiles("Car*", SearchOption.TopDirectoryOnly);
</code>```

I want to be able to select the first x items, let's say 30, of the files in files and remove the rest from files. How do I do that without just looping through it from 0 to 29?

答:
Instead of using GetFiles, use EnumerateFiles plus Take and ToArray:

```<code>DirectoryInfo dir = new DirectoryInfo(folder);
FileInfo[] files = dir.EnumerateFiles("Car*", SearchOption.TopDirectoryOnly).Take(30).ToArray();
</code>```

This will create an array with up to the first thirty items found in the directory. This has the benefit that on really large directories it only returns thirty items at most. GetFiles will return every file in the directory first which can take time if there's a lot of files. EnumerateFiles on the otherhand, returns an IEnumerable<FileInfo> which allows you to "stream" the results and apply LINQ operators before collecting them into an array or List.

Note: you will need to make sure that you have the appropriate using directive at the top of your file:

```<code>using System.Linq;
</code>```

Title: Get first x items from FileInfo

Body:
I have a FileInfo in C# that looks like this:

        DirectoryInfo dir = new DirectoryInfo(folder);
        FileInfo[] files = dir.GetFiles("Car*", SearchOption.TopDirectoryOnly);

I want to be able to select the first x items, let's say 30, of the files in files and remove the rest from files. How do I do that without just looping through it from 0 to 29?

Body:
Instead of using GetFiles, use EnumerateFiles plus Take and ToArray:

DirectoryInfo dir = new DirectoryInfo(folder);
FileInfo[] files = dir.EnumerateFiles("Car*", SearchOption.TopDirectoryOnly).Take(30).ToArray();

This will create an array with up to the first thirty items found in the directory. This has the benefit that on really large directories it only returns thirty items at most. GetFiles will return every file in the directory first which can take time if there's a lot of files. EnumerateFiles on the otherhand, returns an IEnumerable<FileInfo> which allows you to "stream" the results and apply LINQ operators before collecting them into an array or List.

Note: you will need to make sure that you have the appropriate using directive at the top of your file:

using System.Linq;