问:
How put a Confirmation in Hyperlink DataGridView
I want is to have a confirmation before deleting a records in my datagridview. Please check my codes.. Thanks.

here's my asp.net code:

```<code><ItemTemplate><asp:HyperLink ID="hlnk_Delete" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
    NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>
</code>```

Sqldatasource:

```<code><asp:SqlDataSource ID="sds_PublishedBookListings" runat="server" ConnectionString="<%$ ConnectionStrings:learningisfunConnectionString %>"

SelectCommand="SELECT dbo.lif_bookshascategory.lbhc_lc_id,dbo.lif_books.lb_sku, dbo.lif_bookshascategory.lbhc_lb_sku, dbo.lif_category.lc_category, dbo.lif_books.lb_title,
                      dbo.lif_bookshascategory.lbhc_level
FROM         dbo.lif_bookshascategory INNER JOIN
                      dbo.lif_category ON dbo.lif_bookshascategory.lbhc_lc_id = dbo.lif_category.lc_id INNER JOIN
                      dbo.lif_books ON dbo.lif_bookshascategory.lbhc_lb_sku = dbo.lif_books.lb_sku
WHERE     (dbo.lif_books.lb_status = 'publish') and lbhc_level = 1
"

DeleteCommand="DELETE FROM lif_books FROM lif_books INNER JOIN lif_bookshascategory ON lif_books.lb_sku = lif_bookshascategory.lbhc_lb_sku WHERE (lif_books.lb_sku = @lbhc_lb_sku) OR (lif_bookshascategory.lbhc_lb_sku = @lbhc_lb_sku)">
<DeleteParameters>
<asp:Parameter Name="lb_sku" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
</code>```

答:
add this your hyperlink</p>

```<code>onclick="javascript:return confirm('Are you sure you want to delete ?');"

<ItemTemplate><asp:HyperLink ID="hlnk_Delete" onclick="javascript:return confirm('Are you sure you want to delete ?');" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>
</code>```

Body:
I want is to have a confirmation before deleting a records in my datagridview. Please check my codes.. Thanks.

here's my asp.net code:

<ItemTemplate><asp:HyperLink ID="hlnk_Delete" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
    NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>

Sqldatasource:

<asp:SqlDataSource ID="sds_PublishedBookListings" runat="server" ConnectionString="<%$ ConnectionStrings:learningisfunConnectionString %>"

SelectCommand="SELECT dbo.lif_bookshascategory.lbhc_lc_id,dbo.lif_books.lb_sku, dbo.lif_bookshascategory.lbhc_lb_sku, dbo.lif_category.lc_category, dbo.lif_books.lb_title,
                      dbo.lif_bookshascategory.lbhc_level
FROM         dbo.lif_bookshascategory INNER JOIN
                      dbo.lif_category ON dbo.lif_bookshascategory.lbhc_lc_id = dbo.lif_category.lc_id INNER JOIN
                      dbo.lif_books ON dbo.lif_bookshascategory.lbhc_lb_sku = dbo.lif_books.lb_sku
WHERE     (dbo.lif_books.lb_status = 'publish') and lbhc_level = 1
"

DeleteCommand="DELETE FROM lif_books FROM lif_books INNER JOIN lif_bookshascategory ON lif_books.lb_sku = lif_bookshascategory.lbhc_lb_sku WHERE (lif_books.lb_sku = @lbhc_lb_sku) OR (lif_bookshascategory.lbhc_lb_sku = @lbhc_lb_sku)">
<DeleteParameters>
<asp:Parameter Name="lb_sku" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>

Body:
add this your hyperlink

onclick="javascript:return confirm('Are you sure you want to delete ?');"

<ItemTemplate><asp:HyperLink ID="hlnk_Delete" onclick="javascript:return confirm('Are you sure you want to delete ?');" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>


来源: stackexchange

问:
Specifying lifetimes in macro derives
How does one specify lifetimes on macro derives?

```<code>#[derive(ElasticType, Serialize, Deserialize)]
pub struct Xkcd<'a> {
       link: &'a str
}
</code>```

Error example:

#[derive(ElasticType, Serialize, Deserialize)]
 |       ^^^^^^^^^^^ expected lifetime parameter
```

答:
In your piece of code you simply can not fix this issue. It's a bug in the crate providing #[derive(ElasticType)].

File a bug with the author of ElasticType! If it's not possible for some reason to add support for lifetimed struct it should at least emit a useful error message stating so.

ContentLicense: CC BY-SA 4.0

Title: Specifying lifetimes in macro derives

Body:
How does one specify lifetimes on macro derives?

#[derive(ElasticType, Serialize, Deserialize)]
pub struct Xkcd<'a> {
       link: &'a str
}

Error example:

#[derive(ElasticType, Serialize, Deserialize)]
 |       ^^^^^^^^^^^ expected lifetime parameter


问:
How to make Angular 2 form see injected form controls?
I'm dynamically injecting a component (using @ViewChild and insert()) with form controls into a component that wraps it with a form tag
(so that I can have many different form templates with the same form handling).

This all works fine, but now when I check form.valid, it's always valid because apparently, it doesn't see the form controls that are dynamically injected.

Can I somehow trigger a 'reinitialization' of the ngForm directive on the form so that it will know that there are additional form controls injected?

Note: I do realise by now that a better solution to this problem would probably be to use model driven forms, but right now it's too short notice to redo the whole thing.

Parent template:

```<code><form #htmlFormElement="ngForm" novalidate>
    <div #dynamicComponentContainer></div>
    <!-- more buttons and shared form controls here -->
</form>
</code>```

Child template
E.g.:

```<code><textarea name="comments" [(ngModel)]="formData.comments"></textarea>
</code>```

答:
You can set the viewProviders in the child component to use the existing NgForm as the ControlContainer.

This should automatically treat the form controls in the child component as if they are part of the parent component's form.

e.g:

@Component({
    selector: 'child-with-form-controls',
    templateUrl: './child-with-form-controls.component.html',
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm}]
})
export class ChildWithFormControlsComponent {
    ...
}
```

ContentLicense: CC BY-SA 3.0

Body:
I'm dynamically injecting a component (using @ViewChild and insert()) with form controls into a component that wraps it with a form tag
(so that I can have many different form templates with the same form handling).

This all works fine, but now when I check form.valid, it's always valid because apparently, it doesn't see the form controls that are dynamically injected.

Can I somehow trigger a 'reinitialization' of the ngForm directive on the form so that it will know that there are additional form controls injected?

Note: I do realise by now that a better solution to this problem would probably be to use model driven forms, but right now it's too short notice to redo the whole thing.

Parent template:

<form #htmlFormElement="ngForm" novalidate>

</form>

Child template
E.g.:

<textarea name="comments" [(ngModel)]="formData.comments"></textarea>


问:
Using if / else if need to populate nick names in R
I wanted to see nick names against name column

i have created vector (char), latter converted to data.frames. Now i want to see nick names against each names

```<code> y = c("Varun","Rivan","Jyothi","others")
  y = data.frame(y)
  y$nicknames = ""
  View(y)

   y$nicknames = ifelse(y$y =="Varun","Vast",(ifelse(y$y =="Jyothi","jo",
 (ifelse(y$y =="Rivan","Kidoo","others")))))
</code>```

it is working for me, however need to see simple easy way to execute

Need to see nick names in different column

答:
Use case_when from the dplyr library:

```<code>y$nicknames <- case_when(
    y$y == "Varun" ~ "Vast",
    y$y == "Jyothi" ~ "jo",
    y$y == "Rivan" ~ "Kidoo",
    TRUE ~ "others"
)
</code>```

Body:
I wanted to see nick names against name column

i have created vector (char), latter converted to data.frames. Now i want to see nick names against each names

 y = c("Varun","Rivan","Jyothi","others")
  y = data.frame(y)
  y$nicknames = ""
  View(y)

   y$nicknames = ifelse(y$y =="Varun","Vast",(ifelse(y$y =="Jyothi","jo",
 (ifelse(y$y =="Rivan","Kidoo","others")))))

it is working for me, however need to see simple easy way to execute

Need to see nick names in different column

Body:
Use case_when from the dplyr library:

y$nicknames <- case_when(
    y$y == "Varun" ~ "Vast",
    y$y == "Jyothi" ~ "jo",
    y$y == "Rivan" ~ "Kidoo",
    TRUE ~ "others"
)


问:
how to handle useEffect with render props in react
I want to use a render props function with hooks but I am not entirely sure if this is possible.

I have a FetcherComponent that takes a renderprop but I want to use a setState from

```<code>export const HierarchyGraph: React.FunctionComponent = () => {
  const [rootNode, setRootNode] = useState<HierarchyNode<GraphicalNode> | null>(null);

  return (
    <Fetcher
      url="/hierarchy"
      initialData={{}}
      render={({ data }: { data: TreeData }) => {
          // this will cause infinite recursion
          setRootNode(getHierarchy(data));
</code>```

Should I not use render props in this situation?

答:
it causes infinite recursion because of setRootNode causing re-render of HierarchyGraph and this again triggers setRootNode. You need to find a way to stop this state updates when it's not necessary e.g:

```<code>export const HierarchyGraph = () => {
  const [data, setData] = useState({});

  return (
    <Fetcher
      url="/hierarchy"
      initialData={data}
      render={({ data: newData }) => {
          if(data !== newData) {
            setData(newData);
          }
      }}
    />
  );
}
</code>```

Body:
I want to use a render props function with hooks but I am not entirely sure if this is possible.

I have a FetcherComponent that takes a renderprop but I want to use a setState from

export const HierarchyGraph: React.FunctionComponent = () => {
  const [rootNode, setRootNode] = useState<HierarchyNode<GraphicalNode> | null>(null);

  return (
    <Fetcher
      url="/hierarchy"
      initialData={{}}
      render={({ data }: { data: TreeData }) => {
          // this will cause infinite recursion
          setRootNode(getHierarchy(data));

Should I not use render props in this situation?

Body:
it causes infinite recursion because of setRootNode causing re-render of HierarchyGraph and this again triggers setRootNode. You need to find a way to stop this state updates when it's not necessary e.g:

export const HierarchyGraph = () => {
  const [data, setData] = useState({});

  return (
    <Fetcher
      url="/hierarchy"
      initialData={data}
      render={({ data: newData }) => {
          if(data !== newData) {
            setData(newData);
          }
      }}
    />
  );
}


问:
How to add vertical lines to GD::Graph::linespoints line chart?
My line chart is good, but I would like to add vertical lines to indicate "timeline" dates.

```<code>use GD::Graph::linespoints;
use GD::Graph::Data;

my @label = qw(2019-05-05 2019-05-12 2019-05-19 2019-05-26);
my @data = (10, 20, 30, 40);
my @events = qw(2019-05-07 2019-05-15 2019-05-30);

my @input = (\@label, \@data);
my $data = GD::Graph::Data->new(\@input) or die GD::Graph::Data->error;
my $graph = GD::Graph::linespoints->new(1400,600);
$graph->set(
  x_label               => 'Week',
  x_label_position      => .5,
  y_label               => 'Things',
  y_min_value           => 0,
  title                 => 'Average Daily Things',
  x_labels_vertical     => 1,
  textclr               => 'orange',
  labelclr              => 'orange',
  axislabelclr          => 'gray',
  fgclr                 => 'green',
  bgclr                 => 'white',
  shadow_depth          => 3,
  markers               => 1,
  marker_size           => 2,
  shadowclr             => 'dgreen',
  transparent           => 0,
  dclrs                 => [ qw(blue) ],
) or die $graph->error;
$graph->plot($data) or die $graph->error;
my $file = 'testing.png';
open OUT, '>', $file or die "Cannot open '$file' for write: $!";
binmode OUT;
print OUT $graph->gd->png;
close OUT;
</code>```

Desired output:

Vertical lines should be spaced between points based on actual date, but snapped to previous tick would also be acceptable.

The vertical line should fully traverse from top border to bottom border.

A text legend explaining the dates highlighted, if possible.

答:
It seems it is not possible to add vertical lines at specific locations directly to a GD::Graph but you can add lines after doing $graph->plot() using GD::Polyline. For example:

```<code>use strict;
use warnings;
use GD::Graph::mixed;
use GD::Polyline;

my $start_day = 5;
my $end_day = 26;
my @data = (10, 20, 30, 40);
my @label = qw(2019-05-05 2019-05-12 2019-05-19 2019-05-26);
my @all_labels = map { sprintf "2019-05-%02d", $_ } $start_day..$end_day;
my $N = scalar @all_labels;
my $label_indices = get_event_indices( \@all_labels, \@label );
my $ydata = linear_interpolation(\@data, $label_indices, $N);
my @events = qw(2019-05-07 2019-05-15 2019-05-26);

my $points_data1 = get_point_data( \@all_labels, \@label, $ydata);

my @plot_data = (\@all_labels, $ydata, $points_data1);

my $width = 1400;
my $height = 600;
my $graph = GD::Graph::mixed->new($width, $height);
$graph->set(
  axislabelclr          => 'gray',
  bgclr                 => 'white',
  dclrs                 => [ qw(blue) ],
  fgclr                 => 'green',
  labelclr              => 'orange',
  marker_size           => 2,
  markers               => 1,
  shadowclr             => 'dgreen',
  shadow_depth          => 3,
  textclr               => 'orange',
  title                 => 'Average Daily Things',
  transparent           => 0,
  types                 => [ qw( lines points  ) ],
  x_label               => 'Week',
  x_label_position      => .5,
  x_label_skip          => 7,
  x_labels_vertical     => 1,
  y_label               => 'Things',
  y_min_value           => 0,
) or die $graph->error;
$graph->plot(\@plot_data) or die $graph->error;

my $event_indices = get_event_indices( \@all_labels, \@events );

plot_vertical_lines( $graph, $height, $event_indices );

my $file = 'testing.png';
open OUT, '>', $file or die "Cannot open '$file' for write: $!";
binmode OUT;
print OUT $graph->gd->png;
close OUT;

sub plot_vertical_lines {
    my ( $graph, $height, $event_indices ) = @_;

    my $gd = $graph->gd;
    my $black  = $gd->colorAllocate(  0,  0,  0);

    for my $idx ( @$event_indices ) {
        my @line = $graph->get_hotspot(1, $idx);
        my $x = $line[3];
        my $polyline = GD::Polyline->new();

        # add some points
        $polyline->addPt(  $x, 20);
        $polyline->addPt(  $x, $height - 70);
        $gd->setThickness( 2);
        $gd->polydraw($polyline, $black);
    }
}

sub get_event_indices {
    my ( $l1, $l2 ) = @_;

    my @idx;
    my $j = 0;
    for my $i (0..$#$l1) {
        my $label = $l1->[$i];
        if ( $label eq $l2->[$j] ) {
            push @idx, $i;
            $j++;
        }
    }
    return \@idx;
}

sub get_point_data {
    my ( $l1, $l2, $ydata) = @_;

    my @data;
    my $j = 0;
    for my $i (0..$#$l1) {
        my $label = $l1->[$i];
        if ( $label eq $l2->[$j] ) {
            push @data, $ydata->[$i];
            $j++;
        }
        else {
            push @data, undef;
        }
    }
    return \@data;
}

sub linear_interpolation {
    my ($data, $indices, $N) = @_;

    my @all_data = (undef) x $N;
    my $k = 0;
    for my $i (0..($#$data - 1)) {
        my $min = $data->[$i];
        my $max = $data->[$i + 1];
        my $N2 = $indices->[$i + 1] - $indices->[$i];
        my $step = ($max - $min) / $N2;
        for my $j (0..$N2) {
            $all_data[$k] = $min + $step * $j;
            $k++ if $j < $N2;
        }
    }
    return \@all_data;
}
</code>```

Body:
My line chart is good, but I would like to add vertical lines to indicate "timeline" dates.

use GD::Graph::linespoints;
use GD::Graph::Data;

my @label = qw(2019-05-05 2019-05-12 2019-05-19 2019-05-26);
my @data = (10, 20, 30, 40);
my @events = qw(2019-05-07 2019-05-15 2019-05-30);

my @input = (\@label, \@data);
my $data = GD::Graph::Data->new(\@input) or die GD::Graph::Data->error;
my $graph = GD::Graph::linespoints->new(1400,600);
$graph->set(
  x_label               => 'Week',
  x_label_position      => .5,
  y_label               => 'Things',
  y_min_value           => 0,
  title                 => 'Average Daily Things',
  x_labels_vertical     => 1,
  textclr               => 'orange',
  labelclr              => 'orange',
  axislabelclr          => 'gray',
  fgclr                 => 'green',
  bgclr                 => 'white',
  shadow_depth          => 3,
  markers               => 1,
  marker_size           => 2,
  shadowclr             => 'dgreen',
  transparent           => 0,
  dclrs                 => [ qw(blue) ],
) or die $graph->error;
$graph->plot($data) or die $graph->error;
my $file = 'testing.png';
open OUT, '>', $file or die "Cannot open '$file' for write: $!";
binmode OUT;
print OUT $graph->gd->png;
close OUT;

Desired output:

Vertical lines should be spaced between points based on actual date, but snapped to previous tick would also be acceptable.

The vertical line should fully traverse from top border to bottom border.

A text legend explaining the dates highlighted, if possible.

Body:
It seems it is not possible to add vertical lines at specific locations directly to a GD::Graph but you can add lines after doing $graph->plot() using GD::Polyline. For example:

use strict;
use warnings;
use GD::Graph::mixed;
use GD::Polyline;

my $start_day = 5;
my $end_day = 26;
my @data = (10, 20, 30, 40);
my @label = qw(2019-05-05 2019-05-12 2019-05-19 2019-05-26);
my @all_labels = map { sprintf "2019-05-%02d", $_ } $start_day..$end_day;
my $N = scalar @all_labels;
my $label_indices = get_event_indices( \@all_labels, \@label );
my $ydata = linear_interpolation(\@data, $label_indices, $N);
my @events = qw(2019-05-07 2019-05-15 2019-05-26);

my $points_data1 = get_point_data( \@all_labels, \@label, $ydata);

my @plot_data = (\@all_labels, $ydata, $points_data1);

my $width = 1400;
my $height = 600;
my $graph = GD::Graph::mixed->new($width, $height);
$graph->set(
  axislabelclr          => 'gray',
  bgclr                 => 'white',
  dclrs                 => [ qw(blue) ],
  fgclr                 => 'green',
  labelclr              => 'orange',
  marker_size           => 2,
  markers               => 1,
  shadowclr             => 'dgreen',
  shadow_depth          => 3,
  textclr               => 'orange',
  title                 => 'Average Daily Things',
  transparent           => 0,
  types                 => [ qw( lines points  ) ],
  x_label               => 'Week',
  x_label_position      => .5,
  x_label_skip          => 7,
  x_labels_vertical     => 1,
  y_label               => 'Things',
  y_min_value           => 0,
) or die $graph->error;
$graph->plot(\@plot_data) or die $graph->error;

my $event_indices = get_event_indices( \@all_labels, \@events );

plot_vertical_lines( $graph, $height, $event_indices );

my $file = 'testing.png';
open OUT, '>', $file or die "Cannot open '$file' for write: $!";
binmode OUT;
print OUT $graph->gd->png;
close OUT;

sub plot_vertical_lines {
    my ( $graph, $height, $event_indices ) = @_;

    my $gd = $graph->gd;
    my $black  = $gd->colorAllocate(  0,  0,  0);

    for my $idx ( @$event_indices ) {
        my @line = $graph->get_hotspot(1, $idx);
        my $x = $line[3];
        my $polyline = GD::Polyline->new();

        # add some points
        $polyline->addPt(  $x, 20);
        $polyline->addPt(  $x, $height - 70);
        $gd->setThickness( 2);
        $gd->polydraw($polyline, $black);
    }
}

sub get_event_indices {
    my ( $l1, $l2 ) = @_;

    my @idx;
    my $j = 0;
    for my $i (0..$#$l1) {
        my $label = $l1->[$i];
        if ( $label eq $l2->[$j] ) {
            push @idx, $i;
            $j++;
        }
    }
    return \@idx;
}

sub get_point_data {
    my ( $l1, $l2, $ydata) = @_;

    my @data;
    my $j = 0;
    for my $i (0..$#$l1) {
        my $label = $l1->[$i];
        if ( $label eq $l2->[$j] ) {
            push @data, $ydata->[$i];
            $j++;
        }
        else {
            push @data, undef;
        }
    }
    return \@data;
}

sub linear_interpolation {
    my ($data, $indices, $N) = @_;

    my @all_data = (undef) x $N;
    my $k = 0;
    for my $i (0..($#$data - 1)) {
        my $min = $data->[$i];
        my $max = $data->[$i + 1];
        my $N2 = $indices->[$i + 1] - $indices->[$i];
        my $step = ($max - $min) / $N2;
        for my $j (0..$N2) {
            $all_data[$k] = $min + $step * $j;
            $k++ if $j < $N2;
        }
    }
    return \@all_data;
}


问:
A structure with a pointer to itself inside the same structure
In this program i have a struct Node.There is another link pointer inside struct node.Can anyone explain how this link pointer works .What does the compiler does with this code snippet when it is run.What is the struct pointer converted to.Please explain to me what is happening at the machine level.Please excuse me if this is a stupid question.I am totally confused with this.

```<code>#include<stdio.h>
struct node{
  int data;
  struct node *link;
}*top=NULL;

void main(){

}
</code>```

This is the assembly code for this when i ran gcc -S

```<code>    .file   "test.c"
    .globl  top
    .bss
    .align 8
    .type   top, @object
    .size   top, 8
top:
    .zero   8
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    nop
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609"
    .section    .note.GNU-stack,"",@progbits
</code>```

答: It is not pointer  to itself. It is a pointer to another object of the same type (it can be assigned of course with the reference to the enclosing object as well). This is used to create a linked list when one object holds the reference to another.

Body:
In this program i have a struct Node.There is another link pointer inside struct node.Can anyone explain how this link pointer works .What does the compiler does with this code snippet when it is run.What is the struct pointer converted to.Please explain to me what is happening at the machine level.Please excuse me if this is a stupid question.I am totally confused with this.

#include<stdio.h>
struct node{
  int data;
  struct node *link;
}*top=NULL;

void main(){

}

This is the assembly code for this when i ran gcc -S

    .file   "test.c"
    .globl  top
    .bss
    .align 8
    .type   top, @object
    .size   top, 8
top:
    .zero   8
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    nop
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609"
    .section    .note.GNU-stack,"",@progbits


问:
TextAlignment is not working dynamically for checkbox
Android.Views.Textalignment is not working dynamically

I have tried the below code:

In load time:

```<code>CheckBox checkBox = new CheckBox(this);
checkBox.TextAlignment = Android.Views.TextAlignment.ViewStart;
</code>```

Dynamically change the alignment in a button click. But alignment not updated.

```<code>checkBox.TextAlignment = Android.Views.TextAlignment.Center;
</code>```

答:
```<code>        <CheckBox
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Check Box"
            android:gravity="center"
            android:textAlignment="center"/>
</code>```

make sure to use the width as match_parent ,

or a fixed size creater than the size of the checkbox text,

then you can use the textAlignment as center or anything you want

Body:
Android.Views.Textalignment is not working dynamically

I have tried the below code:

In load time:

CheckBox checkBox = new CheckBox(this);
checkBox.TextAlignment = Android.Views.TextAlignment.ViewStart;

Dynamically change the alignment in a button click. But alignment not updated.

checkBox.TextAlignment = Android.Views.TextAlignment.Center;

Body:
        <CheckBox
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Check Box"
            android:gravity="center"
            android:textAlignment="center"/>

make sure to use the width as match_parent ,

or a fixed size creater than the size of the checkbox text,

then you can use the textAlignment as center or anything you want


问:
How I can find specific words in the string and add class (Javascript)
There is a text in P element. In this text you can select some terms with a mouse click. But I want to display some previously selected words in a different class

I want to find special words in this text and add class.

Related part

```<code>var previosSelectedWords = 'aute,dolor,ex,sed,velit'; // previos selected words
var PSW = previosSelectedWords.split(',');

for (var i = 0; i < words.length; i++) {
    if (PSW[i] == words[i]) {
      wrapped.push('<span class="previosSelecteds">' + words[i] + '</span>');
    } else {
      wrapped.push('<span>' + words[i] + '</span>');
    }
  }
</code>```

But it doesn't show the pre-selected words. What could be the reason?

答:
The problem was your loop: You used the same loop and the same index for both arrays.</p>

```<code>   // Loop through each word and wrap
for (var j = 0; j < PSW.length; j++) {
    for (var i = 0; i < words.length; i++) {
        if (PSW[j] == words[i]) {
            var prevS = '<span class="previosSelecteds">' + words[i] + '</span>';
            words[i] = prevS;
        }
    }
}

for (var i = 0; i < words.length; i++) {
    if (!words[i].includes('previosSelecteds')) {
        wrapped.push('<span>' + words[i] + '</span>');
    }
    else {
        wrapped.push(words[i]);
    }
}
</code>```

Body:
There is a text in P element. In this text you can select some terms with a mouse click. But I want to display some previously selected words in a different class

I want to find special words in this text and add class.

Related part

var previosSelectedWords = 'aute,dolor,ex,sed,velit'; // previos selected words
var PSW = previosSelectedWords.split(',');

for (var i = 0; i < words.length; i++) {
    if (PSW[i] == words[i]) {
      wrapped.push('' + words[i] + '');
    } else {
      wrapped.push('' + words[i] + '');
    }
  }

But it doesn't show the pre-selected words. What could be the reason?

Body:
The problem was your loop: You used the same loop and the same index for both arrays.

   // Loop through each word and wrap
for (var j = 0; j < PSW.length; j++) {
    for (var i = 0; i < words.length; i++) {
        if (PSW[j] == words[i]) {
            var prevS = '<span class="previosSelecteds">' + words[i] + '</span>';
            words[i] = prevS;
        }
    }
}

for (var i = 0; i < words.length; i++) {
    if (!words[i].includes('previosSelecteds')) {
        wrapped.push('<span>' + words[i] + '</span>');
    }
    else {
        wrapped.push(words[i]);
    }
}


问:
Filling object fields value at runtime falls under which design pattern
just having a question in mind so thought lets get the views from expert. it might be a silly question.

Actually i am using Reflection Mechanism to fill the some of the fields value of a class at run time. lets say i have a class A with 5 fields. i'll set the value of 2 fields at compile time but the remaining three fields value i'll set at run time.

So my question is that does it fall under some Design pattern?

Regards,

Mahendra Athneria

答:
This is very close to what AutoFixture does. Its internal architecture is basically just a big Chain of Responsibility.

The Builder pattern also comes to mind.


问:
How to access previous value of a field in django model form before save?
I need to access the previous value of the Django model instance field before saving the form. For example in the form_valid method need to access previous values of the model instance. How can I achieve this?

答:
you can use copy your previous model instance with copy so that when you save your new instance it donot override your previous instance:

```<code>import copy

if form.is_valid():
    obj = YourModel.objects.get(pk=form.instance.pk)
    prev_obj = copy.copy(obj)
    // here you can access any field of your previous object related to that instance.
    // prev_obj.field
    new_obj = form.save()
</code>```

Note: this is only applicable if you are going to update your model not during creation.

Body:
you can use copy your previous model instance with copy so that when you save your new instance it donot override your previous instance:

import copy

if form.is_valid():
    obj = YourModel.objects.get(pk=form.instance.pk)
    prev_obj = copy.copy(obj)
    // here you can access any field of your previous object related to that instance.
    // prev_obj.field
    new_obj = form.save()

Note: this is only applicable if you are going to update your model not during creation.


问:
How to set client local endpoint - Java RMI
So I have a very basic client-server program running on my local lan network.
The program consists in the server being a permanent listener, adding every client who connects to his ip to a list of observers and updating them every 5 seconds (Client Extends UnicastRemoteObject).
The problem is that I don't know why the client creates a reference using an unknown ip address.

This is what I usually get from the client, if I type System.out.println(this):

```<code>RmiClient[UnicastServerRef [liveRef: [endpoint:[192.168.56.1:64199](local),objID:[32218df3:16acc934a0a:-7fff, 8241015111525045915]]]]
</code>```

I did some research and I found that ip address belongs to my VirtualBox Host-Only Newtork interface, so when I disable this I get the correct infos:

```<code>RmiClient[UnicastServerRef [liveRef: [endpoint:[192.168.1.3:64307](local),objID:[1b156947:16acc999fa5:-7fff, 6095931207093481175]]]]
</code>```

Which is the correct ip of this machine on my lan.
My question is how do I make this work without permanent disabling the interface?

Also if I set server and client on different machines, I get a RemoteException when the server tries to update the  clients because it tries to contact 192.168.56.1 and obviously fails.

答:
Solved! The problem consisted in the Client extending UnicastRemoteObject.
Apparently I had to set the property java.rmi.server.hostname in both client and server applications, but in the client that wasn't working because of the extension.
So I managed to solve by eliminating the extension and adding the following code:
UnicastRemoteObject.exportObject(this, port);

This way the propery works correctly on the client.

Body:
So I have a very basic client-server program running on my local lan network.
The program consists in the server being a permanent listener, adding every client who connects to his ip to a list of observers and updating them every 5 seconds (Client Extends UnicastRemoteObject).
The problem is that I don't know why the client creates a reference using an unknown ip address.

This is what I usually get from the client, if I type System.out.println(this):

RmiClient[UnicastServerRef [liveRef: [endpoint:[192.168.56.1:64199](local),objID:[32218df3:16acc934a0a:-7fff, 8241015111525045915]]]]

I did some research and I found that ip address belongs to my VirtualBox Host-Only Newtork interface, so when I disable this I get the correct infos:

RmiClient[UnicastServerRef [liveRef: [endpoint:[192.168.1.3:64307](local),objID:[1b156947:16acc999fa5:-7fff, 6095931207093481175]]]]

Which is the correct ip of this machine on my lan.
My question is how do I make this work without permanent disabling the interface?

Also if I set server and client on different machines, I get a RemoteException when the server tries to update the  clients because it tries to contact 192.168.56.1 and obviously fails.


问:
Angular casting HttpClient response - class or interface
I saw two methods to convert a response to our custom data model.

Interface

```<code>export interface User {
  id: number;
  name: string;
  more_complex_object: // so I am not sure how do this in right way. pass here another interface
  //or just a object like {id: '', name: ''}. I show how to do this in class way...
}
</code>```

And in service:

```<code>return this.http.get<User>...
</code>```

And its fine, no need to do something more.

Class

```<code>export interface Deserializable {
  deserialize(input: any): this;
}

export class ComplexModel implements Deserializable {
  field1: string;
  field2: number;
  field3: number;

  deserialize(input: any): this {
    Object.assign(this, input);
    return this;
  }
}

export class User implements Deserializable {
 id: number;
 name: string;
 complex: ComplexModel;

 deserialize(input: any): this {
   Object.assign(this, input);
   this.complex = new ComplexModel().deserialize(input.complex));
   return this;
 }
}
</code>```

And in service

```<code>return this.http.get('/users/id/').pipe(
  map(user => new User().deserialize(user))
);
</code>```

As we can see in class method we must manually creating a object. Its fine with object like above, but when we have more complex object, or array of object we must do something like this:

```<code>return this.http.get('/users').pipe(
  map(users => {
    if (users instanceof Array) { // <- to avoid 'object has no method map' error
      return users.map(user => {
        return new User().deserialize(user);
      });
    }
  })
);
</code>```

In class way we have much more complex code. And finally, the questions:

Any idea how do it as best as possible?
Which methods is the best for you and why?

Interface-way looks more beautiful, but we don't have 'a real object' so we can't use class-methods, etc, right?

In class-way we get a real object, but is it so much needed?

答:
There is an explanation for this in the book: "Angular Up and Running" by Shyam Seshadri.
I am quoting directly from the book Ch9 Making HTTP Calls in Angular p.178:

"One important thing to note is that the HttpClient can give you type-assurance
across your code. We leverage this feature in the getStocks() and the toggleFavor
ite() methods.
One effect of this is that we need to change our stock.ts from a TypeScript class to a
TypeScript interface.
Why is this? While we don’t need to, Angular does a simple typecast of the response body into the type we have defined. But TypeScript (and
ECMAScript underneath it) has no nice and easy way to convert a simple plain-old
JavaScript object into a prototypical JavaScript/TypeScript class object.
This means
that while our response from StockService will have all the properties of the class
Stock, it would not have the functions (in particular, isPositiveChange()) available.
We could write a converter, but it is only worth it in very specific cases. It is easier to
simply leverage TypeScript for type safety and work with other ways of encapsulation
(either at a component level, or maybe as an Angular service)."

Please refer to the book for more explanation

Body:
I saw two methods to convert a response to our custom data model.

Interface

export interface User {
  id: number;
  name: string;
  more_complex_object: // so I am not sure how do this in right way. pass here another interface
  //or just a object like {id: '', name: ''}. I show how to do this in class way...
}

And in service:

return this.http.get<User>...

And its fine, no need to do something more.

Class

export interface Deserializable {
  deserialize(input: any): this;
}

export class ComplexModel implements Deserializable {
  field1: string;
  field2: number;
  field3: number;

  deserialize(input: any): this {
    Object.assign(this, input);
    return this;
  }
}

export class User implements Deserializable {
 id: number;
 name: string;
 complex: ComplexModel;

 deserialize(input: any): this {
   Object.assign(this, input);
   this.complex = new ComplexModel().deserialize(input.complex));
   return this;
 }
}

And in service

return this.http.get('/users/id/').pipe(
  map(user => new User().deserialize(user))
);

As we can see in class method we must manually creating a object. Its fine with object like above, but when we have more complex object, or array of object we must do something like this:

return this.http.get('/users').pipe(
  map(users => {
    if (users instanceof Array) { // <- to avoid 'object has no method map' error
      return users.map(user => {
        return new User().deserialize(user);
      });
    }
  })
);

In class way we have much more complex code. And finally, the questions:

Any idea how do it as best as possible?
Which methods is the best for you and why?

Interface-way looks more beautiful, but we don't have 'a real object' so we can't use class-methods, etc, right?

In class-way we get a real object, but is it so much needed?


问:
Traversing an array to find the second largest element in linear time
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.

Solution : Sort the array and take the second element but Sorting not allowed

Modification : By definition second largest element will be the one which is numerically smaller. Like if we have

Arr = {5,5,4,3,1}
Then second largest is 4

Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.

答:
You can, this is the pseudo algorithm:

```<code>max = 2max = SMALLEST_INT_VALUE;

for element in v:
   if element > max:
      2max = max;
      max = element;

  else if element > 2max:
      2max = element;
</code>```

2max is the value you are looking for.

The algorithm won't return a correct value for particular cases, such as an array where its elements are equal.

Body:
You can, this is the pseudo algorithm:

max = 2max = SMALLEST_INT_VALUE;

for element in v:
   if element > max:
      2max = max;
      max = element;

  else if element > 2max:
      2max = element;

2max is the value you are looking for.

The algorithm won't return a correct value for particular cases, such as an array where its elements are equal.


问:
Vlookup on fulfilment of certain condition
Within my Google sheet I need to find a value in a specific range (say A15:A45) when the row value in another column (Say Column D) exceeds a specific cell value (Say C20). How do I write the syntax?

I did try using Vlookup and If combination. Also tried using query. However I think I am making some mistake in the arguments. either I get an error or I do not get any outcome.

答:
Assuming C20 and ColumnD are Numeric (other than a label) then perhaps:

```<code>=query(A:D,"select A where D > "&C20&"")
</code>```

VLOOKUP would not be suitable as this does not "look to its left" and an INDEX/MATCH combination would not be suitable for multiple results.

Body:
Assuming C20 and ColumnD are Numeric (other than a label) then perhaps:

=query(A:D,"select A where D > "&C20&"")

VLOOKUP would not be suitable as this does not "look to its left" and an INDEX/MATCH combination would not be suitable for multiple results.


问:
Can you use variables for interface properties?
Let's say I have the classic example of discriminated union:

```<code>interface Circle {
  type: 'circle';
  radius: number;
}
interface Square {
  type: 'square';
  width: number;
}
type Shape = Circle | Square;
</code>```

And then I throw it in a switch case:

```<code>switch (shape.type) {
  case 'circle':
    ...
  case 'square':
    ...
}
</code>```

Is it possible to use variables to allow me to reference the discriminant in a singular way?

答:
You can define constants. Their types will be inferred as literal types. Then you can use typeof operator to get the type of the variable:

```<code>const circle = 'circle';
const square = 'square';

interface Circle {
  type: typeof circle;
  radius: number;
}
interface Square {
  type: typeof square;
  width: number;
}

type Shape = Circle | Square;
declare const shape: Shape;

switch (shape.type) {
  case circle:
    // ...
  case square:
    // ...
}
</code>```

Playground

Body:
Let's say I have the classic example of discriminated union:

interface Circle {
  type: 'circle';
  radius: number;
}
interface Square {
  type: 'square';
  width: number;
}
type Shape = Circle | Square;

And then I throw it in a switch case:

switch (shape.type) {
  case 'circle':
    ...
  case 'square':
    ...
}

Is it possible to use variables to allow me to reference the discriminant in a singular way?

Body:
You can define constants. Their types will be inferred as literal types. Then you can use typeof operator to get the type of the variable:

const circle = 'circle';
const square = 'square';

interface Circle {
  type: typeof circle;
  radius: number;
}
interface Square {
  type: typeof square;
  width: number;
}

type Shape = Circle | Square;
declare const shape: Shape;

switch (shape.type) {
  case circle:
    // ...
  case square:
    // ...
}

<a href="https://www.typescriptlang.org/play/index.html#src=const%20circle%20%3D%20'circle'%3B%0Aconst%20square%20%3D%20'square'%3B%0A%0Ainterface%20Circle%20%7B%0A%20%20type%3A%20typeof%20circle%3B%0A%20%20radius%3A%20number%3B%0A%7D%0Ainterface%20Square%20%7B%0A%20%20type%3A%20typeof%20square%3B%0A%20%20width%3A%20number%3B%0A%7D%0A%0Atype%20Shape%20%3D%20Circle%20%7C%20Square%3B%0Adeclare%20const%20shape%3A%20Shape%3B%0A%0Aswitch%20(shape.type)%20%7B%0A%20%20case%20circle%3A%0A%20%20%20%20%2F%2F%20...%0A%20%20case%20square%3A%0A%20%20%20%20%2F%2F%20...%0A%7D" rel="nofollow noreferrer">Playground


答:
Go through the array, keeping 2 memory slots to record the 2 largest elements seen so far.  Return the smaller of the two.

.... is there anything tricky about this question that I can't see?

Title: Traversing an array to find the second largest element in linear time

Body:
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.

Solution : Sort the array and take the second element but Sorting not allowed

Modification : By definition second largest element will be the one which is numerically smaller. Like if we have

Arr = {5,5,4,3,1}
Then second largest is 4

Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.


问:
How can I stop the countdown until the localStorage expires?
The following script makes a countdown until it reaches the set number (in this case 76), after which it starts again the countdown and so on. Updating the page the countdown does not reset until the localStorage expires.

I want that when the countdown reaches 76 it stops and doesn't start counting again. This until the localStorage expires. Please how can I do this?

```

```var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (+max - +min)) + +min;

if (localStorage.getItem("counter")) {
  if (localStorage.getItem("counter") >= 1000000000) { // Duration of localStorage
    var value = random;
  } else {
    var value = localStorage.getItem("counter");
  }
} else {
  var value = random;
}

document.getElementById('divCounter').innerHTML = value;

var counter = function () {
  if (value <= 76) { // End count down. <= or >=
    localStorage.setItem("counter", random);
    value = random;
  } else {
    value = parseInt(value) - 1; // + 1 or - 1
    localStorage.setItem("counter", value);
  }

  document.getElementById('divCounter').innerHTML = value;
};

var interval = setInterval(function () {
  counter();
}, 1000); // speed count
```

答: There are a lot of issues with this code, but given how it is here, you need to call clearInterval(interval) when value <= 76 to stop localStorage from changing again at that point.</p>

Body:
The following script makes a countdown until it reaches the set number (in this case 76), after which it starts again the countdown and so on. Updating the page the countdown does not reset until the localStorage expires.

I want that when the countdown reaches 76 it stops and doesn't start counting again. This until the localStorage expires. Please how can I do this?

var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (+max - +min)) + +min;

if (localStorage.getItem("counter")) {
  if (localStorage.getItem("counter") >= 1000000000) { // Duration of localStorage
    var value = random;
  } else {
    var value = localStorage.getItem("counter");
  }
} else {
  var value = random;
}

document.getElementById('divCounter').innerHTML = value;

var counter = function () {
  if (value <= 76) { // End count down. <= or >=
    localStorage.setItem("counter", random);
    value = random;
  } else {
    value = parseInt(value) - 1; // + 1 or - 1
    localStorage.setItem("counter", value);
  }

  document.getElementById('divCounter').innerHTML = value;
};

var interval = setInterval(function () {
  counter();
}, 1000); // speed count


问:
How to simulate ```WHERE``` from SQL or ```grep``` in Python to iterate and change data with certain attributes?
I'm looking for a quick and simple tool to simulate WHERE from SQL. In a collection (list, set, dictionary, etc) of objects (each of which should be a list or class instance), I'd like to pick out just those with some certain properties/attributes and process them.

Example 1:

```<code>stuff = {
    "item1":[1,2,3],
    "item2":[4,5,6,7,8,9],
    "item3":[2,4,5]
}

def myfunc(this): # this is the dict above
    result = list()
    for item in this:
        if len(item) == 3:
            result.append(item)
    return result
</code>```

In example 1, myfunc simulates return items in stuff WHERE len(item)==3 which looks for and returns objects with length 3 in the dictionary stuff.

Example 2:

```<code>class thing:
    def init(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

item1 = thing(1,2,3)
item2 = thing(2,3,4)
item3 = thing(3,5,7)
test_list = [item1, item2, item3]

def func(this): # this is the test_list
    result = list()
    for item in this:
        if item.a % 2:
            result.append(item)
    return result
</code>```

In example 2, func simulates return items in test_list WHERE (item.a % 2) == 1 which returns objects where object.a is odd.

In both examples, a collection of objects is scanned for certain attributes that meet certain conditions and return those objects to be processed.

答:
Hacky code ahead (better solution below)

You can implement __iter__ in a away that it will return all the attributes of the instance, then you will be able to pretty much achieve what you are looking for:

```<code>class particle:
    def __init__(self):
        self.x = 90
        self.y = 70

    def __iter__(self):
        yield from self.__dict__

particles = [particle() for _ in range(2)]

for particle in particles:
    for attribute in particle:
        current_val = getattr(particle, attribute)
        if isinstance(current_val, int):
            setattr(particle, attribute, current_val - 1)

for particle in particles:
    print(particle.x, particle.y)
</code>```

Outputs

```<code>89 69
89 69
</code>```

The better solution

However I do not think this is the correct approach. A better way may be to implement the attribute modification inside the class itself.

```<code>class particle:
    def __init__(self):
        self.x = 90
        self.y = 70

    def change_all_attributes(self, attr_type, change_by):
        for attr_name, attr_value in self.__dict__.items():
            if isinstance(attr_value, attr_type):
                setattr(self, attr_name, attr_value + change_by)

particles = [particle() for _ in range(2)]

for particle in particles:
    particle.change_all_attributes(int, -1)
    print(particle.x, particle.y)
</code>```

Outputs

```<code>89 69
89 69
</code>```

What you get:

More idiomatic code. The change in the attribute is done by the class, not by arbitrary nested loop somewhere in your code (easier to debug).

A builtin way to control the type of the modified attributes and by how much they change

This can be taken a step further by using properties' getters and setters.

Body:
I'm looking for a quick and simple tool to simulate WHERE from SQL. In a collection (list, set, dictionary, etc) of objects (each of which should be a list or class instance), I'd like to pick out just those with some certain properties/attributes and process them.

Example 1:

stuff = {
    "item1":[1,2,3],
    "item2":[4,5,6,7,8,9],
    "item3":[2,4,5]
}

def myfunc(this): # this is the dict above
    result = list()
    for item in this:
        if len(item) == 3:
            result.append(item)
    return result

In example 1, myfunc simulates return items in stuff WHERE len(item)==3 which looks for and returns objects with length 3 in the dictionary stuff.

Example 2:

class thing:
    def init(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

item1 = thing(1,2,3)
item2 = thing(2,3,4)
item3 = thing(3,5,7)
test_list = [item1, item2, item3]

def func(this): # this is the test_list
    result = list()
    for item in this:
        if item.a % 2:
            result.append(item)
    return result

In example 2, func simulates return items in test_list WHERE (item.a % 2) == 1 which returns objects where object.a is odd.

In both examples, a collection of objects is scanned for certain attributes that meet certain conditions and return those objects to be processed.

Body:
Hacky code ahead (better solution below)

You can implement __iter__ in a away that it will return all the attributes of the instance, then you will be able to pretty much achieve what you are looking for:

class particle:
    def __init__(self):
        self.x = 90
        self.y = 70

    def __iter__(self):
        yield from self.__dict__

particles = [particle() for _ in range(2)]

for particle in particles:
    for attribute in particle:
        current_val = getattr(particle, attribute)
        if isinstance(current_val, int):
            setattr(particle, attribute, current_val - 1)

for particle in particles:
    print(particle.x, particle.y)

Outputs

89 69
89 69

The better solution

However I do not think this is the correct approach. A better way may be to implement the attribute modification inside the class itself.

class particle:
    def __init__(self):
        self.x = 90
        self.y = 70

    def change_all_attributes(self, attr_type, change_by):
        for attr_name, attr_value in self.__dict__.items():
            if isinstance(attr_value, attr_type):
                setattr(self, attr_name, attr_value + change_by)

particles = [particle() for _ in range(2)]

for particle in particles:
    particle.change_all_attributes(int, -1)
    print(particle.x, particle.y)

Outputs

89 69
89 69

What you get:

More idiomatic code. The change in the attribute is done by the class, not by arbitrary nested loop somewhere in your code (easier to debug).

A builtin way to control the type of the modified attributes and by how much they change

This can be taken a step further by using properties' getters and setters.


答:
You can use a render prop but you have to branch inside the render function of HierarchyGraph to detect whether or not you have to make the call. Otherwise the request is triggered multiple times. Here is a quick example:

```<code>const HierarchyGraph = () => {
  const [rootNode, setRootNode] = useState(null);

  if (!rootNode) {
    return (
      <Fetcher
        url="/hierarchy"
        initialData={{}}
        render={({ data }) => {
          setRootNode(getHierarchy(data));
        }}
      />
    );
  }

  return <div>render the data related to rootNode</div>;
};
</code>```

An alternative solution is to inline the call inside the render function and perform the operation on each render. It depends on the use case but if the operation is cheap it might be simpler. The last alternative is to leverage useEffect rather than the Fetcher component. Its usage would be more suited than the render prop pattern since you can explicitly trigger the call to the API only once.

Title: how to handle useEffect with render props in react

Body:
I want to use a render props function with hooks but I am not entirely sure if this is possible.

I have a FetcherComponent that takes a renderprop but I want to use a setState from

export const HierarchyGraph: React.FunctionComponent = () => {
  const [rootNode, setRootNode] = useState<HierarchyNode<GraphicalNode> | null>(null);

  return (
    <Fetcher
      url="/hierarchy"
      initialData={{}}
      render={({ data }: { data: TreeData }) => {
          // this will cause infinite recursion
          setRootNode(getHierarchy(data));

Should I not use render props in this situation?

Body:
You can use a render prop but you have to branch inside the render function of HierarchyGraph to detect whether or not you have to make the call. Otherwise the request is triggered multiple times. Here is a quick example:

const HierarchyGraph = () => {
  const [rootNode, setRootNode] = useState(null);

  if (!rootNode) {
    return (
      <Fetcher
        url="/hierarchy"
        initialData={{}}
        render={({ data }) => {
          setRootNode(getHierarchy(data));
        }}
      />
    );
  }

  return <div>render the data related to rootNode</div>;
};

An alternative solution is to inline the call inside the render function and perform the operation on each render. It depends on the use case but if the operation is cheap it might be simpler. The last alternative is to leverage useEffect rather than the Fetcher component. Its usage would be more suited than the render prop pattern since you can explicitly trigger the call to the API only once.


问:
MVC3 two partial views in one view
I am trying to learn MVC 3 & Razor and I'm stuck here for 3 hours now. This is what I have

MVC project created using the default template with Account registration and all that good stuff from the template. What I'm trying to do is have both registration page and login page in the index of the HomeController so I created a partial view for both Register (_RegisterPartial) and LogOn (_LogOnPartial). When I go to the index page, I see the registration and login forms which is good but when I try to login or register it goes into an infinite loop.

My HomeController looks like this;

```<code>// **************************************
// Registration
// **************************************

public ActionResult DoRegister()
{
    return PartialView("_Register");
}

[HttpPost]
public ActionResult DoRegister(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.UserProfile);

        if (createStatus == MembershipCreateStatus.Success)
        {
            FormsService.SignIn(model.UserName, false); // createPersistentCookie
            return View("Success");
        }
        else
        {
            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        }
    }

    // If we got this far, something failed, redisplay form
    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
    return View(model);
}

// **************************************
// Login
// **************************************

public ActionResult DoLogin()
{
    return PartialView("_Login");
}

[HttpPost]
public ActionResult DoLogin(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            // logged in
            FormsService.SignIn(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl))
            {
                Redirect(returnUrl);
            }
            else
            {
                View("Success");
            }
        }
        else
        {
            // Not logged in
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View("Success");
}
</code>```

and my cshtml looks like this;

```<code>@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (Request.IsAuthenticated)
{
    @Html.ActionLink("Log Off", "LogOff", "Account")
}
else
{
    Html.RenderAction("DoLogin");
    Html.RenderAction("DoRegister");
}
</code>```

Regards,

Ryan

答:
I can't exactly replicate your situation but I would say that you partial forms are not posting correctly. Have a look a rendered html of the page and check where the forms are being posted to. My guess is that they are being posted to the Index action. Coupled with the redirect, I think that is where the infinite loop is coming from.

My guess is the html rendered for both forms are similar and posting to the same action i.e. <form action="/" method="post">, since they are being rendered by the HomeController's Index action.

Change the partial forms (_Login.cshtml and _Register.cshtml) and explicitly state which action/controller combination to post to (more on Html.BeginForm from MSDN)

```<code>@using (Html.BeginForm("DoLogin","Home"))    {/*snipped*/} //in _Login.cshtml
@using (Html.BeginForm("DoRegister","Home")) {/*snipped*/} //in _Register.cshtml
</code>```

Also I would change the Html.RenderAction calls to

```<code>Html.RenderPartial("_Login");
Html.RenderPartial("_Register");
</code>```

Title: MVC3 two partial views in one view

Body:
I am trying to learn MVC 3 & Razor and I'm stuck here for 3 hours now. This is what I have

MVC project created using the default template with Account registration and all that good stuff from the template. What I'm trying to do is have both registration page and login page in the index of the HomeController so I created a partial view for both Register (_RegisterPartial) and LogOn (_LogOnPartial). When I go to the index page, I see the registration and login forms which is good but when I try to login or register it goes into an infinite loop.

My HomeController looks like this;

// **************************************
// Registration
// **************************************

public ActionResult DoRegister()
{
    return PartialView("_Register");
}

[HttpPost]
public ActionResult DoRegister(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.UserProfile);

        if (createStatus == MembershipCreateStatus.Success)
        {
            FormsService.SignIn(model.UserName, false); // createPersistentCookie
            return View("Success");
        }
        else
        {
            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        }
    }

    // If we got this far, something failed, redisplay form
    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
    return View(model);
}

// **************************************
// Login
// **************************************

public ActionResult DoLogin()
{
    return PartialView("_Login");
}

[HttpPost]
public ActionResult DoLogin(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            // logged in
            FormsService.SignIn(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl))
            {
                Redirect(returnUrl);
            }
            else
            {
                View("Success");
            }
        }
        else
        {
            // Not logged in
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View("Success");
}

and my cshtml looks like this;

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (Request.IsAuthenticated)
{
    @Html.ActionLink("Log Off", "LogOff", "Account")
}
else
{
    Html.RenderAction("DoLogin");
    Html.RenderAction("DoRegister");
}

Regards,

Ryan

Body:
I can't exactly replicate your situation but I would say that you partial forms are not posting correctly. Have a look a rendered html of the page and check where the forms are being posted to. My guess is that they are being posted to the Index action. Coupled with the redirect, I think that is where the infinite loop is coming from.

My guess is the html rendered for both forms are similar and posting to the same action i.e. <form action="/" method="post">, since they are being rendered by the HomeController's Index action.

Change the partial forms (_Login.cshtml and _Register.cshtml) and explicitly state which action/controller combination to post to (more on Html.BeginForm from MSDN)

@using (Html.BeginForm("DoLogin","Home"))    {/*snipped*/} //in _Login.cshtml
@using (Html.BeginForm("DoRegister","Home")) {/*snipped*/} //in _Register.cshtml

Also I would change the Html.RenderAction calls to

Html.RenderPartial("_Login");
Html.RenderPartial("_Register");


问:
How to use token-based authentication with axios and react
There is 401 error(Invalid or not provided access token), How to pass token correctly with axios, This is my code &
API documentation: https://trefle.io

答:
From trefle docs, you first need to request a client-side token which will return JWT token, that'll be used to make requests from client side.

```<code>// requst JWT token
https://trefle.io/api/auth/claim?token=YOUR-TOKEN&origin=YOUR-WEBSITE-URL
</code>```

The plant endpoint accepts two params, id path parameter and token query parameter.

You need to pass your token as a query parameter.

```<code>componentDidMount = () => {

    axios.get('https://trefle.io/api/plants/103505?token=YOURTOKEN')
      .then(res => {
        console.log(res)
      })
      .catch(e => console.log(e))
}
</code>```

or

```<code>componentDidMount = () => {

    axios.get('https://trefle.io/api/plants/103505', {
      params: {
        token: 'YOURTOKEN'
      }
    })
      .then(res => {
        console.log(res)
      })
      .catch(e => console.log(e))
}
</code>```

Body:
From trefle docs, you first need to request a client-side token which will return JWT token, that'll be used to make requests from client side.

// requst JWT token
https://trefle.io/api/auth/claim?token=YOUR-TOKEN&origin=YOUR-WEBSITE-URL

The plant endpoint accepts two params, id path parameter and token query parameter.

You need to pass your token as a query parameter.

componentDidMount = () => {

    axios.get('https://trefle.io/api/plants/103505?token=YOURTOKEN')
      .then(res => {
        console.log(res)
      })
      .catch(e => console.log(e))
}

or

componentDidMount = () => {

    axios.get('https://trefle.io/api/plants/103505', {
      params: {
        token: 'YOURTOKEN'
      }
    })
      .then(res => {
        console.log(res)
      })
      .catch(e => console.log(e))
}


问:
React native, scrollView is trimming the empty 'view' components(having background color as well)
New to react native,  I have a view component with flex direction as row, now it is nested with two view components with background colours pink and blue respectively. It renders as expected.

without Scrollview image

```<code><View style={{flex:1, flexDirection:'row'}}>
    <View style ={{flex:0.3, backgroundColor: 'pink'}}>
    </View>
    <View style ={{flex:0.7, backgroundColor: 'blue'}}>
    </View>
</View>
</code>```

Now if i wrap above code inside scrollView then nothing is being rendered on screen. It is trimming the empty view components.I want scrollview also should render the empty view components with background colours.
with scrollview image

```<code><View style={{flex:1}}>
    <ScrollView style={{flex:1}}>
        //above code here
    </ScrollView>
</View>
</code>```

答:
change ScrollView style prop to contentContainerStyle like this:

```<code> <ScrollView contentContainerStyle={{flex:1}}>
</code>```

check this link:
style vs contentContainerStyle

Body:
New to react native,  I have a view component with flex direction as row, now it is nested with two view components with background colours pink and blue respectively. It renders as expected.

without Scrollview image

<View style={{flex:1, flexDirection:'row'}}>
    <View style ={{flex:0.3, backgroundColor: 'pink'}}>
    </View>
    <View style ={{flex:0.7, backgroundColor: 'blue'}}>
    </View>
</View>

Now if i wrap above code inside scrollView then nothing is being rendered on screen. It is trimming the empty view components.I want scrollview also should render the empty view components with background colours.
with scrollview image

<View style={{flex:1}}>
    <ScrollView style={{flex:1}}>
        //above code here
    </ScrollView>
</View>

Body:
change ScrollView style prop to contentContainerStyle like this:

 <ScrollView contentContainerStyle={{flex:1}}>

check this link:
style vs contentContainerStyle


问:
Wordpress Heartbeat API minimal interval
What is the minimal interval between pulses in Wordpress Heartbeat API? I am referring to changing default interval, not this other feature allowing to temporary speed pulses for 2,5 minutes.

Is this good idea to lower this interval under 5 seconds?

If there is Heartbeat pulse waiting for response from server, will there be next pulse send even if previous one is not completed? Or it will wait until previous one is completed and then send next one?

答: I believe the lowest interval available is every 15 seconds.</p>


问:
How can I create a BST by reading from a text file?
I have to create a database of students, that contains their ID, name, surname, and grade. This information is read from a txt file that looks like this:

```<code>AE797989 Spears Michael 10.00
AA566734 Walsh Brad 10.00
AE808090 Jones Dimitris 5.00
...
</code>```

and contains 19 students

I have to read each line of the file and create a binary search tree based on their ID. There seems to be a problem when I'm creating a node, because when I try to search a student I can't. Here's my code:

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

struct node
{
    struct node *left;
    char ID[100];
    char NAME[100];
    char LAST_NAME[100];
    float Grade;
    struct node *right;
};

struct node *newNode(char, char, char, float);
struct node *insertNode(struct node node, char id, char name, char last_name, float grade);
void search(struct node *root, char *ID);
void deleteFromBST(char *ID);

int main()
{

  char ID[100];
  int insertDone = 0;
  int ch;

  while (1) {
    printf("\n1. Insertion\t2. Deletion\n");
    printf("3. Searching\t4. Display In Order\n5. Edit\t        6. Exit\n");
    printf("Enter your choice:");
    scanf("%d", &ch);

    switch (ch) {
    case 1:
      if (insertDone)
        puts("Inserton was already done");
      else {
        struct node* insertNode(struct node *node,char *id, char *name, char *last_name, float grade)
        {
            if (node == NULL)
            return newNode(*id,*name,*last_name,grade);

            if ( strcmp(id , node->ID) < 0)
            node->left = insertNode(node->left,id,name,last_name,grade);

            else if ( strcmp( id , node->ID) >= 0)
            node->right = insertNode(node->right,id,name,last_name,grade);

            return node;
        }
        insertDone = 1;
      }
      break;

    case 2:
      break;

    case 3:
      printf("Enter the AM to search:");
      scanf("%99s", ID);
      void search(struct node *root, char *ID)
        {
        int flag=0;

        if (!root)
        {
        printf("Search element unavailable in BST\n");
        return;
        }

        while (root != NULL) {
        if (strcmp(root->ID, ID) == 0) {
            printf("Student ID  : %s\n", root->ID);
            printf("First Name     : %s\n", root->NAME);
            printf("Last Name     : %s\n", root->LAST_NAME);
            printf("grade      : %lg\n", root->Grade);
            flag = 1;
            break;
             }

        else if (strcmp(ID , root->ID) > 0)
        {
         return search(root->right,ID);
        }

        else if(strcmp(ID , root->ID) < 0)
        {
        return search(root->left,ID);
        }

          if (!flag)
          printf("Search element unavailable in BST\n");
        }
       }

      break;
    case 4:
      //display();
      break;
    case 5:
      break;
    case 6:
      exit(0);
    default:
      printf("U have entered wrong option!!\n");
      break;
    }
  }
  struct node* newNode(char *id, char *name, char *last_name, float grade)
{

  struct node *newnode = malloc(sizeof(struct node));
  struct node Node;

  FILE *fp;
  fp = fopen ("Foitites-Vathmologio-DS.txt","rb");

  if (fp == NULL)
  {
    fprintf(stderr,"Could not open file");
    return;
  }

  char line[4096];

  while (fgets(line, sizeof line,fp))
  {
    size_t len = strlen(line);
    if (len && (line[len - 1] == '\n'))
    {
      /* incomplete line */
      if (sscanf(line,"%99s %99s %99s %f",Node.ID, Node.NAME, Node.LAST_NAME, &Node.Grade) != 4)
      {
      puts("invalid file");
      return;
      }

    strcpy(newnode->ID , id);
    strcpy(newnode->NAME , name);
    strcpy(newnode->LAST_NAME , last_name);
    newnode->Grade = grade;
    newnode->left = newnode->right = NULL;
    return newnode;

    }
  }
fclose(fp);
}
  return 0;
}
</code>```

I get no error messages.. thank you for your time!

答:
If you get no error message with this code, I would suggest you to use a different compiler. Mine chokes in main at:

```<code>    switch (ch) {
    case 1:
        if (insertDone)
            puts("Inserton was already done");
        else {
            struct node* insertNode(struct node *node, char *id, char *name,
                   char *last_name, float grade)      // ERROR HERE
            {
                if (node == NULL)
</code>```

It looks that you have copied the definition of the function instead of just calling it.

My problem is that you managed to write many different errors in a single program. And the global design of how the program should be structured is not clear: it looks like you started coding without first writing on a paper (yes papers and pencils are still very good tools for beginners) what each function should do, what was its its inputs and what should be its outputs and eventually what data it was including (for example what part is in charge of the file name). Of course, I could write a BST program for you, but you would not learn anything from that.

So here are some hints:

in a BST, you insert new data under existing nodes so you will need a function insertNode with following input parameters: the current root node (or NULL at first time), the id, name, last_name and grade to insert. You should build a new copy of the input strings (strdup is your friend). This function will allocate a new structure, fills is fields, and either return it if the current root was NULL, or insert it at its correct place in the existing tree

you want to process all lines from a file. You will need a function that open the file, read it line by line and will use previous one to insert the new record in the BST

BTW a function definition is something like

```<code>struct node *insert(struct node *root, const char id*, const char *name, const char *last_name, float grade) {
    struct node * newnode = malloc(sizeof *newnode);
    ...
    return root;
}
</code>```

outside of any other function definition, while a function call will be like:

```<code>struc node *root = NULL;
char id[100], name[100], last_name[100];
float grade;
...
      if (sscanf(line,"%99s %99s %99s %f",id, name, last_name, &grade)) != 4)
      {
      puts("invalid file");
      return;
      }
      root = insert(root, id, name, last_name, grade);  // here is the function call
</code>```

Body:
I have to create a database of students, that contains their ID, name, surname, and grade. This information is read from a txt file that looks like this:

AE797989 Spears Michael 10.00
AA566734 Walsh Brad 10.00
AE808090 Jones Dimitris 5.00
...

and contains 19 students

I have to read each line of the file and create a binary search tree based on their ID. There seems to be a problem when I'm creating a node, because when I try to search a student I can't. Here's my code:

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

struct node
{
    struct node *left;
    char ID[100];
    char NAME[100];
    char LAST_NAME[100];
    float Grade;
    struct node *right;
};

struct node *newNode(char, char, char, float);
struct node *insertNode(struct node node, char id, char name, char last_name, float grade);
void search(struct node *root, char *ID);
void deleteFromBST(char *ID);

int main()
{

  char ID[100];
  int insertDone = 0;
  int ch;

  while (1) {
    printf("\n1. Insertion\t2. Deletion\n");
    printf("3. Searching\t4. Display In Order\n5. Edit\t        6. Exit\n");
    printf("Enter your choice:");
    scanf("%d", &ch);

    switch (ch) {
    case 1:
      if (insertDone)
        puts("Inserton was already done");
      else {
        struct node* insertNode(struct node *node,char *id, char *name, char *last_name, float grade)
        {
            if (node == NULL)
            return newNode(*id,*name,*last_name,grade);

            if ( strcmp(id , node->ID) < 0)
            node->left = insertNode(node->left,id,name,last_name,grade);

            else if ( strcmp( id , node->ID) >= 0)
            node->right = insertNode(node->right,id,name,last_name,grade);

            return node;
        }
        insertDone = 1;
      }
      break;

    case 2:
      break;

    case 3:
      printf("Enter the AM to search:");
      scanf("%99s", ID);
      void search(struct node *root, char *ID)
        {
        int flag=0;

        if (!root)
        {
        printf("Search element unavailable in BST\n");
        return;
        }

        while (root != NULL) {
        if (strcmp(root->ID, ID) == 0) {
            printf("Student ID  : %s\n", root->ID);
            printf("First Name     : %s\n", root->NAME);
            printf("Last Name     : %s\n", root->LAST_NAME);
            printf("grade      : %lg\n", root->Grade);
            flag = 1;
            break;
             }

        else if (strcmp(ID , root->ID) > 0)
        {
         return search(root->right,ID);
        }

        else if(strcmp(ID , root->ID) < 0)
        {
        return search(root->left,ID);
        }

          if (!flag)
          printf("Search element unavailable in BST\n");
        }
       }

      break;
    case 4:
      //display();
      break;
    case 5:
      break;
    case 6:
      exit(0);
    default:
      printf("U have entered wrong option!!\n");
      break;
    }
  }
  struct node* newNode(char *id, char *name, char *last_name, float grade)
{

  struct node *newnode = malloc(sizeof(struct node));
  struct node Node;

  FILE *fp;
  fp = fopen ("Foitites-Vathmologio-DS.txt","rb");

  if (fp == NULL)
  {
    fprintf(stderr,"Could not open file");
    return;
  }

  char line[4096];

  while (fgets(line, sizeof line,fp))
  {
    size_t len = strlen(line);
    if (len && (line[len - 1] == '\n'))
    {
      /* incomplete line */
      if (sscanf(line,"%99s %99s %99s %f",Node.ID, Node.NAME, Node.LAST_NAME, &Node.Grade) != 4)
      {
      puts("invalid file");
      return;
      }

    strcpy(newnode->ID , id);
    strcpy(newnode->NAME , name);
    strcpy(newnode->LAST_NAME , last_name);
    newnode->Grade = grade;
    newnode->left = newnode->right = NULL;
    return newnode;

    }
  }
fclose(fp);
}
  return 0;
}

I get no error messages.. thank you for your time!

Body:
If you get no error message with this code, I would suggest you to use a different compiler. Mine chokes in main at:

    switch (ch) {
    case 1:
        if (insertDone)
            puts("Inserton was already done");
        else {
            struct node* insertNode(struct node *node, char *id, char *name,
                   char *last_name, float grade)      // ERROR HERE
            {
                if (node == NULL)

It looks that you have copied the definition of the function instead of just calling it.

My problem is that you managed to write many different errors in a single program. And the global design of how the program should be structured is not clear: it looks like you started coding without first writing on a paper (yes papers and pencils are still very good tools for beginners) what each function should do, what was its its inputs and what should be its outputs and eventually what data it was including (for example what part is in charge of the file name). Of course, I could write a BST program for you, but you would not learn anything from that.

So here are some hints:

in a BST, you insert new data under existing nodes so you will need a function insertNode with following input parameters: the current root node (or NULL at first time), the id, name, last_name and grade to insert. You should build a new copy of the input strings (strdup is your friend). This function will allocate a new structure, fills is fields, and either return it if the current root was NULL, or insert it at its correct place in the existing tree

you want to process all lines from a file. You will need a function that open the file, read it line by line and will use previous one to insert the new record in the BST

BTW a function definition is something like

struct node *insert(struct node *root, const char id*, const char *name, const char *last_name, float grade) {
    struct node * newnode = malloc(sizeof *newnode);
    ...
    return root;
}

outside of any other function definition, while a function call will be like:

struc node *root = NULL;
char id[100], name[100], last_name[100];
float grade;
...
      if (sscanf(line,"%99s %99s %99s %f",id, name, last_name, &grade)) != 4)
      {
      puts("invalid file");
      return;
      }
      root = insert(root, id, name, last_name, grade);  // here is the function call


问:
Count values per X minutes in Prometheus
I`m trying to watch values in Prometheus per 1 minute.

For example, If in every 30 seconds I'm increasing a counter by 10, that's how the values will be:

```<code>#Time    Interval     New Counter Value
1        10           10
31       10           20
61       10           30
91       10           40
121      10           50
151      10           60
...
</code>```

In that example, I want to see in the graph a straight line on value 20 (because in every 60 seconds, the counter increased by 20).

Is it possible to have it in Prometheus?

Body:
I`m trying to watch values in Prometheus per 1 minute.

For example, If in every 30 seconds I'm increasing a counter by 10, that's how the values will be:

#Time    Interval     New Counter Value
1        10           10
31       10           20
61       10           30
91       10           40
121      10           50
151      10           60
...

In that example, I want to see in the graph a straight line on value 20 (because in every 60 seconds, the counter increased by 20).

Is it possible to have it in Prometheus?


问:
Visual Studio Windows Console Application throwing exception on 'return 0' from main()
I'm creating a simple Windows Console application and am experiencing a strange error. The program runs fine and does everything without error, but when it hits the final return 0; in the main routine i get the following error

I've never seen it before and don't know what it means. I tried to read through the documentation but it was not enlightening.

Here's the program. I do some dynamic allocations, so I thought that might be it but I've never gotten this error in the past despite having made plenty of pointer, dynamic allocation, and indexing errors before. It's always seg-faults, syntax, or compilation errors.

```<code>const char WHITE = 'x';
const char BLACK = 'o';
const char EMPTY = '-';
const char EDGE = 'e';

struct BoardSpace
{
    int x_loc;
    int y_loc;
    int white_score;
    int black_score;
    string last_visitor;
    char stone;
    char owner;
};

class GoBoard
{

private:

    void InitBoard(BoardSpace** board)
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            board[x][0].stone = EDGE;
            board[0][x].stone = EDGE;
            board[x][BoardSize - 1].stone = EDGE;
            board[BoardSize - 1][x].stone = EDGE;
        }

        for (unsigned int x = 1; x < BoardSize - 1; x++)
        {
            for (unsigned int y = 1; y < BoardSize - 1; y++)
            {
                MyBoard[x][y].stone = EMPTY;
            }
        }
    }

public:

    unsigned int BoardSize;
    BoardSpace **MyBoard;

    GoBoard(int size)
    {
        BoardSize = size + 2;
        MyBoard = new BoardSpace*[BoardSize];

        for (unsigned int x = 0; x < BoardSize; x++)
        {
            MyBoard[x] = new BoardSpace[BoardSize];
        }

        InitBoard(MyBoard);
    }

    ~GoBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            delete MyBoard[x];
        }

        delete MyBoard;
    }

    void PrintBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            for (unsigned int y = 0; y < BoardSize; y++)
            {
                cout << MyBoard[x][y].stone << ' ';
            }
            cout << endl;
        }
    }
};
</code>```

答:
As mentioned in the comments, the dtor must change to:

```<code>~GoBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            delete [] MyBoard[x];
        }

        delete [] MyBoard;
    }
</code>```

however it is recommended to use smart pointers or other containers like vector instead. Here is an example with uinque_ptr:

```<code>#include <iostream>
#include <string>
#include<memory>
using namespace std;

const char WHITE = 'x';
const char BLACK = 'o';
const char EMPTY = '-';
const char EDGE = 'e';

struct BoardSpace
{
    int x_loc;
    int y_loc;
    int white_score;
    int black_score;
    string last_visitor;
    char stone;
    char owner;
};

class GoBoard
{

private:

    void InitBoard(unique_ptr<unique_ptr<BoardSpace[]>[]>& board)
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            board[x][0].stone = EDGE;
            board[0][x].stone = EDGE;
            board[x][BoardSize - 1].stone = EDGE;
            board[BoardSize - 1][x].stone = EDGE;
        }

        for (unsigned int x = 1; x < BoardSize - 1; x++)
        {
            for (unsigned int y = 1; y < BoardSize - 1; y++)
            {
                MyBoard[x][y].stone = EMPTY;
            }
        }
    }

public:

    unsigned int BoardSize;
    unique_ptr<unique_ptr<BoardSpace[]>[]> MyBoard;

    GoBoard(int size)
    {
        BoardSize = size + 2;
        MyBoard.reset(new unique_ptr<BoardSpace[]>[BoardSize]);

        for (unsigned int x = 0; x < BoardSize; x++)
        {
            MyBoard[x].reset(new BoardSpace[BoardSize]);
        }

        InitBoard(MyBoard);
    }

    ~GoBoard()
    {
    }

    void PrintBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            for (unsigned int y = 0; y < BoardSize; y++)
            {
                cout << MyBoard[x][y].stone << ' ';
            }
            cout << endl;
        }
    }
};

int main()
{
    GoBoard myGboard(9);
    myGboard.PrintBoard();
    return 0;
}
</code>```

Body:
I'm creating a simple Windows Console application and am experiencing a strange error. The program runs fine and does everything without error, but when it hits the final return 0; in the main routine i get the following error

I've never seen it before and don't know what it means. I tried to read through the documentation but it was not enlightening.

Here's the program. I do some dynamic allocations, so I thought that might be it but I've never gotten this error in the past despite having made plenty of pointer, dynamic allocation, and indexing errors before. It's always seg-faults, syntax, or compilation errors.

const char WHITE = 'x';
const char BLACK = 'o';
const char EMPTY = '-';
const char EDGE = 'e';

struct BoardSpace
{
    int x_loc;
    int y_loc;
    int white_score;
    int black_score;
    string last_visitor;
    char stone;
    char owner;
};

class GoBoard
{

private:

    void InitBoard(BoardSpace** board)
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            board[x][0].stone = EDGE;
            board[0][x].stone = EDGE;
            board[x][BoardSize - 1].stone = EDGE;
            board[BoardSize - 1][x].stone = EDGE;
        }

        for (unsigned int x = 1; x < BoardSize - 1; x++)
        {
            for (unsigned int y = 1; y < BoardSize - 1; y++)
            {
                MyBoard[x][y].stone = EMPTY;
            }
        }
    }

public:

    unsigned int BoardSize;
    BoardSpace **MyBoard;

    GoBoard(int size)
    {
        BoardSize = size + 2;
        MyBoard = new BoardSpace*[BoardSize];

        for (unsigned int x = 0; x < BoardSize; x++)
        {
            MyBoard[x] = new BoardSpace[BoardSize];
        }

        InitBoard(MyBoard);
    }

    ~GoBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            delete MyBoard[x];
        }

        delete MyBoard;
    }

    void PrintBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            for (unsigned int y = 0; y < BoardSize; y++)
            {
                cout << MyBoard[x][y].stone << ' ';
            }
            cout << endl;
        }
    }
};

Body:
As mentioned in the comments, the dtor must change to:

~GoBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            delete [] MyBoard[x];
        }

        delete [] MyBoard;
    }

however it is recommended to use smart pointers or other containers like vector instead. Here is an example with uinque_ptr:

#include <iostream>
#include <string>
#include<memory>
using namespace std;

const char WHITE = 'x';
const char BLACK = 'o';
const char EMPTY = '-';
const char EDGE = 'e';

struct BoardSpace
{
    int x_loc;
    int y_loc;
    int white_score;
    int black_score;
    string last_visitor;
    char stone;
    char owner;
};

class GoBoard
{

private:

    void InitBoard(unique_ptr<unique_ptr<BoardSpace[]>[]>& board)
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            board[x][0].stone = EDGE;
            board[0][x].stone = EDGE;
            board[x][BoardSize - 1].stone = EDGE;
            board[BoardSize - 1][x].stone = EDGE;
        }

        for (unsigned int x = 1; x < BoardSize - 1; x++)
        {
            for (unsigned int y = 1; y < BoardSize - 1; y++)
            {
                MyBoard[x][y].stone = EMPTY;
            }
        }
    }

public:

    unsigned int BoardSize;
    unique_ptr<unique_ptr<BoardSpace[]>[]> MyBoard;

    GoBoard(int size)
    {
        BoardSize = size + 2;
        MyBoard.reset(new unique_ptr<BoardSpace[]>[BoardSize]);

        for (unsigned int x = 0; x < BoardSize; x++)
        {
            MyBoard[x].reset(new BoardSpace[BoardSize]);
        }

        InitBoard(MyBoard);
    }

    ~GoBoard()
    {
    }

    void PrintBoard()
    {
        for (unsigned int x = 0; x < BoardSize; x++)
        {
            for (unsigned int y = 0; y < BoardSize; y++)
            {
                cout << MyBoard[x][y].stone << ' ';
            }
            cout << endl;
        }
    }
};

int main()
{
    GoBoard myGboard(9);
    myGboard.PrintBoard();
    return 0;
}


问:
run macros dynamically on value change |VBA|Excel|
I have Sheet 1 and Sheet

Sheet 1 => https://paste.pics/6d48d50d54592eb1bdcb31e727b44958

Sheet 2 => https://paste.pics/80f4230bf6819a80ed36e1b6415ece08

Value of Sheet 1 => F5 => '50'  => is referenced in Sheet 2  => E4 => '50'

When i enter Value in Sheet 1 in place of F5 => Value gets Change in Sheet 2 => E4 => Automatically

Now the issue is I want to print the DATA 1 and DATA 2 of Sheet 2 => That many times => how much value which is shown in place of Sheet 2 => E4 [Position] => in place of COLUMN => 'I' and 'J'

Like this Below Output :https://paste.pics/494c856d2908a83ca031ee20bb706a09

My code which partially print only one Column output but need to PRINT 'RAM' and 'RAJ' => COLUMN => 'I' and 'J'

Module :
Sub mac()

```<code>Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column).End(xlUp))
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount) = sValue

End Sub
</code>```

Sheet  1 code :

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Sheets("Sheet1").Range("F5"), Target) Is Nothing Then
       Call mac
    End If
End Sub
</code>```

答:
If print means just filling the cells, then you can use following sub. Modify the code to adjust it with Worksheet_Change event

```<code>Sub FillNames()
Dim ws As Worksheet
Dim i, destLen As Long

Set ws = Worksheets("Sheet2")
destLen = ws.Range("E4")

    For i = 1 To destLen
        ws.Cells(i + 1, "I") = ws.Range("E8")
        ws.Cells(i + 1, "J") = ws.Range("E12")
    Next

Set ws = Nothing
End Sub
</code>```

Body:
I have Sheet 1 and Sheet

Sheet 1 => https://paste.pics/6d48d50d54592eb1bdcb31e727b44958

Sheet 2 => https://paste.pics/80f4230bf6819a80ed36e1b6415ece08

Value of Sheet 1 => F5 => '50'  => is referenced in Sheet 2  => E4 => '50'

When i enter Value in Sheet 1 in place of F5 => Value gets Change in Sheet 2 => E4 => Automatically

Now the issue is I want to print the DATA 1 and DATA 2 of Sheet 2 => That many times => how much value which is shown in place of Sheet 2 => E4 [Position] => in place of COLUMN => 'I' and 'J'

Like this Below Output :https://paste.pics/494c856d2908a83ca031ee20bb706a09

My code which partially print only one Column output but need to PRINT 'RAM' and 'RAJ' => COLUMN => 'I' and 'J'

Module :
Sub mac()

Dim ws As Worksheet
Dim rDest As Range
Dim lCount As Long
Dim sValue As String

Set ws = ThisWorkbook.Sheets("Sheet2")
Set rDest = ws.Range("I2")

With ws.Range(rDest, ws.Cells(ws.Rows.Count, rDest.Column).End(xlUp))
    If .Row >= rDest.Row Then .ClearContents
End With

lCount = Val(ws.Range("E4").Value)
sValue = ws.Range("E8").Value

If lCount > 0 Then rDest.Resize(lCount) = sValue

End Sub

Sheet  1 code :

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Sheets("Sheet1").Range("F5"), Target) Is Nothing Then
       Call mac
    End If
End Sub

Body:
If print means just filling the cells, then you can use following sub. Modify the code to adjust it with Worksheet_Change event

Sub FillNames()
Dim ws As Worksheet
Dim i, destLen As Long

Set ws = Worksheets("Sheet2")
destLen = ws.Range("E4")

    For i = 1 To destLen
        ws.Cells(i + 1, "I") = ws.Range("E8")
        ws.Cells(i + 1, "J") = ws.Range("E12")
    Next

Set ws = Nothing
End Sub


问:
How to write multiple queries in one query based on condition in SQL Server?
```<code>SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [x]
FROM
    [my_table]
WHERE
    state LIKE '%firstCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [y]
FROM
    [my_table]
WHERE
    state LIKE '%secondCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [z]
FROM
    [my_table]
WHERE
    state LIKE '%thirdCondition%'
GROUP BY
    [LNMAJORTP], [MainType]
</code>```

How I can change this queries to one query?

答:
You could try a UNION ALL between each select.</p>

```<code>SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [x]
FROM
    [my_table]
WHERE
    state LIKE '%firstCondition%'
GROUP BY
    [LNMAJORTP], [MainType]
UNION ALL
SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [y]
FROM
    [my_table]
WHERE
    state LIKE '%secondCondition%'
GROUP BY
    [LNMAJORTP], [MainType]
UNION ALL
SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [z]
FROM
    [my_table]
WHERE
    state LIKE '%thirdCondition%'
GROUP BY
    [LNMAJORTP], [MainType]
</code>```

Body:
SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [x]
FROM
    [my_table]
WHERE
    state LIKE '%firstCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [y]
FROM
    [my_table]
WHERE
    state LIKE '%secondCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [z]
FROM
    [my_table]
WHERE
    state LIKE '%thirdCondition%'
GROUP BY
    [LNMAJORTP], [MainType]

How I can change this queries to one query?

Body:
You could try a UNION ALL between each select.

SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [x]
FROM
    [my_table]
WHERE
    state LIKE '%firstCondition%'
GROUP BY
    [LNMAJORTP], [MainType]
UNION ALL
SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [y]
FROM
    [my_table]
WHERE
    state LIKE '%secondCondition%'
GROUP BY
    [LNMAJORTP], [MainType]
UNION ALL
SELECT
    [LNMAJORTP], [MainType],
    SUM(x + y - z) [z]
FROM
    [my_table]
WHERE
    state LIKE '%thirdCondition%'
GROUP BY
    [LNMAJORTP], [MainType]


问:
MVC ModelState not updating
I have a view model, which I have described in a previous question:
ASP.net MVC Validation on mutiple controls

My controller action that handles the form post has the field DOB correctly populated however my ModelState object does not thereby causing the validation (which is 'Required') to fail.  In here, DOB is null.  I have tried outputting DOB as a hidden field in my view however this has not fixed the issue.  Is there a proper way to achieve this or could I just edit the ModelState before calling IsValid?

答: You may find the following blog post helpful.</p>

Title: MVC ModelState not updating