问:
Neural network produces same outputs no matter on inputs
I am new to neural networks, and have been working on creating an ANN from scratch, however the values being outputted do not seem to change based on the inputs, and the error does not reduce.

My logic for feedforward:

```<code>A0 = inputs
Z1 = weights(input layer) * A0 = hidden pre-activation
A1 = sigmoid(Z1) = hidden post-activation
Z2 = weights(hidden layer) * A1 = output pre-activation
A2 = sigmoid(Z2) = output post-activation
</code>```

My logic for backpropagation:

```<code>E(output) = 2 * (A2 - Target Value) * derivative_sigmoid(Z2)
E(hidden) = transposed_weights(hidden layer) * E(output) * derivative_sigmoid(Z1)
</code>```

and weights are updated as follows:

```<code>weights(input layer) -= numpy.outer(error, A0)
weights(hidden layer) -= numpy.outer(error, A1)
</code>```

This is a simplified version from the actual code, as the code only accounts for more than 1 hidden layers so far.

Also, I don't know how I should be updating biases in the code, as they are currently omitted.

Here is the code, and attached is a graph of the error, where the line is blue when the target output is one, and red when target output is zero.

https://pastebin.com/nJjVRjHr

```<code> def back_propagate(self):
        # check if propagated
        assert self.propagated, "Not propagated"

        error = 0

        # calculate how much to change weights in accordance to errors
        first = True
        for index in reversed(range(0, len(self.hidden_layers))):
            # first hidden layer uses output layer
            if first:
                error = 2 * (self.output_layer.a - self.output_layer.targets) * derivative_sigmoid(self.output_layer.z)
                self.hidden_layers[index].update_weight_matrix = numpy.outer(error, self.hidden_layers[index].a)
                first = False
            else:
                error = numpy.matmul(self.hidden_layers[index + 1].weight_matrix[:, :self.hidden_layers[index + 1].node_count - 1].transpose(), error)
                error *= derivative_sigmoid(self.hidden_layers[index].z)
                self.hidden_layers[index].update_weight_matrix = numpy.outer(error, self.hidden_layers[index].a)

        error = numpy.matmul(self.hidden_layers[0].weight_matrix[:, :self.hidden_layers[0].node_count - 1].transpose(), error)
        error *= derivative_sigmoid(self.hidden_layers[0].z)
        self.input_layer.update_weight_matrix = numpy.outer(error, self.input_layer.inputs)

        self.input_layer.update_weight_matrix = self.input_layer.update_weight_matrix * 10 / numpy.linalg.norm(self.input_layer.update_weight_matrix)
        self.input_layer.weight_matrix[:, :] -= LEARNING_RATE * self.input_layer.update_weight_matrix
        for index in range(len(self.hidden_layers)):
            self.hidden_layers[index].update_weight_matrix = self.hidden_layers[index].update_weight_matrix * 10 / numpy.linalg.norm(
                self.hidden_layers[index].update_weight_matrix)
            self.hidden_layers[index].weight_matrix[:, :-1] -= LEARNING_RATE * self.hidden_layers[index].update_weight_matrix

        self.propagated = False
</code>```

Any help would be greatly appreciated.

Body:
I am new to neural networks, and have been working on creating an ANN from scratch, however the values being outputted do not seem to change based on the inputs, and the error does not reduce.

My logic for feedforward:

A0 = inputs
Z1 = weights(input layer) * A0 = hidden pre-activation
A1 = sigmoid(Z1) = hidden post-activation
Z2 = weights(hidden layer) * A1 = output pre-activation
A2 = sigmoid(Z2) = output post-activation

My logic for backpropagation:

E(output) = 2 * (A2 - Target Value) * derivative_sigmoid(Z2)
E(hidden) = transposed_weights(hidden layer) * E(output) * derivative_sigmoid(Z1)

and weights are updated as follows:

weights(input layer) -= numpy.outer(error, A0)
weights(hidden layer) -= numpy.outer(error, A1)

This is a simplified version from the actual code, as the code only accounts for more than 1 hidden layers so far.

Also, I don't know how I should be updating biases in the code, as they are currently omitted.

Here is the code, and attached is a graph of the error, where the line is blue when the target output is one, and red when target output is zero.

https://pastebin.com/nJjVRjHr

 def back_propagate(self):
        # check if propagated
        assert self.propagated, "Not propagated"

        error = 0

        # calculate how much to change weights in accordance to errors
        first = True
        for index in reversed(range(0, len(self.hidden_layers))):
            # first hidden layer uses output layer
            if first:
                error = 2 * (self.output_layer.a - self.output_layer.targets) * derivative_sigmoid(self.output_layer.z)
                self.hidden_layers[index].update_weight_matrix = numpy.outer(error, self.hidden_layers[index].a)
                first = False
            else:
                error = numpy.matmul(self.hidden_layers[index + 1].weight_matrix[:, :self.hidden_layers[index + 1].node_count - 1].transpose(), error)
                error *= derivative_sigmoid(self.hidden_layers[index].z)
                self.hidden_layers[index].update_weight_matrix = numpy.outer(error, self.hidden_layers[index].a)

        error = numpy.matmul(self.hidden_layers[0].weight_matrix[:, :self.hidden_layers[0].node_count - 1].transpose(), error)
        error *= derivative_sigmoid(self.hidden_layers[0].z)
        self.input_layer.update_weight_matrix = numpy.outer(error, self.input_layer.inputs)

        self.input_layer.update_weight_matrix = self.input_layer.update_weight_matrix * 10 / numpy.linalg.norm(self.input_layer.update_weight_matrix)
        self.input_layer.weight_matrix[:, :] -= LEARNING_RATE * self.input_layer.update_weight_matrix
        for index in range(len(self.hidden_layers)):
            self.hidden_layers[index].update_weight_matrix = self.hidden_layers[index].update_weight_matrix * 10 / numpy.linalg.norm(
                self.hidden_layers[index].update_weight_matrix)
            self.hidden_layers[index].weight_matrix[:, :-1] -= LEARNING_RATE * self.hidden_layers[index].update_weight_matrix

        self.propagated = False

Any help would be greatly appreciated.


来源: stackexchange

问:
Want to publish vue nuxt.js app to iis on windows server
maybe someone more experienced in IIS could help.
I have the following scenario: Windows Server 2019, mais site and several applications running on IIS 10 i.e (site.com/app1, site.com/app2).
My objective is to have a vue/nuxt app running in site.com/app3, utilizing same SSL config.

I've already tested IISNode and Url Rewrite without success, my best shot was redirecting site.com/app3 to port 3000 where the app is running, but it doesn't load anything but the main page.

ContentLicense: CC BY-SA 4.0


问:
how can i get data from a site
I am working in android studio program and I am using java, I want to pull data from a site like Tradingview, how can I do that?</p>

Title: how can i get data from a site


问:
GCP custom policy, restrict resources
I want to restrict GCP resources via a custom policy.
1- specific VM types,
2- Storage size restrictions only 10GB allowed size selection.

Is this possible in GCP that we restrict users to create specific types of resources?

I have created a custom role, that only allowed create, update, delete and list operations on GCP resources.

I cannot restrict user that specific type of VM Instance creation allowed.

Title: GCP custom policy, restrict resources


问:
Selenium UI Automation Testing plugin in IntelliJ IDEA
Regarding Selenium Support in IntelliJ IDEA, I tend to use the methods recommended by jetbrains, which I found at

https://blog.jetbrains.com/idea/2020/03/intellij-idea-2020-1-selenium-support/

https://www.jetbrains.com/help/idea/selenium.html (Last modified: 05 December 2022)

They both recommend the Selenium UI Automation Testing plugin, yet I'm not able to find it myself:

Digging deeper, I found

https://plugins.jetbrains.com/plugin/13691-selenium-ui-testing

which says it is "Included In
Test Automation Kit"

Yet, I'm unable to find the "Test Automation Kit" either.

Given that https://www.jetbrains.com/help/idea/selenium.html was last modified at 05 December 2022, I'm thinking that I'm missing something very obvious. Please help.

How can I have Selenium Support in IntelliJ IDEA?

How can I run Selenium scripts in IntelliJ IDEA?


问:
Swift i want to check the data entered by user
I'm new to coding on Swift and I'm having a problem with a code. I want to verify the data entered by the user.

IngredientDetailView contains a form to add or modify an ingredient. In this view I want to control the data entered by the user. So the ingredients have a unique name.

My problem
When I modify the name of an existing ingredient with a name of another ingredient, my control does not work.

IngredientListView contains the list of existing ingredients that can be modified.

Thanks in advance for reading and helping.

```<code>struct IngredientDetailView: View {
    @Environment(\.dismiss) private var dismiss

    @State var ingredientItemData : Ingredient
    @EnvironmentObject var ingredientsVM: IngredientModel
    // To display the message that an ingredient already exists
    @State private var showingAlertIngredientExist = false
    let metrics: [String] = [
        "Unité", "kg", "g", "l", "ml"
    ]

    var body: some View {
        List{
            TextField("Ingredient name", text: $ingredientItemData.nom)
            Text("Metric").bold()
            Picker(selection: $ingredientItemData.metric, label: Text("Metric"), content: {
                ForEach(metrics, id: \.self){ item in
                    Text(item)
                }
            }).pickerStyle(.segmented)
        }
        .toolbar{
            ToolbarItem(placement: .navigationBarLeading){
                Button("Cancel"){
                    dismiss()
                }
            }
            ToolbarItem(placement: .navigationBarTrailing){
                Button("Ok"){
                    //If the id already exists
                    if ingredientsVM.ingredients.contains(where: {$0.id == ingredientItemData.id}){
                        // If the name you entered already exists
                        if ingredientsVM.ingredients.contains(where: {$0.nom.lowercased() == ingredientItemData.nom.lowercased()}){
                            // We get the index of the element we are working on
                            let i = ingredientsVM.ingredients.firstIndex(where: {$0.id == ingredientItemData.id})
                            // We check if the name has not changed if the ingredient has not been modified
                            if ingredientsVM.ingredients[i!].nom == ingredientItemData.nom {
                                dismiss()
                            }
                            else
                            {
                                // The name you want to modify already exists
                                showingAlertIngredientExist.toggle()
                            }
                        }
                        else {
                            // We save and save in the application
                            ingredientsVM.add(ing: ingredientItemData)
                            dismiss()
                        }
                    } else{
                        // No ID so we check if the name entered by the user already exists
                        if ingredientsVM.ingredients.contains(where: {$0.nom.lowercased() == ingredientItemData.nom.lowercased()}){
                            // The name you want to modify already exists
                            showingAlertIngredientExist.toggle()
                        }
                        else{
                            // We save and save in the application
                            ingredientsVM.add(ing: ingredientItemData)
                            dismiss()
                        }
                    }
}
                .alert(isPresented: $showingAlertIngredientExist){
                    Alert(title: Text("Ingredient already present"), message: Text("An ingredient already exists with this name !"), dismissButton: .default(Text("Ok")))
                }
            }
        }
        .navigationBarBackButtonHidden()
        .navigationBarTitleDisplayMode(.inline)
    }
}

struct IngredientDetailView_Previews: PreviewProvider {
    static var previews: some View {
        IngredientDetailView(ingredientItemData: Ingredient())
            .environmentObject(IngredientModel())
    }
}

struct IngredientListView: View {
    @Environment(\.dismiss) private var dismiss

    @State private var sheetIsPresented = false

    @EnvironmentObject var ingredientVM: IngredientModel

    func getIndex(item: Ingredient) -> Int{
        return ingredientVM.ingredients.firstIndex{(item1) -> Bool in
            return item.id == item1.id
        } ?? 0
    }

    var body: some View {
        NavigationStack{
            List{
                ForEach(ingredientVM.ingredients){ item in
                    NavigationLink{
                        IngredientDetailView(ingredientItemData: item)
                    }label: {
                        Text(item.nom)
                    }
                }
                .onDelete{ indexSet in
                    // Temporaire. Fonction à mettre dans le model
                    ingredientVM.ingredients.remove(atOffsets: indexSet)
                    ingredientVM.saveData()
                }
            }.navigationTitle("IngredientListView")
                .navigationBarTitleDisplayMode(.automatic)
            .toolbar{
                ToolbarItem(placement: .navigationBarLeading){
                    EditButton()
                }
                ToolbarItem(placement: .navigationBarTrailing){
                    Button{
                        sheetIsPresented.toggle()
                    }label: {
                        Image(systemName: "plus")
                    }
                }
            }
            .sheet(isPresented: $sheetIsPresented){
                NavigationStack{
                    IngredientDetailView(ingredientItemData: Ingredient())
                }
                .presentationDetents([.large,.medium,.fraction(0.75)])
            }
        }
    }
}

struct IngredientListView_Previews: PreviewProvider {
    static var previews: some View {
        IngredientListView()
            .environmentObject(IngredientModel())
    }
}

class IngredientModel: ObservableObject{
    @Published var ingredients : [Ingredient] = []
    let saveKey = "Ingredients"

    init(){
        loadData()
    }

    func add(ing: Ingredient){
        if ing.id == nil{
            var newIngredient = ing
            newIngredient.id = UUID().uuidString
            ingredients.append(newIngredient)
        }else{
            if let index = ingredients.firstIndex(where: {$0.id == ing.id}){
                ingredients[index] = ing
            }
        }
        saveData()
    }

    func loadData(){
        if let data = UserDefaults.standard.data(forKey: saveKey){
            if let decoded = try? JSONDecoder().decode([Ingredient].self, from: data){
                ingredients = decoded
                return
            }
        }
    }

    func saveData(){
        if let encoded = try? JSONEncoder().encode(ingredients) {
            UserDefaults.standard.set(encoded, forKey: saveKey)
        }
    }
}

class Ingredient: Identifiable, Codable{
    var id: String?
    var nom = ""
    var metric = ""

    init (){

    }

    init(id: String, nom: String, metric: String){
        self.id = id
        self.nom = nom
        self.metric = metric
    }
}

</code>```

Body:
I'm new to coding on Swift and I'm having a problem with a code. I want to verify the data entered by the user.

IngredientDetailView contains a form to add or modify an ingredient. In this view I want to control the data entered by the user. So the ingredients have a unique name.

My problem
When I modify the name of an existing ingredient with a name of another ingredient, my control does not work.

IngredientListView contains the list of existing ingredients that can be modified.

Thanks in advance for reading and helping.

struct IngredientDetailView: View {
    @Environment(\.dismiss) private var dismiss

    @State var ingredientItemData : Ingredient
    @EnvironmentObject var ingredientsVM: IngredientModel
    // To display the message that an ingredient already exists
    @State private var showingAlertIngredientExist = false
    let metrics: [String] = [
        "Unité", "kg", "g", "l", "ml"
    ]

    var body: some View {
        List{
            TextField("Ingredient name", text: $ingredientItemData.nom)
            Text("Metric").bold()
            Picker(selection: $ingredientItemData.metric, label: Text("Metric"), content: {
                ForEach(metrics, id: \.self){ item in
                    Text(item)
                }
            }).pickerStyle(.segmented)
        }
        .toolbar{
            ToolbarItem(placement: .navigationBarLeading){
                Button("Cancel"){
                    dismiss()
                }
            }
            ToolbarItem(placement: .navigationBarTrailing){
                Button("Ok"){
                    //If the id already exists
                    if ingredientsVM.ingredients.contains(where: {$0.id == ingredientItemData.id}){
                        // If the name you entered already exists
                        if ingredientsVM.ingredients.contains(where: {$0.nom.lowercased() == ingredientItemData.nom.lowercased()}){
                            // We get the index of the element we are working on
                            let i = ingredientsVM.ingredients.firstIndex(where: {$0.id == ingredientItemData.id})
                            // We check if the name has not changed if the ingredient has not been modified
                            if ingredientsVM.ingredients[i!].nom == ingredientItemData.nom {
                                dismiss()
                            }
                            else
                            {
                                // The name you want to modify already exists
                                showingAlertIngredientExist.toggle()
                            }
                        }
                        else {
                            // We save and save in the application
                            ingredientsVM.add(ing: ingredientItemData)
                            dismiss()
                        }
                    } else{
                        // No ID so we check if the name entered by the user already exists
                        if ingredientsVM.ingredients.contains(where: {$0.nom.lowercased() == ingredientItemData.nom.lowercased()}){
                            // The name you want to modify already exists
                            showingAlertIngredientExist.toggle()
                        }
                        else{
                            // We save and save in the application
                            ingredientsVM.add(ing: ingredientItemData)
                            dismiss()
                        }
                    }
}
                .alert(isPresented: $showingAlertIngredientExist){
                    Alert(title: Text("Ingredient already present"), message: Text("An ingredient already exists with this name !"), dismissButton: .default(Text("Ok")))
                }
            }
        }
        .navigationBarBackButtonHidden()
        .navigationBarTitleDisplayMode(.inline)
    }
}

struct IngredientDetailView_Previews: PreviewProvider {
    static var previews: some View {
        IngredientDetailView(ingredientItemData: Ingredient())
            .environmentObject(IngredientModel())
    }
}

struct IngredientListView: View {
    @Environment(\.dismiss) private var dismiss

    @State private var sheetIsPresented = false

    @EnvironmentObject var ingredientVM: IngredientModel

    func getIndex(item: Ingredient) -> Int{
        return ingredientVM.ingredients.firstIndex{(item1) -> Bool in
            return item.id == item1.id
        } ?? 0
    }

    var body: some View {
        NavigationStack{
            List{
                ForEach(ingredientVM.ingredients){ item in
                    NavigationLink{
                        IngredientDetailView(ingredientItemData: item)
                    }label: {
                        Text(item.nom)
                    }
                }
                .onDelete{ indexSet in
                    // Temporaire. Fonction à mettre dans le model
                    ingredientVM.ingredients.remove(atOffsets: indexSet)
                    ingredientVM.saveData()
                }
            }.navigationTitle("IngredientListView")
                .navigationBarTitleDisplayMode(.automatic)
            .toolbar{
                ToolbarItem(placement: .navigationBarLeading){
                    EditButton()
                }
                ToolbarItem(placement: .navigationBarTrailing){
                    Button{
                        sheetIsPresented.toggle()
                    }label: {
                        Image(systemName: "plus")
                    }
                }
            }
            .sheet(isPresented: $sheetIsPresented){
                NavigationStack{
                    IngredientDetailView(ingredientItemData: Ingredient())
                }
                .presentationDetents([.large,.medium,.fraction(0.75)])
            }
        }
    }
}

struct IngredientListView_Previews: PreviewProvider {
    static var previews: some View {
        IngredientListView()
            .environmentObject(IngredientModel())
    }
}

class IngredientModel: ObservableObject{
    @Published var ingredients : [Ingredient] = []
    let saveKey = "Ingredients"

    init(){
        loadData()
    }

    func add(ing: Ingredient){
        if ing.id == nil{
            var newIngredient = ing
            newIngredient.id = UUID().uuidString
            ingredients.append(newIngredient)
        }else{
            if let index = ingredients.firstIndex(where: {$0.id == ing.id}){
                ingredients[index] = ing
            }
        }
        saveData()
    }

    func loadData(){
        if let data = UserDefaults.standard.data(forKey: saveKey){
            if let decoded = try? JSONDecoder().decode([Ingredient].self, from: data){
                ingredients = decoded
                return
            }
        }
    }

    func saveData(){
        if let encoded = try? JSONEncoder().encode(ingredients) {
            UserDefaults.standard.set(encoded, forKey: saveKey)
        }
    }
}

class Ingredient: Identifiable, Codable{
    var id: String?
    var nom = ""
    var metric = ""

    init (){

    }

    init(id: String, nom: String, metric: String){
        self.id = id
        self.nom = nom
        self.metric = metric
    }
}


问:
Is there a way to find device total and free storage information?`
I need to find the device total free and used space. I used disk_space: ^0.2.1 package but I am not getting close to accurate value. Anyone can help on this topic?</p>


问:
"Error in R parallel: Error in checkForRemoteErrors(val) : 8 nodes produced errors" using DeaR package
I am currently trying to run a parallelized a Date Envelopment Analysis (DEA) by using "DeaR" package and "Snow".

The libraries that I use are:

```<code>library(deaR)
library(snow)
library(dplyr)
</code>```

I generate a random data frame as follow:

```<code>n <- 1000
df <- data.frame("DMU"=paste0("Unit_",c(1:n)),
                    "input1"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "input2"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "input3"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "input4"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "output1"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "output2"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "output3"=round(runif(n, min = 0.001, max = 1), digits = 3))
</code>```

Then, I run a standard DEA as follow:

```<code>dea <- function(x){
  model <- read_data(x,
                     dmus = 1,
                     inputs = 2:5,
                     outputs = 6:8)
  results <- model_basic (model,
                          orientation = "io",
                          rts = "vrs")
  return(results)
}

results <- dea(df)
eff <- efficiencies(results)
</code>```

Finally, I try the same but with a parallelization:

```<code>cluster <- makeCluster(16)
clusterEvalQ(cluster, library(deaR))
dea <- function(x){
  model <- read_data(x,
                     dmus = 1,
                     inputs = c(2:5),
                     outputs = c(6:8))
  results <- model_basic(model,
                         orientation = "io",
                         rts = "vrs")
  return(results)
}

results <- clusterApply(cl = cluster,x = datos, fun = dea)

stopCluster(cluster)

eff <- efficiencies(results)
</code>```

In this case, the outcome is an error:

```<code>Error in checkForRemoteErrors(val) :
  8 nodes produced errors; first error: Invalid data datadea (should be a data frame)!
</code>```

When I introduce something like " x <- as.data.frame(x)" the outcome is:

```<code>Error in checkForRemoteErrors(val) :
  8 nodes produced errors; first error: undefined columns selected
</code>```

Every time I solve the error (that shouldn't happen) a new one appears, even when the same process without parallelization is working perfectly.

What can I do? How can I make this DEA parallel?

How do I make DEA in parallel?

Body:
I am currently trying to run a parallelized a Date Envelopment Analysis (DEA) by using "DeaR" package and "Snow".

The libraries that I use are:

library(deaR)
library(snow)
library(dplyr)

I generate a random data frame as follow:

n <- 1000
df <- data.frame("DMU"=paste0("Unit_",c(1:n)),
                    "input1"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "input2"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "input3"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "input4"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "output1"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "output2"=round(runif(n, min = 0.001, max = 1), digits = 3),
                    "output3"=round(runif(n, min = 0.001, max = 1), digits = 3))

Then, I run a standard DEA as follow:

dea <- function(x){
  model <- read_data(x,
                     dmus = 1,
                     inputs = 2:5,
                     outputs = 6:8)
  results <- model_basic (model,
                          orientation = "io",
                          rts = "vrs")
  return(results)
}

results <- dea(df)
eff <- efficiencies(results)

Finally, I try the same but with a parallelization:

cluster <- makeCluster(16)
clusterEvalQ(cluster, library(deaR))
dea <- function(x){
  model <- read_data(x,
                     dmus = 1,
                     inputs = c(2:5),
                     outputs = c(6:8))
  results <- model_basic(model,
                         orientation = "io",
                         rts = "vrs")
  return(results)
}

results <- clusterApply(cl = cluster,x = datos, fun = dea)

stopCluster(cluster)

eff <- efficiencies(results)

In this case, the outcome is an error:

Error in checkForRemoteErrors(val) :
  8 nodes produced errors; first error: Invalid data datadea (should be a data frame)!

When I introduce something like " x <- as.data.frame(x)" the outcome is:

Error in checkForRemoteErrors(val) :
  8 nodes produced errors; first error: undefined columns selected

Every time I solve the error (that shouldn't happen) a new one appears, even when the same process without parallelization is working perfectly.

What can I do? How can I make this DEA parallel?

How do I make DEA in parallel?


问:
How to embeded png in the body of mail using mailr
i have a code that sends mail using rstudio
In this mail, I want to insert.png image in the body of the mail
I have no clue how to get this done

here is my script below.

library(mailR)

```<code>sender <- "***********@gmail.com"
  recipients <- c("***********@gmail.com")
  send.mail(from = sender,
            to = recipients,
            subject = "Testing",
            body =,
            smtp = list(host.name = "smtp.gmail.com", port = 465,
                        user.name = "*************@gmal.com",
                        passwd = "**************", ssl = TRUE),
            authenticate = TRUE,
            send = TRUE)
</code>```

The png image is located in my download folder

```<code>"C:/Users/Guest 1/Desktop/Aut/table.testing_1.png"
</code>```

I want the final output to look like this in the body of the mail

Thank you

Body:
i have a code that sends mail using rstudio
In this mail, I want to insert.png image in the body of the mail
I have no clue how to get this done

here is my script below.

library(mailR)

sender <- "***********@gmail.com"
  recipients <- c("***********@gmail.com")
  send.mail(from = sender,
            to = recipients,
            subject = "Testing",
            body =,
            smtp = list(host.name = "smtp.gmail.com", port = 465,
                        user.name = "*************@gmal.com",
                        passwd = "**************", ssl = TRUE),
            authenticate = TRUE,
            send = TRUE)

The png image is located in my download folder

"C:/Users/Guest 1/Desktop/Aut/table.testing_1.png"

I want the final output to look like this in the body of the mail

Thank you


问:
Removing Write Folder permissions using PowerShell
I'm pretty new to PowerShell scripting and I am trying to remove Write permissions from "Extensions" folder to prevent users from downloading new extensions but let them use the ones that they have currently installed, this is what my script looks like so far:

`

```<code>$ACL = Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("DESKTOP-ATGGG71\Dawid","Write","Deny")
$ACL.RemoveAccessRule($AccessRule)
$ACL | Set-Acl -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
(Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\').Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize
</code>```

`

and that's the output:

`

```<code>PS C:\Windows\system32> $ACL = Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("DESKTOP-ATGGG71\Dawid","Write","Deny")
$ACL.RemoveAccessRule($AccessRule)
$ACL | Set-Acl -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
(Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\').Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize
True

IdentityReference      FileSystemRights AccessControlType IsInherited                InheritanceFlags
-----------------      ---------------- ----------------- -----------                ----------------
NT AUTHORITY\SYSTEM         FullControl             Allow        True ContainerInherit, ObjectInherit
BUILTIN\Administrators      FullControl             Allow        True ContainerInherit, ObjectInherit
DESKTOP-ATGGG71\Dawid       FullControl             Allow        True ContainerInherit, ObjectInherit
</code>```

`

It is not giving me any errors but won't remove Write permissions, what would need to be changed?

Thanks

Body:
I'm pretty new to PowerShell scripting and I am trying to remove Write permissions from "Extensions" folder to prevent users from downloading new extensions but let them use the ones that they have currently installed, this is what my script looks like so far:

`

$ACL = Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("DESKTOP-ATGGG71\Dawid","Write","Deny")
$ACL.RemoveAccessRule($AccessRule)
$ACL | Set-Acl -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
(Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\').Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize

`

and that's the output:

`

PS C:\Windows\system32> $ACL = Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("DESKTOP-ATGGG71\Dawid","Write","Deny")
$ACL.RemoveAccessRule($AccessRule)
$ACL | Set-Acl -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\'
(Get-ACL -Path 'C:\Users\Dawid\AppData\Local\Microsoft\Edge\User Data\Default\Extensions\').Access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags -AutoSize
True

IdentityReference      FileSystemRights AccessControlType IsInherited                InheritanceFlags
-----------------      ---------------- ----------------- -----------                ----------------
NT AUTHORITY\SYSTEM         FullControl             Allow        True ContainerInherit, ObjectInherit
BUILTIN\Administrators      FullControl             Allow        True ContainerInherit, ObjectInherit
DESKTOP-ATGGG71\Dawid       FullControl             Allow        True ContainerInherit, ObjectInherit

`

It is not giving me any errors but won't remove Write permissions, what would need to be changed?

Thanks


问:
Sequelize migrations - Google cloud build trigger
I am currently trying to host a typescript/sequelize project in Google cloud build.
I am connecting through a unix socket and cloud sql proxy.
The app is deployed and a test running "sequelize.authenticate()" seems to be working.
Migrations to localhost seems to be working aswell.

I have written a cloud build trigger that does the following:
-builds a simple docker image
-pushes the simple docker image
-npm install
-downloads the cloud_sql_proxy
-initiates the cloud_sql_proxy

the next step would be to migrate a simple table to my gcloud database.

please check out my drawing for further details: https://excalidraw.com/#json=LnvpSjngbk7h1F0RzBgUP,HPwtVWgh-sFgrmvfU9JK0A

If i try to run "npx sequelize-cli db:migrate" gcloud gives the following message: [31mERROR:[39m connect ENOENT /cloudsql/xxxxxxx/.s.PGSQL.5432

but if i replace the command with npx sequelize-cli --version, it simply prints out the version and moves on with the rest of the trigger operations.


问:
Retrieve rows from DB if Date-Difference condition apply
I need to retrieve rows from SQL database where a time-difference condition apply.
Basically I need to retrieve rows where date difference from Now() is < x minutes.

Column datetime has this format: 2022-12-05 15:01:43

I tried

SELECT * FROM copytrade WHERE DATEDIFF(minute, datetime, GETDATE() AS DateDiff) < 10

Using this select I get error "Incorrect parameter count in the call to native function 'DATEDIFF'

Is it possible in a single SQL line to achieve this select?
Thanks


问:
Xticklabel in pyplot
If the xrange of a particular pyplot figure is [0,100], can we still give the xticklabel values between [100,200].

if yes, how can we do this

If the xrange of a particular pyplot figure is [0,100], can we still give the xticklabel values between [100,200].

if yes, how can we do this

Title: Xticklabel in pyplot


问:
How to use MPIPool inside a loop?
I want to use MPIPool inside a loop on my university cluster, but every time the code freeze at the first iteration, is there anyone knowing what happed and what should I do now?

The example codes are shown below:

```<code>import sys
import time
import emcee
import numpy as np
from schwimmbad import MPIPool
from multiprocessing import Pool

def log_prob(theta):
t = time.time() + np.random.uniform(0.005, 0.008)
while True:
if time.time() \>= t:
break
return -0.5\*np.sum(theta\*\*2)

for i in range(5):
    np.random.seed(i+10)
    initial = np.random.randn(32, 5)
    nwalkers, ndim = initial.shape
    nsteps = 100

    pool = MPIPool()
    sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, pool=pool)
    start = time.time()
    sampler.run_mcmc(initial, nsteps)
    end = time.time()
    print(end - start)
    pool.close()

mpiexec -n 16 python3 /feynman/home/dap/lceg/yl272379/test.py
</code>```

Title: How to use MPIPool inside a loop?

Body:
I want to use MPIPool inside a loop on my university cluster, but every time the code freeze at the first iteration, is there anyone knowing what happed and what should I do now?

The example codes are shown below:

import sys
import time
import emcee
import numpy as np
from schwimmbad import MPIPool
from multiprocessing import Pool

def log_prob(theta):
t = time.time() + np.random.uniform(0.005, 0.008)
while True:
if time.time() \>= t:
break
return -0.5\*np.sum(theta\*\*2)

for i in range(5):
    np.random.seed(i+10)
    initial = np.random.randn(32, 5)
    nwalkers, ndim = initial.shape
    nsteps = 100

    pool = MPIPool()
    sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, pool=pool)
    start = time.time()
    sampler.run_mcmc(initial, nsteps)
    end = time.time()
    print(end - start)
    pool.close()

mpiexec -n 16 python3 /feynman/home/dap/lceg/yl272379/test.py


问:
How to access only Vue.js components elements using a global mixin?
Trying to create a plugin with global mixin which would automatically look for specific element and change its attributes.

```<code>export default {
  // called by Vue.use(ThisPlugin)
  install(Vue, options) {
    Vue.mixin({
      created() {
         console.log($("div").length); // get rid of jQuery and global content
      },
    });
  },
};
</code>```

As this is called on every vue component I want to limit content mixin accesses with similar like el parameter in directives or like components have element querySelector (this.$el.querySelector("div")) and to replace jquery usage. Is my approach correct and how would I access only components contents in a mixin?
Want to skip directives as those would need to modify tons of existing components, rather introduce a plugin for a component.

Body:
Trying to create a plugin with global mixin which would automatically look for specific element and change its attributes.

export default {
  // called by Vue.use(ThisPlugin)
  install(Vue, options) {
    Vue.mixin({
      created() {
         console.log($("div").length); // get rid of jQuery and global content
      },
    });
  },
};

As this is called on every vue component I want to limit content mixin accesses with similar like el parameter in directives or like components have element querySelector (this.$el.querySelector("div")) and to replace jquery usage. Is my approach correct and how would I access only components contents in a mixin?
Want to skip directives as those would need to modify tons of existing components, rather introduce a plugin for a component.


问:
Why would one consider using Bellman Ford?
So, say you wanted to find the shortest path between two vertices.
I would argue this:

A.) If the graph has no negative edge weights and is represented by an adjacency list, you could run Dijkstra's algorithm either once to find a single source shortest path in O(V^2) time or run Dijkstra's algorithm on all vertices O(V^3) (both of are pretty sloppy in the case of non-complete graphs) to find all shortest paths.

B.) Graph with no negative edge weights and is in matrix form: Either use Dijkstra's to find a single source shortest path O(V^2) or run Floyd-Warshall to find all possible shortest paths O(V^3).

C.) Graph has negative edge weights and is in either list or matrix form: Run either Bellman-Ford to find the single source shortest path O(V^3) or use FW to find all shortest paths in O(V^3) time. Since their runtime is approximately the same (they will differ if the graph is in list form) you might as well just run FW and get more information for approximately the same runtime... right?

So: Is there any real-world application where one would use Bellman-Ford? The only thing I can think of is if the graph is in list form and has negative edge weights. I'm not sure of the implications this has on FW or if that list would first need to be converted into a matrix.


问:
Im trying to get the String texts from the user and print it out in Toast
enter image description here
Hi I would some assistance on printing a user input to a toast message after a click of a button

```<code>`amountEditText = findViewById( R.id.amount_edit_text );
Editable userAmountInput = amountEditText.getText();
String amountInputString =  userAmountInput.toString();
submit=findViewById( R.id.send_button );
submit.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText( MainActivity.this, ""+amountInputString, Toast.LENGTH_SHORT ).show();
    }
} );`

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

I've tried to use Editable and String object retrieve the user input in a Toast message. But it prints nothing.

Body:
enter image description here
Hi I would some assistance on printing a user input to a toast message after a click of a button

`amountEditText = findViewById( R.id.amount_edit_text );
Editable userAmountInput = amountEditText.getText();
String amountInputString =  userAmountInput.toString();
submit=findViewById( R.id.send_button );
submit.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText( MainActivity.this, ""+amountInputString, Toast.LENGTH_SHORT ).show();
    }
} );`

I've tried to use Editable and String object retrieve the user input in a Toast message. But it prints nothing.


问:
wiredtiger_kv_engine.cpp File Missing After RAID Recovery
I recently recovered RAID and everything came back. only problem is mongodb is not starting.

I tried to change db path

```<code>mongod --dbpath /home/abhi/mongo-live-db/dbnew --repair
</code>```

before that i given ownership to moved folder

```<code>chown -R mongodb:mongodb /home/abhi/mongo-live-db/dbnew
</code>```

NOT worked because i am getting error

WiredTiger error (-31803) [1670257513:986000][3349149:0x7f3078139ac0], txn-recover: Recovery failed: WT_NOTFOUND: item not found

Since it says FILE NOT FOUND, I updated locatedb and searched for file on ubuntu server

```<code>locate wiredtiger_kv_engine.cpp
</code>```

Nothing found.

Please help me to get out from this. Thanks.

Body:
I recently recovered RAID and everything came back. only problem is mongodb is not starting.

I tried to change db path

mongod --dbpath /home/abhi/mongo-live-db/dbnew --repair

before that i given ownership to moved folder

chown -R mongodb:mongodb /home/abhi/mongo-live-db/dbnew

NOT worked because i am getting error

WiredTiger error (-31803) [1670257513:986000][3349149:0x7f3078139ac0], txn-recover: Recovery failed: WT_NOTFOUND: item not found

Since it says FILE NOT FOUND, I updated locatedb and searched for file on ubuntu server

locate wiredtiger_kv_engine.cpp

Nothing found.

Please help me to get out from this. Thanks.


问:
VBA to Copy Hidden Cells and Paste as "visible"?
I have a VBA code that is taking hidden rows/cells (consider it a "template" set of cells), copying that range, and then pasting elsewhere into the sheet.

When the code pastes the cells, I want them to be visible. However, because they are copied from hidden cells, they also paste as hidden.

Is there an easy way to paste them as "visible", even when copied from a hidden range?


问:
What's better for large datasets in reinforcement learning? Dictionary, numpy or pandas?
I'm trying to implement a Chess AI with Reinforcement Learning, i'm using the Q-learn algorithm and, to keep track of the q-values that each state have, as a starting point, i implemented a dictionary of dictionaries. (in other words, to keep track of large amount of values that holds a large amount of values, i implemented a dictionary of dictionary)

This implementation worked smooth in small and dumb scenarios.
For example, having the following board, if the whites are the only ones that can move, it gets a checkmate in less than 3 minutes.
Initial testing board

I've tried to minimize the computational requeriments for each step in the q-learning algorithm, but nothing seems to work, so, as the mentioned algorithm works around the q-table itself, it's really probable that i'm not using the optimal structure.

Right now this is the method that gets/initialize the values for each state-action (the first dictionary is the state, the second the different actions (future states) that that state does).
`
def get_qdict(self, state, action):
string_state = self.stateToString(state)
string_action = self.stateToString(action)

```<code>if string_state in self.q_dict:
    if string_action in self.q_dict[string_state]:
        return self.q_dict[string_state][string_action]
    else:
        self.q_dict[string_state][string_action] = 0
        return 0
else:
    self.q_dict[string_state]={}
    self.q_dict[string_state][string_action] = 0
    return 0

self.q_dict[string_state][string_action] = 0
return 0
</code>```

`
The stateToString transform the type array position to a string

The problem comes as i try to add the black movements in the equation or i set a more complex scenario, the time needed increases exponentially, needing hours to get somewhere.

For example, for each episode in the previous scenario (the one with just the black king, and white rook and king) it takes around 0,01s.
While for each episode in the scenario where blacks can do a movement, the time needed for episode is around 0,3s.

How could i fix this? Should i implement the q-table as a numpy? Or is it better if i implement it as a pandas DataFrame
Or, is it normal that when i set the second scenario, the times augments that much?

Body:
I'm trying to implement a Chess AI with Reinforcement Learning, i'm using the Q-learn algorithm and, to keep track of the q-values that each state have, as a starting point, i implemented a dictionary of dictionaries. (in other words, to keep track of large amount of values that holds a large amount of values, i implemented a dictionary of dictionary)

This implementation worked smooth in small and dumb scenarios.
For example, having the following board, if the whites are the only ones that can move, it gets a checkmate in less than 3 minutes.
Initial testing board

I've tried to minimize the computational requeriments for each step in the q-learning algorithm, but nothing seems to work, so, as the mentioned algorithm works around the q-table itself, it's really probable that i'm not using the optimal structure.

Right now this is the method that gets/initialize the values for each state-action (the first dictionary is the state, the second the different actions (future states) that that state does).
`
def get_qdict(self, state, action):
string_state = self.stateToString(state)
string_action = self.stateToString(action)

if string_state in self.q_dict:
    if string_action in self.q_dict[string_state]:
        return self.q_dict[string_state][string_action]
    else:
        self.q_dict[string_state][string_action] = 0
        return 0
else:
    self.q_dict[string_state]={}
    self.q_dict[string_state][string_action] = 0
    return 0

self.q_dict[string_state][string_action] = 0
return 0

`
The stateToString transform the type array position to a string

The problem comes as i try to add the black movements in the equation or i set a more complex scenario, the time needed increases exponentially, needing hours to get somewhere.

For example, for each episode in the previous scenario (the one with just the black king, and white rook and king) it takes around 0,01s.
While for each episode in the scenario where blacks can do a movement, the time needed for episode is around 0,3s.

How could i fix this? Should i implement the q-table as a numpy? Or is it better if i implement it as a pandas DataFrame
Or, is it normal that when i set the second scenario, the times augments that much?


问:
Segmentation fault programming an AVL tree in C programming language
I have written a code to create an AVL tree.
Write a program that sorts the given integer values. The number of values is not known in advance. Your program will output the sorted values and the structure of the tree using given output format. (Assume for this lab study,
values are distinct). Use AVL tree in your program.
Input:
72 18 28 36 27 117 108 90 -1
Your output will be the sorted list of given numbers (In-order walk on AVL tree produce the sorted list).
18
27
28
36
72
90
108
117
Your program should also print the AVL tree in the following way (First number represents the value, second number displays the parent node and the third number shows the balance factor. B is used for balance factor, L represents left child and R represents right child).
28 (-1 B)
18 (28 L) (-1 B) 72 (28 R) (-1 B)
27 (18 R) (0 B) 36 (72 L) (0 B) 108 (72 R) (0 B) 90 (108 L) (0 B) 117 (108 R) (0 B)</p>
```<code>#include <stdio.h>
#include <stdlib.h>

struct treeNode {
    int value;
    struct treeNode* leftChild;
    struct treeNode* rightChild;
    int height;
};

int height( struct treeNode *root) {
    if(root==NULL) {
        return -1;
    }
    else {
        return root->height;
    }
}

int max(int a,int b) {
    if (a>b) {
        return a;
    }
    else {
        return b;
    }
}

struct treeNode *createNode( int value) {
    struct treeNode* root= (struct treeNode*) malloc(sizeof(struct treeNode));

    root->value=value;
    root->leftChild=NULL;
    root->rightChild=NULL;
    root->height=1;
    return root;
}

int balanceFactor(struct treeNode *root) {
    if(root==NULL) {
        return 0;
    }
    else {
        return height(root->leftChild)-height(root->rightChild);
    }
}

struct treeNode *leftRotation(struct treeNode* parent) {
    struct treeNode *child1= parent->rightChild;
    struct treeNode *child2= child1->leftChild;

    child1->leftChild=parent;
    parent->rightChild= child2;

    parent->height=max(height(parent->rightChild), height(parent->leftChild)) +1;
    child1->height=max(height(child1->rightChild), height(child1->leftChild)) +1;

    return child1;
}

struct treeNode *rightRotation(struct treeNode* child1) {
    struct treeNode *parent = child1->rightChild;
    struct treeNode *child2= parent->rightChild;

    parent->rightChild=child1;
    child1->leftChild= child2;

    parent->height=max(height(parent->rightChild), height(parent->leftChild)) +1;
    child1->height=max(height(child1->rightChild), height(child1->leftChild)) +1;

    return parent;
}

struct treeNode *RL(struct treeNode *c) {
    c->leftChild=rightRotation(c->leftChild);

    return leftRotation(c);
}

struct treeNode *LR(struct treeNode *b) {
    b->rightChild=leftRotation(b->rightChild);

    return rightRotation(b);
}

struct treeNode *insert(struct treeNode* root, int value) {
    if (root==NULL) {
        return (createNode(value));
    }
    if( value< root->value) {
        root->leftChild= insert(root->leftChild,value);
    }
    else if(value> root->value) {
        root->rightChild=insert(root->rightChild, value);
    }
    else {
        return root;
    }
    root->height=1 + max(height(root->leftChild), height(root->rightChild));

    int balanceF= balanceFactor(root);
    if(balanceF<-1 && value> root->rightChild->value) {
        return leftRotation(root);
    }
    if (balanceF<-1 && value< root->rightChild->value) {
        root->rightChild=rightRotation(root->rightChild);
         return leftRotation(root);
    }
    if(balanceF>1 && value<root->leftChild->value) {
        return rightRotation(root);
    }
    if(balanceF>1 && value<root->leftChild->value) {
        root->leftChild=leftRotation(root->leftChild);
        return rightRotation(root);
    }
    return root;
}

void inorder(struct treeNode *root) {
    if (root) {
        inorder(root->leftChild);
        printf("%d \n", root->value);
        inorder(root->rightChild);
    }
}

int treeHeight( struct treeNode *root) {
    if (root== NULL ) {
        return 0;
    }
    else{
        int leftHeight = treeHeight(root->leftChild);
        int rightHeight= treeHeight(root->rightChild);
        if (leftHeight>rightHeight) {
            return (leftHeight+1);
        }
        else {
            return (rightHeight+1);
        }
    }
}

void currentLevel (struct treeNode *root, int treeheight, struct treeNode *parent, char child ) {

    if (root != NULL) {
        if (treeheight==0) {
            if (parent !=NULL) {

                int bf=balanceFactor(root);
                printf("%d (%d %c)(%d B)", root->value, parent->value, child, bf);
            }

            else {
            printf("%d \n", root->value);
            }
        }
        else if (treeheight>0) {
            currentLevel(root->leftChild, treeheight-1, root, 'L' );
            currentLevel(root->rightChild, treeheight-1, root, 'R');

        }
    }
}

int main () {
    struct treeNode *root = NULL;
    int value;
    while(1) {
         scanf ("%d", &value);
         if(value==-1) {
            break;
         }
         root=insert(root,value);
    }

    inorder(root);
    int i;
    int height= treeHeight(root);

    for (int i=0; i<=height;i++) {
        currentLevel(root,i, NULL, ' ');
        printf("\n");
    }

return 0;
}

</code>```

Body:
I have written a code to create an AVL tree.
Write a program that sorts the given integer values. The number of values is not known in advance. Your program will output the sorted values and the structure of the tree using given output format. (Assume for this lab study,
values are distinct). Use AVL tree in your program.
Input:
72 18 28 36 27 117 108 90 -1
Your output will be the sorted list of given numbers (In-order walk on AVL tree produce the sorted list).
18
27
28
36
72
90
108
117
Your program should also print the AVL tree in the following way (First number represents the value, second number displays the parent node and the third number shows the balance factor. B is used for balance factor, L represents left child and R represents right child).
28 (-1 B)
18 (28 L) (-1 B) 72 (28 R) (-1 B)
27 (18 R) (0 B) 36 (72 L) (0 B) 108 (72 R) (0 B) 90 (108 L) (0 B) 117 (108 R) (0 B)

#include <stdio.h>
#include <stdlib.h>

struct treeNode {
    int value;
    struct treeNode* leftChild;
    struct treeNode* rightChild;
    int height;
};

int height( struct treeNode *root) {
    if(root==NULL) {
        return -1;
    }
    else {
        return root->height;
    }
}

int max(int a,int b) {
    if (a>b) {
        return a;
    }
    else {
        return b;
    }
}

struct treeNode *createNode( int value) {
    struct treeNode* root= (struct treeNode*) malloc(sizeof(struct treeNode));

    root->value=value;
    root->leftChild=NULL;
    root->rightChild=NULL;
    root->height=1;
    return root;
}

int balanceFactor(struct treeNode *root) {
    if(root==NULL) {
        return 0;
    }
    else {
        return height(root->leftChild)-height(root->rightChild);
    }
}

struct treeNode *leftRotation(struct treeNode* parent) {
    struct treeNode *child1= parent->rightChild;
    struct treeNode *child2= child1->leftChild;

    child1->leftChild=parent;
    parent->rightChild= child2;

    parent->height=max(height(parent->rightChild), height(parent->leftChild)) +1;
    child1->height=max(height(child1->rightChild), height(child1->leftChild)) +1;

    return child1;
}

struct treeNode *rightRotation(struct treeNode* child1) {
    struct treeNode *parent = child1->rightChild;
    struct treeNode *child2= parent->rightChild;

    parent->rightChild=child1;
    child1->leftChild= child2;

    parent->height=max(height(parent->rightChild), height(parent->leftChild)) +1;
    child1->height=max(height(child1->rightChild), height(child1->leftChild)) +1;

    return parent;
}

struct treeNode *RL(struct treeNode *c) {
    c->leftChild=rightRotation(c->leftChild);

    return leftRotation(c);
}

struct treeNode *LR(struct treeNode *b) {
    b->rightChild=leftRotation(b->rightChild);

    return rightRotation(b);
}

struct treeNode *insert(struct treeNode* root, int value) {
    if (root==NULL) {
        return (createNode(value));
    }
    if( value< root->value) {
        root->leftChild= insert(root->leftChild,value);
    }
    else if(value> root->value) {
        root->rightChild=insert(root->rightChild, value);
    }
    else {
        return root;
    }
    root->height=1 + max(height(root->leftChild), height(root->rightChild));

    int balanceF= balanceFactor(root);
    if(balanceF<-1 && value> root->rightChild->value) {
        return leftRotation(root);
    }
    if (balanceF<-1 && value< root->rightChild->value) {
        root->rightChild=rightRotation(root->rightChild);
         return leftRotation(root);
    }
    if(balanceF>1 && value<root->leftChild->value) {
        return rightRotation(root);
    }
    if(balanceF>1 && value<root->leftChild->value) {
        root->leftChild=leftRotation(root->leftChild);
        return rightRotation(root);
    }
    return root;
}

void inorder(struct treeNode *root) {
    if (root) {
        inorder(root->leftChild);
        printf("%d \n", root->value);
        inorder(root->rightChild);
    }
}

int treeHeight( struct treeNode *root) {
    if (root== NULL ) {
        return 0;
    }
    else{
        int leftHeight = treeHeight(root->leftChild);
        int rightHeight= treeHeight(root->rightChild);
        if (leftHeight>rightHeight) {
            return (leftHeight+1);
        }
        else {
            return (rightHeight+1);
        }
    }
}

void currentLevel (struct treeNode *root, int treeheight, struct treeNode *parent, char child ) {

    if (root != NULL) {
        if (treeheight==0) {
            if (parent !=NULL) {

                int bf=balanceFactor(root);
                printf("%d (%d %c)(%d B)", root->value, parent->value, child, bf);
            }

            else {
            printf("%d \n", root->value);
            }
        }
        else if (treeheight>0) {
            currentLevel(root->leftChild, treeheight-1, root, 'L' );
            currentLevel(root->rightChild, treeheight-1, root, 'R');

        }
    }
}

int main () {
    struct treeNode *root = NULL;
    int value;
    while(1) {
         scanf ("%d", &value);
         if(value==-1) {
            break;
         }
         root=insert(root,value);
    }

    inorder(root);
    int i;
    int height= treeHeight(root);

    for (int i=0; i<=height;i++) {
        currentLevel(root,i, NULL, ' ');
        printf("\n");
    }

return 0;
}


问:
Classification modeling with duplicated customer_id and multiple spending categories
I am trying to predict if a customer will convert to premium shoppers. The dataset looks as below:

```<code>customer_id  category  sales   conversion
1234           1        18       converted
1234           2        24       converted
1568           2        49       not converted
1568           6        12       not converted
1568           1        17       not converted
</code>```

I am trying to predict if a customer will convert or not using 1)logistic regression 2) light GBM. However, usually the customer id is unique, corresponding with multiple spending information.

For my case, I cannot pivot category because there are 30 categories, but I am afraid duplicated customer_id will impact my final model prediction.

How do I deal with the category code?

How do I deal with the duplicate of customer_id? Any good model that can handle this?

Body:
I am trying to predict if a customer will convert to premium shoppers. The dataset looks as below:

customer_id  category  sales   conversion
1234           1        18       converted
1234           2        24       converted
1568           2        49       not converted
1568           6        12       not converted
1568           1        17       not converted

I am trying to predict if a customer will convert or not using 1)logistic regression 2) light GBM. However, usually the customer id is unique, corresponding with multiple spending information.

For my case, I cannot pivot category because there are 30 categories, but I am afraid duplicated customer_id will impact my final model prediction.

How do I deal with the category code?

How do I deal with the duplicate of customer_id? Any good model that can handle this?


问:
Pandas Datatime Excel data with different formats
I've got automatic sensor data stored in .csv in inconsistent formats.
For instance:

```<code>2/29/2020 8:00:00 PM
2/29/2020 9:00:00 PM
2/29/2020 10:00:00 PM
2/29/2020 11:00:00 PM
3-1-2020 00:00
3-1-2020 01:00
3-1-2020 02:00
....
3-2-2020 00:00
3-2-2020 01:00
3-2-2020 02:00
3-2-2020 03:00
3-2-2020 04:00
</code>```

I import this data with

```<code>df = pd.read_csv(path+r'\mydata.csv', sep=';', header=0)
Time = df.iloc[:,0]
Time = pd.to_datetime(PL_Time)
</code>```

Now of course simply doing Time = pd.to_datetime(PL_Time) doesn't work as the data is in inconsistent format. Do you have any suggestions on how to effectively deal with the conversion of this dataset to the format yyyy-mm-dd hh:mm?

Body:
I've got automatic sensor data stored in .csv in inconsistent formats.
For instance:

2/29/2020 8:00:00 PM
2/29/2020 9:00:00 PM
2/29/2020 10:00:00 PM
2/29/2020 11:00:00 PM
3-1-2020 00:00
3-1-2020 01:00
3-1-2020 02:00
....
3-2-2020 00:00
3-2-2020 01:00
3-2-2020 02:00
3-2-2020 03:00
3-2-2020 04:00

I import this data with

df = pd.read_csv(path+r'\mydata.csv', sep=';', header=0)
Time = df.iloc[:,0]
Time = pd.to_datetime(PL_Time)

Now of course simply doing Time = pd.to_datetime(PL_Time) doesn't work as the data is in inconsistent format. Do you have any suggestions on how to effectively deal with the conversion of this dataset to the format yyyy-mm-dd hh:mm?


问:
Undefined reference to `HAL_TIM_Base_Init'
267 / 5.000
Resultados de tradução
Sorry for the English, but I'm trying to compile a simple code and it's giving an error of "undefined reference to `HAL_TIM_Base_Init'".

My code:

```<code>#include "main.h"
#include "rf_driver_hal_tim.h"

TIM_HandleTypeDef htim1;

static void mxtim1(void);

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void) {

    /* System initialization function */
    if (SystemInit(SYSCLK_64M, BLE_SYSCLK_NONE) != SUCCESS){
        /* Error during system clock configuration take appropriate action */
        while (1);
    }

    HAL_Init();
    IRQHandler_Config();
    MX_GPIO_Init();
    MX_USART1_UART_Init();
    mxtim1();

    while (1) {

    }
}

static void mxtim1(void){
    HAL_TIM_Base_Init(&htim1);  //error: undefined reference to `HAL_TIM_Base_Init'
}
</code>```

I already called the Timer library in the main file, but even so the error persists, I expected that if I called this library all the files that would be in it would be seen by main.c.

Body:
267 / 5.000
Resultados de tradução
Sorry for the English, but I'm trying to compile a simple code and it's giving an error of "undefined reference to `HAL_TIM_Base_Init'".

My code:

#include "main.h"
#include "rf_driver_hal_tim.h"

TIM_HandleTypeDef htim1;

static void mxtim1(void);

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void) {

    /* System initialization function */
    if (SystemInit(SYSCLK_64M, BLE_SYSCLK_NONE) != SUCCESS){
        /* Error during system clock configuration take appropriate action */
        while (1);
    }

    HAL_Init();
    IRQHandler_Config();
    MX_GPIO_Init();
    MX_USART1_UART_Init();
    mxtim1();

    while (1) {

    }
}

static void mxtim1(void){
    HAL_TIM_Base_Init(&htim1);  //error: undefined reference to `HAL_TIM_Base_Init'
}

I already called the Timer library in the main file, but even so the error persists, I expected that if I called this library all the files that would be in it would be seen by main.c.


问:
How to group by on first table row many to many relation with left join in LINQ
How can I group by complaint in this scenario?

I get all Data with left join with bellow query
now I want all the application users grouped for every related complaint row
my mean one complaint should have many users that is assigned to how should I group users by
complaint and how to loop through it in order to assign the grouped users to any ViewModel
property

public class Complaint
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string? Name { get; set; }

    [Required]
    public string? Email { get; set; }

    [Required]
    public string? Complaint{ get; set; }

    public ICollection<AsignComplaintToUsers> asignComplaintToUsers { get; set; }
}

public class ApplicationUser : IdentityUser
{

    [Column(TypeName = "nvarchar(100)")]
    public string? FirstName { get; set; }

    [PersonalData]
    [Column(TypeName = "nvarchar(100)")]
    public string? LastName { get; set; }

    public ICollection<AsignComplaintToUsers> asignComplaintToUsers { get; set; }
}

public class AsignComplaintToUsers
{
    [System.ComponentModel.DataAnnotations.Key]
    public int Id { get; set; }

    public int ComplaintId { get; set; }
    [ForeignKey("ComplaintId")]
    public Complaint complaint { get; set; }

    public string? AsignToId { get; set; }
    [ForeignKey("AsignTo")]
    public ApplicationUser applicationUser { get; set; }

    public string? AsignById { get; set; }
}

```
<pre class="lang-cs prettyprint-override"><code>var xyz =
    (from c in _context.complaints
    join AC in _context.asignComplaintToUsers
        on c.Id equals AC.ComplaintId into temp
    from t in temp.DefaultIfEmpty()

    join AppUser in _context.applicationUsers
        on t.AsignTo equals AppUser.Id into temp2
    from t2 in temp2.DefaultIfEmpty()

    select new
    {
        complaint = c,
        asugnSugessionTousers = t,
        usersWhoAsignedComplaints = t2

    })
    .ToList();
</code>```

Now I want to have list of all user assigned to each complaint, so how can I do that please?

Body:
How can I group by complaint in this scenario?

I get all Data with left join with bellow query
now I want all the application users grouped for every related complaint row
my mean one complaint should have many users that is assigned to how should I group users by
complaint and how to loop through it in order to assign the grouped users to any ViewModel
property

public class Complaint
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string? Name { get; set; }

    [Required]
    public string? Email { get; set; }

    [Required]
    public string? Complaint{ get; set; }

    public ICollection<AsignComplaintToUsers> asignComplaintToUsers { get; set; }
}

public class ApplicationUser : IdentityUser
{

    [Column(TypeName = "nvarchar(100)")]
    public string? FirstName { get; set; }

    [PersonalData]
    [Column(TypeName = "nvarchar(100)")]
    public string? LastName { get; set; }

    public ICollection<AsignComplaintToUsers> asignComplaintToUsers { get; set; }
}

public class AsignComplaintToUsers
{
    [System.ComponentModel.DataAnnotations.Key]
    public int Id { get; set; }

    public int ComplaintId { get; set; }
    [ForeignKey("ComplaintId")]
    public Complaint complaint { get; set; }

    public string? AsignToId { get; set; }
    [ForeignKey("AsignTo")]
    public ApplicationUser applicationUser { get; set; }

    public string? AsignById { get; set; }
}

var xyz =
    (from c in _context.complaints
    join AC in _context.asignComplaintToUsers
        on c.Id equals AC.ComplaintId into temp
    from t in temp.DefaultIfEmpty()

    join AppUser in _context.applicationUsers
        on t.AsignTo equals AppUser.Id into temp2
    from t2 in temp2.DefaultIfEmpty()

    select new
    {
        complaint = c,
        asugnSugessionTousers = t,
        usersWhoAsignedComplaints = t2

    })
    .ToList();

Now I want to have list of all user assigned to each complaint, so how can I do that please?


问:
background color of side menu becomes transparent on adding transform
i have addded a menu icon and side menu for mobile devices.

when menu icon is clicked side menu will be visible.

iam trying to add a ease in animation on opening side menu.
but when iam adding transform property the background of sidemenu becomes transparent,when i commented out those lines it works fine without animation.

why the background become transparent on adding transform property?

how to acheive this animation on opening side menu.

```<code>    .menu {
       transform: translateX(70%);// commenting this line and
       transition: all 0.5s ease-in;

       opacity: 0;

        pointer-events: none;

        visibility: hidden;
        display: none;
        width: 0;
        height: 0;
    }
   .menu-active {
        opacity: 1;
        pointer-events: auto;
        visibility: visible;
        transform: translateX(0);//commenting this line
        display: block;
        width: 100%;
        height: 100%;
        z-index: 9999999;
   }
</code>```

i have created two pens to show the issue?

without transform ( works fine but no animation ) https://codepen.io/sinan-m/pen/QWxzveK

with transform arises issue  https://codepen.io/sinan-m/pen/bGKORgw

Body:
i have addded a menu icon and side menu for mobile devices.

when menu icon is clicked side menu will be visible.

iam trying to add a ease in animation on opening side menu.
but when iam adding transform property the background of sidemenu becomes transparent,when i commented out those lines it works fine without animation.

why the background become transparent on adding transform property?

how to acheive this animation on opening side menu.

    .menu {
       transform: translateX(70%);// commenting this line and
       transition: all 0.5s ease-in;

       opacity: 0;

        pointer-events: none;

        visibility: hidden;
        display: none;
        width: 0;
        height: 0;
    }
   .menu-active {
        opacity: 1;
        pointer-events: auto;
        visibility: visible;
        transform: translateX(0);//commenting this line
        display: block;
        width: 100%;
        height: 100%;
        z-index: 9999999;
   }

i have created two pens to show the issue?

without transform ( works fine but no animation ) https://codepen.io/sinan-m/pen/QWxzveK

with transform arises issue  https://codepen.io/sinan-m/pen/bGKORgw


问:
Python/Django Prevent a script from being run twice
I got a big script that retrieves a lot of data via an API (Magento Invoices). This script is launched by a cron every 20 minutes. But sometimes, we need to refresh manually for getting the last invoiced orders. I have a dedicated page for this.

I would like to prevent from manual launching of the script by testing if it's already running because both API and script take a lot of ressources and time.

I tried to add a "process" model with is_active = True/False that would be tested and avoid re-launching if script is already active. At the start of the script, I switch the process status to TRUE and set it to FALSE when the script has finished.
But it seems that the 2nd instance of the script waits for the first to be finished before starting. At the end, both scripts are run because process.is_active always = False

I also tried with request.session variable, but same issue.

Spent lotsa time on this but didn't find a way to achieve my goal.
Has anyone already faced such a case ?


问:
How to Add an extra column to barplot y-axis to enhance understanding of the visualization
I want to add an extra column to my barplot to enhance the understanding of the visualization. I keep getting an axes sub-plot script error.

Let's search for players in all position with great potential under or equal to age 23 and plot players overall vs potential showing their respective playing position

```<code>trf_loan_trgt=players_df[['name', 'age', 'height_cm', 'nationality','player_positions', 'overall', 'potential', 'club_name', 'league_name', 'value_eur', 'pace', 'work_rate']]

trf_loan_trgt=trf_loan_trgt.loc[(trf_loan_trgt['potential']<=88) & (trf_loan_trgt['value_eur']<=10000000) & (trf_loan_trgt['age']<=23)]

trf_loan_trgt=trf_loan_trgt.groupby('name')[['overall','potential']].max()
trf_loan_trgt=trf_loan_trgt.sort_values('potential', ascending= False).head(20)
trf_loan_trgt.plot(kind='barh', figsize=(18,9));
plt.title('Target transfers overall and potential')
plt.xlabel('Ratings')
plt.ylabel('Player Name')
</code>```

plot output

On the player's name, I want each of the player's position to be shown somewhere in the graph.

I tried

```<code>trf_loan_trgt.plot(kind='barh', x=['players_positions', 'name'] figsize=(18,9));
</code>```

output: Axes sub-plot object is not subscriptable

```<code>trf_loan_trgt.plot(kind='barh', x='players_positions',  figsize=(18,9));
</code>```

shows plot of players_position against rating excluding the name from the plot.

Body:
I want to add an extra column to my barplot to enhance the understanding of the visualization. I keep getting an axes sub-plot script error.

Let's search for players in all position with great potential under or equal to age 23 and plot players overall vs potential showing their respective playing position

trf_loan_trgt=players_df[['name', 'age', 'height_cm', 'nationality','player_positions', 'overall', 'potential', 'club_name', 'league_name', 'value_eur', 'pace', 'work_rate']]

trf_loan_trgt=trf_loan_trgt.loc[(trf_loan_trgt['potential']<=88) & (trf_loan_trgt['value_eur']<=10000000) & (trf_loan_trgt['age']<=23)]

trf_loan_trgt=trf_loan_trgt.groupby('name')[['overall','potential']].max()
trf_loan_trgt=trf_loan_trgt.sort_values('potential', ascending= False).head(20)
trf_loan_trgt.plot(kind='barh', figsize=(18,9));
plt.title('Target transfers overall and potential')
plt.xlabel('Ratings')
plt.ylabel('Player Name')

plot output

On the player's name, I want each of the player's position to be shown somewhere in the graph.

I tried

trf_loan_trgt.plot(kind='barh', x=['players_positions', 'name'] figsize=(18,9));

output: Axes sub-plot object is not subscriptable

trf_loan_trgt.plot(kind='barh', x='players_positions',  figsize=(18,9));

shows plot of players_position against rating excluding the name from the plot.


问:
How to adapt C++ Makefile to allow for using openmpi parallelization compiling several files into 1 executable
Just a disclaimer I'm not too experienced with Make files, so forgive me if the answer is simple! I have a Make file that compiles several .cpp & .h files into .o files, and then produces an executable. I am using g++ as the compiler currently. I'd like to adapt this file to allow for openmpi multi-core computing. To note: I'm on a Windows 11 x 64 architecture, using Cygwin to build run this cpp code. I also would like this to run on MacOS systems as well.

In particular, the parallelization macros are only in 1 .cpp file, what I'd consider the 'main' file of this project (mag_spec_tracker.cpp). I don't know if that makes a difference here but thought it could be useful to let be known.

My current Makefile is below - note I added a line to try and grab the mpicc compile flags, but I am unsure on how to use them here.

```<code>IDIR = include
CXX = g++
CXXFLAGS = -I$(IDIR) -std=c++17
ODIR = obj
_DEPS = my_functions.h particle.h beam.h threevector.h threematrix.h screen.h magnet.h
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS))
_OBJ = my_functions.o particle.o beam.o mag_spec_tracker.o screen.o magnet.o
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))

$(ODIR)/%.o: %.cpp $(DEPS)
    $(CXX) -c -o $@ $< $(CXXFLAGS)

run: $(OBJ)
    $(CXX) -o $@ $^ $(CXXFLAGS)

.PHONY: clean

clean:
    rm -f $(ODIR)/*.o *~ core $(IDIR)/*~
</code>```

I have tried adding lines into the Makefile to get the mpi compile flags based on other reference I've found online, but was unsure how to adapt my current code to add these flags to allow for correct usage of openmpi. The lines I added to grab compile flags were:

```<code>MPI_COMPILE_FLAGS = $(shell mpicc --showme:compile)
MPI_LINK_FLAGS = $(shell mpicc --showme:link)
</code>```

Thank you in advance!

Update (12/6/2022)

Responding to the comment from Matzeri ('for opempi the compiler is mpicc not gcc. for c++ is mpicxx not g++'), I replaced 'g++' in my makefile with 'mpicxx' and recieved the following error:

```<code>    $ make
mpicxx -c -o obj/mag_spec_tracker.o mag_spec_tracker.cpp -Iinclude -std=c++17
mpicxx -o run obj/my_functions.o obj/particle.o obj/beam.o obj/mag_spec_tracker.o obj/screen.o obj/magnet.o -Iinclude -std=c++17
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lmpi_cxx: No such file or directory
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lmpi: No such file or directory
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lopen-rte: No such file or directory
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lopen-pal: No such file or directory
collect2.exe: error: ld returned 1 exit status
make: *** [Makefile:19: run] Error 1
</code>```

I notice that its looking for an ld executable in 'mingw64'. I tried removing that directory (previously I had installed mingw64, but switched to cygwin), and got the following error:

```<code>$ make
mpicxx -o run obj/my_functions.o obj/particle.o obj/beam.o obj/mag_spec_tracker.o obj/screen.o obj/magnet.o -Iinclude -std=c++17
--------------------------------------------------------------------------
The Open MPI wrapper compiler was unable to find the specified compiler
g++ in your PATH.

Note that this compiler was either specified at configure time or in
one of several possible environment variables.
--------------------------------------------------------------------------
make: *** [Makefile:19: run] Error 1
</code>```

I also added c:\cygwin\bin to my environment paths, and this issue still occurs. I confirmed that mpicxx is in that bin folder.

Any ideas?

Body:
Just a disclaimer I'm not too experienced with Make files, so forgive me if the answer is simple! I have a Make file that compiles several .cpp & .h files into .o files, and then produces an executable. I am using g++ as the compiler currently. I'd like to adapt this file to allow for openmpi multi-core computing. To note: I'm on a Windows 11 x 64 architecture, using Cygwin to build run this cpp code. I also would like this to run on MacOS systems as well.

In particular, the parallelization macros are only in 1 .cpp file, what I'd consider the 'main' file of this project (mag_spec_tracker.cpp). I don't know if that makes a difference here but thought it could be useful to let be known.

My current Makefile is below - note I added a line to try and grab the mpicc compile flags, but I am unsure on how to use them here.

IDIR = include
CXX = g++
CXXFLAGS = -I$(IDIR) -std=c++17
ODIR = obj
_DEPS = my_functions.h particle.h beam.h threevector.h threematrix.h screen.h magnet.h
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS))
_OBJ = my_functions.o particle.o beam.o mag_spec_tracker.o screen.o magnet.o
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))

$(ODIR)/%.o: %.cpp $(DEPS)
    $(CXX) -c -o $@ $< $(CXXFLAGS)

run: $(OBJ)
    $(CXX) -o $@ $^ $(CXXFLAGS)

.PHONY: clean

clean:
    rm -f $(ODIR)/*.o *~ core $(IDIR)/*~

I have tried adding lines into the Makefile to get the mpi compile flags based on other reference I've found online, but was unsure how to adapt my current code to add these flags to allow for correct usage of openmpi. The lines I added to grab compile flags were:

MPI_COMPILE_FLAGS = $(shell mpicc --showme:compile)
MPI_LINK_FLAGS = $(shell mpicc --showme:link)

Thank you in advance!

Update (12/6/2022)

Responding to the comment from Matzeri ('for opempi the compiler is mpicc not gcc. for c++ is mpicxx not g++'), I replaced 'g++' in my makefile with 'mpicxx' and recieved the following error:

    $ make
mpicxx -c -o obj/mag_spec_tracker.o mag_spec_tracker.cpp -Iinclude -std=c++17
mpicxx -o run obj/my_functions.o obj/particle.o obj/beam.o obj/mag_spec_tracker.o obj/screen.o obj/magnet.o -Iinclude -std=c++17
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lmpi_cxx: No such file or directory
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lmpi: No such file or directory
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lopen-rte: No such file or directory
C:/Users/Jason/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lopen-pal: No such file or directory
collect2.exe: error: ld returned 1 exit status
make: *** [Makefile:19: run] Error 1

I notice that its looking for an ld executable in 'mingw64'. I tried removing that directory (previously I had installed mingw64, but switched to cygwin), and got the following error:

$ make
mpicxx -o run obj/my_functions.o obj/particle.o obj/beam.o obj/mag_spec_tracker.o obj/screen.o obj/magnet.o -Iinclude -std=c++17
--------------------------------------------------------------------------
The Open MPI wrapper compiler was unable to find the specified compiler
g++ in your PATH.

Note that this compiler was either specified at configure time or in
one of several possible environment variables.
--------------------------------------------------------------------------
make: *** [Makefile:19: run] Error 1

I also added c:\cygwin\bin to my environment paths, and this issue still occurs. I confirmed that mpicxx is in that bin folder.

Any ideas?


问:
why i can't use document inside class in script.js file
when im trying to use the document.getElementById("") command, inside a class
method/constructor im receiving error:

```<code>
Uncaught ReferenceError ReferenceError: document is not defined
    at get element (d:\my Folders\Documents\Code\Tic-tac-toe\scripts\classes.js:13:9)
    at <anonymous> (d:\my Folders\Documents\Code\Tic-tac-toe\scripts\classes.js:129:17)
    at Module._compile (internal/modules/cjs/loader:1105:14)
    at Module._extensions..js (internal/modules/cjs/loader:1159:10)
    at Module.load (internal/modules/cjs/loader:981:32)
    at Module._load (internal/modules/cjs/loader:827:12)
    at executeUserEntryPoint (internal/modules/run_main:77:12)
    at <anonymous> (internal/main/run_main_module:17:47)

</code>```

*the script is loaded in my html file just like all the scripts that works
well, all but this one.

iv'e tried this :

```<code>class Button {
    constructor(id) {
        this._id = id;
    }

    get element() {
        return document.getElementById(this._id);
    }
}

const button3 = new Button('actionButton3');

console.log(button3.element);

</code>```

and tried also this:

```<code>class Button {
    constructor(id) {
        this._id = id;
        this._element = document.getElementById(this._id);
    }

    get element() {
        return this._element;
    }
}

const button3 = new Button('actionButton3');

console.log(button3.element);

</code>```

Body:
when im trying to use the document.getElementById("") command, inside a class
method/constructor im receiving error:

Uncaught ReferenceError ReferenceError: document is not defined
    at get element (d:\my Folders\Documents\Code\Tic-tac-toe\scripts\classes.js:13:9)
    at <anonymous> (d:\my Folders\Documents\Code\Tic-tac-toe\scripts\classes.js:129:17)
    at Module._compile (internal/modules/cjs/loader:1105:14)
    at Module._extensions..js (internal/modules/cjs/loader:1159:10)
    at Module.load (internal/modules/cjs/loader:981:32)
    at Module._load (internal/modules/cjs/loader:827:12)
    at executeUserEntryPoint (internal/modules/run_main:77:12)
    at <anonymous> (internal/main/run_main_module:17:47)

*the script is loaded in my html file just like all the scripts that works
well, all but this one.

iv'e tried this :

class Button {
    constructor(id) {
        this._id = id;
    }

    get element() {
        return document.getElementById(this._id);
    }
}

const button3 = new Button('actionButton3');

console.log(button3.element);

and tried also this:

class Button {
    constructor(id) {
        this._id = id;
        this._element = document.getElementById(this._id);
    }

    get element() {
        return this._element;
    }
}

const button3 = new Button('actionButton3');

console.log(button3.element);


问:
Promises not waiting in an synchronously implementation to chrome.storage.session.get
I am quite new to promises and I think the implementation is quite weird also ;-)

I am working on a manifest 3 extension and need to make calls to chrome.storage.session.get and chrome.storage.local.get synchronously without callback seen from the caller side.

This is because a lot of the code in the big project is used both in the extension but also on normal web pages etc and it will be a nightmare to rewrite everything and test it again.

But my implementation test with async/await does not work as expected.

I have this function

```<code>const getObjectFromSessionStorage = async function(key)
{
  return new Promise((resolve, reject) =>
  {
    try
    {
      chrome.storage.session.get(key, function(value)
      {
        if (chrome.runtime.lastError)
          reject(chrome.runtime.lastError);

        if(typeof(value[key]) === 'undefined')
          reject('undefined:' + key);

        resolve(value[key]);
      });
    }
    catch (ex)
    {
      reject(ex);
    }
  });
};
</code>```

That I try to call synchronously in this function:

```<code>const getItemPromise = (session, key) =>
{
  let returnvalue;

  (async function ()
  {
    if(session)
    {
      returnvalue = await getObjectFromSessionStorage(key);
    }
    else
    {
      returnvalue = await getObjectFromLocalStorage(key);
    }
  }());

  //debugger;

  return returnvalue;
</code>```

But it only work if I stop in the debugger just before "return returnvalue;"
If I do not it will return right away.

```<code>  chrome.storage.session.set({'TEST': 'HELLO'}, () =>
  {
          if (chrome.runtime.lastError)
              console.log(chrome.runtime.lastError);

          chrome.storage.session.get('TEST', (value) =>
          {
            if (chrome.runtime.lastError)
              console.log(chrome.runtime.lastError);

            console.log(value);
          });

          console.log(getItemPromise(true, 'TEST'));
 });
</code>```

E.g without debugger stop console.log(value); is returned last and console.log(getItemPromise(true, 'TEST')); is returned first with undefined as result. With debugger stop console.log(getItemPromise(true, 'TEST')); is returned last and with the correct content.

I do not understand why - hope somebody can help me out here

Body:
I am quite new to promises and I think the implementation is quite weird also ;-)

I am working on a manifest 3 extension and need to make calls to chrome.storage.session.get and chrome.storage.local.get synchronously without callback seen from the caller side.

This is because a lot of the code in the big project is used both in the extension but also on normal web pages etc and it will be a nightmare to rewrite everything and test it again.

But my implementation test with async/await does not work as expected.

I have this function

const getObjectFromSessionStorage = async function(key)
{
  return new Promise((resolve, reject) =>
  {
    try
    {
      chrome.storage.session.get(key, function(value)
      {
        if (chrome.runtime.lastError)
          reject(chrome.runtime.lastError);

        if(typeof(value[key]) === 'undefined')
          reject('undefined:' + key);

        resolve(value[key]);
      });
    }
    catch (ex)
    {
      reject(ex);
    }
  });
};

That I try to call synchronously in this function:

const getItemPromise = (session, key) =>
{
  let returnvalue;

  (async function ()
  {
    if(session)
    {
      returnvalue = await getObjectFromSessionStorage(key);
    }
    else
    {
      returnvalue = await getObjectFromLocalStorage(key);
    }
  }());

  //debugger;

  return returnvalue;

But it only work if I stop in the debugger just before "return returnvalue;"
If I do not it will return right away.

  chrome.storage.session.set({'TEST': 'HELLO'}, () =>
  {
          if (chrome.runtime.lastError)
              console.log(chrome.runtime.lastError);

          chrome.storage.session.get('TEST', (value) =>
          {
            if (chrome.runtime.lastError)
              console.log(chrome.runtime.lastError);

            console.log(value);
          });

          console.log(getItemPromise(true, 'TEST'));
 });

E.g without debugger stop console.log(value); is returned last and console.log(getItemPromise(true, 'TEST')); is returned first with undefined as result. With debugger stop console.log(getItemPromise(true, 'TEST')); is returned last and with the correct content.

I do not understand why - hope somebody can help me out here


问:
Metric name label have prefix is other variable in prometheus
I have a variable :

```<code>serviceName : label_values(go_info, name)
</code>```

ex: "AAA-deployment"
And metric in prometheus looklike:

```<code>metric_name{pod="AAA-deployment-XXXXX" ,name="k8s_POD_AAA-deployment-XXXX"}
</code>```

If you want filer metric have prefix is a constant word we can use:

```<code>label_values(metric_name{pod=~"CONST_PREFIX*"},name)
</code>```

But how to filter metric_name's label have prefix is other label  in prometheus?
I try

```<code>label_values(metric_name{pod=~"$serviceName*"},name)
</code>```

but it not work

Body:
I have a variable :

serviceName : label_values(go_info, name)

ex: "AAA-deployment"
And metric in prometheus looklike:

metric_name{pod="AAA-deployment-XXXXX" ,name="k8s_POD_AAA-deployment-XXXX"}

If you want filer metric have prefix is a constant word we can use:

label_values(metric_name{pod=~"CONST_PREFIX*"},name)

But how to filter metric_name's label have prefix is other label  in prometheus?
I try

label_values(metric_name{pod=~"$serviceName*"},name)

but it not work


问:
Trying to save to file private and public keys of ECDSA using mbedtls
Working on a embedded bootloader, which is trying to check ECDSA signatures for programs being loaded.  In order to accomplish this, I am trying to do the following:

First time - generate private and public keys.  Sign any application using the private key, and place the public key in the bootloader to verify.

Subsequent times - Read the private and public keys from file.  Sign any application using the private key - the public key is already in the bootloader so no need to modify anything there.

My issue is with saving the private key.  The first run of the signing software doesn't find files, so it calls to mbedtls_ecdsa_genkey, which works, and gives me two keys.  I tried writing them to files like this:

Attempt 1)  For both keys, calls to

mbedtls_ecp_point_write_binary(&ctx->MBEDTLS_PRIVATE(grp), &key->MBEDTLS_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED, &len, buf, sizeof buf);
and
mbedtls_ecp_point_write_binary(&ctx->MBEDTLS_PRIVATE(grp), &key->MBEDTLS_PRIVATE(d), MBEDTLS_ECP_PF_UNCOMPRESSED, &len, buf, sizeof buf);
and fwriting them to their own files.

On the second run, I read them both back in with
mbedtls_ecp_point_read_binary(...)

and this works, however, although the keys appear identical under the debugger, the signature fails with something crashing in mbedtls_internal_aes_encrypt.

So instead I tried, for the private key, using mbed_ecp_write_key/read_key.  The key was half the size (using MBEDTLS_ECP_DP_SEC521R1) - first method gave me keys of 133 bytes each, second made the private key 66 as I did this when writing:

len = (key->private_grp.nbits + 7)/8; // = 66
mbed_ecp_write_key(key, buf, len);

Same issue, though, crashing in mbedtls_internal_aes_encrypt.

I've been digging though mbed_ecdsa_genkey to see what else is happening which I am obviously missing, but have been unable to spot it yet.


问:
How to deselect photo selection after uploading it?
My question is, how can I deselect(or empty the selection) after finishing uploading.

Right now, image upload successfully and display at HomeView as well. But when I try just to click share button it upload again the last selection. How can I fix that?

PhotoPicker:

```<code>struct PhotoPicker: UIViewControllerRepresentable {
    @Binding var image: UIImage

    func makeUIViewController(context: Context) ->  UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.allowsEditing = true
        return picker

    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { }

    func makeCoordinator() -> Coordinator {
        return Coordinator(photoPicker: self)
    }

    final class Coordinator:NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let photoPicker: PhotoPicker
        init(photoPicker: PhotoPicker){
            self.photoPicker = photoPicker
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let image = info[.editedImage] as? UIImage {
                guard let data = image.jpegData(compressionQuality: 1), let compressedImage = UIImage(data: data) else {
                          return
                      }
                photoPicker.image = compressedImage
            } else {

            }
            picker.dismiss(animated: true)
        }
    }
}
</code>```

Function for persistImage:

```<code>         func persistUserInformation(){
        guard let uid = Auth.auth().currentUser?.uid else
        { return }

        let ref = Storage.storage().reference(withPath: uid)
        guard let data = self.image.jpegData(compressionQuality: 0.5) else { return }
        ref.putData(data, metadata: nil) { metadata, err in
            if let err = err {
                print("There was an error while putting data \(err) " )
                return
            }

            ref.downloadURL { url, error in
                if let error = error {
                    print("There was an error while downloading the data.")
                    return
                }

                print("Successfully uploaded image to storage! \(url?.absoluteString ?? "")")
                quoteVM.addAQuote(quote: self.quoteField, imageUrl: url!)

            }
        }

    }
</code>```

I was expecting to refresh the last selection, and leave it empty until another one.

Body:
My question is, how can I deselect(or empty the selection) after finishing uploading.

Right now, image upload successfully and display at HomeView as well. But when I try just to click share button it upload again the last selection. How can I fix that?

PhotoPicker:

struct PhotoPicker: UIViewControllerRepresentable {
    @Binding var image: UIImage

    func makeUIViewController(context: Context) ->  UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.allowsEditing = true
        return picker

    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { }

    func makeCoordinator() -> Coordinator {
        return Coordinator(photoPicker: self)
    }

    final class Coordinator:NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let photoPicker: PhotoPicker
        init(photoPicker: PhotoPicker){
            self.photoPicker = photoPicker
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let image = info[.editedImage] as? UIImage {
                guard let data = image.jpegData(compressionQuality: 1), let compressedImage = UIImage(data: data) else {
                          return
                      }
                photoPicker.image = compressedImage
            } else {

            }
            picker.dismiss(animated: true)
        }
    }
}

Function for persistImage:

         func persistUserInformation(){
        guard let uid = Auth.auth().currentUser?.uid else
        { return }

        let ref = Storage.storage().reference(withPath: uid)
        guard let data = self.image.jpegData(compressionQuality: 0.5) else { return }
        ref.putData(data, metadata: nil) { metadata, err in
            if let err = err {
                print("There was an error while putting data \(err) " )
                return
            }

            ref.downloadURL { url, error in
                if let error = error {
                    print("There was an error while downloading the data.")
                    return
                }

                print("Successfully uploaded image to storage! \(url?.absoluteString ?? "")")
                quoteVM.addAQuote(quote: self.quoteField, imageUrl: url!)

            }
        }

    }

I was expecting to refresh the last selection, and leave it empty until another one.


问:
Change the EXPLORER title to workspace name
Is there a way to change the word EXPLORER in the sidebar to the name of the workspace folder?

And maybe to increase the font size a little bit?

If not, is this reachable by an extension?

edit after the first comment

Yes, the workspacefolder name is the root folder in the treeview.

But for me it would be faster and easier to recognize if not the string EXPLORER stays on top, instead SK-AUTH-PRISMA.

Maybe in a little increased fontsize.