问:
Time difference in R by group based on condition and two time columns
I would like to get the time elapsed between events in my dataframe, for each grouping of data by the ID. The dates i want to use are in their own columns. I have done the following already using dplyr:

Grouped my data by the ID

Ordered by the ID

This is how the data looks. I would like the output to be the time_diff column. Any help would be very much appreciated!

```<code>ID: Status:    Start-time:   End-time:    time-diff:
1   Active      01/01/2018       NA           0
1   Complete      NA         01/02/2018       1
2   Active      03/02/2018                    0
2   Active        NA                          0
2   Complete      NA         03/06/2018       4
</code>```

答:
Taking the time difference between a time and a NA value will just return NA. A more meaningful approach would be to take the individual time different of each event, and then summarize over each group (id).

```<code>d <- tibble(id = c(1,1,2,2),
            st = ymd(c("2019-05-03", "2019-02-06", "2019-07-11","2019-05-13")),
            et = ymd(c("2019-05-10", "2019-02-16", "2019-07-04","2019-05-09")))

d2 <- d %>%
  mutate(td  = et-st,         # calculate the time difference (td)
         atd = abs(td)) %>%   # calculate the absolute td (atd)
d2

# A tibble: 4 x 5
     id st         et         td      atd
  <dbl> <date>     <date>     <time>  <time>
1     1 2019-05-03 2019-05-10  7 days  7 days
2     1 2019-02-06 2019-02-16 10 days 10 days
3     2 2019-07-11 2019-07-04 -7 days  7 days
4     2 2019-05-13 2019-05-09 -4 days  4 days
</code>```

Then you can take the mean of the absolute differences for example and get:

```<code>d2 %>%
  group_by(id) %>%            # for each group (id)
  summarise(mtd = mean(atd))  # calculate the mean time difference (mtd)

# A tibble: 2 x 2
     id mtd
  <dbl> <time>
1     1 8.5 days
2     2 5.5 days
</code>```

Body:
I would like to get the time elapsed between events in my dataframe, for each grouping of data by the ID. The dates i want to use are in their own columns. I have done the following already using dplyr:

Grouped my data by the ID

Ordered by the ID

This is how the data looks. I would like the output to be the time_diff column. Any help would be very much appreciated!

ID: Status:    Start-time:   End-time:    time-diff:
1   Active      01/01/2018       NA           0
1   Complete      NA         01/02/2018       1
2   Active      03/02/2018                    0
2   Active        NA                          0
2   Complete      NA         03/06/2018       4

Body:
Taking the time difference between a time and a NA value will just return NA. A more meaningful approach would be to take the individual time different of each event, and then summarize over each group (id).

d <- tibble(id = c(1,1,2,2),
            st = ymd(c("2019-05-03", "2019-02-06", "2019-07-11","2019-05-13")),
            et = ymd(c("2019-05-10", "2019-02-16", "2019-07-04","2019-05-09")))

d2 <- d %>%
  mutate(td  = et-st,         # calculate the time difference (td)
         atd = abs(td)) %>%   # calculate the absolute td (atd)
d2

# A tibble: 4 x 5
     id st         et         td      atd
  <dbl> <date>     <date>     <time>  <time>
1     1 2019-05-03 2019-05-10  7 days  7 days
2     1 2019-02-06 2019-02-16 10 days 10 days
3     2 2019-07-11 2019-07-04 -7 days  7 days
4     2 2019-05-13 2019-05-09 -4 days  4 days

Then you can take the mean of the absolute differences for example and get:

d2 %>%
  group_by(id) %>%            # for each group (id)
  summarise(mtd = mean(atd))  # calculate the mean time difference (mtd)

# A tibble: 2 x 2
     id mtd
  <dbl> <time>
1     1 8.5 days
2     2 5.5 days


来源: stackexchange

问:
How to get the router values containing special characters in express router
I am working on to get route value in Nodes js using express framework

the url goes like

```<code>   http://localhost:3000/course/view/turbine/turcV39/%20V42/%20V44/%20V47
</code>```

Need to get the value "V39/%20V42/%20V44/%20V47" from the above url and route

```<code>     router.get('/view/turbine/:turc?', function(req, res) {
     console.log('a');
     });
</code>```

答:
You can use regex to get it, like this</p>

```<code>app.get(/\/view\/turbine\/turc(.*)/, function(req, res) {
    console.log(req.params[0])
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on to get route value in Nodes js using express framework

the url goes like

   http://localhost:3000/course/view/turbine/turcV39/%20V42/%20V44/%20V47

Need to get the value "V39/%20V42/%20V44/%20V47" from the above url and route

     router.get('/view/turbine/:turc?', function(req, res) {
     console.log('a');
     });

Body:
You can use regex to get it, like this

app.get(/\/view\/turbine\/turc(.*)/, function(req, res) {
    console.log(req.params[0])
});


问:
how to add compile-time metadata/behavior to specific function
My codebase is C++ on NXP ARM M4 with custom C++ RTOS.

There exists a certain function, DWB() aka DangerWillRobinson(), that if called could have unexpected side-effects (which are valid when it's used correctly).

DWB() could be called in a very deeply nested manner as in
A()->B()->C()->D()->...->DWB()

I want author of any functions that, directly or indirectly, call DWB() to be aware that DWB() is called and I want to force them to acknowledge that they know DWB() is called.

I know this could be accomplished by parsing the linker's generated call-trees using Python but I'd much prefer this to be a compile-time error thing.

Here's how I'd like this to work:

```<code>void A()
{
    B();
}
</code>```

Author goes to compile:

ERROR: DWB() is called. Please acknowledge.

Author then thinks about side-effects of calling DWB() and finds no issues.

```<code>void A()
{
    // some macro-thing ... ?
    B();
}
</code>```

If possible, I do not want this to be a runtime check. I think in theory, this is possible. If Base is inherited, I would like all possible classes' call-trees to be considered; it's ok if none of them are even instantiated but not ideal.

QUESTION

Is this compile-time metadata/behavior of a function possible?

答:
Is this compile-time metadata/behavior of a function possible?

No, it isn't. There might be some configurable SCA tools available (consider a commercial high level one), but not with plain c-preprocessing or meta-template-programming magic.

I want author of any functions that, directly or indirectly, call DWB() to be aware that DWB() is called and I want to force them to acknowledge that they know DWB() is called.

The least intrusive way to do that is to mark the DWB() function [[deprecated]].

I just suppose you prefer to factor out such error prone function in a midterm roadmap, and replace it with something more stable.

The most quick way in case you are sure what all the conditions of a correct DWB() call are is to apply a bunch of assert() calls at the start of that function.

There might come up complaints from fellow developers, which are trying to use that function incorrectly. Give them best advice as you can in the assertion messages.

Body:
My codebase is C++ on NXP ARM M4 with custom C++ RTOS.

There exists a certain function, DWB() aka DangerWillRobinson(), that if called could have unexpected side-effects (which are valid when it's used correctly).

DWB() could be called in a very deeply nested manner as in
A()->B()->C()->D()->...->DWB()

I want author of any functions that, directly or indirectly, call DWB() to be aware that DWB() is called and I want to force them to acknowledge that they know DWB() is called.

I know this could be accomplished by parsing the linker's generated call-trees using Python but I'd much prefer this to be a compile-time error thing.

Here's how I'd like this to work:

void A()
{
    B();
}

Author goes to compile:

ERROR: DWB() is called. Please acknowledge.

Author then thinks about side-effects of calling DWB() and finds no issues.

void A()
{
    // some macro-thing ... ?
    B();
}

If possible, I do not want this to be a runtime check. I think in theory, this is possible. If Base is inherited, I would like all possible classes' call-trees to be considered; it's ok if none of them are even instantiated but not ideal.

QUESTION

Is this compile-time metadata/behavior of a function possible?


问:
GTK3+ - How to update graphics based on mouse click?
I am trying to modify the cairo graphics rendering I found in http://zetcode.com/gfx/cairo/basicdrawing/ so that it updates the graphics when I click the drawing area with the left mouse button. Currently the code in the website uses the right mouse button click to update the graphics.

I have tried adding gtk_widget_queue_draw(widget); to gboolean clicked(), when event->button == 1:

```<code>#include <cairo.h>
#include <gtk/gtk.h>

static void do_drawing(cairo_t *);

struct {
  int count;
  double coordx[100];
  double coordy[100];
} glob;

static gboolean on_draw_event(GtkWidget *widget, cairo_t *cr,
    gpointer user_data)
{
  do_drawing(cr);

  return FALSE;
}

static void do_drawing(cairo_t *cr)
{
  cairo_set_source_rgb(cr, 0, 0, 0);
  cairo_set_line_width(cr, 0.5);

  int i, j;
  for (i = 0; i <= glob.count - 1; i++ ) {
      for (j = 0; j <= glob.count - 1; j++ ) {
          cairo_move_to(cr, glob.coordx[i], glob.coordy[i]);
          cairo_line_to(cr, glob.coordx[j], glob.coordy[j]);
      }
  }

  glob.count = 0;
  cairo_stroke(cr);
}

static gboolean clicked(GtkWidget *widget, GdkEventButton *event,
    gpointer user_data)
{
    if (event->button == 1) {
        glob.coordx[glob.count] = event->x;
        glob.coordy[glob.count++] = event->y;
        gtk_widget_queue_draw(widget);
    }

    if (event->button == 3) {
        gtk_widget_queue_draw(widget);
    }

    return TRUE;
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *darea;

  glob.count = 0;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  darea = gtk_drawing_area_new();
  gtk_container_add(GTK_CONTAINER(window), darea);

  gtk_widget_add_events(window, GDK_BUTTON_PRESS_MASK);

  g_signal_connect(G_OBJECT(darea), "draw",
      G_CALLBACK(on_draw_event), NULL);
  g_signal_connect(window, "destroy",
      G_CALLBACK(gtk_main_quit), NULL);

  g_signal_connect(window, "button-press-event",
      G_CALLBACK(clicked), NULL);

  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
  gtk_window_set_title(GTK_WINDOW(window), "Lines");

  gtk_widget_show_all(window);

  gtk_main();

  return 0;
}
</code>```

However, this does not work since now the graphics aren't updated at all.

Is there a way of updating the graphics by pressing the left mouse button (button 1) and simultaneously carry out inserting the coordinates to struct glob as before?

Thanks!

答:
```<code>g_signal_connect(window, "button-press-event", G_CALLBACK(clicked), NULL);
</code>```

When your callback is called, the window (which emits "button-press-event") is passed as first parameter. The queue_draw call queues redraw of window. However, redraw  of DrawingArea is not requested and will not happen.

You can:

Queue redraw of DrawingArea

Connect to "button-press-event" of DrawingArea

Without any changes of code: press a mouse button and resize the window. Gtk will see, that DrawingArea has changed (it's resized too) and queue redraw of this widget.

Body:
I am trying to modify the cairo graphics rendering I found in http://zetcode.com/gfx/cairo/basicdrawing/ so that it updates the graphics when I click the drawing area with the left mouse button. Currently the code in the website uses the right mouse button click to update the graphics.

I have tried adding gtk_widget_queue_draw(widget); to gboolean clicked(), when event->button == 1:

#include <cairo.h>
#include <gtk/gtk.h>

static void do_drawing(cairo_t *);

struct {
  int count;
  double coordx[100];
  double coordy[100];
} glob;

static gboolean on_draw_event(GtkWidget *widget, cairo_t *cr,
    gpointer user_data)
{
  do_drawing(cr);

  return FALSE;
}

static void do_drawing(cairo_t *cr)
{
  cairo_set_source_rgb(cr, 0, 0, 0);
  cairo_set_line_width(cr, 0.5);

  int i, j;
  for (i = 0; i <= glob.count - 1; i++ ) {
      for (j = 0; j <= glob.count - 1; j++ ) {
          cairo_move_to(cr, glob.coordx[i], glob.coordy[i]);
          cairo_line_to(cr, glob.coordx[j], glob.coordy[j]);
      }
  }

  glob.count = 0;
  cairo_stroke(cr);
}

static gboolean clicked(GtkWidget *widget, GdkEventButton *event,
    gpointer user_data)
{
    if (event->button == 1) {
        glob.coordx[glob.count] = event->x;
        glob.coordy[glob.count++] = event->y;
        gtk_widget_queue_draw(widget);
    }

    if (event->button == 3) {
        gtk_widget_queue_draw(widget);
    }

    return TRUE;
}

int main(int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *darea;

  glob.count = 0;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  darea = gtk_drawing_area_new();
  gtk_container_add(GTK_CONTAINER(window), darea);

  gtk_widget_add_events(window, GDK_BUTTON_PRESS_MASK);

  g_signal_connect(G_OBJECT(darea), "draw",
      G_CALLBACK(on_draw_event), NULL);
  g_signal_connect(window, "destroy",
      G_CALLBACK(gtk_main_quit), NULL);

  g_signal_connect(window, "button-press-event",
      G_CALLBACK(clicked), NULL);

  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
  gtk_window_set_title(GTK_WINDOW(window), "Lines");

  gtk_widget_show_all(window);

  gtk_main();

  return 0;
}

However, this does not work since now the graphics aren't updated at all.

Is there a way of updating the graphics by pressing the left mouse button (button 1) and simultaneously carry out inserting the coordinates to struct glob as before?

Thanks!

Body:
g_signal_connect(window, "button-press-event", G_CALLBACK(clicked), NULL);

When your callback is called, the window (which emits "button-press-event") is passed as first parameter. The queue_draw call queues redraw of window. However, redraw  of DrawingArea is not requested and will not happen.

You can:

Queue redraw of DrawingArea

Connect to "button-press-event" of DrawingArea

Without any changes of code: press a mouse button and resize the window. Gtk will see, that DrawingArea has changed (it's resized too) and queue redraw of this widget.


问:
Postman - Validate value from Response and print on Console
From below Response, I want to fetch the value of "responseCode" and store temporarily. If a value is 1 then on Console, I want to write "Test PASS". Can anyone share code for this test?

```<code>{
   "data":{
      "transactionId":"$1"
   },
   "responseMessage":"Transaction successfully done. Transaction Id : txn_15594028419901124218",
   "responseCode":1
}
</code>```

I tried to use the following code to set the variable:

```<code>var jsonData = JSON.parse(responseBody);
pm.globals.set("responseCode",jsonData.data.responseCode);
</code>```

答:
This basic test would check that value in the response, store the variable and also write Test PASS to the console

```<code>pm.test("Check the Response Code is 1", () => {
    pm.expect(pm.response.json().responseCode).to.eql(1);
    pm.globals.set("responseCode", pm.response.json().responseCode)
    console.log("Test PASS")
});
</code>```

This doesn't account for the test failing and writing Test FAIL to the console, you kind of get that anyway in the Postman UI.

If you didn't want to wrap this in a test, you could just do something like:

```<code>if(pm.response.json().responseCode === 1){
    pm.globals.set("responseCode", pm.response.json().responseCode)
    console.log("Test PASS")
}
else {
    console.log("Test FAIL")
}
</code>```

Body:
From below Response, I want to fetch the value of "responseCode" and store temporarily. If a value is 1 then on Console, I want to write "Test PASS". Can anyone share code for this test?

{
   "data":{
      "transactionId":"$1"
   },
   "responseMessage":"Transaction successfully done. Transaction Id : txn_15594028419901124218",
   "responseCode":1
}

I tried to use the following code to set the variable:

var jsonData = JSON.parse(responseBody);
pm.globals.set("responseCode",jsonData.data.responseCode);

Body:
This basic test would check that value in the response, store the variable and also write Test PASS to the console

pm.test("Check the Response Code is 1", () => {
    pm.expect(pm.response.json().responseCode).to.eql(1);
    pm.globals.set("responseCode", pm.response.json().responseCode)
    console.log("Test PASS")
});

This doesn't account for the test failing and writing Test FAIL to the console, you kind of get that anyway in the Postman UI.

If you didn't want to wrap this in a test, you could just do something like:

if(pm.response.json().responseCode === 1){
    pm.globals.set("responseCode", pm.response.json().responseCode)
    console.log("Test PASS")
}
else {
    console.log("Test FAIL")
}


问:
Pass parameter with navigateForward angular 7
I'm trying to pass a parameter on the route but it arrives at as undefined.
On the login screen I call through the NavController tabs, but in the ActivatedRoute tabs the route arrives as undefined.</p>

```<code>export class TabsPage {
  logado = false;
  id=0;

  constructor(public navCtrl: NavController, private route: ActivatedRoute)
  {

  }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
        this.id = params["id"];
    });

    if(this.id == undefined || this.id == null || this.id == NaN || this.id < 1){
      this.navCtrl.navigateForward('/login');
      this.logado = false;
    }else{
      this.logado = true;
      this.navCtrl.navigateForward('/home');
    }
}
}
</code>```

答:
Move your logic into your queryParams subscription so it only runs once the id is set:</p>

```<code>ngOnInit() {
  this.route.queryParams.subscribe(params => {
    this.id = params["id"];

    if (this.id == undefined || this.id == null || this.id == NaN || this.id < 1) {
      this.navCtrl.navigateForward('/login');
      this.logado = false;
    } else {
      this.logado = true;
      this.navCtrl.navigateForward('/home');
    }
  });
}
</code>```

Body:
I'm trying to pass a parameter on the route but it arrives at as undefined.
On the login screen I call through the NavController tabs, but in the ActivatedRoute tabs the route arrives as undefined.

export class TabsPage {
  logado = false;
  id=0;

  constructor(public navCtrl: NavController, private route: ActivatedRoute)
  {

  }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
        this.id = params["id"];
    });

    if(this.id == undefined || this.id == null || this.id == NaN || this.id < 1){
      this.navCtrl.navigateForward('/login');
      this.logado = false;
    }else{
      this.logado = true;
      this.navCtrl.navigateForward('/home');
    }
}
}

Body:
Move your logic into your queryParams subscription so it only runs once the id is set:

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    this.id = params["id"];

    if (this.id == undefined || this.id == null || this.id == NaN || this.id < 1) {
      this.navCtrl.navigateForward('/login');
      this.logado = false;
    } else {
      this.logado = true;
      this.navCtrl.navigateForward('/home');
    }
  });
}


问:
XSLT-FO apply-templates
I've got a XML file

```<code><results xmlns="zwierzeta">
    <animal family="kurowate" genus="tetrao">
        <name>skrzekot</name>
        <food>wszystkożerca</food>
    </animal>
    <animal family="kurowate" genus="lyrurus">
        <name>cietrzew</name>
        <status>zagrożony</status>
        <food>wszystkożerca</food>
        <lifespan>15</lifespan>
    </animal>
    <animal family="kurowate" genus="tetrao">
        <name>głuszec</name>
        <status>zagrożony</status>
        <food>wszystkożerca</food>
        <lifespan>12</lifespan>
    </animal>
</results>
</code>```

And trying to make a simple table with three columns: name, status, food.

My xsl file:

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns="zwierzeta" xmlns:a="anatomia">

    <xsl:template match="/">
        <fo:root>
            <fo:layout-master-set>
                <fo:simple-page-master master-name="wzorzec1" page-width="210mm" page-height="297mm" margin-top="1cm" margin-bottom="1cm" margin-left="1cm" margin-right="1cm">
                    <fo:region-body margin="3cm"/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="wzorzec1">
                <fo:flow flow-name="xsl-region-body" font-family="Arial">
                    <fo:block font-size="20" text-align="center">Raport</fo:block>
                    <fo:table border="1pt solid black" text-align="center" border-spacing="2pt">
                        <fo:table-header>
                            <fo:table-row>
                                <fo:table-cell border="1pt solid black"> <fo:block>Nazwa</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Status</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Odzywianie</fo:block> </fo:table-cell>
                            </fo:table-row>
                        </fo:table-header>
                        <fo:table-body>
                            <xsl:apply-templates select="animal"/>
                        </fo:table-body>
                    </fo:table>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

    <xsl:template match="animal">
        <fo:table-row>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="name"/></fo:block>
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="status"/></fo:block>
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="food"/></fo:block>
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>
</xsl:stylesheet>
</code>```

This gives me an error:

```<code>Not valid: org.apache.fop.fo.ValidationException: "fo:table-body" is missing child elements. Required content model: marker* (table-row+|table-cell+) (See position 1:975)
</code>```

Which I understand is a problem of the apply-templates part not being evaluated. But I do not know why it's happening. I tried to copy different files that were working correctly and changing the elements names but it's not helping.

答:
Apparently your default namespace

```<code>xmlns="zwierzeta"
</code>```

is not accepted. Changing it to a prefixed namespace fixes your problems. So change it to

```<code>xmlns:zw="zwierzeta"
</code>```

and then add the prefix to all elements which depended on a default namespace. The whole XSLT file could look like the following:

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:zw="zwierzeta" xmlns:a="anatomia">

    <xsl:template match="/zw:results">                     <!-- Prefixed -->
        <fo:root>
            <fo:layout-master-set>
                <fo:simple-page-master master-name="wzorzec1" page-width="210mm" page-height="297mm" margin-top="1cm" margin-bottom="1cm" margin-left="1cm" margin-right="1cm">
                    <fo:region-body margin="3cm"/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="wzorzec1">
                <fo:flow flow-name="xsl-region-body" font-family="Arial">
                    <fo:block font-size="20" text-align="center">Raport</fo:block>
                    <fo:table border="1pt solid black" text-align="center" border-spacing="2pt">
                        <fo:table-header>
                            <fo:table-row>
                                <fo:table-cell border="1pt solid black"> <fo:block>Nazwa</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Status</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Odzywianie</fo:block> </fo:table-cell>
                            </fo:table-row>
                        </fo:table-header>
                        <fo:table-body>
                            <xsl:apply-templates select="zw:animal"/>
                        </fo:table-body>
                    </fo:table>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

    <xsl:template match="zw:animal">                                    <!-- Prefixed -->
        <fo:table-row>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="zw:name"/></fo:block>   <!-- Prefixed -->
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="zw:status"/></fo:block> <!-- Prefixed -->
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="zw:food"/></fo:block>   <!-- Prefixed -->
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>
</xsl:stylesheet>
</code>```

Title: XSLT-FO apply-templates

Body:
I've got a XML file

<results xmlns="zwierzeta">
    <animal family="kurowate" genus="tetrao">
        <name>skrzekot</name>
        <food>wszystkożerca</food>
    </animal>
    <animal family="kurowate" genus="lyrurus">
        <name>cietrzew</name>
        <status>zagrożony</status>
        <food>wszystkożerca</food>
        <lifespan>15</lifespan>
    </animal>
    <animal family="kurowate" genus="tetrao">
        <name>głuszec</name>
        <status>zagrożony</status>
        <food>wszystkożerca</food>
        <lifespan>12</lifespan>
    </animal>
</results>

And trying to make a simple table with three columns: name, status, food.

My xsl file:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns="zwierzeta" xmlns:a="anatomia">

    <xsl:template match="/">
        <fo:root>
            <fo:layout-master-set>
                <fo:simple-page-master master-name="wzorzec1" page-width="210mm" page-height="297mm" margin-top="1cm" margin-bottom="1cm" margin-left="1cm" margin-right="1cm">
                    <fo:region-body margin="3cm"/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="wzorzec1">
                <fo:flow flow-name="xsl-region-body" font-family="Arial">
                    <fo:block font-size="20" text-align="center">Raport</fo:block>
                    <fo:table border="1pt solid black" text-align="center" border-spacing="2pt">
                        <fo:table-header>
                            <fo:table-row>
                                <fo:table-cell border="1pt solid black"> <fo:block>Nazwa</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Status</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Odzywianie</fo:block> </fo:table-cell>
                            </fo:table-row>
                        </fo:table-header>
                        <fo:table-body>
                            <xsl:apply-templates select="animal"/>
                        </fo:table-body>
                    </fo:table>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

    <xsl:template match="animal">
        <fo:table-row>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="name"/></fo:block>
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="status"/></fo:block>
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="food"/></fo:block>
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>
</xsl:stylesheet>

This gives me an error:

Not valid: org.apache.fop.fo.ValidationException: "fo:table-body" is missing child elements. Required content model: marker* (table-row+|table-cell+) (See position 1:975)

Which I understand is a problem of the apply-templates part not being evaluated. But I do not know why it's happening. I tried to copy different files that were working correctly and changing the elements names but it's not helping.

Body:
Apparently your default namespace

xmlns="zwierzeta"

is not accepted. Changing it to a prefixed namespace fixes your problems. So change it to

xmlns:zw="zwierzeta"

and then add the prefix to all elements which depended on a default namespace. The whole XSLT file could look like the following:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:zw="zwierzeta" xmlns:a="anatomia">

    <xsl:template match="/zw:results">                     <!-- Prefixed -->
        <fo:root>
            <fo:layout-master-set>
                <fo:simple-page-master master-name="wzorzec1" page-width="210mm" page-height="297mm" margin-top="1cm" margin-bottom="1cm" margin-left="1cm" margin-right="1cm">
                    <fo:region-body margin="3cm"/>
                </fo:simple-page-master>
            </fo:layout-master-set>
            <fo:page-sequence master-reference="wzorzec1">
                <fo:flow flow-name="xsl-region-body" font-family="Arial">
                    <fo:block font-size="20" text-align="center">Raport</fo:block>
                    <fo:table border="1pt solid black" text-align="center" border-spacing="2pt">
                        <fo:table-header>
                            <fo:table-row>
                                <fo:table-cell border="1pt solid black"> <fo:block>Nazwa</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Status</fo:block> </fo:table-cell>
                                <fo:table-cell border="1pt solid black"> <fo:block>Odzywianie</fo:block> </fo:table-cell>
                            </fo:table-row>
                        </fo:table-header>
                        <fo:table-body>
                            <xsl:apply-templates select="zw:animal"/>
                        </fo:table-body>
                    </fo:table>
                </fo:flow>
            </fo:page-sequence>
        </fo:root>
    </xsl:template>

    <xsl:template match="zw:animal">                                    <!-- Prefixed -->
        <fo:table-row>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="zw:name"/></fo:block>   <!-- Prefixed -->
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="zw:status"/></fo:block> <!-- Prefixed -->
            </fo:table-cell>
            <fo:table-cell border="1pt solid black">
                <fo:block><xsl:value-of select="zw:food"/></fo:block>   <!-- Prefixed -->
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>
</xsl:stylesheet>


问:
python3 tkinter: can I get ragged grids without aligned columns?
I'm writing a GUI in python, and using tkinter. I'm having trouble settling on an approach and need guidance.

Background: there's a server (not a webserver) that wants to present a lot of information to users, and let them edit some of it. It needs to send down information that a (relatvely) dumb python client uses to fill the window. Read only fields are Labels. The fields are generally single line Entry widgets, but some are multiline Text. There are some buttons, checkboxes and dropdowns. Asynchronously, the server can also update widgets, add them and remove them. In some cases, there are tables presented, to which the user needs to be able to add and remove rows.

The real problem is, the layout is dense and chaotic. The first row might contain 3 dropdown fields. The next might be 20 short Labels. The next might be a single long Entry field, and then I might want two tables (of different lengths) side by side,and then etc.. Based on user input of external factors, widgets, rows or entire tables might have to be dyamically added, or vanish.

I considered Grid, but it's unusable. A row with a single, long entry widgit in it, makes the first column wide and thereby pushes 12 of the 13 columns in the next row right off the window.

I considered Place, but this app will run on 3 different operating systems and users will be able to select their own fonts, so I'll never get the positions right. If there was some way to ask a widget how big it was, I'd happily use that to compute my own layouts in pixels, but it's apparently impossible to ask the size of a widget until AFTER it's been laid out by a geometry manager, which of course is too late.

So what I think I'm left with is Pack, where each row is its own frame, and some of those rows have tables (grids) in them. But I'm concerned that that means lots and lots of frames to render, and some of the users are on old, slow hardware. Plus...  it looks just plain complex.

Am I missing a better way? Grid would be fine if I could convince it to stop trying to make columns line up. Place would be crunchy, but ok, if I could get the size of each widget in advance. Is placing within a lot of frames really the best I have?

答: Short answer, there's no better way; and the frame count isn't high enough to cause performance problems; so generating a frame per row is what works.</p>


问:
Why the sentence "The expression can be used only as the left-hand operand of a member function call" in [expr.ref]p(6.3.2)?
[expr.ref]p(6.3.2):

Otherwise, if E1.E2 refers to a non-static member function and the
  type of E2 is “function of parameter-type-list cv
  ref-qualifieropt returning T”, then E1.E2 is a prvalue. The expression designates a non-static member function. The
  expression can be used only as the left-hand operand of a member
  function call ([class.mfct]). [ Note: Any redundant set of
  parentheses surrounding the expression is ignored ([expr.prim.paren]).
  — end note ] The type of E1.E2 is “function of parameter-type-list
  cv returning T”.

For example the second statement in main below doesn't compile, probably because of the highlighted sentence above. But why is the language set up to work this way?

```<code>#include<iostream>
void g();
struct S { void f(); };
S s;

int main(){
    std::cout << "decltype(g) == void() ? " << std::is_same<decltype(g), void()>::value << '\n';            // Ok
    std::cout << "decltype(s.f) == void() ? " << std::is_same<decltype(s.f), void()>::value << '\n';        // Doesn't compile probably because of the sentence hihlighted above in [expr.ref]p(6.3.2).
}
</code>```

答:
When you do E1.E2, you are not talking about a general property of the type of thing that E1 is. You're asking to access a thing within the object designated by E1, where the name of the thing to be accessed is E2. If E2 is static, it accesses the class static thing; if E2 is non-static, then it accesses the member thing specific to that object. That's important.

Member variables become the subobject. If your class S had a non-static data member int i;, s.i is a reference to an int. That reference, from the stand point of an int&, behaves no differently from any other int&.

Let me say that more clearly: any int* or int& can point to/reference an int which is a complete object or an int which is a subobject of some other object. The single construct int& can serve double-duty in this way.*

Given that understanding of s.i, what would be the presumed meaning of s.f? Well, it should be similar, right? s.f would be some kind of thing that, when called with params, will be the equivalent of doing s.f(params).

But that is not a thing which exists in C++.

There is no language construct in C++ which can represent that meaning of s.f. Such a construct would need to store a reference to s as well as the member S::f.

A function pointer can't do that. Function pointers need to be able to be pointer-interconvertible with void***. But such an s.f would need to store the member S::f as well as a reference to s itself. So by definition, it'll have to be bigger than a void*.

A member pointer can't do that either. Member pointers explicitly don't carry their this object along with them (that's kind of the point); you must provide them at call-time using the specific member pointer call syntax .* or .->.

Oh, there are ways to encode this within the language: lambdas, std::bind, etc. But there is no language-level construct which has this precise meaning.

Because C++ is asymmetric in this way, where s.i has an encodable meaning but not s.f, C++ makes the unencodable one illegal.

You may ask why such a construct doesn't simply get built. It's not really that important. The language works perfectly fine as is, and due to the complexity of what an s.f would need to be, it's probably best to make you use a lambda (for which admittedly there should be ways to make it shorter to write such things) if that's what you want.

And if you want a naked s.f to be equivalent to S::f (ie: designates the member function), that doesn't really work either. First, S::f doesn't have a type either; the only thing you can do with such a prvalue is convert it to a pointer to a member. Second, a member function pointer doesn't know what object it came from, so in order to use one to call the member, you need to give it s. Therefore, in a call expression, s would have to appear twice. Which is really silly.

*: there are things you can do to complete objects that you cannot do to subobjects. But those provoke UB because they're not detectable by the compiler, because an int* doesn't say if it comes from a subobject or not. Which is the main point; nobody can tell the difference.

**: the standard does not require this, but the standard cannot do something which out-right makes such an implementation impossible. Most implementations provide this functionality, and basically any DLL/SO loading code relies on it. Oh, and it would also be completely incompatible with C, which makes it a non-starter.

Body:
[expr.ref]p(6.3.2):

Otherwise, if E1.E2 refers to a non-static member function and the
  type of E2 is “function of parameter-type-list cv
  ref-qualifieropt returning T”, then E1.E2 is a prvalue. The expression designates a non-static member function. The
  expression can be used only as the left-hand operand of a member
  function call ([class.mfct]). [ Note: Any redundant set of
  parentheses surrounding the expression is ignored ([expr.prim.paren]).
  — end note ] The type of E1.E2 is “function of parameter-type-list
  cv returning T”.

For example the second statement in main below doesn't compile, probably because of the highlighted sentence above. But why is the language set up to work this way?

#include<iostream>
void g();
struct S { void f(); };
S s;

int main(){
    std::cout << "decltype(g) == void() ? " << std::is_same<decltype(g), void()>::value << '\n';            // Ok
    std::cout << "decltype(s.f) == void() ? " << std::is_same<decltype(s.f), void()>::value << '\n';        // Doesn't compile probably because of the sentence hihlighted above in [expr.ref]p(6.3.2).
}


问:
Can an async method await multiple responses?
I am learning more about Mass Transit in my free time.  Please see the code below:

```<code>var serviceAddress = new Uri("rabbitmq://localhost/check-order-status");
var client = bus.CreateRequestClient<CheckOrderStatus>(serviceAddress);
var response = await client.GetResponse<OrderStatusResult>(new { OrderId = id});
</code>```

which I took from here: http://masstransit-project.com/MassTransit/usage/request-response.html

GetResponse sends a message to a rabbitmq fan out exchange, which has x consumers.  Each consumer needs to send a reply to the publisher, however the code above will only receive one reply and then carry on.  How can it receive x replies?

I have managed to do this with RabbitMQ (without Mass Transit) like this: https://dotnetcodr.com/2014/05/12/messaging-with-rabbitmq-and-net-c-part-5-headers-and-scattergather/.  However, I cannot work out how to do it with mass transit.

Can an async method await multiple replies?

Update

Using a handler appears to work:

```<code> sbc.ReceiveEndpoint(host, myMessage.Id.ToString(), ep =>
                {
                    ep.Handler<MyMessage>(context =>
                    {
                        testlist.Add(context.Message);
                        return Console.Out.WriteLineAsync($"Received: {context.Message.Name}");
                    });
                });
</code>```

I can now access testlist inside the sender.

答:
I believe you should be able to achieve similar behaviour than the scatter/gather example by using Task.WhenAll(IEnumerable). There is a section in the Mass Transit request-response page on how to use it on Composing multiple results.

Following the example code from Mass Transit, suppose that you have multiple serviceAddresses stored in a field:

```<code>ICollection<Uri> _serviceAddresses;
</code>```

If you want to get CheckOrderStatus responses from all the clients, you can do it as follows:

```<code>var getResponseTasks = new List<Task<Response<CheckOrderStatus>>>();
foreach(var serviceAdress in _serviceAddresses)
{
    var client = bus.CreateRequestClient<CheckOrderStatus>(serviceAddress);
    getResponseTasks.Add(client.GetResponse<OrderStatusResult>(new { OrderId = id}));
}

await Task.WhenAll(getResponseTasks);
</code>```

Now you'll just have to unwrap the results:

```<code>var responses = new List<Response<CheckOrderStatus>>();
foreach(var responseTask in getResponseTasks)
{
    var response = await responseTask;
    responses.Add(response);
}
</code>```

Body:
I am learning more about Mass Transit in my free time.  Please see the code below:

var serviceAddress = new Uri("rabbitmq://localhost/check-order-status");
var client = bus.CreateRequestClient<CheckOrderStatus>(serviceAddress);
var response = await client.GetResponse<OrderStatusResult>(new { OrderId = id});

which I took from here: http://masstransit-project.com/MassTransit/usage/request-response.html

GetResponse sends a message to a rabbitmq fan out exchange, which has x consumers.  Each consumer needs to send a reply to the publisher, however the code above will only receive one reply and then carry on.  How can it receive x replies?

I have managed to do this with RabbitMQ (without Mass Transit) like this: https://dotnetcodr.com/2014/05/12/messaging-with-rabbitmq-and-net-c-part-5-headers-and-scattergather/.  However, I cannot work out how to do it with mass transit.

Can an async method await multiple replies?

Update

Using a handler appears to work:

 sbc.ReceiveEndpoint(host, myMessage.Id.ToString(), ep =>
                {
                    ep.Handler<MyMessage>(context =>
                    {
                        testlist.Add(context.Message);
                        return Console.Out.WriteLineAsync($"Received: {context.Message.Name}");
                    });
                });

I can now access testlist inside the sender.

Body:
I believe you should be able to achieve similar behaviour than the scatter/gather example by using Task.WhenAll(IEnumerable). There is a section in the Mass Transit request-response page on how to use it on Composing multiple results.

Following the example code from Mass Transit, suppose that you have multiple serviceAddresses stored in a field:

ICollection<Uri> _serviceAddresses;

If you want to get CheckOrderStatus responses from all the clients, you can do it as follows:

var getResponseTasks = new List<Task<Response<CheckOrderStatus>>>();
foreach(var serviceAdress in _serviceAddresses)
{
    var client = bus.CreateRequestClient<CheckOrderStatus>(serviceAddress);
    getResponseTasks.Add(client.GetResponse<OrderStatusResult>(new { OrderId = id}));
}

await Task.WhenAll(getResponseTasks);

Now you'll just have to unwrap the results:

var responses = new List<Response<CheckOrderStatus>>();
foreach(var responseTask in getResponseTasks)
{
    var response = await responseTask;
    responses.Add(response);
}


问:
How to Execute R Script from Windows Command Prompt
I have the following added to my system path on Windows 10: C:\Program Files\R\R-3.4.3\bin\x64

Then I tried running from cmd prompt ~:> R myscript.R

ARGUMENT 'example_batch.R' ignored

It proceeded to an interactive session without any execution.

No idea how it seemed to work in this answer. I would prefer something this simple, as it is in Python.

The following works R -e "source('myscript.R')"

But I'll never remember this when I need it.

答:
The best way I've found is by executing Rscript.exe (it's installed with R.exe inside R directory).
You can do:

```<code>"C:\Program Files\R\R-3.6.0\bin\Rscript.exe" D:\path\to\yourRfile.r arg1 arg2 arg3
</code>```

The quotation marks ("") are necessary because dir name Program Files has space between it and Windows CMD wouldn't recognize it without quotation marks.

If you don't want to write R path, you can put R Path to your windows PATH environment variable. This way you could run like:

```<code>Rscript.exe D:\path\to\yourRfile.r arg1 arg2 arg3
</code>```

If you have doubts how to add R path to Windows PATH environment variable, you can follow these instructions (they are for adding Java to PATH, but you can use for R, the idea is the same).

Body:
The best way I've found is by executing Rscript.exe (it's installed with R.exe inside R directory).
You can do:

"C:\Program Files\R\R-3.6.0\bin\Rscript.exe" D:\path\to\yourRfile.r arg1 arg2 arg3

The quotation marks ("") are necessary because dir name Program Files has space between it and Windows CMD wouldn't recognize it without quotation marks.

If you don't want to write R path, you can put R Path to your windows PATH environment variable. This way you could run like:

Rscript.exe D:\path\to\yourRfile.r arg1 arg2 arg3

If you have doubts how to add R path to Windows PATH environment variable, you can follow these instructions (they are for adding Java to PATH, but you can use for R, the idea is the same).


问:
Git remote clone
I've git repo on remote server. I have ssh access to this server. When I try to clone the repo with command git clone ssh://nick@ip_addres:9022/repo.git I can't clone it. Error that appear is
git clone ssh://nick@ip_address:9022/repo.git
Cloning into repo...
fatal: '/repo.git' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

答:
If you ssh to that machine with the name login and do cd /repo.git, what do you get ?

You are probably missing the path to the repository...

ContentLicense: CC BY-SA 3.0

Title: Git remote clone


问:
establishing socket connection with two wifip2p device
I am imlementing wifip2p device discovery as service. I have successfully discovered a device and I have its WifiP2pDevice instance available. Now I want to establish a socket connection. For this first I have to connect to found device as

```<code>WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = wifiP2pDevice.deviceAddress;
wifiP2pManager.connect(channel, config, listener);
</code>```

Here I am successfully connecting to peer. But when I tried to connect socket for data transfer I found that I do not have proper InetAddress but I tried with following code

```<code>Socket socket = new Socket();
socket.bind(null);
socket.connect( new InetSocketAddress(port), 1000);
</code>```

As expected I got connection failed. So here most probably the problem is I don't have any hostname. I tried finding docs but could not found any thing.

In short I have a peer connected and have its wifip2pdevice instance, how will I establish socket connection?

答:
For transferring and receiving data between two devices through wifip2p.You need to create three threads.each  for client,server and clientServer thread for transferring data.refer the complete code.
 MainActivity.java file:-</p>

```<code>public class MainActivity extends AppCompatActivity {

    Button btnOnOff, btnDiscover, btnSend;
    ListView listView;
    TextView read_msg_box, connectionStatus;
    EditText writeMsg;

    WifiManager wifiManager;
    WifiP2pManager mManager;
    WifiP2pManager.Channel mChannel;

    BroadcastReceiver mReceiver;
    IntentFilter mIntentFilter;

    List<WifiP2pDevice> peers=new ArrayList<WifiP2pDevice>();
    String[] deviceNameArray;
    WifiP2pDevice[] deviceArray;

    static final int MESSAGE_READ=1;

    ServerClass serverClass;
    ClientClass clientClass;
    SendReceive sendReceive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialWork();
        exqListener();
    }

    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what)
            {
                case MESSAGE_READ:
                    byte[] readBuff= (byte[]) msg.obj;
                    String tempMsg=new String(readBuff,0,msg.arg1);
                    read_msg_box.setText(tempMsg);
                    break;
            }
            return true;
        }
    });

    private void exqListener() {
        btnOnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(false);
                    btnOnOff.setText("ON");
                }else {
                    wifiManager.setWifiEnabled(true);
                    btnOnOff.setText("OFF");
                }
            }
        });

        btnDiscover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        connectionStatus.setText("Discovery Started");
                    }

                    @Override
                    public void onFailure(int i) {
                        connectionStatus.setText("Discovery Starting Failed");
                    }
                });
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final WifiP2pDevice device=deviceArray[i];
                WifiP2pConfig config=new WifiP2pConfig();
                config.deviceAddress=device.deviceAddress;

                mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(getApplicationContext(),"Connected to "+device.deviceName,Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int i) {
                        Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg=writeMsg.getText().toString();
                sendReceive.write(msg.getBytes());
            }
        });
    }

    private void initialWork() {
        btnOnOff=(Button) findViewById(R.id.onOff);
        btnDiscover=(Button) findViewById(R.id.discover);
        btnSend=(Button) findViewById(R.id.sendButton);
        listView=(ListView) findViewById(R.id.peerListView);
        read_msg_box=(TextView) findViewById(R.id.readMsg);
        connectionStatus=(TextView) findViewById(R.id.connectionStatus);
        writeMsg=(EditText) findViewById(R.id.writeMsg);

        wifiManager= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        mManager= (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel=mManager.initialize(this,getMainLooper(),null);

        mReceiver=new WiFiDirectBroadCastReviever(mManager, mChannel,this);

        mIntentFilter=new IntentFilter();
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    }

    WifiP2pManager.PeerListListener peerListListener=new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerList) {
            if(!peerList.getDeviceList().equals(peers))
            {
                peers.clear();
                peers.addAll(peerList.getDeviceList());

                deviceNameArray=new String[peerList.getDeviceList().size()];
                deviceArray=new WifiP2pDevice[peerList.getDeviceList().size()];
                int index=0;

                for(WifiP2pDevice device : peerList.getDeviceList())
                {
                    deviceNameArray[index]=device.deviceName;
                    deviceArray[index]=device;
                    index++;
                }

                ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
                listView.setAdapter(adapter);
            }

            if(peers.size()==0)
            {
                Toast.makeText(getApplicationContext(),"No Device Found",Toast.LENGTH_SHORT).show();
                return;
            }
        }
    };

    WifiP2pManager.ConnectionInfoListener connectionInfoListener=new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
            final InetAddress groupOwnerAddress=wifiP2pInfo.groupOwnerAddress;

            if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner)
            {
                connectionStatus.setText("Host");
                serverClass=new ServerClass();
                serverClass.start();
            }else if(wifiP2pInfo.groupFormed)
            {
                connectionStatus.setText("Client");
                clientClass=new ClientClass(groupOwnerAddress);
                clientClass.start();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver,mIntentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    public class ServerClass extends Thread{
        Socket socket;
        ServerSocket serverSocket;

        @Override
        public void run() {
            try {
                serverSocket=new ServerSocket(8888);
                socket=serverSocket.accept();
                sendReceive=new SendReceive(socket);
                sendReceive.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class SendReceive extends Thread{
        private Socket socket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public SendReceive(Socket skt)
        {
            socket=skt;

                try {
                    inputStream = socket.getInputStream();
                    outputStream = socket.getOutputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }

        @Override
        public void run() {
            byte[] buffer=new byte[1024];
            int bytes;

            while (socket!=null)
            {
                try {
                    bytes=inputStream.read(buffer);
                    if(bytes>0)
                    {
                        handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void write(byte[] bytes) {

                try {
                    outputStream.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }

    public class ClientClass extends Thread{
        Socket socket;
        String hostAdd;

        public  ClientClass(InetAddress hostAddress)
        {
            hostAdd=hostAddress.getHostAddress();
            socket=new Socket();
        }

        @Override
        public void run() {
            try {
                socket.connect(new InetSocketAddress(hostAdd,8888),500);
                sendReceive=new SendReceive(socket);
                sendReceive.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

WiFiDirectBroadCastReviever.java class:
public class WiFiDirectBroadCastReviever extends BroadcastReceiver {
    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private MainActivity mActivity;

    public WiFiDirectBroadCastReviever(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
        this.mManager = mManager;
        this.mChannel = mChannel;
        this.mActivity = mActivity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action=intent.getAction();
        if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
            int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
            if (state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
                Toast.makeText(context,"wifi is on",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(context,"wifi is off",Toast.LENGTH_SHORT).show();
            }
        }else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
            if (mManager!=null){
                mManager.requestPeers(mChannel,mActivity.peerListListener);
            }
        }else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
            if (mManager==null){
                return;
            }

            NetworkInfo networkInfo=intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

            if(networkInfo.isConnected()){
                mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
            }else {
                mActivity.connectionStatus.setText("device disconnected");
            }
        }else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
        }
    }
}
</code>```

Body:
I am imlementing wifip2p device discovery as service. I have successfully discovered a device and I have its WifiP2pDevice instance available. Now I want to establish a socket connection. For this first I have to connect to found device as

WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = wifiP2pDevice.deviceAddress;
wifiP2pManager.connect(channel, config, listener);

Here I am successfully connecting to peer. But when I tried to connect socket for data transfer I found that I do not have proper InetAddress but I tried with following code

Socket socket = new Socket();
socket.bind(null);
socket.connect( new InetSocketAddress(port), 1000);

As expected I got connection failed. So here most probably the problem is I don't have any hostname. I tried finding docs but could not found any thing.

In short I have a peer connected and have its wifip2pdevice instance, how will I establish socket connection?

Body:
For transferring and receiving data between two devices through wifip2p.You need to create three threads.each  for client,server and clientServer thread for transferring data.refer the complete code.
 MainActivity.java file:-

public class MainActivity extends AppCompatActivity {

    Button btnOnOff, btnDiscover, btnSend;
    ListView listView;
    TextView read_msg_box, connectionStatus;
    EditText writeMsg;

    WifiManager wifiManager;
    WifiP2pManager mManager;
    WifiP2pManager.Channel mChannel;

    BroadcastReceiver mReceiver;
    IntentFilter mIntentFilter;

    List<WifiP2pDevice> peers=new ArrayList<WifiP2pDevice>();
    String[] deviceNameArray;
    WifiP2pDevice[] deviceArray;

    static final int MESSAGE_READ=1;

    ServerClass serverClass;
    ClientClass clientClass;
    SendReceive sendReceive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initialWork();
        exqListener();
    }

    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what)
            {
                case MESSAGE_READ:
                    byte[] readBuff= (byte[]) msg.obj;
                    String tempMsg=new String(readBuff,0,msg.arg1);
                    read_msg_box.setText(tempMsg);
                    break;
            }
            return true;
        }
    });

    private void exqListener() {
        btnOnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(false);
                    btnOnOff.setText("ON");
                }else {
                    wifiManager.setWifiEnabled(true);
                    btnOnOff.setText("OFF");
                }
            }
        });

        btnDiscover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        connectionStatus.setText("Discovery Started");
                    }

                    @Override
                    public void onFailure(int i) {
                        connectionStatus.setText("Discovery Starting Failed");
                    }
                });
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final WifiP2pDevice device=deviceArray[i];
                WifiP2pConfig config=new WifiP2pConfig();
                config.deviceAddress=device.deviceAddress;

                mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(getApplicationContext(),"Connected to "+device.deviceName,Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int i) {
                        Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg=writeMsg.getText().toString();
                sendReceive.write(msg.getBytes());
            }
        });
    }

    private void initialWork() {
        btnOnOff=(Button) findViewById(R.id.onOff);
        btnDiscover=(Button) findViewById(R.id.discover);
        btnSend=(Button) findViewById(R.id.sendButton);
        listView=(ListView) findViewById(R.id.peerListView);
        read_msg_box=(TextView) findViewById(R.id.readMsg);
        connectionStatus=(TextView) findViewById(R.id.connectionStatus);
        writeMsg=(EditText) findViewById(R.id.writeMsg);

        wifiManager= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        mManager= (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel=mManager.initialize(this,getMainLooper(),null);

        mReceiver=new WiFiDirectBroadCastReviever(mManager, mChannel,this);

        mIntentFilter=new IntentFilter();
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    }

    WifiP2pManager.PeerListListener peerListListener=new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerList) {
            if(!peerList.getDeviceList().equals(peers))
            {
                peers.clear();
                peers.addAll(peerList.getDeviceList());

                deviceNameArray=new String[peerList.getDeviceList().size()];
                deviceArray=new WifiP2pDevice[peerList.getDeviceList().size()];
                int index=0;

                for(WifiP2pDevice device : peerList.getDeviceList())
                {
                    deviceNameArray[index]=device.deviceName;
                    deviceArray[index]=device;
                    index++;
                }

                ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
                listView.setAdapter(adapter);
            }

            if(peers.size()==0)
            {
                Toast.makeText(getApplicationContext(),"No Device Found",Toast.LENGTH_SHORT).show();
                return;
            }
        }
    };

    WifiP2pManager.ConnectionInfoListener connectionInfoListener=new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
            final InetAddress groupOwnerAddress=wifiP2pInfo.groupOwnerAddress;

            if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner)
            {
                connectionStatus.setText("Host");
                serverClass=new ServerClass();
                serverClass.start();
            }else if(wifiP2pInfo.groupFormed)
            {
                connectionStatus.setText("Client");
                clientClass=new ClientClass(groupOwnerAddress);
                clientClass.start();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver,mIntentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    public class ServerClass extends Thread{
        Socket socket;
        ServerSocket serverSocket;

        @Override
        public void run() {
            try {
                serverSocket=new ServerSocket(8888);
                socket=serverSocket.accept();
                sendReceive=new SendReceive(socket);
                sendReceive.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class SendReceive extends Thread{
        private Socket socket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public SendReceive(Socket skt)
        {
            socket=skt;

                try {
                    inputStream = socket.getInputStream();
                    outputStream = socket.getOutputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }

        @Override
        public void run() {
            byte[] buffer=new byte[1024];
            int bytes;

            while (socket!=null)
            {
                try {
                    bytes=inputStream.read(buffer);
                    if(bytes>0)
                    {
                        handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void write(byte[] bytes) {

                try {
                    outputStream.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
    }

    public class ClientClass extends Thread{
        Socket socket;
        String hostAdd;

        public  ClientClass(InetAddress hostAddress)
        {
            hostAdd=hostAddress.getHostAddress();
            socket=new Socket();
        }

        @Override
        public void run() {
            try {
                socket.connect(new InetSocketAddress(hostAdd,8888),500);
                sendReceive=new SendReceive(socket);
                sendReceive.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

WiFiDirectBroadCastReviever.java class:
public class WiFiDirectBroadCastReviever extends BroadcastReceiver {
    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private MainActivity mActivity;

    public WiFiDirectBroadCastReviever(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
        this.mManager = mManager;
        this.mChannel = mChannel;
        this.mActivity = mActivity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action=intent.getAction();
        if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
            int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
            if (state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
                Toast.makeText(context,"wifi is on",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(context,"wifi is off",Toast.LENGTH_SHORT).show();
            }
        }else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
            if (mManager!=null){
                mManager.requestPeers(mChannel,mActivity.peerListListener);
            }
        }else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
            if (mManager==null){
                return;
            }

            NetworkInfo networkInfo=intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

            if(networkInfo.isConnected()){
                mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
            }else {
                mActivity.connectionStatus.setText("device disconnected");
            }
        }else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
            // TODO: 19-Mar-19
        }
    }
}


问:
React Native failed to compile giving Error on the Device
I'm new to the React Native application development. When I after creating project and configured my device, It gives error like below and stop responding.

```<code>BUILD SUCCESSFUL in 27s
26 actionable tasks: 1 executed, 25 up-to-date
'C:\Users\Amila' is not recognized as an internal or external command,
operable program or batch file.
info Starting the app (C:\Users\Amila Eranda\AppData\Local\Android
\Sdk/platform-tools/adb shell am start -n
com.awesomeproject/com.awesomeproject.MainActivity...
Starting: Intent { cmp=com.awesomeproject/.MainActivity }
</code>```

It shows build is success but there is an error on the Device saying

Unable to load script. Make sure you're either running a metro server...

running the adb devices command shows there is a device connected to my PC. But it fails running it in the Device.

答:
That error on your device means that your device cannot connect to the metro server running on your computer to get the js bundle. The app on your device is a temporary app used by react native to quickly download the javascript code from your computer and convert it to code your device can understand each and every time you make changes to your code. Your device must be connected to your computer either on the same wifi network (with metro bundler running in a terminal window on your computer) or through a usb cable (with usb debugging enabled on your device and adb reverse set on a command prompt on your computer).

Read this from the android documentation to find out how to enable developer options on your android device: https://developer.android.com/studio/debug/dev-options

If your android device lets you, you can create a hotspot and have your computer connect to it if you do not have wifi available and usb debugging does not work for you.

Read this from the react native documentation: https://facebook.github.io/react-native/docs/running-on-device#connecting-to-the-development-server-1

Body:
I'm new to the React Native application development. When I after creating project and configured my device, It gives error like below and stop responding.

BUILD SUCCESSFUL in 27s
26 actionable tasks: 1 executed, 25 up-to-date
'C:\Users\Amila' is not recognized as an internal or external command,
operable program or batch file.
info Starting the app (C:\Users\Amila Eranda\AppData\Local\Android
\Sdk/platform-tools/adb shell am start -n
com.awesomeproject/com.awesomeproject.MainActivity...
Starting: Intent { cmp=com.awesomeproject/.MainActivity }

It shows build is success but there is an error on the Device saying

Unable to load script. Make sure you're either running a metro server...

running the adb devices command shows there is a device connected to my PC. But it fails running it in the Device.


问:
Proxy a node/react application in an apache server
Using forever to forever run the node server on the virtual machine, I am unable to get the app to run without explicitly adding the port in the url like so: URL.com:8080
If I don't use the port in the URL, I do load up the file structure of the application.

Steps to reproduce: I have a create-react-app application.On the virtual server I run 'npm run build' to make sure I have a build to serve. I then run forever start on the root of the application.

The code below should give all the necessary details. I can provide more if you need.

I have spent so much time tweaking the .conf file to try different configurations but I can't seem to get it. I am using it and successfully hosting two static html sites but not this node application.

Package.json:

```<code>...
"main":"server/index.js",
"proxy":"http://localhost:8080"
...
</code>```

Apache url.conf:

```<code><VirtualHost *:80>
    ServerName URL.com
    ServerAlias URL.com:8080/
    DocumentRoot /var/www/nameOfApp/
<Directory />
    Options -Indexes +FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www/nameOfApp/public>
    Options +Indexes +FollowSymLinks +MultiViews
    AllowOverride All
</Directory>
</VirtualHost>
</code>```

Node server file using express:

```<code>app.use(express.static(`${__dirname}/../build`));
</code>```

I've also made sure I have the modules enabled to allow for proxying. So I think essentially, what I need is to request this site and not need the :8080 at the end.

答:
The configuration that eventually worked was as simple as this:

```<code><VirtualHost *:80>
    ServerName yourdomain.com
    ProxyPreserveHost on
    ProxyPass / http://localhost:8080/
</VirtualHost>
</code>```

Looks like I was over complicating it trying to create a complicated proxy but the solution was very simply adding this to the config for the node application and then running sudo systemctl restart apache2 and everything worked beautifully.

Body:
Using forever to forever run the node server on the virtual machine, I am unable to get the app to run without explicitly adding the port in the url like so: URL.com:8080
If I don't use the port in the URL, I do load up the file structure of the application.

Steps to reproduce: I have a create-react-app application.On the virtual server I run 'npm run build' to make sure I have a build to serve. I then run forever start on the root of the application.

The code below should give all the necessary details. I can provide more if you need.

I have spent so much time tweaking the .conf file to try different configurations but I can't seem to get it. I am using it and successfully hosting two static html sites but not this node application.

Package.json:

...
"main":"server/index.js",
"proxy":"http://localhost:8080"
...

Apache url.conf:

<VirtualHost *:80>
    ServerName URL.com
    ServerAlias URL.com:8080/
    DocumentRoot /var/www/nameOfApp/
<Directory />
    Options -Indexes +FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www/nameOfApp/public>
    Options +Indexes +FollowSymLinks +MultiViews
    AllowOverride All
</Directory>
</VirtualHost>

Node server file using express:

app.use(express.static(`${__dirname}/../build`));

I've also made sure I have the modules enabled to allow for proxying. So I think essentially, what I need is to request this site and not need the :8080 at the end.

Body:
The configuration that eventually worked was as simple as this:

<VirtualHost *:80>
    ServerName yourdomain.com
    ProxyPreserveHost on
    ProxyPass / http://localhost:8080/
</VirtualHost>

Looks like I was over complicating it trying to create a complicated proxy but the solution was very simply adding this to the config for the node application and then running sudo systemctl restart apache2 and everything worked beautifully.


问:
How can I make my HTTP website become HTTPS?
I have a website called http://jobdirecto.com/ that I want to turn into HTTPS.

The site is hosted in Heroku and the domain I got from Namecheap.

I got the paid version of Heroku since that lets me configure the SSL (and I think that's what I have to configure to make it HTTPS). They ask me for a "public certificate" that I don't have though.

I also bought a SSL from SSLs.com and they gave me a private key but no public certificate.

I am lost in what I have to do now to make my website secure.

答:
There's no need to purchase anything. Use Heroku's Automated Certificate Management, which is powered by Let's Encrypt:

Run heroku domains and make note of the .herokudns.com domain it lists

Set up a CNAME record for your custom domain pointing to the .herokudns.com domain from the previous step

Run heroku certs:auto:enable to start the certficate provisioning process

Run heroku certs:auto to see your certificate's status

Please note that

It usually takes between 45 and 60 minutes to generate a TLS certificate for your app’s custom domains

This will let your site run over HTTPS, but it won't automatically redirect requests from HTTP to HTTPS. To do that we'll need to know more about your application.


问:
ASP.NET MVC Controller with multiple repositories?
I have a View where I am searching my db for an object(i.e. Books)..

My controller for this view depends on a BooksRepository that implements a search method.

Everything works fine. I also have the option to do an advanced search which presents a larger form in a Modal popup. This form has many fields including a Dropdown box to select an 'Author' to search by.

I would like to pass a list of authors in my viewmodel so in my conroller I instantiate an instance of my view model, I need to call a repository method to bring back the list of authors's...

My thinking is that this GetAuthors() method should be in an AuthorRepository...

Is it bad practice to inject multiple repo's into a controller?  or should I have an Author controller that gets injected with the author repo...and call a method in the Author controller from my BookSearch controller?

答:
From an architect point of view.

If you feel your mvc controllers are getting out of hand with dependencies, then its time to think about 2 things.

have a look at the design and determine if you need facade classes to represent complex subsystems, besides its better for unit testing anyway (there are such thing as 4 tier apps)

look at some of the other design patterns that can help solve this issue before it becomes it becomes a problem (strategy with DI, visitor possibly)

Also, I bet in this situation the unit tests are more of a pain, if you can't unit test it in a simple way, it should be flagged for improvement

Good luck,


问:
Why is there space between the parallelogram-divs?
I've made a few parallelograms in a row like that, but there is some space between them. I want to remove that space. margin-left: -1px; works, but I'm afraid that it's a bad solution to this problem.

Here is a fiddle: https://jsfiddle.net/rw40ugq1/

Here is the code:

body {
    font-size: 0;
    margin: 0;
}

.parallelogram {
    background-color: red;
    display: inline-block;
    height: 100px;
    width: 85px;
    transform: skew(20deg);
    position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
    <div class="parallelogram"></div>
</body></code>```

答:
The problem here seems to be the width of the parallelogram sometimes a certain width can show a space between the divs.

Try to change:

```<code>width: 85px;
</code>```

To

```<code>width: 86px;
</code>```

Usually the odd numbers will show a space between the divs try to always use an even number while choosing the width of an element.

Body:
The problem here seems to be the width of the parallelogram sometimes a certain width can show a space between the divs.

Try to change:

width: 85px;

To

width: 86px;

Usually the odd numbers will show a space between the divs try to always use an even number while choosing the width of an element.


问:
STM32F746ZG - How to update some part of 256 KB sector in flash
I'm using STM32F103 and moving my code to STM32F746. The F103 was able to update Flash on a per-page basis in 1KB and 2KB.
I have STM32F746ZG Nucleo-board and my code size is big, flash took up to 0x08038000. I want to save other small applications on 0x08040000(sector_5). This applications consist of several 2KB sizes. I need to store multiple applications in Sector_5 and M7 cannot use Flash in 1KB or 2KB increments.

The followings are sector sizes of STM32F746ZG.

```<code>#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08008000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08010000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x08018000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08020000) // 128 Kbytes
#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08040000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08080000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x080C0000) // 256 Kbytes
</code>```

STM32F746 consists of flash in a sector size of 256 KB each from Sector_5 to Sector7. If I want to use the Sector_5, I have to erase the whole of one sector. What if I want to update only about 2KB in the front of the Sector_5 and keep the area after 2KB intact? It means I only update the content from 0x08040000 to 0x08042000. I have to keep from 0x08042001 to 0x0807FFFF.

I can't even copy 256 KB of Flash to RAM. Because F746 only have 240KB of internal RAM and my many tasks already used RAM, so there is not enough RAM to copy one sector. In this case, please let me know how to update part of 256KB in flash.

答:
On the ST's flash technology, there is no way to update anywhere in the sector without first erasing it. So if there are content in the first 2KB, you cannot update it without erasing the rest of the sector.

One possibility is that you can keep one sector as a temporary buffer and never use it for real storage. Let's say you use sector 7 for that. So when you want to update sector 5, erase sector 7, copy sector 5 into sector 7, and then erase sector 5 and copy relevant content back.

Another possibility is to add an external EEPROM or SRAM for this purpose. SPI flash EEPROM is fairly inexpensive and they have a typical 100,000 write cycles, so also perfect for this use.

Body:
I'm using STM32F103 and moving my code to STM32F746. The F103 was able to update Flash on a per-page basis in 1KB and 2KB.
I have STM32F746ZG Nucleo-board and my code size is big, flash took up to 0x08038000. I want to save other small applications on 0x08040000(sector_5). This applications consist of several 2KB sizes. I need to store multiple applications in Sector_5 and M7 cannot use Flash in 1KB or 2KB increments.

The followings are sector sizes of STM32F746ZG.

#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08008000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08010000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x08018000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08020000) // 128 Kbytes
#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08040000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08080000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x080C0000) // 256 Kbytes

STM32F746 consists of flash in a sector size of 256 KB each from Sector_5 to Sector7. If I want to use the Sector_5, I have to erase the whole of one sector. What if I want to update only about 2KB in the front of the Sector_5 and keep the area after 2KB intact? It means I only update the content from 0x08040000 to 0x08042000. I have to keep from 0x08042001 to 0x0807FFFF.

I can't even copy 256 KB of Flash to RAM. Because F746 only have 240KB of internal RAM and my many tasks already used RAM, so there is not enough RAM to copy one sector. In this case, please let me know how to update part of 256KB in flash.


问:
Undefined method error for main:Object when using gem
Testing out making a gem, figured logic gates would be more or less effortless(if useless) to actually implement so I used them. I have this code in my lib/logic.rb file:

```<code>require "logic/version"

module Logic
  def or_gate(a, b)
    a || b
  end

  def and_gate(a, b)
    a && b
  end

  def nand_gate(a, b)
    !(a && b)
  end

  def nor_gate(a, b)
    !(a || b)
  end

  def not_gate(a)
    !a
  end

  def xor_gate(a, b)
    !(a == b)
  end

  def xnor_gate(a, b)
    a == b
  end
end
</code>```

I can build and install the gem without issue, but when testing with irb calling the or_gate method for example just returns a "NoMethodError: undefined method 'or_gate' for main:Object'. Doing something like

```<code>Logic.or_gate
</code>```

or

```<code>Logic::Gate.or_gate
</code>```

(putting methods in a Gate class) both have the same problem. What am I doing wrong?

答:
You have defined instance methods, not module methods. Change:

```<code>def or_gate(a, b)
</code>```

to:

```<code>def self.or_gate(a, b)
</code>```

and it'll work the way you expect:

```<code>Logic.or_gate(1,2)
 => 1
</code>```

Repeat this change for all your method definitions.

Alternatively, you can use extend self to accomplish the same goal without having to add self. to each method definition:

```<code>module Logic
  extend self

  def or_gate(a, b)
    a || b
  end
end
</code>```

This adds/copies all the instance methods as module methods.

There is more discussion of this here, and this answer goes into some more detail on how methods are defined in modules.

Body:
Testing out making a gem, figured logic gates would be more or less effortless(if useless) to actually implement so I used them. I have this code in my lib/logic.rb file:

require "logic/version"

module Logic
  def or_gate(a, b)
    a || b
  end

  def and_gate(a, b)
    a && b
  end

  def nand_gate(a, b)
    !(a && b)
  end

  def nor_gate(a, b)
    !(a || b)
  end

  def not_gate(a)
    !a
  end

  def xor_gate(a, b)
    !(a == b)
  end

  def xnor_gate(a, b)
    a == b
  end
end

I can build and install the gem without issue, but when testing with irb calling the or_gate method for example just returns a "NoMethodError: undefined method 'or_gate' for main:Object'. Doing something like

Logic.or_gate

or

Logic::Gate.or_gate

(putting methods in a Gate class) both have the same problem. What am I doing wrong?

Body:
You have defined instance methods, not module methods. Change:

def or_gate(a, b)

to:

def self.or_gate(a, b)

and it'll work the way you expect:

Logic.or_gate(1,2)
 => 1

Repeat this change for all your method definitions.

Alternatively, you can use extend self to accomplish the same goal without having to add self. to each method definition:

module Logic
  extend self

  def or_gate(a, b)
    a || b
  end
end

This adds/copies all the instance methods as module methods.

There is more discussion of this here, and this answer goes into some more detail on how methods are defined in modules.


问:
Position sticky and background-color of thead cell hides outline of tbody
How do you prevent the red outline from being hidden by the green background-color of the th and keep the border-collapse? Is there a CSS spec that defines this behavior?

table {
  border-collapse: collapse
}

tbody {
  outline: solid red;
}

thead tr th {
  background-color: green;
  position: sticky;
  top: 0
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr><th>header</th></tr>
  </thead>
  <tbody>
    <tr><td>content</td></tr>
  </tbody>
</table></code>```

答:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_without_z-index talks about the order in which elements are painted. position: sticky elements are "positioned" so are painted on top of the position: static tbody element. You can use z-index to override this.

table {
  border-collapse: collapse
}

tbody {
  outline: solid red;
}

thead tr th {
  background-color: green;
  position: sticky;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr><th>header</th></tr>
  </thead>
  <tbody>
    <tr><td>content</td></tr>
  </tbody>
</table></code>```

Body:
How do you prevent the red outline from being hidden by the green background-color of the th and keep the border-collapse? Is there a CSS spec that defines this behavior?

table {
  border-collapse: collapse
}

tbody {
  outline: solid red;
}

thead tr th {
  background-color: green;
  position: sticky;
  top: 0
}

header

content

Body:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_without_z-index talks about the order in which elements are painted. position: sticky elements are "positioned" so are painted on top of the position: static tbody element. You can use z-index to override this.

table {
  border-collapse: collapse
}

tbody {
  outline: solid red;
}

thead tr th {
  background-color: green;
  position: sticky;
  z-index: -1;
}

<table>
  <thead>
    <tr><th>header</th></tr>
  </thead>
  <tbody>
    <tr><td>content</td></tr>
  </tbody>
</table>


问:
Is there a way to make an indeterminate checkbutton with PyGtk?
I am designing a GUI where I have a list of checkable items that also has a sublist of checkable items. I want to graphically represent in the parent checkbox if only some of the child items are checked. I have been searching Google for hours with this and the only documents explain how to style a possible button. Is there a way in Gtk to do this cleanly?</p>

答: Checkbutton's parent ToggleButton has inconsistent property, which is what you are looking for (screenshot)


问:
How to read column value generically from a datatable in .NET without explicitly specifying the data type and column name
I want to read column value from a datatable without explicitly specifying the data type and column name.

E.g.

```<code>int carId = CarTable.Rows[i].Field<int>("CarId");  //this requires the data type and column name.

string name= CarTable.Rows[i].Field<string>("Name");
</code>```

I want to read to carId without explicitly specifying the data type and column name.

Will it be easier if I want the return type of all columns be string type?

答:
Assuming you're thinking of using the column's position rather than its name, you should be able to do :</p>

```<code>Object colvalue = CarTable.Rows[i].Items[colpos];
</code>```

Body:
I want to read column value from a datatable without explicitly specifying the data type and column name.

E.g.

int carId = CarTable.Rows[i].Field<int>("CarId");  //this requires the data type and column name.

string name= CarTable.Rows[i].Field<string>("Name");

I want to read to carId without explicitly specifying the data type and column name.

Will it be easier if I want the return type of all columns be string type?

Body:
Assuming you're thinking of using the column's position rather than its name, you should be able to do :

Object colvalue = CarTable.Rows[i].Items[colpos];


问:
Finding an alphanumeric character in a string using find_if and isalnum
I'm using g++ 4.7.

What I'm trying to do is this,

```<code>find_if(s.begin(), s.end(), isalnum);
</code>```

where isalnum is defined in cctype and s is a string.

```<code>logman.cpp:68:47: error: no matching function for call to ‘find_if(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, <unresolved overloaded function type>)’
</code>```

However, this works,

```<code>bool my_isalnum(int c) {
    return isalnum(c);
}

find_if(s.begin(), s.end(), my_isalnum);
</code>```

How can I get this to work without creating my own function?

答:
This should work</p>

```<code>#include <algorithm >
#include <cctype>

auto result = std::find_if(std::begin(s), std::end(s),  isalnum) ;
</code>```

Body:
I'm using g++ 4.7.

What I'm trying to do is this,

find_if(s.begin(), s.end(), isalnum);

where isalnum is defined in cctype and s is a string.

logman.cpp:68:47: error: no matching function for call to ‘find_if(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, <unresolved overloaded function type>)’

However, this works,

bool my_isalnum(int c) {
    return isalnum(c);
}

find_if(s.begin(), s.end(), my_isalnum);

How can I get this to work without creating my own function?

Body:
This should work

#include <algorithm >
#include <cctype>

auto result = std::find_if(std::begin(s), std::end(s),  isalnum) ;


问:
Router link changes the path but Router view doesn’t change
So i have a side navbar and some link in it. The entry point is the homepage. The problem is, when i'm trying to change router-view using router-link in my side navbar, the router-view doesn't change, but the path has change.

So here's my route path on my router.js:

```<code>        {
        path: '/',
        component: Home,
        children: [
                {
                    path: ':name',
                    name: 'theTask',
                    props: true,
                    component: TodoList
                }
            ]
        },
    ],
</code>```

And here's my App.vue

```<code><div class="container">
            <div class="main__content">
                <div class="sidenav">
                    <aside class="menu">
                        <ul class="menu-list">
                            <li><router-link :to="{ name: 'theTask', params: {name: 'today'} }">Today</router-link></li>
                            <li><router-link :to="{ name: 'home' }">Next 7 Days</router-link></li>
                        </ul>
                    </aside>
                </div>
                <div class="content">
                    <router-view></router-view>
                </div>
            </div>
     </div>
</code>```

It rendered the homepage, but when i'm clicking router-link to the child route, it doesn't change the router-view, only the router link.

答:
In this case you should provide an empty subroute path. I have created a fiddle for the same here. This is as per the vue-router documentation.

```<code>    { path: '/',
        component: Base,
      children: [{
        path: '',
        name: 'Home',
        component: Home
      },{
        path: ':name',
        name: 'theTask',
        props: true,
        component: Foo
      }]
    }
  ]
})
</code>```

Body:
So i have a side navbar and some link in it. The entry point is the homepage. The problem is, when i'm trying to change router-view using router-link in my side navbar, the router-view doesn't change, but the path has change.

So here's my route path on my router.js:

        {
        path: '/',
        component: Home,
        children: [
                {
                    path: ':name',
                    name: 'theTask',
                    props: true,
                    component: TodoList
                }
            ]
        },
    ],

And here's my App.vue

<router-link :to="{ name: 'theTask', params: {name: 'today'} }">Today</router-link>

<router-link :to="{ name: 'home' }">Next 7 Days</router-link>

                    <router-view></router-view>

It rendered the homepage, but when i'm clicking router-link to the child route, it doesn't change the router-view, only the router link.

Body:
In this case you should provide an empty subroute path. I have created a fiddle for the same here. This is as per the vue-router documentation.

    { path: '/',
        component: Base,
      children: [{
        path: '',
        name: 'Home',
        component: Home
      },{
        path: ':name',
        name: 'theTask',
        props: true,
        component: Foo
      }]
    }
  ]
})