问:
Where can I see the source code for classes within my current ruby intallation?
I am new to ruby but nonetheless I have installed various versions of Ruby using RVM,
Here's the the output of my LOAD_PATH

```<code>ruby-1.9.2-p136 :001 > puts $LOAD_PATH
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/i686-linux
</code>```

Ok. So the question here is, Where within these directories can I see the source code for classes like Array, or Time ? (I know, it's an extremely n00b question, but I need to know.)

I've been needing to take a look at the source of Array for a long time.

Thanks in advance!

PS. Which class do you recommend looking at if I want to become a better ruby programmer?

答: Array is partially implemented in C for performance reasons, so for Array you would need to download the Ruby source code.</p>

Body:
I am new to ruby but nonetheless I have installed various versions of Ruby using RVM,
Here's the the output of my LOAD_PATH

ruby-1.9.2-p136 :001 > puts $LOAD_PATH
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby/1.9.1/i686-linux
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/vendor_ruby
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1
/home/jose/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/i686-linux

Ok. So the question here is, Where within these directories can I see the source code for classes like Array, or Time ? (I know, it's an extremely n00b question, but I need to know.)

I've been needing to take a look at the source of Array for a long time.

Thanks in advance!

PS. Which class do you recommend looking at if I want to become a better ruby programmer?


来源: stackexchange

问:
Json deserialization error „'W' is an invalid start of a value
I need to create a simple game in Console. I have Serializing JSON and when i want to deserialize this file i have this error:
System.Text.Json.JsonException: „'W' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.”

This is code of my classes:

```<code>public class Person
{
    public string Speciality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> people { get; set; }
    public List<Monster> monsters { get; set; }
}
</code>```

Json file

```<code>{
  "Person": [
    {
      "Speciality": "Archer",
      "PWZ": 432742,
      "Name": "Charlie",
      "Surname": "Evans",
      "Items": [
        "Bow",
        "Arrow",
      ]
    },
    {
      "Speciality": "Soldier",
      "PWZ": 432534879,
      "Name": "Harry",
      "Surname": "Thomas",
      "Items": [
        "Gun",
        "Knife",
     ]
    }
  ],
  "Monster": [
    {
      "Name": "Papua",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    },
    {
     "Name": "Geot",
      "Skills": [
        "Run",
        "Push",
      ]
    }
  ]
}
</code>```

And it's my code used to deserialize json file:

```<code>string fileName = "Local.json";
var options = new JsonSerializerOptions { AllowTrailingCommas = true };
var result = JsonSerializer.Deserialize<Root>(fileName, options);
</code>```

I haven't worked with serialize and deserialize with JSON files.
Thanks in advance.

答:
You can use the following Model structure to deserialize your JSON:

```<code>using System;
using System.Collections.Generic;
using System.Text.Json;

public class Program
{
    public static void Main()
    {
        var myString=@"{'Person':[{'Speciality':'Archer','PWZ':432742,'Name':'Charlie','Surname':'Evans','Items':['Bow','Arrow']},{'Speciality':'Soldier','PWZ':432534879,'Name':'Harry','Surname':'Thomas','Items':['Gun','Knife']}],'Monster':[{'Name':'Papua','Skills':['Jump','SlowWalk']},{'Name':'Geot','Skills':['Run','Push']}]}";
        var options = new JsonSerializerOptions { AllowTrailingCommas = true };
        var result = JsonSerializer.Deserialize<Root>(myString, options);
        foreach(var item in result.Person)
        {
            Console.WriteLine(item.Name);
        }
    }
}

public class Person
{
    public string Speciality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> Person { get; set; }
    public List<Monster> Monster { get; set; }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to create a simple game in Console. I have Serializing JSON and when i want to deserialize this file i have this error:
System.Text.Json.JsonException: „'W' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.”

This is code of my classes:

public class Person
{
    public string Speciality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> people { get; set; }
    public List<Monster> monsters { get; set; }
}

Json file

{
  "Person": [
    {
      "Speciality": "Archer",
      "PWZ": 432742,
      "Name": "Charlie",
      "Surname": "Evans",
      "Items": [
        "Bow",
        "Arrow",
      ]
    },
    {
      "Speciality": "Soldier",
      "PWZ": 432534879,
      "Name": "Harry",
      "Surname": "Thomas",
      "Items": [
        "Gun",
        "Knife",
     ]
    }
  ],
  "Monster": [
    {
      "Name": "Papua",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    },
    {
     "Name": "Geot",
      "Skills": [
        "Run",
        "Push",
      ]
    }
  ]
}

And it's my code used to deserialize json file:

string fileName = "Local.json";
var options = new JsonSerializerOptions { AllowTrailingCommas = true };
var result = JsonSerializer.Deserialize<Root>(fileName, options);

I haven't worked with serialize and deserialize with JSON files.
Thanks in advance.

Body:
You can use the following Model structure to deserialize your JSON:

using System;
using System.Collections.Generic;
using System.Text.Json;

public class Program
{
    public static void Main()
    {
        var myString=@"{'Person':[{'Speciality':'Archer','PWZ':432742,'Name':'Charlie','Surname':'Evans','Items':['Bow','Arrow']},{'Speciality':'Soldier','PWZ':432534879,'Name':'Harry','Surname':'Thomas','Items':['Gun','Knife']}],'Monster':[{'Name':'Papua','Skills':['Jump','SlowWalk']},{'Name':'Geot','Skills':['Run','Push']}]}";
        var options = new JsonSerializerOptions { AllowTrailingCommas = true };
        var result = JsonSerializer.Deserialize<Root>(myString, options);
        foreach(var item in result.Person)
        {
            Console.WriteLine(item.Name);
        }
    }
}

public class Person
{
    public string Speciality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> Person { get; set; }
    public List<Monster> Monster { get; set; }
}


问:
Create multiple null containers in R (to be used in "for loop"), using a simple code
I'm creating empty null containers, to collect values from a "for loop".
Here is an example in my code, for which I've created 6 empty containers.

```<code>cont_min  <- NULL
cont_max  <- NULL
cont_unused <-  NULL
cont_n_rec  <- NULL
cont_n_don  <- NULL
cont_loop_time <- NULL
</code>```

I need to create quite a few of these and it's using a lot of space using a line of code for each.
Is there a way to create multiple containers without having a separate line of code? Many thanks

答:
If we want to do this in a single line, an option is %<-% from zeallot

```<code>library(zeallot)
 c(cont_min, cont_max, cont_unused, cont_n_rec, cont_n_don, cont_loop_time) %<-%
    rep(list(NULL), 6)
</code>```

-checking

```<code>> cont_min
NULL
</code>```

Body:
I'm creating empty null containers, to collect values from a "for loop".
Here is an example in my code, for which I've created 6 empty containers.

cont_min  <- NULL
cont_max  <- NULL
cont_unused <-  NULL
cont_n_rec  <- NULL
cont_n_don  <- NULL
cont_loop_time <- NULL

I need to create quite a few of these and it's using a lot of space using a line of code for each.
Is there a way to create multiple containers without having a separate line of code? Many thanks

Body:
If we want to do this in a single line, an option is %<-% from zeallot

library(zeallot)
 c(cont_min, cont_max, cont_unused, cont_n_rec, cont_n_don, cont_loop_time) %<-%
    rep(list(NULL), 6)

-checking

> cont_min
NULL


问:
SMOTE_NC function in R: error in the ouput
thank you in advance for your time!

I'm having some trouble with the SMOTE_NC function in R (https://rdrr.io/github/dongyuanwu/RSBID/man/SMOTE_NC.html). Shortly, I have a dataset with continuous and categorical (binary only) variables in which I would like to use the SMOTE function to undersample the majority class and oversample the minority one, to perform a random forest afterward. Since SMOTE does not work well with categorical and continuous variables together, I used SMOTE_NC.
Hereafter is a short script to show you my problem using the iris dataset.

```<code>data(iris)

View(iris)

iris <- iris[-c(70:150),] # Shrinking the dataset to have only two species
                          # with one majority and one minority class

iris <- droplevels(iris)

levels(iris$Species) <- c(0,1)

str(iris)

iris$rng <- sample(c(0,1), replace=TRUE, size=nrow(iris)) # Adding a new random categorical
                                                          # column

iris$rng <- as.factor(iris$rng)
</code>```

I took the SMOTE_NC from the RSBID package downloaded as described here (https://rdrr.io/github/dongyuanwu/RSBID/f/README.md)

```<code>install.packages("devtools")
devtools::install_github("dongyuanwu/RSBID", build_vignettes=TRUE)

library(RSBID)
</code>```

The problem comes when I try to use the function

```<code>irisSMO <- SMOTE_NC(iris, iris$Species, 100, 5)
</code>```

And this error shows up

```<code>Error in if (outcome < 1 | outcome > ncol(data)) { :
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In Ops.factor(outcome, 1) : ‘<’ makes no sense for factor variables
2: In Ops.factor(outcome, ncol(data)) :
  ‘>’ makes no sense for factor variables
3: In if (outcome < 1 | outcome > ncol(data)) { :
  the condition has length > 1 and only the first element will be used
</code>```

I apologize that this particular part makes no sense for factor variables is translated by me since the original code is in Italian (but I don't know why) and it is è senza senso per variabili factor

Anyway, I don't know how to proceed, I looked for possible solutions on the internet but I wasn't able to find any (I read that the SMOTE_NC function should be better implemented in Python but I don't know how to write in that language and if possible I would prefer using R). The original dataset, like the one in the example, does not have any missing value and has almost 50 continuous and 50 categorical (binary) variables.

Thank you for the help, sorry for the newbie mistakes, and have a nice day!

答:
You just need the name of the variable (not the variable's values)

set.seed(519)
data(iris)
iris <- iris[-c(70:150),] # Shrinking the dataset to have only two species
# with one majority and one minority class
iris <- droplevels(iris)
levels(iris$Species) <- c(0,1)
str(iris)
#> 'data.frame':    69 obs. of  5 variables:
#>  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#>  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#>  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#>  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#>  $ Species     : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
iris$rng <- sample(c(0,1), replace=TRUE, size=nrow(iris)) # Adding a new random categorical
# column

iris$rng <- as.factor(iris$rng)

remotes::install_github("dongyuanwu/RSBID", build_vignettes=FALSE)
#> Skipping install of 'RSBID' from a github remote, the SHA1 (e640b85b) has not changed since last install.
#>   Use `force = TRUE` to force installation

library(RSBID)
#> Loading required package: FNN
#> Loading required package: clustMixType
#> Loading required package: klaR
#> Loading required package: MASS

irisSMO <- SMOTE_NC(iris, "Species", 100, 5)
#> Variables are continous and categorical, SMOTE_NC could be used.
#>   |                                                                              |                                                                      |   0%  |                                                                              |====                                                                  |   6%  |                                                                              |========                                                              |  11%  |                                                                              |============                                                          |  17%  |                                                                              |================                                                      |  22%  |                                                                              |===================                                                   |  28%  |                                                                              |=======================                                               |  33%  |                                                                              |===========================                                           |  39%  |                                                                              |===============================                                       |  44%  |                                                                              |===================================                                   |  50%  |                                                                              |=======================================                               |  56%  |                                                                              |===========================================                           |  61%  |                                                                              |===============================================                       |  67%  |                                                                              |===================================================                   |  72%  |                                                                              |======================================================                |  78%  |                                                                              |==========================================================            |  83%  |                                                                              |==============================================================        |  89%  |                                                                              |==================================================================    |  94%  |                                                                              |======================================================================| 100%
head(irisSMO)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species rng
#> 1          5.1         3.5          1.4         0.2       0   1
#> 2          4.9         3.0          1.4         0.2       0   1
#> 3          4.7         3.2          1.3         0.2       0   0
#> 4          4.6         3.1          1.5         0.2       0   0
#> 5          5.0         3.6          1.4         0.2       0   0
#> 6          5.4         3.9          1.7         0.4       0   1
```

Created on 2022-02-13 by the reprex package (v2.0.1)

Body:
thank you in advance for your time!

I'm having some trouble with the SMOTE_NC function in R (https://rdrr.io/github/dongyuanwu/RSBID/man/SMOTE_NC.html). Shortly, I have a dataset with continuous and categorical (binary only) variables in which I would like to use the SMOTE function to undersample the majority class and oversample the minority one, to perform a random forest afterward. Since SMOTE does not work well with categorical and continuous variables together, I used SMOTE_NC.
Hereafter is a short script to show you my problem using the iris dataset.

data(iris)

View(iris)

iris <- iris[-c(70:150),] # Shrinking the dataset to have only two species
                          # with one majority and one minority class

iris <- droplevels(iris)

levels(iris$Species) <- c(0,1)

str(iris)

iris$rng <- sample(c(0,1), replace=TRUE, size=nrow(iris)) # Adding a new random categorical
                                                          # column

iris$rng <- as.factor(iris$rng)

I took the SMOTE_NC from the RSBID package downloaded as described here (https://rdrr.io/github/dongyuanwu/RSBID/f/README.md)

install.packages("devtools")
devtools::install_github("dongyuanwu/RSBID", build_vignettes=TRUE)

library(RSBID)

The problem comes when I try to use the function

irisSMO <- SMOTE_NC(iris, iris$Species, 100, 5)

And this error shows up

Error in if (outcome < 1 | outcome > ncol(data)) { :
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In Ops.factor(outcome, 1) : ‘<’ makes no sense for factor variables
2: In Ops.factor(outcome, ncol(data)) :
  ‘>’ makes no sense for factor variables
3: In if (outcome < 1 | outcome > ncol(data)) { :
  the condition has length > 1 and only the first element will be used

I apologize that this particular part makes no sense for factor variables is translated by me since the original code is in Italian (but I don't know why) and it is è senza senso per variabili factor

Anyway, I don't know how to proceed, I looked for possible solutions on the internet but I wasn't able to find any (I read that the SMOTE_NC function should be better implemented in Python but I don't know how to write in that language and if possible I would prefer using R). The original dataset, like the one in the example, does not have any missing value and has almost 50 continuous and 50 categorical (binary) variables.

Thank you for the help, sorry for the newbie mistakes, and have a nice day!

Body:
You just need the name of the variable (not the variable's values)

set.seed(519)
data(iris)
iris <- iris[-c(70:150),] # Shrinking the dataset to have only two species
# with one majority and one minority class
iris <- droplevels(iris)
levels(iris$Species) <- c(0,1)
str(iris)
#> 'data.frame':    69 obs. of  5 variables:
#>  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#>  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#>  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#>  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#>  $ Species     : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...
iris$rng <- sample(c(0,1), replace=TRUE, size=nrow(iris)) # Adding a new random categorical
# column

iris$rng <- as.factor(iris$rng)

remotes::install_github("dongyuanwu/RSBID", build_vignettes=FALSE)
#> Skipping install of 'RSBID' from a github remote, the SHA1 (e640b85b) has not changed since last install.
#>   Use `force = TRUE` to force installation

library(RSBID)
#> Loading required package: FNN
#> Loading required package: clustMixType
#> Loading required package: klaR
#> Loading required package: MASS

irisSMO <- SMOTE_NC(iris, "Species", 100, 5)
#> Variables are continous and categorical, SMOTE_NC could be used.
#>   |                                                                              |                                                                      |   0%  |                                                                              |====                                                                  |   6%  |                                                                              |========                                                              |  11%  |                                                                              |============                                                          |  17%  |                                                                              |================                                                      |  22%  |                                                                              |===================                                                   |  28%  |                                                                              |=======================                                               |  33%  |                                                                              |===========================                                           |  39%  |                                                                              |===============================                                       |  44%  |                                                                              |===================================                                   |  50%  |                                                                              |=======================================                               |  56%  |                                                                              |===========================================                           |  61%  |                                                                              |===============================================                       |  67%  |                                                                              |===================================================                   |  72%  |                                                                              |======================================================                |  78%  |                                                                              |==========================================================            |  83%  |                                                                              |==============================================================        |  89%  |                                                                              |==================================================================    |  94%  |                                                                              |======================================================================| 100%
head(irisSMO)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species rng
#> 1          5.1         3.5          1.4         0.2       0   1
#> 2          4.9         3.0          1.4         0.2       0   1
#> 3          4.7         3.2          1.3         0.2       0   0
#> 4          4.6         3.1          1.5         0.2       0   0
#> 5          5.0         3.6          1.4         0.2       0   0
#> 6          5.4         3.9          1.7         0.4       0   1

Created on 2022-02-13 by the reprex package (v2.0.1)


问:
Repeated if else blocks
I have an if else construction that will sound absurd to you. Actually, I wrote a basic version of my real code so as not to prolong it. Is there anyone who can rationalize it?</p>
```<code>let someThink
let someWhere

if(someThink === true){
      // get someData in a database and after
      if( someData > 5 ){

             if(someWhere === true){
                   // get someData2 in a database and after
                  if( someData2 > 3 ){
                    console.log("Go to plans page")
                  } else {
                    console.log("Update data")
                  }
            } else {
              console.log("Go to plans page")
            }

      } else {
        console.log("Update data")
      }

} else if (someWhere === true){
    // get someData2 in a database and after
    if( someData2 > 3 ){
      console.log("Go to plans page")
    } else {
      console.log("Update data")
    }

} else {
  console.log("Go to plans page")
}
</code>```

答:
You can use some early returns after finding a case for updating the data:

```<code>let someThink
let someWhere

if (someThink) {
  // get someData in a database and after
  if (someData <= 5) {
    console.log("Update data")
    return;
  }
}

if (someWhere) {
  // get someData2 in a database and after
  if (someData2 <= 3) {
    console.log("Update data")
    return;
  }
}

console.log("Go to plans page");
</code>```

You can avoid the early returns by putting the data fetching stuff in some helper function instead of inside the decision logic:

```<code>let someThink
let someWhere

if (someThink && getSomeData() <= 5
 || someWhere && getSomeData2() <= 3
) {
  console.log("Update data")
} else {
  console.log("Go to plans page");
}
</code>```

Title: Repeated if else blocks

Body:
I have an if else construction that will sound absurd to you. Actually, I wrote a basic version of my real code so as not to prolong it. Is there anyone who can rationalize it?

let someThink
let someWhere

if(someThink === true){
      // get someData in a database and after
      if( someData > 5 ){

             if(someWhere === true){
                   // get someData2 in a database and after
                  if( someData2 > 3 ){
                    console.log("Go to plans page")
                  } else {
                    console.log("Update data")
                  }
            } else {
              console.log("Go to plans page")
            }

      } else {
        console.log("Update data")
      }

} else if (someWhere === true){
    // get someData2 in a database and after
    if( someData2 > 3 ){
      console.log("Go to plans page")
    } else {
      console.log("Update data")
    }

} else {
  console.log("Go to plans page")
}

Body:
You can use some early returns after finding a case for updating the data:

let someThink
let someWhere

if (someThink) {
  // get someData in a database and after
  if (someData <= 5) {
    console.log("Update data")
    return;
  }
}

if (someWhere) {
  // get someData2 in a database and after
  if (someData2 <= 3) {
    console.log("Update data")
    return;
  }
}

console.log("Go to plans page");

You can avoid the early returns by putting the data fetching stuff in some helper function instead of inside the decision logic:

let someThink
let someWhere

if (someThink && getSomeData() <= 5
 || someWhere && getSomeData2() <= 3
) {
  console.log("Update data")
} else {
  console.log("Go to plans page");
}


问:
Show duplicate entries removed by a set
I expect the below program to print the duplicate entries, which were removed by the Set.
But it always prints a empty array. What could be wrong?</p>
```<code>
public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

        System.out.println(strList);
    }
}```
</code>```

答:
```<code>strList.removeAll(strSet);
</code>```

This is your error line. In this line the list will remove any elements that match with the provided elements that you pass as parameter (strSet). They will be removed not only once but more than once if some element matches.

The following however will work because remove method on list, removes only the first occurance and not all matching elements of list!

```<code>public class Main
{
    public static void main(String[] args) {

        String str="HelloWorld";
        String[] strChar=str.split("");
        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        strSet.forEach(element -> {
            if (strList.contains(element)){
                strList.remove(element);
             }
        });

        System.out.println(strList);
    }
}
</code>```

Title: Show duplicate entries removed by a set

Body:
I expect the below program to print the duplicate entries, which were removed by the Set.
But it always prints a empty array. What could be wrong?

public class HelloWorld{
    public static void main(String[] args){
        String str="HelloWorld";
        String[] strChar=str.split("");

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));
        System.out.println(strList);
        System.out.println(strSet);

        //Show the duplicate entries that were removed by the set
        strList.removeAll(strSet);

        System.out.println(strList);
    }
}```

Body:
strList.removeAll(strSet);

This is your error line. In this line the list will remove any elements that match with the provided elements that you pass as parameter (strSet). They will be removed not only once but more than once if some element matches.

The following however will work because remove method on list, removes only the first occurance and not all matching elements of list!

public class Main
{
    public static void main(String[] args) {

        String str="HelloWorld";
        String[] strChar=str.split("");
        List<String> strList=new ArrayList<String>(Arrays.asList(strChar));

        //Remove the duplicates
        Set<String> strSet=new LinkedHashSet<String>(Arrays.asList(strChar));

        strSet.forEach(element -> {
            if (strList.contains(element)){
                strList.remove(element);
             }
        });

        System.out.println(strList);
    }
}


问:
Api to read device logs on iOS 8
How does this app "System Console" (made by a company named Electric Labs Ltd)  access the device logs on iOS 8?

I'm trying to do the same thing but all I get is my own app's log messages.
I'm using the api for the Apple System Logging facility following the example from this article "Accessing the iOS System Log".

I'm aware that due the sandbox subsystem in iOS 7+, my app can only see its own log messages. But I'm wondering how does the "System Console" app avoid this limitation?

答:
Fails to connect to socket, at this line. Is there an alternative available?

if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0)

ContentLicense: CC BY-SA 3.0

Title: Api to read device logs on iOS 8


问:
Use a variable outside of a function in Cypress
I want to use a value that i got from a website and stored in a variable outside of a "within" function to comapre it with another value.

```<code>cy.get('.TableCloumn_3')
    .within($tr => {
     cy.get('[class="ng-star-inserted"]').then(($span) => {

    const relRep = $span.text();

     cy.log(relRep);
      })
    })

   cy.log(relRep)

  })
</code>```

The first cy.log for relRep prints me the value but the second one does not. When I change from it from cont to var it also gives me an empty log. How can i use this value outside the function?

答:
You can initialize a variable at the top level and assign it inside the function

let foo

function bar() {
  foo = "1"
}
bar()
console.log(foo)```

Body:
I want to use a value that i got from a website and stored in a variable outside of a "within" function to comapre it with another value.

cy.get('.TableCloumn_3')
    .within($tr => {
     cy.get('[class="ng-star-inserted"]').then(($span) => {

    const relRep = $span.text();

     cy.log(relRep);
      })
    })

   cy.log(relRep)

  })

The first cy.log for relRep prints me the value but the second one does not. When I change from it from cont to var it also gives me an empty log. How can i use this value outside the function?


问:
import/export of external types failing in jest unit tests (vue2)
I'm trying to create a package which exports some types, enums, consts and interfaces I use across multiple projects.

So I created a main.ts and I put all the exports there, specify it in package.json: "main": "main.ts".

One of my exports needs some mapbox-gl types. Obviously, I don't want my package to include mapbox-gl types. So I did the following:

```<code>"peerDependencies": {
  "mapbox-gl": "^1.13.0"
},
"devDependencies": {
  "@types/mapbox-gl": "^1.13.0",
}
</code>```

Inside main.ts, I do:

import mapboxgl from "mapbox-gl";

export interface DataSourceOptions {
  shouldLoad?: boolean;
  name: string;
  map: mapboxgl.Map;
  layer: mapboxgl.Layer;
}
```
<p>I published my package, imported it in my project and it works as expected.
Until I try to test any of the components using this package.</p>
<p>Jest is throwing the following error:</p>
<blockquote>
<p>D:\path\to\project\node_modules\some-custom-package\main.ts:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import mapboxgl from "mapbox-gl";
SyntaxError: Cannot use import statement outside a module</p>
</blockquote>
<p>I tried to fix this by specifying my package in the <code>transformIgnorePatterns</code> of <code>jest.config.js</code>:</p>
```transformIgnorePatterns: [
  "<rootDir>/node_modules/(?!(@mapbox/mapbox-gl-draw" +
    "|some-custom-package" +
    ")/)",
],
```
<p>However, I'm still seeing the same error.</p>
<p>I've also tried bundling my package with <code>rollup</code>, using either <code>tsc</code> and <code>rollup-plugin-typescript2</code> plugins, because I know in <code>rollup</code> I can use <code>externals</code> to declare <code>mapbox-gl</code> as such. For some unknown reason, neither <code>tsc</code> nor <code>rollup-plugin-typescript2</code> seem to declare my interfaces, they only declare <code>const</code>s, <code>type</code>s and <code>enum</code>s (possibly related).</p>
<p>I know it looks like multiple questions into one but I'm only looking for a solution.</p>
<ul>
<li>either resolve jest's problem in importing my package (again, what I have works quite well in the actual app - it only fails in tests)</li>
<li>or find a way to keep interfaces while bundling my exports with rollup and declaring <code>mapbox-gl</code> as external</li>
</ul>
<hr />
<p>A possible workaround I see would be to circumvent the mapboxgl import in my package, by making the types I use from it dynamic:</p>
```export interface DataSourceOptions<M,L> {
  shouldLoad?: boolean;
  name: string;
  map: M;
  layer: L;
}
```

and, in my project go: options: DataSourceOptions<mapboxgl.Map, mapboxgl.Layer>, but I don't really like this solution, to be fair. It circumvents the problem, it doesn't solve it.

答:
I was able to fix it by setting:

```<code>"type": "module"
</code>```

in the the modules' package.json, together with adding it to transformIgnorePatterns in jest.config.js of the project consuming it, as shown above.

Body:
I'm trying to create a package which exports some types, enums, consts and interfaces I use across multiple projects.

So I created a main.ts and I put all the exports there, specify it in package.json: "main": "main.ts".

One of my exports needs some mapbox-gl types. Obviously, I don't want my package to include mapbox-gl types. So I did the following:

"peerDependencies": {
  "mapbox-gl": "^1.13.0"
},
"devDependencies": {
  "@types/mapbox-gl": "^1.13.0",
}

Inside main.ts, I do:

import mapboxgl from "mapbox-gl";

export interface DataSourceOptions {
  shouldLoad?: boolean;
  name: string;
  map: mapboxgl.Map;
  layer: mapboxgl.Layer;
}

I published my package, imported it in my project and it works as expected.
Until I try to test any of the components using this package.

Jest is throwing the following error:

D:\path\to\project\node_modules\some-custom-package\main.ts:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import mapboxgl from "mapbox-gl";
SyntaxError: Cannot use import statement outside a module

I tried to fix this by specifying my package in the transformIgnorePatterns of jest.config.js:

transformIgnorePatterns: [
  "<rootDir>/node_modules/(?!(@mapbox/mapbox-gl-draw" +
    "|some-custom-package" +
    ")/)",
],

However, I'm still seeing the same error.

I've also tried bundling my package with rollup, using either tsc and rollup-plugin-typescript2 plugins, because I know in rollup I can use externals to declare mapbox-gl as such. For some unknown reason, neither tsc nor rollup-plugin-typescript2 seem to declare my interfaces, they only declare consts, types and enums (possibly related).

I know it looks like multiple questions into one but I'm only looking for a solution.

either resolve jest's problem in importing my package (again, what I have works quite well in the actual app - it only fails in tests)

or find a way to keep interfaces while bundling my exports with rollup and declaring mapbox-gl as external

A possible workaround I see would be to circumvent the mapboxgl import in my package, by making the types I use from it dynamic:

export interface DataSourceOptions<M,L> {
  shouldLoad?: boolean;
  name: string;
  map: M;
  layer: L;
}

and, in my project go: options: DataSourceOptions<mapboxgl.Map, mapboxgl.Layer>, but I don't really like this solution, to be fair. It circumvents the problem, it doesn't solve it.

Body:
I was able to fix it by setting:

"type": "module"

in the the modules' package.json, together with adding it to transformIgnorePatterns in jest.config.js of the project consuming it, as shown above.


问:
Keycodes / onclick enter, show Multiple innerHTML names
When I move the 4 arrows on the keyboard, the green hover color moves over each button. I want when I press "Enter" to write the number that corresponds to each box. For example now I have "columns" and it writes 0,1,2,3,4,5,6. I want to write One Two Three etc .. Of course I use Handebars, Backcone, Lodash so I do not want to change anything in HTML (Handlebars.compile) Thank you very much ..

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;

case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
 rowButtons = rowButtons == $rows.click;

 document.getElementById('screen').innerHTML = columns;

break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');
}
});

// Click function on handlebars
// Affect href ie.  (It doesn't work on enter(13)
var ListView = BacListViewkbone.View.extend({
events: {
'click a': 'onClick'
},
render: function() {
var rawHTML = _template({ items: myList });
this.$el.html(rawHTML);
this.$items = this.$el.find('a');
return this;
},

onClick: function(e) {
var id = $(e.currentTarget).attr('patterns');
dispatcher.trigger(dispatcher.EventKeys.PATTERNS_SELECTED, myList[id]);
}
});
function init(options) {
dispatcher.register(evs);
new ListView(options).render();
}

return {
init: init
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}</code>```

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

href="#" patterns="twelve" id="twelve" onClick="twelve()">Twelve

Numbers
```

答:
If you don't want to store the translation on the elements html themselves, you'll need to have an object mapping the values to the names to be output.
Here's a minimalist example:

const numberNameMap = {
  1: 'one',
  2: 'two',
  3: 'three',
  4: 'four',
  5: 'five'
};

const select = document.querySelector('select');
const output = document.getElementById('output');

select.addEventListener('change', ({ target: { value } }) => {
  output.textContent = numberNameMap[value];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>

<div id="output"></div></code>```

Body:
When I move the 4 arrows on the keyboard, the green hover color moves over each button. I want when I press "Enter" to write the number that corresponds to each box. For example now I have "columns" and it writes 0,1,2,3,4,5,6. I want to write One Two Three etc .. Of course I use Handebars, Backcone, Lodash so I do not want to change anything in HTML (Handlebars.compile) Thank you very much ..

var columns = 0;
var rowButtons = 0;

var $rows = $('.multiple');
var liSelected;

var arrows = {
    left: 37,
    up: 38,
    right: 39,
    down: 40,
    enter: 13
    };

$(window).keydown(function(e) {
  if (Object.values(arrows).indexOf(e.which) > -1) {
    e.preventDefault();
    $('.multiple li').removeClass('selected');

switch (e.which) {
  case arrows.up:
    rowButtons = rowButtons == 0 ? $rows.length - 1 : rowButtons - 1;
    break;

  case arrows.down:
    rowButtons = rowButtons == $rows.length - 1 ? 0 : rowButtons + 1;
    break;

  case arrows.left:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == 0 ? $buttonsInRow.length - 1 : columns - 1;
    break;

  case arrows.right:
    $buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
    columns = columns == $buttonsInRow.length - 1 ? 0 : columns + 1;
    break;

case arrows.enter:
// find the column and row position:
$buttonsInRow = $('.multiple:eq(' + rowButtons + ') li');
var position = (rowButtons * 6 ) + columns + 1;
 rowButtons = rowButtons == $rows.click;

 document.getElementById('screen').innerHTML = columns;

break;
     }

    buttonSelected = $('.multiple:eq(' + rowButtons + ') li:eq(' + columns + ')');
    buttonSelected.addClass('selected');
}
});

// Click function on handlebars
// Affect href ie.  (It doesn't work on enter(13)
var ListView = BacListViewkbone.View.extend({
events: {
'click a': 'onClick'
},
render: function() {
var rawHTML = _template({ items: myList });
this.$el.html(rawHTML);
this.$items = this.$el.find('a');
return this;
},

onClick: function(e) {
var id = $(e.currentTarget).attr('patterns');
dispatcher.trigger(dispatcher.EventKeys.PATTERNS_SELECTED, myList[id]);
}
});
function init(options) {
dispatcher.register(evs);
new ListView(options).render();
}

return {
init: init
}

li.selected {
  background: green;
}

.multiple, .allRows li{
    text-align:center;
    position:relative;
    display: flex;
    flex-wrap: nowrap;
}

.allRows a {
  text-decoration:none;
  padding: 3px;
  border: 1px solid #555;
  color: #222;
  margin: 0px;
  text-align: center;
  font-size:20px;

}

#screen {
  background:#222;
  color:#ddd;
  position:absolute;
  top: 100px;
  padding:30px 150px;
}

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Twelve

Numbers

Body:
If you don't want to store the translation on the elements html themselves, you'll need to have an object mapping the values to the names to be output.
Here's a minimalist example:

const numberNameMap = {
  1: 'one',
  2: 'two',
  3: 'three',
  4: 'four',
  5: 'five'
};

const select = document.querySelector('select');
const output = document.getElementById('output');

select.addEventListener('change', ({ target: { value } }) => {
  output.textContent = numberNameMap[value];
});

<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>

<div id="output"></div>


答:
The strSet contains ['H', 'e', 'l', 'o', 'W', 'r', 'd'] that corresponding all of items in the strList (once of each item) so when you call strList.removeAll(strSet); all of items in the list will be removed.
You can write the following code to find duplicate characters.

```<code>String str="HelloWorld";
String[] split = str.split("");
Map<String, Integer> charRepeat = new HashMap<>();
for (String c : split) {
  charRepeat.put(c, charRepeat.containsKey(c) ? charRepeat.get(c) + 1 : 1);
}
charRepeat.entrySet().stream()
        .filter(entry -> entry.getValue() > 1)
        .forEach(entry -> System.out.println(entry.getKey()));
</code>```

Title: Show duplicate entries removed by a set

Body:
The strSet contains ['H', 'e', 'l', 'o', 'W', 'r', 'd'] that corresponding all of items in the strList (once of each item) so when you call strList.removeAll(strSet); all of items in the list will be removed.
You can write the following code to find duplicate characters.

String str="HelloWorld";
String[] split = str.split("");
Map<String, Integer> charRepeat = new HashMap<>();
for (String c : split) {
  charRepeat.put(c, charRepeat.containsKey(c) ? charRepeat.get(c) + 1 : 1);
}
charRepeat.entrySet().stream()
        .filter(entry -> entry.getValue() > 1)
        .forEach(entry -> System.out.println(entry.getKey()));


问:
How to make a list view widget out of a firestore array
I am trying to display my Cart data from firestore into a listview widget but to do so, I need the 'Cart' array's length.

How do I build a listview on my app based on the data from the 'Cart' collection?

```<code>child: StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('Users')
        .doc(user.uid)
        .collection('Cart')
        .snapshots(),
    builder: (context, AsyncSnapshot snapshot) {
      if (!snapshot.hasData)
        return Center(child: CircularProgressIndicator());
      else
        return Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ListView.separated(
                  shrinkWrap: true,
                  itemBuilder: (context, index) => Cartproductcard(
                        cartItem: snapshot.data[index],
                      ),
                  separatorBuilder: (context, _) =>
                      SizedBox(width: 12),
                  itemCount: snapshot.data
                      .length()
              ),
</code>```

This is what I am am left with so far, when I tried to run it I got the error:

"NoSuchMethodError (NoSuchMethodError: Class '_JsonQuerySnapshot' has no instance method 'length'.
Receiver: Instance of '_JsonQuerySnapshot'
Tried calling: length())"

答:
As far as I can tell from your screenshots Carts is not a subcollection under the user's document, but an array field inside the user's document.

So this code doesn't find any documents (since the Carts collection doesn't exist):

```<code>stream: FirebaseFirestore.instance
    .collection('Users')
    .doc(user.uid)
    .collection('Cart')
</code>```

You'll instead need to:

Read the FirebaseFirestore.instance.collection('Users').doc(user.uid).snapshots()

Get the Cart array from that document.

Loop over the items in that array.

Construct the widget(s) for each item from the array.

Body:
I am trying to display my Cart data from firestore into a listview widget but to do so, I need the 'Cart' array's length.

How do I build a listview on my app based on the data from the 'Cart' collection?

child: StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('Users')
        .doc(user.uid)
        .collection('Cart')
        .snapshots(),
    builder: (context, AsyncSnapshot snapshot) {
      if (!snapshot.hasData)
        return Center(child: CircularProgressIndicator());
      else
        return Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ListView.separated(
                  shrinkWrap: true,
                  itemBuilder: (context, index) => Cartproductcard(
                        cartItem: snapshot.data[index],
                      ),
                  separatorBuilder: (context, _) =>
                      SizedBox(width: 12),
                  itemCount: snapshot.data
                      .length()
              ),

This is what I am am left with so far, when I tried to run it I got the error:

"NoSuchMethodError (NoSuchMethodError: Class '_JsonQuerySnapshot' has no instance method 'length'.
Receiver: Instance of '_JsonQuerySnapshot'
Tried calling: length())"

Body:
As far as I can tell from your screenshots Carts is not a subcollection under the user's document, but an array field inside the user's document.

So this code doesn't find any documents (since the Carts collection doesn't exist):

stream: FirebaseFirestore.instance
    .collection('Users')
    .doc(user.uid)
    .collection('Cart')

You'll instead need to:

Read the FirebaseFirestore.instance.collection('Users').doc(user.uid).snapshots()

Get the Cart array from that document.

Loop over the items in that array.

Construct the widget(s) for each item from the array.


问:
How to solve could not find or load main class error with spring boot?
I created a Maven project for Spring Boot. I have a lot of Spring dependencies and one main class:

```<code>package com.vastserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyArtifactApplication {

    public static void main(String[] args) {

//      SpringApplication.run(MyArtifactApplication.class, args);
        System.out.println("hello!");
    }

}
</code>```

The folder structure of src directory is:

```<code>.
└── main
    ├── java
    │   └── com
    │       └── vastserver
    │           └── MyArtifactApplication.java
    └── resources
        └── application.properties
</code>```

In my pom.xml I use maven-assembly-plugin in order to build my project in a standalone .jar file. Even though I triple checked that the directory structure and main class file appear correctly in the pom.xml I keep getting the error: Error: Could not find or load main class com.vastserver.MyArtifactApplication when I run mvn package and then java -cp target/vast-ad-server-artifactId-1.0-SNAPSHOT-jar-with-dependencies.jar com.vastserver.MyArtifactApplication or mvn exec:exec. The main class does work if I run it from Intellij so I know the code is not the problem but rather Maven build settings. I lost at where my problem could be.

My pom.xml looks as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <maven.compiler.release>11</maven.compiler.release>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <mainClass>com.vastserver.MyArtifactApplication</mainClass>
        <descriptorRef>jar-with-dependencies</descriptorRef>
        <targetSnapshot>target/vast-ad-server-artifactId-1.0-SNAPSHOT</targetSnapshot>
        <targetWithDependencies>${targetSnapshot}-${descriptorRef}.jar</targetWithDependencies>
    </properties>

    <groupId>com.vastserver</groupId>
    <artifactId>vast-ad-server-artifactId</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>${mainClass}</mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>${descriptorRef}</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <executable>java</executable>
                    <arguments>
                        <argument>-cp</argument>
                        <argument>${targetWithDependencies}</argument>
                        <argument>${mainClass}</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
Your source file is missing from classpath. For me it happened when I restarted STS.

Go to Run -->Run Configurations- classpath , in user entries add your project.

Go to source tab of Run configurations and add workspace folder and select your src file where your main method class is there.
Click on apply and execute. It will work.

Body:
I created a Maven project for Spring Boot. I have a lot of Spring dependencies and one main class:

package com.vastserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyArtifactApplication {

    public static void main(String[] args) {

//      SpringApplication.run(MyArtifactApplication.class, args);
        System.out.println("hello!");
    }

}

The folder structure of src directory is:

.
└── main
    ├── java
    │   └── com
    │       └── vastserver
    │           └── MyArtifactApplication.java
    └── resources
        └── application.properties

In my pom.xml I use maven-assembly-plugin in order to build my project in a standalone .jar file. Even though I triple checked that the directory structure and main class file appear correctly in the pom.xml I keep getting the error: Error: Could not find or load main class com.vastserver.MyArtifactApplication when I run mvn package and then java -cp target/vast-ad-server-artifactId-1.0-SNAPSHOT-jar-with-dependencies.jar com.vastserver.MyArtifactApplication or mvn exec:exec. The main class does work if I run it from Intellij so I know the code is not the problem but rather Maven build settings. I lost at where my problem could be.

My pom.xml looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.release>11</maven.compiler.release>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <mainClass>com.vastserver.MyArtifactApplication</mainClass>
        <descriptorRef>jar-with-dependencies</descriptorRef>
        <targetSnapshot>target/vast-ad-server-artifactId-1.0-SNAPSHOT</targetSnapshot>
        <targetWithDependencies>${targetSnapshot}-${descriptorRef}.jar</targetWithDependencies>
    </properties>

    <groupId>com.vastserver</groupId>
    <artifactId>vast-ad-server-artifactId</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>${mainClass}</mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>${descriptorRef}</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <executable>java</executable>
                    <arguments>
                        <argument>-cp</argument>
                        <argument>${targetWithDependencies}</argument>
                        <argument>${mainClass}</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


问:
linq query to xml with variable having clause
Trying to create linq query from following xml.

```<code><root>
  <mileage value="100">
  </mileage>
  <mileage value="75">
  </mileage>
  <mileage value="60">
  </mileage>
   <mileage value="50">
  </mileage>
</root>
</code>```

The output needs to iterate xml tree getting all mileage values in mileage node and count each total when greater than or equal to 50, greater than or equal to 75 and greater than or equal to 100. So the output would be:

```<code><root>
      <mileage value="100" count="1"/>
      <mileage value="75" count="2"/>
      <mileage value="50" count="4"/>
</root>
</code>```

Not sure where to begin

答:
Here's a piece of code that does exactly what you want. You should add error handling and consider the cases where not all the attributes are present or they are not what you expect (mileage value is not an int for example).</p>

```<code>    static void Main(string[] args)
    {
        XElement result = new XElement("root");
        int[] groupValues = { 100, 75, 50 };

        string xml = "<root><mileage value=\"100\"></mileage><mileage value=\"75\"></mileage><mileage value=\"60\"></mileage><mileage value=\"50\"></mileage></root>";
        XElement element = XElement.Parse(xml);

        foreach (int groupValue in groupValues)
        {
            var newGroup = new XElement("mileage");
            newGroup.Add(new XAttribute("value", groupValue));
            newGroup.Add(new XAttribute("count", element.Elements("mileage").Count(m => int.Parse(m.Attribute("value").Value) >= groupValue)));

            result.Add(newGroup);
        }

        Console.WriteLine(result.ToString());
        Console.ReadKey();
    }
</code>```

Body:
Trying to create linq query from following xml.

<root>
  <mileage value="100">
  </mileage>
  <mileage value="75">
  </mileage>
  <mileage value="60">
  </mileage>
   <mileage value="50">
  </mileage>
</root>

The output needs to iterate xml tree getting all mileage values in mileage node and count each total when greater than or equal to 50, greater than or equal to 75 and greater than or equal to 100. So the output would be:

<root>
      <mileage value="100" count="1"/>
      <mileage value="75" count="2"/>
      <mileage value="50" count="4"/>
</root>

Not sure where to begin

Body:
Here's a piece of code that does exactly what you want. You should add error handling and consider the cases where not all the attributes are present or they are not what you expect (mileage value is not an int for example).

    static void Main(string[] args)
    {
        XElement result = new XElement("root");
        int[] groupValues = { 100, 75, 50 };

        string xml = "<root><mileage value=\"100\"></mileage><mileage value=\"75\"></mileage><mileage value=\"60\"></mileage><mileage value=\"50\"></mileage></root>";
        XElement element = XElement.Parse(xml);

        foreach (int groupValue in groupValues)
        {
            var newGroup = new XElement("mileage");
            newGroup.Add(new XAttribute("value", groupValue));
            newGroup.Add(new XAttribute("count", element.Elements("mileage").Count(m => int.Parse(m.Attribute("value").Value) >= groupValue)));

            result.Add(newGroup);
        }

        Console.WriteLine(result.ToString());
        Console.ReadKey();
    }


问:
How to Generate SCRAM-SHA-256 to Create Postgres 13 User
I want to create a Postgres user with the CREATE USER command and an already hashed digest for the password.  After much searching, I thought it was only possible with MD5 until I found this link.  I've verified that works like so:

```<code>CREATE USER test_user WITH LOGIN PASSWORD 'SCRAM-SHA-256$4096:H45+UIZiJUcEXrB9SHlv5Q==$I0mc87UotsrnezRKv9Ijqn/zjWMGPVdy1zHPARAGfVs=:nSjwT9LGDmAsMo+GqbmC2X/9LMgowTQBjUQsl45gZzA=';
</code>```

I can then log into that user with the password, which the article doesn't necessarily say but it's "postgres".  Now that I know it's possible, how using .NET 5 can I generate a scram-sha-256 digest that Postgres 13 will accept?  I've seen other Postgres articles using the outdated MD5 hash where the username is concatenated with the password before hashing.  Does that need to happen with the new scram-sha-256 as well?  I couldn't find much information on this topic anywhere.

答:
Someone built a Go tool to do this:

https://github.com/supercaracal/scram-sha-256

Here's a python 3 port based on that Go project:

```<code>from base64 import standard_b64encode
from hashlib import pbkdf2_hmac, sha256
from os import urandom
import hmac
import sys

salt_size = 16
digest_len = 32
iterations = 4096

def b64enc(b: bytes) -> str:
    return standard_b64encode(b).decode('utf8')

def pg_scram_sha256(passwd: str) -> str:
    salt = urandom(salt_size)
    digest_key = pbkdf2_hmac('sha256', passwd.encode('utf8'), salt, iterations,
                             digest_len)
    client_key = hmac.digest(digest_key, 'Client Key'.encode('utf8'), 'sha256')
    stored_key = sha256(client_key).digest()
    server_key = hmac.digest(digest_key, 'Server Key'.encode('utf8'), 'sha256')
    return (
        f'SCRAM-SHA-256${iterations}:{b64enc(salt)}'
        f'${b64enc(stored_key)}:{b64enc(server_key)}'
    )

def print_usage():
    print("Usage: provide single password argument to encrypt")
    sys.exit(1)

def main():
    args = sys.argv[1:]

    if args and len(args) > 1:
        print_usage()

    if args:
        passwd = args[0]
    else:
        passwd = sys.stdin.read().strip()

    if not passwd:
        print_usage()

    print(pg_scram_sha256(passwd))

if __name__ == "__main__":
    main()

</code>```

NOTE: Passing passwords directly on the command line can leak secrets into shell history, make secrets visible in process output to other users on the system, etc. If you are using this tool to generate real password hashes, take care to protect it from such leakage (e.g. write the plain text password to a text file with secure permissions and redirect it to the script's input using python scram256.py < secret-password.txt). Also take care to use non-reused randomly generated passwords of sufficient length and other best practices that are beyond the scope of this question/answer.

Body:
I want to create a Postgres user with the CREATE USER command and an already hashed digest for the password.  After much searching, I thought it was only possible with MD5 until I found this link.  I've verified that works like so:

CREATE USER test_user WITH LOGIN PASSWORD 'SCRAM-SHA-256$4096:H45+UIZiJUcEXrB9SHlv5Q==$I0mc87UotsrnezRKv9Ijqn/zjWMGPVdy1zHPARAGfVs=:nSjwT9LGDmAsMo+GqbmC2X/9LMgowTQBjUQsl45gZzA=';

I can then log into that user with the password, which the article doesn't necessarily say but it's "postgres".  Now that I know it's possible, how using .NET 5 can I generate a scram-sha-256 digest that Postgres 13 will accept?  I've seen other Postgres articles using the outdated MD5 hash where the username is concatenated with the password before hashing.  Does that need to happen with the new scram-sha-256 as well?  I couldn't find much information on this topic anywhere.

Body:
Someone built a Go tool to do this:

https://github.com/supercaracal/scram-sha-256

Here's a python 3 port based on that Go project:

from base64 import standard_b64encode
from hashlib import pbkdf2_hmac, sha256
from os import urandom
import hmac
import sys

salt_size = 16
digest_len = 32
iterations = 4096

def b64enc(b: bytes) -> str:
    return standard_b64encode(b).decode('utf8')

def pg_scram_sha256(passwd: str) -> str:
    salt = urandom(salt_size)
    digest_key = pbkdf2_hmac('sha256', passwd.encode('utf8'), salt, iterations,
                             digest_len)
    client_key = hmac.digest(digest_key, 'Client Key'.encode('utf8'), 'sha256')
    stored_key = sha256(client_key).digest()
    server_key = hmac.digest(digest_key, 'Server Key'.encode('utf8'), 'sha256')
    return (
        f'SCRAM-SHA-256${iterations}:{b64enc(salt)}'
        f'${b64enc(stored_key)}:{b64enc(server_key)}'
    )

def print_usage():
    print("Usage: provide single password argument to encrypt")
    sys.exit(1)

def main():
    args = sys.argv[1:]

    if args and len(args) > 1:
        print_usage()

    if args:
        passwd = args[0]
    else:
        passwd = sys.stdin.read().strip()

    if not passwd:
        print_usage()

    print(pg_scram_sha256(passwd))

if __name__ == "__main__":
    main()

NOTE: Passing passwords directly on the command line can leak secrets into shell history, make secrets visible in process output to other users on the system, etc. If you are using this tool to generate real password hashes, take care to protect it from such leakage (e.g. write the plain text password to a text file with secure permissions and redirect it to the script's input using python scram256.py < secret-password.txt). Also take care to use non-reused randomly generated passwords of sufficient length and other best practices that are beyond the scope of this question/answer.


问:
Why can't this be local?
This is a dummy variant of a setup I'm running. The Launcher function does not seem to see the GetLevel. At least the first print is seen but the second isn't. So the function never starts. Is that because the code comes after the place it is launched it in the code, and at the point Launcher executes it doesn't exist yet? When I remove the local tag it works. So global functions can be "seen" from anywhere in the script, but local ones only from later in the code?
I'm trying to find out which functions I can make local, as they are all currently global. Is there even a benefit to this - is there a difference between a function that's local to the entire script and one that's not local?</p>
```<code>local UseLevel = true
local Limit = 0

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end

local function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end
</code>```

答:
Is there even a benefit to this - is there a difference between a function that's local to the entire script and one that's not local?

The benefit of using locals is twofold:

First, locals are usually faster, as they simply use registers in Lua's virtual machine whereas globals are entries in the global table (which is effectively a hash map). Calling a global function requires first indexing the hash map.

Second, locals help improve code quality, as they are only visible in their local scope (say, a file, or even within an if-branch, a loop or the like). Putting everything in the global scope is known as "global pollution" and frowned upon. It also slows down global access as it bloats the global table. Note that Lua allows changing the environment using _ENV (or setfenv in older versions), so you can sometimes save yourself both the local keyword and forward declarations by doing so without polluting the global environment. Usually you shouldn't change environments though.

Globals are often used to expose interfaces as pointed out by Nicol Bolas. You can alternatively use return my_api_table at the end of your files for this; the API table can then be "imported" using local my_api_table = require(relative_path).

Is that because the code comes after the place it is launched it in the code, and at the point Launcher executes it doesn't exist yet?

Yes. You can fix this using a "forward local declaration" of GetLevel:

local UseLevel = true
local Limit = 0
local GetLevel -- "forward declaration" for Launcher

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end

-- This is the same as GetLevel = function() ... end and thus does not set a global variable
-- but instead assigns to the previously declared local variable GetLevel
function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end
```
<p>Simply putting the <code>Launcher</code> function below <code>GetLevel</code> also works:</p>
<pre class="lang-lua prettyprint-override"><code>local UseLevel = true
local Limit = 0

local function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end
</code>```

Title: Why can't this be local?

Body:
This is a dummy variant of a setup I'm running. The Launcher function does not seem to see the GetLevel. At least the first print is seen but the second isn't. So the function never starts. Is that because the code comes after the place it is launched it in the code, and at the point Launcher executes it doesn't exist yet? When I remove the local tag it works. So global functions can be "seen" from anywhere in the script, but local ones only from later in the code?
I'm trying to find out which functions I can make local, as they are all currently global. Is there even a benefit to this - is there a difference between a function that's local to the entire script and one that's not local?

local UseLevel = true
local Limit = 0

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end

local function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end

Body:
Is there even a benefit to this - is there a difference between a function that's local to the entire script and one that's not local?

The benefit of using locals is twofold:

First, locals are usually faster, as they simply use registers in Lua's virtual machine whereas globals are entries in the global table (which is effectively a hash map). Calling a global function requires first indexing the hash map.

Second, locals help improve code quality, as they are only visible in their local scope (say, a file, or even within an if-branch, a loop or the like). Putting everything in the global scope is known as "global pollution" and frowned upon. It also slows down global access as it bloats the global table. Note that Lua allows changing the environment using _ENV (or setfenv in older versions), so you can sometimes save yourself both the local keyword and forward declarations by doing so without polluting the global environment. Usually you shouldn't change environments though.

Globals are often used to expose interfaces as pointed out by Nicol Bolas. You can alternatively use return my_api_table at the end of your files for this; the API table can then be "imported" using local my_api_table = require(relative_path).

Is that because the code comes after the place it is launched it in the code, and at the point Launcher executes it doesn't exist yet?

Yes. You can fix this using a "forward local declaration" of GetLevel:

local UseLevel = true
local Limit = 0
local GetLevel -- "forward declaration" for Launcher

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end

-- This is the same as GetLevel = function() ... end and thus does not set a global variable
-- but instead assigns to the previously declared local variable GetLevel
function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end

Simply putting the Launcher function below GetLevel also works:

local UseLevel = true
local Limit = 0

local function GetLevel()
  print("GetLevel was launched")
  if UseLevel then
    Limit = 4
  else
    Limit = 5
  end
end

local function Launcher()
  print("trying to launch GetLevel now")
  GetLevel()
end


问:
Dynamic time sleep until new minute starts with HH:MM:01 second
I have a python code which usually runs within 20 to 48 seconds.

Currently I am using time.sleep(10) after the code + with while true & Try to run the same code after 10 second.

My objective is to use time.sleep(dynamic) so that multiple iteration of my code in same time minute stamp(within same minute)can be stopped to remove duplication of data values.

For example :

```<code>##Let say Code runs at 12:30:01 pm

while True:
    try:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        start = '11:45:01'
        end = '18:02:00'
        if current_time > start and current_time < end:while True:
            Import Code1  ## run first program file
            Import Code1  ## run second program file
            Time.sleep(3)
        else:
            print("out of time")
            time.sleep(3)
    except Exception as e:
        print(e)
        time.sleep(3)
        continue
    continue
</code>```

Now if code finishes at 12:30:50 pm then time.sleep(remianing second) should be = 10.
if code finishes at 12:30:57 pm then time.sleep(remianing second) should be = 3.
and if code finishes at 12:30:40 pm then time.sleep(remianing second) should be = 20.
and so on…

Restart next iteration at 12:31:01 second (or after).

答:
You can sleep the necessary amount of remaining time up to a minute by marking the time when the work starts and finishes, e.g.

```<code>import time
import random

while True:
    start_time = time.time()
    time.sleep(random.randint(2,5))  # do some work
    worked_time = time.time() - start_time
    print("worked for", worked_time)
    wait_to_align = 60.0 - worked_time % 60.0
    print(f"sleep {wait_to_align} to align to a minute")
    time.sleep(wait_to_align)
</code>```

produces

```<code>worked for 3.002328634262085
sleep 56.997671365737915 to align to a minute
worked for 5.003056764602661
sleep 54.99694323539734 to align to a minute
...
</code>```

Body:
I have a python code which usually runs within 20 to 48 seconds.

Currently I am using time.sleep(10) after the code + with while true & Try to run the same code after 10 second.

My objective is to use time.sleep(dynamic) so that multiple iteration of my code in same time minute stamp(within same minute)can be stopped to remove duplication of data values.

For example :

##Let say Code runs at 12:30:01 pm

while True:
    try:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        start = '11:45:01'
        end = '18:02:00'
        if current_time > start and current_time < end:while True:
            Import Code1  ## run first program file
            Import Code1  ## run second program file
            Time.sleep(3)
        else:
            print("out of time")
            time.sleep(3)
    except Exception as e:
        print(e)
        time.sleep(3)
        continue
    continue

Now if code finishes at 12:30:50 pm then time.sleep(remianing second) should be = 10.
if code finishes at 12:30:57 pm then time.sleep(remianing second) should be = 3.
and if code finishes at 12:30:40 pm then time.sleep(remianing second) should be = 20.
and so on…

Restart next iteration at 12:31:01 second (or after).

Body:
You can sleep the necessary amount of remaining time up to a minute by marking the time when the work starts and finishes, e.g.

import time
import random

while True:
    start_time = time.time()
    time.sleep(random.randint(2,5))  # do some work
    worked_time = time.time() - start_time
    print("worked for", worked_time)
    wait_to_align = 60.0 - worked_time % 60.0
    print(f"sleep {wait_to_align} to align to a minute")
    time.sleep(wait_to_align)

produces

worked for 3.002328634262085
sleep 56.997671365737915 to align to a minute
worked for 5.003056764602661
sleep 54.99694323539734 to align to a minute
...


问:
Trouble drawing multiple object with OpenGL
I'm trying to render multiple objects, but only the first object specified is rendering. I have a series of vertices arrays with their corresponding indices in a separate array.  According to everything I've read, I simply allot 2 VBOs per object I'm drawing -- one VBO for vertices, one for indices.  I generate the buffers and bind them to their respective VAO.  When rendering, I then need to have individual draw calls for each object.

This is my code for declaring the needed VAOs and VBOs:

```<code>        GLuint VAO[5];         // Handle for the vertex array object
        GLuint VBO[10];         // Handle for the vertex buffer object
        GLuint nMonumentIndices;    // Number of indices of the mesh
        GLuint nPlaneIndices;
        GLuint nBuildingIndices;
        GLuint nColumnIndices;
        GLuint nPoolIndices;
</code>```

And this is my code for generating and binding the respective VAOs and VBOs:

```<code>const GLuint floatsPerVertex = 3; // Number of coordinates per vertex
    const GLuint floatsPerColor = 4;  // (r, g, b, a)

    // Strides between vertex coordinates is 6 (x, y, r, g, b, a). A tightly packed stride is 0.
    GLint stride = sizeof(float) * (floatsPerVertex + floatsPerColor);// The number of floats before each

    glGenVertexArrays(5, mesh.VAO);  //generates 1 vertex array
    glGenBuffers(10, mesh.VBO);      // generates two VBOs

    glBindVertexArray(mesh.VAO[0]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[0]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(monumentVerts), monumentVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nMonumentIndices = sizeof(monumentIndices) / sizeof(monumentIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[1]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(monumentIndices), monumentIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float) * floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[1]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[2]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(planeVerts), planeVerts, GL_STATIC_DRAW);  //sends the vertices to the buffer

    mesh.nPlaneIndices = sizeof(planeIndices) / sizeof(planeIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[3]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(planeIndices), planeIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[2]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[4]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(monumentVerts), monumentVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nBuildingIndices = sizeof(buildingIndices) / sizeof(buildingIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[5]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(buildingIndices), buildingIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[3]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[6]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(columnVerts), columnVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nBuildingIndices = sizeof(columnIndices) / sizeof(columnIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[7]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(columnIndices), columnIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[4]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[8]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(poolVerts), poolVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nBuildingIndices = sizeof(poolIndices) / sizeof(poolIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[9]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(poolIndices), poolIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);
</code>```

I also have separate draw calls for each object that I'm rendering:

```<code> // Activate the VBOs contained within the mesh's VAO
    glBindVertexArray(gMesh.VAO[0]);
    glDrawElements(GL_TRIANGLES, gMesh.nMonumentIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[1]);
    glDrawElements(GL_TRIANGLES, gMesh.nPlaneIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[2]);
    glDrawElements(GL_TRIANGLES, gMesh.nBuildingIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[3]);
    glDrawElements(GL_TRIANGLES, gMesh.nColumnIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[4]);
    glDrawElements(GL_TRIANGLES, gMesh.nPoolIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);
</code>```

However, when rendering, only the first object (the monument) is drawn.  Where am I going wrong?  On a code level, are there any flaws?

答:
You cannot bind all the Vertex Array Objects at once. You have to bind the correct Vertex Array Object before the draw call. The current VAO is a global state. Binding a VAO breaks the existing vertex array object binding.

glBindVertexArray(mesh.VAO[0]);
glDrawElements(GL_TRIANGLES, gMesh.nMonumentIndices, GL_UNSIGNED_SHORT, NULL);

glBindVertexArray(mesh.VAO[1]);
glDrawElements(GL_TRIANGLES, gMesh.nPlaneIndices, GL_UNSIGNED_SHORT, NULL);

glBindVertexArray(mesh.VAO[2]);
glDrawElements(GL_TRIANGLES, gMesh.nBuildingIndices, GL_UNSIGNED_SHORT, NULL);

glBindVertexArray(mesh.VAO[3]);
glDrawElements(GL_TRIANGLES, gMesh.nColumnIndices, GL_UNSIGNED_SHORT, NULL);

glBindVertexArray(mesh.VAO[4]);
glDrawElements(GL_TRIANGLES, gMesh.nPoolIndices, GL_UNSIGNED_SHORT, NULL);
```

Body:
I'm trying to render multiple objects, but only the first object specified is rendering. I have a series of vertices arrays with their corresponding indices in a separate array.  According to everything I've read, I simply allot 2 VBOs per object I'm drawing -- one VBO for vertices, one for indices.  I generate the buffers and bind them to their respective VAO.  When rendering, I then need to have individual draw calls for each object.

This is my code for declaring the needed VAOs and VBOs:

        GLuint VAO[5];         // Handle for the vertex array object
        GLuint VBO[10];         // Handle for the vertex buffer object
        GLuint nMonumentIndices;    // Number of indices of the mesh
        GLuint nPlaneIndices;
        GLuint nBuildingIndices;
        GLuint nColumnIndices;
        GLuint nPoolIndices;

And this is my code for generating and binding the respective VAOs and VBOs:

const GLuint floatsPerVertex = 3; // Number of coordinates per vertex
    const GLuint floatsPerColor = 4;  // (r, g, b, a)

    // Strides between vertex coordinates is 6 (x, y, r, g, b, a). A tightly packed stride is 0.
    GLint stride = sizeof(float) * (floatsPerVertex + floatsPerColor);// The number of floats before each

    glGenVertexArrays(5, mesh.VAO);  //generates 1 vertex array
    glGenBuffers(10, mesh.VBO);      // generates two VBOs

    glBindVertexArray(mesh.VAO[0]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[0]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(monumentVerts), monumentVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nMonumentIndices = sizeof(monumentIndices) / sizeof(monumentIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[1]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(monumentIndices), monumentIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float) * floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[1]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[2]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(planeVerts), planeVerts, GL_STATIC_DRAW);  //sends the vertices to the buffer

    mesh.nPlaneIndices = sizeof(planeIndices) / sizeof(planeIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[3]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(planeIndices), planeIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[2]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[4]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(monumentVerts), monumentVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nBuildingIndices = sizeof(buildingIndices) / sizeof(buildingIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[5]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(buildingIndices), buildingIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[3]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[6]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(columnVerts), columnVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nBuildingIndices = sizeof(columnIndices) / sizeof(columnIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[7]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(columnIndices), columnIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    glBindVertexArray(mesh.VAO[4]);  //binds our VAO
    glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO[8]); //binds our first VBO
    glBufferData(GL_ARRAY_BUFFER, sizeof(poolVerts), poolVerts, GL_STATIC_DRAW);    //sends the vertices to the buffer

    mesh.nBuildingIndices = sizeof(poolIndices) / sizeof(poolIndices[0]);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.VBO[9]);  //binds second VBO
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(poolIndices), poolIndices, GL_STATIC_DRAW);  //sends the indices to the buffer

    // Creates the Vertex Attribute Pointer
    glVertexAttribPointer(0, floatsPerVertex, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, floatsPerColor, GL_FLOAT, GL_FALSE, stride, (char*)(sizeof(float)* floatsPerVertex));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0);

I also have separate draw calls for each object that I'm rendering:

 // Activate the VBOs contained within the mesh's VAO
    glBindVertexArray(gMesh.VAO[0]);
    glDrawElements(GL_TRIANGLES, gMesh.nMonumentIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[1]);
    glDrawElements(GL_TRIANGLES, gMesh.nPlaneIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[2]);
    glDrawElements(GL_TRIANGLES, gMesh.nBuildingIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[3]);
    glDrawElements(GL_TRIANGLES, gMesh.nColumnIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

    glBindVertexArray(gMesh.VAO[4]);
    glDrawElements(GL_TRIANGLES, gMesh.nPoolIndices, GL_UNSIGNED_SHORT, NULL);
    glBindVertexArray(0);

However, when rendering, only the first object (the monument) is drawn.  Where am I going wrong?  On a code level, are there any flaws?


问:
How to read parquet files into array of python dictionary?
Is there a way to convert parquet files into an array of python dictionaries where the keys are the columns?

```<code>import pyarrow.parquet as pq
</code>```

Does that library natively support that feature?

答:
Use to_pylist

import pandas as pd
import pyarrow.parquet as pq

df = pd.concat(
    [
        pd.Series([1, 2, 3], name='col1'),
        pd.Series(["abc", "def", "ghi"], name='col2')
    ],
    axis=1
)
df.to_parquet('df.parquet')
pq.read_table('df.parquet').to_pydict()
>>> {'col1': [1, 2, 3], 'col2': ['abc', 'def', 'ghi']}
```

Body:
Is there a way to convert parquet files into an array of python dictionaries where the keys are the columns?

import pyarrow.parquet as pq

Does that library natively support that feature?