问:
Finding Time Complexity of these two algorithms?
Here's the first algorithm,

```<code>sum = 0;
for( i=1; i<n; i++ )
        for( j=0; j<i*n; j++ )
            for( k=0; k<j; k++)
            sum++;
</code>```

Here's the second algorithm

```<code>sum = 0;
for( i=1; i<n; i++ )
    ( j=1; j<i*n; j++ )
        if( j%1 == 0 )
            for( k=0; k<j; k++ )
                sum++;
</code>```

Can anyone help me finding the Big O for these two algorithms?
I tried doing it and I got n^5 but when I checked it by comparing the running times of an algorithm of n^5 and these algorithms, there was a huge difference...
Although both of these algorithms had more or less equal running times, which mean their time complexity is same.

If anyone can then please provide a possible way to analyze these two algorithms and to find the time complexities of both. Thank you

Note: I have also tried comparing it with algorithms of n^4 time and there still was a huge difference between the running times... I can provide the values also of the running times of all these different algorithms if required.

答:
The time complextiy for the first algorithm is like the following sum:

```<code>sum_{i=1}^{n-1} sum_{j=1}^{i*n} j =
sum_{i=1}^{n-1} i * n * (i*n + 1) / 2 =
0.5 * sum_{i=1}^{n-1} i^2 * n^2 + i*n =
0.5 * (n^2 * sum_{i=1}^{n-1} i^2 + n * sum_{i=1}^{n-1} i) =
0.5 * (n^2 * \Theta(n^3) + n * \Theta(n^2)) = \Theta(n^5)
</code>```

So, you are right. But be careful that this is the asymptotic time complexity and can be different from the measured CPU running time.

And it is the same for the second algorithm (with a tiny difference), as always, j%1 is equal to zero for all j > 0.

Body:
Here's the first algorithm,

sum = 0;
for( i=1; i<n; i++ )
        for( j=0; j<i*n; j++ )
            for( k=0; k<j; k++)
            sum++;

Here's the second algorithm

sum = 0;
for( i=1; i<n; i++ )
    ( j=1; j<i*n; j++ )
        if( j%1 == 0 )
            for( k=0; k<j; k++ )
                sum++;

Can anyone help me finding the Big O for these two algorithms?
I tried doing it and I got n^5 but when I checked it by comparing the running times of an algorithm of n^5 and these algorithms, there was a huge difference...
Although both of these algorithms had more or less equal running times, which mean their time complexity is same.

If anyone can then please provide a possible way to analyze these two algorithms and to find the time complexities of both. Thank you

Note: I have also tried comparing it with algorithms of n^4 time and there still was a huge difference between the running times... I can provide the values also of the running times of all these different algorithms if required.

Body:
The time complextiy for the first algorithm is like the following sum:

sum_{i=1}^{n-1} sum_{j=1}^{i*n} j =
sum_{i=1}^{n-1} i * n * (i*n + 1) / 2 =
0.5 * sum_{i=1}^{n-1} i^2 * n^2 + i*n =
0.5 * (n^2 * sum_{i=1}^{n-1} i^2 + n * sum_{i=1}^{n-1} i) =
0.5 * (n^2 * \Theta(n^3) + n * \Theta(n^2)) = \Theta(n^5)

So, you are right. But be careful that this is the asymptotic time complexity and can be different from the measured CPU running time.

And it is the same for the second algorithm (with a tiny difference), as always, j%1 is equal to zero for all j > 0.


来源: stackexchange

问:
Javascript: Get instance getter and fields names or names and values
I usually use the next sentence to obtain all object fields but I just realized that is skips object getters

```<code>Object.entries(myInstance)
</code>```

I also tried without results:

```<code>Object.keys(myInstance)
Object.values(myInstance)
</code>```

There is any way to traverse the object attributes AND getters? I am interested in the name and value of the getter not the function itself.

答:
You can also make the getter enumerable using Object.defineProperty to define the instance with the config to allow it to be enumerable. Substituting 'this' for a reference to your object below.

```<code>Object.defineProperty(this, 'getterName' {
   enumerable: true,
   get: function() {
       return 'value'
   }
}
</code>```

MDN: Object.defineProperty

ContentLicense: CC BY-SA 4.0

Body:
I usually use the next sentence to obtain all object fields but I just realized that is skips object getters

Object.entries(myInstance)

I also tried without results:

Object.keys(myInstance)
Object.values(myInstance)

There is any way to traverse the object attributes AND getters? I am interested in the name and value of the getter not the function itself.

Body:
You can also make the getter enumerable using Object.defineProperty to define the instance with the config to allow it to be enumerable. Substituting 'this' for a reference to your object below.

Object.defineProperty(this, 'getterName' {
   enumerable: true,
   get: function() {
       return 'value'
   }
}

MDN: Object.defineProperty


问:
Python - Replace Multiple Indices With One in For Loop
I'm trying to find a way to replace multiple indices with a single one.

Original list:

```<code>a[100] = "-277/480V RATED:"
a[101] = "Model L-N:"
a[102] = "B3 Ring Wave: 600"
a[103] = "C3 Combined Wave: 1300"
a[104] = "6kV-3Ka UL VPR: 1200"
a[105] = "Model L-G:"
a[106] = "B3 Ring Wave: 875"
a[107] = "C3 Combined Wave: 1300"
a[108] = "6kV-3Ka UL VPR: 1200"
a[109] = "Some other string"
</code>```

The output I want is:

```<code>a[100] = "-277/480V RATED:"
a[101] = "Model L-N:\nB3 Ring Wave: 600\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[102] = "Model L-G:\nB3 Ring Wave: 875\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[103] = "Some other string"
</code>```

I think I know how I'm going to concat everything. I'm going to a.startswith("B3 Ring Wave:) because that appears to be a constant and then join the indices above and below it with "\n" for new line.

Th issue is I don't know how I can replace the indices and if I can have this run in a for loop. My thought is that if I could replace them it would check a[101] which wouldn't match. It would move onto a[102] which would match so it would replace a[101-104]. It would then go into the for loop for a[102] which used to be a[105]. Is that correct?

```<code>original = ["Some Other Sting","-277/480V RATED:","Model L-N:","B3 Ring Wave: 600","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Model L-G:","B3 Ring Wave: 875","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Some other string"]

joinedList = []

for i, str in enumerate(original):
    if str.startswith("B3 Ring Wave:"):
        joinedList.append("\n".join(original[i - 1: i + 2]))
    else:
        "Do Nothing"
</code>```

答:
An option is to iterate through the list and alter one of the indices with your new value.  You could then record the indices you need to drop and do it afterwards.

Example

```<code>test_list = ["-277/480V RATED:",
 "Model L-N:",
 "B3 Ring Wave: 600",
 "C3 Combined Wave: 1300",
"6kV-3Ka UL VPR: 1200",
 "Model L-G:",
"B3 Ring Wave: 875",
"C3 Combined Wave: 1300",
 "6kV-3Ka UL VPR: 1200",
"Some other string"]

drop_inds = []
for item in test_list:
    if item.startswith("B3"):
        ind = test_list.index(item)
        change_string = '\n'.join(test_list[ind-1:ind+3])
        test_list[ind-1] = change_string
        for i in range(ind,ind+3):
            drop_inds.append(i)

final_list = [test_list[t] for t in range(len(test_list)) if t not in drop_inds]
print(final_list)

['-277/480V RATED:',
 'Model L-N:\nB3 Ring Wave: 600\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200',
 'Model L-G:\nB3 Ring Wave: 875\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200',
 'Some other string']
</code>```

Body:
I'm trying to find a way to replace multiple indices with a single one.

Original list:

a[100] = "-277/480V RATED:"
a[101] = "Model L-N:"
a[102] = "B3 Ring Wave: 600"
a[103] = "C3 Combined Wave: 1300"
a[104] = "6kV-3Ka UL VPR: 1200"
a[105] = "Model L-G:"
a[106] = "B3 Ring Wave: 875"
a[107] = "C3 Combined Wave: 1300"
a[108] = "6kV-3Ka UL VPR: 1200"
a[109] = "Some other string"

The output I want is:

a[100] = "-277/480V RATED:"
a[101] = "Model L-N:\nB3 Ring Wave: 600\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[102] = "Model L-G:\nB3 Ring Wave: 875\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[103] = "Some other string"

I think I know how I'm going to concat everything. I'm going to a.startswith("B3 Ring Wave:) because that appears to be a constant and then join the indices above and below it with "\n" for new line.

Th issue is I don't know how I can replace the indices and if I can have this run in a for loop. My thought is that if I could replace them it would check a[101] which wouldn't match. It would move onto a[102] which would match so it would replace a[101-104]. It would then go into the for loop for a[102] which used to be a[105]. Is that correct?

original = ["Some Other Sting","-277/480V RATED:","Model L-N:","B3 Ring Wave: 600","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Model L-G:","B3 Ring Wave: 875","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Some other string"]

joinedList = []

for i, str in enumerate(original):
    if str.startswith("B3 Ring Wave:"):
        joinedList.append("\n".join(original[i - 1: i + 2]))
    else:
        "Do Nothing"

Body:
An option is to iterate through the list and alter one of the indices with your new value.  You could then record the indices you need to drop and do it afterwards.

Example

test_list = ["-277/480V RATED:",
 "Model L-N:",
 "B3 Ring Wave: 600",
 "C3 Combined Wave: 1300",
"6kV-3Ka UL VPR: 1200",
 "Model L-G:",
"B3 Ring Wave: 875",
"C3 Combined Wave: 1300",
 "6kV-3Ka UL VPR: 1200",
"Some other string"]

drop_inds = []
for item in test_list:
    if item.startswith("B3"):
        ind = test_list.index(item)
        change_string = '\n'.join(test_list[ind-1:ind+3])
        test_list[ind-1] = change_string
        for i in range(ind,ind+3):
            drop_inds.append(i)

final_list = [test_list[t] for t in range(len(test_list)) if t not in drop_inds]
print(final_list)

['-277/480V RATED:',
 'Model L-N:\nB3 Ring Wave: 600\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200',
 'Model L-G:\nB3 Ring Wave: 875\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200',
 'Some other string']


答:
Since you dont want to convert it to a table you can use this:</p>

```<code>import datetime
import numpy as np

dates = list(map(lambda x: datetime.datetime.strptime(x[2], '%d.%m.%Y'), tab))
list(np.diff(dates))

[datetime.timedelta(days=-1),
 datetime.timedelta(0),
 datetime.timedelta(days=-1),
 datetime.timedelta(days=-1),
 datetime.timedelta(days=-2),
 datetime.timedelta(0),
 datetime.timedelta(0),
 datetime.timedelta(0),
 datetime.timedelta(0),
 datetime.timedelta(days=-39),
 datetime.timedelta(days=39)]
</code>```

Title: How to convert date from string format in python

Body:
I have below table. I want to count timedelta between first and second date, second and third and so on in a for loop…
I really do not want to convert my dates in table to integer set to use timedelta() function. Is there any function in python which can convert str like: ’30.06.2019’ or 30/06/2019 to date ?
Perfect would be convert all tab[i][2] to date and then count time date between them in a loop.

tab = [ [21091705,  0,'30.06.2019'],
        [21091705,  653777,'29.06.2019'],
        [21091705,  653842,'29.06.2019'],
        [21091705,  641701,'28.06.2019'],
        [21091705,  642000,'27.06.2019'],
        [21091705,  0,'25.06.2019'],
        [21091705,  642030,'25.06.2019'],
        [21091705,  642030,'25.06.2019'],
        [21091705,  637030,'25.06.2019'],
        [21091705,  0,'25.06.2019'],
        [21091705,  0,'17.05.2019'],
        [21091705,  0,'25.06.2019']
        ]

Body:
Since you dont want to convert it to a table you can use this:

import datetime
import numpy as np

dates = list(map(lambda x: datetime.datetime.strptime(x[2], '%d.%m.%Y'), tab))
list(np.diff(dates))

[datetime.timedelta(days=-1),
 datetime.timedelta(0),
 datetime.timedelta(days=-1),
 datetime.timedelta(days=-1),
 datetime.timedelta(days=-2),
 datetime.timedelta(0),
 datetime.timedelta(0),
 datetime.timedelta(0),
 datetime.timedelta(0),
 datetime.timedelta(days=-39),
 datetime.timedelta(days=39)]


问:
Plot training, validation and test set on same plot
This is how I segmented the data

```<code>(X, y), (X_test, y_test) = mnist.load_data()
X_train, X_val, y_train, y_val = train_test_split(X,
                                                  y,
                                                  test_size=0.1,
                                                  random_state=1)
</code>```

The below code plots X_train and X_val, I would like to add X_test the plot

```<code>history = model.fit(
    x= X_train,
    y= y_train,
    epochs = 10,
    validation_data = (X_val, y_val),
    batch_size = 128
)

from matplotlib import pyplot as plt

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
</code>```

Is it also possible to plot the test_loss on top of this to get an overview of all three on the same plot?

There is no history.history['test_loss'].

答:
You did not calculate test_loss yet.
You first need to predict some labels using X_test and then calculate the loss based on the predicted values and y_test. Alternatively, you can use evaluate to do that directly:

```<code>test_loss = model.evaluate(X_test, y_test)
</code>```

You cannot plot them together since test_loss is a single value that is calculated once at the end of training and not every epoch like validation.

Nevertheless, you should not use X_test and y_test in training as you will have trained on the whole available data so you can't test anymore.

X_test and y_test are to be used solely at the end of all the steps to test the performance of the model.

The validation data serves the purpuse of "test data" while you are training. After you have done all the training and optimization you can then retrain the network on the combined dataset of train ad validation, and use the resulting network to test it's performace on the test dataset (X_test, y_test)

Body:
This is how I segmented the data

(X, y), (X_test, y_test) = mnist.load_data()
X_train, X_val, y_train, y_val = train_test_split(X,
                                                  y,
                                                  test_size=0.1,
                                                  random_state=1)

The below code plots X_train and X_val, I would like to add X_test the plot

history = model.fit(
    x= X_train,
    y= y_train,
    epochs = 10,
    validation_data = (X_val, y_val),
    batch_size = 128
)

from matplotlib import pyplot as plt

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

Is it also possible to plot the test_loss on top of this to get an overview of all three on the same plot?

There is no history.history['test_loss'].

Body:
You did not calculate test_loss yet.
You first need to predict some labels using X_test and then calculate the loss based on the predicted values and y_test. Alternatively, you can use evaluate to do that directly:

test_loss = model.evaluate(X_test, y_test)

You cannot plot them together since test_loss is a single value that is calculated once at the end of training and not every epoch like validation.

Nevertheless, you should not use X_test and y_test in training as you will have trained on the whole available data so you can't test anymore.

X_test and y_test are to be used solely at the end of all the steps to test the performance of the model.

The validation data serves the purpuse of "test data" while you are training. After you have done all the training and optimization you can then retrain the network on the combined dataset of train ad validation, and use the resulting network to test it's performace on the test dataset (X_test, y_test)


问:
O_DIRECT support on a jffs2 Linux filesystem
Im trying to use O_DIRECT to open a file and we're using jffs2

```<code>fd = open(filename, O_RDONLY|O_DIRECT|O_SYNC);
</code>```

But i only get an "invalid argument" error.
I have also tried the solutions
in this SO link but to no avail.
Ofcourse i have also put in "-D_GNU_SOURCE" in building the source.

I've read that O_DIRECT is not supported on tmpfs, but couldn't find support or un-support for jffs2.
If someone could give me proof or un-proof for jffs2 support and/or any other thing i'm missing to make O_DIRECT work.

note:
This all happened because Linux seem to cache memory data on its own when i use fread()/read().
And using system("echo 3 > /proc/sys/vm/drop_caches"); would be too late because I don't want the FS allocating cache memory in the first place.

Thanks,
Naze

答:
jffs2 does not support O_DIRECT.

You can see in __dentry_open() that in order to support O_DIRECT, a filesystem must supply the direct_IO and/or get_xip_mem members of the address_space_operations struct.  You can likewise see that jffs2 does not supply these members.

It is not clear why you are so keen to avoid the page cache.  Pages in the page cache are effectively "free" - they will be reclaimed when more memory is required for other uses.

ContentLicense: CC BY-SA 3.0

Body:
Im trying to use O_DIRECT to open a file and we're using jffs2

fd = open(filename, O_RDONLY|O_DIRECT|O_SYNC);

But i only get an "invalid argument" error.
I have also tried the solutions
in this SO link but to no avail.
Ofcourse i have also put in "-D_GNU_SOURCE" in building the source.

I've read that O_DIRECT is not supported on tmpfs, but couldn't find support or un-support for jffs2.
If someone could give me proof or un-proof for jffs2 support and/or any other thing i'm missing to make O_DIRECT work.

note:
This all happened because Linux seem to cache memory data on its own when i use fread()/read().
And using system("echo 3 > /proc/sys/vm/drop_caches"); would be too late because I don't want the FS allocating cache memory in the first place.

Thanks,
Naze


问:
Is there a way to display choices through prompt options as still buttons even though few choices have larger length text in MSBOT via C# SDKV4?
I am creating a chatBot using microsoft Bot framework using SDKV4 in C#. The BOT has multiple waterfall dialogs. The channel is Web Chat Channel.

In this one dialog class shows few choice options in form of buttons using Prompt Options. Normally, if the choice list is simple like Option1 ,Option2 so on till Option6 the buttons will be displayed properly.
But If i have choices which have text of greater length like the values provided in the below code:

```<code>return await stepContext.PromptAsync(
                            "choicePrompt",
                            new PromptOptions
                            {
                                Prompt = stepContext.Context.Activity.CreateReply("Based on the access privileges assigned to you by your admin, below are the options you can avail. Please click/choose any one from the following: "),
                                Choices = new[] { new Choice { Value = "Show My VMs" }, new Choice { Value = "Show VMs Status" }, new Choice { Value = "Start VM" }, new Choice { Value = "Stop VM" }, new Choice { Value = "Request Model/License" }, new Choice { Value = "Request For New VM" }, new Choice { Value = "Extend My Existing VM" }, new Choice { Value = "Logout" }, new Choice { Value = "Help" } }.ToList(),
                                RetryPrompt = stepContext.Context.Activity.CreateReply("Sorry, I did not understand that. Please choose any one from the options displayed below: "),
                            });
</code>```

On executing the code the values provided in the choice list will not be rendered as buttons but instead as list of numbered bullet-ed text options something like below:

Show My VMs

Show VMs Status

Start VM

Stop VM

Request Model/License

Request For New VM

Extend My Existing VM

Logout

Help

Now, if i remove the spaces between the words i.e if i modify/rewrite one of the option as only "RequestModel/License" (without spaces) like wise if is remove the space for all the text which have more than 2-3 words, on executing the code now the choices will be displayed as Buttons as expected.

So, coming to my query/issue:
How can i still use choices in prompt options as shown in above code(with longer string values) and still make the buttons to be displayed?

Please note that i am a bit new to coding hence i would humbly request to provide detailed steps if this is behavior is achievable.

Thanks in Advance

Regards

ChaitanyaNG

答:
If you are asking if there is a way to force buttons to be displayed, it is likely not possible. The length is different by channel (you may find buttons in webchat are rendered as numbered list in Teams, for example) and cannot be changed. In examining the class I saw some things that supposedly would override this behavior, but none of it worked.

If you just want to send a different value than the button displays, you can do that by adding an action attribute to the choice. The title is what is displayed on the button and the value is what will be passed to stepContext.result (or whatever your context object is named). I don't know the C# syntax, but in nodejs the choice definition would be

{
   value: 'Request Model/License',
   action: {
      type: 'imBack',
      title: 'RequestModel/License',
      value: 'Request Model/License'
   },
   synonyms: ['Model','License']
}
```

Obviously you don't have to use synonyms, but that can be helpful too when someone might manually type something similar instead of using the buttons. For what it's worth, I like abbreviating to "Req Model/License" instead of running the words together but that's your personal preference.

Body:
I am creating a chatBot using microsoft Bot framework using SDKV4 in C#. The BOT has multiple waterfall dialogs. The channel is Web Chat Channel.

In this one dialog class shows few choice options in form of buttons using Prompt Options. Normally, if the choice list is simple like Option1 ,Option2 so on till Option6 the buttons will be displayed properly.
But If i have choices which have text of greater length like the values provided in the below code:

return await stepContext.PromptAsync(
                            "choicePrompt",
                            new PromptOptions
                            {
                                Prompt = stepContext.Context.Activity.CreateReply("Based on the access privileges assigned to you by your admin, below are the options you can avail. Please click/choose any one from the following: "),
                                Choices = new[] { new Choice { Value = "Show My VMs" }, new Choice { Value = "Show VMs Status" }, new Choice { Value = "Start VM" }, new Choice { Value = "Stop VM" }, new Choice { Value = "Request Model/License" }, new Choice { Value = "Request For New VM" }, new Choice { Value = "Extend My Existing VM" }, new Choice { Value = "Logout" }, new Choice { Value = "Help" } }.ToList(),
                                RetryPrompt = stepContext.Context.Activity.CreateReply("Sorry, I did not understand that. Please choose any one from the options displayed below: "),
                            });

On executing the code the values provided in the choice list will not be rendered as buttons but instead as list of numbered bullet-ed text options something like below:

Show My VMs

Show VMs Status

Start VM

Stop VM

Request Model/License

Request For New VM

Extend My Existing VM

Logout

Help

Now, if i remove the spaces between the words i.e if i modify/rewrite one of the option as only "RequestModel/License" (without spaces) like wise if is remove the space for all the text which have more than 2-3 words, on executing the code now the choices will be displayed as Buttons as expected.

So, coming to my query/issue:
How can i still use choices in prompt options as shown in above code(with longer string values) and still make the buttons to be displayed?

Please note that i am a bit new to coding hence i would humbly request to provide detailed steps if this is behavior is achievable.

Thanks in Advance

Regards

ChaitanyaNG

Body:
If you are asking if there is a way to force buttons to be displayed, it is likely not possible. The length is different by channel (you may find buttons in webchat are rendered as numbered list in Teams, for example) and cannot be changed. In examining the class I saw some things that supposedly would override this behavior, but none of it worked.

If you just want to send a different value than the button displays, you can do that by adding an action attribute to the choice. The title is what is displayed on the button and the value is what will be passed to stepContext.result (or whatever your context object is named). I don't know the C# syntax, but in nodejs the choice definition would be

{
   value: 'Request Model/License',
   action: {
      type: 'imBack',
      title: 'RequestModel/License',
      value: 'Request Model/License'
   },
   synonyms: ['Model','License']
}

Obviously you don't have to use synonyms, but that can be helpful too when someone might manually type something similar instead of using the buttons. For what it's worth, I like abbreviating to "Req Model/License" instead of running the words together but that's your personal preference.


问:
process.env.SOME_KEY is undefined
How do I set the value of process.env.SOME_KEY=some value in the operating system and then read it in my node application?  I am running on Windows.

I tried these steps:

```<code>SET SOME_KEY=abc
npm start
</code>```

But when I try to read process.env.SOME_KEY, I am getting "undefined".

How do I set a env value and how do i read that in my code?

答:
```<code>SOME_KEY=`${abc}` Fixed it for me.
</code>```

Title: process.env.SOME_KEY is undefined

Body:
How do I set the value of process.env.SOME_KEY=some value in the operating system and then read it in my node application?  I am running on Windows.

I tried these steps:

SET SOME_KEY=abc
npm start

But when I try to read process.env.SOME_KEY, I am getting "undefined".

How do I set a env value and how do i read that in my code?

Body: SOME_KEY=`${abc}` Fixed it for me.


答:
```<code>y, x = np.ogrid[:C.shape[0],:C.shape[1]]
D = A[C[y, x], y, x]
</code>```

Title: How to slice a 3D array from a 2D array without nested loops?

Body:
I have four matrices, partially created from each other:

A is a 3D matrix that represents a stack of grayscale images and is of shape (n, h, w)

B is a 3D matrix that also represents a stack of images, where each slice is individually calculated from the corresponding slice in A and is also of shape (n, h, w)

C is a 2D matrix, containing the index with the maximum value of B in z direction and is of shape (h, w)

D is a 2D matrix, where a value from A is copied from a certain slice, which is indicated by the value in C at position (x, y).

A minimum example implemented with loops would look as follows:

import numpy as np

A = np.random.randint(0, 255, size=(3, 4, 5))
B = np.random.randint(0, 255, size=(3, 4, 5))
C = np.argmax(B, axis=0)

D = np.zeros(C.shape, dtype=int)
for y in range(C.shape[0]):
    for x in range(C.shape[1]):
        D[y, x] = A[C[y, x], y, x]

> A
array([[[ 24,  84, 155,   8, 147],
        [ 25,   4,  49, 195,  57],
        [ 93,  76, 233,  83, 177],
        [ 70, 211, 201, 132, 239]],

       [[177, 144, 247, 251, 207],
        [242, 148,  28,  40, 105],
        [181,  28, 132,  94, 196],
        [166, 121,  72,  14,  14]],

       [[ 55, 254, 140, 142,  14],
        [112,  28,  85, 112, 145],
        [ 16,  72,  16, 248, 179],
        [160, 235, 225,  14, 211]]])

> B
array([[[246,  14,  55, 163, 161],
        [  3, 152, 128, 104, 203],
        [ 43, 145,  59, 169, 242],
        [106, 169,  31, 222, 240]],

       [[ 41,  26, 239,  25,  65],
        [ 47, 252, 205, 210, 138],
        [194,  64, 135, 127, 101],
        [ 63, 208, 179, 137,  59]],

       [[112, 156, 183,  23, 253],
        [ 35,   6, 233,  42, 100],
        [ 66, 119, 102, 217,  64],
        [ 82,  67, 135,   6,   8]]])

> C
array([[0, 2, 1, 0, 2],
       [1, 1, 2, 1, 0],
       [1, 0, 1, 2, 0],
       [0, 1, 1, 0, 0]])

> D
array([[ 24, 254, 247,   8,  14],
       [242, 148,  85,  40,  57],
       [181,  76, 132, 248, 177],
       [ 70, 121,  72, 132, 239]])

My question is: How to slice A with C efficiently eliminating the nested for-loops? My initial idea was to expand C to a 3D boolean mask, where only the positions [c, y, x] are set to True and then to simply multiply it elementwise with A and take the sum over z-axis. But I can't think of an pythonesque implementation without loops (and I probably wouldn't need to create a boolean mask anymore, if I'd knew how to write that).

The closest already implemented function I found is np.choose(), but it only takes 32 elements for C.


问:
Xamarin.Forms BackgroudImage not showing
I am trying to apply background image to all pages within my Xamarin.Forms app using an application style, but it is not applying the style to the pages.

I tried with this:

App.xaml resources

```<code>...
<Application.Resources>
  <ResourceDictionary>
    <Style TargetType="Page">
      <Setter Property="BackgroundImageSource" Value="logo.png"/>
    </Style>
...
</code>```

MainPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="FinansovoPregledi.MainPage">
    <StackLayout Spacing="10" VerticalOptions="Center">
        <Button Text="Login" BackgroundColor="#006BE6" x:Name="scanButton" TextColor="WhiteSmoke" Command="{Binding LogInCommand}"/>
    </StackLayout>
</ContentPage>
</code>```

MainPage.xaml.cs

```<code>    public partial class MainPage : ContentPage
    {
        LoginViewModel loginViewModel = new LoginViewModel();
        public MainPage()
        {
            InitializeComponent();
            BindingContext = loginViewModel;

        }
...
</code>```

This isn't working. In my scenario the background image has a white background with transparency.

答:
ContentPage is derived from Page and for your style to apply to Pages as well as all controls derived from Pages you need to set the ApplyToDerivedTypes property of your style to True.

Your style would need to be

```

<p>Another approach would be to set the TargetType to ContentPage</p>

<pre class="lang-xml prettyprint-override"><code><Style TargetType="ContentPage">
  <Setter Property="BackgroundImageSource" Value="logo.png"/>
</Style>
</code>```

Body:
I am trying to apply background image to all pages within my Xamarin.Forms app using an application style, but it is not applying the style to the pages.

I tried with this:

App.xaml resources

...
<Application.Resources>
  <ResourceDictionary>

...

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="FinansovoPregledi.MainPage">
    <StackLayout Spacing="10" VerticalOptions="Center">
        <Button Text="Login" BackgroundColor="#006BE6" x:Name="scanButton" TextColor="WhiteSmoke" Command="{Binding LogInCommand}"/>
    </StackLayout>
</ContentPage>

MainPage.xaml.cs

    public partial class MainPage : ContentPage
    {
        LoginViewModel loginViewModel = new LoginViewModel();
        public MainPage()
        {
            InitializeComponent();
            BindingContext = loginViewModel;

        }
...

This isn't working. In my scenario the background image has a white background with transparency.

Body:
ContentPage is derived from Page and for your style to apply to Pages as well as all controls derived from Pages you need to set the ApplyToDerivedTypes property of your style to True.

Your style would need to be

<Style ApplyToDerivedTypes="True" TargetType="Page">
  <Setter Property="BackgroundImageSource" Value="logo.png"/>
</Style>

Another approach would be to set the TargetType to ContentPage

<Style TargetType="ContentPage">
  <Setter Property="BackgroundImageSource" Value="logo.png"/>
</Style>


问:
Big O simplification of factorial
To calculate BigO and constant for the following function :
I have don't know how to simplify it further. Any advise ? Thx</p>

```<code> T(n) =  (n!n+n^3)(n^2+7logn)
      <= (n!n+n^3)(n^2 +7n)   (since n>= log n)
      <= (n!n+n^3)(n^2 +7n)    (n^3 >= 7n if n > 3)
      <= (n!n+n^3)(n^2 + n^3)
      <= (n!n+n^3)(n!n + n^3)  (n!n >= n^2)
         :
</code>```

答:
The highest-order term can be found by expanding:

```<code> T(n) =  (n!n+n^3)(n^2+7logn)
      =  n!n^3 + 6n!nlogn + n^5 + 7n^3logn
</code>```

At this point we can simply compare terms and see which one is biggest:

```<code>n!n^3 vs 6n!nlogn
since n^2 > 7logn for n >= 4, n!n^3 > 7n!nlogn for n >= 1

n!n^3 vs n^5
since n! > n^2 for n >= 4, n!n^3 > n^5 for n >= 4

n!n^3 vs 7n^3logn
since n! > 7logn for n >= 4, n!n^3 > 7n^3logn for n >= 4
</code>```

Based on all this, for n >= 4,

```<code> T(n) =  (n!n+n^3)(n^2+7logn)
      =  n!n^3 + 6n!nlogn + n^5 + 7n^3logn
     <=  n!n^3 + n!n^3 + n!n^3 + n!n^3
      = 4n!n^3
      = O(n!n^3)
</code>```

If you want to find another expression that bounds n!n^3 that's well and good, but I'd recommend another question for that.

Title: Big O simplification of factorial

Body:
To calculate BigO and constant for the following function :
I have don't know how to simplify it further. Any advise ? Thx

 T(n) =  (n!n+n^3)(n^2+7logn)
      <= (n!n+n^3)(n^2 +7n)   (since n>= log n)
      <= (n!n+n^3)(n^2 +7n)    (n^3 >= 7n if n > 3)
      <= (n!n+n^3)(n^2 + n^3)
      <= (n!n+n^3)(n!n + n^3)  (n!n >= n^2)
         :

Body:
The highest-order term can be found by expanding:

 T(n) =  (n!n+n^3)(n^2+7logn)
      =  n!n^3 + 6n!nlogn + n^5 + 7n^3logn

At this point we can simply compare terms and see which one is biggest:

n!n^3 vs 6n!nlogn
since n^2 > 7logn for n >= 4, n!n^3 > 7n!nlogn for n >= 1

n!n^3 vs n^5
since n! > n^2 for n >= 4, n!n^3 > n^5 for n >= 4

n!n^3 vs 7n^3logn
since n! > 7logn for n >= 4, n!n^3 > 7n^3logn for n >= 4

Based on all this, for n >= 4,

 T(n) =  (n!n+n^3)(n^2+7logn)
      =  n!n^3 + 6n!nlogn + n^5 + 7n^3logn
     <=  n!n^3 + n!n^3 + n!n^3 + n!n^3
      = 4n!n^3
      = O(n!n^3)

If you want to find another expression that bounds n!n^3 that's well and good, but I'd recommend another question for that.


问:
pass specific parameter to a function
I have a function:

```<code>getBooks(page, count, authorId){
      return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
        .then(response => {
            return response.data
        })
}
</code>```

I am implementing search function and in search I pass only the authorId  i.e

getBooks(akdjh23)

But on doing this it sets akdjh23 to page. i.e page=akdjh23 but I want authorId=akdjh23

My question is how do I send only authorId during search and page and count on general get request.

Search based on id:

```<code>getBooks(id)
</code>```

Get all books:

```<code>get(1, 40) -> page=1, count=40
</code>```

答:
```<code>getBooks(null, null, id)
</code>```

should do the trick. Note that your code won't work as page and count in your function will not be defined.

Title: pass specific parameter to a function

Body:
I have a function:

getBooks(page, count, authorId){
      return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
        .then(response => {
            return response.data
        })
}

I am implementing search function and in search I pass only the authorId  i.e

getBooks(akdjh23)

But on doing this it sets akdjh23 to page. i.e page=akdjh23 but I want authorId=akdjh23

My question is how do I send only authorId during search and page and count on general get request.

Search based on id:

getBooks(id)

Get all books:

get(1, 40) -> page=1, count=40

Body:
getBooks(null, null, id)

should do the trick. Note that your code won't work as page and count in your function will not be defined.


问:
Flutter: pub get failed (66)
When i try to implement scoped model, i get this error message:

[flutter_course] flutter packages get
Running "flutter packages get" in flutter_course...

Creation of temporary directory failed, path = 'C:\Program Files\flutter.pub-cache_temp\dir' (OS Error: Access is denied.
, errno = 5)

```<code>name: flutter_course
description: A new Flutter project.

version: 1.0.0+1

environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  scoped_model: ^1.0.1

dev_dependencies:
  flutter_test:
    sdk: flutter
</code>```

答:
This happens to be an active issue and the flutter team is currently working on it. The problem is specific to the Windows operating system. You can try the following workarounds for now:

1) Make sure your installation does not reside in any directory which requires special privileges like Program Files. If that's the case, you can try running it as admin for now but you should change your installation directory to a user's data directory as soon as possible (@Günter Zöchbauer has already pointed this out in the comments).

2) Try restarting your machine.

3) Try deleting the .dart_tools folder and also try clearing the cache in flutter/bin/cache

4) Try disabling your antivirus and/or windows defender temporarily (although it's not really possible for people working on corporate machines). This issue could have been caused by an active antivirus locking your files temporarily.

Title: Flutter: pub get failed (66)

Body:
When i try to implement scoped model, i get this error message:

[flutter_course] flutter packages get
Running "flutter packages get" in flutter_course...

Creation of temporary directory failed, path = 'C:\Program Files\flutter.pub-cache_temp\dir' (OS Error: Access is denied.
, errno = 5)

name: flutter_course
description: A new Flutter project.

version: 1.0.0+1

environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  scoped_model: ^1.0.1

dev_dependencies:
  flutter_test:
    sdk: flutter


问:
How do I store a variable of a variable in bukkit?
so i've been trying to make an alt detection plugin in bukkit, i'm pretty new to the api and haven't coded in a good bit but i'm not sure on how to make it work, i've tried hashmaps and i've tried other stuff too but i still don't quite understand how to do it, Basically i'm trying to get the IP of anyone that joins that isn't already in the config and put his ip there including with his IP, and then just check if his alt joins by seeing if he has the same ip as stored already, and add him to the list of usernames that are related to the IP

I thought at the start i could do something like this:

String ip = event.getAddress().toString().replaceAll("/", "");
plugin.getConfig().set("IPs.", ip);
plugin.saveConfig();
if(plugin.getConfig().getString("IPs.") == s) {
    if(plugin.getConfig().get("IPs." + ip) == player.getName()) {
        plugin.getConfig().set("IPs." + s, player.getName());
        plugin.saveConfig();
    }
}
```

<p>but i've realized I can't so i thought of trying to make a String list, and adding the list of IPs in the config, and then i realized I would need to do a weird List of lists even i technically can't then store the ip of someone and check the list of names they have since i can't check if there's a list in the name of his IP</p>

<p>I got really confused here, would love some help!
Thanks!</p>

<p>EDIT 1 My HashMap code i used:</p>

``` // s is the ip string
    HashMap<String,String[]> map = new HashMap<String,String[]>();
                String[] names = new String[10];
                names[0] = player.getName();
                map.put(s, names);
                saveHashMap(map);
```

<p>saveHashMap:</p>

```public void saveHashMap(HashMap<String, String[]> hm) {

    for (String key : hm.keySet()) {
        plugin.getConfig().set("IPs."+key, hm.get(key));
        }
            plugin.saveConfig();
    }

}
```

<p>To test i tried this:</p>

```    HashMap<String,String[]> test = loadHashMap();
    String[] a = test.get(s);

    System.out.println(a[0]);
```

<p>loadHashMap:</p>

```    public HashMap<String, String[]> loadHashMap() {
    HashMap<String, String[]> hm = new HashMap<String,String[]>();
    for (String key : plugin.getConfig().getConfigurationSection("IPs").getKeys(false)) {
        hm.put(key, (String[]) plugin.getConfig().get("IPs."+key));
        }

    return hm;
    }
```

答:
According to the gamepedia entry you should save HashMaps like this:

getConfig().createSection(String path, Map< String, Object > map)
```

<p>and retrieve them like this:</p>

<pre class="lang-java prettyprint-override"><code>getConfig().getConfigurationSection("path.to.map").getValues(false)
</code>```

You then need to cast the map to the types you want.

Body:
so i've been trying to make an alt detection plugin in bukkit, i'm pretty new to the api and haven't coded in a good bit but i'm not sure on how to make it work, i've tried hashmaps and i've tried other stuff too but i still don't quite understand how to do it, Basically i'm trying to get the IP of anyone that joins that isn't already in the config and put his ip there including with his IP, and then just check if his alt joins by seeing if he has the same ip as stored already, and add him to the list of usernames that are related to the IP

I thought at the start i could do something like this:

String ip = event.getAddress().toString().replaceAll("/", "");
plugin.getConfig().set("IPs.", ip);
plugin.saveConfig();
if(plugin.getConfig().getString("IPs.") == s) {
    if(plugin.getConfig().get("IPs." + ip) == player.getName()) {
        plugin.getConfig().set("IPs." + s, player.getName());
        plugin.saveConfig();
    }
}

but i've realized I can't so i thought of trying to make a String list, and adding the list of IPs in the config, and then i realized I would need to do a weird List of lists even i technically can't then store the ip of someone and check the list of names they have since i can't check if there's a list in the name of his IP

I got really confused here, would love some help!
Thanks!

EDIT 1 My HashMap code i used:

 // s is the ip string
    HashMap<String,String[]> map = new HashMap<String,String[]>();
                String[] names = new String[10];
                names[0] = player.getName();
                map.put(s, names);
                saveHashMap(map);

saveHashMap:

public void saveHashMap(HashMap<String, String[]> hm) {

    for (String key : hm.keySet()) {
        plugin.getConfig().set("IPs."+key, hm.get(key));
        }
            plugin.saveConfig();
    }

}

To test i tried this:

    HashMap<String,String[]> test = loadHashMap();
    String[] a = test.get(s);

    System.out.println(a[0]);

loadHashMap:

    public HashMap<String, String[]> loadHashMap() {
    HashMap<String, String[]> hm = new HashMap<String,String[]>();
    for (String key : plugin.getConfig().getConfigurationSection("IPs").getKeys(false)) {
        hm.put(key, (String[]) plugin.getConfig().get("IPs."+key));
        }

    return hm;
    }

Body:
According to the gamepedia entry you should save HashMaps like this:

getConfig().createSection(String path, Map< String, Object > map)

and retrieve them like this:

getConfig().getConfigurationSection("path.to.map").getValues(false)

You then need to cast the map to the types you want.


问:
AttributeError: module 'matplotlib' has no attribute 'interactive'
When using %matplotlib inline in Jupyter  notebook I'm getting error:

AttributeError: module 'matplotlib' has no attribute 'interactive'

This is the issue.

I have also reffered to this issue in stackoverflow
but I could not find the answer.

I tried this :

```<code>%matplotlib --list
</code>```

and found this :

Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'wx', 'qt4', 'qt5', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']

It shows, that I have inline in my matplotlib but couldnot use it.

I have also tried :

```<code>import matplotlib.pyplot as plt
</code>```

without using %matplotlib inline but found this error instead :

ModuleNotFoundError: No module named 'matplotlib.pyplot'

Then, I tried to install this module in my conda venv and got this error :
error
please help me out :)

答:
Solution for me was to remove matplot lib from my conda environment which forced dependencies to be removed as well.
After running installation again :

```<code>conda install -c conda-forge matplotlib
</code>```

all worked well.

Body:
When using %matplotlib inline in Jupyter  notebook I'm getting error:

AttributeError: module 'matplotlib' has no attribute 'interactive'

This is the issue.

I have also reffered to this issue in stackoverflow
but I could not find the answer.

I tried this :

%matplotlib --list

and found this :

Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'wx', 'qt4', 'qt5', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']

It shows, that I have inline in my matplotlib but couldnot use it.

I have also tried :

import matplotlib.pyplot as plt

without using %matplotlib inline but found this error instead :

ModuleNotFoundError: No module named 'matplotlib.pyplot'

Then, I tried to install this module in my conda venv and got this error :
error
please help me out :)

Body:
Solution for me was to remove matplot lib from my conda environment which forced dependencies to be removed as well.
After running installation again :

conda install -c conda-forge matplotlib

all worked well.


问:
Googlemaps Api weird behavior
I decided to have a play around with googlemaps and the ISS api to build a basic tracker. I plan on adding a bunch of stuff to this but for now this is kept simple.

The problem i am having is, i can set dummy values in the asp:Labels for Latitude & Longitude then populate a string with them that i can use with google maps.

```<code>var ISS = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };
</code>```

This works, when i then try use the values i get from the json callback even though i can see these when i use console.log(), they do not work.

```<code>ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] };
</code>```

I have tried instead of reading directly adding back to the asp:Label's then reading however it does not work either.

What am i doing wrong? I have tried not to add any complexity to this while i toy with googlemaps api but this not working is confusing me as i dont see whats different with dummy values vs what i get from an api.

Below is all my code for this page.

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ISS.aspx.cs" Inherits="WebApps.IIS" %>

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <head runat="server">
        <title>ISS Tracker</title>
        <style>
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
          #pageTitle{
              margin: auto;
              padding: 10px;
          }
        </style>
    </head>
    <body>
        <div id="pageTitle">
            <h3>ISS Tracker</h3>
            <h4>International Space Station</h4>
        </div>
        <form runat="server">
            <label>Latitude: </label><asp:Label runat="server" ID="lblLat"/><br />
            <label>Longitude: </label><asp:Label runat="server" ID="lblLong"/><br />
            <label>Time: </label><asp:Label runat="server" ID="lblTime" Text="13/02/2020 15:45:00" /><br />
            <asp:Button runat="server" ID="btnRefresh" Text="Refresh" onClick="btnRefresh_Click" style="height: 26px" />
            <div id="map"></div>
        </form>
        <script>

            //globals
            var map;
            var ISS;// = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };
            var image = 'http://icons.iconarchive.com/icons/goodstuff-no-nonsense/free-space/256/international-space-station-icon.png'

            // Initialize and add the map
            function initMap() {
                // The location of ISS
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] };
                    console.log("latitude: " + data['iss_position']['latitude'] + " & longitude: " + data['iss_position']['longitude']);
                    document.getElementById('lblLat').innerText = data['iss_position']['latitude'];
                    document.getElementById('lblLong').innerText = data['iss_position']['longitude'];
                });
                // The map, centered at ISS
                map = new google.maps.Map(
                    document.getElementById('map'), { zoom: 10, center: ISS });
                // The marker, positioned at ISS
                var marker = new google.maps.Marker({
                    position: ISS,
                    map: map,
                    icon: {
                        url: image,
                        scaledSize: new google.maps.Size(128, 128),
                        size: new google.maps.Size(128, 128)
                    }
                });
                marker.position = ISS;

            }

            //Will use later when i want to update
            function moveISS() {
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    var lat = data['iss_position']['latitude'];
                    var lon = data['iss_position']['longitude'];
                    ISS = { lat: lat, lng: lon };
                    document.getElementById('lblLat').innerText = lat;
                    document.getElementById('lblLong').innerText = lon;
                });
                setTimeout(moveISS, 5000);
            }
        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=*****api key *****&callback=initMap">
        </script>
    </body>
</html>
</code>```

答:
Looks like you don't understand something about JS API calls.
When you call  $.getJSON you have callback method which will have a result when data was loaded.
So when you create marker you don't have defined IIS lat/lng coordinates.
Another interesting thing about JS that you must to know - JS is a synchronous language, so your callback will be executed after all operations were done (your last line for the script - marker.position = ISS; ).
Just create a marker in your $.getJSON callback to make it work

I created a working demo which fixes some other errors which are present.

here i display start location - you must convert coordinates to number type:

```<code>function initMap() {
            // The location of ISS
            $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                ISS = new google.maps.LatLng(Number(data.iss_position.latitude), Number(data.iss_position.longitude));
                console.log("latitude: " + data['iss_position']['latitude'] + " & longitude: " + data['iss_position']['longitude']);
                document.getElementById('lblLat').value = data['iss_position']['latitude'];
                document.getElementById('lblLong').value = data['iss_position']['longitude'];

                // The map, centered at ISS
            map = new google.maps.Map(
                document.getElementById('map'), { zoom: 10, center: ISS });
            // The marker, positioned at ISS
            marker = new google.maps.Marker({
                position: ISS,
                map: map,
                icon: {
                    url: image,
                    scaledSize: new google.maps.Size(128, 128),
                    size: new google.maps.Size(128, 128)
                }
            });

            });
        }
</code>```

move marker code (use google classes for location new google.maps.LatLng) :

```<code>function moveISS() {
            $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                ISS = new google.maps.LatLng(Number(data.iss_position.latitude), Number(data.iss_position.longitude));
                document.getElementById('lblLat').value = data.iss_position.latitude;
                document.getElementById('lblLong').value = data.iss_position.longitude;
                marker.setPosition(ISS);
                map.setCenter(ISS);
            });

            setTimeout(moveISS, 5000);
        }
</code>```

http://jsfiddle.net/cheaterr/41h7tmqb/11/

Title: Googlemaps Api weird behavior

Body:
I decided to have a play around with googlemaps and the ISS api to build a basic tracker. I plan on adding a bunch of stuff to this but for now this is kept simple.

The problem i am having is, i can set dummy values in the asp:Labels for Latitude & Longitude then populate a string with them that i can use with google maps.

var ISS = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };

This works, when i then try use the values i get from the json callback even though i can see these when i use console.log(), they do not work.

ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] };

I have tried instead of reading directly adding back to the asp:Label's then reading however it does not work either.

What am i doing wrong? I have tried not to add any complexity to this while i toy with googlemaps api but this not working is confusing me as i dont see whats different with dummy values vs what i get from an api.

Below is all my code for this page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ISS.aspx.cs" Inherits="WebApps.IIS" %>

<!DOCTYPE html>

        <title>ISS Tracker</title>

ISS Tracker

International Space Station

        <form runat="server">
            Latitude: <asp:Label runat="server" ID="lblLat"/>

            Longitude: <asp:Label runat="server" ID="lblLong"/>

            Time: <asp:Label runat="server" ID="lblTime" Text="13/02/2020 15:45:00" />

            <asp:Button runat="server" ID="btnRefresh" Text="Refresh" onClick="btnRefresh_Click" style="height: 26px" />

        </form>

Body:
Looks like you don't understand something about JS API calls.
When you call  $.getJSON you have callback method which will have a result when data was loaded.
So when you create marker you don't have defined IIS lat/lng coordinates.
Another interesting thing about JS that you must to know - JS is a synchronous language, so your callback will be executed after all operations were done (your last line for the script - marker.position = ISS; ).
Just create a marker in your $.getJSON callback to make it work

I created a working demo which fixes some other errors which are present.

here i display start location - you must convert coordinates to number type:

function initMap() {
            // The location of ISS
            $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                ISS = new google.maps.LatLng(Number(data.iss_position.latitude), Number(data.iss_position.longitude));
                console.log("latitude: " + data['iss_position']['latitude'] + " & longitude: " + data['iss_position']['longitude']);
                document.getElementById('lblLat').value = data['iss_position']['latitude'];
                document.getElementById('lblLong').value = data['iss_position']['longitude'];

                // The map, centered at ISS
            map = new google.maps.Map(
                document.getElementById('map'), { zoom: 10, center: ISS });
            // The marker, positioned at ISS
            marker = new google.maps.Marker({
                position: ISS,
                map: map,
                icon: {
                    url: image,
                    scaledSize: new google.maps.Size(128, 128),
                    size: new google.maps.Size(128, 128)
                }
            });

            });
        }

move marker code (use google classes for location new google.maps.LatLng) :

function moveISS() {
            $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                ISS = new google.maps.LatLng(Number(data.iss_position.latitude), Number(data.iss_position.longitude));
                document.getElementById('lblLat').value = data.iss_position.latitude;
                document.getElementById('lblLong').value = data.iss_position.longitude;
                marker.setPosition(ISS);
                map.setCenter(ISS);
            });

            setTimeout(moveISS, 5000);
        }

http://jsfiddle.net/cheaterr/41h7tmqb/11/


问:
Problem connecting to my email with a Centos7 server
I developed a simple code, with the php language, to connect to my email and count the number of emails received, using the local Window 10 server.

```<code><?php
// server IMAP per la connessione
$server = "{imap.gmail.com:993/ssl/novalidate-cert}";

// account Gmail
$login = 'login@gmail.com';
// password per l'accesso a Gmail
$password = 'password';

// connessione IMAP ad un account Gmail
$connessione = imap_open($server, $login, $password);

$conteggio = imap_num_msg($connessione);

echo $conteggio."<br>";
</code>```

By enabling the IMAP protocol on Gmail and enabling access to less secure apps, the code does
not give any kind of error.

The problem arises when I try to execute this code into a Centos 7 server machine.
I installed the IMAP protocol compatible with my PHP 7.3 version, using this command line: yum --enablerepo=centos-sclo-sclo-testing install sclo-php73-php-imapservice imapd restart.
Once the package is successfully downloaded, I restart the server machine and go check on

```<code><?php

phpinfo();

?>
</code>```

and notice that the IMAP is enabled.

```<code>imap
IMAP c-Client Version   2007f
SSL Support enabled
Kerberos Support    enabled
</code>```

After this check, if I try to run my initial code, this error message appears to me on output: warning: imap_open(): couldn’t open stream {imap.gmail.com:993/ssl/novalidate-cert} even though i have enabled imap and by actvaing.

PS. the password and login are correct.

答:
The issue doesn't seem to be PHP related, but connection related, especially if the script works on a different machine.

There are two things you need to check.

Can you outbound connect on port 993 (is it open for OUT connections). You can try telnet to check that and if it doesn't work verify your Linux Firewall settings.

Do you have SELinux enabled and if you do did you check your audit log for AVC denials? It you have issues you may need to enable your httpd_can_network_connect or even do an audit2allow as the port might be non-standard. Be careful what you are doing as you can disrupt security on your server.

Body:
I developed a simple code, with the php language, to connect to my email and count the number of emails received, using the local Window 10 server.

<?php
// server IMAP per la connessione
$server = "{imap.gmail.com:993/ssl/novalidate-cert}";

// account Gmail
$login = 'login@gmail.com';
// password per l'accesso a Gmail
$password = 'password';

// connessione IMAP ad un account Gmail
$connessione = imap_open($server, $login, $password);

$conteggio = imap_num_msg($connessione);

echo $conteggio."
";

By enabling the IMAP protocol on Gmail and enabling access to less secure apps, the code does
not give any kind of error.

The problem arises when I try to execute this code into a Centos 7 server machine.
I installed the IMAP protocol compatible with my PHP 7.3 version, using this command line: yum --enablerepo=centos-sclo-sclo-testing install sclo-php73-php-imapservice imapd restart.
Once the package is successfully downloaded, I restart the server machine and go check on

<?php

phpinfo();

?>

and notice that the IMAP is enabled.

imap
IMAP c-Client Version   2007f
SSL Support enabled
Kerberos Support    enabled

After this check, if I try to run my initial code, this error message appears to me on output: warning: imap_open(): couldn’t open stream {imap.gmail.com:993/ssl/novalidate-cert} even though i have enabled imap and by actvaing.

PS. the password and login are correct.


问:
How do I rename both a Git local and remote branch name?
I have a local branch master that points to a remote branch origin/regacy (oops, typo!).

How do I rename the remote branch to origin/legacy or origin/master?

I tried:

```<code>git remote rename regacy legacy
</code>```

But this gave an error:

error : Could not rename config section 'remote.regacy' to 'remote.legacy'

答:
Attaching a Simple Snippet for renaming your current branch (local and on origin):

```<code>git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>
</code>```

Explanation from git docs:

git branch -m or -M option,  will be renamed to
  . If  had a corresponding reflog, it is renamed
  to match , and a reflog entry is created to remember the
  branch renaming. If  exists, -M must be used to force the
  rename to happen.

The special refspec : (or +: to allow non-fast-forward updates)
  directs Git to push "matching" branches: for every branch that exists
  on the local side, the remote side is updated if a branch of the same
  name already exists on the remote side.

--set-upstream
  Set up 's tracking information so  is considered 's upstream branch. If no  is specified, then it defaults to the current branch.

Body:
I have a local branch master that points to a remote branch origin/regacy (oops, typo!).

How do I rename the remote branch to origin/legacy or origin/master?

I tried:

git remote rename regacy legacy

But this gave an error:

error : Could not rename config section 'remote.regacy' to 'remote.legacy'

Body:
Attaching a Simple Snippet for renaming your current branch (local and on origin):

git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>

Explanation from git docs:

git branch -m or -M option,  will be renamed to
  . If  had a corresponding reflog, it is renamed
  to match , and a reflog entry is created to remember the
  branch renaming. If  exists, -M must be used to force the
  rename to happen.

The special refspec : (or +: to allow non-fast-forward updates)
  directs Git to push "matching" branches: for every branch that exists
  on the local side, the remote side is updated if a branch of the same
  name already exists on the remote side.

--set-upstream
  Set up 's tracking information so  is considered 's upstream branch. If no  is specified, then it defaults to the current branch.


答:
Instead of multiple arguments you can change how getBooks work and pass an object instead

```<code>getBooks({ page, count, authorId })
</code>```

you can now just pass the authorId if you need

```<code>getBooks({ authorId: 'authorIdPassed' });
</code>```

Title: pass specific parameter to a function

Body:
Instead of multiple arguments you can change how getBooks work and pass an object instead

getBooks({ page, count, authorId })

you can now just pass the authorId if you need

getBooks({ authorId: 'authorIdPassed' });


问:
Checking membership in an array without for loop in matlab
I want to simplify this code to working without for loop.

```<code>for i=1:N
    for j=1:N
        if ismember(j,A)

           PID(i,i)=TFP(i,j)+ PID(i,i);

        end
    end
end
</code>```

in which A is a matrix that contains some labels. I previously stored TFP in the form of N*N sparse double. So, I came up with the following solution but I couldn't find a way to implement membership condition (Specified by ?) in that.

```<code>PID = sum(TFP).*(?);
</code>```

Can it be implemented without a loop?

答:
Your ismember(j,A) is equivalent of just using the values of A to index. So you can use that and completely avoid the ismember function (which is by far the slowest part of the code).

So a first step for optimization is

```<code>A2=unique(A); % just in case you do not do this already
for i=1:N
    for j=A2
        PID(i,i)=TFP(i,j)+ PID(i,i);
    end
end
</code>```

This should be already very fast. Loops are not bad in MATLAB and get heavily optimized by the JIT compiler.

The next step to optimization is to get all the indices together and remove the secondary loop. You can do this with linear indexing, so

```<code>A2=unique(A); % just in case you do not do this already
for i=1:N
    PID(i,i)=sum(TFP(i,A2));
end
</code>```

And finally, you can get rid of this by diagonalizing the sum of the desired columns:

```<code>A2=unique(A); % just in case you do not do this already
PID=diag(sum(TFP(:,A2),2));
</code>```

Body:
I want to simplify this code to working without for loop.

for i=1:N
    for j=1:N
        if ismember(j,A)

           PID(i,i)=TFP(i,j)+ PID(i,i);

        end
    end
end

in which A is a matrix that contains some labels. I previously stored TFP in the form of N*N sparse double. So, I came up with the following solution but I couldn't find a way to implement membership condition (Specified by ?) in that.

PID = sum(TFP).*(?);

Can it be implemented without a loop?

Body:
Your ismember(j,A) is equivalent of just using the values of A to index. So you can use that and completely avoid the ismember function (which is by far the slowest part of the code).

So a first step for optimization is

A2=unique(A); % just in case you do not do this already
for i=1:N
    for j=A2
        PID(i,i)=TFP(i,j)+ PID(i,i);
    end
end

This should be already very fast. Loops are not bad in MATLAB and get heavily optimized by the JIT compiler.

The next step to optimization is to get all the indices together and remove the secondary loop. You can do this with linear indexing, so

A2=unique(A); % just in case you do not do this already
for i=1:N
    PID(i,i)=sum(TFP(i,A2));
end

And finally, you can get rid of this by diagonalizing the sum of the desired columns:

A2=unique(A); % just in case you do not do this already
PID=diag(sum(TFP(:,A2),2));


问:
how to pass screen.height & screen.width in vue test case | Jest Framework
I have used screen.height & screen.width for js operations. I can't able to pass the test case. (code coverage). I am using vue utils - Jest framework.
below My js code

```<code>const clientWidth = this.clientWidth ? this.clientWidth : screen.width;
const clientHeight = this.clientHeight ? this.clientHeight : screen.height;
</code>```

Below what i have tried in my test case

```<code>it('should set the height of window screen', () =>{
    Object.defineProperty(HTMLElement.prototype, 'screen', {
    height: {
        value: 100,
    }
    configurable: true,
});
</code>```

How to write test case for this scenario.

答:
In this case screen is window.screen, which is an instance of window.Screen. In both browsers and Jest's simplified DOM implementation (jsdom) it consists of read-only properies that are implemented with property descriptors.

Either screen property can be mocked on window object with Object.defineProperty, or width and height can be mocked separately on either Screen.prototype or screen with Object.defineProperty.

Mocking a property with Jest spy allows for automatic clean-up after each test without restoring property descriptors in afterEach, also reduces the boilerplate caused by the use of Object.defineProperty manually:

```<code>jest.spyOn(screen, 'height', 'get').mockReturnValue(100);
expect(screen.height).toBe(100);
// evaluate piece of code that uses `screen`
</code>```

Body:
I have used screen.height & screen.width for js operations. I can't able to pass the test case. (code coverage). I am using vue utils - Jest framework.
below My js code

const clientWidth = this.clientWidth ? this.clientWidth : screen.width;
const clientHeight = this.clientHeight ? this.clientHeight : screen.height;

Below what i have tried in my test case

it('should set the height of window screen', () =>{
    Object.defineProperty(HTMLElement.prototype, 'screen', {
    height: {
        value: 100,
    }
    configurable: true,
});

How to write test case for this scenario.

Body:
In this case screen is window.screen, which is an instance of window.Screen. In both browsers and Jest's simplified DOM implementation (jsdom) it consists of read-only properies that are implemented with property descriptors.

Either screen property can be mocked on window object with Object.defineProperty, or width and height can be mocked separately on either Screen.prototype or screen with Object.defineProperty.

Mocking a property with Jest spy allows for automatic clean-up after each test without restoring property descriptors in afterEach, also reduces the boilerplate caused by the use of Object.defineProperty manually:

jest.spyOn(screen, 'height', 'get').mockReturnValue(100);
expect(screen.height).toBe(100);
// evaluate piece of code that uses `screen`


答:
You could pass an object rather the fixed parameters and destructure it by using ES6 Object destructuring

Example.

```<code>getBooks({ page, count, authorId }){
  return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
    .then(response => {
        return response.data
    })
}

getBooks({ authorId: 45});
getBooks({ page: 'abc', authorId: 67});
</code>```

Title: pass specific parameter to a function

Body:
I have a function:

getBooks(page, count, authorId){
      return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
        .then(response => {
            return response.data
        })
}

I am implementing search function and in search I pass only the authorId  i.e

getBooks(akdjh23)

But on doing this it sets akdjh23 to page. i.e page=akdjh23 but I want authorId=akdjh23

My question is how do I send only authorId during search and page and count on general get request.

Search based on id:

getBooks(id)

Get all books:

get(1, 40) -> page=1, count=40

Body:
You could pass an object rather the fixed parameters and destructure it by using ES6 Object destructuring

Example.

getBooks({ page, count, authorId }){
  return API.get('/books/?page=' +page + '&count='+count+ '&author='+ authorId})
    .then(response => {
        return response.data
    })
}

getBooks({ authorId: 45});
getBooks({ page: 'abc', authorId: 67});


问:
Modify RDS change Microsoft SQL Server license type
I'm about to set up Microsoft SQL Server on RDS.
In the future we are going to use Standard License to get advantage of Multi-AZ replication. But we want to avoid costs in the earlier stage and go with Express Edition for now.

Is it possible to modify RDS and change license from Express to Standard later?

答:
If someone else is looking for the answer. I got reply from aws support:

It would not be possible to change your SQL Server licence from Express to Standard by modifying the RDS instance. If you would like to upgrade your SQL Server instance to begin using Standard Edition, you will need to take a snapshot of the Express Edition instance, and restore it as a new instance using Standard Edition.

I would be happy to outline a way you can do this below:

Take a snapshot of your SQL Server DB instance that you want to
upgrade to Standard Edition. If you are unsure on how to do this, I
can provide this documentation which explains how to do this:
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateSnapshot.html

When the snapshot has been created select the snapshot and click 'Actions', then click 'Restore Snapshot'.

Next, you will be brought to the Restore Snapshot screen. Under the DB engine heading, you can then select 'Microsoft SQL Server Standard Edition' option.

When you are happy with the configuration of the new Standard Edition instance, click 'Restore DB Instance'.


问:
Is there any way to change the directions left to right in Slick carousel ? Default it goes Right to left directions
When I set rtf fasle then the page goes white and when I set slidesToScroll- 1 it also trhoughs same result.</p>

```<code>$('.demo').slick({
    dots: false,
    slidesToShow: 3,
    slidesToScroll: 1,
    infinite: true,
    cssEase: 'linear',

    accessibility:true,

    autoplay:true,
    autoplaySpeed: 3000,

  });
</code>```

答:
Add the rtl option when you initialize slick and set it to true.  You'll also need to set the attribute "dir" to "rtl" for the HTML tag or the parent of the slider.</p>

```<code>$('.demo').slick({
  dots: false,
  slidesToShow: 3,
  slidesToScroll: 1,
  infinite: true,
  cssEase: 'linear',
  accessibility:true,
  autoplay:true,
  autoplaySpeed: 3000,
  rtl: true
});
</code>```

Body:
When I set rtf fasle then the page goes white and when I set slidesToScroll- 1 it also trhoughs same result.

$('.demo').slick({
    dots: false,
    slidesToShow: 3,
    slidesToScroll: 1,
    infinite: true,
    cssEase: 'linear',

    accessibility:true,

    autoplay:true,
    autoplaySpeed: 3000,

  });

Body:
Add the rtl option when you initialize slick and set it to true.  You'll also need to set the attribute "dir" to "rtl" for the HTML tag or the parent of the slider.

$('.demo').slick({
  dots: false,
  slidesToShow: 3,
  slidesToScroll: 1,
  infinite: true,
  cssEase: 'linear',
  accessibility:true,
  autoplay:true,
  autoplaySpeed: 3000,
  rtl: true
});


问:
Ionic/Cordova/Phonegap: Is there a way to disable Emoji-Keyboard on iOS and Android?
Is there a way to allow the ASCII-keyboard only, on iOS and Android?
I'm using the Ionic framework.

I'm not able to find any information regarding this question on the internet. I just found some native solutions.

Body:
i've used this piece of code,to restrict the entries of emoji

this.message_text = e.target.value
      .replace(
        /(?:[\u2700\-\u27bf]|(?:\ud83c[\udde6\-\uddff]){2}|[\ud800\-\udbff][\udc00\-\udfff]|[\u0023\-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70\-\udd71]|\ud83c[\udd7e\-\udd7f]|\ud83c\udd8e|\ud83c[\udd91\-\udd9a]|\ud83c[\udde6\-\uddff]|\ud83c[\ude01\-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32\-\ude3a]|\ud83c[\ude50\-\ude51]|\u203c|\u2049|[\u25aa\-\u25ab]|\u25b6|\u25c0|[\u25fb\-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600\-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9\-\u23f3]|[\u23f8\-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190\-\u21ff]|[\uE000\-\uF8FF]|\uD83C[\uDF00\-\uDFFF]|\uD83D[\uDC00\-\uDDFF])/g,
        ""
      )
      .replace(
        /[^A-Za-z0-9\w\.,\?""!@#\$%\^&\*\(\)\-_=\+;:<>\/\\\|\}\{\[\]`~\s\']*/g,
        ""
      );

      let regExp = new RegExp('^[A-Za-z0-9?@$,.*%#!=+:&;"`~_ ]+$');
      if (! regExp.test(this.message_text)) {
        e.target.value = this.message_text.slice(0, -1);
      }

It disables the emoji from keyboard but i've got one issue let's see whether you guys notice it! if u notice it kindly reply back with a solution for it!


答:
I am not sure i completely uderstand your problem
Have you tried this?

```<code>j=1:N;
PID = sum(TFP).*ismember(j,A);
</code>```

ismember would work as a matrix that when is true is equal to'1' so it would allow to multiply.

Title: Checking membership in an array without for loop in matlab

Body:
I am not sure i completely uderstand your problem
Have you tried this?

j=1:N;
PID = sum(TFP).*ismember(j,A);

ismember would work as a matrix that when is true is equal to'1' so it would allow to multiply.


问:
Find item by key in Javascript
Quick rookie question please.

Suppose I have a javsacript object like so:

```<code>var meh=[["cars",27], ["bikes",85], ["skates",4]];
</code>```

To go through each data object here, I can do this:

```<code>$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });
</code>```

And considering I know the place of, say, cars, I can do this to access it:

```<code>console.log(meh[0][0]) //shows "Cars"
</code>```

and of course, if I want the value of cars, I need to do this:

```<code>console.log(meh[0][1]) //Shows 27
</code>```

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

答:
If you can't alter the object, you can create a map to make managing the indices simple. E.g.

```<code>map = {
  'cars': 0,
  'bikes': 1,
  'skates': 2
};
</code>```

Then, you can do:

```<code>alert(meh[map['cars']][1]);
</code>```

Title: Find item by key in Javascript

Body:
Quick rookie question please.

Suppose I have a javsacript object like so:

var meh=[["cars",27], ["bikes",85], ["skates",4]];

To go through each data object here, I can do this:

$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });

And considering I know the place of, say, cars, I can do this to access it:

console.log(meh[0][0]) //shows "Cars"

and of course, if I want the value of cars, I need to do this:

console.log(meh[0][1]) //Shows 27

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

Body:
If you can't alter the object, you can create a map to make managing the indices simple. E.g.

map = {
  'cars': 0,
  'bikes': 1,
  'skates': 2
};

Then, you can do:

alert(meh[map['cars']][1]);


问:
athena.getQueryExecution returns a status of RUNNING for 1 minute+, even though history says the job took 4 seconds
I'm writing a node app using typescript and the aws-sdk to call Athena.  Occasionally, the call to Athena will timeout after a minute of waiting for the Athena response.  The thing I don't understand is that if I go to the AWS console and look at the Athena History tab, it says my query took 4 seconds to succeed, yet in my code it runs for over a minute waiting for a response.  I'm hoping there's something I'm doing wrong in my code.

```<code>myFunct... {
    const athena = getAthena();

    const startQueryExecutionResponse: StartQueryExecutionOutput = await athena.startQueryExecution(params).promise();

    let status = "UNKNOWN";
    do {
        await sleep(1000);
        status = await getQueryStatus(athena, startQueryExecutionResponse);
    } while (status === "QUEUED" || status === "RUNNING");

    return await athena.getQueryResults(startQueryExecutionResponse as GetQueryResultsInput).promise();
};

const sleep = (ms: number) => {
    return new Promise(resolve => {
        setTimeout(resolve, ms)
    })
};

const getQueryStatus = async (athena: AWS.Athena, startQueryExecutionResponse: Athena.StartQueryExecutionOutput): Promise<QueryExecutionState> => {
    const result: GetQueryExecutionOutput = await athena.getQueryExecution(startQueryExecutionResponse as GetQueryResultsInput).promise();
    console.log(result);
    return result!.QueryExecution!.Status!.State || "Unknown"
};
</code>```

The code gets stuck in that while loop, and I can see from the console.log below, that the status is Status: { State: 'RUNNING', SubmissionDateTime: 2019-07-23T18:28:00.639Z }, over and over again.

If the AWS console says this query took 4 seconds to complete, why does the getQueryExecution response say it's still RUNNING for minutes?

答:
The history in the Athena console shows execution time.  In addition to execution time, there is time in queue, planning, and service processing.  I've had queries stuck in queue for much longer than the execution time.  I think this is likely in your case.  Also, the Athena showed queued queries as "RUNNING" until recently.

More info here: AWS Athena concurrency limits: Number of submitted queries VS number of running queries

Example stats of a query stuck in queue:

```<code>"Statistics": {
  "EngineExecutionTimeInMillis": 2689,
  "DataScannedInBytes": 35347476,
  "TotalExecutionTimeInMillis": 106676,
  "QueryQueueTimeInMillis": 103971,
  "QueryPlanningTimeInMillis": 600,
  "ServiceProcessingTimeInMillis": 16
}
</code>```

Body:
I'm writing a node app using typescript and the aws-sdk to call Athena.  Occasionally, the call to Athena will timeout after a minute of waiting for the Athena response.  The thing I don't understand is that if I go to the AWS console and look at the Athena History tab, it says my query took 4 seconds to succeed, yet in my code it runs for over a minute waiting for a response.  I'm hoping there's something I'm doing wrong in my code.

myFunct... {
    const athena = getAthena();

    const startQueryExecutionResponse: StartQueryExecutionOutput = await athena.startQueryExecution(params).promise();

    let status = "UNKNOWN";
    do {
        await sleep(1000);
        status = await getQueryStatus(athena, startQueryExecutionResponse);
    } while (status === "QUEUED" || status === "RUNNING");

    return await athena.getQueryResults(startQueryExecutionResponse as GetQueryResultsInput).promise();
};

const sleep = (ms: number) => {
    return new Promise(resolve => {
        setTimeout(resolve, ms)
    })
};

const getQueryStatus = async (athena: AWS.Athena, startQueryExecutionResponse: Athena.StartQueryExecutionOutput): Promise<QueryExecutionState> => {
    const result: GetQueryExecutionOutput = await athena.getQueryExecution(startQueryExecutionResponse as GetQueryResultsInput).promise();
    console.log(result);
    return result!.QueryExecution!.Status!.State || "Unknown"
};

The code gets stuck in that while loop, and I can see from the console.log below, that the status is Status: { State: 'RUNNING', SubmissionDateTime: 2019-07-23T18:28:00.639Z }, over and over again.

If the AWS console says this query took 4 seconds to complete, why does the getQueryExecution response say it's still RUNNING for minutes?

Body:
The history in the Athena console shows execution time.  In addition to execution time, there is time in queue, planning, and service processing.  I've had queries stuck in queue for much longer than the execution time.  I think this is likely in your case.  Also, the Athena showed queued queries as "RUNNING" until recently.

More info here: AWS Athena concurrency limits: Number of submitted queries VS number of running queries

Example stats of a query stuck in queue:

"Statistics": {
  "EngineExecutionTimeInMillis": 2689,
  "DataScannedInBytes": 35347476,
  "TotalExecutionTimeInMillis": 106676,
  "QueryQueueTimeInMillis": 103971,
  "QueryPlanningTimeInMillis": 600,
  "ServiceProcessingTimeInMillis": 16
}


问:
ReactJS: useEffect is not run when the url changes
I have a ReactJS website, and I'm still a noob using it.

I've 2 Components

The first one is the / page, that must be rendered after a request to a web server, when the user get to that route, I've used useEffect for this.

The second one is the /mostraMaterie/:id that must be rendered after another request to the web server.

The first component work like a charm, whereas the second one doesn't trigger the useEffect function.

When the user clicks a button on the / component, it is redirected to /mostraMateria/:id with the according id.

The problem is the /mostraMateria component I have another useEffect function, but it is not triggered.

As suggested in the comment, this is the mostraMateria file in JSFiddle
mostraMaterie.js

App.js
handles the user connection

```<code>import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";

import Main from "./Contenuti/Main";

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/mostraMateria/:id" component={MostraMaterie} />{" "}
        <Route exact path="/" component={Main} />{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;
</code>```

Main.js
handles the page rendering if the location is / and work perfectly.

```<code>import React, { useEffect, useState } from "react";
import {  Link } from "react-router-dom";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";
import "../App.css";
import FullNavBar from "../NavBar/FullNavBar";

function Main() {
  const [indirizzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = () => {
    async function prendiIndirizzi() {
      let indirizzi = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
      );
      let ind = await indirizzi.json();

      for (let i = 0; i < ind.length; i++) {
        async function prendiMaterie() {
          let materie = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/materie.php?indirizzo=${ind[i].Indirizzo}`
          );
          materie = await materie.json();

          for (let materia of materie) {
            Object.defineProperty(
              materia,
              "nome",
              Object.getOwnPropertyDescriptor(materia, "Materia")
            );
            delete materia["Materia"];

            Object.defineProperty(
              materia,
              "id",
              Object.getOwnPropertyDescriptor(materia, "IDMateria")
            );
            delete materia["IDMateria"];
            delete materia["Indirizzo"];
          }

          Object.defineProperty(
            ind[i],
            "nome",
            Object.getOwnPropertyDescriptor(ind[i], "Indirizzo")
          );
          delete ind[i]["Indirizzo"];
          Object.assign(ind[i], { dati: materie });
          Object.assign(ind[i], { id: i });
        }

        await prendiMaterie();
      }
      console.log("Main.js", ind);
      cambiaIndirizzi(ind);
    }
    prendiIndirizzi();
  };
  useEffect(fetchIndirizzi, []);

  return (
    <React.Fragment>
      <FullNavBar elementi={indirizzi} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}
      {indirizzi.map(indirizzo => {
        console.log(indirizzo);
        return <Indirizzi dati={indirizzo} />;
      })}
    </React.Fragment>
  );
}

export default Main;
</code>```

MostraMaterie.js
handles the page rendering if the location is /mostraMaterie/:id and doesn't work.

```<code>import React, { useEffect, useState } from "react";
import "../App.css";
import history from "../Util/history";
import { Link } from "react-router-dom";
import FullNavBar from "../NavBar/FullNavBar";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";

function MostraMaterie(props) {
  const [anni, cambiaAnni] = useState([]);

  // *** this function is never called ***
  const fetchAnni = () => {
    async function prendiAnni() {
      let anniJson = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/ottieniAnni.php"
      );
      let idMateria = props.match.params.id;
      let ann = [];
      anniJson = await anniJson.json();

      for (let anno of anniJson) {
        async function prendiAnteprime() {
          let anteprimeFetch = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/anteprima.php?idMateria=${idMateria}&anno=${anno}`
          );

          anteprimeFetch = await anteprimeFetch.json();
          for (let anteprima of anteprimeFetch) {
            Object.defineProperty(
              anteprima,
              "nome",
              Object.getOwnPropertyDescriptor(anteprima, "Titolo")
            );

            Object.defineProperty(
              anteprima,
              "id",
              Object.getOwnPropertyDescriptor(anteprima, "ID")
            );
            delete anteprima["Titolo"];
            delete anteprima["ID"];
          }

          let annoOggetto = {
            nome: anno + "",
            anteprime: anteprimeFetch
          };
          ann.push(annoOggetto);
        }

        await prendiAnteprime();
      }
      debugger;
      cambiaAnni(ann);
    }
    console.log("Vengo eseguito");
    prendiAnni();
  };

  useEffect(fetchAnni, []);
  console.log(history.location);

  return (
    <React.Fragment>
      <FullNavBar indirizzi={anni} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}
      <h1> CIao CIAO CIAO CIAOC </h1>{" "}
      {
        //*** this depends on the response of the web server ***
         anni.map(anno => {
              console.log("Ciao");
              return <Indirizzi dati={anno} />;
            })}{" "}
    </React.Fragment>
  );
}

export default MostraMaterie;
</code>```

How can I make this work?

Edit

I've remove the <FullNavBar indirizzi={anni} />{" "} and it works, now my request is made to the server and the ``fetchAnni``` function in fired.

The problem is, I need the piece of code I removed, it seems that the
<FullNavBar indirizzi={anni} />{" "} is rendered before the call of fetchAnni, even adding the await prendiAnni and async fetchAnni  as suggested by Artur doesn't work.

I've also changed from useEffect(fetchAnni, []); to useEffect(fetchAnni, [props.location.pathname]); that is a string

答:
Second useEffect arg [] :

First of all: Sending a [] as second arg of useEffect will say "NEVER RE-RUN this function" (only 2times, on mount and on unmount).

Removing it ! it's NO :

You do not want to remove it or your effect will be called on every render and cause performances issues.

Choosing the right var(s) to track:

You have to give React all the fields who will affect the re-render of your function, in your case "when the URL change".

Hint: React will test every time if one of variable has been update since last render, but we als know that non-primitive will not works:

```<code>const a = {name: "Foo"};
const b = {name: "Foo"};
const res = (a === b); // False
</code>```

So, you have to choose for primitive values only. In your case the simplest is the /:id on your Route: props.match.params.id.

```<code>  useEffect(fetchAnni, [props.match.params.id]);
  console.log(`Render for ID: ${props.match.params.id}`);
</code>```

Async/Await

Also, you're function prendiAnni is defined as async but you call it:

```<code>console.log("Vengo eseguito");
prendiAnni();
</code>```

Instead of

```<code>await prendiAnni();
</code>```

Body:
I have a ReactJS website, and I'm still a noob using it.

I've 2 Components

The first one is the / page, that must be rendered after a request to a web server, when the user get to that route, I've used useEffect for this.

The second one is the /mostraMaterie/:id that must be rendered after another request to the web server.

The first component work like a charm, whereas the second one doesn't trigger the useEffect function.

When the user clicks a button on the / component, it is redirected to /mostraMateria/:id with the according id.

The problem is the /mostraMateria component I have another useEffect function, but it is not triggered.

As suggested in the comment, this is the mostraMateria file in JSFiddle
mostraMaterie.js

App.js
handles the user connection

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";

import Main from "./Contenuti/Main";

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/mostraMateria/:id" component={MostraMaterie} />{" "}
        <Route exact path="/" component={Main} />{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;

Main.js
handles the page rendering if the location is / and work perfectly.

import React, { useEffect, useState } from "react";
import {  Link } from "react-router-dom";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";
import "../App.css";
import FullNavBar from "../NavBar/FullNavBar";

function Main() {
  const [indirizzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = () => {
    async function prendiIndirizzi() {
      let indirizzi = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
      );
      let ind = await indirizzi.json();

      for (let i = 0; i < ind.length; i++) {
        async function prendiMaterie() {
          let materie = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/materie.php?indirizzo=${ind[i].Indirizzo}`
          );
          materie = await materie.json();

          for (let materia of materie) {
            Object.defineProperty(
              materia,
              "nome",
              Object.getOwnPropertyDescriptor(materia, "Materia")
            );
            delete materia["Materia"];

            Object.defineProperty(
              materia,
              "id",
              Object.getOwnPropertyDescriptor(materia, "IDMateria")
            );
            delete materia["IDMateria"];
            delete materia["Indirizzo"];
          }

          Object.defineProperty(
            ind[i],
            "nome",
            Object.getOwnPropertyDescriptor(ind[i], "Indirizzo")
          );
          delete ind[i]["Indirizzo"];
          Object.assign(ind[i], { dati: materie });
          Object.assign(ind[i], { id: i });
        }

        await prendiMaterie();
      }
      console.log("Main.js", ind);
      cambiaIndirizzi(ind);
    }
    prendiIndirizzi();
  };
  useEffect(fetchIndirizzi, []);

  return (
    <React.Fragment>
      <FullNavBar elementi={indirizzi} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}
      {indirizzi.map(indirizzo => {
        console.log(indirizzo);
        return <Indirizzi dati={indirizzo} />;
      })}
    </React.Fragment>
  );
}

export default Main;

MostraMaterie.js
handles the page rendering if the location is /mostraMaterie/:id and doesn't work.

import React, { useEffect, useState } from "react";
import "../App.css";
import history from "../Util/history";
import { Link } from "react-router-dom";
import FullNavBar from "../NavBar/FullNavBar";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";

function MostraMaterie(props) {
  const [anni, cambiaAnni] = useState([]);

  // *** this function is never called ***
  const fetchAnni = () => {
    async function prendiAnni() {
      let anniJson = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/ottieniAnni.php"
      );
      let idMateria = props.match.params.id;
      let ann = [];
      anniJson = await anniJson.json();

      for (let anno of anniJson) {
        async function prendiAnteprime() {
          let anteprimeFetch = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/anteprima.php?idMateria=${idMateria}&anno=${anno}`
          );

          anteprimeFetch = await anteprimeFetch.json();
          for (let anteprima of anteprimeFetch) {
            Object.defineProperty(
              anteprima,
              "nome",
              Object.getOwnPropertyDescriptor(anteprima, "Titolo")
            );

            Object.defineProperty(
              anteprima,
              "id",
              Object.getOwnPropertyDescriptor(anteprima, "ID")
            );
            delete anteprima["Titolo"];
            delete anteprima["ID"];
          }

          let annoOggetto = {
            nome: anno + "",
            anteprime: anteprimeFetch
          };
          ann.push(annoOggetto);
        }

        await prendiAnteprime();
      }
      debugger;
      cambiaAnni(ann);
    }
    console.log("Vengo eseguito");
    prendiAnni();
  };

  useEffect(fetchAnni, []);
  console.log(history.location);

  return (
    <React.Fragment>
      <FullNavBar indirizzi={anni} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}

 CIao CIAO CIAO CIAOC
{" "}
      {
        //*** this depends on the response of the web server ***
         anni.map(anno => {
              console.log("Ciao");
              return <Indirizzi dati={anno} />;
            })}{" "}
    </React.Fragment>
  );
}

export default MostraMaterie;

How can I make this work?

Edit

I've remove the <FullNavBar indirizzi={anni} />{" "} and it works, now my request is made to the server and the ``fetchAnni``` function in fired.

The problem is, I need the piece of code I removed, it seems that the
<FullNavBar indirizzi={anni} />{" "} is rendered before the call of fetchAnni, even adding the await prendiAnni and async fetchAnni  as suggested by Artur doesn't work.

I've also changed from useEffect(fetchAnni, []); to useEffect(fetchAnni, [props.location.pathname]); that is a string

Body:
Second useEffect arg [] :

First of all: Sending a [] as second arg of useEffect will say "NEVER RE-RUN this function" (only 2times, on mount and on unmount).

Removing it ! it's NO :

You do not want to remove it or your effect will be called on every render and cause performances issues.

Choosing the right var(s) to track:

You have to give React all the fields who will affect the re-render of your function, in your case "when the URL change".

Hint: React will test every time if one of variable has been update since last render, but we als know that non-primitive will not works:

const a = {name: "Foo"};
const b = {name: "Foo"};
const res = (a === b); // False

So, you have to choose for primitive values only. In your case the simplest is the /:id on your Route: props.match.params.id.

  useEffect(fetchAnni, [props.match.params.id]);
  console.log(`Render for ID: ${props.match.params.id}`);

Async/Await

Also, you're function prendiAnni is defined as async but you call it:

console.log("Vengo eseguito");
prendiAnni();

Instead of

await prendiAnni();