问:
how to fix Error: export 'ɵsupportsWebAnimations'
im trying to replicate this component:

stackblitz.com/edit/angular-material-star-rating?file=package.json

however, on my project im unable to run it due to the following errors:

```<code>./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:9-31 - Error: export 'ɵsupportsWebAnimations' (imported as 'ɵsupportsWebAnimations') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)

./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:69-88 - Error: export 'ɵCssKeyframesDriver' (imported as 'ɵCssKeyframesDriver') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)
</code>```

i have already did the

```<code>npm install --save @angular/material @angular/cdk @angular/animations --force
</code>```

答:
I changed @angular/animations version and I solved this problem.

on package.json,

```<code>"@angular/animations": "13.0.1",
"@angular/cdk": "13.0.1",
"@angular/common": "13.0.1",
"@angular/compiler": "13.0.1",
"@angular/core": "13.0.1",
"@angular/forms": "13.0.1",
"@angular/language-service": "13.0.1",
"@angular/platform-browser": "13.0.1",
"@angular/platform-browser-dynamic": "13.0.1",
"@angular/router": "13.0.1",
</code>```

When @angular/animations version is 13.2.3 (latest), same problem has occurred.
Fix your version same with angular version.

Body:
im trying to replicate this component:

stackblitz.com/edit/angular-material-star-rating?file=package.json

however, on my project im unable to run it due to the following errors:

./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:9-31 - Error: export 'ɵsupportsWebAnimations' (imported as 'ɵsupportsWebAnimations') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)

./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:69-88 - Error: export 'ɵCssKeyframesDriver' (imported as 'ɵCssKeyframesDriver') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)

i have already did the

npm install --save @angular/material @angular/cdk @angular/animations --force

Body:
I changed @angular/animations version and I solved this problem.

on package.json,

"@angular/animations": "13.0.1",
"@angular/cdk": "13.0.1",
"@angular/common": "13.0.1",
"@angular/compiler": "13.0.1",
"@angular/core": "13.0.1",
"@angular/forms": "13.0.1",
"@angular/language-service": "13.0.1",
"@angular/platform-browser": "13.0.1",
"@angular/platform-browser-dynamic": "13.0.1",
"@angular/router": "13.0.1",

When @angular/animations version is 13.2.3 (latest), same problem has occurred.
Fix your version same with angular version.


来源: stackexchange

问:
ArrayList vs HashSet
I was working on this problem https://cses.fi/problemset/task/1660, and here's my code:

```<code>import java.util.*;
public class SubarraySumsI {

public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    int N = in.nextInt();
    int X = in.nextInt();

    ArrayList <Long> prefix = new ArrayList <Long> ();
    int count = 0;
    prefix.add(0l);
    long prefixsum = 0;
    for (int a = 0; a < N; a++) {
        prefixsum += in.nextInt();
        prefix.add(prefixsum);

        if (prefix.contains(prefixsum - X)) {
            count++;
        }
    }

    System.out.println(count);
    in.close();
  }
}
</code>```

I noticed that on a lot of the test cases, it was really slow. However, if I just change prefix from an ArrayList to a HashSet, it suddenly becomes a lot faster.

I'm not that experienced with using Sets and HashSets yet, so can someone explain what the difference is between ArrayList and HashSet?

答:
The question that you asked

"Can someone explain what the difference is between ArrayList and HashSet?"

is too broad.  There are many differences, and you should be able to find many resources that summarize them.

The (probable) specific thing that is causing a performance difference in your program will be this:

```<code> if (list.contains(prefixsum - X)) {
        count++;
 }
</code>```

versus (presumably)

```<code> if (set.contains(prefixsum - X)) {
        count++;
 }
</code>```

In the ArrayList case, the contains method has to test each element of the list until it either find a match or reaches the end.  The time taken to do that will typically be proportional to the number of elements in the list.

In the HashSet case, a hash table data structure is used which (typically) reduces the number of elements that need to be tested to a small number.

The net result is that contain is fast for a HashSet and slow for ArrayList.

Explaining in detail how hash tables work in general and specifically in the HashSet case is beyond the scope of this Q&A.

ContentLicense: CC BY-SA 4.0

Title: ArrayList vs HashSet

Body:
I was working on this problem https://cses.fi/problemset/task/1660, and here's my code:

import java.util.*;
public class SubarraySumsI {

public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    int N = in.nextInt();
    int X = in.nextInt();

    ArrayList <Long> prefix = new ArrayList <Long> ();
    int count = 0;
    prefix.add(0l);
    long prefixsum = 0;
    for (int a = 0; a < N; a++) {
        prefixsum += in.nextInt();
        prefix.add(prefixsum);

        if (prefix.contains(prefixsum - X)) {
            count++;
        }
    }

    System.out.println(count);
    in.close();
  }
}

I noticed that on a lot of the test cases, it was really slow. However, if I just change prefix from an ArrayList to a HashSet, it suddenly becomes a lot faster.

I'm not that experienced with using Sets and HashSets yet, so can someone explain what the difference is between ArrayList and HashSet?

Body:
The question that you asked

"Can someone explain what the difference is between ArrayList and HashSet?"

is too broad.  There are many differences, and you should be able to find many resources that summarize them.

The (probable) specific thing that is causing a performance difference in your program will be this:

 if (list.contains(prefixsum - X)) {
        count++;
 }

versus (presumably)

 if (set.contains(prefixsum - X)) {
        count++;
 }

In the ArrayList case, the contains method has to test each element of the list until it either find a match or reaches the end.  The time taken to do that will typically be proportional to the number of elements in the list.

In the HashSet case, a hash table data structure is used which (typically) reduces the number of elements that need to be tested to a small number.

The net result is that contain is fast for a HashSet and slow for ArrayList.

Explaining in detail how hash tables work in general and specifically in the HashSet case is beyond the scope of this Q&A.


问:
constructor parameter type as optional lookup property
i've just started creating constructors based on my interfaces and i'm stuck here, where "Property 'message' does not exist on type '{ message: string; } | undefined'" in the errorMessage parameter's lookup type:

interface fetchResponse {
  data:null|object|any[];
  error?:{
    message:string;
  };
};
interface FetchResponse extends fetchResponse {};
class FetchResponse {
  constructor(data:fetchResponse["data"], errorMessage?:fetchResponse["error"]["message"]) {
    this.data = data;
    this.error = errorMessage ? {
      message: errorMessage,
    } : undefined;
  };
};
```
<p>i found the following possible ways to fix this, but i've been able to successfully implement none:</p>
<ol>
<li>resolving the property of <code>error</code> based on the property of <code>data</code> (i.e if <code>data</code> is an object/array then <code>error</code> is undefined, and if <code>data</code> is null then <code>error</code> and <code>error.message</code> are defined), which <em>should</em> make it so that <code>error</code> is not possibly undefined if i'm trying to pass an <code>errorMessage</code>: the only way i found to maybe do that is with a union (according to this SO post), but imitating that as seen below only caused typescript to flag 2 more problems which i'm clueless about in the latter half of the code</li>
</ol>
<pre class="lang-ts prettyprint-override"><code>interface fetchResponsePositive {
  data:object|any[];
};
interface fetchResponseNegative {
  data:null;
  error: {
    message:string;
  };
};

type fetchResponse = fetchResponsePositive | fetchResponseNegative;
</code>```

overloading (according to this OS post)? this is my first ever exposure to the concept of overloading, after looking it up i understand the concept but cant figure out how to implement it here in a way that solves the issue (or whether it's even a solution to this)

adding a definite assertion to the fetchResponse["error"]["message"] lookup: i just have no idea how to do that, i placed the exclamation mark in every conceivable spot to no success

答:
Here's a utility type that should allow you to get around this issue (inspired by type-fest's Get helper):

type Get<T, K> = T extends undefined ? undefined : K extends keyof T ? T[K] : unknown;
```
<p>It will fetch the type at a given key, even when the base type is optional. You can use it like this:</p>
<pre class="lang-js prettyprint-override"><code>class FetchResponse {
  constructor(data:fetchResponse["data"], errorMessage?:Get<fetchResponse["error"], "message">) {
    this.data = data;
    this.error = errorMessage ? {
      message: errorMessage,
    } : undefined;
  };
};
</code>```

It should evaluate to string | undefined, which I assume is what you want. (If you don't want undefined there, you can always use the Exclude utility type to remove it from the union.)

Body:
i've just started creating constructors based on my interfaces and i'm stuck here, where "Property 'message' does not exist on type '{ message: string; } | undefined'" in the errorMessage parameter's lookup type:

interface fetchResponse {
  data:null|object|any[];
  error?:{
    message:string;
  };
};
interface FetchResponse extends fetchResponse {};
class FetchResponse {
  constructor(data:fetchResponse["data"], errorMessage?:fetchResponse["error"]["message"]) {
    this.data = data;
    this.error = errorMessage ? {
      message: errorMessage,
    } : undefined;
  };
};

i found the following possible ways to fix this, but i've been able to successfully implement none:

resolving the property of error based on the property of data (i.e if data is an object/array then error is undefined, and if data is null then error and error.message are defined), which should make it so that error is not possibly undefined if i'm trying to pass an errorMessage: the only way i found to maybe do that is with a union (according to this SO post), but imitating that as seen below only caused typescript to flag 2 more problems which i'm clueless about in the latter half of the code

interface fetchResponsePositive {
  data:object|any[];
};
interface fetchResponseNegative {
  data:null;
  error: {
    message:string;
  };
};

type fetchResponse = fetchResponsePositive | fetchResponseNegative;

overloading (according to this OS post)? this is my first ever exposure to the concept of overloading, after looking it up i understand the concept but cant figure out how to implement it here in a way that solves the issue (or whether it's even a solution to this)

adding a definite assertion to the fetchResponse["error"]["message"] lookup: i just have no idea how to do that, i placed the exclamation mark in every conceivable spot to no success

Body:
Here's a utility type that should allow you to get around this issue (inspired by type-fest's Get helper):

type Get<T, K> = T extends undefined ? undefined : K extends keyof T ? T[K] : unknown;

It will fetch the type at a given key, even when the base type is optional. You can use it like this:

class FetchResponse {
  constructor(data:fetchResponse["data"], errorMessage?:Get<fetchResponse["error"], "message">) {
    this.data = data;
    this.error = errorMessage ? {
      message: errorMessage,
    } : undefined;
  };
};

It should evaluate to string | undefined, which I assume is what you want. (If you don't want undefined there, you can always use the Exclude utility type to remove it from the union.)


问:
How can I stop isNaN from returning an error for a blank field?
EDIT:

Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,

When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?

I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!

答:
Why don't you use 3 different functions or an argument to identify which of the inputs the user is pressing? If each of the inputs calls checkNumber(1), checkNumber(2) and checkNumber(3) you can only validate the input that the user is using instead of validating all 3 at the same time.

Alternatively you can use input validation and instead of an alert just return false to prevent the user from inputing invalid chars

ContentLicense: CC BY-SA 3.0


问:
Python: whats does comma mean in in [ : ,1 ]
guys I am new to python and learning machine learning.I have trouble understanding what does this line of code mean:-

```<code>y_scores_knn = y_probas_knn[:,1]
</code>```

I didnt get what  ,1 mean inside an array box [] and what it does

答: if x is a two dimensional array (a matrix) then x[:,1] is the second column (all elements where the second index is 1). This notation is quite common for things like octave, matlab and numpy which have a concept of a two dimensional array.  While it does work for numpy, it will not work for a python list of lists.  A list of lists that happen to have the same number of elements is just another one dimensional list as far as python is concerned. If you want to do work with matrices and you want to use python, use numpy.</p>

Body:
guys I am new to python and learning machine learning.I have trouble understanding what does this line of code mean:-

y_scores_knn = y_probas_knn[:,1]

I didnt get what  ,1 mean inside an array box [] and what it does


问:
Copy original array with empty values
I have the following array:

```<code>arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
</code>```

How can I get this array as:

```<code>arr2 = [{Name: "", Email: "", Age: ""}]
</code>```

without mutating arr1

I have tried doing:

```<code>let arr2 = arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log(arr2) //returns [{Name: "", Email: "", Age: ""}]
</code>```

but this mutates arr1[0] with empty values as well

I have searched a lot of questions on SO, but couldn't get anything that would set all the values empty.

答:
You're passing by reference instead of copying the array.

https://dmitripavlutin.com/value-vs-reference-javascript/#:~:text=In%20JavaScript%2C%20you%20can%20pass,by%20reference%20when%20assigning%20objects.

Here's your code refactored to work as intended.

arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
let arr2 = {...arr1[0]} // make a copy of arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log([arr2]) //returns [{Name: "", Email: "", Age: ""}]```

Title: Copy original array with empty values

Body:
I have the following array:

arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]

How can I get this array as:

arr2 = [{Name: "", Email: "", Age: ""}]

without mutating arr1

I have tried doing:

let arr2 = arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log(arr2) //returns [{Name: "", Email: "", Age: ""}]

but this mutates arr1[0] with empty values as well

I have searched a lot of questions on SO, but couldn't get anything that would set all the values empty.


问:
"GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)" error
Google thinks that I am trying to read data from localhost:8801, but I am trying to read that data from another file called "main.js." The error is "GET http://localhost:8801/main.js net::ERR_ABORTED 404 (Not Found)" How can I reference the command from main.js without google thinking that it is a subdirectory. Here is my code in index.html:

https://sourceb.in/iuMyon5XI7

Thank you in advance.

答:
Ok so I was doing some more research over the past few weeks and I realized I was coming about this all wrong. Require is a feature specific to node.js, and because chrome does not just automatically have node.js, it does not work. What I was attempting to do was read a JSON file and output it into some HTML so I can view it there. The solution I found is to get express.js and make an API. So something like

`

```<code>app.get("/api/database", (req, res) => {
    res.sendFile(__dirname + '/DB.json')
})
</code>```

`

And on the HTML side you can add `

```<code>fetch('/api/database')
        .then(response => response.json())
        .then(data => {
            console.log(data.Input1)
            document.querySelector("#debug").innerText = data.Input1
        })
</code>```

`
With

Right above the script tags.

Thanks to everyone who helped. The video I took the html side of the code can be found here.

Body:
Ok so I was doing some more research over the past few weeks and I realized I was coming about this all wrong. Require is a feature specific to node.js, and because chrome does not just automatically have node.js, it does not work. What I was attempting to do was read a JSON file and output it into some HTML so I can view it there. The solution I found is to get express.js and make an API. So something like

`

app.get("/api/database", (req, res) => {
    res.sendFile(__dirname + '/DB.json')
})

`

And on the HTML side you can add `

fetch('/api/database')
        .then(response => response.json())
        .then(data => {
            console.log(data.Input1)
            document.querySelector("#debug").innerText = data.Input1
        })

`
With

<div id="debug"></div>

Right above the script tags.

Thanks to everyone who helped. The video I took the html side of the code can be found here.


答:
The error

```<code>No applicable_loaders found for UNKNOWN
</code>```

indicates that load does not know how to load the file; specifically a .txt file. There are two options to fix this:

Explicitly state that the file is CSV, which it does know how to load:

```<code>df = load(File(format"CSV", "testfile.txt"), spacedelim=true, header_exists=false)
    |> DataFrame
</code>```

Rename your data file to have a csv extension

```<code>df = load("testfile.csv", spacedelim=true, header_exists=false) |> DataFrame
</code>```

Both will produce the output:

```<code>    7×4 DataFrame
     Row │ Column1  Column2  Column3     Column4
         │ Float64  Float64  Float64     Float64
    ─────┼───────────────────────────────────────
       1 │   5.0e6    1.0e7  1.86965e13  20000.0
       2 │   1.5e7    1.0e7  1.67889e13  20000.0
       3 │   2.5e7    1.0e7  1.50764e13  20000.0
       4 │   3.5e7    1.0e7  1.35391e13  20000.0
       5 │   4.5e7    1.0e7  1.21591e13  20000.0
       6 │   5.5e7    1.0e7  1.09201e13  20000.0
       7 │   6.5e7    1.0e7  9.80791e12  20000.0
</code>```

Note the addition of the spacedelim=true to read space delimited values, which is what you supplied as the example data file contents.

Title: Julia: Error reading tabular data from a txt file

Body:
I have the file called testfile.txt in my working directory.

5.00000000E+06  1.00000000E+07  1.86965370E+13  2.00000000E+04
1.50000000E+07  1.00000000E+07  1.67889215E+13  2.00000000E+04
2.50000000E+07  1.00000000E+07  1.50764483E+13  2.00000000E+04
3.50000000E+07  1.00000000E+07  1.35391442E+13  2.00000000E+04
4.50000000E+07  1.00000000E+07  1.21590771E+13  2.00000000E+04
5.50000000E+07  1.00000000E+07  1.09201484E+13  2.00000000E+04
6.50000000E+07  1.00000000E+07  9.80790597E+12  2.00000000E+04

I want to store this tabular data in a dataframe.

# using necessary packages
using DataFrames, Queryverse

df = load("testfile.txt",
           header_exists = false) |> DataFrame

When I try this though, I get the error:

No applicable_loaders found for UNKNOWN

How can I resolve this?

Body:
The error

No applicable_loaders found for UNKNOWN

indicates that load does not know how to load the file; specifically a .txt file. There are two options to fix this:

Explicitly state that the file is CSV, which it does know how to load:

df = load(File(format"CSV", "testfile.txt"), spacedelim=true, header_exists=false)
    |> DataFrame

Rename your data file to have a csv extension

df = load("testfile.csv", spacedelim=true, header_exists=false) |> DataFrame

Both will produce the output:

    7×4 DataFrame
     Row │ Column1  Column2  Column3     Column4
         │ Float64  Float64  Float64     Float64
    ─────┼───────────────────────────────────────
       1 │   5.0e6    1.0e7  1.86965e13  20000.0
       2 │   1.5e7    1.0e7  1.67889e13  20000.0
       3 │   2.5e7    1.0e7  1.50764e13  20000.0
       4 │   3.5e7    1.0e7  1.35391e13  20000.0
       5 │   4.5e7    1.0e7  1.21591e13  20000.0
       6 │   5.5e7    1.0e7  1.09201e13  20000.0
       7 │   6.5e7    1.0e7  9.80791e12  20000.0

Note the addition of the spacedelim=true to read space delimited values, which is what you supplied as the example data file contents.


问:
Kubernetes, cannot mount NFS share via DNS
I am trying to mount a NFS share (outside of k8s cluster) in my container via DNS lookup, my config is as below

```<code>apiVersion: v1
kind: Pod
metadata:
  name: service-a
spec:
  containers:
  - name: service-a
    image: dockerregistry:5000/centOSservice-a
    command: ["/bin/bash"]
    args: ["/etc/init.d/jboss","start"]
    volumeMounts:
      - name: service-a-vol
        mountPath: /myservice/por/data
  volumes:
    - name: service-a-vol
      nfs:
        server: nfs.service.domain
        path: "/myservice/data"
  restartPolicy: OnFailure
</code>```

nslookup of nfs.service.domin works fine from my container. This is achiveded via StubDomain . However when creating the container it fails to resolve the nfs server. Error:

```<code>Warning  FailedMount  <invalid>  kubelet, worker-node-1  MountVolume.SetUp failed for volume "service-a-vol" : mount failed: exit status 32
Mounting command: systemd-run
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/44aabfb8-2767-11e8-bcf9-fa163ece9426/volumes/kubernetes.io~nfs/service-a-vol --scope -- mount -t nfs nfs.service.domain:/myservice/data /var/lib/kubelet/pods/44aabfb8-2767-11e8-bcf9-fa163ece9426/volumes/kubernetes.io~nfs/service-a-vol
Output: Running scope as unit run-27293.scope.
mount.nfs: Failed to resolve server nfs.service.domain: Name or service not known
mount.nfs: Operation already in progress
</code>```

If i modify server: nfs.service.domain to server: 10.10.1.11 this works fine! So to summarise

DNS resolution of the service works fine

Mounting via DNS resolution does not

Mounting via specific IP address works

I have tried Headless Service instead of StubDomain but the same issue exists

Any help much appreciated

Update 1: If i add an entry in the /etc/hosts files of worker/master nodes 10.10.1.11 nfs.service.domain then my configuration above server: nfs.service.domain works. This is obviously not a desired workaround...

答: try to use full service name as follow "[service-name].[service-namespace].svc.cluster.local".</p>

Body:
I am trying to mount a NFS share (outside of k8s cluster) in my container via DNS lookup, my config is as below

apiVersion: v1
kind: Pod
metadata:
  name: service-a
spec:
  containers:
  - name: service-a
    image: dockerregistry:5000/centOSservice-a
    command: ["/bin/bash"]
    args: ["/etc/init.d/jboss","start"]
    volumeMounts:
      - name: service-a-vol
        mountPath: /myservice/por/data
  volumes:
    - name: service-a-vol
      nfs:
        server: nfs.service.domain
        path: "/myservice/data"
  restartPolicy: OnFailure

nslookup of nfs.service.domin works fine from my container. This is achiveded via StubDomain . However when creating the container it fails to resolve the nfs server. Error:

Warning  FailedMount  <invalid>  kubelet, worker-node-1  MountVolume.SetUp failed for volume "service-a-vol" : mount failed: exit status 32
Mounting command: systemd-run
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/44aabfb8-2767-11e8-bcf9-fa163ece9426/volumes/kubernetes.io~nfs/service-a-vol --scope -- mount -t nfs nfs.service.domain:/myservice/data /var/lib/kubelet/pods/44aabfb8-2767-11e8-bcf9-fa163ece9426/volumes/kubernetes.io~nfs/service-a-vol
Output: Running scope as unit run-27293.scope.
mount.nfs: Failed to resolve server nfs.service.domain: Name or service not known
mount.nfs: Operation already in progress

If i modify server: nfs.service.domain to server: 10.10.1.11 this works fine! So to summarise

DNS resolution of the service works fine

Mounting via DNS resolution does not

Mounting via specific IP address works

I have tried Headless Service instead of StubDomain but the same issue exists

Any help much appreciated

Update 1: If i add an entry in the /etc/hosts files of worker/master nodes 10.10.1.11 nfs.service.domain then my configuration above server: nfs.service.domain works. This is obviously not a desired workaround...


问:
{{ @require_once(@resource_path()) }} causes a random 1 string character to be outputted in laravel
I have tried looking for the character with ctrl + f, I checked my web.php, checked the layouts file and the file itself. Nowhere do I output the character 1 ("1 ").
I emptied the file and then tried it again, it returns the "1 ". I tried it with other files, same. The only time it does not happen is when I completely remove {{ @require_once(@resource_path("views/includes/myFile.blade.php)) }}. The character is printed on every page as well.

This is how my layout.blade.php file looks like:

```<code><!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <title>
            layout Component
        </title>

        @yield("head_css")

        @yield("head_js")
    </head>
    <body>
        <div class="card">
            <div class="card-header">
               {{ @require_once(@resource_path("views/Includes/navigation.blade.php")) }}
            </div>
            <div class="card-body">
                @yield("body_content")
            </div>
            <div class="card-footer">
                @yield("footer")
            </div>
        </div>
    </body>
</html>
</code>```

this is how my navigation.blade.php looks like:

```<code><nav class="navbar navbar-expand-md navbar-light">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="#">
                    hello
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">
                    <select class="selectpicker" data-width="fit">
                        <option>a</option>
                        <option>b</option>
                    </select>
                </a>
            </li>
        </ul>
    </div>
</nav>
</code>```

答:
This line has multiple issues:

```<code>{{ @require_once(@resource_path("views/Includes/navigation.blade.php")) }}
</code>```

The curly braces are for outputting data, like an echo statement. Additionally it encodes HTML entities, which you definitely don't want. See https://laravel.com/docs/master/blade#including-subviews.

It looks like you are trying to include another blade view file that is already inside your views path. You should be able then to use the @include directive as documented here: https://laravel.com/docs/master/blade#including-subviews.

So I think you want to do something like this:

```<code>@include("Includes.navigation"))
</code>```

Body:
I have tried looking for the character with ctrl + f, I checked my web.php, checked the layouts file and the file itself. Nowhere do I output the character 1 ("1 ").
I emptied the file and then tried it again, it returns the "1 ". I tried it with other files, same. The only time it does not happen is when I completely remove {{ @require_once(@resource_path("views/includes/myFile.blade.php)) }}. The character is printed on every page as well.

This is how my layout.blade.php file looks like:

<!DOCTYPE html>
getLocale() }}">

        <title>
            layout Component
        </title>

        @yield("head_css")

        @yield("head_js")

               {{ @require_once(@resource_path("views/Includes/navigation.blade.php")) }}

                @yield("body_content")

                @yield("footer")

this is how my navigation.blade.php looks like:

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                    hello

                    <select class="selectpicker" data-width="fit">
                        <option>a</option>
                        <option>b</option>
                    </select>

Body:
This line has multiple issues:

{{ @require_once(@resource_path("views/Includes/navigation.blade.php")) }}

The curly braces are for outputting data, like an echo statement. Additionally it encodes HTML entities, which you definitely don't want. See https://laravel.com/docs/master/blade#including-subviews.

It looks like you are trying to include another blade view file that is already inside your views path. You should be able then to use the @include directive as documented here: https://laravel.com/docs/master/blade#including-subviews.

So I think you want to do something like this:

@include("Includes.navigation"))


问:
Vue : Vue Formulate input custom error message
I using Vue Formulate for form validation. When submit the error message show Formid is required., but I want Form ID is required

```<code>  <FormulateForm
    class="login-form"
    v-model="formValues"
    @submit="submitHandler"
  >
    <FormulateInput
      name="formid"
      type="text"
      label="Form ID"
      placeholder=""
      validation="required"

    />
    <FormulateInput
      type="submit"
      label="Log In"
    />
  </FormulateForm>
</code>```

答:
Use custom validation message link , validation-name props to replace default name

```<code>  <FormulateForm
    class="login-form"
    v-model="formValues"
    @submit="submitHandler"
  >
    <FormulateInput
      name="formid"
      type="text"
      label="Form ID"
      placeholder=""
      validation="required"
      validation-name="Form ID"
    />
    <FormulateInput
      type="submit"
      label="Log In"
    />
  </FormulateForm>
</code>```

Body:
I using Vue Formulate for form validation. When submit the error message show Formid is required., but I want Form ID is required

  <FormulateForm
    class="login-form"
    v-model="formValues"
    @submit="submitHandler"
  >
    <FormulateInput
      name="formid"
      type="text"
      label="Form ID"
      placeholder=""
      validation="required"

    />
    <FormulateInput
      type="submit"
      label="Log In"
    />
  </FormulateForm>

Body:
Use custom validation message link , validation-name props to replace default name

  <FormulateForm
    class="login-form"
    v-model="formValues"
    @submit="submitHandler"
  >
    <FormulateInput
      name="formid"
      type="text"
      label="Form ID"
      placeholder=""
      validation="required"
      validation-name="Form ID"
    />
    <FormulateInput
      type="submit"
      label="Log In"
    />
  </FormulateForm>


问:
Combining pandas dataframes according to other dataframes
Right now, I have 3 pandas dfs that I want to combine. Below is a short version of what I'm working with. Basically, dfs 2 and 3 have the indices that correspond to df1. I want to create another column on the first df that has the labels I want according to the indices of dfs 2 and 3 (please see below for a reference of what my desired result is).
Any help is very appreciated! Thank you!

```<code>#df 1
Animal Number
2
4
6
9
11

#df 2
Lions
2
11

#df 3
Tigers
4
6
9
</code>```

This is what I would want my result to look like:

```<code>Animal #  Animal Type
0   2   Lion
1   4   Tiger
2   6   Tiger
3   9   Tiger
4   11  Lion
</code>```

答:
Try:

```<code>m = pd.concat([df2, df3], axis=1).stack().reset_index().set_index(0)['level_1']
df1['Animal Type'] = df1['Animal Number'].map(m)
print(df1)
</code>```

Output:

```<code>   Animal Number Animal Type
0              2       Lions
1              4      Tigers
2              6      Tigers
3              9      Tigers
4             11       Lions
</code>```

Body:
Right now, I have 3 pandas dfs that I want to combine. Below is a short version of what I'm working with. Basically, dfs 2 and 3 have the indices that correspond to df1. I want to create another column on the first df that has the labels I want according to the indices of dfs 2 and 3 (please see below for a reference of what my desired result is).
Any help is very appreciated! Thank you!

#df 1
Animal Number
2
4
6
9
11

#df 2
Lions
2
11

#df 3
Tigers
4
6
9

This is what I would want my result to look like:

Animal #  Animal Type
0   2   Lion
1   4   Tiger
2   6   Tiger
3   9   Tiger
4   11  Lion

Body:
Try:

m = pd.concat([df2, df3], axis=1).stack().reset_index().set_index(0)['level_1']
df1['Animal Type'] = df1['Animal Number'].map(m)
print(df1)

Output:

   Animal Number Animal Type
0              2       Lions
1              4      Tigers
2              6      Tigers
3              9      Tigers
4             11       Lions


问:
Getting this error: warning: too many arguments for format [-Wformat-extra-args]
```<code>  printf("\nEnter Matrix A\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &a[i][j]);
    }

  printf("\nEnter Matrix B\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &b[i][j]);
    }
</code>```

When I compile this, I get an error message saying main.c:9:10: warning: too many arguments for format [-Wformat-extra-args] on lines 10 and 16. I’m new to programming C so any tips would be helpful.

答:
Oh I see you are just missing the %i for your printf. No big deal. That what it was telling you. If this helps please give green check. Thank you</p>
```<code>#include <stdio.h>

int main() {
  int r, c, a[100][100], b[100][100], sum[100][100], i, j;
  printf("Enter the number of rows: ");
  scanf("%d", &r);
  printf("Enter the number of columns: ");
  scanf("%d", &c);

  printf("\nEnter Matrix A\n %i,%i", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &a[i][j]);
    }

  printf("\nEnter Matrix B\n %i,%i", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &b[i][j]);
    }

  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      sum[i][j] = a[i][j] + b[i][j];
    }

  printf("\nA + B = \n");
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      printf("%d   ", sum[i][j]);
      if (j == c - 1) {
        printf("\n\n");
      }
    }

  return 0;
}
</code>```

Body:
  printf("\nEnter Matrix A\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &a[i][j]);
    }

  printf("\nEnter Matrix B\n", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &b[i][j]);
    }

When I compile this, I get an error message saying main.c:9:10: warning: too many arguments for format [-Wformat-extra-args] on lines 10 and 16. I’m new to programming C so any tips would be helpful.

Body:
Oh I see you are just missing the %i for your printf. No big deal. That what it was telling you. If this helps please give green check. Thank you

#include <stdio.h>

int main() {
  int r, c, a[100][100], b[100][100], sum[100][100], i, j;
  printf("Enter the number of rows: ");
  scanf("%d", &r);
  printf("Enter the number of columns: ");
  scanf("%d", &c);

  printf("\nEnter Matrix A\n %i,%i", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &a[i][j]);
    }

  printf("\nEnter Matrix B\n %i,%i", i + 1, j + 1);
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      scanf("%d", &b[i][j]);
    }

  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      sum[i][j] = a[i][j] + b[i][j];
    }

  printf("\nA + B = \n");
  for (i = 0; i < r; ++i)
    for (j = 0; j < c; ++j) {
      printf("%d   ", sum[i][j]);
      if (j == c - 1) {
        printf("\n\n");
      }
    }

  return 0;
}


问:
copy everything after a string into a different column in R
I have some columns in a data frame that look like this:

```<code>df <- data.frame(act=c("DEC S/N, de 21/06/2006",
                        "DEC S/N, de 05/06/2006",
                         "DEC S/N, de 21/06/2006; MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"), adj=NA)
</code>```

I would like to copy everything after the first ; (MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012) in the column 'act', into the column 'adj'. Ideally, removing the space that would be left at the star of the cut-off string. All other cells, this is, where the strings in column 'act' do not have a ; should be left NA in column 'adj'.

答:
```<code>df %>%
  extract(act, 'adj', '; (.*)', remove = FALSE)
</code>```

or even try:

```<code>df %>%
  separate(act, c('act1', 'adj'), '; ',
           extra = 'merge', fill = 'right', remove = FALSE)
</code>```

Body:
I have some columns in a data frame that look like this:

df <- data.frame(act=c("DEC S/N, de 21/06/2006",
                        "DEC S/N, de 05/06/2006",
                         "DEC S/N, de 21/06/2006; MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012"), adj=NA)

I would like to copy everything after the first ; (MP 542, de 12/08/2011; LEI 12.678, de 25/06/2012) in the column 'act', into the column 'adj'. Ideally, removing the space that would be left at the star of the cut-off string. All other cells, this is, where the strings in column 'act' do not have a ; should be left NA in column 'adj'.

Body:
df %>%
  extract(act, 'adj', '; (.*)', remove = FALSE)

or even try:

df %>%
  separate(act, c('act1', 'adj'), '; ',
           extra = 'merge', fill = 'right', remove = FALSE)


问:
How to globally specify android and ios are not supported in a .net 5.0 app
I'm using System.IO.Ports in a .net 5.0 project. This generates warnings as follows:

warning CA1416: This call site is reachable on all platforms. 'SerialPort.Close()' is unsupported on: 'ios', 'android'.

I can put guards in to check the platform before calling SerialPort methods, but I calls these in a lot of places.

Instead I was wondering if there was a way to tell .net at the project level that I don't support ios and android.

I don't want to suppress all CA1416 warnings because I do support:

Windows and...

Linux

...and want to be warned if I use something not available on those platforms.

答:
TL; DR: essentially your question is divided into two parts and sadly only one appears to be possible.

1. How to exclude an OS from your project

OP:

How to globally specify android and ios are not supported in a .net 5.0 app

I can put guards in to check the platform before calling SerialPort methods, but I calls these in a lot of places.

Yes. Instead of allowing all destinations that say net5.0 provides, you can fine-tune your output by using the plural <TargetFrameworks> element (note the "s") instead of the default <TargetFramework>1.

Here's an example project that targeting net5.0:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
</Project>
</code>```

The above project will let your app compile for all OSs including Windows, Mac OS, Android and iOS.

Instead I was wondering if there was a way to tell .net at the project level that I don't support ios and android.

Yes.  To achieve that we would use OS-specific TFMs instead of the general net5.0. 1

change <TargetFramework> to <TargetFrameworks>

change net5.0 to net5.0-windows;net5.0-macos

...like so:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net5.0-windows;net5.0-macos</TargetFrameworks>
  </PropertyGroup>
</Project>
</code>```

With this iOS and Android support have been removed.

2. How to exclude Linux

OP:

I don't want to suppress all CA1416 warnings because I do support Windows and Linux

This is where it gets tricky as Microsoft has not defined a TFM for Linux (too many flavours?) so the only way to specify that you want to target Linux is to use net5.0.  Linux support is implied.  Unfortunately this re-activates support for iOS and Android the very thing we just removed.  It also activated MacOS which you might not care about.

1 Target frameworks in SDK-style projects
, MSFT

Body:
TL; DR: essentially your question is divided into two parts and sadly only one appears to be possible.

1. How to exclude an OS from your project

OP:

How to globally specify android and ios are not supported in a .net 5.0 app

I can put guards in to check the platform before calling SerialPort methods, but I calls these in a lot of places.

Yes. Instead of allowing all destinations that say net5.0 provides, you can fine-tune your output by using the plural <TargetFrameworks> element (note the "s") instead of the default <TargetFramework>1.

Here's an example project that targeting net5.0:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
</Project>

The above project will let your app compile for all OSs including Windows, Mac OS, Android and iOS.

Instead I was wondering if there was a way to tell .net at the project level that I don't support ios and android.

Yes.  To achieve that we would use OS-specific TFMs instead of the general net5.0. 1

change <TargetFramework> to <TargetFrameworks>

change net5.0 to net5.0-windows;net5.0-macos

...like so:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net5.0-windows;net5.0-macos</TargetFrameworks>
  </PropertyGroup>
</Project>

With this iOS and Android support have been removed.

2. How to exclude Linux

OP:

I don't want to suppress all CA1416 warnings because I do support Windows and Linux

This is where it gets tricky as Microsoft has not defined a TFM for Linux (too many flavours?) so the only way to specify that you want to target Linux is to use net5.0.  Linux support is implied.  Unfortunately this re-activates support for iOS and Android the very thing we just removed.  It also activated MacOS which you might not care about.

1 Target frameworks in SDK-style projects
, MSFT


问:
Unit testing with Expressions?
I am unit testing some code that interactes with a repository, that takes an expression (Expression<Func<Entity, bool>>) to filter the results, like so:

```<code>int orderId = 10;

_respository.GetFiltered(order => order.Id == orderId);
</code>```

I am having a problem Unit Testing, more specifically setting up expectations that an expression will match.  In a unit test I want to do this:

```<code>_mockRespository.Setup(r => r.GetFiltered(order => order.Id == 10)).Returns(new Order[0]).AtMostOnce();
</code>```

I found one solution that suggested doing .ToString() on each expression and compairing that, however when you reference a variable such as orderId, the expression is completely different!

What are people doing to test this?

Thanks,

David

答:
I'd say this is in part a matter of what you actually want to verify with a unit test, which comes down to your unit testing philosophy.

What we do is we don't necessarily verify that a linq to entities expression parameter passed from type A (under test) uses a specific expression tree when calling GetFoo() on a repository collaborator (not under test). For a unit test, we are content with verifying that method GetFoo() the correct signature is called at all.

In your case it looks like you are using Moq (?), in which case that would become something like this (beware of syntax mess)

```<code>_mockRespository.Setup(r => r.GetFiltered(It.IsAny<Expression<Func<Entity, bool>>>())).Returns(new Order[0]).AtMostOnce();
</code>```

For us, this makes sense because a) mocked method parameter expression tree comparison verification is indeed a pain and b) even if we could verify that parameter, how B actually would interpret different combinations of parameter values might change (as in semantics of contract A->B) and if that's the case, would make the test brittle.

We use automated story tests for testing interaction between production A and production B. We think this is a better way to test these scenarios, since they are typically something like 'filter all A in storage according to expression X and give me all the objects that match'. For us, this makes sense as integration tests (one or two happy cases usually are enough).

If that's not enough for you, I'd read up on a) how to create custom Moq matchers, though I can't say for certain that there is an easy solution (there might very well be) or b) setting up expectation callbacks so you can capture the parameter and inspect it after the test. Something like this:

```<code>    Expression<Func<Entity, bool>> actualExpression = null;
    _mockRespository.Setup(r => r.GetFiltered(It.IsAny<Expression<Func<Entity, bool>>>())).Returns(new Order[0]).AtMostOnce().Callback((Expression<Func<Entity, bool>> expr => { actualExpression = expr});

    // exercise production code

    Assert.IsTrue(actualExpression ...... someithing clever here);
</code>```

Note: All above code was written in the stack overflow editor. Don't hold me accountable if it does not compile, the Moq docs cover this

ContentLicense: CC BY-SA 2.5

Title: Unit testing with Expressions?

Body:
I am unit testing some code that interactes with a repository, that takes an expression (Expression<Func<Entity, bool>>) to filter the results, like so:

int orderId = 10;

_respository.GetFiltered(order => order.Id == orderId);

I am having a problem Unit Testing, more specifically setting up expectations that an expression will match.  In a unit test I want to do this:

_mockRespository.Setup(r => r.GetFiltered(order => order.Id == 10)).Returns(new Order[0]).AtMostOnce();

I found one solution that suggested doing .ToString() on each expression and compairing that, however when you reference a variable such as orderId, the expression is completely different!

What are people doing to test this?

Thanks,

David

Body:
I'd say this is in part a matter of what you actually want to verify with a unit test, which comes down to your unit testing philosophy.

What we do is we don't necessarily verify that a linq to entities expression parameter passed from type A (under test) uses a specific expression tree when calling GetFoo() on a repository collaborator (not under test). For a unit test, we are content with verifying that method GetFoo() the correct signature is called at all.

In your case it looks like you are using Moq (?), in which case that would become something like this (beware of syntax mess)

_mockRespository.Setup(r => r.GetFiltered(It.IsAny<Expression<Func<Entity, bool>>>())).Returns(new Order[0]).AtMostOnce();

For us, this makes sense because a) mocked method parameter expression tree comparison verification is indeed a pain and b) even if we could verify that parameter, how B actually would interpret different combinations of parameter values might change (as in semantics of contract A->B) and if that's the case, would make the test brittle.

We use automated story tests for testing interaction between production A and production B. We think this is a better way to test these scenarios, since they are typically something like 'filter all A in storage according to expression X and give me all the objects that match'. For us, this makes sense as integration tests (one or two happy cases usually are enough).

If that's not enough for you, I'd read up on a) how to create custom Moq matchers, though I can't say for certain that there is an easy solution (there might very well be) or b) setting up expectation callbacks so you can capture the parameter and inspect it after the test. Something like this:

    Expression<Func<Entity, bool>> actualExpression = null;
    _mockRespository.Setup(r => r.GetFiltered(It.IsAny<Expression<Func<Entity, bool>>>())).Returns(new Order[0]).AtMostOnce().Callback((Expression<Func<Entity, bool>> expr => { actualExpression = expr});

    // exercise production code

    Assert.IsTrue(actualExpression ...... someithing clever here);

Note: All above code was written in the stack overflow editor. Don't hold me accountable if it does not compile, the Moq docs cover this


问:
ARKit – How to know if 3d object is in the center of a screen?
I place 3d object in the world space. After that I try to move camera randomly. Then right now I need to know after I knew object has became inside frustum by isNode method, if the object is in center, top or bottom of camera view.

答:
```<code>    func nodeInCenter() -> SCNNode? {
        let x = (Int(sceneView.projectPoint(sceneView.pointOfView!.worldPosition).x - sceneView.projectPoint(sphereNode.worldPosition).x) ^^ 2) < 9
        let y = (Int(sceneView.projectPoint(sceneView.pointOfView!.worldPosition).y - sceneView.projectPoint(sphereNode.worldPosition).y) ^^ 2) < 9
            if x && y {
                return node
            }
            return nil
        }

</code>```


问:
Pythonic "or" operation
In python I can write an expression like 3 < a < 10 and it gets evaluated with an and condition.

That is, 3 < a < 10  is a syntactic sugar for: 3 < a and a < 10

Is there a similar pythonic way to write it as an or condition?

答:
a < 3 or a > 10 is what I would write.

If you had 3 >= a or a >= 10 you could use de Morgan's laws to turn the or into an and, resulting in not (3 < a < 10).

For the specific case of checking if a number is out of range you could use a not in range(3, 11). A neat trick, but the 11 being off by one bugs me. I'd stick with or, myself.

Title: Pythonic "or" operation


答:
let arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
let arr2 = {...arr1[0]}

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1)
console.log(arr2)```

Title: Copy original array with empty values

Body:
I have the following array:

arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]

How can I get this array as:

arr2 = [{Name: "", Email: "", Age: ""}]

without mutating arr1

I have tried doing:

let arr2 = arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log(arr2) //returns [{Name: "", Email: "", Age: ""}]

but this mutates arr1[0] with empty values as well

I have searched a lot of questions on SO, but couldn't get anything that would set all the values empty.


问:
I am trying to assign value for index[arr[i][j]]['x'], i am getting the Cannot set property 'x' of undefined error
Here is my code for reference. I'm getting error for line 9 and 10. Is there a way to assign values for dictionary inside an initially empty dictionary :</p>
```<code>function anticlockwiseRotate(arr){
            //store the index of elements in a dict
            let index={};
            for(let i=0;i<3;i++){
                for(let j=0;j<3;j++){
                    if(!index.hasOwnProperty(arr[i][j]['x']) && !index.hasOwnProperty(arr[i][j]['y'])){
                        //left shift by 2 and change rowInde)
                        //left shift by 2 and change rowIndex->columnIndex
                        index[arr[i][j]]['x'] = (Math.abs(j-2));
                        index[arr[i][j]]['y']=i;
                    }
                }
            }
            let rotatedArr= [];
            for(let idx in index){
                rotatedArr[index[idx][x]][index[idx][y]]=idx;
            }
            return rotatedArr
        }
        console.log(anticlockwiseRotate([[1,2,3],[4,5,6],[7,8,9]]))
</code>```

答:
set index[arr[i][j]] as object before assigning any properties to index[arr[i][j]]

```<code>index[arr[i][j]] = {};
//left shift by 2 and change rowInde)
//left shift by 2 and change rowIndex->columnIndex
index[arr[i][j]]['x'] = (Math.abs(j-2));
index[arr[i][j]]['y']=i;
</code>```

Body:
Here is my code for reference. I'm getting error for line 9 and 10. Is there a way to assign values for dictionary inside an initially empty dictionary :

function anticlockwiseRotate(arr){
            //store the index of elements in a dict
            let index={};
            for(let i=0;i<3;i++){
                for(let j=0;j<3;j++){
                    if(!index.hasOwnProperty(arr[i][j]['x']) && !index.hasOwnProperty(arr[i][j]['y'])){
                        //left shift by 2 and change rowInde)
                        //left shift by 2 and change rowIndex->columnIndex
                        index[arr[i][j]]['x'] = (Math.abs(j-2));
                        index[arr[i][j]]['y']=i;
                    }
                }
            }
            let rotatedArr= [];
            for(let idx in index){
                rotatedArr[index[idx][x]][index[idx][y]]=idx;
            }
            return rotatedArr
        }
        console.log(anticlockwiseRotate([[1,2,3],[4,5,6],[7,8,9]]))

Body:
set index[arr[i][j]] as object before assigning any properties to index[arr[i][j]]

index[arr[i][j]] = {};
//left shift by 2 and change rowInde)
//left shift by 2 and change rowIndex->columnIndex
index[arr[i][j]]['x'] = (Math.abs(j-2));
index[arr[i][j]]['y']=i;


问:
pandas two lists of dict in one variable into one list of dict in one variable
I have two lists of dict in one variable want to combine to one list of dict in one variable, how to do?

```<code>df30 = df10.merge(df21, on='id', how='inner')
df30 = df30.to_dict('records')
</code>```

The variable of df30 inside have 2 lists.

[
  {
    'id': 2101,
    'percent': -10.213240935732046
  }
]

[
  {
    'id': 2100,
    'percent': -77.0623742454728
  }
]
```
<p>I want to combine them into one list of dict, how do I do that?</p>

<pre class="lang-html prettyprint-override"><code>[
    {
        'id': 2101,
        'percent': -10.213240935732046
    },
    {
        'id': 2100,
        'percent': -77.0623742454728
    }
]
</code>```

or create two new variables for two lists in df30 and combine the two variables is it possible?

Body:
I have two lists of dict in one variable want to combine to one list of dict in one variable, how to do?

df30 = df10.merge(df21, on='id', how='inner')
df30 = df30.to_dict('records')

The variable of df30 inside have 2 lists.

[
  {
    'id': 2101,
    'percent': -10.213240935732046
  }
]

[
  {
    'id': 2100,
    'percent': -77.0623742454728
  }
]

I want to combine them into one list of dict, how do I do that?

[
    {
        'id': 2101,
        'percent': -10.213240935732046
    },
    {
        'id': 2100,
        'percent': -77.0623742454728
    }
]

or create two new variables for two lists in df30 and combine the two variables is it possible?

Body:
Quite confused here, but:

l1 = [{'A':1, 'W':10}]
l2 = [{'B':2, 'Y':20}]

l1 + l2

Output:

[{'A': 1, 'W': 10}, {'B': 2, 'Y': 20}]


问:
How to read a binary file with a known header and file format for data analysis?
I'm currently working doing some basic analysis/trying to make tools to automate some of the more quantitative parts of my job.  One of these tasks is analyzing data from local instruments, and using that data to draw quantitative conclusions.  The end goal is to calculate percent data coverage over a given region (What percent of values in area 'x' exceed value 'y'?).  However, there are problems.

First, the data we are looking at is in binary.  While the programmer's guides for the data document some of the data structure, they are very sparse in how to actually utilize the data for analysis outside of their proprietary programs.

Second, I am new to Python.  While I tried programming tasks in python years ago, I did not end up making anything useful; I am more adept at shell scripting, can work with html/javascript/php, and managing a program using Fortran; I'm trying to learn Python to diversify.

What I know about the data in question: The binary file contains a 640-character long header made up of three parts. Each part is a a mixture of: characters; unsigned and signed 8, 16, and 32 bit integers; and 16 and 32 bit binary angles.  After the header, the files show a cartesian grid of data as 'pixels' in an 'image'.  Each 'pixel' within the 'image' is an one-byte unsigned character with a value between 0 and 255. The 'image' is a 2-D grid of 'x by y' with the next 'image' occurring after a given number of bytes (In this data set, the images are 720 by 720 'pixels', so the 'images' are separated after 720^2 bytes).

Right now, my goal is just to read the file into a python program and separate the various "images" for inspection.  The initialized data/format are below:

```<code>testFile = 'C:/path/to/file/binaryFile'
headerFormat = '640c'
nBytesData = 720 * 720
# Below is commented out
inputFile = open(testfile, 'rb')
</code>```

I have been able to read the file in as a binary file, but I have no clue how to inspect it.  First instinct was to try and put it in a numpy array, but additional research suggested using the  struct module and struct.unpack to break apart the data.  From what I've read, the following block should unpack each 'image' correctly after the initial header, even if it's not the most efficient method:

```<code>header_size = struct.calcsize(headerFormat)
testUnpacked = []
with open(testFile, 'rb') as testData:
    headerOut = testData.read(header_size)
    print("header is: ", headerOut)
    while True:
        testContent = testData.read()
        if not testContent: break
        testArray = struct.unpack(testContent, nBytesData)
        testUnpacked.append(testArray)
</code>```

The problem is I do not know how to set up the code to unpack/skip the header to the binary file.  I do not think the headerFormat = '640c' line of code, plus the next couple of commands to try and format its output, correct.  I was able to output a line that the program, run in PyCharm, interpreted as the "header", and below is a sample of the output starting from the first 'print':
b'\x1b\x00\x08\x00\x80\xd4\x0f\x00\x00\x00\x00\x00\x1a\x00\x06\x00@\x01\x00\x00\x00\x00\x00\x00\x03\x00\x02\x00\x00\x00\x00\x00}\t\x0

After that, I got a error stating that there is an embedded null character preventing the data from saving to the designated array.

Other questions I referenced to try and figure out how to read the data:

Reading a binary file with python
Reading a binary file into a struct
Fastest way to read a binary file with a defined format?

Main questions are as follows:

How do I tell the program to read the binary file header and then start reading the file according to the 720^2 arrays?

How do I tell the program to save the header in a format I can understand?

How do I figure out what is causing the struct.error message?

答:
Based on this description it is difficult to say how one could read the header, since this will depend on its specific structure. It should be possible though to read the rest of the file.

Start by reading the file as a byte array:

```<code>with open(testFile, 'rb') as testData:
    data = testData.read()
</code>```

len(data) will give the number of bytes. Assuming that the header consists of fewer than 720^2 bytes, and that the rest of the bytes is subdivided into images 720^2 bytes each, the reminder from the division of len(data) by 720^2 will give the length of the header:

```<code>len_header = len(data) % 720**2
</code>```

You can then disregard the header and convert the remaining bytes into integers:

```<code>pixels = [b for b in data[len_header:]]
</code>```

Next, you can use numpy to rearrange this list into a 2-dimensional array with 720^2 columns, so that each row consists of pixels of a single image:

```<code>import numpy as np

images = np.array(pixels).reshape(-1, 720**2)
</code>```

Each image can be now accessed as images[i] where i is the index of a row. This is a 1-dimensional array, so to make it into a 2-dimensional structure representing an image reshape again:

```<code>images[i].reshape(720, 720)
</code>```

Finally, you can use matplotlib to display the image and check if it looks correctly:

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

plt.imshow(images[i].reshape(720, 720), cmap="gray_r")
plt.show()
</code>```

Body:
I'm currently working doing some basic analysis/trying to make tools to automate some of the more quantitative parts of my job.  One of these tasks is analyzing data from local instruments, and using that data to draw quantitative conclusions.  The end goal is to calculate percent data coverage over a given region (What percent of values in area 'x' exceed value 'y'?).  However, there are problems.

First, the data we are looking at is in binary.  While the programmer's guides for the data document some of the data structure, they are very sparse in how to actually utilize the data for analysis outside of their proprietary programs.

Second, I am new to Python.  While I tried programming tasks in python years ago, I did not end up making anything useful; I am more adept at shell scripting, can work with html/javascript/php, and managing a program using Fortran; I'm trying to learn Python to diversify.

What I know about the data in question: The binary file contains a 640-character long header made up of three parts. Each part is a a mixture of: characters; unsigned and signed 8, 16, and 32 bit integers; and 16 and 32 bit binary angles.  After the header, the files show a cartesian grid of data as 'pixels' in an 'image'.  Each 'pixel' within the 'image' is an one-byte unsigned character with a value between 0 and 255. The 'image' is a 2-D grid of 'x by y' with the next 'image' occurring after a given number of bytes (In this data set, the images are 720 by 720 'pixels', so the 'images' are separated after 720^2 bytes).

Right now, my goal is just to read the file into a python program and separate the various "images" for inspection.  The initialized data/format are below:

testFile = 'C:/path/to/file/binaryFile'
headerFormat = '640c'
nBytesData = 720 * 720
# Below is commented out
inputFile = open(testfile, 'rb')

I have been able to read the file in as a binary file, but I have no clue how to inspect it.  First instinct was to try and put it in a numpy array, but additional research suggested using the  struct module and struct.unpack to break apart the data.  From what I've read, the following block should unpack each 'image' correctly after the initial header, even if it's not the most efficient method:

header_size = struct.calcsize(headerFormat)
testUnpacked = []
with open(testFile, 'rb') as testData:
    headerOut = testData.read(header_size)
    print("header is: ", headerOut)
    while True:
        testContent = testData.read()
        if not testContent: break
        testArray = struct.unpack(testContent, nBytesData)
        testUnpacked.append(testArray)

The problem is I do not know how to set up the code to unpack/skip the header to the binary file.  I do not think the headerFormat = '640c' line of code, plus the next couple of commands to try and format its output, correct.  I was able to output a line that the program, run in PyCharm, interpreted as the "header", and below is a sample of the output starting from the first 'print':
b'\x1b\x00\x08\x00\x80\xd4\x0f\x00\x00\x00\x00\x00\x1a\x00\x06\x00@\x01\x00\x00\x00\x00\x00\x00\x03\x00\x02\x00\x00\x00\x00\x00}\t\x0

After that, I got a error stating that there is an embedded null character preventing the data from saving to the designated array.

Other questions I referenced to try and figure out how to read the data:

Reading a binary file with python
Reading a binary file into a struct
Fastest way to read a binary file with a defined format?

Main questions are as follows:

How do I tell the program to read the binary file header and then start reading the file according to the 720^2 arrays?

How do I tell the program to save the header in a format I can understand?

How do I figure out what is causing the struct.error message?

Body:
Based on this description it is difficult to say how one could read the header, since this will depend on its specific structure. It should be possible though to read the rest of the file.

Start by reading the file as a byte array:

with open(testFile, 'rb') as testData:
    data = testData.read()

len(data) will give the number of bytes. Assuming that the header consists of fewer than 720^2 bytes, and that the rest of the bytes is subdivided into images 720^2 bytes each, the reminder from the division of len(data) by 720^2 will give the length of the header:

len_header = len(data) % 720**2

You can then disregard the header and convert the remaining bytes into integers:

pixels = [b for b in data[len_header:]]

Next, you can use numpy to rearrange this list into a 2-dimensional array with 720^2 columns, so that each row consists of pixels of a single image:

import numpy as np

images = np.array(pixels).reshape(-1, 720**2)

Each image can be now accessed as images[i] where i is the index of a row. This is a 1-dimensional array, so to make it into a 2-dimensional structure representing an image reshape again:

images[i].reshape(720, 720)

Finally, you can use matplotlib to display the image and check if it looks correctly:

import matplotlib.pyplot as plt

plt.imshow(images[i].reshape(720, 720), cmap="gray_r")
plt.show()


问:
Doxygen: how to describe class member variables in php?
I'm trying to use doxygen to parse php code into xml output.
Doxygen does not parse description of class member variables.

Here is my sample php file:

```<code><?php
class A
{
    /**
      * Id on page.
      *
      * @var integer
      */
    var $id = 1;
}
?>
</code>```

Note that comment has a brief description and variable type.
Here is xml i got from this source:

```<code><?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="compound.xsd" version="1.7.2">
  <compounddef id="class_a" kind="class" prot="public">
<compoundname>A</compoundname>
  <sectiondef kind="public-attrib">
  <memberdef kind="variable" id="class_a_1ae97941710d863131c700f069b109991e" prot="public" static="no" mutable="no">
    <type></type>
    <definition>$id</definition>
    <argsstring></argsstring>
    <name>$id</name>
    <initializer> 1</initializer>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <inbodydescription>
    </inbodydescription>
    <location file="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" line="11" bodyfile="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" bodystart="11" bodyend="-1"/>
  </memberdef>
  </sectiondef>
<briefdescription>
</briefdescription>
<detaileddescription>
</detaileddescription>
<location file="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" line="5" bodyfile="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" bodystart="4" bodyend="12"/>
<listofallmembers>
  <member refid="class_a_1ae97941710d863131c700f069b109991e" prot="public" virt="non-virtual"><scope>A</scope><name>$id</name></member>
</listofallmembers>
  </compounddef>
</doxygen>
</code>```

Neither description or type were parsed.
How can I fix this?

答:
While this is not a direct answer to your question: If you are at liberty to use the right tool for the job, have a look at DocBlox. It also generates an XML-document for further transformation into HTML or any other display format and works very good for PHP. It won't break your usual docblock-usage either.

As an example output, check out the Zend Framework API documentation.

Body:
I'm trying to use doxygen to parse php code into xml output.
Doxygen does not parse description of class member variables.

Here is my sample php file:

<?php
class A
{
    /**
      * Id on page.
      *
      * @var integer
      */
    var $id = 1;
}
?>

Note that comment has a brief description and variable type.
Here is xml i got from this source:

<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="compound.xsd" version="1.7.2">
  <compounddef id="class_a" kind="class" prot="public">
<compoundname>A</compoundname>
  <sectiondef kind="public-attrib">
  <memberdef kind="variable" id="class_a_1ae97941710d863131c700f069b109991e" prot="public" static="no" mutable="no">
    <type></type>
    <definition>$id</definition>
    <argsstring></argsstring>
    <name>$id</name>
    <initializer> 1</initializer>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <inbodydescription>
    </inbodydescription>
    <location file="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" line="11" bodyfile="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" bodystart="11" bodyend="-1"/>
  </memberdef>
  </sectiondef>
<briefdescription>
</briefdescription>
<detaileddescription>
</detaileddescription>
<location file="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" line="5" bodyfile="C:/projects/version6-7/asprunner/PHP/source/classes/a.php" bodystart="4" bodyend="12"/>
<listofallmembers>
  <member refid="class_a_1ae97941710d863131c700f069b109991e" prot="public" virt="non-virtual"><scope>A</scope><name>$id</name></member>
</listofallmembers>
  </compounddef>
</doxygen>

Neither description or type were parsed.
How can I fix this?


问:
PnPOnline login issue
In our tenants, we use MFA and I needed to use -UseWebLogin if I want to do connect-PNPOnline. The problem I have is when I try to pass my login credentials, it giving me an errors so I would be really appreciated if I can get any help or suggestion how should I make it work.

I was able to login using just like this but I need to pass my credentials so that I don't have to enter it again and again

```<code>#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin

</code>```

If I just use it like this then I got the error below

```<code>Connect-PnPOnline -Url $SiteURL -Credentials($psCred)

Error: AADSTS53001: Device is not in required device state: domain_joined. Conditional Access policy requires a domain joined device, and the device is not domain joined.
</code>```

So the only solution for me is to use -UseWebLogin like I stated above and I tried like these but I'm still getting an error

```<code>Connect-PnPOnline -Url $SiteURL -UseWebLogin($psCred)

or

Connect-PnPOnline -Url $SiteURL -UseWebLogin -Credentials($psCred)

then I got this error
Error: A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.

</code>```

答: You can store your user id and password as object in a variable. Then pass that variable as paramter to -Credential.</p>

Title: PnPOnline login issue

Body:
In our tenants, we use MFA and I needed to use -UseWebLogin if I want to do connect-PNPOnline. The problem I have is when I try to pass my login credentials, it giving me an errors so I would be really appreciated if I can get any help or suggestion how should I make it work.

I was able to login using just like this but I need to pass my credentials so that I don't have to enter it again and again

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin

If I just use it like this then I got the error below

Connect-PnPOnline -Url $SiteURL -Credentials($psCred)

Error: AADSTS53001: Device is not in required device state: domain_joined. Conditional Access policy requires a domain joined device, and the device is not domain joined.

So the only solution for me is to use -UseWebLogin like I stated above and I tried like these but I'm still getting an error

Connect-PnPOnline -Url $SiteURL -UseWebLogin($psCred)

or

Connect-PnPOnline -Url $SiteURL -UseWebLogin -Credentials($psCred)

then I got this error
Error: A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.


问:
How to get to users %APPDATA% when running as system user from a batch file
Deploying applications via SCCM. Currently trying to deploy Wireshark and I am 1st trying to create the directory then copy over a preference file to the users %APPDATA%. The preference file basically stops the application from checking for auto updates.

Reason I need to create the directory is because it does not exist until Wireshark is launched for the 1st time.

Issue is that when doing this, SCCM is deploying as a system user so %APPDATA% goes to directory C:\Windows\System32\config\systemprofile\AppData\Roaming\

But I would like to get to C:\Users\SPECIFIC USER\AppData\Roaming

I am deploying the application with a batch file:

```<code>Wireshark-win64-2.4.6.exe /S

mkdir %APPDATA%\Wireshark\

xcopy preferences %APPDATA%\Wireshark
</code>```

This will work locally on my own machine but if I run under PSEXEC (like SCCM would) then it will end up in the incorrect directory.

I am new to creating applications within SCCM as well as using batch files to deploy so please include details if possible. Regardless I appreciate the help!

答:
for /f "TOKENS=1,2,*" %%a in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do if /i "%%a %%b"=="User Name:" (set domain_user=%%c)

for /f "TOKENS=1,2 DELIMS=" %%a in ("%domain_user%") do set domain=%%a && set LoggedInUserID=%%b

Body:
Deploying applications via SCCM. Currently trying to deploy Wireshark and I am 1st trying to create the directory then copy over a preference file to the users %APPDATA%. The preference file basically stops the application from checking for auto updates.

Reason I need to create the directory is because it does not exist until Wireshark is launched for the 1st time.

Issue is that when doing this, SCCM is deploying as a system user so %APPDATA% goes to directory C:\Windows\System32\config\systemprofile\AppData\Roaming\

But I would like to get to C:\Users\SPECIFIC USER\AppData\Roaming

I am deploying the application with a batch file:

Wireshark-win64-2.4.6.exe /S

mkdir %APPDATA%\Wireshark\

xcopy preferences %APPDATA%\Wireshark

This will work locally on my own machine but if I run under PSEXEC (like SCCM would) then it will end up in the incorrect directory.

I am new to creating applications within SCCM as well as using batch files to deploy so please include details if possible. Regardless I appreciate the help!


问:
Can someone help me figure out why it keeps saying that largest is undefined? Smallest runs fine
```<code>firstNumber = -50;
secondNumber = 53;
thirdNumber = 78;

# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber:
    if secondNumber>thirdNumber:
        largest=secondNumber
elif firstNumber>secondNumber:
    if firstNumber>thirdNumber:
        largest=firstNumber
else:
    largest=thirdNumber
if secondNumber<firstNumber:
    if secondNumber<thirdNumber:
        smallest=secondNumber
elif firstNumber<secondNumber:
    if firstNumber<thirdNumber:
        smallest=firstNumber
else:
    smallest=thirdNumber

# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))
</code>```

Can someone help me figure out why it keeps saying that largest is undefined? Smallest runs fine
I've been sitting here for the past 30 minutes trying to see if I typed largest wrong lol

答:
largest is undefined because there's no condition where largest is created.  see the comments I added for additional insight.

```<code>firstNumber = -50
secondNumber = 53
thirdNumber = 78

# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber: # is True
    if secondNumber>thirdNumber: # is False
        largest=secondNumber
elif firstNumber>secondNumber: # Skipped because first if is True
    if firstNumber>thirdNumber:
        largest=firstNumber
else: # Skipped because first if is True
    largest=thirdNumber
if secondNumber<firstNumber:
    if secondNumber<thirdNumber:
        smallest=secondNumber
elif firstNumber<secondNumber:
    if firstNumber<thirdNumber:
        smallest=firstNumber
else:
    smallest=thirdNumber

# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))
</code>```

if you remove the nesting, it will work

```<code># Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber and secondNumber>thirdNumber:
        largest=secondNumber
elif firstNumber>secondNumber and firstNumber>thirdNumber:
        largest=firstNumber
else:
    largest=thirdNumber
if secondNumber<firstNumber and secondNumber<thirdNumber:
        smallest=secondNumber
elif firstNumber<secondNumber and firstNumber<thirdNumber:
        smallest=firstNumber
else:
    smallest=thirdNumber

# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))
</code>```

Body:
firstNumber = -50;
secondNumber = 53;
thirdNumber = 78;

# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber:
    if secondNumber>thirdNumber:
        largest=secondNumber
elif firstNumber>secondNumber:
    if firstNumber>thirdNumber:
        largest=firstNumber
else:
    largest=thirdNumber
if secondNumber<firstNumber:
    if secondNumber<thirdNumber:
        smallest=secondNumber
elif firstNumber<secondNumber:
    if firstNumber<thirdNumber:
        smallest=firstNumber
else:
    smallest=thirdNumber

# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))

Can someone help me figure out why it keeps saying that largest is undefined? Smallest runs fine
I've been sitting here for the past 30 minutes trying to see if I typed largest wrong lol

Body:
largest is undefined because there's no condition where largest is created.  see the comments I added for additional insight.

firstNumber = -50
secondNumber = 53
thirdNumber = 78

# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber: # is True
    if secondNumber>thirdNumber: # is False
        largest=secondNumber
elif firstNumber>secondNumber: # Skipped because first if is True
    if firstNumber>thirdNumber:
        largest=firstNumber
else: # Skipped because first if is True
    largest=thirdNumber
if secondNumber<firstNumber:
    if secondNumber<thirdNumber:
        smallest=secondNumber
elif firstNumber<secondNumber:
    if firstNumber<thirdNumber:
        smallest=firstNumber
else:
    smallest=thirdNumber

# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))

if you remove the nesting, it will work

# Write assignment, if, or if else statements here as appropriate
if secondNumber>firstNumber and secondNumber>thirdNumber:
        largest=secondNumber
elif firstNumber>secondNumber and firstNumber>thirdNumber:
        largest=firstNumber
else:
    largest=thirdNumber
if secondNumber<firstNumber and secondNumber<thirdNumber:
        smallest=secondNumber
elif firstNumber<secondNumber and firstNumber<thirdNumber:
        smallest=firstNumber
else:
    smallest=thirdNumber

# Output largest and smallest number.
print("The largest value is " + str(largest))
print("The smallest value is " + str(smallest))


问:
How do I display the output of a method from the first page on a second page in flutter?
The app is supposed to take in the first name on the first page and reverse it, then print the output on the second page. I'm having trouble implementing the output from the _incrementCounter method into the SecondScreen class in order to print the output on the second page.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return MaterialApp(
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatelessWidget {
  String t1 = '', output = '';
  RevName name = RevName();

  void _incrementCounter() {
    setState(() {
      output = name.reverseName(t1) as String;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(child: Text("Reverse Name")),
        ),
        body: Column(
          children: [
            Padding(
              padding: EdgeInsets.all(20.0),
              child: TextField(keyboardType: TextInputType.name,
                decoration: const InputDecoration(
                    labelText: 'Enter Your First Name',
                    border: OutlineInputBorder()),
                onChanged: (text) {
                  t1 = text;
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: OutlinedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => SecondScreen()),
                  );
                  _incrementCounter();
                },
                child: Text('Reverse Name'),
              ),
            ),
          ],
        )
    );
  }

  void setState(Null Function() param0) {}
}
</code>```
```<code>class SecondScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Reverse Name"),
        ),
        body: Column(
          children: [
          Center(
              child: OutlinedButton(
                onPressed: (){
                  Navigator.pop(context);
                },
                child: Text('Back')
              ),
            ),
          ],
        )
    );
  }
}
</code>```

The class where name is being reversed and returning the reversed name

```<code>class RevName {
  String name, reversed;

  RevName({this.name = '', this.reversed = ''});

  String reverseName(name) {
    reversed = name.split('').reversed.join('');
    return '$reversed';
  }
}
</code>```

答:
You've RevName model class, to store name and reverse name. You can modify like,

class RevName {
  String name, reversed;

  RevName({
    required this.name,
  }) : reversed = name.split('').reversed.join('');
}
```
<p>Now let's pass data using constructor. Remove state <code>RevName</code> and follow this,</p>
<pre class="lang-dart prettyprint-override"><code>child: OutlinedButton(
  onPressed: () {
    RevName revName = RevName(name: t1);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SecondScreen(
          data: revName,
        ),
      ),
    );
  },
  child: const Text('Reverse Name'),
),
</code>```

On receiver side SecondScreen.

class SecondScreen extends StatelessWidget {
  final RevName data;
  const SecondScreen({
    Key? key,
    required this.data,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Reverse Name"),
        ),
        body: Column(
          children: [
            Text(data.name),
            Text(data.reversed),
```

You can follow this answer to explore alternative way.

Body:
The app is supposed to take in the first name on the first page and reverse it, then print the output on the second page. I'm having trouble implementing the output from the _incrementCounter method into the SecondScreen class in order to print the output on the second page.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return MaterialApp(
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatelessWidget {
  String t1 = '', output = '';
  RevName name = RevName();

  void _incrementCounter() {
    setState(() {
      output = name.reverseName(t1) as String;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(child: Text("Reverse Name")),
        ),
        body: Column(
          children: [
            Padding(
              padding: EdgeInsets.all(20.0),
              child: TextField(keyboardType: TextInputType.name,
                decoration: const InputDecoration(
                    labelText: 'Enter Your First Name',
                    border: OutlineInputBorder()),
                onChanged: (text) {
                  t1 = text;
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: OutlinedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => SecondScreen()),
                  );
                  _incrementCounter();
                },
                child: Text('Reverse Name'),
              ),
            ),
          ],
        )
    );
  }

  void setState(Null Function() param0) {}
}

class SecondScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Reverse Name"),
        ),
        body: Column(
          children: [
          Center(
              child: OutlinedButton(
                onPressed: (){
                  Navigator.pop(context);
                },
                child: Text('Back')
              ),
            ),
          ],
        )
    );
  }
}

The class where name is being reversed and returning the reversed name

class RevName {
  String name, reversed;

  RevName({this.name = '', this.reversed = ''});

  String reverseName(name) {
    reversed = name.split('').reversed.join('');
    return '$reversed';
  }
}

Body:
You've RevName model class, to store name and reverse name. You can modify like,

class RevName {
  String name, reversed;

  RevName({
    required this.name,
  }) : reversed = name.split('').reversed.join('');
}

Now let's pass data using constructor. Remove state RevName and follow this,

child: OutlinedButton(
  onPressed: () {
    RevName revName = RevName(name: t1);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SecondScreen(
          data: revName,
        ),
      ),
    );
  },
  child: const Text('Reverse Name'),
),

On receiver side SecondScreen.

class SecondScreen extends StatelessWidget {
  final RevName data;
  const SecondScreen({
    Key? key,
    required this.data,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Reverse Name"),
        ),
        body: Column(
          children: [
            Text(data.name),
            Text(data.reversed),

You can follow this answer to explore alternative way.


问:
php 8.1 - explode(): Passing null to parameter #2 ($string) of type string is deprecated
Coming across some deprecated errors with 8.1 I want to address.

PHP Deprecated:  explode(): Passing null to parameter #2 ($string) of type string is deprecated in...

```<code>//explode uids into an array
$comp_uids = explode(',', $result['comp_uids']);
</code>```

$result['comp_uids'] in this case is empty which is why the null error shows.  I'm not sure why they are deprecating this ability, but what is the recommended change to avoid this?  I'm seeing similar with strlen(): Passing null to parameter #1 ($string) of type string is deprecated and a few others using 8.1.

答:
Use the null coalescing operator to default the value to an empty string if the value is null.

```<code>$comp_uids = explode(',', $result['comp_uids'] ?? '');
</code>```

Body:
Coming across some deprecated errors with 8.1 I want to address.

PHP Deprecated:  explode(): Passing null to parameter #2 ($string) of type string is deprecated in...

//explode uids into an array
$comp_uids = explode(',', $result['comp_uids']);

$result['comp_uids'] in this case is empty which is why the null error shows.  I'm not sure why they are deprecating this ability, but what is the recommended change to avoid this?  I'm seeing similar with strlen(): Passing null to parameter #1 ($string) of type string is deprecated and a few others using 8.1.

Body:
Use the null coalescing operator to default the value to an empty string if the value is null.

$comp_uids = explode(',', $result['comp_uids'] ?? '');


答:
The problem is subtle. What is happening here is, if one of the top-level if statments if true, then the elif and else statments is automatically being not considered. So in this example, because your second number is larger than your first, BUT NOT larger than the second, the code goes down the path of your first if statment, but since the second if statment within is not true, the variable "largest" actually never gets assigned.

An alternative way is to use a "and" syntax on your if statments e.g.,

```<code>if secondNumber>firstNumber and secondNumber>thirdNumber:
    largest = secondNumber
</code>```

Title: Can someone help me figure out why it keeps saying that largest is undefined? Smallest runs fine

Body:
The problem is subtle. What is happening here is, if one of the top-level if statments if true, then the elif and else statments is automatically being not considered. So in this example, because your second number is larger than your first, BUT NOT larger than the second, the code goes down the path of your first if statment, but since the second if statment within is not true, the variable "largest" actually never gets assigned.

An alternative way is to use a "and" syntax on your if statments e.g.,

if secondNumber>firstNumber and secondNumber>thirdNumber:
    largest = secondNumber


问:
Is there any ansible module to change the existing server ip and reboot it
I have a playbook, which replace the IP and hostname. The playbook works fine till it reboots the machine, but unable to connect it back as now the IP of that server is changed to something else.

Is there any better way to handle this problem.

```<code>---
- hosts: test
  remote_user: root
  vars:
    IP_TO_REPLACE: '192.168.1.15'
    IP_TO_REPLACE_WITH: '192.168.1.16'
    HOSTNAME_TO_REPLACE: 'devops-15'
    HOSTNAME_TO_REPLACE_WITH: 'devops-16'

  tasks:
  - name: modifying the ifcfg-BR0 file
    replace:
      path: "{{ item.path }}"
      regexp: "{{ item.regexp1 }}"
      replace: "{{ item.replace }}"
      backup: yes
    with_items:
      - { path: '/etc/sysconfig/network/ifcfg-br0', regexp1: "{{ IP_TO_REPLACE }}", replace: "{{ IP_TO_REPLACE_WITH }}" }
      - { path: '/etc/hosts', regexp1: "{{ IP_TO_REPLACE }}", replace: "{{ IP_TO_REPLACE_WITH }}" }
      - { path: '/etc/hosts', regexp1: "{{ HOSTNAME_TO_REPLACE }}", replace: "{{ HOSTNAME_TO_REPLACE_WITH }}" }
      - { path: '/etc/hostname', regexp1: "{{ HOSTNAME_TO_REPLACE }}", replace: "{{ HOSTNAME_TO_REPLACE_WITH }}" }

    register: task_result

  - name: Reboot immediately the server to take latest changes
    shell: "sleep 15 && reboot"
    async: 1
    poll: 0
    when: task_result is changed

  - name: Wait for the reboot to complete if there was a changed
    wait_for:
      port: 22
      host: '{{ (ansible_ssh_host |default(ansible_host))|default(inventory_hostname) }}'
      search_regex: OpenSSH
      delay: 10
      timeout: 90
    when: task_result is changed

  - name: Check the uptime of the server
    shell: "uptime"
    register: uptime_result

  - debug: var=uptime_result
</code>```

Actual Output

TASK [Reboot immediately the server to take latest changes] *****************************************************************************
fatal: [192.168.1.15]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to 192.168.1.15 closed.\r\n", "unreachable": true}

Expected Output

It should connect to the new IP 192.168.1.16

答:
My research lead me to the following solution

Inspire by the suggestion of "drenthe73" here:

https://www.reddit.com/r/ansible/comments/n6xfyv/change_current_ip_address_and_reboot_into_the_new/

playbook with 2 plays

---
# play 1
hosts:
  - host_ip_initial

  # ...

  tasks:
    - name: "change ip address"

      # ...

    - name: "reboot target"
      ansible.builtin.shell: "reboot"
      async: 1
      poll: 0

# play2
gather_facts: no
hosts:
  - host_ip_final

  # ...

  tasks:
    - name: "Wait for the target to reboot before probing it is up and running"
      ansible.builtin.wait_for:
        timeout: 300
      delegate_to: localhost

    - name: "wait for boot up"
      ansible.builtin.wait_for_connection:
        connect_timeout: 5
        sleep: 5
        delay: 30
        timeout: 600
```

You need to know the final IP address and creates in your inventory the proper homolog entries.

Ansible various way to restart target:

https://www.redhat.com/sysadmin/automate-reboot-ansible

I am a bit late, but it might help someone else...

Body:
I have a playbook, which replace the IP and hostname. The playbook works fine till it reboots the machine, but unable to connect it back as now the IP of that server is changed to something else.

Is there any better way to handle this problem.

---
- hosts: test
  remote_user: root
  vars:
    IP_TO_REPLACE: '192.168.1.15'
    IP_TO_REPLACE_WITH: '192.168.1.16'
    HOSTNAME_TO_REPLACE: 'devops-15'
    HOSTNAME_TO_REPLACE_WITH: 'devops-16'

  tasks:
  - name: modifying the ifcfg-BR0 file
    replace:
      path: "{{ item.path }}"
      regexp: "{{ item.regexp1 }}"
      replace: "{{ item.replace }}"
      backup: yes
    with_items:
      - { path: '/etc/sysconfig/network/ifcfg-br0', regexp1: "{{ IP_TO_REPLACE }}", replace: "{{ IP_TO_REPLACE_WITH }}" }
      - { path: '/etc/hosts', regexp1: "{{ IP_TO_REPLACE }}", replace: "{{ IP_TO_REPLACE_WITH }}" }
      - { path: '/etc/hosts', regexp1: "{{ HOSTNAME_TO_REPLACE }}", replace: "{{ HOSTNAME_TO_REPLACE_WITH }}" }
      - { path: '/etc/hostname', regexp1: "{{ HOSTNAME_TO_REPLACE }}", replace: "{{ HOSTNAME_TO_REPLACE_WITH }}" }

    register: task_result

  - name: Reboot immediately the server to take latest changes
    shell: "sleep 15 && reboot"
    async: 1
    poll: 0
    when: task_result is changed

  - name: Wait for the reboot to complete if there was a changed
    wait_for:
      port: 22
      host: '{{ (ansible_ssh_host |default(ansible_host))|default(inventory_hostname) }}'
      search_regex: OpenSSH
      delay: 10
      timeout: 90
    when: task_result is changed

  - name: Check the uptime of the server
    shell: "uptime"
    register: uptime_result

  - debug: var=uptime_result

Actual Output

TASK [Reboot immediately the server to take latest changes] *****************************************************************************
fatal: [192.168.1.15]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to 192.168.1.15 closed.\r\n", "unreachable": true}

Expected Output

It should connect to the new IP 192.168.1.16

Body:
My research lead me to the following solution

Inspire by the suggestion of "drenthe73" here:

https://www.reddit.com/r/ansible/comments/n6xfyv/change_current_ip_address_and_reboot_into_the_new/

playbook with 2 plays

---
# play 1
hosts:
  - host_ip_initial

  # ...

  tasks:
    - name: "change ip address"

      # ...

    - name: "reboot target"
      ansible.builtin.shell: "reboot"
      async: 1
      poll: 0

# play2
gather_facts: no
hosts:
  - host_ip_final

  # ...

  tasks:
    - name: "Wait for the target to reboot before probing it is up and running"
      ansible.builtin.wait_for:
        timeout: 300
      delegate_to: localhost

    - name: "wait for boot up"
      ansible.builtin.wait_for_connection:
        connect_timeout: 5
        sleep: 5
        delay: 30
        timeout: 600

You need to know the final IP address and creates in your inventory the proper homolog entries.

Ansible various way to restart target:

https://www.redhat.com/sysadmin/automate-reboot-ansible

I am a bit late, but it might help someone else...