问:
Question about Perceptron activation threshold
I have a Perceptron written in Javascript that works fine, code below. My question is about the threshold in the activation function. Other code I have seen has something like if (sum > 0) {return 1} else {return 0}. My perceptron only works with if (sum > 1) {return 1} else {return 0}. Why is that? Full code below.

```<code>(function () {
    "use strict";

    function Perceptron(numInputs=2) {
        let weights = Array.from({length: numInputs}, () => 2 * Math.random() - 1);  // [-1, 1)
        this.learningRate = 0.5;

        this.train = function (inputs, goal) {
            // feed forward
            let guess = this.predict(inputs);

            // back propagation
            let error = goal - guess;
            if (error !== 0) {
                for (let i = 0; i < weights.length; i += 1) {
                    weights[i] += this.learningRate * error * inputs[i];
                }
            }
        }

        this.predict = function (inputs) {
            // transfer function
            let sumProducts = 0;
            for (let i = 0; i < inputs.length; i += 1) {
                sumProducts += inputs[i] * weights[i];
            }

            // activation function, threshold = 1
            return (sumProducts >= 1) ? 1 : 0;  // <-- this is the line I have a question about
        }
    }

    // train
    let data = [
        [0, 0, 0],
        [0, 1, 0],
        [1, 0, 0],
        [1, 1, 1]
    ];

    let p = new Perceptron(2);

    const epochs = 20;
    for (let i = 0; i < epochs; i += 1) {
        let r = Math.floor(Math.random() * data.length);
        p.train(data[r].slice(0, 2), data[r].slice(-1));
    }

    // test
    for (let i = 0; i < data.length; i += 1) {
        let inputs = data[i].slice(0, 2);
        console.log(`inputs = ${inputs}; output = ${p.predict(inputs)}`);
    }
}());
</code>```

答:
For anyone else following this question, here is the final code. Thanks to @lejlot for helping!

/*jslint for:true, long:true, devel:true, this:true */
/*jshint esversion: 6*/

(function () {
    "use strict";

    function Perceptron(numInputs = 2) {
        this.weights = Array.from({length: numInputs}, () => 2 * Math.random() - 1);  // [-1, 1)
        this.learningRate = 0.5;
        this.bias = 1;

        this.train = function (inputs, goal) {
            // feed forward
            let guess = this.predict(inputs);

            // back propagation
            let error = goal - guess;
            if (error !== 0) {
                for (let i = 0; i < this.weights.length; i += 1) {
                    this.weights[i] += error * inputs[i] * this.learningRate;
                }

                // Bias should be learned, not fixed. The update rules is
                // identical to the weight, just lacks "* inputs[i]" (as
                // described in the answer it is equivalent to having a constant
                // input of 1, and multiplying by 1 does nothing).
                this.bias += error * this.learningRate;
            }
        };

        this.predict = function (inputs) {
            // transfer function
            let sumProducts = 0;
            for (let i = 0; i < inputs.length; i += 1) {
                sumProducts += inputs[i] * this.weights[i];
            }

            // Your perception lacks a bias term, your equation if of form
            // SUM_i w_i x_i, instead of SUM_i w_i x_i + b. With the
            // functional form you have it is impossible to separate points,
            // where the separating hyperplane does not cross the origin
            // (and yours does not). Alternatively you can add a column of
            // "1s" to your data, it will serve the same purpose, as the
            // corresponding w_i will just behave as "b" (since all x_i will
            // be 1)
            sumProducts += this.bias;

            // activation function
            return (sumProducts >= 0) ? 1 : 0;
        };
    }

    // train - boolean AND
    let data = [
        [0, 0, 0],
        [0, 1, 0],
        [1, 0, 0],
        [1, 1, 1]
    ];

    let p = new Perceptron(2);

    const epochs = 100;

    for (let i = 0; i < epochs; i += 1) {
        let r = Math.floor(Math.random() * data.length);
        p.train(data[r].slice(0, 2), data[r].slice(-1));
    }

    // test
    for (let i = 0; i < data.length; i += 1) {
        let inputs = data[i].slice(0, 2);
        console.log(`inputs = ${inputs}; output = ${p.predict(inputs)}`);
    }
}());
```

Body:
I have a Perceptron written in Javascript that works fine, code below. My question is about the threshold in the activation function. Other code I have seen has something like if (sum > 0) {return 1} else {return 0}. My perceptron only works with if (sum > 1) {return 1} else {return 0}. Why is that? Full code below.

(function () {
    "use strict";

    function Perceptron(numInputs=2) {
        let weights = Array.from({length: numInputs}, () => 2 * Math.random() - 1);  // [-1, 1)
        this.learningRate = 0.5;

        this.train = function (inputs, goal) {
            // feed forward
            let guess = this.predict(inputs);

            // back propagation
            let error = goal - guess;
            if (error !== 0) {
                for (let i = 0; i < weights.length; i += 1) {
                    weights[i] += this.learningRate * error * inputs[i];
                }
            }
        }

        this.predict = function (inputs) {
            // transfer function
            let sumProducts = 0;
            for (let i = 0; i < inputs.length; i += 1) {
                sumProducts += inputs[i] * weights[i];
            }

            // activation function, threshold = 1
            return (sumProducts >= 1) ? 1 : 0;  // <-- this is the line I have a question about
        }
    }

    // train
    let data = [
        [0, 0, 0],
        [0, 1, 0],
        [1, 0, 0],
        [1, 1, 1]
    ];

    let p = new Perceptron(2);

    const epochs = 20;
    for (let i = 0; i < epochs; i += 1) {
        let r = Math.floor(Math.random() * data.length);
        p.train(data[r].slice(0, 2), data[r].slice(-1));
    }

    // test
    for (let i = 0; i < data.length; i += 1) {
        let inputs = data[i].slice(0, 2);
        console.log(`inputs = ${inputs}; output = ${p.predict(inputs)}`);
    }
}());


来源: stackexchange

问:
Git push rejected after adding Git support
After adding Git support, I'm not able to push to my repo.
I pulled as the error suggested, but it didn't work either.

How can I resolve this?

```<code>svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0
❯ ggp
To github.com:shinokada/svelte-flow.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:shinokada/svelte-flow.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0 took 2s
❯ gst
On branch main
Your branch is ahead of 'origin/main' by 2 commits.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0
❯ ggp
To github.com:shinokada/svelte-flow.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:shinokada/svelte-flow.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0
❯ git pull
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
Unpacking objects: 100% (4/4), 1.01 KiB | 172.00 KiB/s, done.
remote: Total 4 (delta 1), reused 0 (delta 0), pack-reused 0
From github.com:shinokada/svelte-flow
   df125f9..381c351  main       -> origin/main
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.

svelte-flow on  main [⇕] is  v0.2.4 via  v16.13.0 took 2s
❯ git pull origin main
From github.com:shinokada/svelte-flow
 * branch            main       -> FETCH_HEAD
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.

</code>```

答:
You have commits the remote branch does not have and the remote branch contains commits not in your local branch.

A-local
\
 - remote
```
<p>Git protects you from overwriting the changes in the remote branch using the error you received.</p>
<p>Git allows to merge those changes but you didn't tell it what stretegy to use. It suggests you the following options when pulling:</p>
<h3>merge</h3>
<p>Merging branches means that you create a commit based of both commits (the local and remote one). This is the standard behaviour.</p>
<pre class="lang-none prettyprint-override"><code>A - local   - merge commit
\          /
 - remote -
</code>```

You can enable merging on pulls using git config pull.rebase false.

rebase

Rebasing means you are taking your local branch and putting it on top of the remote branch:

A - remote - local
```

You can enable rebasing on pulls using git config pull.rebase true or by pulling using git pull --rebase.

only allow fast forwards

You can also configure pulling in a way that it does not allow this case. If it would need to merge changes where both the local and remote branch have different commits, it would fail.

This can be configured using git config pull.ff only

ContentLicense: CC BY-SA 4.0

Body:
After adding Git support, I'm not able to push to my repo.
I pulled as the error suggested, but it didn't work either.

How can I resolve this?

svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0
❯ ggp
To github.com:shinokada/svelte-flow.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:shinokada/svelte-flow.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0 took 2s
❯ gst
On branch main
Your branch is ahead of 'origin/main' by 2 commits.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0
❯ ggp
To github.com:shinokada/svelte-flow.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:shinokada/svelte-flow.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

svelte-flow on  main [⇡] is  v0.2.4 via  v16.13.0
❯ git pull
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
Unpacking objects: 100% (4/4), 1.01 KiB | 172.00 KiB/s, done.
remote: Total 4 (delta 1), reused 0 (delta 0), pack-reused 0
From github.com:shinokada/svelte-flow
   df125f9..381c351  main       -> origin/main
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.

svelte-flow on  main [⇕] is  v0.2.4 via  v16.13.0 took 2s
❯ git pull origin main
From github.com:shinokada/svelte-flow
 * branch            main       -> FETCH_HEAD
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.

Body:
You have commits the remote branch does not have and the remote branch contains commits not in your local branch.

A-local
\
 - remote

Git protects you from overwriting the changes in the remote branch using the error you received.

Git allows to merge those changes but you didn't tell it what stretegy to use. It suggests you the following options when pulling:

merge

Merging branches means that you create a commit based of both commits (the local and remote one). This is the standard behaviour.

A - local   - merge commit
\          /
 - remote -

You can enable merging on pulls using git config pull.rebase false.

rebase

Rebasing means you are taking your local branch and putting it on top of the remote branch:

A - remote - local

You can enable rebasing on pulls using git config pull.rebase true or by pulling using git pull --rebase.

only allow fast forwards

You can also configure pulling in a way that it does not allow this case. If it would need to merge changes where both the local and remote branch have different commits, it would fail.

This can be configured using git config pull.ff only


问:
Sheetview with zipped arrays
Problem:
I the sheet view only opens the first item in the arrays. I've looked and found a few similar answers, but they don't deal with zipping arrays together. They mostly have one array. Here is one example. I've also tried to extract the item to a string, and then use the string instead of the item.0, or item.1.

If anyone has any suggestions, it would help a lot.

Main Code:

```<code>  ScheduledAirplanes = ["1", "2", "3", "4"]
  ScheduledInstructors = ["5", "6", "7", "8"]
  ScheduledstartTime = ["9", "10", "11", "12"]
  ScheduledDate = ["1/2", "1/3", "1/4", "1/5"]
  @State private var showingSheet = false
  var arraysForLoop : [(String,String,String,String)] {
    let result = zip(ScheduledAirplanes,zip(ScheduledInstructors,zip(ScheduledstartTime,ScheduledDate)))
    return result.map { ($0.0, $0.1.0, $0.1.1.0, $0.1.1.1) }
  }
</code>```
```<code>                  ForEach(arraysForLoop, id: \.0) { item in
                    VStack {
                      Group {
                        Text("Time")
                        VStack {
                          Text(item.3)
                            .font(.caption)
                            .foregroundColor(.gray)
                          Text(item.2)
                            .font(.caption)
                            .foregroundColor(.gray)
                        }
                        .padding([.leading, .trailing])
                        Divider()
                          .padding([.leading, .trailing])
                        Text("Flight")
                        Text(item.0)
                          .font(.caption)
                          .foregroundColor(.gray)
                        Text("Instructor")
                        Text(item.1)
                          .font(.caption)
                          .foregroundColor(.gray)
                      }
                    }
                    .onTapGesture {
                      showingSheet.toggle()
                    }
                    .sheet(isPresented: $showingSheet) {
                      FlightInfo(Airplane: "\(item.0)", Instructor: "\(item.1)")
                    }
                    .frame(width: 110, height: 140)
                    .overlay {
                      RoundedRectangle(cornerRadius: 10)
                        .stroke(.gray.opacity(0.3), lineWidth: 1)
                    }
                    Spacer()
                  }
</code>```

Here is the FlightView code:

```<code>struct FlightInfo: View {

    @Environment(\.dismiss) var dismiss
    @State var Airplane: String
    @State var Instructor: String

    var body: some View {
        VStack {
            HStack {
                Text("Flight Info")
                    .font(.title)
                    .fontWeight(.bold)
                Spacer()
                Button("Cancel") {
                    dismiss()
                }

            }
            .padding()
            VStack {
                Text("\(Airplane)")
                    .font(.caption)
                    .fontWeight(.medium)
                    .foregroundColor(.gray)
                Text("\(Instructor)")
                    .font(.caption)
                    .fontWeight(.medium)
                    .foregroundColor(.gray)
            }
            Spacer(minLength: 0)
            Button(action: {
                dismiss()
            }) {
                Text("Done")
            }
            .foregroundColor(.white)
            .frame(width: 120, height: 45)
            .background(Color("Blue"))
            .cornerRadius(30)
            .padding(.bottom)
        }
    }
}

</code>```

答:
I would strongly suggest that you rethink modeling your data by having a set of different String arrays that all correspond together by index. Instead, modeling your data with something like this would be much more friendly to work with in SwiftUI:

```<code>struct Model {
    var scheduleAirplane : String
    var scheduledInstructor: String
    var scheduledStartTime: String
    var scheduledDate: String
}

extension Model : Identifiable {
    var id : String { scheduleAirplane }
}

</code>```

If for some reason you're stuck with the separate arrays, you can still take advantage of the more friendly models by doing something like I have below. Note that I've kept your zip code and used to to create the models. The other important difference is that I'm using sheet(item:) and passing a reference to the correct item. That gets handled by a single sheet modifier that takes a reference to the item.

```<code>struct ContentView: View {
    var scheduledAirplanes = ["1", "2", "3", "4"]
    var scheduledInstructors = ["5", "6", "7", "8"]
    var scheduledStartTime = ["9", "10", "11", "12"]
    var scheduledDate = ["1/2", "1/3", "1/4", "1/5"]
    @State private var sheetItem : Model?

    var arraysForLoop : [Model] {
        let result = zip(scheduledAirplanes,zip(scheduledInstructors,zip(scheduledStartTime,scheduledDate)))
        return result.map { Model(scheduleAirplane: $0.0, scheduledInstructor: $0.1.0, scheduledStartTime: $0.1.1.0, scheduledDate: $0.1.1.1) }
    }

    var body: some View {
        ForEach(arraysForLoop) { item in
            VStack {
                Group {
                    Text("Time")
                    VStack {
                        Text(item.scheduledDate)
                            .font(.caption)
                            .foregroundColor(.gray)
                        Text(item.scheduledStartTime)
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                    .padding([.leading, .trailing])
                    Divider()
                        .padding([.leading, .trailing])
                    Text("Flight")
                    Text(item.scheduleAirplane)
                        .font(.caption)
                        .foregroundColor(.gray)
                    Text("Instructor")
                    Text(item.scheduledInstructor)
                        .font(.caption)
                        .foregroundColor(.gray)
                }
            }
            .onTapGesture {
                sheetItem = item
            }
            .frame(width: 110, height: 140)
            .overlay {
                RoundedRectangle(cornerRadius: 10)
                    .stroke(.gray.opacity(0.3), lineWidth: 1)
            }
            Spacer()
        }.sheet(item: $sheetItem) { item in
            FlightInfo(Airplane: "\(item.scheduleAirplane)", Instructor: "\(item.scheduledInstructor)")
        }
    }
}
</code>```

Note that if you took the first suggestion and coalesced the arrays into models first, the beginning of the View would just look like this:

```<code>struct ContentView: View {
    var models = [Model]
    @State private var sheetItem : Model?

    var body: some View {
        ForEach(models) { item in
        //etc
</code>```

Title: Sheetview with zipped arrays

Body:
Problem:
I the sheet view only opens the first item in the arrays. I've looked and found a few similar answers, but they don't deal with zipping arrays together. They mostly have one array. Here is one example. I've also tried to extract the item to a string, and then use the string instead of the item.0, or item.1.

If anyone has any suggestions, it would help a lot.

Main Code:

  ScheduledAirplanes = ["1", "2", "3", "4"]
  ScheduledInstructors = ["5", "6", "7", "8"]
  ScheduledstartTime = ["9", "10", "11", "12"]
  ScheduledDate = ["1/2", "1/3", "1/4", "1/5"]
  @State private var showingSheet = false
  var arraysForLoop : [(String,String,String,String)] {
    let result = zip(ScheduledAirplanes,zip(ScheduledInstructors,zip(ScheduledstartTime,ScheduledDate)))
    return result.map { ($0.0, $0.1.0, $0.1.1.0, $0.1.1.1) }
  }

                  ForEach(arraysForLoop, id: \.0) { item in
                    VStack {
                      Group {
                        Text("Time")
                        VStack {
                          Text(item.3)
                            .font(.caption)
                            .foregroundColor(.gray)
                          Text(item.2)
                            .font(.caption)
                            .foregroundColor(.gray)
                        }
                        .padding([.leading, .trailing])
                        Divider()
                          .padding([.leading, .trailing])
                        Text("Flight")
                        Text(item.0)
                          .font(.caption)
                          .foregroundColor(.gray)
                        Text("Instructor")
                        Text(item.1)
                          .font(.caption)
                          .foregroundColor(.gray)
                      }
                    }
                    .onTapGesture {
                      showingSheet.toggle()
                    }
                    .sheet(isPresented: $showingSheet) {
                      FlightInfo(Airplane: "\(item.0)", Instructor: "\(item.1)")
                    }
                    .frame(width: 110, height: 140)
                    .overlay {
                      RoundedRectangle(cornerRadius: 10)
                        .stroke(.gray.opacity(0.3), lineWidth: 1)
                    }
                    Spacer()
                  }

Here is the FlightView code:

struct FlightInfo: View {

    @Environment(\.dismiss) var dismiss
    @State var Airplane: String
    @State var Instructor: String

    var body: some View {
        VStack {
            HStack {
                Text("Flight Info")
                    .font(.title)
                    .fontWeight(.bold)
                Spacer()
                Button("Cancel") {
                    dismiss()
                }

            }
            .padding()
            VStack {
                Text("\(Airplane)")
                    .font(.caption)
                    .fontWeight(.medium)
                    .foregroundColor(.gray)
                Text("\(Instructor)")
                    .font(.caption)
                    .fontWeight(.medium)
                    .foregroundColor(.gray)
            }
            Spacer(minLength: 0)
            Button(action: {
                dismiss()
            }) {
                Text("Done")
            }
            .foregroundColor(.white)
            .frame(width: 120, height: 45)
            .background(Color("Blue"))
            .cornerRadius(30)
            .padding(.bottom)
        }
    }
}

Body:
I would strongly suggest that you rethink modeling your data by having a set of different String arrays that all correspond together by index. Instead, modeling your data with something like this would be much more friendly to work with in SwiftUI:

struct Model {
    var scheduleAirplane : String
    var scheduledInstructor: String
    var scheduledStartTime: String
    var scheduledDate: String
}

extension Model : Identifiable {
    var id : String { scheduleAirplane }
}

If for some reason you're stuck with the separate arrays, you can still take advantage of the more friendly models by doing something like I have below. Note that I've kept your zip code and used to to create the models. The other important difference is that I'm using sheet(item:) and passing a reference to the correct item. That gets handled by a single sheet modifier that takes a reference to the item.

struct ContentView: View {
    var scheduledAirplanes = ["1", "2", "3", "4"]
    var scheduledInstructors = ["5", "6", "7", "8"]
    var scheduledStartTime = ["9", "10", "11", "12"]
    var scheduledDate = ["1/2", "1/3", "1/4", "1/5"]
    @State private var sheetItem : Model?

    var arraysForLoop : [Model] {
        let result = zip(scheduledAirplanes,zip(scheduledInstructors,zip(scheduledStartTime,scheduledDate)))
        return result.map { Model(scheduleAirplane: $0.0, scheduledInstructor: $0.1.0, scheduledStartTime: $0.1.1.0, scheduledDate: $0.1.1.1) }
    }

    var body: some View {
        ForEach(arraysForLoop) { item in
            VStack {
                Group {
                    Text("Time")
                    VStack {
                        Text(item.scheduledDate)
                            .font(.caption)
                            .foregroundColor(.gray)
                        Text(item.scheduledStartTime)
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                    .padding([.leading, .trailing])
                    Divider()
                        .padding([.leading, .trailing])
                    Text("Flight")
                    Text(item.scheduleAirplane)
                        .font(.caption)
                        .foregroundColor(.gray)
                    Text("Instructor")
                    Text(item.scheduledInstructor)
                        .font(.caption)
                        .foregroundColor(.gray)
                }
            }
            .onTapGesture {
                sheetItem = item
            }
            .frame(width: 110, height: 140)
            .overlay {
                RoundedRectangle(cornerRadius: 10)
                    .stroke(.gray.opacity(0.3), lineWidth: 1)
            }
            Spacer()
        }.sheet(item: $sheetItem) { item in
            FlightInfo(Airplane: "\(item.scheduleAirplane)", Instructor: "\(item.scheduledInstructor)")
        }
    }
}

Note that if you took the first suggestion and coalesced the arrays into models first, the beginning of the View would just look like this:

struct ContentView: View {
    var models = [Model]
    @State private var sheetItem : Model?

    var body: some View {
        ForEach(models) { item in
        //etc


问:
Pywalify - evaluate nested maps
I'm using pykwalify to validate a schema.

Given this yaml:

```<code>variables:
  dev:
    options:
      key: value
  uat:
    key: value
    key2: value
  prd:
    key: value
    key2: value
</code>```

Under variables, any map should be allowed.
Under that second level (dev, uat, prd) - any key should be allowed, EXCEPT options.  "options" should not be allowed here.

I've tried using a regex, but this is only evaluating the top level, and I'm not quite sure how evaluate the level nested under that "dev, uat, prd" level.

```<code>variables:
  type: map
  matching-rule: all
  mapping:
    regex;([^,]+):
      type: any
    regex;(^(?!.*options:).*$):
      type: any
</code>```

Another potential option would be if I have to explicitly list the values that are allowed, that would work too.

答:
I see two issues in your snippet:

The regex to match anything but "options" is wrong.

The schema isn't properly structured for the nested mapping.

The following schema should provide what you need:

variables:
  type: map
  matching-rule: all
  mapping:
    regex;([^,]+):
      type: map
      mapping:
        regex;(^(?!options$).*):
          type: any
```

Title: Pywalify - evaluate nested maps

Body:
I'm using pykwalify to validate a schema.

Given this yaml:

variables:
  dev:
    options:
      key: value
  uat:
    key: value
    key2: value
  prd:
    key: value
    key2: value

Under variables, any map should be allowed.
Under that second level (dev, uat, prd) - any key should be allowed, EXCEPT options.  "options" should not be allowed here.

I've tried using a regex, but this is only evaluating the top level, and I'm not quite sure how evaluate the level nested under that "dev, uat, prd" level.

variables:
  type: map
  matching-rule: all
  mapping:
    regex;([^,]+):
      type: any
    regex;(^(?!.*options:).*$):
      type: any

Another potential option would be if I have to explicitly list the values that are allowed, that would work too.


问:
Python: Anything wrong with dynamically assigning instance methods as instance attributes
I came up with the following code to decorate instance methods using a decorator that requires the instance itself as an argument:

```<code>from functools import wraps

def logging_decorator(tricky_instance):
    def wrapper(fn):
        @wraps(fn)
        def wrapped(*a, **kw):
            if tricky_instance.log:
                print("Calling %s.." % fn.__name__)
            return fn(*a, **kw)
        return wrapped
    return wrapper

class Tricky(object):
    def __init__(self, log):
        self.log = log
        self.say_hi = logging_decorator(self)(self.say_hi)

    def say_hi(self):
       print("Hello, world!")

i1 = Tricky(log=True)
i2 = Tricky(log=False)

i1.say_hi()
i2.say_hi()
</code>```

This seems to work great, but I fear that I may have overlooked some unintended side effects of this trick. Am I about to shoot myself in the foot, or is this  safe?

Note that I don't actually want to use this for logging, it's just the shortest meaningful example I could come up with.

答:
It's not really clear to me why you would ever want to do this. If you want to assign a new method type dynamically use types:

```<code>import types

class Tricky(object):
    def __init__(self):
        def method(self):
            print('Hello')
        self.method = types.MethodType(method, self)
</code>```

If you want to do something with the instance, do it in the __init__ method. If you just want access to the method's instance inside the decorator, you can use the im_self attribute:

```<code>def decorator(tricky_instance):
    def wrapper(meth):
        print(meth.im_self == tricky_instance)
        return meth
    return wrapper
</code>```

Personally, I think this is veering into Maybe-I-Shouldn't-Use-Decorators land.

ContentLicense: CC BY-SA 3.0

Body:
I came up with the following code to decorate instance methods using a decorator that requires the instance itself as an argument:

from functools import wraps

def logging_decorator(tricky_instance):
    def wrapper(fn):
        @wraps(fn)
        def wrapped(*a, **kw):
            if tricky_instance.log:
                print("Calling %s.." % fn.__name__)
            return fn(*a, **kw)
        return wrapped
    return wrapper

class Tricky(object):
    def __init__(self, log):
        self.log = log
        self.say_hi = logging_decorator(self)(self.say_hi)

    def say_hi(self):
       print("Hello, world!")

i1 = Tricky(log=True)
i2 = Tricky(log=False)

i1.say_hi()
i2.say_hi()

This seems to work great, but I fear that I may have overlooked some unintended side effects of this trick. Am I about to shoot myself in the foot, or is this  safe?

Note that I don't actually want to use this for logging, it's just the shortest meaningful example I could come up with.

Body:
It's not really clear to me why you would ever want to do this. If you want to assign a new method type dynamically use types:

import types

class Tricky(object):
    def __init__(self):
        def method(self):
            print('Hello')
        self.method = types.MethodType(method, self)

If you want to do something with the instance, do it in the __init__ method. If you just want access to the method's instance inside the decorator, you can use the im_self attribute:

def decorator(tricky_instance):
    def wrapper(meth):
        print(meth.im_self == tricky_instance)
        return meth
    return wrapper

Personally, I think this is veering into Maybe-I-Shouldn't-Use-Decorators land.


问:
How can we add multiple foreign keys from one model to another on ASP.NET Core & EF Core & C#
So let's say I have an ApplicationUser : IdentityUser model class that has the identity relations and it has a String ID by default and roles assigned when the user signs up.

ApplicationUsers will have different roles for example Student and Library.

The Library will have a list of books while the Student will have list of orders.

Now I want to create a List of another model which will have the name Orders, but the Orders model class will have two UserIds as foreign keys from ApplicationUser.

```<code>ApplicationUser: IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Libraries> Libraries { get; set; }
    public List<Orders> Orders { get; set; }
}
</code>```

Since the ApplicationUser is connected with ASPNetRoles, what I want to achieve on Orders model class is that I want to have different StudentId and LibraryId from the same table which is ApplicationUser:

```<code>public class Orders
{
    [Key]
    public id OrderId {get; set;}

    [ForeignKey("StudentId")]
    public string StudentId { get; set; }
    public ApplicationUser Student {get; set;}

    [ForeignKey("LibraryId")]
    public string LibraryId {get; set;}
    public ApplicationUser Library {get; set;}
}
</code>```

Is there any way I can achieve this? What are the best solutions for this case? I did try ICollection and list but still same. Any suggestion about this would be great.

When I run Add-Migrations, I get this error:

System.InvalidOperationException: Unable to determine the relationship represented by navigation 'ApplicationUser.OrdersLists' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

Thank you.

答:
Ok, something in you model doesn't look quite right...

In your User class you have a collection of Orders and an collection of a class called Library. Yet within your Order class you have a property called Library, but point that at an ApplicationUser class?

EF does support having multiple references to the same class, though you need to explicitly tell it what the FK names would be. EF's default convention is to base FK names on the type of the navigation property, not the name of the navigation property.

Take the following:

```<code>public class Order
{
    ....

    public int CreatedById { get; set; }
    public virtual ApplicationUser CreatedBy { get; set; }

    public int LastModifiedById { get; set; }
    public virtual ApplicationUser LastModifiedBy { get; set; }
}
</code>```

Here by default EF would want to use "ApplicationUser_Id" or "ApplicationUserId" as a FK name for both of the two navigation properties, settling on something like "ApplicationUser_Id" and "ApplicationUser_Id1" if left to its own devices with the schema.  In this situation we would need to configure it to use our desired FK properties:

```<code>[ForeignKey("CreatedBy")]
public int CreatedById { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }

[ForeignKey("LastModifiedBy")]
public int LastModifiedById { get; set; }
public virtual ApplicationUser LastModifiedBy { get; set; }
</code>```

or the FK attribute can be put on the navigation property:

```<code>public int CreatedById { get; set; }
[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }

public int LastModifiedById { get; set; }
[ForeignKey("LastModifiedById")]
public virtual ApplicationUser LastModifiedBy { get; set; }
</code>```

The ForeignKey Attribute is a bit weird, as it represents either "I am the FK of ..." if on the FK property, or it represents "My FK is ...." if on the navigation property.

With EF Core the FK property can be left off and treated by EF as a shadow property which is recommended to avoid having two sources of truth in the entity.

```<code>[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }

[ForeignKey("LastModifiedById")]
public virtual ApplicationUser LastModifiedBy { get; set; }
</code>```

In situations where you want bi-directional references in the other side of the relationship, you may need to map those out. For instance if I want a "CreatedOrders" in my ApplicationUser class:

```<code>public class ApplicationUser
{
    // ...

    public virtual ICollection<Order> CreatedOrders { get; set; } = new List<Order>();
}
</code>```

Now it's generally a good idea to tell EF what to relate this back to since Order has two references to the application user. Again, this can be done on either side of the relationship. So in the case of back in our Order class:

```<code>[ForeignKey("CreatedById"), InverseProperty("CreatedOrders")]
public virtual ApplicationUser CreatedBy { get; set; }
</code>```

This tells EF that CreatedBy on this record is the link to use when accessing the orders for CreatedOrders.

Back to your example it is a bit confusing why ApplicationUser would contain a collection of Libraries while an Order expects a "library" to be a User.

Body:
So let's say I have an ApplicationUser : IdentityUser model class that has the identity relations and it has a String ID by default and roles assigned when the user signs up.

ApplicationUsers will have different roles for example Student and Library.

The Library will have a list of books while the Student will have list of orders.

Now I want to create a List of another model which will have the name Orders, but the Orders model class will have two UserIds as foreign keys from ApplicationUser.

ApplicationUser: IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<Libraries> Libraries { get; set; }
    public List<Orders> Orders { get; set; }
}

Since the ApplicationUser is connected with ASPNetRoles, what I want to achieve on Orders model class is that I want to have different StudentId and LibraryId from the same table which is ApplicationUser:

public class Orders
{
    [Key]
    public id OrderId {get; set;}

    [ForeignKey("StudentId")]
    public string StudentId { get; set; }
    public ApplicationUser Student {get; set;}

    [ForeignKey("LibraryId")]
    public string LibraryId {get; set;}
    public ApplicationUser Library {get; set;}
}

Is there any way I can achieve this? What are the best solutions for this case? I did try ICollection and list but still same. Any suggestion about this would be great.

When I run Add-Migrations, I get this error:

System.InvalidOperationException: Unable to determine the relationship represented by navigation 'ApplicationUser.OrdersLists' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

Thank you.

Body:
Ok, something in you model doesn't look quite right...

In your User class you have a collection of Orders and an collection of a class called Library. Yet within your Order class you have a property called Library, but point that at an ApplicationUser class?

EF does support having multiple references to the same class, though you need to explicitly tell it what the FK names would be. EF's default convention is to base FK names on the type of the navigation property, not the name of the navigation property.

Take the following:

public class Order
{
    ....

    public int CreatedById { get; set; }
    public virtual ApplicationUser CreatedBy { get; set; }

    public int LastModifiedById { get; set; }
    public virtual ApplicationUser LastModifiedBy { get; set; }
}

Here by default EF would want to use "ApplicationUser_Id" or "ApplicationUserId" as a FK name for both of the two navigation properties, settling on something like "ApplicationUser_Id" and "ApplicationUser_Id1" if left to its own devices with the schema.  In this situation we would need to configure it to use our desired FK properties:

[ForeignKey("CreatedBy")]
public int CreatedById { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }

[ForeignKey("LastModifiedBy")]
public int LastModifiedById { get; set; }
public virtual ApplicationUser LastModifiedBy { get; set; }

or the FK attribute can be put on the navigation property:

public int CreatedById { get; set; }
[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }

public int LastModifiedById { get; set; }
[ForeignKey("LastModifiedById")]
public virtual ApplicationUser LastModifiedBy { get; set; }

The ForeignKey Attribute is a bit weird, as it represents either "I am the FK of ..." if on the FK property, or it represents "My FK is ...." if on the navigation property.

With EF Core the FK property can be left off and treated by EF as a shadow property which is recommended to avoid having two sources of truth in the entity.

[ForeignKey("CreatedById")]
public virtual ApplicationUser CreatedBy { get; set; }

[ForeignKey("LastModifiedById")]
public virtual ApplicationUser LastModifiedBy { get; set; }

In situations where you want bi-directional references in the other side of the relationship, you may need to map those out. For instance if I want a "CreatedOrders" in my ApplicationUser class:

public class ApplicationUser
{
    // ...

    public virtual ICollection<Order> CreatedOrders { get; set; } = new List<Order>();
}

Now it's generally a good idea to tell EF what to relate this back to since Order has two references to the application user. Again, this can be done on either side of the relationship. So in the case of back in our Order class:

[ForeignKey("CreatedById"), InverseProperty("CreatedOrders")]
public virtual ApplicationUser CreatedBy { get; set; }

This tells EF that CreatedBy on this record is the link to use when accessing the orders for CreatedOrders.

Back to your example it is a bit confusing why ApplicationUser would contain a collection of Libraries while an Order expects a "library" to be a User.


问:
Facing issue " Failed to install the app. Make sure you have the Android development environment " in react native
Would you please help me, I am stuck to create a new project in react-native Like below screenshot. I have able to run old projects. but I am not able to run a new project

I have followed these steps:

react-native init projectName

cd projectName

react-native run-projectName

But I get the error below:

```<code>error Failed to install the app. Make sure you have the Android development environment set up:
</code>```

答: Make sure you have Java JDK installed - for Ubuntu 20.04 - sudo apt install openjdk-11-jdk fixed it for me

Body:
Would you please help me, I am stuck to create a new project in react-native Like below screenshot. I have able to run old projects. but I am not able to run a new project

I have followed these steps:

react-native init projectName

cd projectName

react-native run-projectName

But I get the error below:

error Failed to install the app. Make sure you have the Android development environment set up:


问:
Add dynamic icon beside  tag
I am trying with this example.

I am trying to add down arrow beside 'Show more' and up arrow beside 'Show less' (please refer the image below).

I was trying with the following code example but still no luck.

```<code>$('#nav li').each(function(i) {
$(this).append('<i class="fa' + ' ' + iconsArray[i] + '"></i>')})
</code>```

How can I add the icon beside  tag in the given example?

答:
You can try something like this,and modify the code accordingly for your needs.

Play with it here

// "READMORE" ELEMENT CONSTRUCTOR FUNCTION
const readMore = (textObj) => {
  const span = document.createElement("span")
  span.classList = "readMore"
  span.dataset.text = textObj
  const text = document.createElement("span")
  text.className = "readMoreText"
  text.innerText = "Show more"
  const icon = document.createElement("i")
  icon.classList = "icon fas fa-angle-down"
  span.append(text)
  span.append(icon)
  return span
}
const more = document.querySelectorAll(".more") //GET ALL "MORE" ELEMENTS

//ITERATE OVER ALL "MORE" ELEMENTS
more.forEach(more => {
const content = more.querySelector(".content") //GET CONTENT
const full_text = content.innerText //GET TEXT OF CONTENT,WE NEED IT TO PASS IT TO "READMORE" FUNCTION
const short_text = full_text.substring(0, 100) + '...' //CREATE SHORT VERSION
content.innerText = short_text //SWAP CONTENT FOR SHORT VERSION
  more.appendChild(readMore(JSON.stringify({ full: full_text, short: short_text }))) //ADD "READMORE" ELEMENT TO "MORE" ELEMENT AND PASS TEXT DATA
})

//CLICK HANDLER FOR ALL 'READMORE' ELEMENTS
$(".readMore").click(function(){
const short_text = $(this).data("text").short //GET SHORT VERSION
const full_text = $(this).data("text").full //GET LONG VERSION

if ( $(this).find(".icon").hasClass("rotate") ){
  $(this).find(".icon").removeClass("rotate")
  $(this).parent().find(".content").text(short_text)
  $(this).find(".readMoreText").text("Show more")
}else{
  $(this).find(".icon").addClass("rotate")
  $(this).parent().find(".content").text(full_text)
  $(this).find(".readMoreText").text("Show less")
}

});

$(".readMore").hover(function () {
  $(this).parents(".more").css("background", "rgb(234, 234, 234)");
}, function () {
    $(this).parents(".more").css("background", "rgb(243, 243, 243)");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.more{
width: 500px;
background: rgb(243, 243, 243);
padding: 5px;
}

.readMore{
cursor: pointer;
user-select: none;
color: indianred;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
font-size: 0.9em;
}
.readMore:hover{
color: rgb(104, 104, 223);
}

.fa-angle-down{
margin-left: 0.2em;
animation: rotationBack 0.8s;
height: 13px;
}

.rotate{
transform: rotate(180deg);
animation: rotation 0.8s;
}
@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(180deg);
  }
}
@keyframes rotationBack {
  from {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(0deg);
  }
}</code>```

    <title>jQuery Read More/Less Toggle Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
        integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.

        Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus,
        feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia
        ultricies nec eget tellus. Curabitur id sapien massa. In hac
        habitasse platea dictumst. Integer tristique leo
        consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius
        purus id turpis iaculis iaculis. Nulla convallis magna nunc, id
        rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque
        eget tempor massa.

```

Title: Add dynamic icon beside <a> tag

Body:
I am trying with this example.

I am trying to add down arrow beside 'Show more' and up arrow beside 'Show less' (please refer the image below).

I was trying with the following code example but still no luck.

$('#nav li').each(function(i) {
$(this).append('')})

How can I add the icon beside  tag in the given example?

Body:
You can try something like this,and modify the code accordingly for your needs.

Play with it here

// "READMORE" ELEMENT CONSTRUCTOR FUNCTION
const readMore = (textObj) => {
  const span = document.createElement("span")
  span.classList = "readMore"
  span.dataset.text = textObj
  const text = document.createElement("span")
  text.className = "readMoreText"
  text.innerText = "Show more"
  const icon = document.createElement("i")
  icon.classList = "icon fas fa-angle-down"
  span.append(text)
  span.append(icon)
  return span
}
const more = document.querySelectorAll(".more") //GET ALL "MORE" ELEMENTS

//ITERATE OVER ALL "MORE" ELEMENTS
more.forEach(more => {
const content = more.querySelector(".content") //GET CONTENT
const full_text = content.innerText //GET TEXT OF CONTENT,WE NEED IT TO PASS IT TO "READMORE" FUNCTION
const short_text = full_text.substring(0, 100) + '...' //CREATE SHORT VERSION
content.innerText = short_text //SWAP CONTENT FOR SHORT VERSION
  more.appendChild(readMore(JSON.stringify({ full: full_text, short: short_text }))) //ADD "READMORE" ELEMENT TO "MORE" ELEMENT AND PASS TEXT DATA
})

//CLICK HANDLER FOR ALL 'READMORE' ELEMENTS
$(".readMore").click(function(){
const short_text = $(this).data("text").short //GET SHORT VERSION
const full_text = $(this).data("text").full //GET LONG VERSION

if ( $(this).find(".icon").hasClass("rotate") ){
  $(this).find(".icon").removeClass("rotate")
  $(this).parent().find(".content").text(short_text)
  $(this).find(".readMoreText").text("Show more")
}else{
  $(this).find(".icon").addClass("rotate")
  $(this).parent().find(".content").text(full_text)
  $(this).find(".readMoreText").text("Show less")
}

});

$(".readMore").hover(function () {
  $(this).parents(".more").css("background", "rgb(234, 234, 234)");
}, function () {
    $(this).parents(".more").css("background", "rgb(243, 243, 243)");
});

.more{
width: 500px;
background: rgb(243, 243, 243);
padding: 5px;
}

.readMore{
cursor: pointer;
user-select: none;
color: indianred;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
font-size: 0.9em;
}
.readMore:hover{
color: rgb(104, 104, 223);
}

.fa-angle-down{
margin-left: 0.2em;
animation: rotationBack 0.8s;
height: 13px;
}

.rotate{
transform: rotate(180deg);
animation: rotation 0.8s;
}
@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(180deg);
  }
}
@keyframes rotationBack {
  from {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(0deg);
  }
}

<html>

<head>
    <title>jQuery Read More/Less Toggle Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
        integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/js/all.min.js"
        integrity="sha512-fzff82+8pzHnwA1mQ0dzz9/E0B+ZRizq08yZfya66INZBz86qKTCt9MLU0NCNIgaMJCgeyhujhasnFUsYMsi0Q=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>

<body>
    <div class="more">
    <span class="content">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
    </span>
    </div>
    <br /><br />
    <div class="more">
    <span class="content">
        Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus,
        feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia
        ultricies nec eget tellus. Curabitur id sapien massa. In hac
        <a href="#">habitasse</a> platea dictumst. Integer tristique leo
        consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius
        purus id turpis iaculis iaculis. Nulla <em>convallis magna nunc</em>, id
        rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque
        eget tempor massa.
    </span>
    </div>
</body>

</html>


问:
AVAudioFile write not working Swift iOS 14
I have the following function:

```<code>private func getPCMBuffer(utterance: AVSpeechUtterance,
                          completion: @escaping (Result<AVAudioPCMBuffer, Failures>) -> Void
) {
    speechSynthesizer.write(utterance) { (buffer: AVAudioBuffer) in
        guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {
            fatalError("unknown buffer type: \(buffer)")
        }

        completion(.success(pcmBuffer))
    }
    completion(.failure(.failed))
}
</code>```

Which returns to me an AVAudioPCMBuffer. I have verified the utterance I pass in speaks properly.

The issue comes when I try to write this AVAudioPCMBuffer into a URL locally, like this:

```<code>                getPCMBuffer(utterance: speechUtterance) { result in
                    switch result {
                    case .success(let buffer):
                        var settings: [String : Any] = [:]
                        let savePathUrl: URL = URL(fileURLWithPath: NSHomeDirectory() + "/Documents/audioFile.caf")

                        settings[AVFormatIDKey] = kAudioFormatMPEG4AAC
                        settings[AVAudioFileTypeKey] = kAudioFileCAFType
                        settings[AVSampleRateKey] = buffer.format.sampleRate
                        settings[AVNumberOfChannelsKey] = 2
                        settings[AVLinearPCMIsFloatKey] = (buffer.format.commonFormat == .pcmFormatInt32)
                        do {
                            let tempFile = try AVAudioFile(forWriting: savePathUrl, settings: settings, commonFormat: buffer.format.commonFormat, interleaved: buffer.format.isInterleaved)
                            try tempFile.write(from: buffer)
                        } catch {
                            print(error)
                        }
                    case .failure(let failure):
                        print(failure.localizedDescription)
                    }
                }
</code>```

I am met with the following error: CABufferList.h:179:BytesConsumed: ASSERTION FAILURE [(nBytes <= buf->mDataByteSize) != 0 is false]:

on the line where I try to do:

try tempFile.write(from: buffer)

答:
There are several things to consider:

Must use a correct format for the file.

The callback of writeUtterance:toBufferCallback: is called multiple times, each time with a the next chunk of the synthesized audio. As far as I can tell, it synthesizes up to 10ms of the audio each time. (undocumented)

You must close the file in order to flush it. Closing is done by releasing the reference to the object. (undocumented).

```<code>@property (readonly, nonatomic) AVSpeechSynthesizer *synth;
@property (strong, nonatomic) AVAudioFile *file;

...

_synth = [[AVSpeechSynthesizer alloc] init];
self.synth.delegate = self;

...

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
 didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
  self.file = nil; // releasing the file will close it
  NSLog(@"Finished");
}

- (void)generateTranscript {
  AVSpeechUtterance *utterance =
      [AVSpeechUtterance speechUtteranceWithString:...];
  utterance.voice = ...;

  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                          withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                         error:nil];

  [self.synth writeUtterance:utterance toBufferCallback:^(AVAudioBuffer * _Nonnull buffer) {
    NSAssert([buffer isKindOfClass:AVAudioPCMBuffer.class], @"");
    NSError *error;

    if (!self.file) {
      NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory()
                                           stringByAppendingPathComponent:@"recording.m4a"]];
      NSMutableDictionary *settings = [NSMutableDictionary dictionary];
      settings[AVFormatIDKey] = @(kAudioFormatMPEG4AAC);
      settings[AVEncoderAudioQualityKey] = @(AVAudioQualityMax);
      settings[AVSampleRateKey] = buffer.format.settings[AVSampleRateKey]; // 22050 Hz
      settings[AVNumberOfChannelsKey] = buffer.format.settings[AVNumberOfChannelsKey]; // 1 channel
      self.file = [[AVAudioFile alloc] initForWriting:url settings:settings
                                         commonFormat:buffer.format.commonFormat // AVAudioPCMFormatInt16
                                          interleaved:buffer.format.interleaved // YES
                                                        error:&error];
      if (error) {
        NSLog(@"%@", error);
        return;
      }
    }

    [self.file writeFromBuffer:(AVAudioPCMBuffer *)buffer error:&error];
    if (error) {
      NSLog(@"%@", error);
      return;
    }

    AVAudioFrameCount frameCont = ((AVAudioPCMBuffer *)buffer).frameLength;
    double sampleRate = buffer.format.sampleRate;
    NSLog(@"Written %.4lfs", (double)frameCont / sampleRate);
  }];
}

</code>```

Regarding the format, I also advice to read AVSpeechSynthesisVoice audioFileSettings documentation.

Body:
I have the following function:

private func getPCMBuffer(utterance: AVSpeechUtterance,
                          completion: @escaping (Result<AVAudioPCMBuffer, Failures>) -> Void
) {
    speechSynthesizer.write(utterance) { (buffer: AVAudioBuffer) in
        guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {
            fatalError("unknown buffer type: \(buffer)")
        }

        completion(.success(pcmBuffer))
    }
    completion(.failure(.failed))
}

Which returns to me an AVAudioPCMBuffer. I have verified the utterance I pass in speaks properly.

The issue comes when I try to write this AVAudioPCMBuffer into a URL locally, like this:

                getPCMBuffer(utterance: speechUtterance) { result in
                    switch result {
                    case .success(let buffer):
                        var settings: [String : Any] = [:]
                        let savePathUrl: URL = URL(fileURLWithPath: NSHomeDirectory() + "/Documents/audioFile.caf")

                        settings[AVFormatIDKey] = kAudioFormatMPEG4AAC
                        settings[AVAudioFileTypeKey] = kAudioFileCAFType
                        settings[AVSampleRateKey] = buffer.format.sampleRate
                        settings[AVNumberOfChannelsKey] = 2
                        settings[AVLinearPCMIsFloatKey] = (buffer.format.commonFormat == .pcmFormatInt32)
                        do {
                            let tempFile = try AVAudioFile(forWriting: savePathUrl, settings: settings, commonFormat: buffer.format.commonFormat, interleaved: buffer.format.isInterleaved)
                            try tempFile.write(from: buffer)
                        } catch {
                            print(error)
                        }
                    case .failure(let failure):
                        print(failure.localizedDescription)
                    }
                }

I am met with the following error: CABufferList.h:179:BytesConsumed: ASSERTION FAILURE [(nBytes <= buf->mDataByteSize) != 0 is false]:

on the line where I try to do:

try tempFile.write(from: buffer)

Body:
There are several things to consider:

Must use a correct format for the file.

The callback of writeUtterance:toBufferCallback: is called multiple times, each time with a the next chunk of the synthesized audio. As far as I can tell, it synthesizes up to 10ms of the audio each time. (undocumented)

You must close the file in order to flush it. Closing is done by releasing the reference to the object. (undocumented).

@property (readonly, nonatomic) AVSpeechSynthesizer *synth;
@property (strong, nonatomic) AVAudioFile *file;

...

_synth = [[AVSpeechSynthesizer alloc] init];
self.synth.delegate = self;

...

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
 didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
  self.file = nil; // releasing the file will close it
  NSLog(@"Finished");
}

- (void)generateTranscript {
  AVSpeechUtterance *utterance =
      [AVSpeechUtterance speechUtteranceWithString:...];
  utterance.voice = ...;

  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                          withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                         error:nil];

  [self.synth writeUtterance:utterance toBufferCallback:^(AVAudioBuffer * _Nonnull buffer) {
    NSAssert([buffer isKindOfClass:AVAudioPCMBuffer.class], @"");
    NSError *error;

    if (!self.file) {
      NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory()
                                           stringByAppendingPathComponent:@"recording.m4a"]];
      NSMutableDictionary *settings = [NSMutableDictionary dictionary];
      settings[AVFormatIDKey] = @(kAudioFormatMPEG4AAC);
      settings[AVEncoderAudioQualityKey] = @(AVAudioQualityMax);
      settings[AVSampleRateKey] = buffer.format.settings[AVSampleRateKey]; // 22050 Hz
      settings[AVNumberOfChannelsKey] = buffer.format.settings[AVNumberOfChannelsKey]; // 1 channel
      self.file = [[AVAudioFile alloc] initForWriting:url settings:settings
                                         commonFormat:buffer.format.commonFormat // AVAudioPCMFormatInt16
                                          interleaved:buffer.format.interleaved // YES
                                                        error:&error];
      if (error) {
        NSLog(@"%@", error);
        return;
      }
    }

    [self.file writeFromBuffer:(AVAudioPCMBuffer *)buffer error:&error];
    if (error) {
      NSLog(@"%@", error);
      return;
    }

    AVAudioFrameCount frameCont = ((AVAudioPCMBuffer *)buffer).frameLength;
    double sampleRate = buffer.format.sampleRate;
    NSLog(@"Written %.4lfs", (double)frameCont / sampleRate);
  }];
}

Regarding the format, I also advice to read AVSpeechSynthesisVoice audioFileSettings documentation.


问:
how to add two numbers in tkinter
I am trying to learn tkinter. I have written a code to add two numbers and show the result below. But I get an error. Anybody can let me know where I have a mistake? Thank you

This is my code:

```<code>from tkinter import *

root = Tk()
root.geometry("400x400")

label1 = Label(root, text="your first number:").grid(row=0, column=0)
label2 = Label(root, text="your second number:").grid(row=1, column=0)

first_no  = IntVar()
second_no = IntVar()

entry1 = Entry(root, textvariable = first_no).grid(row=0, column=1)
entry2 = Entry(root, textvariable = second_no).grid(row=1, column=1)

def add():
    sumation = first_no.get() + second_no.get()
    label3.config(text = "your final number is:" + str(sumation))

mybutton = Button(root, text="Calculate!", command = add).grid(row=2, column=1)

label3 = Label(root).grid(row=3, column=1)

root.mainloop()
</code>```

and this is the error:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\pymnb\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "<ipython-input-13-6c227c88abbc>", line 17, in addition
    label3.config(text = "your final number is:" + str(sumation))
AttributeError: 'NoneType' object has no attribute 'config'
</code>```

答:
It errors bc .grid doesnt return the label.
so do it two steps

from tkinter import *

root = Tk()
root.geometry("400x400")

Label(root, text="your first number:").grid(row=0, column=0)
Label(root, text="your second number:").grid(row=1, column=0)
# define the label, step 1
label3 = Label(root)
# set grid, step 2
label3.grid(row=3, column=1)

first_no = IntVar()
second_no = IntVar()

# same goes for here
entry1 = Entry(root, textvariable=first_no).grid(row=0, column=1)
entry2 = Entry(root, textvariable=second_no).grid(row=1, column=1)

def add():
    sumation = first_no.get() + second_no.get()
    label3.config(text="your final number is:" + str(sumation))

# and here
mybutton = Button(root, text=("Calculate!"), command=add).grid(row=2, column=1)

root.mainloop()
```

Title: how to add two numbers in tkinter

Body:
I am trying to learn tkinter. I have written a code to add two numbers and show the result below. But I get an error. Anybody can let me know where I have a mistake? Thank you

This is my code:

from tkinter import *

root = Tk()
root.geometry("400x400")

label1 = Label(root, text="your first number:").grid(row=0, column=0)
label2 = Label(root, text="your second number:").grid(row=1, column=0)

first_no  = IntVar()
second_no = IntVar()

entry1 = Entry(root, textvariable = first_no).grid(row=0, column=1)
entry2 = Entry(root, textvariable = second_no).grid(row=1, column=1)

def add():
    sumation = first_no.get() + second_no.get()
    label3.config(text = "your final number is:" + str(sumation))

mybutton = Button(root, text="Calculate!", command = add).grid(row=2, column=1)

label3 = Label(root).grid(row=3, column=1)

root.mainloop()

and this is the error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\pymnb\anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "<ipython-input-13-6c227c88abbc>", line 17, in addition
    label3.config(text = "your final number is:" + str(sumation))
AttributeError: 'NoneType' object has no attribute 'config'


问:
Android- using addJavaScriptInterface to return a value from Javascript
So i know there are other posts addressing the same issue, and I think I've followed them to the letter but alas to no avail.  I'm trying to learn how to get my app to interact with javascript.  I just want to be able to return a value from my javascript to my activity.

here is my activity:

```<code>public class JSExample extends Activity {
WebView mWebView;
String mString;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mWebView = (WebView)findViewById(R.id.mWebView);
    mWebView.addJavascriptInterface(new ClsAccessor(), "accessor");
    String html = getAssetsContent("jsinterface.html");

    mWebView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);

 //   Log.d("YO!", mString);
}

private String getAssetsContent(String filename){
    .....
}

private void closeStream(BufferedReader stream) {
    .....
}

class ClsAccessor{
    public void setValue(String value){
        JSExample.this.mString = value;
    }
}
</code>```

Here is the html file loaded by my WebView that contains the javascript i want to run:

```<code>    <!DOCTYPE html>

<html>
<head>
    <script language="javascript">
        accessor.setValue('Hello!');
    </script>
</head>
<body>
<h1>Testing</h1>
</body>
</html>
</code>```

This does not work.  When i run the code with "Log.d("YO!", mString);" uncommented I get a null pointer exception, which means that the javascript never assigned a value to mString.  what am i doing wrong?

答:
Try enabling javascript on your webview :</p>

```<code>mWebview.getSettings().setJavaScriptEnabled(true);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So i know there are other posts addressing the same issue, and I think I've followed them to the letter but alas to no avail.  I'm trying to learn how to get my app to interact with javascript.  I just want to be able to return a value from my javascript to my activity.

here is my activity:

public class JSExample extends Activity {
WebView mWebView;
String mString;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mWebView = (WebView)findViewById(R.id.mWebView);
    mWebView.addJavascriptInterface(new ClsAccessor(), "accessor");
    String html = getAssetsContent("jsinterface.html");

    mWebView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);

 //   Log.d("YO!", mString);
}

private String getAssetsContent(String filename){
    .....
}

private void closeStream(BufferedReader stream) {
    .....
}

class ClsAccessor{
    public void setValue(String value){
        JSExample.this.mString = value;
    }
}

Here is the html file loaded by my WebView that contains the javascript i want to run:

    <!DOCTYPE html>

Testing

This does not work.  When i run the code with "Log.d("YO!", mString);" uncommented I get a null pointer exception, which means that the javascript never assigned a value to mString.  what am i doing wrong?

Body:
Try enabling javascript on your webview :

mWebview.getSettings().setJavaScriptEnabled(true);


问:
How do I measure how long the user held down a button?
I tried using the Timer class but that only counts down from a fixed duration AFAIK. I have a button where the user can either single tap it or long press and hold it for X amount of seconds, up to a maximum of 10 seconds. I already figured out the single tap code, but if the user presses and holds the button I want to record how long he held it for and also do other stuff.</p>
```<code>Timer startRecordingTimer() => Timer(Duration(milliseconds: 10 * 1000), handleTimeout);

void handleTimeout() {
  //when startRecordingTimer() reaches 0, do the following
  stopRecording();
}

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      startRecording();
                    },
                    onLongPressDown: (details) {
                      startRecordingTimer();
                      startRecording();
                    },
                    onLongPressUp: () {
                      //Need to measure how long user held down button
                      //Do other stuff using the aforementioned duration
                    },
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }
</code>```

答:
on onLongPressDown() you can get the DateTime then get the end DateTime to subtract from on onLongPressUp()

```<code>DateTime startTime;
DateTime endTime;
onLongPressDown: (details) {
    startTime = DateTime.now();
  },
onLongPressUp: () {
    endTime = DateTime.now();
    longPressDuration = endTime.difference(startTime);
  },
</code>```

Body:
I tried using the Timer class but that only counts down from a fixed duration AFAIK. I have a button where the user can either single tap it or long press and hold it for X amount of seconds, up to a maximum of 10 seconds. I already figured out the single tap code, but if the user presses and holds the button I want to record how long he held it for and also do other stuff.

Timer startRecordingTimer() => Timer(Duration(milliseconds: 10 * 1000), handleTimeout);

void handleTimeout() {
  //when startRecordingTimer() reaches 0, do the following
  stopRecording();
}

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      startRecording();
                    },
                    onLongPressDown: (details) {
                      startRecordingTimer();
                      startRecording();
                    },
                    onLongPressUp: () {
                      //Need to measure how long user held down button
                      //Do other stuff using the aforementioned duration
                    },
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }

Body:
on onLongPressDown() you can get the DateTime then get the end DateTime to subtract from on onLongPressUp()

DateTime startTime;
DateTime endTime;
onLongPressDown: (details) {
    startTime = DateTime.now();
  },
onLongPressUp: () {
    endTime = DateTime.now();
    longPressDuration = endTime.difference(startTime);
  },


答:
You forget to instance label3:

```<code>label3 = Label(root, text="result:").grid(row=3, column=0)
</code>```

Because of that this line is returning "NoneType"

```<code>label3.config(text="your final number is:" + str(sumation))
</code>```

Title: how to add two numbers in tkinter

Body:
You forget to instance label3:

label3 = Label(root, text="result:").grid(row=3, column=0)

Because of that this line is returning "NoneType"

label3.config(text="your final number is:" + str(sumation))


问:
Docker Connection Refused when joining Swarm on internal network
I am able to ping IPs between two machines on an internal network. However, when I try and join a Swarm, I get the following error:

```<code>Error response from daemon: rpc error: code = Unavailable desc = connection error: desc = "transport: Error while dialing dial tcp n.n.n.n:nnnn: connect: connection refused"
</code>```

where n.n.n.n:nnnn is obviously the IP and PORT of the Swarm Manager (per docker swarm join-token worker).

I've searched but have been unable to find any information on further configuration I need to do on the Swarm Manager to resolve this issue (most likely because I'm not sure what to search on).

Does anyone happen to know how to resolve this? Thanks for any guidance!

答:
I just found the following in a Docker Swarm doc:

Currently, you cannot use Docker Desktop for Mac or Docker Desktop for Windows alone to test a multi-node swarm, but many examples are applicable to a single-node Swarm setup.

Since I'm running the Master and Worker on two Mac computers, it looks like I'm out luck for now.

Body:
I am able to ping IPs between two machines on an internal network. However, when I try and join a Swarm, I get the following error:

Error response from daemon: rpc error: code = Unavailable desc = connection error: desc = "transport: Error while dialing dial tcp n.n.n.n:nnnn: connect: connection refused"

where n.n.n.n:nnnn is obviously the IP and PORT of the Swarm Manager (per docker swarm join-token worker).

I've searched but have been unable to find any information on further configuration I need to do on the Swarm Manager to resolve this issue (most likely because I'm not sure what to search on).

Does anyone happen to know how to resolve this? Thanks for any guidance!


问:
Bash/WSL - How to run command as root?
```<code>>ubuntu1804.exe -c "echo $USER"
mpen
</code>```

That runs the command as me, how do I run it as root?

The help page doesn't even mention -c

```<code>>ubuntu1804.exe help
Launches or configures a Linux distribution.

Usage:
    <no args>
        Launches the user's default shell in the user's home directory.

    install [--root]
        Install the distribuiton and do not launch the shell when complete.
          --root
              Do not create a user account and leave the default user set to root.

    run <command line>
        Run the provided command line in the current working directory. If no
        command line is provided, the default shell is launched.

    config [setting [value]]
        Configure settings for this distribution.
        Settings:
          --default-user <username>
              Sets the default user to <username>. This must be an existing user.

    help
        Print usage information.
</code>```

答:
If you need to run multiple commands, just login as root:

```<code>wsl -u root
</code>```

and run all commands interactively

Title: Bash/WSL - How to run command as root?

Body:
>ubuntu1804.exe -c "echo $USER"
mpen

That runs the command as me, how do I run it as root?

The help page doesn't even mention -c

>ubuntu1804.exe help
Launches or configures a Linux distribution.

Usage:
    <no args>
        Launches the user's default shell in the user's home directory.

    install [--root]
        Install the distribuiton and do not launch the shell when complete.
          --root
              Do not create a user account and leave the default user set to root.

    run <command line>
        Run the provided command line in the current working directory. If no
        command line is provided, the default shell is launched.

    config [setting [value]]
        Configure settings for this distribution.
        Settings:
          --default-user <username>
              Sets the default user to <username>. This must be an existing user.

    help
        Print usage information.

Body:
If you need to run multiple commands, just login as root:

wsl -u root

and run all commands interactively


问:
Parsing large csv file to tinydb takes forever
I have a large csv file containing 15 columns and approximately 1 million rows. I want to parse the data into tinyDB. The code I use is below:

```<code>import csv
from tinydb import TinyDB

db = TinyDB('db.monitor')
table = db.table('Current')

i=0

datafile = open('newData.csv', 'rb')
data=csv.reader(datafile, delimiter = ';')

for row in data:
    table.insert({'WT_ID': row[0], 'time': row[1], 'MeanCurrent': row[2], 'VapourPressure': row[3], 'MeanVoltage':row[4], 'Temperature': row[5], 'Humidity': row[6], 'BarPressure': row[7], 'RPM': row[8], 'WindSector': row[9], 'WindSpeed': row[10], 'AirDensity': row[12], 'VoltageDC': row[13], 'PowerSec': row[14], 'FurlingAngle': row[15]})
    i=i+1
    print i
</code>```

However, it really takes forever. I have set the i variable to track the progress, and while in the first lines it runs fast, now its been more than an hour and it has parsed about 10000 lines at a pace of almost 1Hz

I couldn't find anything similar so any help would be appreciated

Thank you

答:
User Pandas to write to the Json file which will be a lot quicker.

```<code>generated_rules.to_json('./Data/rules.json', orient='index', index='true')
</code>```

Then edit the generated json file and add table or default in json file eg

Before

```<code>{"0": {...}, "1":{...}
</code>```

After

```<code>{rules:{"0": {...}, "1":{...}}
</code>```

then just read this json file as tiny db.

Body:
I have a large csv file containing 15 columns and approximately 1 million rows. I want to parse the data into tinyDB. The code I use is below:

import csv
from tinydb import TinyDB

db = TinyDB('db.monitor')
table = db.table('Current')

i=0

datafile = open('newData.csv', 'rb')
data=csv.reader(datafile, delimiter = ';')

for row in data:
    table.insert({'WT_ID': row[0], 'time': row[1], 'MeanCurrent': row[2], 'VapourPressure': row[3], 'MeanVoltage':row[4], 'Temperature': row[5], 'Humidity': row[6], 'BarPressure': row[7], 'RPM': row[8], 'WindSector': row[9], 'WindSpeed': row[10], 'AirDensity': row[12], 'VoltageDC': row[13], 'PowerSec': row[14], 'FurlingAngle': row[15]})
    i=i+1
    print i

However, it really takes forever. I have set the i variable to track the progress, and while in the first lines it runs fast, now its been more than an hour and it has parsed about 10000 lines at a pace of almost 1Hz

I couldn't find anything similar so any help would be appreciated

Thank you

Body:
User Pandas to write to the Json file which will be a lot quicker.

generated_rules.to_json('./Data/rules.json', orient='index', index='true')

Then edit the generated json file and add table or default in json file eg

Before

{"0": {...}, "1":{...}

After

{rules:{"0": {...}, "1":{...}}

then just read this json file as tiny db.


问:
Flattening nested array in JavaScript
I have a horrible looking array which looks like this:

EDIT:

```<code>array = [
    {
        Letters: [{ Letter: 'A' }, { Letter: 'B' }, { Letter: 'C' }],
        Numbers: [{ Number: '1' }, { Number: '2' }, { Number: '3' }]
    },
    null,
    {
        Letters: [{ Letter: 'D' }, { Letter: 'E' }, { Letter: 'F' }, { Letter: 'G' }, { Letter: 'H' }],
        Numbers: [{ Number: '4' }, { Number: '5' }, { Number: '6' }, { Number: '7' }]
    }
];
</code>```

And want the array to look like this:

```<code>flattenedArray = [a,b,c,1,2,3,d,e,f,g,h,4,5,6,7]
</code>```

Unfortunately I cannot change the original formatting because that is the form received when merging two API responses that I am getting.

I have tried using:

```<code>var flattenedArray = [].concat.apply([], array);
</code>```

But it just presents the array in the same format it was entered in.

I was wondering if anybody had any advice?

EDIT:
I have tried implementing the suggestions given - thank you so much for your help. It seems it is a problem with the format of the list - unfortunately using the chrome console which is in a 'tree' format I cannot see the direct structure of the array output.

Thank you for all your help!
EDIT 2: See above for the actual array, thank you for showing me how to see this!

答:
Implement flatten function using recursion and spread operator.

const a = [1,[2,[3,4],[5]],6];
const flatten = (arr) => {
    const res = []
    for(let i=0;i<arr.length;i++) {
        if(!Array.isArray(arr[i])) res.push(arr[i]);
        else res.push(...flatten(arr[i]));
    }
    return res;
}
console.log(flatten(a));```

Title: Flattening nested array in JavaScript

Body:
I have a horrible looking array which looks like this:

EDIT:

array = [
    {
        Letters: [{ Letter: 'A' }, { Letter: 'B' }, { Letter: 'C' }],
        Numbers: [{ Number: '1' }, { Number: '2' }, { Number: '3' }]
    },
    null,
    {
        Letters: [{ Letter: 'D' }, { Letter: 'E' }, { Letter: 'F' }, { Letter: 'G' }, { Letter: 'H' }],
        Numbers: [{ Number: '4' }, { Number: '5' }, { Number: '6' }, { Number: '7' }]
    }
];

And want the array to look like this:

flattenedArray = [a,b,c,1,2,3,d,e,f,g,h,4,5,6,7]

Unfortunately I cannot change the original formatting because that is the form received when merging two API responses that I am getting.

I have tried using:

var flattenedArray = [].concat.apply([], array);

But it just presents the array in the same format it was entered in.

I was wondering if anybody had any advice?

EDIT:
I have tried implementing the suggestions given - thank you so much for your help. It seems it is a problem with the format of the list - unfortunately using the chrome console which is in a 'tree' format I cannot see the direct structure of the array output.

Thank you for all your help!
EDIT 2: See above for the actual array, thank you for showing me how to see this!


问:
How to split a stream into two flows using GraphDSL
I'm learning akka streams and as an example I'm attempting to split data into two separate flows depending on the structure of JSON received from a source using the GraphDSL.

Here is the complete code I've stitched together below :

```<code>import akka.Done;
import akka.NotUsed;
import akka.actor.typed.ActorSystem;
import akka.actor.typed.javadsl.Behaviors;
import akka.stream.ClosedShape;
import akka.stream.FlowShape;
import akka.stream.SourceShape;
import akka.stream.UniformFanOutShape;
import akka.stream.javadsl.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import objectmappertest.Request;
import java.util.Collections;
import java.util.concurrent.CompletionStage;

public class FilterObj {

    public static void main(String args[]){

        final ActorSystem actorSystem = ActorSystem.create(Behaviors.empty(), "actorSystem");

        final String json1  = "{\"datePurchased\":\"2022-02-03 21:32:017\"}";
        final String json2  = "{\"unknownField\":\"test\"}";

        final ObjectMapper mapper = new ObjectMapper();

        final Source<String, NotUsed> source1 = Source.repeat(json1).take(3);
        final Source<String, NotUsed> source2 = Source.repeat(json2).take(3);
        final Source<String, NotUsed> source3 = Source.repeat(json2).take(3);

        final Source<String, NotUsed> source =
                Source.combine(source1, source2 , Collections.singletonList(source3), Merge::create);

        final Flow<String, Request, NotUsed> flowOperation = Flow.of(String.class)
                .map ( input -> {
                    final JsonNode request = mapper.readTree(input);
                    if(request.has("datePurchased")){
                        return mapper.readValue(request.toString() , Request.class);
                    }
                    else {
                        return mapper.readValue(request.toString() , Request.class);
                    }

                }).log("error");

        final Sink<Request, CompletionStage<Done>> printSink = Sink.foreach(System.out::println);

        final RunnableGraph<CompletionStage<Done>> graph = RunnableGraph.fromGraph(
                GraphDSL.create(printSink, (builder, out) -> {
                    final SourceShape<String> sourceShape = builder.add(source);
                    final FlowShape<String, Request> flow1Shape = builder.add(flowOperation);

                    final UniformFanOutShape<String, String> broadcast =
                            builder.add(Broadcast.create(2));
                    builder.from(sourceShape)
                            .viaFanOut(broadcast)
                            .via(flow1Shape)
                            .to(out);

                    return ClosedShape.getInstance();
                })
        );
        graph.run(actorSystem);

    }
}
</code>```

Request class :

```<code>import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.ToString;
import lombok.extern.jackson.Jacksonized;
import java.util.Date;

@Builder
@ToString
@Jacksonized
public class Request
{
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:sss")
    private final Date datePurchased;
}
</code>```

Running the above graph prints :

```<code>17:16:57.129 INFO  akka.event.slf4j.Slf4jLogger  [NativeMethodAccessorImpl.java:-2] - Slf4jLogger started
SLF4J: A number (1) of logging calls during the initialization phase have been intercepted and are
SLF4J: now being replayed. These are subject to the filtering rules of the underlying logging system.
SLF4J: See also http://www.slf4j.org/codes.html#replay
Exception in thread "main" java.lang.IllegalStateException: Illegal GraphDSL usage. Outlets [Broadcast.out1] were not returned in the resulting shape and not connected.
    at akka.stream.scaladsl.GraphDSL$Builder.result(Graph.scala:1690)
    at akka.stream.scaladsl.GraphApply.createGraph(GraphApply.scala:1144)
    at akka.stream.scaladsl.GraphApply.createGraph(GraphApply.scala:46)
    at akka.stream.scaladsl.GraphApply.createGraph$(GraphApply.scala:41)
    at akka.stream.scaladsl.GraphDSL$.createGraph(Graph.scala:1557)
    at akka.stream.javadsl.GraphCreate.create(GraphCreate.scala:26)
    at akka.stream.javadsl.GraphDSL.create(Graph.scala)
    at FilterObj.FilterObj.main(FilterObj.java:70)
</code>```

To emulate two types of JSON payloads I merge sources into a single source using :

```<code>    final String json1  = "{\"datePurchased\":\"2022-02-03 21:32:017\"}";
    final String json2  = "{\"unknownField\":\"test\"}";

    final ObjectMapper mapper = new ObjectMapper();

    final Source<String, NotUsed> source1 = Source.repeat(json1).take(3);
    final Source<String, NotUsed> source2 = Source.repeat(json2).take(3);
    final Source<String, NotUsed> source3 = Source.repeat(json2).take(3);

    final Source<String, NotUsed> source =
            Source.combine(source1, source2 , Collections.singletonList(source3), Merge::create);
</code>```

I'm unsure how to correctly incorporate the logic to split the data depending if datePurchased is contained with the JSON being parsed, currently it's implemented as

```<code>                if(request.has("datePurchased")){
                    return mapper.readValue(request.toString() , Request.class);
                }
                else {
                    return mapper.readValue(request.toString() , Request.class);
                }
</code>```

I think I need a UniformFanOutShape but I'm unsure how to incorporate it into the GraphDSL .

答:
If you want to split data than you need Partition rather than Broadcast.

They are both fanout shapes, but whereas Broadcast sends incoming message to all its outputs, Partition allows you to use custom logic to decide which output a message should go to... which is what I think you're trying to do.

The documentation is pretty good with code samples:
https://doc.akka.io/docs/akka/current/stream/operators/Partition.html

Body:
I'm learning akka streams and as an example I'm attempting to split data into two separate flows depending on the structure of JSON received from a source using the GraphDSL.

Here is the complete code I've stitched together below :

import akka.Done;
import akka.NotUsed;
import akka.actor.typed.ActorSystem;
import akka.actor.typed.javadsl.Behaviors;
import akka.stream.ClosedShape;
import akka.stream.FlowShape;
import akka.stream.SourceShape;
import akka.stream.UniformFanOutShape;
import akka.stream.javadsl.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import objectmappertest.Request;
import java.util.Collections;
import java.util.concurrent.CompletionStage;

public class FilterObj {

    public static void main(String args[]){

        final ActorSystem actorSystem = ActorSystem.create(Behaviors.empty(), "actorSystem");

        final String json1  = "{\"datePurchased\":\"2022-02-03 21:32:017\"}";
        final String json2  = "{\"unknownField\":\"test\"}";

        final ObjectMapper mapper = new ObjectMapper();

        final Source<String, NotUsed> source1 = Source.repeat(json1).take(3);
        final Source<String, NotUsed> source2 = Source.repeat(json2).take(3);
        final Source<String, NotUsed> source3 = Source.repeat(json2).take(3);

        final Source<String, NotUsed> source =
                Source.combine(source1, source2 , Collections.singletonList(source3), Merge::create);

        final Flow<String, Request, NotUsed> flowOperation = Flow.of(String.class)
                .map ( input -> {
                    final JsonNode request = mapper.readTree(input);
                    if(request.has("datePurchased")){
                        return mapper.readValue(request.toString() , Request.class);
                    }
                    else {
                        return mapper.readValue(request.toString() , Request.class);
                    }

                }).log("error");

        final Sink<Request, CompletionStage<Done>> printSink = Sink.foreach(System.out::println);

        final RunnableGraph<CompletionStage<Done>> graph = RunnableGraph.fromGraph(
                GraphDSL.create(printSink, (builder, out) -> {
                    final SourceShape<String> sourceShape = builder.add(source);
                    final FlowShape<String, Request> flow1Shape = builder.add(flowOperation);

                    final UniformFanOutShape<String, String> broadcast =
                            builder.add(Broadcast.create(2));
                    builder.from(sourceShape)
                            .viaFanOut(broadcast)
                            .via(flow1Shape)
                            .to(out);

                    return ClosedShape.getInstance();
                })
        );
        graph.run(actorSystem);

    }
}

Request class :

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.ToString;
import lombok.extern.jackson.Jacksonized;
import java.util.Date;

@Builder
@ToString
@Jacksonized
public class Request
{
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:sss")
    private final Date datePurchased;
}

Running the above graph prints :

17:16:57.129 INFO  akka.event.slf4j.Slf4jLogger  [NativeMethodAccessorImpl.java:-2] - Slf4jLogger started
SLF4J: A number (1) of logging calls during the initialization phase have been intercepted and are
SLF4J: now being replayed. These are subject to the filtering rules of the underlying logging system.
SLF4J: See also http://www.slf4j.org/codes.html#replay
Exception in thread "main" java.lang.IllegalStateException: Illegal GraphDSL usage. Outlets [Broadcast.out1] were not returned in the resulting shape and not connected.
    at akka.stream.scaladsl.GraphDSL$Builder.result(Graph.scala:1690)
    at akka.stream.scaladsl.GraphApply.createGraph(GraphApply.scala:1144)
    at akka.stream.scaladsl.GraphApply.createGraph(GraphApply.scala:46)
    at akka.stream.scaladsl.GraphApply.createGraph$(GraphApply.scala:41)
    at akka.stream.scaladsl.GraphDSL$.createGraph(Graph.scala:1557)
    at akka.stream.javadsl.GraphCreate.create(GraphCreate.scala:26)
    at akka.stream.javadsl.GraphDSL.create(Graph.scala)
    at FilterObj.FilterObj.main(FilterObj.java:70)

To emulate two types of JSON payloads I merge sources into a single source using :

    final String json1  = "{\"datePurchased\":\"2022-02-03 21:32:017\"}";
    final String json2  = "{\"unknownField\":\"test\"}";

    final ObjectMapper mapper = new ObjectMapper();

    final Source<String, NotUsed> source1 = Source.repeat(json1).take(3);
    final Source<String, NotUsed> source2 = Source.repeat(json2).take(3);
    final Source<String, NotUsed> source3 = Source.repeat(json2).take(3);

    final Source<String, NotUsed> source =
            Source.combine(source1, source2 , Collections.singletonList(source3), Merge::create);

I'm unsure how to correctly incorporate the logic to split the data depending if datePurchased is contained with the JSON being parsed, currently it's implemented as

                if(request.has("datePurchased")){
                    return mapper.readValue(request.toString() , Request.class);
                }
                else {
                    return mapper.readValue(request.toString() , Request.class);
                }

I think I need a UniformFanOutShape but I'm unsure how to incorporate it into the GraphDSL .