问:
stacking time series graph python
I want to stack the time series of SST and NickSST on 1 plot. When I try to do it simply, I get this error:

ValueError: x and y must have same first dimension, but have shapes (31,) and (0,).

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

class buoy(object):
    def __init__(self, bID):
        self.buoyID = bID
        self.dateTime = []
        self.SST = []
        self.NickSST = []

    def plotSST(self, stID):
        plotName = stID + "-" + self.buoyID
        self.fig1 = plt.figure()
        plt.ion()
        self.axis1 = self.fig1.add_subplot(1, 1, 1)
        self.axis1.plot(self.dateTime, self.SST)
        self.axis1.plot(self.dateTime, self.NickSST)
        self.axis1.set_title("Time Series for" + "" + plotName)
        self.axis1.set_xlabel("Date/Time (UTC)")
        self.axis1.set_ylabel("SST (degrees C)")
        self.fig1.savefig(plotName + ".png")
        plt.show(self.fig1)

class storm(object):
    def __init__(self, stID):
        self.stormID = stID
        self.buoyList = []
</code>```

Please tell me how I am going wrong...

答:
Looks like you have no data in either self.SST or self.NickSST.

Matplotlib expects the same number of values in both lists when you call plot(x, y)

The error is telling you that your X axis has 31 values and nothing in your Y.
Try printing the length of each array:

```<code>print(len(self.dataTime), len(self.SST), len(self.NickSST))
</code>```

Title: stacking time series graph python

Body:
I want to stack the time series of SST and NickSST on 1 plot. When I try to do it simply, I get this error:

ValueError: x and y must have same first dimension, but have shapes (31,) and (0,).

import datetime
import matplotlib.pyplot as plt

class buoy(object):
    def __init__(self, bID):
        self.buoyID = bID
        self.dateTime = []
        self.SST = []
        self.NickSST = []

    def plotSST(self, stID):
        plotName = stID + "-" + self.buoyID
        self.fig1 = plt.figure()
        plt.ion()
        self.axis1 = self.fig1.add_subplot(1, 1, 1)
        self.axis1.plot(self.dateTime, self.SST)
        self.axis1.plot(self.dateTime, self.NickSST)
        self.axis1.set_title("Time Series for" + "" + plotName)
        self.axis1.set_xlabel("Date/Time (UTC)")
        self.axis1.set_ylabel("SST (degrees C)")
        self.fig1.savefig(plotName + ".png")
        plt.show(self.fig1)

class storm(object):
    def __init__(self, stID):
        self.stormID = stID
        self.buoyList = []

Please tell me how I am going wrong...

Body:
Looks like you have no data in either self.SST or self.NickSST.

Matplotlib expects the same number of values in both lists when you call plot(x, y)

The error is telling you that your X axis has 31 values and nothing in your Y.
Try printing the length of each array:

print(len(self.dataTime), len(self.SST), len(self.NickSST))


来源: stackexchange

问:
PHP 'move_uploaded_file' getting 413 Request Entity Too Large
When trying to upload a 130mb file I get 413 Request Entity Too Large. Using Network Solutions web hosting.

I've used .htaccess:

```<code>LimitRequestBody 10485760000
</code>```

and php.ini:

```<code>memory_limit = 10000M
upload_max_filesize = 10000M
post_max_size = 10000M
</code>```

答:
In your htaccess file try to set the limit as

```<code>LimitRequestBody 150000000
</code>```

Because as per apache server it should range between 0 - 2147483647(bytes).

This may solve your problem

Refrence: Apache Server

And if then also its not working you need to set the mod_reqtimeout for apache
modules as per your file and needs

You can refer it here Apache Module mod_reqtimeout

ContentLicense: CC BY-SA 4.0

Body:
When trying to upload a 130mb file I get 413 Request Entity Too Large. Using Network Solutions web hosting.

I've used .htaccess:

LimitRequestBody 10485760000

and php.ini:

memory_limit = 10000M
upload_max_filesize = 10000M
post_max_size = 10000M

Body:
In your htaccess file try to set the limit as

LimitRequestBody 150000000

Because as per apache server it should range between 0 - 2147483647(bytes).

This may solve your problem

Refrence: Apache Server

And if then also its not working you need to set the mod_reqtimeout for apache
modules as per your file and needs

You can refer it here Apache Module mod_reqtimeout


问:
How to convert floating into hex in JMETER
how to convert the floating variable into hex in JMETER.

Any idea, thanks.

答:
There is Commons Codec library in JMeter Distribution bundle which provides Hex class which in its turn exposes encodeHex() function which you can use to convert an ASCII string into its Hex representation like:

Given you need to convert LLOP123344 string it's sufficient to call the aforementioned function like:

```<code>org.apache.commons.codec.binary.Hex.encodeHexString('LLOP123344'.getBytes('UTF-8'))
</code>```

which returns 4c4c4f50313233333434

More information: Apache Groovy - Why and How You Should Use It

Body:
There is Commons Codec library in JMeter Distribution bundle which provides Hex class which in its turn exposes encodeHex() function which you can use to convert an ASCII string into its Hex representation like:

Given you need to convert LLOP123344 string it's sufficient to call the aforementioned function like:

org.apache.commons.codec.binary.Hex.encodeHexString('LLOP123344'.getBytes('UTF-8'))

which returns 4c4c4f50313233333434

More information: Apache Groovy - Why and How You Should Use It


问:
difference between a pointer and reference parameter?
Are these the same:

```<code>int foo(bar* p) {
  return p->someInt();
}
</code>```

and

```<code>int foo(bar& r) {
  return r.someInt();
}
</code>```

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

```<code>bar& ref = *ptr_to_bar;
</code>```

答:
Reference is a constant pointer i.e., you can't change the reference to refer to other object. If you change, value of the referring object changes.

For Ex:

```<code>       int j = 10;
       int &i = j;
       int l = 20;
       i = l; // Now value of j = 20

       int *k = &j;
       k = &l;   // Value of j is still 10
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Are these the same:

int foo(bar* p) {
  return p->someInt();
}

and

int foo(bar& r) {
  return r.someInt();
}

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

bar& ref = *ptr_to_bar;

Body:
Reference is a constant pointer i.e., you can't change the reference to refer to other object. If you change, value of the referring object changes.

For Ex:

       int j = 10;
       int &i = j;
       int l = 20;
       i = l; // Now value of j = 20

       int *k = &j;
       k = &l;   // Value of j is still 10

OwnerDisplayName: Vinay

ContentLicense: CC BY-SA 2.5


问:
REGEX password validation without special characters
I am using this regex to validate my password.
My password -

should be alphanumeric ONLY,

contains at least 8 characters,

at least 2 numbers

and at least 2 alphabet.

My regex is

```<code>^.*(?=.{8,})(?=.*\d*\d)(?=.*[a-zA-Z]*[a-zA-Z])(?!.*\W).*$
</code>```

but unfortunately it still matches if I try to put special characters at the beginning.
For example @password12, !password12.

答:
You can use the following regex in case insensitive mode:

```<code>^(?=[a-z]*[0-9][a-z]*[0-9])^(?=[0-9]*[a-z][0-9]*[a-z])[a-z0-9]{8,}$
</code>```

See it

Body:
I am using this regex to validate my password.
My password -

should be alphanumeric ONLY,

contains at least 8 characters,

at least 2 numbers

and at least 2 alphabet.

My regex is

^.*(?=.{8,})(?=.*\d*\d)(?=.*[a-zA-Z]*[a-zA-Z])(?!.*\W).*$

but unfortunately it still matches if I try to put special characters at the beginning.
For example @password12, !password12.

Body:
You can use the following regex in case insensitive mode:

^(?=[a-z]*[0-9][a-z]*[0-9])^(?=[0-9]*[a-z][0-9]*[a-z])[a-z0-9]{8,}$

See it


问:
How does.format() in this code work [pandas]
I am very much a beginner in pandas posting here for some help.
I was doing an assignment on Coursera, and after I did it I tried searching stack overflow to find more compact and faster codes. Stuff I saw on here I understood but when I did a search on Google I found some code on pastebin that looked too good to be true.

Here it is

```<code>def convert_housing_data_to_quarters():
    data = pd.read_csv('City_Zhvi_AllHomes.csv')
    towns = data[['State','RegionName']]
    for yr in range(2000,2017):
        for q in range(1,12,3):
            if yr == 2016 and q == 4:
                break
            m1 = '{}-{:02d}'.format(yr,q)
            m2 = '{}-{:02d}'.format(yr,q+1)
            m3 = '{}-{:02d}'.format(yr,q+2)
            quarter = '{}q{}'.format(yr,q)
            towns[quarter] = data[[m1,m2,m3]].mean(axis=1)
    return towns
</code>```

The assignment was to read a .csv with data for each month and to make a dataframe with quarters from 2001q1 to the end each quarter has a value of the mean of the 3 months that make it up.
My solution was very normal and looking at code others wrote for this assignment it looked nearly similar.

The code linked up works for everything except that it named the columns as 20xxq1,q4,q7 and q10 instead of q1,2,3,4.
I don't understand how the code in the 2nd for loop works.

What does this syntax mean '{}-{:02d}'? I don't get this at all but it seems extremely powerful. I would love to know how to use it in the future. I saw the pandas documentation, it says you can use a dict as parameters for .format() but I really can't understand how its working here.

Thanks for any help.

答:
'{}-{:02d}'.format(yr,q) is a string formating. It returns a combination of yr and q based on respective values. Since there is no index in the {} curly bracket, yr belongs to the first and q belongs to the second curly bracket. The second part after : is the format selected. 02d means there will be two digits, with zero-padding if possible.

For more info about string formating, you can refer to this link

Body:
I am very much a beginner in pandas posting here for some help.
I was doing an assignment on Coursera, and after I did it I tried searching stack overflow to find more compact and faster codes. Stuff I saw on here I understood but when I did a search on Google I found some code on pastebin that looked too good to be true.

Here it is

def convert_housing_data_to_quarters():
    data = pd.read_csv('City_Zhvi_AllHomes.csv')
    towns = data[['State','RegionName']]
    for yr in range(2000,2017):
        for q in range(1,12,3):
            if yr == 2016 and q == 4:
                break
            m1 = '{}-{:02d}'.format(yr,q)
            m2 = '{}-{:02d}'.format(yr,q+1)
            m3 = '{}-{:02d}'.format(yr,q+2)
            quarter = '{}q{}'.format(yr,q)
            towns[quarter] = data[[m1,m2,m3]].mean(axis=1)
    return towns

The assignment was to read a .csv with data for each month and to make a dataframe with quarters from 2001q1 to the end each quarter has a value of the mean of the 3 months that make it up.
My solution was very normal and looking at code others wrote for this assignment it looked nearly similar.

The code linked up works for everything except that it named the columns as 20xxq1,q4,q7 and q10 instead of q1,2,3,4.
I don't understand how the code in the 2nd for loop works.

What does this syntax mean '{}-{:02d}'? I don't get this at all but it seems extremely powerful. I would love to know how to use it in the future. I saw the pandas documentation, it says you can use a dict as parameters for .format() but I really can't understand how its working here.

Thanks for any help.


问:
Cannot resolve symbol 'URL' in Android Studio
Why can't I use the URL class?
Android Studio does not find this class.

答:
A :

```<code> Clean Project and Rebuild
</code>```

B:

```<code>Invalidate Cach and Restart AS
</code>```

C : use java 8

```<code>compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
</code>```

Body:
A :

 Clean Project and Rebuild

B:

Invalidate Cach and Restart AS

C : use java 8

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}


问:
can I show a specific part of a page using document.getElementById(href)?
if I have a page called "content page":

```<code><body >

<p id="part1">Tread ... inch. </p>

<p id="part2">Tread ... inch. </p>

<p id="part3">Tread ... inch.</p>

</body>
</code>```

and another page with this java script(code in close icon doesn't appear ).

```<code><head>
<script type="text/javascript" src="popupBox.js"></script>
</head>
<body>

show content of part one : <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.
show content of part two : <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.
show content of part three : <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.

</body>
</code>```

if I want to retrive a specific part of a content page to be shown in the popup box, is that possible?

I mean in this part at popup.js:

```<code>var boxdiv = document.getElementById(href);
</code>```

can I specify an ID of a tag in the href of the page to retrive it? like :

```<code>var href = an.href;
var boxdiv = document.getElementById(href).getElementById("Show The content of this ID tag!");
</code>```

any idea?

答:
What you basically want, as I understood it, is to show content of a given URL in a box/container/view on your site.

There are some ways to achive this. Here are two of them:

The most recommanded is to load the
content via ajax. (The link goes
to the jQuery Ajax Documentation -
jQuery will make your live easier ;-)
)

An other way could be to use iFrames.

Body:
if I have a page called "content page":

Tread ... inch.

Tread ... inch.

Tread ... inch.

and another page with this java script(code in close icon doesn't appear ).

show content of part one : Click Here.
show content of part two : Click Here.
show content of part three : Click Here.

if I want to retrive a specific part of a content page to be shown in the popup box, is that possible?

I mean in this part at popup.js:

var boxdiv = document.getElementById(href);

can I specify an ID of a tag in the href of the page to retrive it? like :

var href = an.href;
var boxdiv = document.getElementById(href).getElementById("Show The content of this ID tag!");

any idea?


问:
Bootstrap modal: is not a function
I have a modal in my page. When I try to call it when the windows load, it prints an error to the console that says :

```<code>$(...).modal is not a function
</code>```

This is my Modal HTML :

```<code><div class="modal fade" id="prizePopup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                ×
            </button>
            <h4 class="modal-title" id="myModalLabel">
                This Modal title
            </h4>
        </div>
        <div class="modal-body">
            Add some text here
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">
                Submit changes
            </button>
        </div>
    </div>
</div>
</code>```

```<code><script type="text/javascript" src="js/bootstrap.js"></script>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</code>```

And this is my JavaScript to run it with when a window is loaded :

```<code><script type="text/javascript">
$(window).load(function() {
    $('#prizePopup').modal('show');
});
</script>
</code>```

How can I fix this problem?

答:
Use:

jQuery.noConflict();
$('#prizePopup').modal('toggle');
```

Title: Bootstrap modal: is not a function

Body:
I have a modal in my page. When I try to call it when the windows load, it prints an error to the console that says :

$(...).modal is not a function

This is my Modal HTML :

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                ×
            </button>

                This Modal title

            Add some text here

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">
                Submit changes
            </button>

And this is my JavaScript to run it with when a window is loaded :

How can I fix this problem?


问:
Number of occurrences of an element in a 2d-array c++
If I'm given a 2d array say {{1,2},{2,3,4},{5,1,2,7}}, how do I count how many times an element say 1 has occurred in the array?
Is there any c++ STL function for this?

答:
If this is a "normal" 2D array, where the data is stored in contiguous memory, then usage of std::count is all that's required if you give it the start and ending location in memory.

```<code>#include <algorithm>
#include <iostream>
//...
int main()
{
   const int m=10;
   const int n=20;
   int arr[m][n] = {0};
   arr[0][0] = 1;
   arr[m-1][n-1] = 1;
   std::cout << "The number of 1's is " << std::count(&arr[0][0], &arr[m-1][n], 1);
}
</code>```

Output:

```<code>The number of 1's is 2
</code>```

Body:
If this is a "normal" 2D array, where the data is stored in contiguous memory, then usage of std::count is all that's required if you give it the start and ending location in memory.

#include <algorithm>
#include <iostream>
//...
int main()
{
   const int m=10;
   const int n=20;
   int arr[m][n] = {0};
   arr[0][0] = 1;
   arr[m-1][n-1] = 1;
   std::cout << "The number of 1's is " << std::count(&arr[0][0], &arr[m-1][n], 1);
}

Output:

The number of 1's is 2


问:
How to get logs from kubernetes using Go?
I'm looking for the solution of how to get logs from a pod in Kubernetes cluster using Go. I've looked at "https://github.com/kubernetes/client-go" and "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client", but couldn't understand how to use them for this purpose. I have no issues getting information of a pod or any other object in K8S except for logs.

For example, I'm using Get() from "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client#example-Client--Get" to get K8S job info:

```<code>found := &batchv1.Job{}
err = r.client.Get(context.TODO(), types.NamespacedName{Name: job.Name, Namespace: job.Namespace}, found)
</code>```

Please share of how you get pod's logs nowadays.
Any suggestions would be appreciated!

Update:
The solution provided in Kubernetes go client api for log of a particular pod is out of date. It have some tips, but it is not up to date with current libraries.

答:
@Emixam23

I believe you will find this snippet useful.

How to get the dynamic name of a pod?

```<code>import  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

    labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{<LABEL_KEY>: <LABEL_VALUE>}}
    listOptions := metav1.ListOptions{
        LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
    }
    pod, err := k8sClient.CoreV1().Pods(<NAMESPACE>).List(listOptions)
    podName := pod.Items[0].ObjectMeta.Name
</code>```

Body:
I'm looking for the solution of how to get logs from a pod in Kubernetes cluster using Go. I've looked at "https://github.com/kubernetes/client-go" and "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client", but couldn't understand how to use them for this purpose. I have no issues getting information of a pod or any other object in K8S except for logs.

For example, I'm using Get() from "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client#example-Client--Get" to get K8S job info:

found := &batchv1.Job{}
err = r.client.Get(context.TODO(), types.NamespacedName{Name: job.Name, Namespace: job.Namespace}, found)

Please share of how you get pod's logs nowadays.
Any suggestions would be appreciated!

Update:
The solution provided in Kubernetes go client api for log of a particular pod is out of date. It have some tips, but it is not up to date with current libraries.

Body:
@Emixam23

I believe you will find this snippet useful.

How to get the dynamic name of a pod?

import  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

    labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{<LABEL_KEY>: <LABEL_VALUE>}}
    listOptions := metav1.ListOptions{
        LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
    }
    pod, err := k8sClient.CoreV1().Pods(<NAMESPACE>).List(listOptions)
    podName := pod.Items[0].ObjectMeta.Name


问:
Sum, Average of elements and Count the occurence of elements in Lists in Prolog
how can I write three predicates in Prolog that do the following things:

1) Define the sum (X, N) predicate, which is true when N is the sum of integers from the list X.

2) Define the avg (X, N) predicate that calculates the arithmetic average of all elements of the list X, where N is the number of elements.

3) Define the predicate called count(X, Y, N), which is true if the list Y contains N element instances
X.

Could you give me the examples of them and explain to me why they work the way they do? I know there are dozens of sum and avg predicates here on Stack Overflow, but I can't really understand why they work.

答:
Define the sum(X, N) predicate, which is true when N is the sum of integers from the list X.

You want to calculate the sum of the elements of a list. What would be the simplest instance of the problem? When the list is empty, the sum of its element is 0. How can we break down larger lists to get to the simple case? We can remove the first element of the list, calculate the sum of the remaining list, and then add the first element to the result.

This approach can be implemented with the following code:

```<code>% Simple case: Sum of the empty list
sum([], 0).

% Recursive case: Split list into first element X and remaining list XS
sum([X|XS], N) :- sum(XS, M), N is M + X.
</code>```

Usage:

```<code>?- sum([1,2,3],6).
true.
?- sum([1,2,3],X).
X = 6.
</code>```

The is operator does arithmetic evaluation of its right-hand side (reference), as opposed to treating M + X as a literal term. If you would use = instead of is, M + X would be treated as a literal term. You would then get the following output:

```<code>?- sum([1,2,3],6).
false.
?- sum([1,2,3],0+3+2+1).
true.
</code>```

So for Prolog 6 and 0+3+2+1 are different terms, until you force arithmetic evaluation as done by is.

2) Define the avg (X, N) predicate that calculates the arithmetic average of all elements of the list X, where N is the number of elements.

This is not possible. If X is the list and N the number of elements, then the predicate has no way of outputting the average (unless you count printing the average as a side-effect, I don't think you want). To fix this, add another parameter A that represents the average: avg(X, N, A).

We can calculate the average by taking the sum of the list and dividing it by the length of the list:

```<code>avg(X, N, A) :- sum(X, S), length(X, N), A is S / N.
</code>```

Usage:

```<code>?- avg([1,2,3],3,2).
true.
?- avg([1,2,3,4],N,X).
N = 4,
X = 2.5.
</code>```

3) Define the predicate called count(X, Y, N), which is true if the list Y contains N element instances X.

I understand you want N to be the number of times that the number X occurs in the list Y. We can again break this down into a simple case and then try to break down the general case into smaller steps until we get to the simple case.
For an empty list, we know that X occurs zero times in that list. For a non-empty list, we can remove the first element and check of how often X occurs in the remaining list. If the first element if equal to X, then the total number of occurrences of X is one plus the number of occurrences in the remaining list. If the first element is not equal to X, then the total number of occurrences of X is equal to the number of occurrences in the remaining list.

This approach can be implemented with the following code:

```<code>% Simple case: The list is empty.
count(_, [], 0).

% Recursive case: First element is equal to X
count(X, [X|YS], N) :- count(X, YS, M), N is M + 1, !.

% Recursive case: First element is unequal to X
count(X, [Y|YS], N) :- X \= Y, count(X, YS, N).
</code>```

We use _ for variables we do not care about. We could also write X instead of _, but Prolog would then give us a warning about an unused variable.

Usage:

```<code>?- count(1, [1,1,2,3], N).
N = 2.
?- count(2, [1,1,2,3], N).
N = 1.
</code>```

Body:
Define the sum(X, N) predicate, which is true when N is the sum of integers from the list X.

You want to calculate the sum of the elements of a list. What would be the simplest instance of the problem? When the list is empty, the sum of its element is 0. How can we break down larger lists to get to the simple case? We can remove the first element of the list, calculate the sum of the remaining list, and then add the first element to the result.

This approach can be implemented with the following code:

% Simple case: Sum of the empty list
sum([], 0).

% Recursive case: Split list into first element X and remaining list XS
sum([X|XS], N) :- sum(XS, M), N is M + X.

Usage:

?- sum([1,2,3],6).
true.
?- sum([1,2,3],X).
X = 6.

The is operator does arithmetic evaluation of its right-hand side (reference), as opposed to treating M + X as a literal term. If you would use = instead of is, M + X would be treated as a literal term. You would then get the following output:

?- sum([1,2,3],6).
false.
?- sum([1,2,3],0+3+2+1).
true.

So for Prolog 6 and 0+3+2+1 are different terms, until you force arithmetic evaluation as done by is.

2) Define the avg (X, N) predicate that calculates the arithmetic average of all elements of the list X, where N is the number of elements.

This is not possible. If X is the list and N the number of elements, then the predicate has no way of outputting the average (unless you count printing the average as a side-effect, I don't think you want). To fix this, add another parameter A that represents the average: avg(X, N, A).

We can calculate the average by taking the sum of the list and dividing it by the length of the list:

avg(X, N, A) :- sum(X, S), length(X, N), A is S / N.

Usage:

?- avg([1,2,3],3,2).
true.
?- avg([1,2,3,4],N,X).
N = 4,
X = 2.5.

3) Define the predicate called count(X, Y, N), which is true if the list Y contains N element instances X.

I understand you want N to be the number of times that the number X occurs in the list Y. We can again break this down into a simple case and then try to break down the general case into smaller steps until we get to the simple case.
For an empty list, we know that X occurs zero times in that list. For a non-empty list, we can remove the first element and check of how often X occurs in the remaining list. If the first element if equal to X, then the total number of occurrences of X is one plus the number of occurrences in the remaining list. If the first element is not equal to X, then the total number of occurrences of X is equal to the number of occurrences in the remaining list.

This approach can be implemented with the following code:

% Simple case: The list is empty.
count(_, [], 0).

% Recursive case: First element is equal to X
count(X, [X|YS], N) :- count(X, YS, M), N is M + 1, !.

% Recursive case: First element is unequal to X
count(X, [Y|YS], N) :- X \= Y, count(X, YS, N).

We use _ for variables we do not care about. We could also write X instead of _, but Prolog would then give us a warning about an unused variable.

Usage:

?- count(1, [1,1,2,3], N).
N = 2.
?- count(2, [1,1,2,3], N).
N = 1.


问:
Cannot get python to load json file
This is the error I keep getting

```<code>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

This is what the json data looks like:

```<code>{
    "TITLE": "Rome: The Punic Wars - The First Punic War - Extra History - #1",
    "CHANNEL_NAME": "Extra Credits",
    "NUMBER_OF_VIEWS": "3,954,083 views",
    "LIKES": "50,431",
    "DISLIKES": "887",
    "NUMBER_OF_SUBSCRIPTIONS": "2.37M",
    "HASH_TAGS": []
}
</code>```

I've tried to modify the file to point of deleting all but the curly brackets, then even them to, but the error still happens.

This is what my code looks like:

```<code>import json

with open('C:/Users/longv/Desktop/data.json') as f:
    print('hello')
    data = json.load(f)
</code>```

I also searched StackOverflow, but the discussions are so over my head I don't even understand, and it doesn't look like it'd work in my case anyway.

EDIT: This is a load of BS, because I used the online platform repl.it and this code worked fine.

答:
Maybe it's the indentation. Indenting the with block like so might fix it:

```<code>import json

with open('C:/Users/longv/Desktop/data.json') as f:
    print('hello')
    data = json.load(f)
</code>```

Title: Cannot get python to load json file

Body:
This is the error I keep getting

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This is what the json data looks like:

{
    "TITLE": "Rome: The Punic Wars - The First Punic War - Extra History - #1",
    "CHANNEL_NAME": "Extra Credits",
    "NUMBER_OF_VIEWS": "3,954,083 views",
    "LIKES": "50,431",
    "DISLIKES": "887",
    "NUMBER_OF_SUBSCRIPTIONS": "2.37M",
    "HASH_TAGS": []
}

I've tried to modify the file to point of deleting all but the curly brackets, then even them to, but the error still happens.

This is what my code looks like:

import json

with open('C:/Users/longv/Desktop/data.json') as f:
    print('hello')
    data = json.load(f)

I also searched StackOverflow, but the discussions are so over my head I don't even understand, and it doesn't look like it'd work in my case anyway.

EDIT: This is a load of BS, because I used the online platform repl.it and this code worked fine.

Body:
Maybe it's the indentation. Indenting the with block like so might fix it:

import json

with open('C:/Users/longv/Desktop/data.json') as f:
    print('hello')
    data = json.load(f)


问:
How does PyTorch's loss.backward() work when "retain_graph=True" is specified?
I'm a newbie with PyTorch and adversarial networks. I've tried to look for an answer on the PyTorch documentation and from previous discussions both in the PyTorch and StackOverflow forums, but I couldn't find anything useful.

I'm trying to train a GAN with a Generator and a Discriminator, but I cannot understand if the whole process is working or not. As far as I'm concerned, I should train the Generator first and, then, updating the Discriminator's weights (similarly as this). My code for updating the weights of both models is:

```<code># computing loss_g and loss_d...
optim_g.zero_grad()
loss_g.backward()
optim_g.step()

optim_d.zero_grad()
loss_d.backward()
optim_d.step()
</code>```

where loss_g is the generator loss, loss_d is the discriminator loss, optim_g is the optimizer referring to the generator's parameters and optim_d is the discriminator optimizer.
If I run the code like this, I get an error:

RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.

So I specify loss_g.backward(retain_graph=True), and here comes my doubt: why should I specify retain_graph=True if there are two networks with two different graphs? Am I getting something wrong?

答:
Having two different networks doesn't necessarily mean that the computational graph is different. The computational graph only tracks the operations that were performed from the input to the output and it doesn't matter where the operation takes place. In other words, if you use the output of the first model in the second model (e.g. model2(model1(input))), you have the same sequential operations as if they were part of the same model. In fact, that is no different from having different parts of the model, such as multiple convolutions, that you apply one after the other.

The error you get, indicates that you are trying to backpropagate from the discriminator through the generator, which would mean that the discriminator's output directly adapts the generator's parameters for the discriminator to be successful. In an adversarial setting that is precisely what you want to avoid, they should be independent from each other. By setting retrain_graph=True you incorrectly hide this bug. In nearly all cases retain_graph=True is not the solution and should be avoided.

To resolve that issue, the two models need to be made independent from each other. The crossover between the two models happens when you use the generators output for the discriminator, since it should decide whether that was real or fake. Something along these lines:

fake = generator(noise)

real_prediction = discriminator(real)
# Using the output of the generator, continues the graph.
fake_prediction = discriminator(fake)
```

<p>Even though <code>fake</code> comes from the generator, as far as the discriminator is concerned, it's merely another input, just like <code>real</code>. Therefore <code>fake</code> should be treated the same as <code>real</code>, where it is not attached to any computational graph. That can easily be done with <code>torch.Tensor.detach</code>, which decouples the tensor from the graph.</p>

<pre class="lang-py prettyprint-override"><code>fake = generator(noise)

real_prediction = discriminator(real)
# Detach to make it independent of the generator
fake_prediction = discriminator(fake.detach())
</code>```

That is also done in the code you referenced, from erikqu/EnhanceNet-PyTorch - train.py:

hr_imgs = torch.cat([discriminator(hr), discriminator(generated_hr.detach())], dim=0)
```

Body:
I'm a newbie with PyTorch and adversarial networks. I've tried to look for an answer on the PyTorch documentation and from previous discussions both in the PyTorch and StackOverflow forums, but I couldn't find anything useful.

I'm trying to train a GAN with a Generator and a Discriminator, but I cannot understand if the whole process is working or not. As far as I'm concerned, I should train the Generator first and, then, updating the Discriminator's weights (similarly as this). My code for updating the weights of both models is:

# computing loss_g and loss_d...
optim_g.zero_grad()
loss_g.backward()
optim_g.step()

optim_d.zero_grad()
loss_d.backward()
optim_d.step()

where loss_g is the generator loss, loss_d is the discriminator loss, optim_g is the optimizer referring to the generator's parameters and optim_d is the discriminator optimizer.
If I run the code like this, I get an error:

RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.

So I specify loss_g.backward(retain_graph=True), and here comes my doubt: why should I specify retain_graph=True if there are two networks with two different graphs? Am I getting something wrong?

Body:
Having two different networks doesn't necessarily mean that the computational graph is different. The computational graph only tracks the operations that were performed from the input to the output and it doesn't matter where the operation takes place. In other words, if you use the output of the first model in the second model (e.g. model2(model1(input))), you have the same sequential operations as if they were part of the same model. In fact, that is no different from having different parts of the model, such as multiple convolutions, that you apply one after the other.

The error you get, indicates that you are trying to backpropagate from the discriminator through the generator, which would mean that the discriminator's output directly adapts the generator's parameters for the discriminator to be successful. In an adversarial setting that is precisely what you want to avoid, they should be independent from each other. By setting retrain_graph=True you incorrectly hide this bug. In nearly all cases retain_graph=True is not the solution and should be avoided.

To resolve that issue, the two models need to be made independent from each other. The crossover between the two models happens when you use the generators output for the discriminator, since it should decide whether that was real or fake. Something along these lines:

fake = generator(noise)

real_prediction = discriminator(real)
# Using the output of the generator, continues the graph.
fake_prediction = discriminator(fake)

Even though fake comes from the generator, as far as the discriminator is concerned, it's merely another input, just like real. Therefore fake should be treated the same as real, where it is not attached to any computational graph. That can easily be done with torch.Tensor.detach, which decouples the tensor from the graph.

fake = generator(noise)

real_prediction = discriminator(real)
# Detach to make it independent of the generator
fake_prediction = discriminator(fake.detach())

That is also done in the code you referenced, from erikqu/EnhanceNet-PyTorch - train.py:

hr_imgs = torch.cat([discriminator(hr), discriminator(generated_hr.detach())], dim=0)


问:
How to control two google chrome profiles using selenium python at the same time?
I am trying to control two google chrome instances using two different profiles. But when I open first profile and then run second chrome instance with different one I get an errors.

```<code>from selenium import webdriver

def launch(login, password):
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument(r'--user-data-dir=/home/marek/.config/google-chrome')
    chrome_options.add_argument(r'--profile-directory=Profile 3')
    second_options = webdriver.ChromeOptions()
    second_options.add_argument(r'--user-data-dir=/home/marek/.config/google-chrome')
    second_options.add_argument(r'--profile-directory=Profile 4')
    driver = webdriver.Chrome(options = chrome_options)
    second_driver = webdriver.Chrome(options = second_options)
    driver.get('http://google.com')
    second_driver.get('http://google.com')

if __name__ == '__main__':
    login = 'xxx'
    password = 'xxx'
    launch(login,password)
</code>```

Error logs :

```<code>  File "auto.py", line 19, in <module>
    launch(login,password)
  File "auto.py", line 11, in launch_draw
    driver = webdriver.Chrome(options = chrome_options)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
  (Driver info: chromedriver=72.0.3626.69 (3c16f8a135abc0d4da2dff33804db79b849a7c38),platform=Linux 4.19.23-1-MANJARO x86_64)
</code>```

Any ideas how to get this working?

答:
It might have something to do with how you are specifying your profile directory.

The following code works for me (doesn't seem to have much to do with whether I'm logged in or not).

Assumes n > 0 profile folders in chrome/user/data saved as
'Profile1', 'Profile2', ..., 'Profilen'

Code

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import DesiredCapabilities
from concurrent.futures import ThreadPoolExecutor
import os, pyautogui, easygui

def new_profile(i):
    global profiles, parent, ev

    profiles[i] = path_profile + str(i)
    o = webdriver.ChromeOptions()
    o.add_argument('--user-data-dir=' + profiles[i])
    d[i] = webdriver.Chrome(path_exec, options=o)
    parent[i] = d[i].current_window_handle
    [ev[i]] = [d[i].execute_script]
    nu = 'x' if i < 10 else 'y'
    try:
        d[i].get('https://' + nu + str(i))
    except:
        pass
    wd[i] = gwwt('x' + i) if i < 10 else gwwt('y' + i)
    d[i].get('google.co.uk')
</code>```

E.g. could activate ith browser window using:

```<code>wd[i][0].activate()
</code>```

alternatively:

```<code>wd[i][0].minimize()
wd[i][0].restore
</code>```

Could also evaluate jQuery (e.g. new tab):

```<code>ev[i]('open()')
</code>```

Of course, you can also do this across all browsers asynchronously using thread_all() method.

```<code>def thread_all(ps, fn, parm='', actions=[], workers=6, chunk=1):
    print(f'thread_all({ps}, {fn}, {parm}, {actions}')
    if parm == '':
        with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
            return executor.map(fn, ps, timeout=90, chunksize=max(1, chunk))
    else:
        with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
            return executor.map(fn, ps, itertools.repeat(parm, L), timeout=90, chunksize=max(1, chunk))

def vars_glob():
    global path_profile, path_core, path_exec
    global d, profiles, parent, ev, wd, n, ps
    global gwwt
    resp = easygui.multenterbox('Enter preferences', 'Inputs', ['Number of browsers'],[4])
    try:
        n = int(resp[0])
    except:
        print('enter a digit! run code again please :(')
        quit()
        [gwwt] = [pyautogui.getWindowsWithTitle]
        profiles, d, parent, ev, wd = [''] * n, [''] * n, [''] * n, [''] * n, [['']] * n
        ps = list(range(n))
        path_core = os.path.expanduser("~")
        path_profile = os.path.join(path_core, "AppData", "Local", "Google", "Chrome", "User", "Data", "Profile")
        path_exec = os.path.join(path_core, '< rest of path >', 'chromedriver.exe')
</code>```

d will be 'n' chrome-drivers (one for each independent browser/profile)

```<code>if __name__ == '__main__':
   vars_glob()
   thread_all(ps,new_profile, workers = n+1, chunk = n+1)
</code>```

Body:
I am trying to control two google chrome instances using two different profiles. But when I open first profile and then run second chrome instance with different one I get an errors.

from selenium import webdriver

def launch(login, password):
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument(r'--user-data-dir=/home/marek/.config/google-chrome')
    chrome_options.add_argument(r'--profile-directory=Profile 3')
    second_options = webdriver.ChromeOptions()
    second_options.add_argument(r'--user-data-dir=/home/marek/.config/google-chrome')
    second_options.add_argument(r'--profile-directory=Profile 4')
    driver = webdriver.Chrome(options = chrome_options)
    second_driver = webdriver.Chrome(options = second_options)
    driver.get('http://google.com')
    second_driver.get('http://google.com')

if __name__ == '__main__':
    login = 'xxx'
    password = 'xxx'
    launch(login,password)

Error logs :

  File "auto.py", line 19, in <module>
    launch(login,password)
  File "auto.py", line 11, in launch_draw
    driver = webdriver.Chrome(options = chrome_options)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
  (Driver info: chromedriver=72.0.3626.69 (3c16f8a135abc0d4da2dff33804db79b849a7c38),platform=Linux 4.19.23-1-MANJARO x86_64)

Any ideas how to get this working?

Body:
It might have something to do with how you are specifying your profile directory.

The following code works for me (doesn't seem to have much to do with whether I'm logged in or not).

Assumes n > 0 profile folders in chrome/user/data saved as
'Profile1', 'Profile2', ..., 'Profilen'

Code

from selenium import webdriver
from selenium.webdriver.chrome.options import DesiredCapabilities
from concurrent.futures import ThreadPoolExecutor
import os, pyautogui, easygui

def new_profile(i):
    global profiles, parent, ev

    profiles[i] = path_profile + str(i)
    o = webdriver.ChromeOptions()
    o.add_argument('--user-data-dir=' + profiles[i])
    d[i] = webdriver.Chrome(path_exec, options=o)
    parent[i] = d[i].current_window_handle
    [ev[i]] = [d[i].execute_script]
    nu = 'x' if i < 10 else 'y'
    try:
        d[i].get('https://' + nu + str(i))
    except:
        pass
    wd[i] = gwwt('x' + i) if i < 10 else gwwt('y' + i)
    d[i].get('google.co.uk')

E.g. could activate ith browser window using:

wd[i][0].activate()

alternatively:

wd[i][0].minimize()
wd[i][0].restore

Could also evaluate jQuery (e.g. new tab):

ev[i]('open()')

Of course, you can also do this across all browsers asynchronously using thread_all() method.

def thread_all(ps, fn, parm='', actions=[], workers=6, chunk=1):
    print(f'thread_all({ps}, {fn}, {parm}, {actions}')
    if parm == '':
        with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
            return executor.map(fn, ps, timeout=90, chunksize=max(1, chunk))
    else:
        with ThreadPoolExecutor(max_workers=max(1, workers)) as executor:
            return executor.map(fn, ps, itertools.repeat(parm, L), timeout=90, chunksize=max(1, chunk))

def vars_glob():
    global path_profile, path_core, path_exec
    global d, profiles, parent, ev, wd, n, ps
    global gwwt
    resp = easygui.multenterbox('Enter preferences', 'Inputs', ['Number of browsers'],[4])
    try:
        n = int(resp[0])
    except:
        print('enter a digit! run code again please :(')
        quit()
        [gwwt] = [pyautogui.getWindowsWithTitle]
        profiles, d, parent, ev, wd = [''] * n, [''] * n, [''] * n, [''] * n, [['']] * n
        ps = list(range(n))
        path_core = os.path.expanduser("~")
        path_profile = os.path.join(path_core, "AppData", "Local", "Google", "Chrome", "User", "Data", "Profile")
        path_exec = os.path.join(path_core, '< rest of path >', 'chromedriver.exe')

d will be 'n' chrome-drivers (one for each independent browser/profile)

if __name__ == '__main__':
   vars_glob()
   thread_all(ps,new_profile, workers = n+1, chunk = n+1)


问:
Regex to match string with five forward slashes
I want to write a regex to match any string with 5 forward slashes in. This is to match a URL in Google Analytics. I thought I had gotten close, but no cigar yet. This is what I've come up with:

```<code>\/.*\/.*\/.*\/.*\/.*$
</code>```

But it doesn't match anything. How can I correct this? Or is it not possible?

答:
I need to pull out links only have just string with excluding numbers and queries in URL in Google Analytics.

so, I need this URL

www.site.com/en/rent/cairo/apartments-for-rent/

and exclude these

```<code>www.website.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/

  www.website.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/?price=1000
</code>```

Body:
I want to write a regex to match any string with 5 forward slashes in. This is to match a URL in Google Analytics. I thought I had gotten close, but no cigar yet. This is what I've come up with:

\/.*\/.*\/.*\/.*\/.*$

But it doesn't match anything. How can I correct this? Or is it not possible?

Body:
I need to pull out links only have just string with excluding numbers and queries in URL in Google Analytics.

so, I need this URL

www.site.com/en/rent/cairo/apartments-for-rent/

and exclude these

www.website.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/

  www.website.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/?price=1000


问:
Exclude symbols from Regular Expressions [PHP]
I'm new to programming, i'm starting with PHP and trying to use regular expressions to exclude symbols from a string and check the maximum length to be 16 characters.

This is what i've done by now:

```<code><php
if(!preg_match("/^[^\!\¡\-\"\#\$\%\&\/\(\)\=\?\¿\_\,\.\~\<\>\\\[\]\{\}\+\*\;\:\@\¬\=\°\^]{0,16}/", $Sname))
    {
      $Error = '<span class="label error"> Invalid name. </span>';
    }
?>
</code>```

I've been using regex101 to 'validate' this regex and it is supposed to work (I mean, i've testing with strings in the web and worked as intended) . the original string that i got from the page was

```<code>^[^!¡\-"#$%&\/()=?¿_,.~<>\[\]{}+*;:@¬=°\^]{0,16}
</code>```

Whoever, this didn't work in the code, it always show 'Invalid Name' even though the string it's supposed to be valid. I'm kinda lost right now. Any ideas?

Sorry for the ignorance

Thanks in advice!

Cheers!

答:
if with no symbols you mean only letters, digits and space this could be the right regex: ^[a-zA-Z\d\s]{1,16}$ so you can do something like this:

```<code>if (preg_match('/^[a-zA-Z\d\s]{1,16}$/', $target)) {
   // do something
}
</code>```

Edit

Usually is a bad idea to allow accented characters because you can easily face encoding problems when for example you store and retrieve something from/to a database. Another bad habit is to think a regex from subtraction, don't think on what a string don't need but what it needs and i'll give you an example to deal with accented characters but not with special characters. What you may looking for is:

```<code>if (preg_match('/^[^!£$%\'()=]{1,16}$/', $target)) {
       // do something
    }
</code>```

But what if i miss some symbols? There are thousands of symbols that could be used to bypass this simple regex, no one for the previous one.

Body:
I'm new to programming, i'm starting with PHP and trying to use regular expressions to exclude symbols from a string and check the maximum length to be 16 characters.

This is what i've done by now:

<php
if(!preg_match("/^[^\!\¡\-\"\#\$\%\&\/\(\)\=\?\¿\_\,\.\~\<\>\\\[\]\{\}\+\*\;\:\@\¬\=\°\^]{0,16}/", $Sname))
    {
      $Error = ' Invalid name. ';
    }
?>

I've been using regex101 to 'validate' this regex and it is supposed to work (I mean, i've testing with strings in the web and worked as intended) . the original string that i got from the page was

^[^!¡\-"#$%&\/()=?¿_,.~<>\[\]{}+*;:@¬=°\^]{0,16}

Whoever, this didn't work in the code, it always show 'Invalid Name' even though the string it's supposed to be valid. I'm kinda lost right now. Any ideas?

Sorry for the ignorance

Thanks in advice!

Cheers!

Body:
if with no symbols you mean only letters, digits and space this could be the right regex: ^[a-zA-Z\d\s]{1,16}$ so you can do something like this:

if (preg_match('/^[a-zA-Z\d\s]{1,16}$/', $target)) {
   // do something
}

Edit

Usually is a bad idea to allow accented characters because you can easily face encoding problems when for example you store and retrieve something from/to a database. Another bad habit is to think a regex from subtraction, don't think on what a string don't need but what it needs and i'll give you an example to deal with accented characters but not with special characters. What you may looking for is:

if (preg_match('/^[^!£$%\'()=]{1,16}$/', $target)) {
       // do something
    }

But what if i miss some symbols? There are thousands of symbols that could be used to bypass this simple regex, no one for the previous one.


问:
Google Calendar Insert Event API - Reminders do NOT appear as the code was executed
I am adding an event using Google Calendar Java API (version v3-rev305-1.23.0). Event addition goes successfully but the problem I am facing is the reminders that appear in the event.

My code structure is same as available in Java example on this - https://developers.google.com/calendar/create-events#java. And I have provided the code snippet of the event reminder below.

```<code>    Event event = new Event()
        .setSummary(insertEvent.getSummary())
        .setDescription(insertEvent.getDesc());

    DateTime reminderDate = DateTime.parseRfc3339(insertEvent.getReminderDate());
    EventDateTime start = new EventDateTime().setDate(reminderDate);
    event.setStart(start);
    EventDateTime end = new EventDateTime().setDate(reminderDate);
    event.setEnd(end);

    List<EventAttendee> attendees = new ArrayList<>();
    for (String reminderEmail : insertEvent.getReminderEmails()) {
      attendees.add(new EventAttendee().setEmail(reminderEmail));
    }
    event.setAttendees(attendees);

    EventReminder[] reminderOverrides = new EventReminder[] {
        new EventReminder().setMethod("email").setMinutes(5 * 24 * 60),
        new EventReminder().setMethod("popup").setMinutes(10),
    };
    Event.Reminders reminders = new Event.Reminders()
        .setUseDefault(false)
        .setOverrides(Arrays.asList(reminderOverrides));
    event.setReminders(reminders);

    event = this.calendar.events().insert(insertEvent.getCalendarId(), event).execute();
</code>```

Please note that there are 2 reminders being set here, one being an email 5 days before and second is a popup 10 minutes before. But after the event is created I see different reminders. They are also 2 reminders but not the ones that I have coded and executed. If anyone is facing such an issue then please let me know how to solve this. Thanks very much.

答:
Are you checking the reminders view in the Calendar UI with the same user that created the event via the API? Reminders are set per-attendee and cannot be modified / set by any other user including the event organizer / creator.

For details read about shared / private properties of events in the Calendar API.

Body:
I am adding an event using Google Calendar Java API (version v3-rev305-1.23.0). Event addition goes successfully but the problem I am facing is the reminders that appear in the event.

My code structure is same as available in Java example on this - https://developers.google.com/calendar/create-events#java. And I have provided the code snippet of the event reminder below.

    Event event = new Event()
        .setSummary(insertEvent.getSummary())
        .setDescription(insertEvent.getDesc());

    DateTime reminderDate = DateTime.parseRfc3339(insertEvent.getReminderDate());
    EventDateTime start = new EventDateTime().setDate(reminderDate);
    event.setStart(start);
    EventDateTime end = new EventDateTime().setDate(reminderDate);
    event.setEnd(end);

    List<EventAttendee> attendees = new ArrayList<>();
    for (String reminderEmail : insertEvent.getReminderEmails()) {
      attendees.add(new EventAttendee().setEmail(reminderEmail));
    }
    event.setAttendees(attendees);

    EventReminder[] reminderOverrides = new EventReminder[] {
        new EventReminder().setMethod("email").setMinutes(5 * 24 * 60),
        new EventReminder().setMethod("popup").setMinutes(10),
    };
    Event.Reminders reminders = new Event.Reminders()
        .setUseDefault(false)
        .setOverrides(Arrays.asList(reminderOverrides));
    event.setReminders(reminders);

    event = this.calendar.events().insert(insertEvent.getCalendarId(), event).execute();

Please note that there are 2 reminders being set here, one being an email 5 days before and second is a popup 10 minutes before. But after the event is created I see different reminders. They are also 2 reminders but not the ones that I have coded and executed. If anyone is facing such an issue then please let me know how to solve this. Thanks very much.


问:
How to save an array with the same spacing and origin into a SimpleITK image?
I want to write the image [that I have loaded into array] after changing the values of array into a SimpleITK Image. How can I set the spacing and origin?

[res_file_dir is the path to the nii.gz file]

```<code>segmentation_result=sitk.ReadImage(res_file_dir,sitk.sitkUInt8)   #segmentation_result.GetSpacing() (0.3645833432674408, 0.3645833432674408, 0.699999988079071)
seg=sitk.GetArrayFromImage(segmentation_result)  #shape (105, 242, 176)
seg[seg!=obj_label]=0

#segmentation=sitk.Image(segmentation_result.GetSize(),sitk.sitkUInt8)
 numpyOrigin = np.array(list(reversed(segmentation_result.GetOrigin())))
 numpySpacing = np.array(list(reversed(segmentation_result.GetSpacing())))
 segmentation = sitk.GetImageFromArray(seg, sitk.sitkVectorUInt8).SetSpacing(numpySpacing)
</code>```

once I check the spacing of new image, it shows the following:

```<code>segmentation.GetSpacing()
*** AttributeError: 'NoneType' object has no attribute 'GetSpacing'
</code>```

答:
There are two problems with your last line.  The first problem is that segmentation is getting set to the result of the call to SetSpacing, which has a return type of void.

The second problem is your second parameter to sitk.GetImageFromArray.  It is a boolean for the named parameter isVector.  In your case you want it to be False, which is the default value.

In your code, you are passing sitk.sitkVectorUInt8, which turns out to be an integer of value 13, to isVector.  So isVector is getting True, the opposite of what you really want.  With True you are getting a 2-d image with each pixel being a vector of length 176.

To double check, I would print out the results of the call to sitk.GetImageFromArray before doing the call to SetSpacing.

So here's what your code should be:

```<code>segmentation = sitk.GetImageFromArray(seg, isVector=False)
segmentation.SetSpacing(numpySpacing)
</code>```

Note that if you want to mask out values in you image, you can do it in SimpleITK without converting to numpy and back.  Here's how you could do that:

```<code># create a binary mask image of
seg = (segmentation_result==obj_label)

# create an image with pixel values of obj_label
segmentation = seg * obj_label
</code>```

Body:
I want to write the image [that I have loaded into array] after changing the values of array into a SimpleITK Image. How can I set the spacing and origin?

[res_file_dir is the path to the nii.gz file]

segmentation_result=sitk.ReadImage(res_file_dir,sitk.sitkUInt8)   #segmentation_result.GetSpacing() (0.3645833432674408, 0.3645833432674408, 0.699999988079071)
seg=sitk.GetArrayFromImage(segmentation_result)  #shape (105, 242, 176)
seg[seg!=obj_label]=0

#segmentation=sitk.Image(segmentation_result.GetSize(),sitk.sitkUInt8)
 numpyOrigin = np.array(list(reversed(segmentation_result.GetOrigin())))
 numpySpacing = np.array(list(reversed(segmentation_result.GetSpacing())))
 segmentation = sitk.GetImageFromArray(seg, sitk.sitkVectorUInt8).SetSpacing(numpySpacing)

once I check the spacing of new image, it shows the following:

segmentation.GetSpacing()
*** AttributeError: 'NoneType' object has no attribute 'GetSpacing'

Body:
There are two problems with your last line.  The first problem is that segmentation is getting set to the result of the call to SetSpacing, which has a return type of void.

The second problem is your second parameter to sitk.GetImageFromArray.  It is a boolean for the named parameter isVector.  In your case you want it to be False, which is the default value.

In your code, you are passing sitk.sitkVectorUInt8, which turns out to be an integer of value 13, to isVector.  So isVector is getting True, the opposite of what you really want.  With True you are getting a 2-d image with each pixel being a vector of length 176.

To double check, I would print out the results of the call to sitk.GetImageFromArray before doing the call to SetSpacing.

So here's what your code should be:

segmentation = sitk.GetImageFromArray(seg, isVector=False)
segmentation.SetSpacing(numpySpacing)

Note that if you want to mask out values in you image, you can do it in SimpleITK without converting to numpy and back.  Here's how you could do that:

# create a binary mask image of
seg = (segmentation_result==obj_label)

# create an image with pixel values of obj_label
segmentation = seg * obj_label


问:
How do I compare two messages sent in a chat?
```<code>User 1: nuclear
User 2: reactor
</code>```

I want to be able to compare these two messages; but, I'm having some trouble: I just don't know how to save the second message into a variable. I've tried using wait_for(), not sure if this is the way to do it or if i'm using it correctly.

```<code>import discord
from discord.ext import commands

class Shiritori(commands.Cog):
    """ Start a new word from the last letter of the one before. """

    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        last_letter = message.content[-1]
        print(f"The first letter is {message.content[0]}")

        msg = await self.client.wait_for('message')
        print(f"The last letter is {msg}")

        if message.content[0] != msg[-1]:
            await message.delete()

def setup(client):
    client.add_cog(Shiritori(client))
</code>```

My plan is to save the last letter of user 1's word and compare it with the first letter of user 2's word and if they don't match, user 2's message would be deleted.

答:
I hope I'm understanding the question correctly. One way of overcoming this without having to use wait_for is by making use of the class' attributes:

class Shiritori(commands.Cog):
    """ Start a new word from the last letter of the one before. """

    def __init__(self, client):
        self.client = client
        self.lastletter = "a" # keeps track of the recent last letter here

    @commands.Cog.listener()
    async def on_message(self, message):
        firstletter = message.content[0]
        if firstletter.lower() == self.lastletter.lower():
            self.lastletter = message.content[-1]
            print(f"The new letter to start the word with is {self.lastletter}")
        else:
            await message.delete()
```

Additionally, you can add checks for only letting this happen in a specific channel/specific users etc.

Body:
User 1: nuclear
User 2: reactor

I want to be able to compare these two messages; but, I'm having some trouble: I just don't know how to save the second message into a variable. I've tried using wait_for(), not sure if this is the way to do it or if i'm using it correctly.

import discord
from discord.ext import commands

class Shiritori(commands.Cog):
    """ Start a new word from the last letter of the one before. """

    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
        last_letter = message.content[-1]
        print(f"The first letter is {message.content[0]}")

        msg = await self.client.wait_for('message')
        print(f"The last letter is {msg}")

        if message.content[0] != msg[-1]:
            await message.delete()

def setup(client):
    client.add_cog(Shiritori(client))

My plan is to save the last letter of user 1's word and compare it with the first letter of user 2's word and if they don't match, user 2's message would be deleted.

Body:
I hope I'm understanding the question correctly. One way of overcoming this without having to use wait_for is by making use of the class' attributes:

class Shiritori(commands.Cog):
    """ Start a new word from the last letter of the one before. """

    def __init__(self, client):
        self.client = client
        self.lastletter = "a" # keeps track of the recent last letter here

    @commands.Cog.listener()
    async def on_message(self, message):
        firstletter = message.content[0]
        if firstletter.lower() == self.lastletter.lower():
            self.lastletter = message.content[-1]
            print(f"The new letter to start the word with is {self.lastletter}")
        else:
            await message.delete()

Additionally, you can add checks for only letting this happen in a specific channel/specific users etc.


问:
TypeScript better way to define big models
So I am working on an application which has some large models used sometimes, an example is seen below:

```<code>import CapcodeModel from "./CapcodeModel";

export default class MeldingModel {
  hash: string;
  id: number;
  tijd: string;
  melding: string;
  adres: {
    straat: string;
    plaats: string;
    postcode: string;
    longitude: string;
    latitude: string;
  };
  discipline: string;
  disciplineId: number;
  disciplineVolledig: string;
  regioNaam: string;
  regioStream: string;
  cruciaal: boolean;
  proRail: boolean;
  capcodes: CapcodeModel[];

  constructor(
    {
      hash,
      id,
      tijd,
      melding,
      adres,
      discipline,
      disciplineId,
      disciplineVolledig,
      regioNaam,
      regioStream,
      cruciaal,
      proRail,
      capcodes
    }: MeldingModel = {
      hash: "",
      id: 0,
      tijd: "",
      melding: "",
      adres: {
        straat: "",
        plaats: "",
        postcode: "",
        longitude: "",
        latitude: ""
      },
      discipline: "",
      disciplineId: 0,
      disciplineVolledig: "",
      regioNaam: "",
      regioStream: "",
      cruciaal: false,
      proRail: false,
      capcodes: []
    }
  ) {
    this.hash = hash;
    this.id = id;
    this.tijd = tijd;
    this.melding = melding;
    this.adres = adres;
    this.discipline = discipline;
    this.disciplineId = disciplineId;
    this.disciplineVolledig = disciplineVolledig;
    this.regioNaam = regioNaam;
    this.regioStream = regioStream;
    this.cruciaal = cruciaal;
    this.proRail = proRail;
    this.capcodes = capcodes;
  }
}
</code>```

It has default values just so I can assign it as:

```<code>const _melding = new MeldingModel();
</code>```

aswell as

```<code>const _melding = new MeldingModel({ /* all props assigned here */ });
</code>```

Now, this big model looks absolutely hideous and hard to maintain in my opinion, is there a way to clean this up, while still being able to use it's default values?

答:
I would implement as a simple object with default values:

```<code>export default class MeldingModel {
  hash = "";
  id = 0;
  tijd = "";
  melding = "";
  adres: {
    straat: "";
    plaats: "";
    postcode: "";
    longitude: "";
    latitude: "";
  };
  discipline = "";
  disciplineId = 0;
  disciplineVolledig = "";
  regioNaam = "";
  regioStream = "";
  cruciaal = false;
  proRail = false;
  capcodes: CapcodeModel[] = [];
}
</code>```

Then you can do this as before:

```<code>const _melding = new MeldingModel();
</code>```

For your second constructor approach you can use:

```<code>const _melding: MeldingModel = { /* all props assigned here */ };
</code>```

Body:
So I am working on an application which has some large models used sometimes, an example is seen below:

import CapcodeModel from "./CapcodeModel";

export default class MeldingModel {
  hash: string;
  id: number;
  tijd: string;
  melding: string;
  adres: {
    straat: string;
    plaats: string;
    postcode: string;
    longitude: string;
    latitude: string;
  };
  discipline: string;
  disciplineId: number;
  disciplineVolledig: string;
  regioNaam: string;
  regioStream: string;
  cruciaal: boolean;
  proRail: boolean;
  capcodes: CapcodeModel[];

  constructor(
    {
      hash,
      id,
      tijd,
      melding,
      adres,
      discipline,
      disciplineId,
      disciplineVolledig,
      regioNaam,
      regioStream,
      cruciaal,
      proRail,
      capcodes
    }: MeldingModel = {
      hash: "",
      id: 0,
      tijd: "",
      melding: "",
      adres: {
        straat: "",
        plaats: "",
        postcode: "",
        longitude: "",
        latitude: ""
      },
      discipline: "",
      disciplineId: 0,
      disciplineVolledig: "",
      regioNaam: "",
      regioStream: "",
      cruciaal: false,
      proRail: false,
      capcodes: []
    }
  ) {
    this.hash = hash;
    this.id = id;
    this.tijd = tijd;
    this.melding = melding;
    this.adres = adres;
    this.discipline = discipline;
    this.disciplineId = disciplineId;
    this.disciplineVolledig = disciplineVolledig;
    this.regioNaam = regioNaam;
    this.regioStream = regioStream;
    this.cruciaal = cruciaal;
    this.proRail = proRail;
    this.capcodes = capcodes;
  }
}

It has default values just so I can assign it as:

const _melding = new MeldingModel();

aswell as

const _melding = new MeldingModel({ /* all props assigned here */ });

Now, this big model looks absolutely hideous and hard to maintain in my opinion, is there a way to clean this up, while still being able to use it's default values?

Body:
I would implement as a simple object with default values:

export default class MeldingModel {
  hash = "";
  id = 0;
  tijd = "";
  melding = "";
  adres: {
    straat: "";
    plaats: "";
    postcode: "";
    longitude: "";
    latitude: "";
  };
  discipline = "";
  disciplineId = 0;
  disciplineVolledig = "";
  regioNaam = "";
  regioStream = "";
  cruciaal = false;
  proRail = false;
  capcodes: CapcodeModel[] = [];
}

Then you can do this as before:

const _melding = new MeldingModel();

For your second constructor approach you can use:

const _melding: MeldingModel = { /* all props assigned here */ };


问:
Amazon S3 - How to fix 'The request signature we calculated does not match the signature' error?
I have searched on the web for over two days now, and probably have looked through most of the online documented scenarios and workarounds, but nothing worked for me so far.

I am on AWS SDK for PHP V2.8.7 running on PHP 5.3.

I am trying to connect to my Amazon S3 bucket with the following code:

// Create a `Aws` object using a configuration file
$aws = Aws::factory('config.php');

// Get the client from the service locator by namespace
$s3Client = $aws->get('s3');

$bucket = "xxx";
$keyname = "xxx";

try {
    $result = $s3Client->putObject(array(
        'Bucket' => $bucket,
        'Key' => $keyname,
        'Body' => 'Hello World!'
    ));

    $file_error = false;
} catch (Exception $e) {
    $file_error = true;

    echo $e->getMessage();

    die();
}
```
<p>My config.php file is as follows:</p>
<pre class="lang-php prettyprint-override"><code>return [
    // Bootstrap the configuration file with AWS specific features
    'includes' => ['_aws'],
    'services' => [
        // All AWS clients extend from 'default_settings'. Here we are
        // overriding 'default_settings' with our default credentials and
        // providing a default region setting.
        'default_settings' => [
            'params' => [
                'credentials' => [
                    'key'    => 'key',
                    'secret' => 'secret'
                ]
            ]
        ]
    ]
];
</code>```

It is producing the following error:

The request signature we calculated does not match the signature you provided. Check your key and signing method.

I've already checked my access key and secret at least 20 times, generated new ones, used different methods to pass in the information (i.e. profile and including credentials in code) but nothing is working at the moment.

答: This error seems to occur mostly if there is a space before or after your secret key</p>

Body:
I have searched on the web for over two days now, and probably have looked through most of the online documented scenarios and workarounds, but nothing worked for me so far.

I am on AWS SDK for PHP V2.8.7 running on PHP 5.3.

I am trying to connect to my Amazon S3 bucket with the following code:

// Create a `Aws` object using a configuration file
$aws = Aws::factory('config.php');

// Get the client from the service locator by namespace
$s3Client = $aws->get('s3');

$bucket = "xxx";
$keyname = "xxx";

try {
    $result = $s3Client->putObject(array(
        'Bucket' => $bucket,
        'Key' => $keyname,
        'Body' => 'Hello World!'
    ));

    $file_error = false;
} catch (Exception $e) {
    $file_error = true;

    echo $e->getMessage();

    die();
}

My config.php file is as follows:

return [
    // Bootstrap the configuration file with AWS specific features
    'includes' => ['_aws'],
    'services' => [
        // All AWS clients extend from 'default_settings'. Here we are
        // overriding 'default_settings' with our default credentials and
        // providing a default region setting.
        'default_settings' => [
            'params' => [
                'credentials' => [
                    'key'    => 'key',
                    'secret' => 'secret'
                ]
            ]
        ]
    ]
];

It is producing the following error:

The request signature we calculated does not match the signature you provided. Check your key and signing method.

I've already checked my access key and secret at least 20 times, generated new ones, used different methods to pass in the information (i.e. profile and including credentials in code) but nothing is working at the moment.


问:
Changing step values in seekbar?
I have a seekbar, while moving it I want to change values from 0 to 200. I have a TextView, where I display those values while moving the seekbar. But I don't want to have every value from that interval(0,1,2,3,4,5...), but to have 10, 20, 30...so on. So when I move the seekbar, I want to display 10,20,30,40....to 200. Can somebody give me a hint or an example how to do this?</p>

答:
You can use the Slider provided by the Material Components Library using the android:stepSize attribute:

```<code>    <com.google.android.material.slider.Slider
        android:valueFrom="0"
        android:valueTo="200"
        android:stepSize="10"
       ..>
</code>```

Title: Changing step values in seekbar?

Body:
You can use the Slider provided by the Material Components Library using the android:stepSize attribute:

    <com.google.android.material.slider.Slider
        android:valueFrom="0"
        android:valueTo="200"
        android:stepSize="10"
       ..>


问:
How to draw a rectangle in a html file dynamically using javascript ? Google chrome extension Page Ruler have similar feature
I want to draw rectangles over texts or paragraphs in a HTML file. I want to achieve this using javascript without the use of canvas. Multiple rectangles can also exist for selecting multiple paragraphs. Is there any library for achieving this kind of functionality.

Click here to see the intended result

page Ruler link here https://chrome.google.com/webstore/detail/page-ruler-redux/giejhjebcalaheckengmchjekofhhmal?hl=en-US

答:
If you want to highlight pure p elements, you can manipulate the backgroundColor property of the paragraphs, but you'd have to make sure they're displayed inline-block.

document.getElementById('bttn').addEventListener('click', highlight);
function highlight() {
    var p = document.getElementById('target');
    p.style.backgroundColor = '#ff0000'; //change background color
}
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--make sure the paragraph is displayed inline-block, or else the entire line  will be highlighted. -->

<p id="target" style="display:inline-block">This is a paragraph.</p>
<p>This is another paragraph.</p>

<button id="bttn">Click here to highlight</button></code>```

Body:
If you want to highlight pure p elements, you can manipulate the backgroundColor property of the paragraphs, but you'd have to make sure they're displayed inline-block.

document.getElementById('bttn').addEventListener('click', highlight);
function highlight() {
    var p = document.getElementById('target');
    p.style.backgroundColor = '#ff0000'; //change background color
}

<!--make sure the paragraph is displayed inline-block, or else the entire line  will be highlighted. -->

<p id="target" style="display:inline-block">This is a paragraph.</p>
<p>This is another paragraph.</p>

<button id="bttn">Click here to highlight</button>


问:
Can I create a SUMIF with data from either of 2 columns?
I am creating a budgeting table. I am using SUMIF (Category, "Category Name", Amount). However, I have 2 sets of "Amount" - Budgeted and Actual.

How do I make it in such a way that the SUMIF for that Category would add the data from Budgeted if the Actual field is blank?

答:
Try this

check the ";" maybe you have to replace it with a ","

```<code>=SUMIFS(Amount;Category;SelectedCategory)+SUMIFS(Budget;Category;SelectedCategory;Amount;"")
</code>```

Body:
Try this

check the ";" maybe you have to replace it with a ","

=SUMIFS(Amount;Category;SelectedCategory)+SUMIFS(Budget;Category;SelectedCategory;Amount;"")


问:
Javascript: replace <select> with
?
Is there any way to replace <select> tag to a
 with hidden
 that drops down when clicked?
Not a full solution, but maybe some js or jQuery library/plugin to do this. I can spend a day developing it, but maybe someone did have already did it?

The reason i need it is the joomla administrative interface — the dropdown list contains very long values, and i had to set fixed width to those <select>s

Thank you for any help!

答: I tried out quite a few select replacement JQuery plugins, and settled on select-box - be sure to check out the demo page as well. There's a wide variety of plugins for this purpose, so if this one doesn't meet your needs I'm sure you'll find one that does with a little Google-fu.</p>

Title: Javascript: replace <select> with <div>?


问:
PHP custom sorting: Manual sorting an array based on specified keys
I have an array that looks like

```<code>$array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'city' => ['value' => 'Dubai'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'zip_code' => ['value' => 12345],
    'city_id' => ['value' => 22],
    //...
];
</code>```

I would like to sort the array so that the keys country_id, region, region_id, city, city_id occur serially while preserving the position of others.

Expected Output

```<code> $array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'city' => ['value' => 'Dubai'],
    'city_id' => ['value' => 22],
    'zip_code' => ['value' => 12345],
    //...
];
</code>```

I have tried as:

Trial #1

```<code>uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (isset($order[$a]) && isset($order[$b])) {
    return $order[$a] - $order[$b];
  } else {
    return 0;
  }
});

var_dump($array);
</code>```

Trial #2

```<code>uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (!isset($order[$a]) && !isset($order[$b])) {
    return 0;
  } elseif (!isset($order[$a])) {
    return 1;
  } elseif (!isset($order[$b])) {
    return -1;
  } else {
    return $order[$a] - $order[$b];

  }
});

var_dump($array);
</code>```

But the rest of the orders are not maintained anymore.
So I want those custom fields to appear in the same order without breaking the positions of others. For example, name should appear first, etc.

答:
It looks like what you want is difficult to achieve with one of PHP's sort methods. Moreover, as the relative order of the non-matching keys should not change, we can aim for a better time complexity than with a O(nlogn) sort-method.

So, I would suggest writing a function that makes some iterations over both arrays ($array, $order) for it to collect the key/value pairs in the expected order. That constitutes an O(n+m) time complexity, where n and m are the two sizes of the two arrays.

Here is the function:

```<code>function sortadjacent($array, $order) {
    $insertAt = 0;
    foreach($array as $key => $_) {
        if (isset($order[$key])) break;
        $insertAt++;
    }

    $special = [];
    foreach($order as $key => $_) {
        if (isset($array[$key])) $special[$key] = $array[$key];
    }

    $result = [];
    foreach($array as $key => $value) {
        if (!isset($order[$key])) $result[$key] = $value;
        else if (count($result) == $insertAt) $result = array_merge($result, $special);
    }

    return $result;
}
</code>```

You would call it as follows:

```<code>$result = sortadjacent($array, $order);
</code>```

Note that this function does not make changes to $array, but instead returns the expected result in a new array.

Body:
I have an array that looks like

$array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'city' => ['value' => 'Dubai'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'zip_code' => ['value' => 12345],
    'city_id' => ['value' => 22],
    //...
];

I would like to sort the array so that the keys country_id, region, region_id, city, city_id occur serially while preserving the position of others.

Expected Output

 $array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'city' => ['value' => 'Dubai'],
    'city_id' => ['value' => 22],
    'zip_code' => ['value' => 12345],
    //...
];

I have tried as:

Trial #1

uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (isset($order[$a]) && isset($order[$b])) {
    return $order[$a] - $order[$b];
  } else {
    return 0;
  }
});

var_dump($array);

Trial #2

uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (!isset($order[$a]) && !isset($order[$b])) {
    return 0;
  } elseif (!isset($order[$a])) {
    return 1;
  } elseif (!isset($order[$b])) {
    return -1;
  } else {
    return $order[$a] - $order[$b];

  }
});

var_dump($array);

But the rest of the orders are not maintained anymore.
So I want those custom fields to appear in the same order without breaking the positions of others. For example, name should appear first, etc.

Body:
It looks like what you want is difficult to achieve with one of PHP's sort methods. Moreover, as the relative order of the non-matching keys should not change, we can aim for a better time complexity than with a O(nlogn) sort-method.

So, I would suggest writing a function that makes some iterations over both arrays ($array, $order) for it to collect the key/value pairs in the expected order. That constitutes an O(n+m) time complexity, where n and m are the two sizes of the two arrays.

Here is the function:

function sortadjacent($array, $order) {
    $insertAt = 0;
    foreach($array as $key => $_) {
        if (isset($order[$key])) break;
        $insertAt++;
    }

    $special = [];
    foreach($order as $key => $_) {
        if (isset($array[$key])) $special[$key] = $array[$key];
    }

    $result = [];
    foreach($array as $key => $value) {
        if (!isset($order[$key])) $result[$key] = $value;
        else if (count($result) == $insertAt) $result = array_merge($result, $special);
    }

    return $result;
}

You would call it as follows:

$result = sortadjacent($array, $order);

Note that this function does not make changes to $array, but instead returns the expected result in a new array.


问:
Bootstrap flex: in one row, one col has full height and the other has verticaly center aligned elements
Im strugling with bootstrap 4 trying to verticaly align the elements of the right column and have a full height column on the the left col, just to have a background color. I ve seen so many posts about these issues but none about this specific aproach

My HTML

```<code><div class="container-fluid">
    <div class="row ">
        <div class="col-md-6 ">
            <div class="content colour-1">
                //Just want a full height background color

              </div>
        </div>
        <div class="col-md-6 ..->class?">
            <form [formGroup]="loginForm" (ngSubmit)="onSubmit()" >
                //I just want this small form vertically aligned - center
            </form>
        </div>
    </div>
</div>
</code>```

How can I achieve this? Can it be done only with bootstrap 4? Notice i'm using Angular, so these are my dependencies:

```<code> "dependencies": {
    "@angular/animations": "~9.1.9",
    "@angular/cdk": "^9.2.4",
    "@angular/common": "~9.1.9",
    "@angular/compiler": "~9.1.9",
    "@angular/core": "~9.1.9",
    "@angular/flex-layout": "^9.0.0-beta.31",
    "@angular/forms": "~9.1.9",
    "@angular/localize": "~9.1.9",
    "@angular/material": "^9.2.4",
    "@angular/platform-browser": "~9.1.9",
    "@angular/platform-browser-dynamic": "~9.1.9",
    "@angular/router": "~9.1.9",
    "@ng-bootstrap/ng-bootstrap": "^6.1.0", -->NG-BOOTSRAP
    "bootstrap": "^4.4.0", --->BOOTSRAP
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
</code>```

答:
```<code><div class="container">
    <div class="row" style="height: 100vh">
        <div class="col-6 d-flex flex-grow-auto">
            <div class="content colour-1">
                //Just want a full background color

            </div>
        </div>
        <div class="col-6 flex-row d-flex flex-column justify-content-center">
            <input class="form-control">
            <input class="form-control">

        </div>
        </div>

    </div>
</code>```

Body:
Im strugling with bootstrap 4 trying to verticaly align the elements of the right column and have a full height column on the the left col, just to have a background color. I ve seen so many posts about these issues but none about this specific aproach

My HTML

                //Just want a full height background color

class?">
            <form [formGroup]="loginForm" (ngSubmit)="onSubmit()" >
                //I just want this small form vertically aligned - center
            </form>

How can I achieve this? Can it be done only with bootstrap 4? Notice i'm using Angular, so these are my dependencies:

 "dependencies": {
    "@angular/animations": "~9.1.9",
    "@angular/cdk": "^9.2.4",
    "@angular/common": "~9.1.9",
    "@angular/compiler": "~9.1.9",
    "@angular/core": "~9.1.9",
    "@angular/flex-layout": "^9.0.0-beta.31",
    "@angular/forms": "~9.1.9",
    "@angular/localize": "~9.1.9",
    "@angular/material": "^9.2.4",
    "@angular/platform-browser": "~9.1.9",
    "@angular/platform-browser-dynamic": "~9.1.9",
    "@angular/router": "~9.1.9",
    "@ng-bootstrap/ng-bootstrap": "^6.1.0", -->NG-BOOTSRAP
    "bootstrap": "^4.4.0", --->BOOTSRAP
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },


问:
Change Active Menu Item on Page Scroll?
As you scroll down the page, the active menu item changes.  How is this done?</p>

答:
If you want the accepted answer to work in JQuery 3 change the code like this:

```<code>var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });
</code>```

I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)

Title: Change Active Menu Item on Page Scroll?

Body:
If you want the accepted answer to work in JQuery 3 change the code like this:

var scrollItems = menuItems.map(function () {
    var id = $(this).attr("href");
    try {
        var item = $(id);
      if (item.length) {
        return item;
      }
    } catch {}
  });

I also added a try-catch to prevent javascript from crashing if there is no element by that id. Feel free to improve it even more ;)


问:
Using the vala programming language, can you detect when other applications are full screen or maximized, and suspend their own programs?
Using the vala programming language, can you detect when other applications are full screen or maximized, and suspend their own programs?
Is there a similar Demo?</p>

答:
This is something that can only be done by asking the window manager/compositor, since that is the component that actually deals with this kind of thing. And depending on the session type, this will or will not work.

In Wayland, it is impossible to query info/events about other windows for security reasons.

In X, this might be possible using things like xwininfo (see for more info https://stackoverflow.com/a/1018185/2921914). You can either directly call it and parse the result, or see which parts of the X protocol it uses by looking at its source code.

Since you mentioned [gnome] as a tag, you might be able to do this by writing your own GNOME Shell extension, since this has direct access GNOME Shell's internals.


问:
Problem solving - Coding Interview Question?
So I came along this mock interview question, I have to find a solution to this problem without using functions repelem or repmat.
Only 3 lines of code are allowed with the format: (only one  = operator per line)

p=... , q1=.... , q2=....,

So far I only got a solution using repelem, but when I try to change my code I always have to use more lines of code when indexing. Very thankful for any hints you got for me :)

```<code>p=[4 2 5 3 1]

q1 = repelem((1:length(p)),p)
q2 = repelem(p,p)
</code>```

Here is the question, if anyone wants to try by himself (designed for MATLAB, but can be done anywhere)

Let p be a vector with k different positive integer elements and s=sum(p). Two vectors q1 and q2 shall be determined such that:

• q1 is a vector of length s. The first p(1) elements of q1 are equal to 1, the next p(2) elements are equal to 2, . . . , the last p(k) elements are equal to k.

• q2 is a vector of length s. The first p(1) elements of q2 are equal to p(1), the next p(2) elements are equal to p(2), . . . , the last p(k) elements are equal to p(k).

答:
Typing this from a phone so not sure if the syntax is correct.

Using list comprehension we can flatten a list of lists, and using [x]*y we can create a list that repeats x y times.

```<code>q1 = [e for l in [[i+1]*px for i,px in enumerate(p)] for e in l]
</code>```

Im sure q2 is similar?

Body:
So I came along this mock interview question, I have to find a solution to this problem without using functions repelem or repmat.
Only 3 lines of code are allowed with the format: (only one  = operator per line)

p=... , q1=.... , q2=....,

So far I only got a solution using repelem, but when I try to change my code I always have to use more lines of code when indexing. Very thankful for any hints you got for me :)

p=[4 2 5 3 1]

q1 = repelem((1:length(p)),p)
q2 = repelem(p,p)

Here is the question, if anyone wants to try by himself (designed for MATLAB, but can be done anywhere)

Let p be a vector with k different positive integer elements and s=sum(p). Two vectors q1 and q2 shall be determined such that:

• q1 is a vector of length s. The first p(1) elements of q1 are equal to 1, the next p(2) elements are equal to 2, . . . , the last p(k) elements are equal to k.

• q2 is a vector of length s. The first p(1) elements of q2 are equal to p(1), the next p(2) elements are equal to p(2), . . . , the last p(k) elements are equal to p(k).

Body:
Typing this from a phone so not sure if the syntax is correct.

Using list comprehension we can flatten a list of lists, and using [x]*y we can create a list that repeats x y times.

q1 = [e for l in [[i+1]*px for i,px in enumerate(p)] for e in l]

Im sure q2 is similar?


问:
getting the address of the function?
I'm writing this code and printing this line below shows me the address, how is that possible?</p>

```<code>struct back
{
    static const int y = 7;
    static int f(int i = 0)
    {
        return i / 2;
    }
};
</code>```

```<code>std::cout << back::f;      // 003A143D
</code>```

答:
getting the address of the function?

You can get the address of a function using the addressof operator &. The result (except in case of non-static member function) is a pointer to a function. The function lvalue can implicitly convert to a pointer to the function before lvalue to rvalue conversion. This implicit conversion is called decaying.

printing this line below shows me the address, how is that possible?

This may be possible due to some language extension. The standard doesn't specify overloads for inserting function pointers to character streams. Standard conforming behaviour would be to print 1 because function pointer implicitly converts to bool which does have stream insertion overload, and the address of function is never null.

This is hardly ever intended behaviour which is why high quality compilers warn by default when function decays to a pointer.

Title: getting the address of the function?

Body:
I'm writing this code and printing this line below shows me the address, how is that possible?

struct back
{
    static const int y = 7;
    static int f(int i = 0)
    {
        return i / 2;
    }
};

std::cout << back::f;      // 003A143D