问:
How to configure Application Insights sampling on Net Core HostBuilder?
I'm building .Net Core background service, using ApplicationInsights.WorkerService nuget package. The documentation regarding sampling configuration says to refer to this:
https://learn.microsoft.com/en-us/azure/azure-monitor/app/sampling#configure-sampling-settings

And it shows this:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
{
  var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
  // For older versions of the Application Insights SDK, use the following line instead:
  // var builder = configuration.TelemetryProcessorChainBuilder;

  // Using adaptive sampling
  builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5);

  // Alternately, the following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling.
  // builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");

  // If you have other telemetry processors:
  builder.Use((next) => new AnotherProcessor(next));

  builder.Build();

  // ...
}
</code>```

Now on HostBuilder I don't see any extension methods that would give me the TelemetryConfiguration, source code of the nuget doesn't have it either:
https://github.com/microsoft/ApplicationInsights-aspnetcore/blob/develop/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/ApplicationInsightsExtensions.cs

So how do I get either TelemetryConfiguration or TelemetryProcessorChainBuilder on a HostBuilder? At the moment it looks like this:

```<code>Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                    services.AddApplicationInsightsTelemetryWorkerService();
                });
</code>```

答:
You should use it as below:</p>

```<code>Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();

                    services.Configure<TelemetryConfiguration>((config)=>
                    {
                        var builder = config.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

                        builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond: 5);
                        builder.Build();
                    }
                    );

                   // Your other code
                });
</code>```

Body:
I'm building .Net Core background service, using ApplicationInsights.WorkerService nuget package. The documentation regarding sampling configuration says to refer to this:
https://learn.microsoft.com/en-us/azure/azure-monitor/app/sampling#configure-sampling-settings

And it shows this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
{
  var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder;
  // For older versions of the Application Insights SDK, use the following line instead:
  // var builder = configuration.TelemetryProcessorChainBuilder;

  // Using adaptive sampling
  builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5);

  // Alternately, the following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling.
  // builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");

  // If you have other telemetry processors:
  builder.Use((next) => new AnotherProcessor(next));

  builder.Build();

  // ...
}

Now on HostBuilder I don't see any extension methods that would give me the TelemetryConfiguration, source code of the nuget doesn't have it either:
https://github.com/microsoft/ApplicationInsights-aspnetcore/blob/develop/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/ApplicationInsightsExtensions.cs

So how do I get either TelemetryConfiguration or TelemetryProcessorChainBuilder on a HostBuilder? At the moment it looks like this:

Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                    services.AddApplicationInsightsTelemetryWorkerService();
                });

Body:
You should use it as below:

Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();

                    services.Configure<TelemetryConfiguration>((config)=>
                    {
                        var builder = config.DefaultTelemetrySink.TelemetryProcessorChainBuilder;

                        builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond: 5);
                        builder.Build();
                    }
                    );

                   // Your other code
                });


来源: stackexchange

问:
Replace two input text values with values from each other on button click
I  have an html form with two input fields, in first one user puts name of first town, and in other second town, after form is submitted users gets directions how to go from first town to second town.

I want to enable user to click button "Change directions" and to automatically change first town name into second and second town name into first and vise versa. ( A to B, B to A)

I guess i'm supposed to use javascript, but I'm new at it and can't get a clue anywhere.

Can anyone help me please?

```<code>input type="text" size="25" id="fromAddress" name="from"
 value=""/>
  <input name="submit1" type="submit" value="Change directions" />
<input type="text" size="25" id="toAddress" name="to"
 value="" />
<input name="submit" type="submit" value="OK" />
</code>```

答:
Below is the sample code of what you want to achieve enjoy :)

```<code>        function swap1() {
            var data1 = document.getElementById("fromAddress").value;
            var data2 = document.getElementById("toAddress").value;
            document.getElementById("fromAddress").value = data2;
            document.getElementById("toAddress").value = data1;
            document.getElementById("swap_button").onclcik = function () {swap2()};
        }

        function swap2() {
            var data1 = document.getElementById("toAddress").value;
            var data2 = document.getElementById("fromAddress").value;
            document.getElementById("toAddress").value = data2;
            document.getElementById("toAddress").value = data1;
            document.getElementById("swap_button").onclcik = function () {swap2()};
        }

    <input type="text" size="25" id="fromAddress" name="from" value=""/>
    <input id="swap_button" type="button" value="Change directions" onclick="swap1()" />
    <input type="text" size="25" id="toAddress" name="to" value="" />
    <input name="submit" type="submit" value="OK" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I  have an html form with two input fields, in first one user puts name of first town, and in other second town, after form is submitted users gets directions how to go from first town to second town.

I want to enable user to click button "Change directions" and to automatically change first town name into second and second town name into first and vise versa. ( A to B, B to A)

I guess i'm supposed to use javascript, but I'm new at it and can't get a clue anywhere.

Can anyone help me please?

input type="text" size="25" id="fromAddress" name="from"
 value=""/>
  <input name="submit1" type="submit" value="Change directions" />
<input type="text" size="25" id="toAddress" name="to"
 value="" />
<input name="submit" type="submit" value="OK" />

Body:
Below is the sample code of what you want to achieve enjoy :)

        function swap1() {
            var data1 = document.getElementById("fromAddress").value;
            var data2 = document.getElementById("toAddress").value;
            document.getElementById("fromAddress").value = data2;
            document.getElementById("toAddress").value = data1;
            document.getElementById("swap_button").onclcik = function () {swap2()};
        }

        function swap2() {
            var data1 = document.getElementById("toAddress").value;
            var data2 = document.getElementById("fromAddress").value;
            document.getElementById("toAddress").value = data2;
            document.getElementById("toAddress").value = data1;
            document.getElementById("swap_button").onclcik = function () {swap2()};
        }

    <input type="text" size="25" id="fromAddress" name="from" value=""/>
    <input id="swap_button" type="button" value="Change directions" onclick="swap1()" />
    <input type="text" size="25" id="toAddress" name="to" value="" />
    <input name="submit" type="submit" value="OK" />


问:
Expression overflow
```<code>#include <stdio.h>
int main(void)
{
    char a, b;
    int c;

    b = 2;
    a = 127;
    c = a + b;
    printf("%d", c);
}
</code>```

i thought the value of the c should be -127 ,but actually when i run this test,the value is 129.

according to an example from <<c pragramming:a morden approach>>,

```<code>long int i;
int j=1000;

i=j*j;  /*overflow may occur,correct writing is i=(long)i*i;
</code>```

here is the explain of the book--When two int type values are multiplied, the result should also be int, but the result of j * j is too large to be consistent and cannot be expressed as int on some machines, resulting in overflow.

so i think in my test,the type of (a+b) is char,because 129>127..char cannot express 129, which will cause overflow.
i am very confused

答:
What happens in the first piece of code is the result of integer promotions.  This means that any integer value with a type smaller than int (like char or short) is first promoted to type int before being used in an expression.

In this case:

```<code> c = a + b;
</code>```

a and b both have type char, and their values are both promoted to int.  So what is being added is the int value 2 and the int value 127 which is 129.

The difference between the first piece of code and the second piece of code is that no promotion happens in the second case.  The variable j already has type int so the value is not promoted.  Casting one of the arguments to long causes the multiplication to happen with type long.

ContentLicense: CC BY-SA 4.0

Title: Expression overflow

Body:
#include <stdio.h>
int main(void)
{
    char a, b;
    int c;

    b = 2;
    a = 127;
    c = a + b;
    printf("%d", c);
}

i thought the value of the c should be -127 ,but actually when i run this test,the value is 129.

according to an example from <<c pragramming:a morden approach>>,

long int i;
int j=1000;

i=j*j;  /*overflow may occur,correct writing is i=(long)i*i;

here is the explain of the book--When two int type values are multiplied, the result should also be int, but the result of j * j is too large to be consistent and cannot be expressed as int on some machines, resulting in overflow.

so i think in my test,the type of (a+b) is char,because 129>127..char cannot express 129, which will cause overflow.
i am very confused

Body:
What happens in the first piece of code is the result of integer promotions.  This means that any integer value with a type smaller than int (like char or short) is first promoted to type int before being used in an expression.

In this case:

 c = a + b;

a and b both have type char, and their values are both promoted to int.  So what is being added is the int value 2 and the int value 127 which is 129.

The difference between the first piece of code and the second piece of code is that no promotion happens in the second case.  The variable j already has type int so the value is not promoted.  Casting one of the arguments to long causes the multiplication to happen with type long.


问:
cannot find particular movie in a list vue and laravel
I am trying to get the details of a particular movie in a list of movies but it cannot get the particular id.

here is my Vue component:

<template>

        <el-row :gutter="10">
            <el-col :span="6" v-for="movie in movies" v-bind:key="movie">
                <el-card shadow="always" :body-style="{ padding: '0px'} ">

                            {{movie.title}}

{{ movie.year }}

{{ movie.type }}

                            <el-rate v-model="value1" :max="10"></el-rate>

                </el-card>
            </el-col>

        </el-row>

</template>

```

<p>my show method:</p>

```

     public function show($id)
    {
    $movie=Movie::find($id);
    if($movie){
    return response()->json(['status'=>true,'movie'=>$movie]);
    }else{
    return response()->json(['status'=>false]);
    }
    }

```

<p>and my route:</p>

<pre class="lang-php prettyprint-override"><code>Route::get('/movies/{id}', 'MoviesController@show');
</code>```

It cannot find the movie with the particular id. What could be wrong? When I visit the API URL directly on the browser and directly type the route I get the particular movie I want.

答:
Not sure if this would resolve all your issues but you could try the following:

Route::get('/movies/{movie}', 'MoviesController@show');
```

<pre class="lang-php prettyprint-override"><code>public function show(Movie $movie)
{
    return view('details', ['movie' => $movie]);
}
</code>```

Also, the naming convention for controllers is to use the model name in its singular form. Your controller should therefore be named MovieController without s.

Another thing, in your view component you should include the movie_id in the url otherwise Laravel has no way to know which movie you're trying to fetch:

...
axios.get('/movies/1')
...
```

Body:
I am trying to get the details of a particular movie in a list of movies but it cannot get the particular id.

here is my Vue component:

<template>

        <el-row :gutter="10">
            <el-col :span="6" v-for="movie in movies" v-bind:key="movie">
                <el-card shadow="always" :body-style="{ padding: '0px'} ">

                            {{movie.title}}

{{ movie.year }}

{{ movie.type }}

                            <el-rate v-model="value1" :max="10"></el-rate>

                </el-card>
            </el-col>

        </el-row>

</template>

my show method:

     public function show($id)
    {
    $movie=Movie::find($id);
    if($movie){
    return response()->json(['status'=>true,'movie'=>$movie]);
    }else{
    return response()->json(['status'=>false]);
    }
    }

and my route:

Route::get('/movies/{id}', 'MoviesController@show');

It cannot find the movie with the particular id. What could be wrong? When I visit the API URL directly on the browser and directly type the route I get the particular movie I want.

Body:
Not sure if this would resolve all your issues but you could try the following:

Route::get('/movies/{movie}', 'MoviesController@show');

public function show(Movie $movie)
{
    return view('details', ['movie' => $movie]);
}

Also, the naming convention for controllers is to use the model name in its singular form. Your controller should therefore be named MovieController without s.

Another thing, in your view component you should include the movie_id in the url otherwise Laravel has no way to know which movie you're trying to fetch:

...
axios.get('/movies/1')
...


问:
tag helpers is wrong route link using net core 3.1 LTS
I use ASP.NET Core 3.1 LTS and route setting like this

```<code>app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "Backend",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}");

                 endpoints.MapRazorPages();
            });
</code>```

and my areas razor page have a tag helper

```<code><a class="btn btn-primary btn-sm" asp-area="Backend" asp-controller="Article" asp-action="Create"> Create</a>
</code>```

usually this link will be /backend/article/create

but result is /article/create?area=backend

why result is wrong ?

答:
The registering order of routes matters.

```
app.UseEndpoints(endpoints =>
{
    <b>// register this route before the default one</b>
    endpoints.MapControllerRoute(
        name: "Backend",
        pattern: "{area:exists}/{controller=Home}/{action=Index}");
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
     endpoints.MapRazorPages();
});
```

Make sure the area of Backend exists. Otherwise, it will be treated as querystring. For example, if you have already had an Area of Backend(Need to use the standard Area Folder Structure + Namespace, and annotate the controller with [Area("Backend")], see official docs)

[Area("Backend")]      // important
public class ArticleController : Controller
{
    public IActionResult Create(){ ...}
```

<p>then the following code </p>

``` Create
 Create
```

<p>will generate routes as below:</p>

``` Create
 Create
```

Note we specify an parameter of area=AnAreaThatDoesnotExist which doesn't exist at all and then the area=AnAreaThatDoesnotExist will be used as query string.

Body:
I use ASP.NET Core 3.1 LTS and route setting like this

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "Backend",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}");

                 endpoints.MapRazorPages();
            });

and my areas razor page have a tag helper

 Create

usually this link will be /backend/article/create

but result is /article/create?area=backend

why result is wrong ?

Body:
The registering order of routes matters.

app.UseEndpoints(endpoints =>
{
    // register this route before the default one
    endpoints.MapControllerRoute(
        name: "Backend",
        pattern: "{area:exists}/{controller=Home}/{action=Index}");
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
     endpoints.MapRazorPages();
});

Make sure the area of Backend exists. Otherwise, it will be treated as querystring. For example, if you have already had an Area of Backend(Need to use the standard Area Folder Structure + Namespace, and annotate the controller with [Area("Backend")], see official docs)

[Area("Backend")]      // important
public class ArticleController : Controller
{
    public IActionResult Create(){ ...}

then the following code

<a asp-area="Backend" asp-controller="Article" asp-action="Create"> Create</a>
<a asp-area="AnAreaThatDoesnotExist" asp-controller="Article" asp-action="Create"> Create</a>

will generate routes as below:

<a href="/Backend/Article/Create"> Create</a>
<a href="/Article/Create?area=AnAreaThatDoesnotExist"> Create</a>

Note we specify an parameter of area=AnAreaThatDoesnotExist which doesn't exist at all and then the area=AnAreaThatDoesnotExist will be used as query string.


问:
How to read comma separated data set using scanf_s - C Programming
I don't have a working code I can share right now, but basically what I am trying to achieve is to read a user input or from a file in the following format:

```<code>1,2
2,5
3,4
4,5
etc...
</code>```

or

1,3 4,5 6,7 8,6 ...
So a comma separated pair of real numbers and I would need to assign them to an array or 2d array and calculate their means, median, mode etc...

I tried scanf_s("%d,",&n) and stuff like that but none of them have worked out so far. I am really new to C and came from Java so everything been very confusing. If any tips or just an example would be greatly appreciated. I know you can also use fgets, gets or sscanf, however I have not learned those yet.

This was a code sent by another user:(but i don't really understand it, because it gave me src could be 0 error)

```<code>#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;

  while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}
</code>```

答:
There are (at least) two main solutions.  One is to continue to read numbers singly, so you really aren't too bothered by whether there are commas are present or not; the other is to read the numbers in pairs.

Option A involves a minor tweak to the format string from "%d,%n" to "%d %n" so you find out where the number ends (more precisely, where the first character that's not white space appears after the number), and skip the comma separately in a loop:

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

int main(void)
{
    char data[500];
    char *src = data;
    fgets(src, 500, stdin);
    int arr[500];
    int index = 0;
    int n;

    while (sscanf(src, "%d %n", &arr[index], &n) == 1)
    {
        printf("%d\n", arr[index++]);
        src += n;
        if (*src == ',')
        {
            putchar('=');
            src++;
        }
    }
    return 0;
}
</code>```

The putchar('=') lets me see when the comma is skipped; it wouldn't be present in 'production' code.

Sample output (Bash Here String notation):

```<code>$ read41 <<< '1,2  3,4   5,6   7, 8   9,10, 11 , 12xyz'
1
=2
3
=4
5
=6
7
=8
9
=10
=11
=12
$
</code>```

Be cautious — a trailing blank in a scanf() format is devasting for interactive input, but harmless for sscanf().  Note that there is a stray comma after 10 in the data, but this version of the code doesn't care about that.  It also doesn't care about where newlines appear in pairs (or it wouldn't if it iterated on while (fgets(data, sizeof(data), stdin) != 0) { char *src = data; … }).

Option B involves reading numbers in pairs.  Since you're using sscanf() in a loop, you still need the %n conversion specification.  The second space in the format string (after the comma) isn't strictly necessary (the %d will skip white space too), but it is harmless and symmetric.  This demands that there is one comma between pairs of numbers which must be on the same line (but allows spaces, or no spaces, around the comma), and pairs must appear on the same line.

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

int main(void)
{
    char data[500];
    int arr[500];
    int index = 0;

    while (fgets(data, sizeof(data), stdin) != 0)
    {
        int n;
        char *src = data;
        while (sscanf(src, "%d , %d %n", &arr[index + 0], &arr[index + 1], &n) == 2)
        {
            printf("(%d,%d)\n", arr[index + 0], arr[index + 1]);
            src += n;
            index += 2;
        }
    }
    return 0;
}
</code>```

Sample output (using Bash ANSI-C Quoting too):

```<code>$ read43 <<< $'1,2  3,4   5,6   7,8\n9,10 11 , 12xyz'
(1,2)
(3,4)
(5,6)
(7,8)
(9,10)
(11,12)
$
</code>```

Body:
I don't have a working code I can share right now, but basically what I am trying to achieve is to read a user input or from a file in the following format:

1,2
2,5
3,4
4,5
etc...

or

1,3 4,5 6,7 8,6 ...
So a comma separated pair of real numbers and I would need to assign them to an array or 2d array and calculate their means, median, mode etc...

I tried scanf_s("%d,",&n) and stuff like that but none of them have worked out so far. I am really new to C and came from Java so everything been very confusing. If any tips or just an example would be greatly appreciated. I know you can also use fgets, gets or sscanf, however I have not learned those yet.

This was a code sent by another user:(but i don't really understand it, because it gave me src could be 0 error)

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;

  while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}

Body:
There are (at least) two main solutions.  One is to continue to read numbers singly, so you really aren't too bothered by whether there are commas are present or not; the other is to read the numbers in pairs.

Option A involves a minor tweak to the format string from "%d,%n" to "%d %n" so you find out where the number ends (more precisely, where the first character that's not white space appears after the number), and skip the comma separately in a loop:

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

int main(void)
{
    char data[500];
    char *src = data;
    fgets(src, 500, stdin);
    int arr[500];
    int index = 0;
    int n;

    while (sscanf(src, "%d %n", &arr[index], &n) == 1)
    {
        printf("%d\n", arr[index++]);
        src += n;
        if (*src == ',')
        {
            putchar('=');
            src++;
        }
    }
    return 0;
}

The putchar('=') lets me see when the comma is skipped; it wouldn't be present in 'production' code.

Sample output (Bash Here String notation):

$ read41 <<< '1,2  3,4   5,6   7, 8   9,10, 11 , 12xyz'
1
=2
3
=4
5
=6
7
=8
9
=10
=11
=12
$

Be cautious — a trailing blank in a scanf() format is devasting for interactive input, but harmless for sscanf().  Note that there is a stray comma after 10 in the data, but this version of the code doesn't care about that.  It also doesn't care about where newlines appear in pairs (or it wouldn't if it iterated on while (fgets(data, sizeof(data), stdin) != 0) { char *src = data; … }).

Option B involves reading numbers in pairs.  Since you're using sscanf() in a loop, you still need the %n conversion specification.  The second space in the format string (after the comma) isn't strictly necessary (the %d will skip white space too), but it is harmless and symmetric.  This demands that there is one comma between pairs of numbers which must be on the same line (but allows spaces, or no spaces, around the comma), and pairs must appear on the same line.

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

int main(void)
{
    char data[500];
    int arr[500];
    int index = 0;

    while (fgets(data, sizeof(data), stdin) != 0)
    {
        int n;
        char *src = data;
        while (sscanf(src, "%d , %d %n", &arr[index + 0], &arr[index + 1], &n) == 2)
        {
            printf("(%d,%d)\n", arr[index + 0], arr[index + 1]);
            src += n;
            index += 2;
        }
    }
    return 0;
}

Sample output (using Bash ANSI-C Quoting too):

$ read43 <<< $'1,2  3,4   5,6   7,8\n9,10 11 , 12xyz'
(1,2)
(3,4)
(5,6)
(7,8)
(9,10)
(11,12)
$


问:
Do methods take up space in the class instance on javascript?
 Similar questions for other languages.

Consider a simple class:

```<code>class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}
</code>```

For each instance of this class, in javascript, will be consumed memory for a reference for bar method?

If I add other methods in Foo class, the instance of it will be heavier on memory?

If I need to create a lot of Foo objects, should I write:

```<code>function Foo(value) {
  this.a = value;
}

function bar(fooInstance) {
  console.log(fooInstance.a);
}
</code>```

The questions above only illustrate the same question:

Do methods take up space in the class instance?

答:
Class methods are properties of the class prototype object, not each instance. Each instance just has a reference to its prototype, and the prototype has a reference to its parent class prototype, and so on.

Properties are found by searching the prototype chain; this is how inheritance works in JavaScript.

Body:
 Similar questions for other languages.

Consider a simple class:

class Foo {
  a;

  constructor(value) {
    this.a = value;
  }

  bar() {
    console.log(this.a);
  }
}

For each instance of this class, in javascript, will be consumed memory for a reference for bar method?

If I add other methods in Foo class, the instance of it will be heavier on memory?

If I need to create a lot of Foo objects, should I write:

function Foo(value) {
  this.a = value;
}

function bar(fooInstance) {
  console.log(fooInstance.a);
}

The questions above only illustrate the same question:

Do methods take up space in the class instance?


问:
How to prevent auto-generated 'T' letter when parsing String to LocalDateTime using DateTimeFormatterBuilder
I have this fragment of code to bidirectional parsing String to LocalDateTime:

```<code>public class ConvertLocalDateToString {

private static final DateTimeFormatter CUSTOM_LOCAL_DATE;
static {
    CUSTOM_LOCAL_DATE = new DateTimeFormatterBuilder()
            .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
            .appendLiteral('-')
            .appendValue(MONTH_OF_YEAR, 2)
            .appendLiteral('-')
            .appendValue(DAY_OF_MONTH, 2)
            .appendLiteral(' ')
            .appendValue(HOUR_OF_DAY, 2)
            .appendLiteral(':')
            .appendValue(MINUTE_OF_HOUR, 2)
            .optionalStart()
            .appendLiteral(':')
            .appendValue(SECOND_OF_MINUTE, 2)
            .toFormatter();
}

public static void main(String[] args) {

    String str = "2020-02-18 15:04:30";
    LocalDateTime dateTime = LocalDateTime.parse(str, CUSTOM_LOCAL_DATE); //2020-02-18T15:04:30

    LocalDateTime addedDateTime = LocalDateTime.parse(dateTime.plusHours(10).format(CUSTOM_LOCAL_DATE.withZone(ZoneOffset.UTC)));
    System.out.println(addedDateTime);
    System.out.println(dateTime); //2020-02-18T15:04:30

}
</code>```

My assumption is 'T' letter is auto-generated by ISO-8601 format. This caused:

DateTimeParseException: Text '2020-02-18 15:04:30' could not be parsed at index 10

How do I get rid of it?

答:
System.out.println(dateTime) is the same as System.out.println(String.valueOf(dateTime)).

String.valueOf(dateTime) is the same as dateTime.toString(), except it can handle null value.

Calling toString() on a LocalDateTime is documented to do this:

Outputs this date-time as a String, such as 2007-12-03T10:15:30.

The output will be one of the following ISO-8601 formats:

uuuu-MM-dd'T'HH:mm

uuuu-MM-dd'T'HH:mm:ss

uuuu-MM-dd'T'HH:mm:ss.SSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

If you want different format, call format(DateTimeFormatter formatter).

So, to answer your questions:

My assumption is 'T' letter is auto-generated by ISO-8601 format.

The T is no more auto-generated than the - and : characters.

How do I get rid of it?

Call format(...) and specify the format you want, e.g.

```<code>System.out.println(dateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")));
</code>```

Body:
I have this fragment of code to bidirectional parsing String to LocalDateTime:

public class ConvertLocalDateToString {

private static final DateTimeFormatter CUSTOM_LOCAL_DATE;
static {
    CUSTOM_LOCAL_DATE = new DateTimeFormatterBuilder()
            .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
            .appendLiteral('-')
            .appendValue(MONTH_OF_YEAR, 2)
            .appendLiteral('-')
            .appendValue(DAY_OF_MONTH, 2)
            .appendLiteral(' ')
            .appendValue(HOUR_OF_DAY, 2)
            .appendLiteral(':')
            .appendValue(MINUTE_OF_HOUR, 2)
            .optionalStart()
            .appendLiteral(':')
            .appendValue(SECOND_OF_MINUTE, 2)
            .toFormatter();
}

public static void main(String[] args) {

    String str = "2020-02-18 15:04:30";
    LocalDateTime dateTime = LocalDateTime.parse(str, CUSTOM_LOCAL_DATE); //2020-02-18T15:04:30

    LocalDateTime addedDateTime = LocalDateTime.parse(dateTime.plusHours(10).format(CUSTOM_LOCAL_DATE.withZone(ZoneOffset.UTC)));
    System.out.println(addedDateTime);
    System.out.println(dateTime); //2020-02-18T15:04:30

}

My assumption is 'T' letter is auto-generated by ISO-8601 format. This caused:

DateTimeParseException: Text '2020-02-18 15:04:30' could not be parsed at index 10

How do I get rid of it?

Body:
System.out.println(dateTime) is the same as System.out.println(String.valueOf(dateTime)).

String.valueOf(dateTime) is the same as dateTime.toString(), except it can handle null value.

Calling toString() on a LocalDateTime is documented to do this:

Outputs this date-time as a String, such as 2007-12-03T10:15:30.

The output will be one of the following ISO-8601 formats:

uuuu-MM-dd'T'HH:mm

uuuu-MM-dd'T'HH:mm:ss

uuuu-MM-dd'T'HH:mm:ss.SSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

If you want different format, call format(DateTimeFormatter formatter).

So, to answer your questions:

My assumption is 'T' letter is auto-generated by ISO-8601 format.

The T is no more auto-generated than the - and : characters.

How do I get rid of it?

Call format(...) and specify the format you want, e.g.

System.out.println(dateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")));


问:
Is const T& rf = lvalue of T an identity conversion?
```<code>T t;
const T& rf = t; // #1
</code>```

Consider the initialization #1 shown above.  Is it an identity conversion?  In other words, does rf bind directly to the initializer expression?  If not that, how many standard conversions does #1 have and what are these conversion named?

答:
It is an identity conversion.  [over.ics.ref]/1:

When a parameter of reference type binds directly to an argument expression, the implicit conversion sequence is the identity
  conversion, unless the argument expression has a type that is a
  derived class of the parameter type, in which case the implicit
  conversion sequence is a derived-to-base Conversion ([over.best.ics]).
  [...] If the parameter binds directly to the result of applying a
  conversion function to the argument expression, the implicit
  conversion sequence is a user-defined conversion sequence, with the
  second standard conversion sequence either an identity conversion or,
  if the conversion function returns an entity of a type that is a
  derived class of the parameter type, a derived-to-base Conversion.

(emphasis mine)

In your case, the argument type is the same as the parameter type, so the argument type neither derives from the parameter type nor requires a user-defined conversion function.

Body:
T t;
const T& rf = t; // #1

Consider the initialization #1 shown above.  Is it an identity conversion?  In other words, does rf bind directly to the initializer expression?  If not that, how many standard conversions does #1 have and what are these conversion named?


问:
Scrolling content with negative margins
I have generated XAML file from Windows Forms, and with the process calculated right and bottom margins because they do not exist in Forms. I have this output:

```<code><Grid>
    <TextBox Width="129" Height="18" Margin="36,46,278,686" />
    ...
    <TextBox Width="54" Height="18" Margin="345,705,83,31" />
    <TextBox Width="54" Height="18" Margin="345,728,83,8" />
    <TextBox Width="54" Height="18" Margin="345,770,83,-34" />
    ...
</Grid>
</code>```

The problem is that Content of Grid is too large, even for the designer, so scroll bar is generated in win forms. However, this is not case in WPF, so I try adding ScrollViewer around it. But it only scrolls down to content with positive bottom margin. Controls with negative margins are not shown anywhere.

Any idea how to solve this is appreciated.

答:
The Grid is the wrong thing for this task. If you're going to do the positioning yourself, you should use a Canvas and then use Canvas.Left and Canvas.Top to position it. You don't need the Bottom or Right values since you seem to know the Width and Height.

I believe you should be able to use the ScrollViewer around the Canvas object too.

Title: Scrolling content with negative margins

Body:
I have generated XAML file from Windows Forms, and with the process calculated right and bottom margins because they do not exist in Forms. I have this output:

<Grid>
    <TextBox Width="129" Height="18" Margin="36,46,278,686" />
    ...
    <TextBox Width="54" Height="18" Margin="345,705,83,31" />
    <TextBox Width="54" Height="18" Margin="345,728,83,8" />
    <TextBox Width="54" Height="18" Margin="345,770,83,-34" />
    ...
</Grid>

The problem is that Content of Grid is too large, even for the designer, so scroll bar is generated in win forms. However, this is not case in WPF, so I try adding ScrollViewer around it. But it only scrolls down to content with positive bottom margin. Controls with negative margins are not shown anywhere.

Any idea how to solve this is appreciated.


问:
Connecting to Multiple "Dynamic" Databases Along With Local "Static" Database in Spring Boot
I'm building an application using Java and Spring Boot where I want to query two foreign databases (they might have different schemas and data) every time I run. Therefore I'd like to query two different databases every time. After accessing those databases, I would then like to store the result (my business logic) on a local static database.

I originally wanted to store all the database data (user, pass, url) in the application.properties, but then realized that this might not be best practice as the details for the two DBs I'm querying will be received as input from the user. Therefore, I'm not sure if it's the best idea to update and overwrite application.properties every time I receive a new request (please let me know if there's a better way to do this.

Assuming I have the DBs info in application.properties, I've followed multiple tutorials for multiple DB connections in Spring, and they all followed something along the lines of making configuration files for each DB, calling a repository/DAO file for each DB, which references a model of said DB. That seems a bit problematic for me as I don't know the schema of the databases before hand, so I can't define a model class. And even if I did, this will probably change across databases, so I'm really not sure what to do.
Is there a more flexible/versatile way to query "foreign" databases with Spring or old school Java given that I don't know what their schemas might look like?

Any help is greatly appreciated!

答:
Multiple databases config have to be maintained in application.properties or config class as a best practice. Refer here - https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources

You can have a POJO with DB properties which gets assigned from user provided values. Use that POJO in a DB config class to connect to different databases.

Not knowing schema is not a problem as you can handle data with java collections.


问:
Why does option refuse to append to select element?
I'm trying to append an option to a select element from a function that is fired when a button is clicked but it isn't working. What am I doing wrong? It almost seems as if the element does not exist, because even empty() does not work. But if I check for its existence and show an alert, it returns that the element does exist. Here's my code.

function Add(ID) {
  var text = "";
  if (ID == "1") {
    text = "January";
  } else
  if (ID == "2") {
    text = "February"
  } else
  if (ID == "3") {
    text = "March";
  }
  $("#Month").append($("<option></option>").val(ID).html(text));
}
Add(1);
Add(3);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month"></select></code>```

答:
Hope this help you.

function Add(ID) {
  var text = "";
  if (ID == "1") {
    text = "January";
  } else
  if (ID == "2") {
    text = "February"
  } else
  if (ID == "3") {
    text = "March";
  }
  var optionExists = ($("#Month option[value=" + ID + "]").length > 0);
  if (optionExists == true) {
    console.log('Already Exist=>' + ID);
    return;
  }

  $("#Month").append($("<option></option>").val(ID).html(text));
}
Add(1);
Add(3);
Add(3);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month"></select></code>```

Body:
I'm trying to append an option to a select element from a function that is fired when a button is clicked but it isn't working. What am I doing wrong? It almost seems as if the element does not exist, because even empty() does not work. But if I check for its existence and show an alert, it returns that the element does exist. Here's my code.

function Add(ID) {
  var text = "";
  if (ID == "1") {
    text = "January";
  } else
  if (ID == "2") {
    text = "February"
  } else
  if (ID == "3") {
    text = "March";
  }
  $("#Month").append($("<option></option>").val(ID).html(text));
}
Add(1);
Add(3);

<select id="Month"></select>

Body:
Hope this help you.

function Add(ID) {
  var text = "";
  if (ID == "1") {
    text = "January";
  } else
  if (ID == "2") {
    text = "February"
  } else
  if (ID == "3") {
    text = "March";
  }
  var optionExists = ($("#Month option[value=" + ID + "]").length > 0);
  if (optionExists == true) {
    console.log('Already Exist=>' + ID);
    return;
  }

  $("#Month").append($("<option></option>").val(ID).html(text));
}
Add(1);
Add(3);
Add(3);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month"></select>


问:
Strange interaction between print and the ternary conditional operator
Ran into a strange interaction between print and the ternary conditional operator that I don't understand. If we do...:

print 'foo, ' . (1 ? 'yes' : 'no') . ' bar';

...then we get the output...:

foo, yes bar

...as we would expect. However, if we do...:

print (1 ? 'yes' : 'no') . ' bar';

...then we just get the output...:

yes

Why isn't " bar" getting appended to the output in the second case?

答:
Let's do it, but for real -- that is, with warnings on

```<code>perl -we'print (1 ? "yes" : "no") . " bar"'
</code>```

It prints

```
print (...) interpreted as function at -e line 1.
Useless use of concatenation (.) or string in void context at -e line 1.
yes
```

(but no newline at the end)

So since (1 ? "yes" : "no") is taken as the argument list for the print function then the ternary is evaluated to yes and that is the argument for print and so that, alone, is printed. As this is a known "gotcha," which can easily be done in error, we are kindly given a warning for it.

Then the string " bar" is concatenated (to the return value of print which is 1), what is meaningless in void context, and for what we also get a warning.

One workaround is to prepend a +, forcing the interpretation of () as an expression

```<code>perl -we'print +(1 ? "yes" : "no") . " bar", "\n"'
</code>```

Or, call the print as function properly, with full parenthesis

```<code>perl -we'print( (1 ? "yes" : "no") . " bar", "\n" )'
</code>```

where I've added the newline in both cases.

See this post for a detailed discussion of a related example and precise documentation links.

Body:
Let's do it, but for real -- that is, with warnings on

perl -we'print (1 ? "yes" : "no") . " bar"'

It prints

print (...) interpreted as function at -e line 1.
Useless use of concatenation (.) or string in void context at -e line 1.
yes

(but no newline at the end)

So since (1 ? "yes" : "no") is taken as the argument list for the print function then the ternary is evaluated to yes and that is the argument for print and so that, alone, is printed. As this is a known "gotcha," which can easily be done in error, we are kindly given a warning for it.

Then the string " bar" is concatenated (to the return value of print which is 1), what is meaningless in void context, and for what we also get a warning.

One workaround is to prepend a +, forcing the interpretation of () as an expression

perl -we'print +(1 ? "yes" : "no") . " bar", "\n"'

Or, call the print as function properly, with full parenthesis

perl -we'print( (1 ? "yes" : "no") . " bar", "\n" )'

where I've added the newline in both cases.

See this post for a detailed discussion of a related example and precise documentation links.


问:
Posting array of JSON objects to MVC3 action method via jQuery ajax
Does the model binder not suport arrays of JSON objects? The code below works when sending a single JSON domain object as part of the ajax post. However, when sending an array of JSON domain objects, the action parameter is null.

```<code>     var domains = [{
                        DomainName: 'testt1',
                        Price: '19.99',
                        Available: true
                    }, {
                        DomainName: 'testt2',
                        Price: '15.99',
                        Available: false
                    }];

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: domains,
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
            });
</code>```

This is the action method:

```<code>public ActionResult AddDomain(IEnumerable<DomainBasketItemModel> domain)
{
    ...
</code>```

Any ideas if it is possible to do this?

EDIT

@Milimetric

Your solution works! However, this is my fault, but the code I demonstrated isn't the real code of my problem, I was trying to show equivalent code that is easier to understand.

I am actually creating an array, then interating some DOM elements and pushing a JSON object onto the array, then posting this array as the data...

```<code>var domains = [];

                $(this).parents('table').find('input:checked').each(function () {
                    var domain = {
                        DomainName: $(this).parent().parent().find('.name').html(),
                        Price: $(this).parent().parent().find('.price span').html(),
                        Available: $(this).parent().parent().find('.available').html() == "Available"
                    }

                    domains.push(domain);
                });

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: { domain: domains },
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
                });
</code>```

答:
You need:

```<code>var domains = { domains: [... your elements ...]};

            $.ajax({
                type: 'post',
                url: 'Your-URI',
                data: JSON.stringify(domains),
                contentType: "application/json; charset=utf-8",
                traditional: true,
                success: function (data) {
                    ...
                }
            });
</code>```

In general, check out the Request object in the debugger, you'll see what's being passed and get an idea of how to "speak" HTTP.

NOTE: Just found this out.  The model binder chokes on nullable decimal properties like:

```<code>public decimal? latitude { get; set; }
</code>```

So it won't bind that if you're posting to it with a json string that looks like this:

```<code>{"latitude":12.0}
</code>```

But it WILL work if you post something like this:

```<code>{"latitude":"12.0"}
</code>```

See: http://syper-blogger.blogspot.com/2011/07/hello-world.html

Body:
Does the model binder not suport arrays of JSON objects? The code below works when sending a single JSON domain object as part of the ajax post. However, when sending an array of JSON domain objects, the action parameter is null.

     var domains = [{
                        DomainName: 'testt1',
                        Price: '19.99',
                        Available: true
                    }, {
                        DomainName: 'testt2',
                        Price: '15.99',
                        Available: false
                    }];

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: domains,
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
            });

This is the action method:

public ActionResult AddDomain(IEnumerable<DomainBasketItemModel> domain)
{
    ...

Any ideas if it is possible to do this?

EDIT

@Milimetric

Your solution works! However, this is my fault, but the code I demonstrated isn't the real code of my problem, I was trying to show equivalent code that is easier to understand.

I am actually creating an array, then interating some DOM elements and pushing a JSON object onto the array, then posting this array as the data...

var domains = [];

                $(this).parents('table').find('input:checked').each(function () {
                    var domain = {
                        DomainName: $(this).parent().parent().find('.name').html(),
                        Price: $(this).parent().parent().find('.price span').html(),
                        Available: $(this).parent().parent().find('.available').html() == "Available"
                    }

                    domains.push(domain);
                });

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: { domain: domains },
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
                });

Body:
You need:

var domains = { domains: [... your elements ...]};

            $.ajax({
                type: 'post',
                url: 'Your-URI',
                data: JSON.stringify(domains),
                contentType: "application/json; charset=utf-8",
                traditional: true,
                success: function (data) {
                    ...
                }
            });

In general, check out the Request object in the debugger, you'll see what's being passed and get an idea of how to "speak" HTTP.

NOTE: Just found this out.  The model binder chokes on nullable decimal properties like:

public decimal? latitude { get; set; }

So it won't bind that if you're posting to it with a json string that looks like this:

{"latitude":12.0}

But it WILL work if you post something like this:

{"latitude":"12.0"}

See: http://syper-blogger.blogspot.com/2011/07/hello-world.html


问:
How to stop SwiftUI DragGesture from dying when View content changes
In my app, I drag a View horizontally to set a position of a model object. I can also drag it downward and release it to delete the model object. When it has been dragged downward far enough, I indicate the potential for deletion by changing its appearance. The problem is that this change interrupts the DragGesture. I don't understand why this happens.

The example code below demonstrates the problem. You can drag the light blue box side to side. If you pull down, it and it turns to the "rays" system image, but the drag dies.

The DragGesture is applied to the ZStack with a size of 50x50. The ZStack should continue to exist across that state change, no? Why is the drag gesture dying?

```<code>struct ContentView: View {
    var body: some View {
        ZStack {
            DraggableThing()
        }.frame(width: 300, height: 300)
         .border(Color.black, width: 1)
    }
}

struct DraggableThing: View {

    @State private var willDeleteIfDropped = false
    @State private var xPosition: CGFloat = 150

    var body: some View {
        //Rectangle()
        //    .fill(willDeleteIfDropped ? Color.red : Color.blue.opacity(0.3))
        ZStack {
            if willDeleteIfDropped {
                Image(systemName: "rays")
            } else {
                Rectangle().fill(Color.blue.opacity(0.3))
            }
        }
            .frame(width: 50, height: 50)
            .position(x: xPosition, y: 150)
            .gesture(DragGesture()
                .onChanged { val in
                    print("drag changed \(val.translation)")
                    self.xPosition = 150 + val.translation.width
                    self.willDeleteIfDropped = (val.translation.height > 25)
                }
                .onEnded { val in
                    print("drag ended")
                    self.xPosition = 150
                }
            )
    }
}
</code>```

答:
You need to keep content, which originally captured gesture. So your goal can be achieved with the following changes:</p>

```<code>ZStack {
    Rectangle().fill(Color.blue.opacity(willDeleteIfDropped ? 0.0 : 0.3))
    if willDeleteIfDropped {
        Image(systemName: "rays")
    }
}
</code>```

Body:
In my app, I drag a View horizontally to set a position of a model object. I can also drag it downward and release it to delete the model object. When it has been dragged downward far enough, I indicate the potential for deletion by changing its appearance. The problem is that this change interrupts the DragGesture. I don't understand why this happens.

The example code below demonstrates the problem. You can drag the light blue box side to side. If you pull down, it and it turns to the "rays" system image, but the drag dies.

The DragGesture is applied to the ZStack with a size of 50x50. The ZStack should continue to exist across that state change, no? Why is the drag gesture dying?

struct ContentView: View {
    var body: some View {
        ZStack {
            DraggableThing()
        }.frame(width: 300, height: 300)
         .border(Color.black, width: 1)
    }
}

struct DraggableThing: View {

    @State private var willDeleteIfDropped = false
    @State private var xPosition: CGFloat = 150

    var body: some View {
        //Rectangle()
        //    .fill(willDeleteIfDropped ? Color.red : Color.blue.opacity(0.3))
        ZStack {
            if willDeleteIfDropped {
                Image(systemName: "rays")
            } else {
                Rectangle().fill(Color.blue.opacity(0.3))
            }
        }
            .frame(width: 50, height: 50)
            .position(x: xPosition, y: 150)
            .gesture(DragGesture()
                .onChanged { val in
                    print("drag changed \(val.translation)")
                    self.xPosition = 150 + val.translation.width
                    self.willDeleteIfDropped = (val.translation.height > 25)
                }
                .onEnded { val in
                    print("drag ended")
                    self.xPosition = 150
                }
            )
    }
}

Body:
You need to keep content, which originally captured gesture. So your goal can be achieved with the following changes:

ZStack {
    Rectangle().fill(Color.blue.opacity(willDeleteIfDropped ? 0.0 : 0.3))
    if willDeleteIfDropped {
        Image(systemName: "rays")
    }
}


问:
Is there a faster way to enter count data to a data frame in R?

For example, how do I enter these data to a data frame so that I can construct a logistic regression model.

Otherwise, I will type like this

Center<-c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1......,1)

Body:
Center<-c(rep(1,73),rep(2,52),rep(3,38),rep(4,33),rep(5,29),rep(6,21),rep(7,14),rep(8,13))

Thanks Ronak


问:
Divide and conquer algorithm to find position of max element
I am trying to find the index of the max element in an array using a divide and conquer algorithm. Currently, the output is correctly outputting the maximum value of my array, but I cannot figure out how to pass the position of that maximum element.</p>

```<code>#include <iostream>

using namespace std;

int maxElement(int a[], int l, int r) {
   if(r - l == 1) {
        cout << "R - L == 1 " <<  "Array value: " << a[l] << " Pos: " << l << endl;
        return a[l];
   }
   int m = (l + r) / 2;
   int u = maxElement(a, l, m);
   int v = maxElement(a, m, r);
   return u > v ? u : v;
}

/* Driver program to test above functions */
int main() {
    int Arr[] = {1, 4, 9, 3, 4, 9, 5, 6, 9, 3, 7};
    int arrSize = sizeof(Arr)/sizeof(Arr[0]);

    cout << maxElement(Arr, 0, arrSize) << endl;
    return 0;
}
</code>```

答:
You can return a std::pair which contains both the array value & position.

```<code>#include <iostream>
#include <utility>
using namespace std;

std::pair<int, int> maxElement(int a[], int l, int r) {
   if(r - l == 1) {
        cout << "R - L == 1 " <<  "Array value: " << a[l] << " Pos: " << l << endl;
        return {a[l], l};
   }
   int m = (l + r) / 2;
   auto up = maxElement(a, l, m);
   auto vp = maxElement(a, m, r);
   return up.first > vp.first ? up : vp;
}

/* Driver program to test above functions */
int main() {
    int Arr[] = {1, 4, 9, 3, 4, 9, 5, 6, 9, 3, 7};
    int arrSize = sizeof(Arr)/sizeof(Arr[0]);
    auto result = maxElement(Arr, 0, arrSize);
    cout << result.first << ", l = " << result.second << endl;
    return 0;
}
</code>```

Body:
I am trying to find the index of the max element in an array using a divide and conquer algorithm. Currently, the output is correctly outputting the maximum value of my array, but I cannot figure out how to pass the position of that maximum element.

#include <iostream>

using namespace std;

int maxElement(int a[], int l, int r) {
   if(r - l == 1) {
        cout << "R - L == 1 " <<  "Array value: " << a[l] << " Pos: " << l << endl;
        return a[l];
   }
   int m = (l + r) / 2;
   int u = maxElement(a, l, m);
   int v = maxElement(a, m, r);
   return u > v ? u : v;
}

/* Driver program to test above functions */
int main() {
    int Arr[] = {1, 4, 9, 3, 4, 9, 5, 6, 9, 3, 7};
    int arrSize = sizeof(Arr)/sizeof(Arr[0]);

    cout << maxElement(Arr, 0, arrSize) << endl;
    return 0;
}

Body:
You can return a std::pair which contains both the array value & position.

#include <iostream>
#include <utility>
using namespace std;

std::pair<int, int> maxElement(int a[], int l, int r) {
   if(r - l == 1) {
        cout << "R - L == 1 " <<  "Array value: " << a[l] << " Pos: " << l << endl;
        return {a[l], l};
   }
   int m = (l + r) / 2;
   auto up = maxElement(a, l, m);
   auto vp = maxElement(a, m, r);
   return up.first > vp.first ? up : vp;
}

/* Driver program to test above functions */
int main() {
    int Arr[] = {1, 4, 9, 3, 4, 9, 5, 6, 9, 3, 7};
    int arrSize = sizeof(Arr)/sizeof(Arr[0]);
    auto result = maxElement(Arr, 0, arrSize);
    cout << result.first << ", l = " << result.second << endl;
    return 0;
}


问:
Using reflection instead of a long switch statement
Hey so I have a pretty long switch statement that calls a method based on a string like so

```<code>private void callMethod(String name) {
    switch(name) {
        case "blah":
            blah();
            break;
        case "method":
            method()
            break;
    }
}
</code>```

etc.

So I used reflection to shorten the code

```<code>try {
    Method method = ClassName.class.getDeclaredMethod(name, args);
    method.invoke(args);
} catch (NoSuchMethodException e) {
    // switch default
}
</code>```

Just wondering if using reflection like this is bad on memory/performance. I only call this function every so often.

Edit: The reason I used this is because the user has the option to start a different part of the game based on the string they enter in. Each method that starts the event is named after what they need to type in.

答:
Reflection is usually the worst way to do things.  It’s slow, it can’t be optimized at runtime, and the compiler can’t flag mistakes.  And as kpie pointed out, letting user input directly control which method is executed is a security hole.

Any long switch statement can be replaced with a Map.  In your case, a Map<String, Runnable> would suffice:

```<code>Map<String, Runnable> actions = new HashMap<>();
actions.put("blah", this::blah);
actions.put("method", this::method);

// ...

Runnable action = actions.get(name);
if (action == null) {
    throw new IllegalArgumentException("Invalid name: " + name);
}
action.run();
</code>```

Body:
Hey so I have a pretty long switch statement that calls a method based on a string like so

private void callMethod(String name) {
    switch(name) {
        case "blah":
            blah();
            break;
        case "method":
            method()
            break;
    }
}

etc.

So I used reflection to shorten the code

try {
    Method method = ClassName.class.getDeclaredMethod(name, args);
    method.invoke(args);
} catch (NoSuchMethodException e) {
    // switch default
}

Just wondering if using reflection like this is bad on memory/performance. I only call this function every so often.

Edit: The reason I used this is because the user has the option to start a different part of the game based on the string they enter in. Each method that starts the event is named after what they need to type in.

Body:
Reflection is usually the worst way to do things.  It’s slow, it can’t be optimized at runtime, and the compiler can’t flag mistakes.  And as kpie pointed out, letting user input directly control which method is executed is a security hole.

Any long switch statement can be replaced with a Map.  In your case, a Map<String, Runnable> would suffice:

Map<String, Runnable> actions = new HashMap<>();
actions.put("blah", this::blah);
actions.put("method", this::method);

// ...

Runnable action = actions.get(name);
if (action == null) {
    throw new IllegalArgumentException("Invalid name: " + name);
}
action.run();


问:
Laravel unit testing assert functions always failing
I have created a very basic unit testing class under Laravel root-->tests-->Unit-->SimpleTest.php

Inside the file i have import the controller class that i need to test. And test function is like this.

```<code>class SimpleTest extends TestCase
{
   public function testLoadUsers()
   {
     $controller_obj = new UsersController;
     $data_status = $controller_obj->load_users();
        if($data_status != null){
           $this->assertTrue(true);
         }
        else{
           $this->assertTrue(false);
         }
    }

  }
</code>```

I executed this test case in Artisan console like this,

```<code>php vendor/phpunit/phpunit/phpunit tests/Unit/SimpleTest.php
</code>```

Always this fails. My controller function returning data as well without an issue. I tested without defining any condition and just,

```<code>$this->assertTrue(true);
</code>```

Then it works. So i assume there is no any issue with the phpunit test command as well.

答:
I'm sorry, this is not a direct answer.

I think maybe you should check the value of $data_status by this.

```<code>class SimpleTest extends TestCase
{
   public function testLoadUsers()
   {
     $controller_obj = new UsersController;
     $data_status = $controller_obj->load_users();
     $this->expectOutputString('Array');
     print data_status;
   }
}
</code>```

Body:
I have created a very basic unit testing class under Laravel root-->tests-->Unit-->SimpleTest.php

Inside the file i have import the controller class that i need to test. And test function is like this.

class SimpleTest extends TestCase
{
   public function testLoadUsers()
   {
     $controller_obj = new UsersController;
     $data_status = $controller_obj->load_users();
        if($data_status != null){
           $this->assertTrue(true);
         }
        else{
           $this->assertTrue(false);
         }
    }

  }

I executed this test case in Artisan console like this,

php vendor/phpunit/phpunit/phpunit tests/Unit/SimpleTest.php

Always this fails. My controller function returning data as well without an issue. I tested without defining any condition and just,

$this->assertTrue(true);

Then it works. So i assume there is no any issue with the phpunit test command as well.

Body:
I'm sorry, this is not a direct answer.

I think maybe you should check the value of $data_status by this.

class SimpleTest extends TestCase
{
   public function testLoadUsers()
   {
     $controller_obj = new UsersController;
     $data_status = $controller_obj->load_users();
     $this->expectOutputString('Array');
     print data_status;
   }
}


问:
Alternative to fgets()?
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

```<code>void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}
</code>```

答:
Instead of declaring you buffer as a string declare it as something like:

```<code>char buffer[MY_MAX_SIZE]
</code>```

call fgets with that, and then build the string from the buffer if you need in that form instead of going the other way.

The reason what you're doing doesn't work is that you're getting a copy of the buffer contents as a c-style string, not a pointer into the gut of the buffer.  It is, by design, read only.

-- MarkusQ

ContentLicense: CC BY-SA 2.5

Title: Alternative to fgets()?

Body:
Description:

Obtain output from an executable

Note:

Will not compile, due to fgets() declaration

Question:

What is the best alternative to fgets, as fgets requires char *?

Is there a better alternative?

Illustration:

void Q_analysis (const char *data)
{
string buffer;
size_t found;
found = buffer.find_first_of (*data);

FILE *condorData = _popen ("condor_q", "r");
while (fgets (buffer.c_str(), buffer.max_size(), condorData) != NULL)
{
    if (found == string::npos)
    {
        Sleep(2000);
    } else {
        break;
    }
}
return;
}

Body:
Instead of declaring you buffer as a string declare it as something like:

char buffer[MY_MAX_SIZE]

call fgets with that, and then build the string from the buffer if you need in that form instead of going the other way.

The reason what you're doing doesn't work is that you're getting a copy of the buffer contents as a c-style string, not a pointer into the gut of the buffer.  It is, by design, read only.

-- MarkusQ

OwnerDisplayName: MarkusQ


问:
static sql for entity in nhibernate log file
I am using nhibernate to query my db and am seeing various statements in my log files as follow -

static sql for entity
static select for entity
version select
snapshot select

followed by queries using my domain entities.

I believe these are common when building a session factory, but I just wanted to make sure.  Does anyone know what these entries mean?

thanks for any help.

答: It's just letting you know the sql it's going to use the predictable queries such as get by id etc. They are created when setting up the session factory and then cached for optimization. Very normal.</p>


问:
How to get input from textarea in html to .ts in Angular
I am a newbie in Angular and now I want to get user input from a textarea but I fail to do so.

Updated: ng-model="num1" > [(ngModel)]="num1"

HTML:

<input [(ngModel)]="num1" type="text" placeholder="Enter value">
     // user enter one number

<input type="text" readonly value={{answer}}>

<button class="result" (click)=onSelectEqual()>=</button>
     // click this button to get the value that user entered
```

<p>.ts:</p>

```num1 : number;
answer: number;

onSelectEqual(){
  this.answer = this.num1 + 1 ;
}
```

答:
Use [(ngModel)] instead of ng-model in your html template. ng-model is the syntax of Angularjs which will not work in Angular2+.

Also make sure to import FormsModule in app.module.ts

```<code>import { FormsModule } from '@angular/forms';
</code>```

Also add it to the imports array in app.module.ts

```<code>imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
</code>```

This is important as without the FormsModule, angular will not be able to identify the ngModel directive.

On a different note, the input will return the value typed by the user as a string. To read it as a number and add 1 to it, you will have to typecast it:

```<code>onSelectEqual(){
  this.answer = Number(this.num1) + 1 ;
}
</code>```

Please also note that // for comments doesn't work in html template, use  instead.

Body:
I am a newbie in Angular and now I want to get user input from a textarea but I fail to do so.

Updated: ng-model="num1" > [(ngModel)]="num1"

HTML:

<input [(ngModel)]="num1" type="text" placeholder="Enter value">
     // user enter one number

<input type="text" readonly value={{answer}}>

<button class="result" (click)=onSelectEqual()>=</button>
     // click this button to get the value that user entered

.ts:

num1 : number;
answer: number;

onSelectEqual(){
  this.answer = this.num1 + 1 ;
}

Body:
Use [(ngModel)] instead of ng-model in your html template. ng-model is the syntax of Angularjs which will not work in Angular2+.

Also make sure to import FormsModule in app.module.ts

import { FormsModule } from '@angular/forms';

Also add it to the imports array in app.module.ts

imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],

This is important as without the FormsModule, angular will not be able to identify the ngModel directive.

On a different note, the input will return the value typed by the user as a string. To read it as a number and add 1 to it, you will have to typecast it:

onSelectEqual(){
  this.answer = Number(this.num1) + 1 ;
}

Please also note that // for comments doesn't work in html template, use <!-- --> instead.


问:
Render multiple components with a single ternary operator
If currentProfiles.length > 0, I'd like to map over an array named profiles and render a profile component for each profile, and render a pagination component below the profiles. I tried this with a single ternary operator, but this results in only the pagination component being rendered.

```<code>    {currentProfiles.length > 0 ? (
      (currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )),
      (
        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      ))
    ) : (
      <Spinner />
    )}
</code>```

If I use two separate ternary operators, I get the list of profiles and pagination as expected, but can I do both things with a single conditional operator?

答:
You can use an array or a fragment https://reactjs.org/docs/fragments.html

{currentProfiles.length > 0 ? (
     <>
      currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )

        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      </>
    ) : (
      <Spinner />
    )}
```

Body:
If currentProfiles.length > 0, I'd like to map over an array named profiles and render a profile component for each profile, and render a pagination component below the profiles. I tried this with a single ternary operator, but this results in only the pagination component being rendered.

    {currentProfiles.length > 0 ? (
      (currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )),
      (
        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      ))
    ) : (
      <Spinner />
    )}

If I use two separate ternary operators, I get the list of profiles and pagination as expected, but can I do both things with a single conditional operator?


问:
Clasic emoji unicode list
Good friends,

I am trying to send emojis through an API and I have noticed that it only accepts the most common emojis like ☹☝ and newer ones like  are shown as "????". From what I see only old emojis like ☹ are the ones he accepts. These emojis are rendered as a font and have no color (just outline), the question is how do I get a list of these classic emojis? since it is difficult to separate those that are rendered as a font (without color, outlined) to new ones (with color).

答:
It looks like your API only supports Unicode BMP (Basic Multilingual Plane) code points from U+0000 to U+FFFF, so you could filter by code point.  The ones that work are:

```<code>☹ U+2639 WHITE FROWNING FACE
☝ U+261D WHITE UP POINTING INDEX
</code>```

And the ones that don't are:

```<code> U+1F612 UNAMUSED FACE
 U+1F61D FACE WITH STUCK-OUT TONGUE AND TIGHTLY-CLOSED EYES
 U+1F924 DROOLING FACE
</code>```

Refer to https://www.unicode.org/emoji/charts/index.html for a complete list of emoji.

Title: Clasic emoji unicode list

Body:
It looks like your API only supports Unicode BMP (Basic Multilingual Plane) code points from U+0000 to U+FFFF, so you could filter by code point.  The ones that work are:

☹ U+2639 WHITE FROWNING FACE
☝ U+261D WHITE UP POINTING INDEX

And the ones that don't are:

 U+1F612 UNAMUSED FACE
 U+1F61D FACE WITH STUCK-OUT TONGUE AND TIGHTLY-CLOSED EYES
 U+1F924 DROOLING FACE

Refer to https://www.unicode.org/emoji/charts/index.html for a complete list of emoji.


问:
Debian or Fedora/CentOS.. which would be better suited for hardware programmer's needs
Since I'm stuck in a "can't decide on which path to choose" loop concerning choosing a proper Linux distro for a workstation, I need a little help in term's of typical hardware/software programmer's needs.

My two big favorites are Debian and Fedora/CentOS. I already know both have great community support in terms of development, but I'm looking for that extra spark, a slight edge that would lean me to one of them.

Feedback would be very appreciated.

答: I agree, try them both.  Have you used VirtualBox or VMWare?  Using these tools you can try both at the same time.</p>


答:
Your code just needs some restructuring. If you wrap the mapped profiles and pagination components in a parent fragment or other element, it's easy. Note, too, that the first example below still retains the ternary, as requested.

  return (

      {currentProfiles.length ? (
        <>
          {currentProfiles.map(p => (
            <Profile {...p} />
          ))}
          <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
        </>
      ) : (

Loading...

      )}

  );
```

<p>However, you have a few options aside from wrapping them in a non-rendered <code>Fragment</code> or its shorthand derivative. You could also use an actual element, such as a <code>div</code>. Or even omit the parent entirely and place your logic within an array, as in:</p>

<pre class="lang-js prettyprint-override"><code><div className="App">
  {currentProfiles.length ? [
    currentProfiles.map(p => (
      <Profile {...p} />
    )),
    <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
  ] : <p>Loading...</p>}
</div>
</code>```

Always remember that, unless you utilize the second approach, you'll need to ensure siblings share a common parent.

Working example.

Title: Render multiple components with a single ternary operator

Body:
Your code just needs some restructuring. If you wrap the mapped profiles and pagination components in a parent fragment or other element, it's easy. Note, too, that the first example below still retains the ternary, as requested.

  return (
    <div className="App">
      {currentProfiles.length ? (
        <>
          {currentProfiles.map(p => (
            <Profile {...p} />
          ))}
          <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
        </>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );

However, you have a few options aside from wrapping them in a non-rendered Fragment or its shorthand derivative. You could also use an actual element, such as a div. Or even omit the parent entirely and place your logic within an array, as in:

<div className="App">
  {currentProfiles.length ? [
    currentProfiles.map(p => (
      <Profile {...p} />
    )),
    <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
  ] : <p>Loading...</p>}
</div>

Always remember that, unless you utilize the second approach, you'll need to ensure siblings share a common parent.

Working example.


问:
Is there a way to prevent change of data in unmodifiableList in the below scenario?
Here I have scenario where I want to create a unmodifiableList in such a way that no other part of the program can modify its initial values.

Here is the code snippet to give some idea about my problem.

```<code>public class Test {

    public static void main(String[] args) {
        List<String> unmodifiableList = new ArrayList<String>();
        unmodifiableList.add("test1");
        unmodifiableList.add("test2");
        unmodifiableList = Collections.unmodifiableList(unmodifiableList);
        List<String> modifiableList = new ArrayList<String>();
        modifiableList.addAll(unmodifiableList);
        unmodifiableList = modifiableList;
        unmodifiableList.add("test3");
        for (String s : unmodifiableList) {
          System.out.println(s);
        }
    }
}
</code>```

Output:
test1
test2
test3

Expected Output:
test1
test2

答:
Can you try below.

```<code>    final List<String> unmodifiableList1 = Collections.unmodifiableList(unmodifiableList);
</code>```

to avoid creation of extra list try below.

```<code>final List<String> finalList = Collections.unmodifiableList(Arrays.asList("test1", "test2"));
</code>```

Body:
Here I have scenario where I want to create a unmodifiableList in such a way that no other part of the program can modify its initial values.

Here is the code snippet to give some idea about my problem.

public class Test {

    public static void main(String[] args) {
        List<String> unmodifiableList = new ArrayList<String>();
        unmodifiableList.add("test1");
        unmodifiableList.add("test2");
        unmodifiableList = Collections.unmodifiableList(unmodifiableList);
        List<String> modifiableList = new ArrayList<String>();
        modifiableList.addAll(unmodifiableList);
        unmodifiableList = modifiableList;
        unmodifiableList.add("test3");
        for (String s : unmodifiableList) {
          System.out.println(s);
        }
    }
}

Output:
test1
test2
test3

Expected Output:
test1
test2

Body:
Can you try below.

    final List<String> unmodifiableList1 = Collections.unmodifiableList(unmodifiableList);

to avoid creation of extra list try below.

final List<String> finalList = Collections.unmodifiableList(Arrays.asList("test1", "test2"));


问:
Multiple data tables in single sheet with some overlap of names and separating column headers
I have a dataset with multiple tables in the same Excel sheet that I'd like to combine. The sheet's data is formatted like this:

```<code>group_no      group     variable       marker1     marker2     marker3
1             GR-01-1   1              -           -           A
1             GR-01-1   2              B           A           B
1             GR-01-1   3              A           B           -
1             GR-01-1   4              -           -           -
1             GR-01-1   5              B           -           B
group_no.     group     variable       marker 4    marker5     marker6    marker7
2             GR-01-1a  1              B           -           A          -
2             GR-01-1a  2              B           A           -          B
2             GR-01-1a  3              A           B           -          B
2             GR-01-1a  4              A           A           A          A
group_no      group     variable       marker8
3             GR-01-2   1              B
3             GR-01-2   2              A
3             GR-01-2   3              -
group_no      group     variable       marker9     marker10
4             GR-02-1   1              B           A
4             GR-02-1   2              A           A
4             GR-02-1   3              -           B
4             GR-02-1   4              B           B
4             GR-02-1   5              A           B
4             GR-02-1   6              -           A
group_no      group     variable       marker11    marker12    marker13
5             GR-02-2   d              B           B           A
5             GR-02-2   e              A           B           B
5             GR-02-2   f              B           -           -
5             GR-02-2   g              -           B           -
</code>```

As can be seen above, the supplier of the data did not separate out the names of the markers into unique columns. All the tables are stacked on top of one another. What I want to do is transform the data into this:

```<code>marker_name    group_no  group          1    2    3    4    5    6    a    b    c    d    e    f    g
marker1        GR-01-1   1              -    B    A    -    B
marker2        GR-01-1   1              -    A    B    -    -
marker3        GR-01-1   1              A    B    -    -    B
marker4        GR-01-1a  2              B    B    A    A
marker5        GR-01-1a  2              -    A    B    A
marker6        GR-01-1a  2              A    -    -    A
marker7        GR-01-1a  2              -    B    B    A
marker8        GR-01-2   3              B    A    -
marker9        GR-02-1   4              B    A    -    B    A    -
marker10       GR-02-1   4              A    A    B    B    B    A
marker11       GR-02-2   5                                                           B    A    B    -
marker12       GR-02-2   5                                                           B    B    -    B
marker13       GR-02-2   5                                                           A    B    -    -
</code>```

Is there a way to do this in R? A loop maybe? I started off with transposing in R, but that didn't work and I wonder if there may have been a way to read the data in by group_no. But no luck. I am still a novice, I guess. There are 917 tables in my data set in the single sheet. I'm hoping I don't have to assign each to a new R object one-by-one and then rbind or cbind.

答:
#Reading data into R
library(readr)
df1 <- read_csv("C:/Users/userm/Desktop/df1.csv",
                col_names = FALSE)
```

```#Loading libraries:
library(plyr)
library(tidyr)
```

```spl <- diff(c(which(df1$X1 == 'group_no'), nrow(df1))) #defining the split for each table

#Splitting to a list of dataframes, where each dataframe is one of the tables of interest:
dl2 <- split(df1,
            c(rep(1, spl[1]),
              rep(2, spl[2]),
              rep(3, spl[3]),
              rep(4, spl[4]),
              rep(5, spl[5])))
```

```#Assigning the first row as the dataframe header:
dl3 <- lapply(dl2, function(d){colnames(d) <- d[1,]; d <- d[-1,]})

#Removing columns with All NAs:
dl4 <- lapply(dl3, function(d){d <- d[,colSums(is.na(d))<nrow(d)]})

#Binding dataframes with different number of columns (plyr):
df5 <- rbind.fill(dl4)
```

```#Converting from Wide to Long (tidyr):
df6 <- pivot_longer(df5, -c("group_no", "group", "variable"),
                          names_to = "marker_name", values_to = "value")

#Convert from Long to Wide with a different arrangement (tidyr):
df7 <- pivot_wider(df6, names_from = "variable", values_from = "value")
```

```#> # A tibble: 65 x 16
#>    group_no group marker_name a     b     c     `4`   `5`   g     `1`
#>    <chr>    <chr> <chr>       <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#>  1 1        GR-0~ marker1     -     B     A     -     B     <NA>  <NA>
#>  2 1        GR-0~ marker2     -     A     B     -     -     <NA>  <NA>
#>  3 1        GR-0~ marker3     A     B     -     -     B     <NA>  <NA>
#>  4 1        GR-0~ marker4     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  5 1        GR-0~ marker5     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  6 1        GR-0~ marker6     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  7 1        GR-0~ marker7     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  8 1        GR-0~ marker8     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  9 1        GR-0~ marker9     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#> 10 1        GR-0~ marker10    <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#> # ... with 55 more rows, and 6 more variables: `2` <chr>, `3` <chr>,
#> #   `6` <chr>, d <chr>, e <chr>, f <chr>
```

<p><strong><em>Data:</em></strong></p>

```df1 <- structure(list(X1 = c("group_no", "1", "1", "1", "1", "1", "group_no",
"2", "2", "2", "2", "group_no", "3", "3", "3", "group_no", "4",
"4", "4", "4", "4", "4", "group_no", "5", "5", "5", "5"), X2 = c("group",
"GR-01-1", "GR-01-1", "GR-01-1", "GR-01-1", "GR-01-1", "group",
"GR-01-1a", "GR-01-1a", "GR-01-1a", "GR-01-1a", "group", "GR-01-2",
"GR-01-2", "GR-01-2", "group", "GR-02-1", "GR-02-1", "GR-02-1",
"GR-02-1", "GR-02-1", "GR-02-1", "group", "GR-02-2", "GR-02-2",
"GR-02-2", "GR-02-2"), X3 = c("variable", "a", "b", "c", "4",
"5", "variable", "1", "2", "3", "4", "variable", "1", "2", "3",
"variable", "1", "2", "3", "4", "5", "6", "variable", "d", "e",
"f", "g"), X4 = c("marker1", "-", "B", "A", "-", "B", "marker4",
"B", "B", "A", "A", "marker8", "B", "A", "-", "marker9", "B",
"A", "-", "B", "A", "-", "marker11", "B", "A", "B", "-"), X5 = c("marker2",
"-", "A", "B", "-", "-", "marker5", "-", "A", "B", "A", NA, NA,
NA, NA, "marker10", "A", "A", "B", "B", "B", "A", "marker12",
"B", "B", "-", "B"), X6 = c("marker3", "A", "B", "-", "-", "B",
"marker6", "A", "-", "-", "A", NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, "marker13", "A", "B", "-", "-"), X7 = c(NA, NA, NA,
NA, NA, NA, "marker7", "-", "B", "B", "A", NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -27L), spec = structure(list(
    cols = list(X1 = structure(list(), class = c("collector_character",
    "collector")), X2 = structure(list(), class = c("collector_character",
    "collector")), X3 = structure(list(), class = c("collector_character",
    "collector")), X4 = structure(list(), class = c("collector_character",
    "collector")), X5 = structure(list(), class = c("collector_character",
    "collector")), X6 = structure(list(), class = c("collector_character",
    "collector")), X7 = structure(list(), class = c("collector_character",
    "collector"))), default = structure(list(), class = c("collector_guess",
    "collector")), skip = 0), class = "col_spec"))
```

```   X1       X2       X3       X4      X5      X6      X7
 1 group_no group    variable marker1 marker2 marker3 NA
 2 1        GR-01-1  a        -       -       A       NA
 3 1        GR-01-1  b        B       A       B       NA
 4 1        GR-01-1  c        A       B       -       NA
 5 1        GR-01-1  4        -       -       -       NA
 6 1        GR-01-1  5        B       -       B       NA
 7 group_no group    variable marker4 marker5 marker6 marker7
 8 2        GR-01-1a 1        B       -       A       -
 9 2        GR-01-1a 2        B       A       -       B
10 2        GR-01-1a 3        A       B       -       B
# ... with 17 more rows
```

Body:
I have a dataset with multiple tables in the same Excel sheet that I'd like to combine. The sheet's data is formatted like this:

group_no      group     variable       marker1     marker2     marker3
1             GR-01-1   1              -           -           A
1             GR-01-1   2              B           A           B
1             GR-01-1   3              A           B           -
1             GR-01-1   4              -           -           -
1             GR-01-1   5              B           -           B
group_no.     group     variable       marker 4    marker5     marker6    marker7
2             GR-01-1a  1              B           -           A          -
2             GR-01-1a  2              B           A           -          B
2             GR-01-1a  3              A           B           -          B
2             GR-01-1a  4              A           A           A          A
group_no      group     variable       marker8
3             GR-01-2   1              B
3             GR-01-2   2              A
3             GR-01-2   3              -
group_no      group     variable       marker9     marker10
4             GR-02-1   1              B           A
4             GR-02-1   2              A           A
4             GR-02-1   3              -           B
4             GR-02-1   4              B           B
4             GR-02-1   5              A           B
4             GR-02-1   6              -           A
group_no      group     variable       marker11    marker12    marker13
5             GR-02-2   d              B           B           A
5             GR-02-2   e              A           B           B
5             GR-02-2   f              B           -           -
5             GR-02-2   g              -           B           -

As can be seen above, the supplier of the data did not separate out the names of the markers into unique columns. All the tables are stacked on top of one another. What I want to do is transform the data into this:

marker_name    group_no  group          1    2    3    4    5    6    a    b    c    d    e    f    g
marker1        GR-01-1   1              -    B    A    -    B
marker2        GR-01-1   1              -    A    B    -    -
marker3        GR-01-1   1              A    B    -    -    B
marker4        GR-01-1a  2              B    B    A    A
marker5        GR-01-1a  2              -    A    B    A
marker6        GR-01-1a  2              A    -    -    A
marker7        GR-01-1a  2              -    B    B    A
marker8        GR-01-2   3              B    A    -
marker9        GR-02-1   4              B    A    -    B    A    -
marker10       GR-02-1   4              A    A    B    B    B    A
marker11       GR-02-2   5                                                           B    A    B    -
marker12       GR-02-2   5                                                           B    B    -    B
marker13       GR-02-2   5                                                           A    B    -    -

Is there a way to do this in R? A loop maybe? I started off with transposing in R, but that didn't work and I wonder if there may have been a way to read the data in by group_no. But no luck. I am still a novice, I guess. There are 917 tables in my data set in the single sheet. I'm hoping I don't have to assign each to a new R object one-by-one and then rbind or cbind.

Body:
#Reading data into R
library(readr)
df1 <- read_csv("C:/Users/userm/Desktop/df1.csv",
                col_names = FALSE)

#Loading libraries:
library(plyr)
library(tidyr)

spl <- diff(c(which(df1$X1 == 'group_no'), nrow(df1))) #defining the split for each table

#Splitting to a list of dataframes, where each dataframe is one of the tables of interest:
dl2 <- split(df1,
            c(rep(1, spl[1]),
              rep(2, spl[2]),
              rep(3, spl[3]),
              rep(4, spl[4]),
              rep(5, spl[5])))

#Assigning the first row as the dataframe header:
dl3 <- lapply(dl2, function(d){colnames(d) <- d[1,]; d <- d[-1,]})

#Removing columns with All NAs:
dl4 <- lapply(dl3, function(d){d <- d[,colSums(is.na(d))<nrow(d)]})

#Binding dataframes with different number of columns (plyr):
df5 <- rbind.fill(dl4)

#Converting from Wide to Long (tidyr):
df6 <- pivot_longer(df5, -c("group_no", "group", "variable"),
                          names_to = "marker_name", values_to = "value")

#Convert from Long to Wide with a different arrangement (tidyr):
df7 <- pivot_wider(df6, names_from = "variable", values_from = "value")

#> # A tibble: 65 x 16
#>    group_no group marker_name a     b     c     `4`   `5`   g     `1`
#>    <chr>    <chr> <chr>       <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#>  1 1        GR-0~ marker1     -     B     A     -     B     <NA>  <NA>
#>  2 1        GR-0~ marker2     -     A     B     -     -     <NA>  <NA>
#>  3 1        GR-0~ marker3     A     B     -     -     B     <NA>  <NA>
#>  4 1        GR-0~ marker4     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  5 1        GR-0~ marker5     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  6 1        GR-0~ marker6     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  7 1        GR-0~ marker7     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  8 1        GR-0~ marker8     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#>  9 1        GR-0~ marker9     <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#> 10 1        GR-0~ marker10    <NA>  <NA>  <NA>  <NA>  <NA>  <NA>  <NA>
#> # ... with 55 more rows, and 6 more variables: `2` <chr>, `3` <chr>,
#> #   `6` <chr>, d <chr>, e <chr>, f <chr>

Data:

df1 <- structure(list(X1 = c("group_no", "1", "1", "1", "1", "1", "group_no",
"2", "2", "2", "2", "group_no", "3", "3", "3", "group_no", "4",
"4", "4", "4", "4", "4", "group_no", "5", "5", "5", "5"), X2 = c("group",
"GR-01-1", "GR-01-1", "GR-01-1", "GR-01-1", "GR-01-1", "group",
"GR-01-1a", "GR-01-1a", "GR-01-1a", "GR-01-1a", "group", "GR-01-2",
"GR-01-2", "GR-01-2", "group", "GR-02-1", "GR-02-1", "GR-02-1",
"GR-02-1", "GR-02-1", "GR-02-1", "group", "GR-02-2", "GR-02-2",
"GR-02-2", "GR-02-2"), X3 = c("variable", "a", "b", "c", "4",
"5", "variable", "1", "2", "3", "4", "variable", "1", "2", "3",
"variable", "1", "2", "3", "4", "5", "6", "variable", "d", "e",
"f", "g"), X4 = c("marker1", "-", "B", "A", "-", "B", "marker4",
"B", "B", "A", "A", "marker8", "B", "A", "-", "marker9", "B",
"A", "-", "B", "A", "-", "marker11", "B", "A", "B", "-"), X5 = c("marker2",
"-", "A", "B", "-", "-", "marker5", "-", "A", "B", "A", NA, NA,
NA, NA, "marker10", "A", "A", "B", "B", "B", "A", "marker12",
"B", "B", "-", "B"), X6 = c("marker3", "A", "B", "-", "-", "B",
"marker6", "A", "-", "-", "A", NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, "marker13", "A", "B", "-", "-"), X7 = c(NA, NA, NA,
NA, NA, NA, "marker7", "-", "B", "B", "A", NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -27L), spec = structure(list(
    cols = list(X1 = structure(list(), class = c("collector_character",
    "collector")), X2 = structure(list(), class = c("collector_character",
    "collector")), X3 = structure(list(), class = c("collector_character",
    "collector")), X4 = structure(list(), class = c("collector_character",
    "collector")), X5 = structure(list(), class = c("collector_character",
    "collector")), X6 = structure(list(), class = c("collector_character",
    "collector")), X7 = structure(list(), class = c("collector_character",
    "collector"))), default = structure(list(), class = c("collector_guess",
    "collector")), skip = 0), class = "col_spec"))

   X1       X2       X3       X4      X5      X6      X7
 1 group_no group    variable marker1 marker2 marker3 NA
 2 1        GR-01-1  a        -       -       A       NA
 3 1        GR-01-1  b        B       A       B       NA
 4 1        GR-01-1  c        A       B       -       NA
 5 1        GR-01-1  4        -       -       -       NA
 6 1        GR-01-1  5        B       -       B       NA
 7 group_no group    variable marker4 marker5 marker6 marker7
 8 2        GR-01-1a 1        B       -       A       -
 9 2        GR-01-1a 2        B       A       -       B
10 2        GR-01-1a 3        A       B       -       B
# ... with 17 more rows


问:
Random Elements from two Lists - Python
So I have two lists in Python:

```<code>import random
list_1 = ['1','2','3']
list_2 = ['4','5','6']
num = random.choice(list_1 or list_2)
</code>```

This doesn't seem to work. How can I get a random number from either list 1 or list 2?

答:
Not short but could be a reference...</p>

```<code>import random

name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','man','shopping','pen','mouse']

population = list(zip(name, second))
ox_list = []

for a in range(20):
    samples = random.sample(population, 1)
    samples = str(samples).strip('[]')
    ox_list.append(samples.replace("', '", ''))

for o in set(ox_list):
    print (o.replace("')",'').replace("('",''))

I have lemon
I want cat
I love banana
I like man
I buy soap
I hate water
I see shopping
</code>```

Title: Random Elements from two Lists - Python

Body:
So I have two lists in Python:

import random
list_1 = ['1','2','3']
list_2 = ['4','5','6']
num = random.choice(list_1 or list_2)

This doesn't seem to work. How can I get a random number from either list 1 or list 2?

Body:
Not short but could be a reference...

import random

name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','man','shopping','pen','mouse']

population = list(zip(name, second))
ox_list = []

for a in range(20):
    samples = random.sample(population, 1)
    samples = str(samples).strip('[]')
    ox_list.append(samples.replace("', '", ''))

for o in set(ox_list):
    print (o.replace("')",'').replace("('",''))

I have lemon
I want cat
I love banana
I like man
I buy soap
I hate water
I see shopping