问:
Android Room: How to auto generate primary id, without using "autoGenerate = true" (To avoid SQLite keyword AUTOINCREMENT)?

Background

Just recently, I learn that using AUTOINCREMENT in SQLite is not encouraged.

https://www.sqlite.org/autoinc.html

The keyword AUTOINCREMENT is in fact confusing. As, what it really mean is the algorithm method for generating id automatically.

Even if we do not use the keyword AUTOINCREMENT, and do not provide an id during insertion, the id will still be auto generated.

For instance,

```<code>DROP TABLE cities;

CREATE TABLE cities (
   id INTEGER NOT NULL PRIMARY KEY,
   name TEXT NOT NULL
);

INSERT INTO cities (name)
VALUES( 'San Jose');

INSERT INTO cities (name)
VALUES( 'New York');
</code>```

The following table will still be generated even without AUTOINCREMENT keyword

```<code>id  name
========
1   San Jose
2   New York
</code>```

I want to achieve the same behavior in Android Room

Instead of using the following (which will apply SQLite AUTOINCREMENT)

```<code>@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private long id;
</code>```

I use in my entity class

```<code>@PrimaryKey
@ColumnInfo(name = "id")
private long id;
</code>```

However, I notice that I need to explicitly assign a non zero positive value to id, only the insertion will be success.

If the value for id is 0 or -1, then the insertion will not succeed

I expect we need not to assign id manually, even without using Room autoGenerate = true.

But, it seems like that doesn't work as expected. May I know why it is so?

答:
You don't need to achieve the same in Android room. In SQLite, a column with the type of INTEGER PRIMARY KEY is an alias for the ROWID, except if you specify WITHOUT ROWID.

So, upon insert your id will receive an unused integer unless specified otherwise.

The reason for not recommending the AUTOINCREMENT keyword is that unless it's a PRIMARY KEY, then it is unlikely necessary to accept the costs in terms of CPU, memory usage, disk space and I/O overhead. However, using a PRIMARY KEY is in fact a good idea. Note that the page you have shared never claims you should not use a PRIMARY KEY, it just discourages the usage of the AUTOINCREMENT keyword.

Body:
Background

Just recently, I learn that using AUTOINCREMENT in SQLite is not encouraged.

https://www.sqlite.org/autoinc.html

The keyword AUTOINCREMENT is in fact confusing. As, what it really mean is the algorithm method for generating id automatically.

Even if we do not use the keyword AUTOINCREMENT, and do not provide an id during insertion, the id will still be auto generated.

For instance,

DROP TABLE cities;

CREATE TABLE cities (
   id INTEGER NOT NULL PRIMARY KEY,
   name TEXT NOT NULL
);

INSERT INTO cities (name)
VALUES( 'San Jose');

INSERT INTO cities (name)
VALUES( 'New York');

The following table will still be generated even without AUTOINCREMENT keyword

id  name
========
1   San Jose
2   New York

I want to achieve the same behavior in Android Room

Instead of using the following (which will apply SQLite AUTOINCREMENT)

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private long id;

I use in my entity class

@PrimaryKey
@ColumnInfo(name = "id")
private long id;

However, I notice that I need to explicitly assign a non zero positive value to id, only the insertion will be success.

If the value for id is 0 or -1, then the insertion will not succeed

I expect we need not to assign id manually, even without using Room autoGenerate = true.

But, it seems like that doesn't work as expected. May I know why it is so?


来源: stackexchange

问:
List levels of a categorical variable corresponding to another categorical variable in R
I have a data set including two categorical variables, name and position. Every level of name corresponds to a single level of position, but every level of position corresponds to multiple levels of name.

```<code>data <- data.frame(
  name = factor(rep(1:8, each=2)),
  position = rep(c("A", "B", "C", "D", "B", "D", "A", "C"), each=2)
)
table(data$name, data$position)
</code>```

Table output is:

```<code>    A B C D
  1 2 0 0 0
  2 0 2 0 0
  3 0 0 2 0
  4 0 0 0 2
  5 0 2 0 0
  6 0 0 0 2
  7 2 0 0 0
  8 0 0 2 0
</code>```

I'd like to return a list or table of the position levels that correspond to each name level (I'm not picky about the format). For the example above, the desired output could look like:

```<code>  1   2   3   4   5   6   7   8
"A" "B" "C" "D" "B" "D" "A" "C"
</code>```

In this example you could shortcut it by taking all the even or odd values of position but that's not an option for my data frame since the number of cases per level of name varies.

Thanks in advance for helping an R newbie out. I imagine that there is a straightforward function to do this, but I don't know its name to search for it.

答:
```<code>colnames(a<-table(data))[max.col(a)]
[1] "A" "B" "C" "D" "B" "D" "A" "C"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data set including two categorical variables, name and position. Every level of name corresponds to a single level of position, but every level of position corresponds to multiple levels of name.

data <- data.frame(
  name = factor(rep(1:8, each=2)),
  position = rep(c("A", "B", "C", "D", "B", "D", "A", "C"), each=2)
)
table(data$name, data$position)

Table output is:

    A B C D
  1 2 0 0 0
  2 0 2 0 0
  3 0 0 2 0
  4 0 0 0 2
  5 0 2 0 0
  6 0 0 0 2
  7 2 0 0 0
  8 0 0 2 0

I'd like to return a list or table of the position levels that correspond to each name level (I'm not picky about the format). For the example above, the desired output could look like:

  1   2   3   4   5   6   7   8
"A" "B" "C" "D" "B" "D" "A" "C"

In this example you could shortcut it by taking all the even or odd values of position but that's not an option for my data frame since the number of cases per level of name varies.

Thanks in advance for helping an R newbie out. I imagine that there is a straightforward function to do this, but I don't know its name to search for it.


问:
jquery .load() google docs form
i have a form created via google docs like https://spreadsheets.google.com/spreadsheet/embeddedform?formkey=dFgwMWhsallRZ2ViMWNaSVF1VmF2d0E6MQ.

is it possible to load this page into a div with jquery:

var content='https://spreadsheets.google.com/spreadsheet/embeddedform?formkey=dFgwMWhsallRZ2ViMWNaSVF1VmF2d0E6MQ';

$('#some_elem').load(content);

update: #some_elem is a dynamically created element.

答: This will not work because of the same origin policy. Which basically means you cannot load content from site1.com on site2.com via ajax for security reasons, this behaviour is built into modern browsers so there is no easy way around it unless you control both requesting and requested content. Your best bet is to use an iframe to get around this.

ContentLicense: CC BY-SA 3.0

Title: jquery .load() google docs form


问:
Connect remote SQL azure from web app within the Vnet with service endpoints enabled
Hope you are doing well. I have a use case that I am trying to set up, but no success.

Let me explain it.

I have a premium web app integrated with azure vnet and connecting SQL azure using service endpoints (I have created a vnet rule for the SQL server by enabling the service endpoints). that works fine. no issue with that.

But there is a requirement that I need to connect a different SQL Azure database that resides in a different Azure tenant and subscription. and their SQL database is not publicly accessible. they are fine to whitelist the public IP that I am connecting to. I told the IP addresses of my azure web app, but it seems this doesn't use public IP when connecting remote SQL server when vnet integration and service endpoints are enabled. it tries to connect the database using private IP and service endpoints.

I have tried to create a private endpoint for remote SQL server within the network the web app resides, but it seems it does not work either (still trying.)

I am not sure the problem is clear but I need help if you have any idea.

Thanks.

答:
I think I was able to make this work by using the below reference.

https://learn.microsoft.com/en-us/azure/architecture/example-scenario/private-web-app/private-web-app

The problem was when you add a new private endpoint by using resource ID, it does not register its private DNS zone. that was the missing piece.

Thanks for the help.


问:
How can I run android app on from react native
I am facing error while running react native cli to emulator by using android studio

Actual output

Manifest merger failed with multiple errors, see logs

expected output

Running app on. android emulator
with custom app launch icon

actual output with VSCode

```<code>error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

* What went wrong:
Execution failed for task ':app:processDebugMainManifest'.
> Manifest merger failed with multiple errors, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org
</code>```

答:
since the port is mentioned it looks a little bit like you are not connected and need to reconnect your adb server to the application on metro. To do so you need to install adb tools (I believe it was via brew, but google will help) and then run(in 2nd Terminal beside metro):

```<code>adb reverse tcp:8081 tcp:8081
</code>```

When it shows 8081 in the new terminal, you can try again.

Body:
I am facing error while running react native cli to emulator by using android studio

Actual output

Manifest merger failed with multiple errors, see logs

expected output

Running app on. android emulator
with custom app launch icon

actual output with VSCode

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

* What went wrong:
Execution failed for task ':app:processDebugMainManifest'.
> Manifest merger failed with multiple errors, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Body:
since the port is mentioned it looks a little bit like you are not connected and need to reconnect your adb server to the application on metro. To do so you need to install adb tools (I believe it was via brew, but google will help) and then run(in 2nd Terminal beside metro):

adb reverse tcp:8081 tcp:8081

When it shows 8081 in the new terminal, you can try again.


问:
SwiftUI - Get data in remote JSON data to refresh on App startup
I am a noob (and my code/model currently will show it so please go easy on me!).

I’m taking a first whack at creating a recipes style (cenotes) app.

So that I can update the data I have a remote json file, so users won't have to reinstall to get the updated data.

The app successfully retrieves and parses the data (that’s a win!), but only when first installed.

It is not subsequently refreshing the data when it is changed online.   I have tried using .onAppear and also .refreshable unsuccessfully.   I need to delete the App and re-install for it to go and fetch the updated data.

Below are some the redacted versions of my files:  Can anybody help?  I think that I just have a @StateObject/@EnvironmentObject or something similar incorrect, but can’t spot the error.

Locations.swift

```<code>import Foundation

class Locations: ObservableObject {
    @Published var locations = [Location]()

    init() {
        load()
    }

    func load() {
        let url = URL(string: "https://www.i-love-tulum.com/cenotes/locations.json")!
               URLSession.shared.dataTask(with: url) {(data,response,error) in
                   do {
                       if let d = data {
                           let data = try JSONDecoder().decode([Location].self, from: d)
                           DispatchQueue.main.async {
                               self.locations = data
                           }
                       } else {
                           print("No Data")
                       }
                   } catch {
                       print ("Error")
                   }
               }.resume()
    } }
</code>```

Location.swift - VM

```<code>import Foundation

struct Location: Codable, Identifiable {
    var id: String
    let heroPicture: String
    }
</code>```

App.swift - The App opens to this tab view

```<code>import SwiftUI

@main struct App: App {
    @StateObject var locations = Locations()
    @State private var selection = 1

    var body: some Scene {
        WindowGroup {
            TabView (selection:$selection) {
                NavigationView {
                    ListView()
                }
                .tabItem {
                    Image(systemName: "drop.circle")
                    Text("Cenotes")
                } .tag(1)
            }
            .environmentObject(locations)
        }
    } }
</code>```

ListView.swift - The first selected tab is this view - these locations are not updating after the initial install:

```<code>import SwiftUI import MapKit

struct ListView: View {
    @EnvironmentObject var locations: Locations

    var body: some View {
        VStack {
            GeometryReader { geo in
                ScrollView {
                    LazyVStack (alignment: .leading) {
                        ForEach (locations: locations.locations) { location in
                               NavigationLink (
                                    destination: ContentView(location: location),
                                    label: {
                    Image(location.heroPicture)
                    }
            .navigationTitle("Cenotes")
            .navigationBarTitleDisplayMode(.inline)
    } }
</code>```

答:
All is well set up and works fine. This here adds two Buttons to the list, to delete all entries and reload again. Maybe that helps.

```<code>struct ListView: View {
    @EnvironmentObject var locations: Locations

    var body: some View {
        List {
            ForEach (locations.locations) { location in
                NavigationLink {
                    Text("Content View here ...")
                } label: {
                    VStack(alignment: .leading) {
                        Text(location.name).font(.title)
                        Text(location.aka).foregroundColor(.secondary)
                    }
                }
                .navigationTitle("Cenotes")
                .navigationBarTitleDisplayMode(.inline)
            }
        }

        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button("Delete all") {
                    locations.locations = []
                }
            }
            ToolbarItem(placement: .navigationBarTrailing) {
                Button("Reload") {
                    locations.load()
                }
            }
        }
    }
}
</code>```

Body:
I am a noob (and my code/model currently will show it so please go easy on me!).

I’m taking a first whack at creating a recipes style (cenotes) app.

So that I can update the data I have a remote json file, so users won't have to reinstall to get the updated data.

The app successfully retrieves and parses the data (that’s a win!), but only when first installed.

It is not subsequently refreshing the data when it is changed online.   I have tried using .onAppear and also .refreshable unsuccessfully.   I need to delete the App and re-install for it to go and fetch the updated data.

Below are some the redacted versions of my files:  Can anybody help?  I think that I just have a @StateObject/@EnvironmentObject or something similar incorrect, but can’t spot the error.

Locations.swift

import Foundation

class Locations: ObservableObject {
    @Published var locations = [Location]()

    init() {
        load()
    }

    func load() {
        let url = URL(string: "https://www.i-love-tulum.com/cenotes/locations.json")!
               URLSession.shared.dataTask(with: url) {(data,response,error) in
                   do {
                       if let d = data {
                           let data = try JSONDecoder().decode([Location].self, from: d)
                           DispatchQueue.main.async {
                               self.locations = data
                           }
                       } else {
                           print("No Data")
                       }
                   } catch {
                       print ("Error")
                   }
               }.resume()
    } }

Location.swift - VM

import Foundation

struct Location: Codable, Identifiable {
    var id: String
    let heroPicture: String
    }

App.swift - The App opens to this tab view

import SwiftUI

@main struct App: App {
    @StateObject var locations = Locations()
    @State private var selection = 1

    var body: some Scene {
        WindowGroup {
            TabView (selection:$selection) {
                NavigationView {
                    ListView()
                }
                .tabItem {
                    Image(systemName: "drop.circle")
                    Text("Cenotes")
                } .tag(1)
            }
            .environmentObject(locations)
        }
    } }

ListView.swift - The first selected tab is this view - these locations are not updating after the initial install:

import SwiftUI import MapKit

struct ListView: View {
    @EnvironmentObject var locations: Locations

    var body: some View {
        VStack {
            GeometryReader { geo in
                ScrollView {
                    LazyVStack (alignment: .leading) {
                        ForEach (locations: locations.locations) { location in
                               NavigationLink (
                                    destination: ContentView(location: location),
                                    label: {
                    Image(location.heroPicture)
                    }
            .navigationTitle("Cenotes")
            .navigationBarTitleDisplayMode(.inline)
    } }

Body:
All is well set up and works fine. This here adds two Buttons to the list, to delete all entries and reload again. Maybe that helps.

struct ListView: View {
    @EnvironmentObject var locations: Locations

    var body: some View {
        List {
            ForEach (locations.locations) { location in
                NavigationLink {
                    Text("Content View here ...")
                } label: {
                    VStack(alignment: .leading) {
                        Text(location.name).font(.title)
                        Text(location.aka).foregroundColor(.secondary)
                    }
                }
                .navigationTitle("Cenotes")
                .navigationBarTitleDisplayMode(.inline)
            }
        }

        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button("Delete all") {
                    locations.locations = []
                }
            }
            ToolbarItem(placement: .navigationBarTrailing) {
                Button("Reload") {
                    locations.load()
                }
            }
        }
    }
}


问:
How to check memory leaks using memory usages of a process?
```<code>int ParseLine(char* line){
   int i = strlen(line);
   const char* p = line;
   while(*p < '0' || *p > '9') p++;    // Search until a number is found.
   line[i - 3] = '\0'; // Remove " kB"
   i = atoi(p);
   return i;
}

int GetCurrentVirtualMem(){
   std::string cur_proc;
   cur_proc = "/proc/" + std::to_string((int)getpid()) + "/status";

   FILE* fs = fopen(cur_proc.c_str(), "r");
   int result = -1;
   char line[128];

   while(fgets(line, 128, fs) != NULL){
       if(strncmp(line, "VmSize:", 7) == 0){
           result = ParseLine(line);
           break;
       }
   }
   fclose(fs);
   fs = NULL;  //garly modify, for test memory problem

   return result;
}

int GetCurrentMem(){
   std::string cur_proc;
   cur_proc = "/proc/" + std::to_string((int)getpid()) + "/status";

   FILE* fs = fopen(cur_proc.c_str(), "r");
   int result = -1;
   char line[128];

   while(fgets(line, 128, fs) != NULL){
       if(strncmp(line, "VmRSS:", 6) == 0){
           result = ParseLine(line);
           break;
       }
   }
   fclose(fs);
   fs = NULL;  //garly modify, for test memory problem
   return result;
}
</code>```

I'm trying to check memory leaks but I don't understand physical memory and virtual memory clearly. So I just printed both using the functions above.

```<code>float curr_mem = (float)GetCurrentMem() / 1000;
float curr_vir_mem = (float)GetCurrentVirtualMem() / 1000;
std::cout << "Using memory(" << std::to_string((int)getpid()) << "): " << curr_mem << ", " << curr_vir_mem << std::endl;
</code>```

If I check the changes of physical memory or virtual memory, which one should I take a look at?
Both? or one of them?

And I found that even if there are no memory leaks the memory values are changed.

```<code>int main(int argc, char *argv[])
{
   QApplication a(argc, argv);

   float prev_mem = 0;
   float prev_vir_mem = 0;
   while(true){

       int* mem_leak = new int[100];

       float curr_mem = (float)GetCurrentMem() / 1000;
       float curr_vir_mem = (float)GetCurrentVirtualMem() / 1000;

       if(prev_mem != curr_mem || prev_vir_mem != curr_vir_mem){
           prev_mem = curr_mem ;
           prev_vir_mem = curr_vir_mem;

           std::cout << "Using memory(" << std::to_string((int)getpid()) << "): " << curr_mem << ", " << curr_vir_mem << std::endl;
       }

       delete[] mem_leak;
   }
   return 0;
}
</code>```

After an hour of running the code above, it showed the changes in the memory

```<code>Using memory(3303): 28.296, 250.788
Using memory(3303): 28.652, 250.788
Using memory(3303): 28.916, 250.788
</code>```

So is this method fine to check memory leak or not?
I used "Valgrind" but it didn't show any memory leak message from my code(not the above code. It is too huge to upload here. It is over 30000 lines.). But it showed memory changes in the long-term running test(about 1-week).

Please let me know how to check memory leaks correctly without using other software(such as Valgrind).

答:
If I understand you correctly you want to check for memory leaks on Linux using a process image from an process that has not been instrumented in any way.

https://github.com/vmware/chap (free open source) does this.

First you gather a core:

```<code>echo 0x37 > /proc/<pid-of-your-process>/coredump_filter
gcore <pid-of-your-process>
</code>```

Then you open the core in chap:

```<code>chap <core-just-created-by-gcore>
</code>```

To check for the classic kind of leak (objects that can no longer be reached) you can use the following commands from the chap prompt:

```<code>count leaked
</code>```

That tells you how many objects were leaked.

```<code>describe leaked /showUpTo 100
</code>```

That describes each leaked object, gives a hex dump of up to 0x100 bytes of each object and gives you the count at the end.

Various other commands are available but I don't want to repeat the user's manual.

Body:
int ParseLine(char* line){
   int i = strlen(line);
   const char* p = line;
   while(*p < '0' || *p > '9') p++;    // Search until a number is found.
   line[i - 3] = '\0'; // Remove " kB"
   i = atoi(p);
   return i;
}

int GetCurrentVirtualMem(){
   std::string cur_proc;
   cur_proc = "/proc/" + std::to_string((int)getpid()) + "/status";

   FILE* fs = fopen(cur_proc.c_str(), "r");
   int result = -1;
   char line[128];

   while(fgets(line, 128, fs) != NULL){
       if(strncmp(line, "VmSize:", 7) == 0){
           result = ParseLine(line);
           break;
       }
   }
   fclose(fs);
   fs = NULL;  //garly modify, for test memory problem

   return result;
}

int GetCurrentMem(){
   std::string cur_proc;
   cur_proc = "/proc/" + std::to_string((int)getpid()) + "/status";

   FILE* fs = fopen(cur_proc.c_str(), "r");
   int result = -1;
   char line[128];

   while(fgets(line, 128, fs) != NULL){
       if(strncmp(line, "VmRSS:", 6) == 0){
           result = ParseLine(line);
           break;
       }
   }
   fclose(fs);
   fs = NULL;  //garly modify, for test memory problem
   return result;
}

I'm trying to check memory leaks but I don't understand physical memory and virtual memory clearly. So I just printed both using the functions above.

float curr_mem = (float)GetCurrentMem() / 1000;
float curr_vir_mem = (float)GetCurrentVirtualMem() / 1000;
std::cout << "Using memory(" << std::to_string((int)getpid()) << "): " << curr_mem << ", " << curr_vir_mem << std::endl;

If I check the changes of physical memory or virtual memory, which one should I take a look at?
Both? or one of them?

And I found that even if there are no memory leaks the memory values are changed.

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);

   float prev_mem = 0;
   float prev_vir_mem = 0;
   while(true){

       int* mem_leak = new int[100];

       float curr_mem = (float)GetCurrentMem() / 1000;
       float curr_vir_mem = (float)GetCurrentVirtualMem() / 1000;

       if(prev_mem != curr_mem || prev_vir_mem != curr_vir_mem){
           prev_mem = curr_mem ;
           prev_vir_mem = curr_vir_mem;

           std::cout << "Using memory(" << std::to_string((int)getpid()) << "): " << curr_mem << ", " << curr_vir_mem << std::endl;
       }

       delete[] mem_leak;
   }
   return 0;
}

After an hour of running the code above, it showed the changes in the memory

Using memory(3303): 28.296, 250.788
Using memory(3303): 28.652, 250.788
Using memory(3303): 28.916, 250.788

So is this method fine to check memory leak or not?
I used "Valgrind" but it didn't show any memory leak message from my code(not the above code. It is too huge to upload here. It is over 30000 lines.). But it showed memory changes in the long-term running test(about 1-week).

Please let me know how to check memory leaks correctly without using other software(such as Valgrind).

Body:
If I understand you correctly you want to check for memory leaks on Linux using a process image from an process that has not been instrumented in any way.

https://github.com/vmware/chap (free open source) does this.

First you gather a core:

echo 0x37 > /proc/<pid-of-your-process>/coredump_filter
gcore <pid-of-your-process>

Then you open the core in chap:

chap <core-just-created-by-gcore>

To check for the classic kind of leak (objects that can no longer be reached) you can use the following commands from the chap prompt:

count leaked

That tells you how many objects were leaked.

describe leaked /showUpTo 100

That describes each leaked object, gives a hex dump of up to 0x100 bytes of each object and gives you the count at the end.

Various other commands are available but I don't want to repeat the user's manual.


问:
How do programming languages without raw memory access do things like reading files?
Programming languages like C can, as far as I know, execute system calls to make the OS give them direct memory access to file streams that can be read from/written to. Now, how do programming languages without raw memory access (Java, Python, etc.) even do something like open a file "under the hood"?

Obviously, I'm not just talking about opening files here - some languages have built-in file reading features that would make my question obsolete. This concerns anything that has anything to do with direct memory access - e.g. accessing other devices (for instance the keyboard, the mouse), and so on.

答:
Here's an excerpt of the source code of the FileInputStream class from OpenJDK 8 (link):

    /**
     * Opens the specified file for reading.
     * @param name the name of the file
     */
    private native void open0(String name) throws FileNotFoundException;

    // ...

    private native int read0() throws IOException;

    /**
     * Reads a subarray as a sequence of bytes.
     * @param b the data to be written
     * @param off the start offset in the data
     * @param len the number of bytes that are written
     * @exception IOException If an I/O error has occurred.
     */
    private native int readBytes(byte b[], int off, int len) throws IOException;
```

The native keyword (see this other Q&A) means that these methods are not implemented in the Java source code for this class; they are provided by the implementation of the Java interpreter which executes the program (e.g. the java command-line utility, which executes Java bytecode). The Java interpreter itself is ultimately written in a language like C, which has the low-level features required to actually implement these native methods. When the interpreter has to execute a method marked native, it invokes the corresponding function written in C.

Similarly, other high-level languages like Python have some functions which are implemented "natively" in the same sense. These functions, along with the behaviours of basic arithmetic and comparison operations, are "intrinsic" as compared to the large bulk of a language's standard library, which is usually written in the language itself.

Body:
Here's an excerpt of the source code of the FileInputStream class from OpenJDK 8 (link):

    /**
     * Opens the specified file for reading.
     * @param name the name of the file
     */
    private native void open0(String name) throws FileNotFoundException;

    // ...

    private native int read0() throws IOException;

    /**
     * Reads a subarray as a sequence of bytes.
     * @param b the data to be written
     * @param off the start offset in the data
     * @param len the number of bytes that are written
     * @exception IOException If an I/O error has occurred.
     */
    private native int readBytes(byte b[], int off, int len) throws IOException;

The native keyword (see this other Q&A) means that these methods are not implemented in the Java source code for this class; they are provided by the implementation of the Java interpreter which executes the program (e.g. the java command-line utility, which executes Java bytecode). The Java interpreter itself is ultimately written in a language like C, which has the low-level features required to actually implement these native methods. When the interpreter has to execute a method marked native, it invokes the corresponding function written in C.

Similarly, other high-level languages like Python have some functions which are implemented "natively" in the same sense. These functions, along with the behaviours of basic arithmetic and comparison operations, are "intrinsic" as compared to the large bulk of a language's standard library, which is usually written in the language itself.


问:
Getting a form to submit from JavaScript?
I have a form in a JSP as follows:

```<code><form action = "<c:url value = '/displayVisualisation' />"
    title = "${item.visDescription}"
    method = "post" onClick = "return confirmRequest('Do you want to change  to
        another visualisation type?');">
    <input class = "text" type = "text" value = "${item.visTypeName}">

</form>
</code>```

Which calls a Javascript method as follows:

```<code>function confirmRequest(questionText) {
    var confirmRequest = confirm(questionText);
    if (confirmRequest) {
        return true;
    }

    else {
        return false;
    }
}
</code>```

To ask the user for a reply to the question asked. However, the confirm prompt appears but does not perform the displayVisualisation action!

Can anyone suggest why or help me implement this correctly?

In other examples, where the action is triggered by clicking a graphic, all is well.

答:
Since you are using onclick, return true; in your confirmRequest function is simply allowing the rest of the clickHandler chain to be executed. I think you also need to explicitly submit the form at this time, in the true case.

Here is one way to do that, using only javascript:

```<code>function confirmRequest(questionText) {
  var confirmRequest = confirm(questionText);
  if (confirmRequest) {
     document.forms[0].submit();
     return true;
  }
  else {
      return false;
  }
}
</code>```

Body:
I have a form in a JSP as follows:

<form action = "<c:url value = '/displayVisualisation' />"
    title = "${item.visDescription}"
    method = "post" onClick = "return confirmRequest('Do you want to change  to
        another visualisation type?');">
    <input class = "text" type = "text" value = "${item.visTypeName}">

</form>

Which calls a Javascript method as follows:

function confirmRequest(questionText) {
    var confirmRequest = confirm(questionText);
    if (confirmRequest) {
        return true;
    }

    else {
        return false;
    }
}

To ask the user for a reply to the question asked. However, the confirm prompt appears but does not perform the displayVisualisation action!

Can anyone suggest why or help me implement this correctly?

In other examples, where the action is triggered by clicking a graphic, all is well.

Body:
Since you are using onclick, return true; in your confirmRequest function is simply allowing the rest of the clickHandler chain to be executed. I think you also need to explicitly submit the form at this time, in the true case.

Here is one way to do that, using only javascript:

function confirmRequest(questionText) {
  var confirmRequest = confirm(questionText);
  if (confirmRequest) {
     document.forms[0].submit();
     return true;
  }
  else {
      return false;
  }
}


问:
Write F# DataTable to CSV file
I am trying to write an F# DataTable to csv (or output in a txt). The table I have is defined as follows:

```<code>let setup_report_tbl ( tbl : DataTable ) =
    ignore( tbl.Columns.Add("business_date", typeof<System.Int32>) )
    ignore( tbl.Columns.Add("ticker", typeof<System.String>) )
    ignore( tbl.Columns.Add("price", typeof<System.String>) )
    ignore( tbl.Columns.Add("rate", typeof<System.Boolean>) )
    ignore( tbl.Columns.Add("range", typeof<System.Double>) )
</code>```

My goal is to write this empty table with headers into a csv or txt. I'm new to F# and not quite sure where to start here, any help is appreciated thanks!

答:
If you wanted to use an existing library rather than writing your own CSV encoding (which may get tricky when you need to escape things), you could use Deedle which has an easy way to create data frame from a DataTable and save it to a CSV file:

```<code>#r "nuget: Deedle"
open Deedle
open System.Data

// Setup table using your function and add some data
let tbl = new DataTable()
setup_report_tbl tbl
tbl.Rows.Add(1, "very\",evil'ticker", "$42", false, 1.23)

// Turn it into a dataframe and save it
let df = Frame.ReadReader(tbl.CreateDataReader())
df.SaveCsv("C:/temp/test.csv")
</code>```

As a bonus point, you could see if the data frame type from Deedle lets you do some of the other things you want to do with the data - but this depends on your scenario.

Title: Write F# DataTable to CSV file

Body:
I am trying to write an F# DataTable to csv (or output in a txt). The table I have is defined as follows:

let setup_report_tbl ( tbl : DataTable ) =
    ignore( tbl.Columns.Add("business_date", typeof<System.Int32>) )
    ignore( tbl.Columns.Add("ticker", typeof<System.String>) )
    ignore( tbl.Columns.Add("price", typeof<System.String>) )
    ignore( tbl.Columns.Add("rate", typeof<System.Boolean>) )
    ignore( tbl.Columns.Add("range", typeof<System.Double>) )

My goal is to write this empty table with headers into a csv or txt. I'm new to F# and not quite sure where to start here, any help is appreciated thanks!

Body:
If you wanted to use an existing library rather than writing your own CSV encoding (which may get tricky when you need to escape things), you could use Deedle which has an easy way to create data frame from a DataTable and save it to a CSV file:

#r "nuget: Deedle"
open Deedle
open System.Data

// Setup table using your function and add some data
let tbl = new DataTable()
setup_report_tbl tbl
tbl.Rows.Add(1, "very\",evil'ticker", "$42", false, 1.23)

// Turn it into a dataframe and save it
let df = Frame.ReadReader(tbl.CreateDataReader())
df.SaveCsv("C:/temp/test.csv")

As a bonus point, you could see if the data frame type from Deedle lets you do some of the other things you want to do with the data - but this depends on your scenario.


问:
Decrease number of tasks in a Spark stage
I am running a spark sql job in aws EMR which reads ~100k small JSON files from s3, does a few transformations, and writes results back to s3. I have set shuffle partitions and default parallelism to 20 and executor memory to 4GB. However, for one of the stages javaToPython at NativeMethodAccessorImpl.java, as shown in UI which I understand writes to s3, has nearly 2.7k tasks with input data size < 1MB. Same behavior for the stage with a collect action. I don't understand why? What am I missing here?
I have also tested the app by reducing the number of partitions (with coalesce) in the application but nothing seems to change. I am running pyspark 2.4.7 and EMR-5.33.1

答:
I think to understand what you're observing you'll need to understand your cluster details and configurations.

Some assumptions in your application:

You didn't implement threading in your application

The number of tasks are defined by parallelism (total concurrent tasks)- which is defined by the

Number of executors

Number of cores for each executor

Number of partitions

Please take a read of how stages are split into tasks

With that - another thought is that you mentioned

~100k small JSON files

If you haven't already, make sure to review and understand the Small Files Problem

The section called

Hazards of small files

States

It is easy to cause too many tasks. If it exceeds the configuration of the parameter spark.driver.maxResultSize (default 1g), the
following exceptions will be thrown, affecting the processing of tasks
Caused by: org.apache.spark.SparkException: Job aborted due to stage
failure: Total size of serialized results of 478 tasks (2026.0 MB) is
bigger than spark.driver.maxResultSize (1024.0 MB) Of course, you can
increase the default configuration of spark.driver.maxResultSize to
solve the problem, but if you can't solve the small file problem from
the source, you may encounter similar problems in the future.

In addition, when Spark processes tasks, one partition is assigned a
task for processing, and multiple partitions are processed in
parallel. Although parallel processing can improve processing
efficiency, it does not mean that the more tasks, the better. If the
amount of data is small, too many tasks will affect the efficiency.

Understanding how tasks are created (configuration wise and application wise) + what your Spark application is trying to ingest, will help you understand what your application is doing.


问:
The request was aborted: Could not create SSL/TLS secure channel
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

```<code>private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}
</code>```

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?

答:
In my case, I was running under Visual Studio 2022. Time and time again I was getting this error.  Going through the code I saw that it retrieved the certificate just fine.  Security was set to TLS1.2, both answers above.  For whatever reason, running Visual Studio as Administrator made it work!
Maybe someone can explain to me how the code retrieved the certificate from the store just fine. I could see it and all the properties.  Why in the name of this world would it not process the request unless I run VS in admin mode???

Body:
We are unable to connect to an HTTPS server using WebRequest because of this error message:

The request was aborted: Could not create SSL/TLS secure channel.

We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:

private void Somewhere() {
    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}

private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
   return true;
}

The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?

I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP.  Does that change something?


问:
Permanently change selected text background color
How can I permanently change the background color of DIV text when I select it ?
What I am trying to achieve is a highlight effect like this:

Anyone can instruct me how to accomplish this with javascript?

I appreciate your help a lot.

EDIT: I need my text to stay highlighted and highlight multiple texts without losing the highlight of the previous ones.

答:
Use ::selection selector to override the default color:

::selection{
  background: #FFD24D;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>A team of horses will struggle to chase down a spoken word.</p></code>```

Body:
Use ::selection selector to override the default color:

::selection{
  background: #FFD24D;
}

<p>A team of horses will struggle to chase down a spoken word.</p>


问:
React issue with show / hiding elements
This project is using React.

The goal is that when the maximize icon is clicked on the the Editor component, the Preview component will be hidden. When the maximize icon is clicked on the Preview component, the Editor component will be hidden.

The problem is, when I click the maximize icon on the Editor component, the only thing that displays is the text "not found." But the Preview maximize icon works when clicked.

I logged state to the console so I know that the state is updating when the editor button is clicked, but I can't figure out what is wrong with the way I am rendering the Editor element.

Codepen link: https://codepen.io/Jamece/pen/Exbmxmv

Thank you for any help you can provide.

```<code>import * as marked from "https://cdn.skypack.dev/marked@4.0.12";

class Application extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorOnly: false,
      previewOnly: false,
      inputValue: "",
      outputValue: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.editorChange = this.editorChange.bind(this);
    this.previewChange = this.previewChange.bind(this);
  }

  handleChange(event) {
    this.setState({
      inputValue: event.target.value
    });
  }
  //changes view to editorOnly when editor maximize button is clicked then back to full view when clicked again
  editorChange() {
    this.setState((state) => {
      if (state.editorOnly === false) {
        return { editorOnly: true };
      } else {
        return { editorOnly: false };
      }
    });
  }
  //changes view to previewOnly when preview maximize button is clicked then back to full view when clicked again
  previewChange() {
    this.setState((state) => {
      if (state.previewOnly === false) {
        return { previewOnly: true };
      } else {
        return { previewOnly: false };
      }
    });
  }

  render() {
    console.log(this.state);

    if (this.state.editorOnly === false && this.state.previewOnly === false) {
      return (
        <div className="container-fluid px-0">
          <div className="d-flex flex-column main">
            <Editor editorChange={this.editorChange}
              handleChange={this.handleChange}/>
            <Preview previewChange={this.previewChange} />
          </div>
        </div>
      );
    } else if (
      this.state.editorOnly === true &&
      this.state.previewOnly === false
    ) {
      return (
          <div className="container-fluid px-0">
          <div className="d-flex flex-column main">
            <Editor editorChange={this.editorChange}
              handleChange={this.handleChange}/>
          </div>
        </div>
      );
    } else if (
      this.state.editorOnly === false &&
      this.state.previewOnly === true
    ) {
      return (
        <div className="container-fluid px-0">
          <div className="d-flex flex-column main">
            <Preview previewChange={this.previewChange} />
          </div>
        </div>
      );
    }
    else {
      return(
      <div></div>
      )
    }
  }
}
class Editor extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        return (
          <div className="d-flex justify-content-center">
            <form>
              <div className="boxes">
                <div className="d-flex align-items-center label-bar">
                  <div className="leftcon">
                    <i className="fa-solid fa-book"></i>
                  </div>
                  <div className="headings">Editor</div>
                  <div className="rightcon">
                    <button className="btn" onClick={this.props.editorChange}>
                      <i className="fa-solid fa-maximize"></i>
                    </button>
                  </div>
                </div>
                <textarea
                 value={this.props.inputValue}
                  onChange={this.props.handleChange}
                ></textarea>
              </div>
            </form>
          </div>
        );
      }
}
class Preview extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <div className="d-flex justify-content-center">
          <form>
            <div className="boxes">
              <div className="d-flex align-items-center label-bar">
                <div className="leftcon">
                  <i className="fa-solid fa-book"></i>
                </div>
                <div className="headings">Preview</div>
                <div className="rightcon">
                  <button className="btn" onClick={this.props.previewChange}>
                    <i className="fa-solid fa-maximize"></i>
                  </button>
                </div>
              </div>
              <div className="preview">
                <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br />
              </div>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Application />, document.getElementById("app"));
</code>```

答:
A button element inside a form element by default has type="submit".
Hence, when you click the maximize button it tries to submit the form, making an http request.

This is not what you want here so you should set type="button" on your buttons. This way they will not trigger a form submission on click.

The same thing happens on your Preview component, but note that in the console you get the following message:

Form submission canceled because the form is not connected

I believe this is because the way you order the elements in the different states causes React to recreate the preview window in the DOM. If you switch Editor and Preview around in the state where both are visible then Editor works fine and Preview is broken.

Title: React issue with show / hiding elements

Body:
This project is using React.

The goal is that when the maximize icon is clicked on the the Editor component, the Preview component will be hidden. When the maximize icon is clicked on the Preview component, the Editor component will be hidden.

The problem is, when I click the maximize icon on the Editor component, the only thing that displays is the text "not found." But the Preview maximize icon works when clicked.

I logged state to the console so I know that the state is updating when the editor button is clicked, but I can't figure out what is wrong with the way I am rendering the Editor element.

Codepen link: https://codepen.io/Jamece/pen/Exbmxmv

Thank you for any help you can provide.

import * as marked from "https://cdn.skypack.dev/marked@4.0.12";

class Application extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorOnly: false,
      previewOnly: false,
      inputValue: "",
      outputValue: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.editorChange = this.editorChange.bind(this);
    this.previewChange = this.previewChange.bind(this);
  }

  handleChange(event) {
    this.setState({
      inputValue: event.target.value
    });
  }
  //changes view to editorOnly when editor maximize button is clicked then back to full view when clicked again
  editorChange() {
    this.setState((state) => {
      if (state.editorOnly === false) {
        return { editorOnly: true };
      } else {
        return { editorOnly: false };
      }
    });
  }
  //changes view to previewOnly when preview maximize button is clicked then back to full view when clicked again
  previewChange() {
    this.setState((state) => {
      if (state.previewOnly === false) {
        return { previewOnly: true };
      } else {
        return { previewOnly: false };
      }
    });
  }

  render() {
    console.log(this.state);

    if (this.state.editorOnly === false && this.state.previewOnly === false) {
      return (

            <Editor editorChange={this.editorChange}
              handleChange={this.handleChange}/>
            <Preview previewChange={this.previewChange} />

      );
    } else if (
      this.state.editorOnly === true &&
      this.state.previewOnly === false
    ) {
      return (

            <Editor editorChange={this.editorChange}
              handleChange={this.handleChange}/>

      );
    } else if (
      this.state.editorOnly === false &&
      this.state.previewOnly === true
    ) {
      return (

            <Preview previewChange={this.previewChange} />

      );
    }
    else {
      return(

      )
    }
  }
}
class Editor extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        return (

            <form>

Editor

                    <button className="btn" onClick={this.props.editorChange}>

                    </button>

                <textarea
                 value={this.props.inputValue}
                  onChange={this.props.handleChange}
                ></textarea>

            </form>

        );
      }
}
class Preview extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (

          <form>

Preview

                  <button className="btn" onClick={this.props.previewChange}>

                  </button>

          </form>

    );
  }
}

ReactDOM.render(<Application />, document.getElementById("app"));


问:
Location Analysis with Open Street Map Data
I am attempting to do some simple location analysis using features available from Open Street Map. In particular, I want to build features related to proximity to major roads and hourly traffic counts. Using a list of locations I need to find the distance to the nearest major road and the traffic estimates on that road. So far I have been unable to extract Key:traffic:hourly from OSM and have not found an efficient way to compute the nearest major road to a location.

The below example is a simple set-up of all the McDonald's in Atlanta and the major roads. What is the best way to find the nearest major road to each location and the OSM traffic estimate of that road?

```<code>#~~~~~~~~~~Example~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#load packages
library(tidyverse)
library(osmdata)
library(osmar)
library(sf)

#Query McDonald's in Atlanta
q.ATL<- getbb("Atlanta") %>%
  opq() %>%
  add_osm_feature("amenity", "fast_food")%>%
  add_osm_feature("name", "McDonald's",value_exact = FALSE, match_case = FALSE)%>%
  osmdata_sf()

MDs.info<-as.data.frame(q.ATL[["osm_points"]]) # actually make this a dataframe

# Find Major Roads
MajorRds <- getbb("Atlanta Georgia")%>%
  opq()%>%
  add_osm_feature(key = "highway", value = c("motorway", "primary", "motorway_link", "primary_link")) %>%
  #add_osm_feature("traffic", "hourly")%>%  # This does not grab the appropriate information
  osmdata_sf()
</code>```

答:
What you are looking for, is probably st_nearest_feature() function:

library(tidyverse)
library(osmdata)
library(sf)

#Query McDonald's in Atlanta
q.ATL<- getbb("Atlanta") %>%
  opq() %>%
  add_osm_feature("amenity", "fast_food")%>%
  add_osm_feature("name", "McDonald's",value_exact = FALSE, match_case = FALSE)%>%
  osmdata_sf()

MDs.info <- as.data.frame(q.ATL[["osm_points"]]) |>
  select(osm_id, geometry) |>
  st_as_sf()

# Find Major Roads
MajorRds <- getbb("Atlanta Georgia")%>%
  opq()%>%
  add_osm_feature(key = "highway", value = c("motorway", "primary", "motorway_link", "primary_link")) %>%
  #add_osm_feature("traffic", "hourly")%>%  # This does not grab the appropriate information
  osmdata_sf()
```
<p>Now, we have to merge <code>osm_lines</code> and <code>osm_multilines</code> to get all highways:</p>
<pre class="lang-r prettyprint-override"><code>r <- MajorRds$osm_lines |>
  select(osm_id, name, highway, geometry)

r <- MajorRds$osm_multilines |>
  select(osm_id, name, highway, geometry) |>
  add_row(r)
</code>```

Let's plot it for visualization

plot(r$geometry)
plot(MDs.info, col = "blue", add = TRUE)
```
<p><img src="https://i.imgur.com/pFJgrS1.png" alt="" /></p>
<p>Now we will use <code>st_nearest_feature()</code> to find the nearest way and <code>st_distance</code> to calculate how far it is:</p>
<pre class="lang-r prettyprint-override"><code>nearest <- st_nearest_feature(MDs.info, r)
dist = st_distance(MDs.info, r[nearest,], by_element=TRUE)
MDs.info <- cbind(MDs.info, st_drop_geometry(r)[nearest,])
MDs.info$dist <- dist
head(MDs.info)
#> Simple feature collection with 6 features and 5 fields
#> Geometry type: POINT
#> Dimension:     XY
#> Bounding box:  xmin: -84.3696 ymin: 33.7743 xmax: -84.29572 ymax: 33.79026
#> Geodetic CRS:  WGS 84
#>              osm_id osm_id.1                name       highway
#> 497203850 497203850 40861481      Clairmont Road       primary
#> 534028686 534028686  9249238                <NA> motorway_link
#> 544125305 544125305 74927688 East College Avenue       primary
#> 654308248 654308248 74927688 East College Avenue       primary
#> 654308249 654308249 74927688 East College Avenue       primary
#> 654308250 654308250 74927688 East College Avenue       primary
#>                             geometry           dist
#> 497203850 POINT (-84.30741 33.79026)   86.16797 [m]
#> 534028686   POINT (-84.3696 33.7743) 1586.02491 [m]
#> 544125305 POINT (-84.29574 33.77833)  856.44432 [m]
#> 654308248 POINT (-84.29574 33.77831)  854.60091 [m]
#> 654308249 POINT (-84.29572 33.77831)  854.08773 [m]
#> 654308250 POINT (-84.29573 33.77804)  826.30178 [m]
</code>```

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

The issue with key=traffic:hourly is, it's not popular  and very seldom used, see https://taginfo.openstreetmap.org/keys/?key=traffic%3Ahourly

Body:
I am attempting to do some simple location analysis using features available from Open Street Map. In particular, I want to build features related to proximity to major roads and hourly traffic counts. Using a list of locations I need to find the distance to the nearest major road and the traffic estimates on that road. So far I have been unable to extract Key:traffic:hourly from OSM and have not found an efficient way to compute the nearest major road to a location.

The below example is a simple set-up of all the McDonald's in Atlanta and the major roads. What is the best way to find the nearest major road to each location and the OSM traffic estimate of that road?

#~~~~~~~~~~Example~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#load packages
library(tidyverse)
library(osmdata)
library(osmar)
library(sf)

#Query McDonald's in Atlanta
q.ATL<- getbb("Atlanta") %>%
  opq() %>%
  add_osm_feature("amenity", "fast_food")%>%
  add_osm_feature("name", "McDonald's",value_exact = FALSE, match_case = FALSE)%>%
  osmdata_sf()

MDs.info<-as.data.frame(q.ATL[["osm_points"]]) # actually make this a dataframe

# Find Major Roads
MajorRds <- getbb("Atlanta Georgia")%>%
  opq()%>%
  add_osm_feature(key = "highway", value = c("motorway", "primary", "motorway_link", "primary_link")) %>%
  #add_osm_feature("traffic", "hourly")%>%  # This does not grab the appropriate information
  osmdata_sf()

Body:
What you are looking for, is probably st_nearest_feature() function:

library(tidyverse)
library(osmdata)
library(sf)

#Query McDonald's in Atlanta
q.ATL<- getbb("Atlanta") %>%
  opq() %>%
  add_osm_feature("amenity", "fast_food")%>%
  add_osm_feature("name", "McDonald's",value_exact = FALSE, match_case = FALSE)%>%
  osmdata_sf()

MDs.info <- as.data.frame(q.ATL[["osm_points"]]) |>
  select(osm_id, geometry) |>
  st_as_sf()

# Find Major Roads
MajorRds <- getbb("Atlanta Georgia")%>%
  opq()%>%
  add_osm_feature(key = "highway", value = c("motorway", "primary", "motorway_link", "primary_link")) %>%
  #add_osm_feature("traffic", "hourly")%>%  # This does not grab the appropriate information
  osmdata_sf()

Now, we have to merge osm_lines and osm_multilines to get all highways:

r <- MajorRds$osm_lines |>
  select(osm_id, name, highway, geometry)

r <- MajorRds$osm_multilines |>
  select(osm_id, name, highway, geometry) |>
  add_row(r)

Let's plot it for visualization

plot(r$geometry)
plot(MDs.info, col = "blue", add = TRUE)

Now we will use st_nearest_feature() to find the nearest way and st_distance to calculate how far it is:

nearest <- st_nearest_feature(MDs.info, r)
dist = st_distance(MDs.info, r[nearest,], by_element=TRUE)
MDs.info <- cbind(MDs.info, st_drop_geometry(r)[nearest,])
MDs.info$dist <- dist
head(MDs.info)
#> Simple feature collection with 6 features and 5 fields
#> Geometry type: POINT
#> Dimension:     XY
#> Bounding box:  xmin: -84.3696 ymin: 33.7743 xmax: -84.29572 ymax: 33.79026
#> Geodetic CRS:  WGS 84
#>              osm_id osm_id.1                name       highway
#> 497203850 497203850 40861481      Clairmont Road       primary
#> 534028686 534028686  9249238                <NA> motorway_link
#> 544125305 544125305 74927688 East College Avenue       primary
#> 654308248 654308248 74927688 East College Avenue       primary
#> 654308249 654308249 74927688 East College Avenue       primary
#> 654308250 654308250 74927688 East College Avenue       primary
#>                             geometry           dist
#> 497203850 POINT (-84.30741 33.79026)   86.16797 [m]
#> 534028686   POINT (-84.3696 33.7743) 1586.02491 [m]
#> 544125305 POINT (-84.29574 33.77833)  856.44432 [m]
#> 654308248 POINT (-84.29574 33.77831)  854.60091 [m]
#> 654308249 POINT (-84.29572 33.77831)  854.08773 [m]
#> 654308250 POINT (-84.29573 33.77804)  826.30178 [m]

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

The issue with key=traffic:hourly is, it's not popular  and very seldom used, see https://taginfo.openstreetmap.org/keys/?key=traffic%3Ahourly


问:
Ensure there are no trailing arguments in Commander.js
I would like to write a CLI app that takes one optional argument.

```<code>import { Command } from 'commander';
const program = new Command();
program.argument('[a]');
program.action((a) => console.log(`a = ${a}`));
program.parse();
console.log(program.args);
</code>```

If I run it with 0 or 1 arguments, it works as expected. However, I can't see a clean way to check that the whole command line was consumed by arguments. I'd like to error out if there are any trailing command line arguments. What's the best way to achieve that?

```<code>$ node no-trailing-args.js
a = undefined
[]
$ node no-trailing-args.js 1
a = 1
[ '1' ]
$ node no-trailing-args.js 1 2
a = 1
[ '1', '2' ]
$
</code>```

答:
By default it is not an error to pass more arguments than declared, but you can make this an error with .allowExcessArguments(false).

```<code>program.allowExcessArguments(false);
</code>```

Body:
I would like to write a CLI app that takes one optional argument.

import { Command } from 'commander';
const program = new Command();
program.argument('[a]');
program.action((a) => console.log(`a = ${a}`));
program.parse();
console.log(program.args);

If I run it with 0 or 1 arguments, it works as expected. However, I can't see a clean way to check that the whole command line was consumed by arguments. I'd like to error out if there are any trailing command line arguments. What's the best way to achieve that?

$ node no-trailing-args.js
a = undefined
[]
$ node no-trailing-args.js 1
a = 1
[ '1' ]
$ node no-trailing-args.js 1 2
a = 1
[ '1', '2' ]
$

Body:
By default it is not an error to pass more arguments than declared, but you can make this an error with .allowExcessArguments(false).

program.allowExcessArguments(false);


问:
instantiate a viewController func in appDelegate in swift ios
I am new to swift iOS and I am not able to call a func in view controller from AppDelegate to activate at certain point in background in macOS bigsur

In my appDelegate I have below the following:

```<code>func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // new notifications from background
   .myNotifications() // a func in called in my viewController

}
</code>```

答:
Just call the func from an initiation of your view controller instead</p>
```<code>YourViewController().myNotifications()
</code>```

Body:
I am new to swift iOS and I am not able to call a func in view controller from AppDelegate to activate at certain point in background in macOS bigsur

In my appDelegate I have below the following:

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // new notifications from background
   .myNotifications() // a func in called in my viewController

}

Body:
Just call the func from an initiation of your view controller instead

YourViewController().myNotifications()


问:
is it possible to create a message which has a field with its own type with protocol buffer
Is it possible to define a message which has a field of its own type as in linked lists with protocol buffers? For example the value of next field could be null at the end of the list.</p>
```<code>message Node {
 string name = 1;
 Node next = 2;
}
</code>```

答:
I know you asked how to make a custom type. The documentation mentions to try to avoid that. I find that you can model almost anything with the parts / types that are built in. To make a list of nodes with the built in types do this:

```<code>message ResponseOfNodes {
 repeated Node nodes = 1;
}

message Node {
 string name = 1;
 string someOtherData = 2;
}
</code>```

Here's code that uses the generated code / list.

```<code>// make a node so it can be added to the list.
Node node1 = Node.newBuilder().setName("a name").setSomeOtherData("etc").build();

// Build a response (ResponseOfNodes) that will get nodes added to its list. Add two Nodes.
ResponseOfNodes.Builder responseBuilder = ResponseOfNodes.newBuilder().addNodes(node1);
responseBuilder.addNodes(node1.toBuilder().setName("name 2").build());

// build the ResponseOfNodes and print it out.
ResponseOfNodes responseOfNodes = responseBuilder.build();
log.info("the list: {}", responseOfNodes.getNodesList());
</code>```

Console Output;

```<code>[INFO ] [main] - Hello I am a client.
[INFO ] [main] - the list: [name: "a name"
someOtherData: "etc"
, name: "name 2"
someOtherData: "etc"
</code>```

Body:
Is it possible to define a message which has a field of its own type as in linked lists with protocol buffers? For example the value of next field could be null at the end of the list.

message Node {
 string name = 1;
 Node next = 2;
}

Body:
I know you asked how to make a custom type. The documentation mentions to try to avoid that. I find that you can model almost anything with the parts / types that are built in. To make a list of nodes with the built in types do this:

message ResponseOfNodes {
 repeated Node nodes = 1;
}

message Node {
 string name = 1;
 string someOtherData = 2;
}

Here's code that uses the generated code / list.

// make a node so it can be added to the list.
Node node1 = Node.newBuilder().setName("a name").setSomeOtherData("etc").build();

// Build a response (ResponseOfNodes) that will get nodes added to its list. Add two Nodes.
ResponseOfNodes.Builder responseBuilder = ResponseOfNodes.newBuilder().addNodes(node1);
responseBuilder.addNodes(node1.toBuilder().setName("name 2").build());

// build the ResponseOfNodes and print it out.
ResponseOfNodes responseOfNodes = responseBuilder.build();
log.info("the list: {}", responseOfNodes.getNodesList());

Console Output;

[INFO ] [main] - Hello I am a client.
[INFO ] [main] - the list: [name: "a name"
someOtherData: "etc"
, name: "name 2"
someOtherData: "etc"


问:
gRPC stopped working with APO on Windows 11
I have a Windows application (APP) and Audio Processing Object (APO) loaded by AudioDG.exe that communicate via gRPC:

APP part that is written in C# creates server via Grpc.Core.

APO part creates client via grpc++.

Server is on 127.0.0.1:20000 (I can see it's up and listening with netstat -ano).

I can confirm that APO is loaded into audio device graph by inspecting it with process explorer.

Everything worked like a charm on Windows 8 and 10, but on 11 it cannot communicate at all - I get either Error Code 14, Unavailable, failed to connect to all addresses or 4, Deadline Exceeded.

After enabling debug traces, I now see "socket is null" description for "connect failed" error:
I0207 16:20:59.916447 0 ..\..\..\src\core\ext\filters\client_channel\subchannel.cc:950: subchannel 000001D8B9B01E20 {address=ipv4:127.0.0.1:10000, args=grpc.client_channel_factory=0x1d8bb660460, grpc.default_authority=127.0.0.1:10000, grpc.internal.subchannel_pool=0x1d8b8c291b0, grpc.primary_user_agent=grpc-csharp/2.43.0 (.NET Framework 4.8.4470.0; CLR 4.0.30319.42000; net45; x64), grpc.resource_quota=0x1d8b8c28d90, grpc.server_uri=dns:///127.0.0.1:10000}: connect failed: {"created":"@1644240059.916000000","description":"socket is null","file":"..\..\..\src\core\lib\iomgr\tcp_client_windows.cc","file_line":112}

What I've tried so far:

Updating both parts to the latest grpc versions.

Using "no proxy", "Http2UnencryptedSupport" and other env variables.

Using "localhost" or "0.0.0.0" instead of "127.0.0.1".

Updating connection to use self signed SSL certificates (root CA, server cert + key, client cert + key).

Adding inbound / outbound rules for my port, and then disabling firewall completely.

Creating server on APO side and trying to connect with the client in APP.

Everything works (both insecure and SSL creds) if I create both client and server in C# part, but as soon as it's APP-APO communication it feels blocked or sandboxed.

What has been changed in Windows 11 that can "block" gRPC?

Thanks in advance!

答:
In your input you write:

Server is at 127.0.0.1:20000

Further looking at the logs, you can see that:

The server is located at
grpc.server_uri=dns:///127.0.0.1:10000

Based on the question posed and the amount of data provided, I would check which port the server is really using and which port the client is looking for a connection on.

The easiest way to do this is to use the built-in Resource Monitor application. On the Network tab, in the TCP Connections list, you can find the application and the port it uses.

You can also use the PowerShell command

```<code>Test-NetConnection -Port 10000 -InformationLevel "Detailed"
Test-NetConnection -Port 20000 -InformationLevel "Detailed"
</code>```

At least this is the first thing I would check based on what you described.

Regarding your question about the changes in Windows 11, I do not think that this is something that's causing problems for you. However, Windows 11 has additional security features compared to Windows 10, try disabling the security features completely as a test. Perhaps this will help solve the problem.

As for ASP.NET Core 6.0 itself (if I understood the version correctly), then there is a possibility that the server part, working not in the sandbox of the programming environment, still does not accept the client certificate. At the program level, you can try to fix this by adding the following exception to the code:

```<code>// This switch must be set before creating the GrpcChannel/HttpClient.
AppContext.SetSwitch(
    "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

// The port number(5000) must match the port of the gRPC server.
var channel = GrpcChannel.ForAddress("http://localhost:5000");
var client = new Greet.GreeterClient(channel);
</code>```

More troubleshooting issues with ASP.NET Core 6.0 Microsoft described in detail here.
https://learn.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-6.0

I hope it was useful and at least one of the solutions I suggested will help solve your problem. In any case, if I had more information, I think I could help you more accurately.

Body:
In your input you write:

Server is at 127.0.0.1:20000

Further looking at the logs, you can see that:

The server is located at
grpc.server_uri=dns:///127.0.0.1:10000

Based on the question posed and the amount of data provided, I would check which port the server is really using and which port the client is looking for a connection on.

The easiest way to do this is to use the built-in Resource Monitor application. On the Network tab, in the TCP Connections list, you can find the application and the port it uses.

You can also use the PowerShell command

Test-NetConnection -Port 10000 -InformationLevel "Detailed"
Test-NetConnection -Port 20000 -InformationLevel "Detailed"

At least this is the first thing I would check based on what you described.

Regarding your question about the changes in Windows 11, I do not think that this is something that's causing problems for you. However, Windows 11 has additional security features compared to Windows 10, try disabling the security features completely as a test. Perhaps this will help solve the problem.

As for ASP.NET Core 6.0 itself (if I understood the version correctly), then there is a possibility that the server part, working not in the sandbox of the programming environment, still does not accept the client certificate. At the program level, you can try to fix this by adding the following exception to the code:

// This switch must be set before creating the GrpcChannel/HttpClient.
AppContext.SetSwitch(
    "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

// The port number(5000) must match the port of the gRPC server.
var channel = GrpcChannel.ForAddress("http://localhost:5000");
var client = new Greet.GreeterClient(channel);

More troubleshooting issues with ASP.NET Core 6.0 Microsoft described in detail here.
https://learn.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-6.0

I hope it was useful and at least one of the solutions I suggested will help solve your problem. In any case, if I had more information, I think I could help you more accurately.


答:
You need to add event listener in javascript and when a text is selected at that time need to change the color like below</p>
```<code>function logSelection(event) {
  // Get Selection
  sel = window.getSelection();
  if (sel.rangeCount && sel.getRangeAt) {
    range = sel.getRangeAt(0);
  }
  // Set design mode to on
  document.designMode = "on";
  if (range) {
    sel.removeAllRanges();
    sel.addRange(range);
  }
  // Colorize text
  document.execCommand("ForeColor", false, "red");
  // Set design mode to off
  document.designMode = "off";
}

const input = document.querySelector('input');
input.addEventListener('select', logSelection);
</code>```

Title: Permanently change selected text background color

Body:
How can I permanently change the background color of DIV text when I select it ?
What I am trying to achieve is a highlight effect like this:

Anyone can instruct me how to accomplish this with javascript?

I appreciate your help a lot.

EDIT: I need my text to stay highlighted and highlight multiple texts without losing the highlight of the previous ones.

Body:
You need to add event listener in javascript and when a text is selected at that time need to change the color like below

function logSelection(event) {
  // Get Selection
  sel = window.getSelection();
  if (sel.rangeCount && sel.getRangeAt) {
    range = sel.getRangeAt(0);
  }
  // Set design mode to on
  document.designMode = "on";
  if (range) {
    sel.removeAllRanges();
    sel.addRange(range);
  }
  // Colorize text
  document.execCommand("ForeColor", false, "red");
  // Set design mode to off
  document.designMode = "off";
}

const input = document.querySelector('input');
input.addEventListener('select', logSelection);


问:
Sql - Using boolean logic in the where clause
i have a where clause that looks like this

```<code>WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)
</code>```

it is basically allowing filtering within ceratin ranges to be specified for a report
If values are omitted then they default to a very larg positive or negative number

The problem I have is that certain users don't have a Tolerance defined, which means their Tolerance percentage will always be zero,

so if the report specifed a criteria like this

```<code>set @GBPExposureUpper = -7500
    set @OnsideOffsideUpper = -3
    set @UsedToleranceUpper = -100
</code>```

then it would not include users who don't have a tolerance defined (as their tolerance will be zero - which is obviously larger than -100)

So I've created a bit field (@ShowNoSpecialTerms) which is controlled from a checkbox on the report which sets a flag to indicate that we want to addiionally include users who don't have a tolerance defined

When this is false we should use the filter conditions as normal

When this it is true, we should additionally include users who don't have a tolerance defined - these can be identified using the ToleranceLevel column

so the logic is kind of like

```<code>if (@ShowNoSpecialTerms = 0)

    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)

...

if  (@ShowNoSpecialTerms = 1)
--then additionally bring back result where ToleranceLevel=0
</code>```

Have tried the following

```<code>WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND (@ShowNoSpecialTerms = 0 OR
        UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
        AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999))
</code>```

This is half way to what I want - basically when    @ShowNoSpecialTerms = 1 it ignores the rest of the tolerance check

However, what I want is for it to return he results or the tolerance check PLUS those users who have a ToleranceLevel of zero

答:
If I understand your question properly, this is what you need.

Place AND between the condition @ShowNoSpecialTerms = 0 and it’s
true part.

Apply the same procedure to Else if condition too i.e. place the AND
between @ShowNoSpecialTerms = 1 and its body part.

Now place OR between these statements.

Body:
i have a where clause that looks like this

WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)

it is basically allowing filtering within ceratin ranges to be specified for a report
If values are omitted then they default to a very larg positive or negative number

The problem I have is that certain users don't have a Tolerance defined, which means their Tolerance percentage will always be zero,

so if the report specifed a criteria like this

set @GBPExposureUpper = -7500
    set @OnsideOffsideUpper = -3
    set @UsedToleranceUpper = -100

then it would not include users who don't have a tolerance defined (as their tolerance will be zero - which is obviously larger than -100)

So I've created a bit field (@ShowNoSpecialTerms) which is controlled from a checkbox on the report which sets a flag to indicate that we want to addiionally include users who don't have a tolerance defined

When this is false we should use the filter conditions as normal

When this it is true, we should additionally include users who don't have a tolerance defined - these can be identified using the ToleranceLevel column

so the logic is kind of like

if (@ShowNoSpecialTerms = 0)

    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
    AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999)

...

if  (@ShowNoSpecialTerms = 1)
--then additionally bring back result where ToleranceLevel=0

Have tried the following

WHERE
    OnSideOffSideTotal  < Isnull(@OnsideOffsideUpper, 9999999999999)
    AND OnSideOffSideTotal  > Isnull(@OnsideOffsideLower, -9999999999999)
    AND GbpExposureClientTotal < Isnull(@GBPExposureUpper, 9999999999999)
    AND GbpExposureClientTotal > Isnull(@GBPExposureLower, -9999999999999)
    AND (@ShowNoSpecialTerms = 0 OR
        UsedTolerancePercentage < Isnull(@UsedToleranceUpper, 9999999999999)
        AND UsedTolerancePercentage > Isnull(@UsedToleranceLower, -9999999999999))

This is half way to what I want - basically when    @ShowNoSpecialTerms = 1 it ignores the rest of the tolerance check

However, what I want is for it to return he results or the tolerance check PLUS those users who have a ToleranceLevel of zero


问:
Transform table structure
Hello is any sensible algorithm for transforming data table (Table A to Table B) ?

I trying to moving cells , but have no idea how to calculate a place where I should place additional row after my key field Name.

Table A origin

Name
Salary
Bonus
Amount

John S.
5000
Bonus A
50

John S.

Bonus B
100

Alex G.
7000
Bonus C
150

Alex G.

Bonus D
300

Table B (Expected outcome)

Name
Salary
Bonus
Amount

John S.

5000

John S.

Bonus A
50

John S.

Bonus B
100

Alex G.

7000

Alex G.

Bonus C
150

Alex G.

Bonus D
300

```<code>Sub TransformTable()

' Setting variables
Dim Name As String
Dim BaseSalary As String
Dim BonusName As String
Dim BonusAmount As Double

'Setting worksheet object
Dim SheetData As Worksheet
Set SheetData = Sheets("SheetData")

'counter for main loop
Dim x As Long

'Setting main object array
Dim MyArray As Variant

Dim Item As Integer
    Item = 1

'reading values from table
    MyArray = Worksheets("SheetData").ListObjects("Table1").DataBodyRange.Value

'counting last row value

'main loop
    For x = LBound(MyArray) To UBound(MyArray)

'condition check how many costcenter ids with fixed value
     lstRowSrs = SheetData.Cells(Rows.Count, 1).End(xlUp).Row
     Worksheets("SheetData").Cells(Item + 1, 13).Value = MyArray(x, 1)
     Worksheets("SheetData").Cells(Item + 1, 14).Value = MyArray(x, 2)

    If MyArray(x, 3) <> "" Then

    ' Cells(x, lstRowSrs).EntireRow.Insert

     Worksheets("SheetData").Cells(Item + 2, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 2, 16).Value = MyArray(x, 4)
     Item = Item + 1

    Else
     Worksheets("SheetData").Cells(Item + 1, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 1, 16).Value = MyArray(x, 4)

      Item = Item + 1
    End If
    Next x

End Sub
</code>```

答:
Here's another way. It has the same results as @Sgdva but uses some slightly different techniques. Not better, just something to consider.</p>
```<code>Sub TransformTable()

    Dim vaValues As Variant
    Dim i As Long
    Dim aOutput() As Variant
    Dim lCnt As Long

    'put all the values in a 2-d array
    vaValues = Sheet1.ListObjects(1).DataBodyRange
    'make your output array - double the rows of the input
    'it will be too many rows, but you won't run out of room
    ReDim aOutput(1 To UBound(vaValues, 1) * 2, 1 To 4)

    'Loop through the 2-d array
    For i = LBound(vaValues, 1) To UBound(vaValues, 1)
        If Len(vaValues(i, 2)) > 0 Then 'a salary exists
            'add a row to the output array
            lCnt = lCnt + 1
            aOutput(lCnt, 1) = vaValues(i, 1)
            aOutput(lCnt, 4) = vaValues(i, 2)
        End If

        If Len(vaValues(i, 4)) > 0 Then 'a bonus exists
            'add a row to the output array
            lCnt = lCnt + 1
            aOutput(lCnt, 1) = vaValues(i, 1)
            aOutput(lCnt, 3) = vaValues(i, 3)
            aOutput(lCnt, 4) = vaValues(i, 4)
        End If
    Next i

    'write out the output array in one shot
    Sheet1.Range("G1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput

End Sub
</code>```

Title: Transform table structure

Body:
Hello is any sensible algorithm for transforming data table (Table A to Table B) ?

I trying to moving cells , but have no idea how to calculate a place where I should place additional row after my key field Name.

Table A origin

Name
Salary
Bonus
Amount

John S.
5000
Bonus A
50

John S.

Bonus B
100

Alex G.
7000
Bonus C
150

Alex G.

Bonus D
300

Table B (Expected outcome)

Name
Salary
Bonus
Amount

John S.

5000

John S.

Bonus A
50

John S.

Bonus B
100

Alex G.

7000

Alex G.

Bonus C
150

Alex G.

Bonus D
300

Sub TransformTable()

' Setting variables
Dim Name As String
Dim BaseSalary As String
Dim BonusName As String
Dim BonusAmount As Double

'Setting worksheet object
Dim SheetData As Worksheet
Set SheetData = Sheets("SheetData")

'counter for main loop
Dim x As Long

'Setting main object array
Dim MyArray As Variant

Dim Item As Integer
    Item = 1

'reading values from table
    MyArray = Worksheets("SheetData").ListObjects("Table1").DataBodyRange.Value

'counting last row value

'main loop
    For x = LBound(MyArray) To UBound(MyArray)

'condition check how many costcenter ids with fixed value
     lstRowSrs = SheetData.Cells(Rows.Count, 1).End(xlUp).Row
     Worksheets("SheetData").Cells(Item + 1, 13).Value = MyArray(x, 1)
     Worksheets("SheetData").Cells(Item + 1, 14).Value = MyArray(x, 2)

    If MyArray(x, 3) <> "" Then

    ' Cells(x, lstRowSrs).EntireRow.Insert

     Worksheets("SheetData").Cells(Item + 2, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 2, 16).Value = MyArray(x, 4)
     Item = Item + 1

    Else
     Worksheets("SheetData").Cells(Item + 1, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 1, 16).Value = MyArray(x, 4)

      Item = Item + 1
    End If
    Next x

End Sub

Body:
Here's another way. It has the same results as @Sgdva but uses some slightly different techniques. Not better, just something to consider.

Sub TransformTable()

    Dim vaValues As Variant
    Dim i As Long
    Dim aOutput() As Variant
    Dim lCnt As Long

    'put all the values in a 2-d array
    vaValues = Sheet1.ListObjects(1).DataBodyRange
    'make your output array - double the rows of the input
    'it will be too many rows, but you won't run out of room
    ReDim aOutput(1 To UBound(vaValues, 1) * 2, 1 To 4)

    'Loop through the 2-d array
    For i = LBound(vaValues, 1) To UBound(vaValues, 1)
        If Len(vaValues(i, 2)) > 0 Then 'a salary exists
            'add a row to the output array
            lCnt = lCnt + 1
            aOutput(lCnt, 1) = vaValues(i, 1)
            aOutput(lCnt, 4) = vaValues(i, 2)
        End If

        If Len(vaValues(i, 4)) > 0 Then 'a bonus exists
            'add a row to the output array
            lCnt = lCnt + 1
            aOutput(lCnt, 1) = vaValues(i, 1)
            aOutput(lCnt, 3) = vaValues(i, 3)
            aOutput(lCnt, 4) = vaValues(i, 4)
        End If
    Next i

    'write out the output array in one shot
    Sheet1.Range("G1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput

End Sub