问:
Problems with structures with pointers to arrays of other structures in C
I am attempting to tackle college worksheet on C programming (no marking for it, just to improve our learning). What we're meant to do is get a few details about shipping docks. I decided to use structures for this.

My code is below, what I need help with is to print out the information (to see if its working) of whats at the location of the shipyards .run.

Everything compiles and according to the debugger shipyard1.run and shipyard2.run point to different locations, but I can not see the values.

```<code>int main(int argc, char** argv)
{
    typedef struct dockInfo
    {
        int dockCode;
        int dockLength;
    }dckDetails;

    typdef struct shipyard
    {
        char dockName[20];

        /* however big this number is thats how many dockInfo structs are needed.*/

        int numOfDocks;
        dckDetails *run; //points to the array of dockInfo structs

    };

    struct dockInfo *arrayD; // the array to hold all the dockInfo structs
    struct dockInfo tempo; // the temporary dockInfo struct to take in the details
    struct shipyard shipyard1;
    struct shipyard shipyard2;

    /**
    * the variables for shipyard1 and shipyard2 are then assigned
    **/

    int i;
    for (i=0;i<shipyard1.numOfDocks;i++)
    {

    arrayD=calloc(shipyard1.numOfDocks,100); // allocate a new bit of memory for arrayD
    tempo.dockCode=45*i;
    tempo.dockLength=668*i;
    arrayD[i]=tempo; //the element of arrayD becomes tempo.

    }
    shipyard1.run=arrayD; //make shipyard1.run point to the location of arrayD.

    for (i=0;i<shipyard2.numOfDocks;i++)
    {

    arrayD=calloc(shipyard2.numOfDocks,100); // allocate a new bit of memory for arrayD
    tempo.dockCode=1234*i;
    tempo.dockLength=1200*i;
    arrayD[i]=tempo; //the element of arrayD becomes tempo.

    }
    shipyard2.run=arrayD; //make shipyard2.run point to the new location of arrayD.

    int elementTest1; // need element1test to be shipyard1.run[0].dockLength;
    int elementTest2; // need element2test to be shipyard2.run[1].dockCode;

return (EXIT_SUCCESS);
}
</code>```

It should be noted that I have left a lot of code out because I have yet to write it. I have used static examples for the moment (shipyard1 and shipyard2) but in the future I am going to implment a 'load info from file' feature.

Any help would be greatly appreciated and please excuse my English if it's poor, English is not my first language.

答:
I shortened the variable names and re-wrote this to do what I think you are interested in. I also added display of the addresses the data is stored in.
Generally, when I try to understand something in the arrays and pointers world, I make the simple case work - an embedded array (my yard1) and then do the pointer thing after that (yard2, yard3)
You'll note each set of data has different start points, two add i for each point, one multiplies by i for each point.

```<code>#include <libc.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_DOCKS 100

int main(int argc, char** argv)
{

    struct dock
    {
        int code;
        int length;
    };

    struct yard
    {
        char name[20];
        int numDocks;
        struct dock arDocks[MAX_DOCKS]; //an array of dock structs
    };

    struct yard_2
    {
        char name[20];
        int numDocks;
        struct dock *run; //points to the array of dock structs
    };
</code>```

/* data within main function */

```<code>struct dock *arrayD; // pointer to dock structs
struct yard yard1;
struct yard_2 yard2;
struct yard_2 yard3;

int i;
char temp[] = "2 draY";
strcpy( yard2.name, temp );  /* temp is only persistant in main... */
strcpy( yard1.name, "Yard 1");
strcpy( yard3.name, "3 y 3 a 3 r 3 d 3");
yard1.numDocks = MAX_DOCKS; /* or so I guess.. */
yard2.numDocks = MAX_DOCKS; /* or so I guess.. */
yard3.numDocks = MAX_DOCKS; /* or so I guess.. */

/* get some memory, init it to 0 */
arrayD = calloc( yard2.numDocks, sizeof( struct dock ) );
    /* connect to the yard2 struct via "run", a pointer to struct dock */
yard2.run = arrayD;

/* without middleman... get more memory, init it to 0 */
yard3.run = calloc( yard3.numDocks, sizeof( struct dock ) );

/* at this point arrayD could be re-used to get another hunk.. */
</code>```

/* fill in and display data .. */

```<code>for (i=0;i<yard1.numDocks;i++)
    {
    /* This sets  all the memory for yard 1... */
yard1.arDocks[i].code = 45 + i;
yard1.arDocks[i].length = 668 + i;

/* so here are some ways to display the data */

    printf("%d,    %d    %x   %d   %x   -   ",
       i, yard1.arDocks[i].code, &(yard1.arDocks[i].code),
       (yard1.arDocks[i].length), &(yard1.arDocks[i].length) );

    /* This sets the memory for yard 2... */
yard2.run[i].code = 45 * i;
yard2.run[i].length = 668 * i;

/* Display through a pointer to a calloc'ed array of structs is the
 same syntax as the embedded array of structs. The addresses of the
 array are completely different - 0xbffff704 vs 0x800000  on my Intel-based iMac... */

    printf("%d    %x   %d   %x   -   ",
       yard2.run[i].code, &(yard2.run[i].code),
       yard2.run[i].length, &(yard2.run[i].length) );

yard3.run[i].code = 100 + i;
yard3.run[i].length = 2000 + i;

/* see where second calloc got its memory... */

    printf("%d    %x   %d   %x\n",
       yard3.run[i].code, &(yard3.run[i].code),
       yard3.run[i].length, &(yard3.run[i].length) );
    }
</code>```

/* data all filled in, more demos of how to get it back: */

```<code>printf( "%s,     : 1\n", yard1.name );
printf( "%d,     : numOfDocs \n", yard1.numDocks );
printf( "0x%x,     : arDocks \n", yard1.arDocks );

int elementTest1 = yard1.arDocks[0].length;
int elementTest2 = yard1.arDocks[1].code;
int elementTest3 = yard2.run[0].length;
int elementTest4 = yard3.run[1].code;

printf( "elementTest1:  yard1.arDocks[0].length  %d\n", elementTest1 );
printf( "elementTest2:  yard1.arDocks[1].code  %d\n", elementTest2 );
printf( "elementTest3:  yard2.run[0].length  %d\n", elementTest3 );
printf( "elementTest4:  yard3.run[1].code;  %d\n", elementTest4 );

for (i=0; i< yard2.numDocks; i++ ) {
printf("%d   %d   %d    _   ", i, yard2.run[i].length, yard2.run[i].code);
printf(" %d   %d \n",  yard3.run[i].length, yard3.run[i].code);
}

return (EXIT_SUCCESS);
}
</code>```

Here's an edited example of the output, compile/build via cc, cmd line a.out:

```<code>Macintosh-6:interview Bill4$ cc

dockyard.c Macintosh-6:interview

Bill4$ a.out

0  45  bffff6f8  668 bffff6fc - 0   800000  0   800004 -  100 800400  2000 800404
1  46  bffff700  669 bffff704 - 45  800008  668 80000c -  101 800408  2001 80040c
2  47  bffff708  670 bffff70c - 90  800010 1336 800014 -  102 800410  2002 800414
:
Yard 1,     : 1
100,     : numOfDocs
0xbffff6f8,     : arDocks
elementTest1:  yard1.arDocks[0].length  668
elementTest2:  yard1.arDocks[1].code   46
elementTest3:  yard2.run[0].length  0
elementTest4:  yard3.run[1].code;  101
 0   0   0    _    2000   100
 1   668   45    _    2001   101
 2   1336   90    _    2002   102
 3   2004   135    _    2003   103
 :
 99   66132   4455    _    2099   199

Macintosh-6:interview Bill4$
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to tackle college worksheet on C programming (no marking for it, just to improve our learning). What we're meant to do is get a few details about shipping docks. I decided to use structures for this.

My code is below, what I need help with is to print out the information (to see if its working) of whats at the location of the shipyards .run.

Everything compiles and according to the debugger shipyard1.run and shipyard2.run point to different locations, but I can not see the values.

int main(int argc, char** argv)
{
    typedef struct dockInfo
    {
        int dockCode;
        int dockLength;
    }dckDetails;

    typdef struct shipyard
    {
        char dockName[20];

        /* however big this number is thats how many dockInfo structs are needed.*/

        int numOfDocks;
        dckDetails *run; //points to the array of dockInfo structs

    };

    struct dockInfo *arrayD; // the array to hold all the dockInfo structs
    struct dockInfo tempo; // the temporary dockInfo struct to take in the details
    struct shipyard shipyard1;
    struct shipyard shipyard2;

    /**
    * the variables for shipyard1 and shipyard2 are then assigned
    **/

    int i;
    for (i=0;i<shipyard1.numOfDocks;i++)
    {

    arrayD=calloc(shipyard1.numOfDocks,100); // allocate a new bit of memory for arrayD
    tempo.dockCode=45*i;
    tempo.dockLength=668*i;
    arrayD[i]=tempo; //the element of arrayD becomes tempo.

    }
    shipyard1.run=arrayD; //make shipyard1.run point to the location of arrayD.

    for (i=0;i<shipyard2.numOfDocks;i++)
    {

    arrayD=calloc(shipyard2.numOfDocks,100); // allocate a new bit of memory for arrayD
    tempo.dockCode=1234*i;
    tempo.dockLength=1200*i;
    arrayD[i]=tempo; //the element of arrayD becomes tempo.

    }
    shipyard2.run=arrayD; //make shipyard2.run point to the new location of arrayD.

    int elementTest1; // need element1test to be shipyard1.run[0].dockLength;
    int elementTest2; // need element2test to be shipyard2.run[1].dockCode;

return (EXIT_SUCCESS);
}

It should be noted that I have left a lot of code out because I have yet to write it. I have used static examples for the moment (shipyard1 and shipyard2) but in the future I am going to implment a 'load info from file' feature.

Any help would be greatly appreciated and please excuse my English if it's poor, English is not my first language.

Body:
I shortened the variable names and re-wrote this to do what I think you are interested in. I also added display of the addresses the data is stored in.
Generally, when I try to understand something in the arrays and pointers world, I make the simple case work - an embedded array (my yard1) and then do the pointer thing after that (yard2, yard3)
You'll note each set of data has different start points, two add i for each point, one multiplies by i for each point.

#include <libc.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_DOCKS 100

int main(int argc, char** argv)
{

    struct dock
    {
        int code;
        int length;
    };

    struct yard
    {
        char name[20];
        int numDocks;
        struct dock arDocks[MAX_DOCKS]; //an array of dock structs
    };

    struct yard_2
    {
        char name[20];
        int numDocks;
        struct dock *run; //points to the array of dock structs
    };

/* data within main function */

struct dock *arrayD; // pointer to dock structs
struct yard yard1;
struct yard_2 yard2;
struct yard_2 yard3;

int i;
char temp[] = "2 draY";
strcpy( yard2.name, temp );  /* temp is only persistant in main... */
strcpy( yard1.name, "Yard 1");
strcpy( yard3.name, "3 y 3 a 3 r 3 d 3");
yard1.numDocks = MAX_DOCKS; /* or so I guess.. */
yard2.numDocks = MAX_DOCKS; /* or so I guess.. */
yard3.numDocks = MAX_DOCKS; /* or so I guess.. */

/* get some memory, init it to 0 */
arrayD = calloc( yard2.numDocks, sizeof( struct dock ) );
    /* connect to the yard2 struct via "run", a pointer to struct dock */
yard2.run = arrayD;

/* without middleman... get more memory, init it to 0 */
yard3.run = calloc( yard3.numDocks, sizeof( struct dock ) );

/* at this point arrayD could be re-used to get another hunk.. */

/* fill in and display data .. */

for (i=0;i<yard1.numDocks;i++)
    {
    /* This sets  all the memory for yard 1... */
yard1.arDocks[i].code = 45 + i;
yard1.arDocks[i].length = 668 + i;

/* so here are some ways to display the data */

    printf("%d,    %d    %x   %d   %x   -   ",
       i, yard1.arDocks[i].code, &(yard1.arDocks[i].code),
       (yard1.arDocks[i].length), &(yard1.arDocks[i].length) );

    /* This sets the memory for yard 2... */
yard2.run[i].code = 45 * i;
yard2.run[i].length = 668 * i;

/* Display through a pointer to a calloc'ed array of structs is the
 same syntax as the embedded array of structs. The addresses of the
 array are completely different - 0xbffff704 vs 0x800000  on my Intel-based iMac... */

    printf("%d    %x   %d   %x   -   ",
       yard2.run[i].code, &(yard2.run[i].code),
       yard2.run[i].length, &(yard2.run[i].length) );

yard3.run[i].code = 100 + i;
yard3.run[i].length = 2000 + i;

/* see where second calloc got its memory... */

    printf("%d    %x   %d   %x\n",
       yard3.run[i].code, &(yard3.run[i].code),
       yard3.run[i].length, &(yard3.run[i].length) );
    }

/* data all filled in, more demos of how to get it back: */

printf( "%s,     : 1\n", yard1.name );
printf( "%d,     : numOfDocs \n", yard1.numDocks );
printf( "0x%x,     : arDocks \n", yard1.arDocks );

int elementTest1 = yard1.arDocks[0].length;
int elementTest2 = yard1.arDocks[1].code;
int elementTest3 = yard2.run[0].length;
int elementTest4 = yard3.run[1].code;

printf( "elementTest1:  yard1.arDocks[0].length  %d\n", elementTest1 );
printf( "elementTest2:  yard1.arDocks[1].code  %d\n", elementTest2 );
printf( "elementTest3:  yard2.run[0].length  %d\n", elementTest3 );
printf( "elementTest4:  yard3.run[1].code;  %d\n", elementTest4 );

for (i=0; i< yard2.numDocks; i++ ) {
printf("%d   %d   %d    _   ", i, yard2.run[i].length, yard2.run[i].code);
printf(" %d   %d \n",  yard3.run[i].length, yard3.run[i].code);
}

return (EXIT_SUCCESS);
}

Here's an edited example of the output, compile/build via cc, cmd line a.out:

Macintosh-6:interview Bill4$ cc

dockyard.c Macintosh-6:interview

Bill4$ a.out

0  45  bffff6f8  668 bffff6fc - 0   800000  0   800004 -  100 800400  2000 800404
1  46  bffff700  669 bffff704 - 45  800008  668 80000c -  101 800408  2001 80040c
2  47  bffff708  670 bffff70c - 90  800010 1336 800014 -  102 800410  2002 800414
:
Yard 1,     : 1
100,     : numOfDocs
0xbffff6f8,     : arDocks
elementTest1:  yard1.arDocks[0].length  668
elementTest2:  yard1.arDocks[1].code   46
elementTest3:  yard2.run[0].length  0
elementTest4:  yard3.run[1].code;  101
 0   0   0    _    2000   100
 1   668   45    _    2001   101
 2   1336   90    _    2002   102
 3   2004   135    _    2003   103
 :
 99   66132   4455    _    2099   199

Macintosh-6:interview Bill4$


来源: stackexchange

问:
Border transition on click without javascript
My issue is I need to add a transition of 5sec on the border of a button when we click it without javascript.
Can anyone suggest me an idea</p>

答:
You could do this by transition, or by an animation.
Note that there is no CSS selector like button:click{}, so you have to use the :active css selector, wich has the downside, that you have to hold your click for (in your case) 5s to make the animation work.

If you want an animation on "click" you WILL have to use javascript, I dont think there is any method that uses pure CSS to to the trick here.

#b1 {
  border: 5px solid red;
  transition: border 5s;
}

#b1:active {
  border: 5px solid green;

}

#b2{
  border: 5px solid red;
}

#b2:active{
  animation-duration: 5s;
  animation-name: border_transition;
}

@keyframes border_transition {
  0% {
    border: 5px solid red;
  }
  100% {
    border: 5px solid green;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="b1">CLICK ME</button>
<button id="b2">CLICK ME2</button></code>```

ContentLicense: CC BY-SA 4.0

Body:
You could do this by transition, or by an animation.
Note that there is no CSS selector like button:click{}, so you have to use the :active css selector, wich has the downside, that you have to hold your click for (in your case) 5s to make the animation work.

If you want an animation on "click" you WILL have to use javascript, I dont think there is any method that uses pure CSS to to the trick here.

#b1 {
  border: 5px solid red;
  transition: border 5s;
}

#b1:active {
  border: 5px solid green;

}

#b2{
  border: 5px solid red;
}

#b2:active{
  animation-duration: 5s;
  animation-name: border_transition;
}

@keyframes border_transition {
  0% {
    border: 5px solid red;
  }
  100% {
    border: 5px solid green;
  }
}

<button id="b1">CLICK ME</button>
<button id="b2">CLICK ME2</button>


问:
How can I get only one row if only one column is different
I have a table with patient ID's, contact dates and actioncodes. I want to retrieve all rows with actioncodes equal to EPS or D, however i want to keep only one row if the actioncode exists on the same contactdate.

For example this is part of my table, journal:

```<code>PatientID  Contactdate  Actioncode
1          2010-5-6     EPS
1          2010-5-6     D
1          2012-3-4     CNT
1          2013-7-8     D
2          2010-1-4     EPS
2          2010-5-6     D
</code>```

This is the code i have now to retrieve all rows where actioncode is either EPS or D

```<code>select * from journal j where j.actioncode in ('EPS', 'D')
</code>```

I tried group by contactdate, but then i miss the rows where the patients are different. The same effect occurs with distinct(contactdate). What can i use here to return only one row when the date and the patientid are similar and the actioncode is either D or EPS?

Preferred outcome:

```<code>PatientID   Contactd   Actioncode
1           2010-5-6   D
1           2012-3-4   D
2           2010-1-4   EPS
2           2010-5-6   D
</code>```

答:
You can do it with UNION ALL for the 2 cases:

```<code>select * from journal where actioncode = 'D'
union all
select * from journal j where j.actioncode = 'EPS'
and not exists (
  select 1 from journal
  where PatientID = j.PatientID and Contactdate = j.Contactdate and actioncode = 'D'
)
</code>```

The 2nd query will only fetch rows if the 1st query returns nothing for actioncode = 'D'.

See the demo.

Results:

```<code>> patientid | contactdate | actioncode
> --------: | :---------- | :---------
>         1 | 2010-05-06  | D
>         1 | 2013-07-08  | D
>         2 | 2010-05-06  | D
>         2 | 2010-01-04  | EPS
</code>```

Body:
I have a table with patient ID's, contact dates and actioncodes. I want to retrieve all rows with actioncodes equal to EPS or D, however i want to keep only one row if the actioncode exists on the same contactdate.

For example this is part of my table, journal:

PatientID  Contactdate  Actioncode
1          2010-5-6     EPS
1          2010-5-6     D
1          2012-3-4     CNT
1          2013-7-8     D
2          2010-1-4     EPS
2          2010-5-6     D

This is the code i have now to retrieve all rows where actioncode is either EPS or D

select * from journal j where j.actioncode in ('EPS', 'D')

I tried group by contactdate, but then i miss the rows where the patients are different. The same effect occurs with distinct(contactdate). What can i use here to return only one row when the date and the patientid are similar and the actioncode is either D or EPS?

Preferred outcome:

PatientID   Contactd   Actioncode
1           2010-5-6   D
1           2012-3-4   D
2           2010-1-4   EPS
2           2010-5-6   D

Body:
You can do it with UNION ALL for the 2 cases:

select * from journal where actioncode = 'D'
union all
select * from journal j where j.actioncode = 'EPS'
and not exists (
  select 1 from journal
  where PatientID = j.PatientID and Contactdate = j.Contactdate and actioncode = 'D'
)

The 2nd query will only fetch rows if the 1st query returns nothing for actioncode = 'D'.

See the demo.

Results:

> patientid | contactdate | actioncode
> --------: | :---------- | :---------
>         1 | 2010-05-06  | D
>         1 | 2013-07-08  | D
>         2 | 2010-05-06  | D
>         2 | 2010-01-04  | EPS


问:
Populate bootstrap table with JQuery and JSON
I'm trying to populate my bootstrap table (in Database.Master) with  data (in DatabaseUI.aspx.cs).

How do I dynamically add rows to the table with Jquery?

Do I have to convert my string to JSON?
I think I have to add another JQuery script in the masterpagefile to append data to the table

```<code>$(function() {
$.each(response, function(i, item) {
    var $tr = $('<tr>').append(
        $('<td>').text(item.UID)
    .appendTo('#lblDatabase');
});});
</code>```

but I'm not sure how to pass to get response in the script to read the string in DatabaseUI.

In Database.Master

```<code><form id="form1" runat="server">

    <table class="table" id="lblDatabase">
        <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Pid</th>
            </tr>
         </thead>
        <tbody>
        <tr>
            <td>
                    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                    </asp:ContentPlaceHolder>
                    <asp:Label ID="lblDatabaseValues" runat="server"></asp:Label>
            </td>
        </tr>

        </tbody>
    </table>

</form>
</code>```

Code that gets data from API in DatabaseUI

```<code> protected async void GetRequest(string url)
    {
        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                    Label lblDatabaseValues = (Label)Master.FindControl("lblDatabaseValues");
                    //lblDatabaseValues.Text = "Values:";
                    //lblDatabaseValues.Text = "";
                    string myContent = await content.ReadAsStringAsync();
                    string[] values = myContent.Split(';');
                    for (int i = 0; i < values.Length; i++)
                    {
                        lblDatabaseValues.Text = lblDatabaseValues.Text + Environment.NewLine + values[i];
                    }
                    lblDatabaseValues.Text = lblDatabaseValues.Text.ToString().Replace(Environment.NewLine, "<br />");
                }
                //response.IsSuccessStatusCode
                //response.StatusCode
            }
        }
    }
</code>```

答:
Basically the question is not much clear. If you are asking about how to loop over the received response from backend and append it to your table then here is the code for you.

```<code><table id="tdUIDs">
</table>

var rows = "";
$.each(response,function(i,item){
rows += "<tr><td>" + item.UID + "</td></tr>"; //your rows get printed here
});

$("#tdUIDs").append(rows);
</code>```

I hope this is what you are asking for as am not clear with your question.

Body:
I'm trying to populate my bootstrap table (in Database.Master) with  data (in DatabaseUI.aspx.cs).

How do I dynamically add rows to the table with Jquery?

Do I have to convert my string to JSON?
I think I have to add another JQuery script in the masterpagefile to append data to the table

$(function() {
$.each(response, function(i, item) {
    var $tr = $('
').append(
        $('').text(item.UID)
    .appendTo('#lblDatabase');
});});

but I'm not sure how to pass to get response in the script to read the string in DatabaseUI.

In Database.Master

<form id="form1" runat="server">

              #
              Pid

                    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                    </asp:ContentPlaceHolder>
                    <asp:Label ID="lblDatabaseValues" runat="server"></asp:Label>

</form>

Code that gets data from API in DatabaseUI

 protected async void GetRequest(string url)
    {
        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.GetAsync(url))
            {
                using (HttpContent content = response.Content)
                {
                    Label lblDatabaseValues = (Label)Master.FindControl("lblDatabaseValues");
                    //lblDatabaseValues.Text = "Values:";
                    //lblDatabaseValues.Text = "";
                    string myContent = await content.ReadAsStringAsync();
                    string[] values = myContent.Split(';');
                    for (int i = 0; i < values.Length; i++)
                    {
                        lblDatabaseValues.Text = lblDatabaseValues.Text + Environment.NewLine + values[i];
                    }
                    lblDatabaseValues.Text = lblDatabaseValues.Text.ToString().Replace(Environment.NewLine, "
");
                }
                //response.IsSuccessStatusCode
                //response.StatusCode
            }
        }
    }

Body:
Basically the question is not much clear. If you are asking about how to loop over the received response from backend and append it to your table then here is the code for you.

<table id="tdUIDs">
</table>

var rows = "";
$.each(response,function(i,item){
rows += "<tr><td>" + item.UID + "</td></tr>"; //your rows get printed here
});

$("#tdUIDs").append(rows);

I hope this is what you are asking for as am not clear with your question.


问:
How to position two absolute positioned div's side by side in the mobile device,?
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div></code>```

答:
Just remove the padding and set its top. Note: a fixed width might mess with your layout depending on what you want to do.

#header {
  position: relative;
}

.item {
  position: absolute;
  bottom: 0;
  top: 0;
}

#menu {
  right: auto;
  left: 0;
}

#tab {
  overflow: auto;
  right: 0;
  width: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu" class="item">menu</div>
  <div id="search"></div>
  <div id="tab" class="item">tab</div>
</div></code>```

Body:
I wanna position two absolute div's side by side in the mobile device,
but there is a gap between the two divs.

I want to position them side by side if the size of the mobile device changes(flexible)

Thanks In Advance!

#header {
  position: relative;
}

#menu {
  background-color: green;
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
background-color:pink;
  position: absolute;
  overflow: auto;
  right: 0;
  bottom: 0;
  top: 0;
  z-index: 10;
  padding: 1.2rem;
  width: 70%;
  display: block;
}

menu

tab

Body:
Just remove the padding and set its top. Note: a fixed width might mess with your layout depending on what you want to do.

#header {
  position: relative;
}

.item {
  position: absolute;
  bottom: 0;
  top: 0;
}

#menu {
  right: auto;
  left: 0;
}

#tab {
  overflow: auto;
  right: 0;
  width: 70%;
}

<div class="header">
  <div id="menu" class="item">menu</div>
  <div id="search"></div>
  <div id="tab" class="item">tab</div>
</div>


问:
How to find blank pages inside a PDF using PDFBox?
Here is the challenge I'm currently facing.

I have a lot of PDFs and I have to remove the blank pages inside them and display only the pages with content (text or images).

The problem is that those pdfs are scanned documents.

So the blank pages have some dirty left behind by the scanner.

答:
@Shoyo's code works fine for PDFBox version < 2.0. For future readers, there's no much change but, just in case, here is the code for PDFBOX 2.0+ to make your life easier.

In your main (By main, I mean the place where you are loading your PDF into PDDocument) method:

```<code>try {
    PDDocument document = PDDocument.load(new File("/home/codemantra/Downloads/tetml_ct_access/C.pdf"));
    PDFRenderer renderedDoc = new PDFRenderer(document);
    for (int pageNumber = 0; pageNumber < document.getNumberOfPages(); pageNumber++) {
        if(isBlank(renderedDoc.renderImage(pageNumber))) {
            System.out.println("Blank Page Number : " + pageNumber + 1);
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

And isBlank method will just have BufferedImage passed in:

```<code>private static Boolean isBlank(BufferedImage pageImage) throws IOException {
    BufferedImage bufferedImage = pageImage;
    long count = 0;
    int height = bufferedImage.getHeight();
    int width = bufferedImage.getWidth();
    Double areaFactor = (width * height) * 0.99;

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            Color c = new Color(bufferedImage.getRGB(x, y));
            if (c.getRed() == c.getGreen() && c.getRed() == c.getBlue() && c.getRed() >= 248) {
                count++;
            }
        }
    }
    if (count >= areaFactor) {
        return true;
    }
    return false;
}
</code>```

All the credits goes to @Shoyo

Update:

Some PDFs have "This Page was Intentionally Left Blank" to which the above code considers as blank. If this is your requirement then feel free to use the above code. But, my requirement was only to filter out the pages that were completely blank (No any images present nor consisting of any fonts). So, I ended up using this code (Plus this code runs faster :P) :

```<code>public static void main(String[] args) {
    try {
        PDDocument document = PDDocument.load(new File("/home/codemantra/Downloads/CTP2040.pdf"));
        PDPageTree allPages = document.getPages();
        Integer pageNumber = 1;
        for (PDPage page : allPages) {
            Iterable<COSName> xObjects = page.getResources().getXObjectNames();
            Iterable<COSName> fonts = page.getResources().getFontNames();
            if(xObjects.spliterator().getExactSizeIfKnown() == 0 && fonts.spliterator().getExactSizeIfKnown() == 0) {
                System.out.println(pageNumber);
            }
            pageNumber++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

This will return the page numbers of those pages which are completely blank.

Hope this helps someone! :)

ContentLicense: CC BY-SA 3.0

Body:
@Shoyo's code works fine for PDFBox version < 2.0. For future readers, there's no much change but, just in case, here is the code for PDFBOX 2.0+ to make your life easier.

In your main (By main, I mean the place where you are loading your PDF into PDDocument) method:

try {
    PDDocument document = PDDocument.load(new File("/home/codemantra/Downloads/tetml_ct_access/C.pdf"));
    PDFRenderer renderedDoc = new PDFRenderer(document);
    for (int pageNumber = 0; pageNumber < document.getNumberOfPages(); pageNumber++) {
        if(isBlank(renderedDoc.renderImage(pageNumber))) {
            System.out.println("Blank Page Number : " + pageNumber + 1);
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

And isBlank method will just have BufferedImage passed in:

private static Boolean isBlank(BufferedImage pageImage) throws IOException {
    BufferedImage bufferedImage = pageImage;
    long count = 0;
    int height = bufferedImage.getHeight();
    int width = bufferedImage.getWidth();
    Double areaFactor = (width * height) * 0.99;

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            Color c = new Color(bufferedImage.getRGB(x, y));
            if (c.getRed() == c.getGreen() && c.getRed() == c.getBlue() && c.getRed() >= 248) {
                count++;
            }
        }
    }
    if (count >= areaFactor) {
        return true;
    }
    return false;
}

All the credits goes to @Shoyo

Update:

Some PDFs have "This Page was Intentionally Left Blank" to which the above code considers as blank. If this is your requirement then feel free to use the above code. But, my requirement was only to filter out the pages that were completely blank (No any images present nor consisting of any fonts). So, I ended up using this code (Plus this code runs faster :P) :

public static void main(String[] args) {
    try {
        PDDocument document = PDDocument.load(new File("/home/codemantra/Downloads/CTP2040.pdf"));
        PDPageTree allPages = document.getPages();
        Integer pageNumber = 1;
        for (PDPage page : allPages) {
            Iterable<COSName> xObjects = page.getResources().getXObjectNames();
            Iterable<COSName> fonts = page.getResources().getFontNames();
            if(xObjects.spliterator().getExactSizeIfKnown() == 0 && fonts.spliterator().getExactSizeIfKnown() == 0) {
                System.out.println(pageNumber);
            }
            pageNumber++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This will return the page numbers of those pages which are completely blank.

Hope this helps someone! :)


问:
Advanced constructor for non-contiguous matrices
In my implementations I work a lot with submatrices and blocks of matrices. I am wondering if there is a way in Armadillo that would allow me to extract a block of a larger matrix and use the same memory for this submatrix as for the block within the original matrix. My problem is that I do not know how to go about this as the positions in the original matrix are not contiguous.

Here is one simple example that illustrates what I want to do when my original matrix is A = [A1 A2]:

```<code>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat foo(arma::mat A, arma::uword block_start, arma::uword block_length) {
  arma::uword rows = A.n_rows;
  arma::mat B = arma::mat(A.begin_col(block_start), rows, block_length, false);
// fill B here for illustration;
// in the real piece of code I do various manipulations, multiplications, etc using B
  B.fill(1.0);
  return A;
}

/*** R
A <- matrix(0, 4, 4)
foo(A, 0, 2)
> A <- matrix(0, 4, 4)
> foo(A, 0, 2)
     [,1] [,2] [,3] [,4]
[1,]    1    1    0    0
[2,]    1    1    0    0
[3,]    1    1    0    0
[4,]    1    1    0    0
*/
</code>```

In this case, the positions of the submatrix are contiguous and I can use the advanced constructor to link the memory.

Suppose now that I want the submatrix to be A[1:2, 1:2]. Can I obtain a copy B in Armadillo that uses the same memory as the original elements in A? (Ideally, a solution to this question would also generalize to the case where columns are also non-contiguous, e.g. A[c(1, 3), c(1, 3)].)

Edit: To clarify, I really need the matrix B in the function above to exist on its own. I don't fill it in my real code, but use it (and multiple other submatrices) in various matrix multiplications etc. So what I'm after is a way to create B as a non-contiguous submatrix of A while making sure that they use the same memory.

答:
You can use submatrix views to write to contiguous or non-contiguous memory:

```<code>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat foo(arma::mat A) {
    A.submat(0, 0, 1, 1).fill(1.0);
    return A;
}

// [[Rcpp::export]]
arma::mat bar(arma::mat A) {
    arma::uvec rows;
    rows << 0 << 2;
    arma::uvec cols;
    cols << 0 << 2;
    A.submat(rows, cols).fill(2.0);
    return A;
}

/*** R
A <- matrix(0, 4, 4)
foo(A)
bar(A)
*/
</code>```

Output:

```<code>> A <- matrix(0, 4, 4)

> foo(A)
     [,1] [,2] [,3] [,4]
[1,]    1    1    0    0
[2,]    1    1    0    0
[3,]    0    0    0    0
[4,]    0    0    0    0

> bar(A)
     [,1] [,2] [,3] [,4]
[1,]    2    0    2    0
[2,]    0    0    0    0
[3,]    2    0    2    0
[4,]    0    0    0    0
</code>```

Body:
In my implementations I work a lot with submatrices and blocks of matrices. I am wondering if there is a way in Armadillo that would allow me to extract a block of a larger matrix and use the same memory for this submatrix as for the block within the original matrix. My problem is that I do not know how to go about this as the positions in the original matrix are not contiguous.

Here is one simple example that illustrates what I want to do when my original matrix is A = [A1 A2]:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat foo(arma::mat A, arma::uword block_start, arma::uword block_length) {
  arma::uword rows = A.n_rows;
  arma::mat B = arma::mat(A.begin_col(block_start), rows, block_length, false);
// fill B here for illustration;
// in the real piece of code I do various manipulations, multiplications, etc using B
  B.fill(1.0);
  return A;
}

/*** R
A <- matrix(0, 4, 4)
foo(A, 0, 2)
> A <- matrix(0, 4, 4)
> foo(A, 0, 2)
     [,1] [,2] [,3] [,4]
[1,]    1    1    0    0
[2,]    1    1    0    0
[3,]    1    1    0    0
[4,]    1    1    0    0
*/

In this case, the positions of the submatrix are contiguous and I can use the advanced constructor to link the memory.

Suppose now that I want the submatrix to be A[1:2, 1:2]. Can I obtain a copy B in Armadillo that uses the same memory as the original elements in A? (Ideally, a solution to this question would also generalize to the case where columns are also non-contiguous, e.g. A[c(1, 3), c(1, 3)].)

Edit: To clarify, I really need the matrix B in the function above to exist on its own. I don't fill it in my real code, but use it (and multiple other submatrices) in various matrix multiplications etc. So what I'm after is a way to create B as a non-contiguous submatrix of A while making sure that they use the same memory.

Body:
You can use submatrix views to write to contiguous or non-contiguous memory:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat foo(arma::mat A) {
    A.submat(0, 0, 1, 1).fill(1.0);
    return A;
}

// [[Rcpp::export]]
arma::mat bar(arma::mat A) {
    arma::uvec rows;
    rows << 0 << 2;
    arma::uvec cols;
    cols << 0 << 2;
    A.submat(rows, cols).fill(2.0);
    return A;
}

/*** R
A <- matrix(0, 4, 4)
foo(A)
bar(A)
*/

Output:

> A <- matrix(0, 4, 4)

> foo(A)
     [,1] [,2] [,3] [,4]
[1,]    1    1    0    0
[2,]    1    1    0    0
[3,]    0    0    0    0
[4,]    0    0    0    0

> bar(A)
     [,1] [,2] [,3] [,4]
[1,]    2    0    2    0
[2,]    0    0    0    0
[3,]    2    0    2    0
[4,]    0    0    0    0


问:
JQuery: search and filter a table by a single column
I want to search a table by the values in a single column.

The table looks like this:

```<code>  <table class="table main-content">
<thead>
  <td><b>Title</b></td>
  <td><b>Name</b></td>
  <td><b>State (D)</b></td>
  <td><b>Party</b></td>
  <td><b>Room</b></td>
  <td><b>Phone #</b></td>
  <td><b>Special Role(s)</b></td>
</thead>
<tbody id="congress">

  <tr>
    <td>Senator</td>
    <td><a href="http://www.alexander.senate.gov/">Alexander, Lamar</a></td>
    <td>TN</td>
    <td class="republican">Rep.</td>
    <td>455 Dirksen</td>
    <td>(202) 224-4944</td>
    <td></td>
  </tr>

  <tr>
    <td>Senator</td>
    <td><a href="http://www.barrasso.senate.gov">Barrasso, John</a></td>
    <td>WY</td>
    <td class="republican">Rep.</td>
    <td>307 Dirksen</td>
    <td>(202) 224-6441</td>
    <td></td>
  </tr>
  ...
</code>```

I want to be able to search the table by a given column, say names (index 1) or state (index 2). I've tried jets.js but it only allows one instance per page while I require at least two. JQuery is preferred, JS is fine, and external libs are ok but not optimal.

Cheers!

Edit:

I've tried using the following:

```<code>var $rows = $('#congress tr');

        $('#stateSearch').keyup(function() {

            var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

            $rows.show().filter(function() {
                var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
                return !~text.indexOf(val);
            }).hide();

        });
</code>```

The above code searches all of the columns in the table. How can I adjust it to search only for a specific column? (By index.)

The goal is to hide all of the tr that don't match the query in the given column

答:
try this:</p>

```<code>var text = $(this).find('td:eq(1),td:eq(2)').text().replace(/\s+/g, ' ').toLowerCase();
</code>```

Body:
I want to search a table by the values in a single column.

The table looks like this:

  Title
  Name
  State (D)
  Party
  Room
  Phone #
  Special Role(s)

    Senator
    Alexander, Lamar
    TN
    Rep.
    455 Dirksen
    (202) 224-4944

    Senator
    Barrasso, John
    WY
    Rep.
    307 Dirksen
    (202) 224-6441

  ...

I want to be able to search the table by a given column, say names (index 1) or state (index 2). I've tried jets.js but it only allows one instance per page while I require at least two. JQuery is preferred, JS is fine, and external libs are ok but not optimal.

Cheers!

Edit:

I've tried using the following:

var $rows = $('#congress tr');

        $('#stateSearch').keyup(function() {

            var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

            $rows.show().filter(function() {
                var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
                return !~text.indexOf(val);
            }).hide();

        });

The above code searches all of the columns in the table. How can I adjust it to search only for a specific column? (By index.)

The goal is to hide all of the tr that don't match the query in the given column

Body:
try this:

var text = $(this).find('td:eq(1),td:eq(2)').text().replace(/\s+/g, ' ').toLowerCase();


问:
Can't remove item from aux.Value on list of dictionary
Hey guys i can't remove posição ISBN position ISBN from the new List<Criar_Requisitos>. I have the ISBN on the Book List and saves on the new List<Criar_Requisitos>, im using foreach and ifs. I keep having a error on the second in of foreach, can you guys help?

```<code>foreach (KeyValuePair<int, List<Criar_Requisitos>> aux in Nova_Lista)
{
    foreach (Criar_Requisitos posição in aux.Value)
    {
        if (Introduzir_ISBN == posição.ISBN)
        {
            aux.Value.Remove(posição);
        }
    }
}
</code>```

答:
You can try RemoveAll instead of inner foreach:

```<code>foreach (KeyValuePair<int, List<Criar_Requisitos>> aux in Nova_Lista)
  aux.Value.RemoveAll(posição => posição.ISBN == Introduzir_ISBN);
</code>```

Body:
Hey guys i can't remove posição ISBN position ISBN from the new List<Criar_Requisitos>. I have the ISBN on the Book List and saves on the new List<Criar_Requisitos>, im using foreach and ifs. I keep having a error on the second in of foreach, can you guys help?

foreach (KeyValuePair<int, List<Criar_Requisitos>> aux in Nova_Lista)
{
    foreach (Criar_Requisitos posição in aux.Value)
    {
        if (Introduzir_ISBN == posição.ISBN)
        {
            aux.Value.Remove(posição);
        }
    }
}

Body:
You can try RemoveAll instead of inner foreach:

foreach (KeyValuePair<int, List<Criar_Requisitos>> aux in Nova_Lista)
  aux.Value.RemoveAll(posição => posição.ISBN == Introduzir_ISBN);


问:
Can I share Wiki between the projects?
I have some projects in Azure DevOps in one account.
I want to share Wiki between projects.
Can I share Wiki between projects.If so, please tell me the way.</p>

答:
Can I share Wiki between the projects?

Sorry for any inconvenience.

I am afraid there is no such feature to share wiki between projects directly. Actually the wiki pages store as a md file in the wiki repository, so you could clone the repository in VS directly, then pull and push a md file from one repository to another repository. For more information, you could refer to this link:

Clone and update wiki content offline

I would encourage you to create (or upvote) a UserVoice item:

Note: You can vote and add your comments for this feedback. When there are enough communities vote and add comments for this feedback, the product team member will take this feedback seriously.

Title: Can I share Wiki between the projects?


问:
No string after Escape Sequences '\b'
why print('abcd\b') is abcd Instead of abc

it is working if we put space after \b

```<code>>>> print('abcd\b')
abcd
>>> print('abcd\b ')
abc
</code>```

答: The backspace doesn't delete anything, it moves the cursor to the left and it gets covered up by what you write afterward. You can refer to this question Backspace behavior in Python statement, what is correct behavior of printing a '\b' in code?</p>

Title: No string after Escape Sequences '\b'

Body:
why print('abcd\b') is abcd Instead of abc

it is working if we put space after \b

>>> print('abcd\b')
abcd
>>> print('abcd\b ')
abc


问:
responsive youtube video inside fixed width DIV
I want to make a responsive embeded iframe youtube video inside a fixed width div

OR

Place the video in the center of the screen for desktop with width 750px and height 350 px.

The video in any case should be centered and should be responsive on mobile devices aswell.

Thanks in advance for any help.

答:
I used this code in CSS:

```<code>    @media (max-width: 950px)
        {
    .video-responsive{
    overflow:hidden;
    padding-bottom:56.25%;
    position:relative;
    height:0;
}
.video-responsive iframe{
    left:0;
    top:0;
    height:100%;
    width:100%;
    position:absolute;
}
            }
</code>```

And this in HTML:

```<code><div class="col-xs-12 video-responsive" align="center" style="align-content: center; margin: 0px;"><iframe src="VIDEO URL" width="750" height="350" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div>

      <br clear="all">
</code>```

The video shows at the specified size (750x350px) on computers and it is fully responsive on smaller devices (smartphones, tablets,etc.).

Thanks! :)

PS: this works also when you embed Vimeo videos or any other content.

Body:
I used this code in CSS:

    @media (max-width: 950px)
        {
    .video-responsive{
    overflow:hidden;
    padding-bottom:56.25%;
    position:relative;
    height:0;
}
.video-responsive iframe{
    left:0;
    top:0;
    height:100%;
    width:100%;
    position:absolute;
}
            }

And this in HTML:

<div class="col-xs-12 video-responsive" align="center" style="align-content: center; margin: 0px;"><iframe src="VIDEO URL" width="750" height="350" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div>

      <br clear="all">

The video shows at the specified size (750x350px) on computers and it is fully responsive on smaller devices (smartphones, tablets,etc.).

Thanks! :)

PS: this works also when you embed Vimeo videos or any other content.


答:
Just remove the padding assigned in id tab. and add top : 0.

#header {
  position: relative;
}

#menu {
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
  position: absolute;
  overflow: auto;
  right: 0;
  z-index: 10;
  /*padding: 1.2rem;*/
  width: 70%;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div></code>```

Title: How to position two absolute positioned div's side by side in the mobile device,?

Body:
Just remove the padding assigned in id tab. and add top : 0.

#header {
  position: relative;
}

#menu {
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
  position: absolute;
  overflow: auto;
  right: 0;
  z-index: 10;
  /*padding: 1.2rem;*/
  width: 70%;
  top: 0;
}

<div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div>


答:
All you need to do, is to remove padding and add top 0 for tab class :) and you are done.

#header {
  position: relative;
}

#menu {
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
    position: absolute;
    overflow: auto;
    right: 0;
    top: 0;
    z-index: 10;
    width: 70%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div></code>```

Or See the fiddle : https://jsfiddle.net/6qea1os3/

Body:
All you need to do, is to remove padding and add top 0 for tab class :) and you are done.

#header {
  position: relative;
}

#menu {
  position: absolute;
  right: auto;
  left: 0;
  bottom: 0;
  top: 0;
}

#tab {
    position: absolute;
    overflow: auto;
    right: 0;
    top: 0;
    z-index: 10;
    width: 70%
}

<div class="header">
  <div id="menu">menu</div>
  <div id="search"></div>
  <div id="tab">tab</div>
</div>

Or See the fiddle : https://jsfiddle.net/6qea1os3/


问:
Laravel problem with relation leading zero
I have come across problems with Laravel relations when couple of model ids are identical but another has leading zero and the another has not.

```<code>Product ID | Productname
-----------|------------
012345     | Product A
12345      | Product B
</code>```

If those relations are loaded in the same query, only the first one will be returned and the other will not.

The database columns are strings and in the Product model I have been set the incrementing to false and cast of id attribute to string. Doesn't Laravel's eager loading take leading zeros into account?

I'm not able to change those product ids with leading zeros.

Thanks in advance!

答:
I just run a test on a local laravel installation and I can't reproduce the problem.

Are you sure it is not a problem of the way you structure a query? Because if at any time during your program the $id variable is treated as an integer, the future conversion to string will remove the leading zero.

For example, maybe you get the id from the request:

```<code>$productId = $request->get('product_id');
</code>```

At this point $productId is considered an integer, so if you use productId to  query your DB, the leading zero will be removed.

You need to be sure that during the lifecycle of your request that variable is never converted to integer.

You can test the proper query using tinker, and obtaining your products manually:

```<code>Product::find('012345');
Product::find('12345');
</code>```

Body:
I have come across problems with Laravel relations when couple of model ids are identical but another has leading zero and the another has not.

Product ID | Productname
-----------|------------
012345     | Product A
12345      | Product B

If those relations are loaded in the same query, only the first one will be returned and the other will not.

The database columns are strings and in the Product model I have been set the incrementing to false and cast of id attribute to string. Doesn't Laravel's eager loading take leading zeros into account?

I'm not able to change those product ids with leading zeros.

Thanks in advance!

Body:
I just run a test on a local laravel installation and I can't reproduce the problem.

Are you sure it is not a problem of the way you structure a query? Because if at any time during your program the $id variable is treated as an integer, the future conversion to string will remove the leading zero.

For example, maybe you get the id from the request:

$productId = $request->get('product_id');

At this point $productId is considered an integer, so if you use productId to  query your DB, the leading zero will be removed.

You need to be sure that during the lifecycle of your request that variable is never converted to integer.

You can test the proper query using tinker, and obtaining your products manually:

Product::find('012345');
Product::find('12345');


问:
How to increment value when one of row have NULL value in SQL
I have a table "Total Product" that one of some rows has NULL values for the total product. I'd like to create a query that can increment all value even it is NULL. This is what table

```<code>| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |         100         |
| 18/05/01  |         300         |
| 18/01/01  |        1000         |
</code>```

this what table that i was expected

```<code>| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |        1400         |
| 18/06/01  |        1300         |
| 18/05/01  |        1300         |
| 18/04/01  |        1000         |
| 18/03/01  |        1000         |
| 18/01/01  |        1000         |

</code>```

i already used this query but the result not like i want:

```<code>select
    date,
    sum(total_product_added) over (order by date asc) as total_product,

from
    sold_product

group by
    date,
    total_product
order by
    date_created desc
</code>```

when i have used that query, this is the result:

```<code>| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |        1400         |
| 18/05/01  |        1300         |
| 18/01/01  |        1000         |
</code>```

答:
Use generate_series():

```<code>select gs.dte,
       sum(total_product_added) over (order by gs.dte asc) as total_product
from (select generate_series(min(sp.date), max(sp.date), interval '1 day') as dte
      from sold_product sp
     ) gs left join
     sold_product sp
     on sp.date = gs.dte
order by gs.dte;
</code>```

Here is a db<>fiddle.

Body:
I have a table "Total Product" that one of some rows has NULL values for the total product. I'd like to create a query that can increment all value even it is NULL. This is what table

| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |         100         |
| 18/05/01  |         300         |
| 18/01/01  |        1000         |

this what table that i was expected

| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |        1400         |
| 18/06/01  |        1300         |
| 18/05/01  |        1300         |
| 18/04/01  |        1000         |
| 18/03/01  |        1000         |
| 18/01/01  |        1000         |

i already used this query but the result not like i want:

select
    date,
    sum(total_product_added) over (order by date asc) as total_product,

from
    sold_product

group by
    date,
    total_product
order by
    date_created desc

when i have used that query, this is the result:

| Date      | Total Product Added |
|---------- |-------------------- |
| 18/07/01  |        1400         |
| 18/05/01  |        1300         |
| 18/01/01  |        1000         |

Body:
Use generate_series():

select gs.dte,
       sum(total_product_added) over (order by gs.dte asc) as total_product
from (select generate_series(min(sp.date), max(sp.date), interval '1 day') as dte
      from sold_product sp
     ) gs left join
     sold_product sp
     on sp.date = gs.dte
order by gs.dte;

Here is a db<>fiddle.


答:
Use COALESCE:</p>

```<code>select
    date,
    sum(COALESCE(total_product_added, 0)) over (order by date asc) as total_product,
from
    sold_product
group by
    date,
    total_product
order by
    date_created desc
</code>```

Title: How to increment value when one of row have NULL value in SQL

Body:
Use COALESCE:

select
    date,
    sum(COALESCE(total_product_added, 0)) over (order by date asc) as total_product,
from
    sold_product
group by
    date,
    total_product
order by
    date_created desc


问:
How to make Vue material select box showing option when the default value is empty?
I am using the vuematerial for material design framework under vue.js.

For normal HTML, let say I have a selection box like this:

<select>
    <option value="">You should initially see this</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>```
</div>
</div>
</p>

<p>When you run the script, initially you should see a selection box with the
text "You should initially see this"</p>

<p>However, when I am using vuematerial to do something similar:</p>

```<template>

        <md-field>
          <md-select v-model="movie" name="movie" id="movie">
            <md-option value="">Default film</md-option>
            <md-option value="fight-club">Fight Club</md-option>
            <md-option value="godfather">Godfather</md-option>
            <md-option value="godfather-ii">Godfather II</md-option>
            <md-option value="godfather-iii">Godfather III</md-option>
            <md-option value="godfellas">Godfellas</md-option>
            <md-option value="pulp-fiction">Pulp Fiction</md-option>
            <md-option value="scarface">Scarface</md-option>
          </md-select>
        </md-field>

</template>

```

Demo link

I would expect to see a select box with "Default film" chosen, instead of a blank select box. I noticed that by setting the value of the first option box to be something other then an empty string (e.g. -1) solves the problem, but for my actual case I need the default value to be an empty string, so this workaround is not applicable to me. With that in mind, is there a way I can make the value to be shown initially?

答:
You can use a computed property to determine the final selected result. Set your initial option value and movie variable to a string, such as "default". Then use a computed property to return the final result like so:

Vue.use(VueMaterial.default)
new Vue({
  el: '#app',
  data: {
    movie: 'default'
  },
  computed: {
    selectedMovie() {
      return this.movie === 'default' ? '' : this.movie
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#app {
  padding: 30px;
  margin: 50px 0;
}

#selected {
  padding: 15px;
  background: skyblue;
  color: black;
  margin-top: 30px;
}

.as-console-wrapper {
   height: 0;
}</code>```

<link href="https://unpkg.com/vue-material/dist/theme/default.css" rel="stylesheet"/>
<link href="https://unpkg.com/vue-material/dist/vue-material.min.css" rel="stylesheet"/>

      <md-field>
        <md-select v-model="movie" name="movie" id="movie">
          <md-option value="default">Default film</md-option>
          <md-option value="fight-club">Fight Club</md-option>
          <md-option value="godfather">Godfather</md-option>
          <md-option value="godfather-ii">Godfather II</md-option>
          <md-option value="godfather-iii">Godfather III</md-option>
          <md-option value="godfellas">Godfellas</md-option>
          <md-option value="pulp-fiction">Pulp Fiction</md-option>
          <md-option value="scarface">Scarface</md-option>
        </md-select>
      </md-field>

Selected Movie: {{selectedMovie}}

```

Body:
I am using the vuematerial for material design framework under vue.js.

For normal HTML, let say I have a selection box like this:

<select>
    <option value="">You should initially see this</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

When you run the script, initially you should see a selection box with the
text "You should initially see this"

However, when I am using vuematerial to do something similar:

<template>

        <md-field>
          <md-select v-model="movie" name="movie" id="movie">
            <md-option value="">Default film</md-option>
            <md-option value="fight-club">Fight Club</md-option>
            <md-option value="godfather">Godfather</md-option>
            <md-option value="godfather-ii">Godfather II</md-option>
            <md-option value="godfather-iii">Godfather III</md-option>
            <md-option value="godfellas">Godfellas</md-option>
            <md-option value="pulp-fiction">Pulp Fiction</md-option>
            <md-option value="scarface">Scarface</md-option>
          </md-select>
        </md-field>

</template>

Demo link

I would expect to see a select box with "Default film" chosen, instead of a blank select box. I noticed that by setting the value of the first option box to be something other then an empty string (e.g. -1) solves the problem, but for my actual case I need the default value to be an empty string, so this workaround is not applicable to me. With that in mind, is there a way I can make the value to be shown initially?

Body:
You can use a computed property to determine the final selected result. Set your initial option value and movie variable to a string, such as "default". Then use a computed property to return the final result like so:

Vue.use(VueMaterial.default)
new Vue({
  el: '#app',
  data: {
    movie: 'default'
  },
  computed: {
    selectedMovie() {
      return this.movie === 'default' ? '' : this.movie
    }
  }
})

#app {
  padding: 30px;
  margin: 50px 0;
}

#selected {
  padding: 15px;
  background: skyblue;
  color: black;
  margin-top: 30px;
}

.as-console-wrapper {
   height: 0;
}

<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/vue-material@1.0.0-beta-11/dist/vue-material.min.js"></script>
<link href="https://unpkg.com/vue-material/dist/theme/default.css" rel="stylesheet"/>
<link href="https://unpkg.com/vue-material/dist/vue-material.min.css" rel="stylesheet"/>

<div id="app">
  <div class="md-layout md-gutter">
    <div class="md-layout-item">
      <md-field>
        <md-select v-model="movie" name="movie" id="movie">
          <md-option value="default">Default film</md-option>
          <md-option value="fight-club">Fight Club</md-option>
          <md-option value="godfather">Godfather</md-option>
          <md-option value="godfather-ii">Godfather II</md-option>
          <md-option value="godfather-iii">Godfather III</md-option>
          <md-option value="godfellas">Godfellas</md-option>
          <md-option value="pulp-fiction">Pulp Fiction</md-option>
          <md-option value="scarface">Scarface</md-option>
        </md-select>
      </md-field>
    </div>
  </div>
  <div id="selected">Selected Movie: {{selectedMovie}}</div>
</div>


问:
Bootstrap button inside input-group
How to make it so that it appears nicely after input page with same height?

```<code><div class="input-group">
        <input type="text" class="form-control"/>
        <button class="input-group-addon" type="submit">
            <i class="fa fa-search"></i>
        </button>
</div>
</code>```

Here is code http://jsfiddle.net/6mcxdjdr/ The first one is original input-group, the second one is something what I am trying to have

答:
You can also try this way</p>

```<code> <div class="input-group">
          <input type="text" class="form-control search-input" />
          <span class="input-group-addon">
            <i class="fa fa-search"></i>
          </span><span class="input-group-addon">
            <i class="fa fa-refresh"></i>
          </span>
        </div>

.search-input {
  border-right: 0;
}

.input-group-addon {
  background: white;
  border-left: 0;
  border-right: 0;
}

.input-group-addon:last-child {
  border-left: 0;
  border-right: 1px solid #ccc;
}
</code>```

Title: Bootstrap button inside input-group

Body:
How to make it so that it appears nicely after input page with same height?

        <input type="text" class="form-control"/>
        <button class="input-group-addon" type="submit">

        </button>

Here is code http://jsfiddle.net/6mcxdjdr/ The first one is original input-group, the second one is something what I am trying to have

Body:
You can also try this way

 <div class="input-group">
          <input type="text" class="form-control search-input" />
          <span class="input-group-addon">
            <i class="fa fa-search"></i>
          </span><span class="input-group-addon">
            <i class="fa fa-refresh"></i>
          </span>
        </div>

.search-input {
  border-right: 0;
}

.input-group-addon {
  background: white;
  border-left: 0;
  border-right: 0;
}

.input-group-addon:last-child {
  border-left: 0;
  border-right: 1px solid #ccc;
}


问:
SQLSTATE[HY000] [2002] Connection refused within Laravel homestead
Using Mac OS X and Homestead 2.2.1 with Laravel 5.2.

In terminal (within homestead in my project folder) I can do php artisan to see all the available commands. When I try to run php artisan migrate I get a connection error:

SQLSTATE[HY000] [2002] Connection refused

I have setup a Laravel project with these .env settings

```<code>DB_HOST=127.0.0.1
DB_DATABASE=tcv
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```

I have also tried localhost for DB_HOST and root for DB_USERNAME and DB_PASSWORD. And all possible variations of these put together!

In Sequel Pro (db management application) I CAN connect with these settings

```<code>Host       127.0.0.1
Username   homestead
Password   secret
Database   tcv
Port       33060
</code>```

But this database is obviously empty, because I cant migrate to it from terminal ...

As far as I can make out it is a configuration issue, since I can connect to it with Sequel Pro. But I have honestly no freaking idea what is setup wrong.

Thanks for the help !!

EDIT

For some reason I get the same SQLSTATE[HY000] [2002] Connection refused error when moving my project to MAMP and running php artisan migrate.

Now I am completely lost  ...

答:
For me enclosing the credentials in quotes did the trick</p>

```<code>DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE='zzz'
DB_USERNAME='yyy'
DB_PASSWORD='XXX'
</code>```

Body:
Using Mac OS X and Homestead 2.2.1 with Laravel 5.2.

In terminal (within homestead in my project folder) I can do php artisan to see all the available commands. When I try to run php artisan migrate I get a connection error:

SQLSTATE[HY000] [2002] Connection refused

I have setup a Laravel project with these .env settings

DB_HOST=127.0.0.1
DB_DATABASE=tcv
DB_USERNAME=homestead
DB_PASSWORD=secret

I have also tried localhost for DB_HOST and root for DB_USERNAME and DB_PASSWORD. And all possible variations of these put together!

In Sequel Pro (db management application) I CAN connect with these settings

Host       127.0.0.1
Username   homestead
Password   secret
Database   tcv
Port       33060

But this database is obviously empty, because I cant migrate to it from terminal ...

As far as I can make out it is a configuration issue, since I can connect to it with Sequel Pro. But I have honestly no freaking idea what is setup wrong.

Thanks for the help !!

EDIT

For some reason I get the same SQLSTATE[HY000] [2002] Connection refused error when moving my project to MAMP and running php artisan migrate.

Now I am completely lost  ...

Body:
For me enclosing the credentials in quotes did the trick

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE='zzz'
DB_USERNAME='yyy'
DB_PASSWORD='XXX'


问:
'for' loop terminating before termination condition is met
Edit: Solved

This is a program to rotate an array of size 'n' by 'd' towards the left.
For example: 1 2 3 4 5 6 7 for d=3 goes to 4 5 6 7 1 2 3. My problem is regarding the final loop in int main() that is being used to print the array. That loop is not printing the array upto all it's 'n' members.

I've tried printing the array for a specific 'n' for example n=7. It works in that case. Hence, I don't think there is any logical error in the rotleft() function.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}
```

When I replaced 'n' by 7 in the final loop I got the accurate result, but for general 'n', it shows 4 5 6 instead of 4 5 6 7 1 2 3 (refer to above example).

答:
For dynamically allocated arrays you should use pointers and memory allocation on the heap. Otherwise the variables get assigned random values from memory.

http://www.cplusplus.com/doc/tutorial/dynamic/

```<code>#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int* arr,int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d;

    cin>>n>>d;
    int* arr = new int[n];

    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }

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

Body:
Edit: Solved

This is a program to rotate an array of size 'n' by 'd' towards the left.
For example: 1 2 3 4 5 6 7 for d=3 goes to 4 5 6 7 1 2 3. My problem is regarding the final loop in int main() that is being used to print the array. That loop is not printing the array upto all it's 'n' members.

I've tried printing the array for a specific 'n' for example n=7. It works in that case. Hence, I don't think there is any logical error in the rotleft() function.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

When I replaced 'n' by 7 in the final loop I got the accurate result, but for general 'n', it shows 4 5 6 instead of 4 5 6 7 1 2 3 (refer to above example).

Body:
For dynamically allocated arrays you should use pointers and memory allocation on the heap. Otherwise the variables get assigned random values from memory.

http://www.cplusplus.com/doc/tutorial/dynamic/

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int* arr,int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d;

    cin>>n>>d;
    int* arr = new int[n];

    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }

    delete [] arr;
    return 0;
}


问:
laravel how to display pdf in any page
How can I display a PDF in a Laravel View like I can display a normal image?

The code I am using to implement an image is:

```<code><div class="u-img">
    <img
        src="image/{{ Auth::user()->photo_jpeg }}"
        alt="profile"
    />
</div>
</code>```

What options/HTML-tags can I use to display a PDF?

答:
you could use an iframe</p>

```<code><iframe src="http://example.com/pdf-sample.pdf" id="pdf_display_frame" width="100%" height="500px"></iframe>
</code>```

Title: laravel how to display pdf in any page

Body:
How can I display a PDF in a Laravel View like I can display a normal image?

The code I am using to implement an image is:

    photo_jpeg }}"
        alt="profile"
    />

What options/HTML-tags can I use to display a PDF?

Body:
you could use an iframe

<iframe src="http://example.com/pdf-sample.pdf" id="pdf_display_frame" width="100%" height="500px"></iframe>


问:
How to convert List<String> to Map<String,List<String>> based on a delimeter
I have a List of String like:

```<code>List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");
</code>```

And I want to convert in Map<String, List<String>> as like:

```<code>AU = [5631]
CA = [1326]
US = [5423, 6321]
</code>```

I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.

```<code>List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
        .stream()
        .map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
        .collect(
                Collectors.groupingBy(GeoLocation::getCountry,
                Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
        );

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));
</code>```

GeoLocation.java

```<code>private class GeoLocation {
    private String country;
    private String location;

    public GeoLocation(String country, String location) {
        this.country = country;
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
</code>```

But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.

答:
Seems like your location map needs to be sorted based on keys, you can try the following</p>

```<code>List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");

    Map<String, List<String>> locationMap = locations.stream().map(str -> str.split(":"))
            .collect(() -> new TreeMap<String, List<String>>(), (map, parts) -> {
                if (map.get(parts[0]) == null) {
                    List<String> list = new ArrayList<>();
                    list.add(parts[1]);
                    map.put(parts[0], list);
                } else {
                    map.get(parts[0]).add(parts[1]);
                }
            }, (map1, map2) -> {
                map1.putAll(map2);
            });

    System.out.println(locationMap); // this outputs {AU=[5631], CA=[1326], US=[5423, 6321]}
</code>```

Body:
I have a List of String like:

List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");

And I want to convert in Map<String, List<String>> as like:

AU = [5631]
CA = [1326]
US = [5423, 6321]

I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.

List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
        .stream()
        .map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
        .collect(
                Collectors.groupingBy(GeoLocation::getCountry,
                Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
        );

locationMap.forEach((key, value) -> System.out.println(key + " = " + value));

GeoLocation.java

private class GeoLocation {
    private String country;
    private String location;

    public GeoLocation(String country, String location) {
        this.country = country;
        this.location = location;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

But I want to know, Is there any way to convert List<String> to Map<String, List<String>> without introducing new class.

Body:
Seems like your location map needs to be sorted based on keys, you can try the following

List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");

    Map<String, List<String>> locationMap = locations.stream().map(str -> str.split(":"))
            .collect(() -> new TreeMap<String, List<String>>(), (map, parts) -> {
                if (map.get(parts[0]) == null) {
                    List<String> list = new ArrayList<>();
                    list.add(parts[1]);
                    map.put(parts[0], list);
                } else {
                    map.get(parts[0]).add(parts[1]);
                }
            }, (map1, map2) -> {
                map1.putAll(map2);
            });

    System.out.println(locationMap); // this outputs {AU=[5631], CA=[1326], US=[5423, 6321]}


问:
Error libxml-2.0 not found when installing ggiraph
Trying to install R package ggiraph on my Mac OS X I ran into a problem with dependency xml2.

This seems to be a fairly common problem for users of this and other packages so after reading threads here and elsewhere I confirmed the following:

RStudio, R, and all its packages are up do date

libxml2 is installed in developer version, using homebrew

I have copied libxml-2.0.pc from homebrew folder to /usr/local/lib/pkgconfig/

I have added /usr/local/lib/pkgconfig/ to PATH and PKG_CONFIG_PATH

I still get the below error message during installation. Thankful for help!

```<code>> install.packages("ggiraph")
Installing package into ‘/usr/local/lib/R/3.5/site-library’
(as ‘lib’ is unspecified)
also installing the dependency ‘xml2’

trying URL 'https://cran.rstudio.com/src/contrib/xml2_1.2.0.tar.gz'
Content type 'application/x-gzip' length 251614 bytes (245 KB)
==================================================
downloaded 245 KB

trying URL 'https://cran.rstudio.com/src/contrib/ggiraph_0.6.0.tar.gz'
Content type 'application/x-gzip' length 208710 bytes (203 KB)
==================================================
downloaded 203 KB

* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
Found pkg-config cflags and libs!
Using PKG_CFLAGS=-I/usr/include/libxml2
Using PKG_LIBS=-L/usr/lib -lxml2 -lz -lpthread -licucore -lm
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libxml-2.0 was not found. Try installing:
 * deb: libxml2-dev (Debian, Ubuntu, etc)
 * rpm: libxml2-devel (Fedora, CentOS, RHEL)
 * csw: libxml2_dev (Solaris)
If libxml-2.0 is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libxml-2.0.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘xml2’
* removing ‘/usr/local/lib/R/3.5/site-library/xml2’
Warning in install.packages :
  installation of package ‘xml2’ had non-zero exit status
ERROR: dependency ‘xml2’ is not available for package ‘ggiraph’
* removing ‘/usr/local/lib/R/3.5/site-library/ggiraph’
Warning in install.packages :
  installation of package ‘ggiraph’ had non-zero exit status
</code>```

答:
This is a recurrent problem I have on macOS with Homebrew and libxml2. The includes of libxml2 are located in a subdirectory /path/to/includes/libxml2/libxml/ which can't be found by compilers.

I successfully installed xml2 in R doing two things:

Create symlink [...]/include/libxml pointing to [...]/include/libxml2/libxml

Add the include folder path to INCLUDE_DIR

Do point 1 in a terminal. Although filepath may be different on your installation, the shell command on my mac was:

```<code>Bash > ln -s /usr/local/Cellar/libxml2/2.9.9_2/include/libxml2/libxml /usr/local/Cellar/libxml2/2.9.9_2/include/libxml`
</code>```

Do point 2 in RStudio's R Terminal. The command on my mac was:

```<code>R > Sys.setenv(INCLUDE_DIR = paste("/usr/local/Cellar/libxml2/2.9.9_2/include", Sys.getenv("INCLUDE_DIR"), sep = ":"))`
</code>```

Then install xml2 and ultimately ggiraph:

```<code>R > install.packages(c("xml2", "ggiraph"))
</code>```

Body:
Trying to install R package ggiraph on my Mac OS X I ran into a problem with dependency xml2.

This seems to be a fairly common problem for users of this and other packages so after reading threads here and elsewhere I confirmed the following:

RStudio, R, and all its packages are up do date

libxml2 is installed in developer version, using homebrew

I have copied libxml-2.0.pc from homebrew folder to /usr/local/lib/pkgconfig/

I have added /usr/local/lib/pkgconfig/ to PATH and PKG_CONFIG_PATH

I still get the below error message during installation. Thankful for help!

> install.packages("ggiraph")
Installing package into ‘/usr/local/lib/R/3.5/site-library’
(as ‘lib’ is unspecified)
also installing the dependency ‘xml2’

trying URL 'https://cran.rstudio.com/src/contrib/xml2_1.2.0.tar.gz'
Content type 'application/x-gzip' length 251614 bytes (245 KB)
==================================================
downloaded 245 KB

trying URL 'https://cran.rstudio.com/src/contrib/ggiraph_0.6.0.tar.gz'
Content type 'application/x-gzip' length 208710 bytes (203 KB)
==================================================
downloaded 203 KB

* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
Found pkg-config cflags and libs!
Using PKG_CFLAGS=-I/usr/include/libxml2
Using PKG_LIBS=-L/usr/lib -lxml2 -lz -lpthread -licucore -lm
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libxml-2.0 was not found. Try installing:
 * deb: libxml2-dev (Debian, Ubuntu, etc)
 * rpm: libxml2-devel (Fedora, CentOS, RHEL)
 * csw: libxml2_dev (Solaris)
If libxml-2.0 is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libxml-2.0.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘xml2’
* removing ‘/usr/local/lib/R/3.5/site-library/xml2’
Warning in install.packages :
  installation of package ‘xml2’ had non-zero exit status
ERROR: dependency ‘xml2’ is not available for package ‘ggiraph’
* removing ‘/usr/local/lib/R/3.5/site-library/ggiraph’
Warning in install.packages :
  installation of package ‘ggiraph’ had non-zero exit status

Body:
This is a recurrent problem I have on macOS with Homebrew and libxml2. The includes of libxml2 are located in a subdirectory /path/to/includes/libxml2/libxml/ which can't be found by compilers.

I successfully installed xml2 in R doing two things:

Create symlink [...]/include/libxml pointing to [...]/include/libxml2/libxml

Add the include folder path to INCLUDE_DIR

Do point 1 in a terminal. Although filepath may be different on your installation, the shell command on my mac was:

Bash > ln -s /usr/local/Cellar/libxml2/2.9.9_2/include/libxml2/libxml /usr/local/Cellar/libxml2/2.9.9_2/include/libxml`

Do point 2 in RStudio's R Terminal. The command on my mac was:

R > Sys.setenv(INCLUDE_DIR = paste("/usr/local/Cellar/libxml2/2.9.9_2/include", Sys.getenv("INCLUDE_DIR"), sep = ":"))`

Then install xml2 and ultimately ggiraph:

R > install.packages(c("xml2", "ggiraph"))


问:
Merge two array of objects and added a new Key & Value
I have 2 arrays based on the "Form_Name" key value to merge an array with added new key&value "isChecked".

Array One

```<code>arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true}
{id: 11, Form_Name: "form name Two", isChecked: true}];
</code>```

Array Two

```<code>arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}];
</code>```

Expected merged array

```<code>mergedArray = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}]
</code>```

I tried like below

```<code>const mergedArray = [];
for (let i = 0; i < arrayTwo.length; i++) {
  mergedArray.push({
   ...arrayTwo[i],
   ...(arrayOne.find((itmInner) => itmInner.Form_Name === arrayTwo[i].Form_Name))}
  );
}
console.log('merged array result', mergedArray);
</code>```

答:
Try this if the form_name is in the same order in both arrays.

```<code>arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true},
{id: 11, Form_Name: "form name Two", isChecked: true},
{id: 11, Form_Name: "form name Three", isChecked: true},
{id: 11, Form_Name: "form name Four", isChecked: true}]

arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}]

let mergedArray = []

arrayTwo.forEach( (item,i) => { mergedArray.push(Object.assign({}, item, arrayOne[i]))} )

console.log(mergedArray)
</code>```

Hope it helps !

Body:
I have 2 arrays based on the "Form_Name" key value to merge an array with added new key&value "isChecked".

Array One

arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true}
{id: 11, Form_Name: "form name Two", isChecked: true}];

Array Two

arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}];

Expected merged array

mergedArray = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: true}
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05", isChecked: false}]

I tried like below

const mergedArray = [];
for (let i = 0; i < arrayTwo.length; i++) {
  mergedArray.push({
   ...arrayTwo[i],
   ...(arrayOne.find((itmInner) => itmInner.Form_Name === arrayTwo[i].Form_Name))}
  );
}
console.log('merged array result', mergedArray);

Body:
Try this if the form_name is in the same order in both arrays.

arrayOne = [
{id: 11, Form_Name: "form name One", isChecked: true},
{id: 11, Form_Name: "form name Two", isChecked: true},
{id: 11, Form_Name: "form name Three", isChecked: true},
{id: 11, Form_Name: "form name Four", isChecked: true}]

arrayTwo = [
{Form_Name: "form name One", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Two", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Three", Form_AddDate: "2019-05-15T11:03:18.05"},
{Form_Name: "form name Four", Form_AddDate: "2019-05-15T11:03:18.05"}]

let mergedArray = []

arrayTwo.forEach( (item,i) => { mergedArray.push(Object.assign({}, item, arrayOne[i]))} )

console.log(mergedArray)

Hope it helps !


问:
Extract a part of the filepath (a directory) in Python
I need to extract the name of the parent directory of a certain path. This is what it looks like:

```<code>C:\stuff\directory_i_need\subdir\file.jpg
</code>```

I would like to extract directory_i_need.

答:
All you need is parent part if you use pathlib.

```<code>from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent)
</code>```

Will output:

```<code>C:\Program Files\Internet Explorer
</code>```

Case you need all parts (already covered in other answers) use parts:

```<code>p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts)
</code>```

Then you will get a list:

```<code>('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
</code>```

Saves tone of time.

Body:
I need to extract the name of the parent directory of a certain path. This is what it looks like:

C:\stuff\directory_i_need\subdir\file.jpg

I would like to extract directory_i_need.

Body:
All you need is parent part if you use pathlib.

from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent)

Will output:

C:\Program Files\Internet Explorer

Case you need all parts (already covered in other answers) use parts:

p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts)

Then you will get a list:

('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')

Saves tone of time.


问:
How to stop activity from creating everytime when started from other activity?
I am trying to create a multiple activity app. having activity 1.mainactivity
2.mapsactivity. Now I have a navigation drawer i.e when user click on maps
an intent will be called to map activity. Because of this when the user starts operating in the mapsactivity and onBackpressed he again returns to mainactivity and when he again go to maps the activity starts again. Is there a solution to this problem, How can I run my activity even if navigating to other activity?

"This is a part of mainactivity having nav drawer"

```<code> public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
        } else if (id == R.id.nav_maps) {
            // Maps Activity
            Intent intent = new Intent(getApplicationContext(),AttendanceActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_rider_app) {

       }
</code>```

答:
add this in your Second Activity</p>

```<code> @Override
public void onBackPressed() {
   moveTaskToBack(true);
}
</code>```

Body:
I am trying to create a multiple activity app. having activity 1.mainactivity
2.mapsactivity. Now I have a navigation drawer i.e when user click on maps
an intent will be called to map activity. Because of this when the user starts operating in the mapsactivity and onBackpressed he again returns to mainactivity and when he again go to maps the activity starts again. Is there a solution to this problem, How can I run my activity even if navigating to other activity?

"This is a part of mainactivity having nav drawer"

 public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
        } else if (id == R.id.nav_maps) {
            // Maps Activity
            Intent intent = new Intent(getApplicationContext(),AttendanceActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_rider_app) {

       }

Body:
add this in your Second Activity

 @Override
public void onBackPressed() {
   moveTaskToBack(true);
}


问:
Laravel returning server error 500 on CentOS 7
As the title says, I have a VPS running on CentOS 7, I installed all the requisites for Laravel, PHP 7.3, but it still giving me 'Server Error 500'.

Note that this is a fresh installation of Laravel with composer.

My CentOS version is CentOS Linux release 7.2.1511 (Core)

PHP version is PHP 7.3.6 (cli)

I manually installed all the necessary modules from PHP

What I have already tried

I already did quite a lot of research:

Laravel giving 500 internal error on centos 7 with apache and php 7

I followed what the answer to that questions says and still the same for me.

I did also set up permissions correctly following this other post:

How to set up File Permissions for Laravel 5 (and others)

Also these ones

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

https://www.ionos.com/community/server-cloud-infrastructure/apache/how-to-fix-http-error-code-500-internal-server-error/

And a bunch of more articles I read on another websites.

These are the permissions for the project folder:

drwxr-xr-x 13 apache apache 4096 May 31 05:23 laravel

And for storage:

drwxr-xr-x  5 apache apache   4096 May 31 04:44 storage

Tried generating the key and got this:

```<code>[root@server laravel]# php artisan key:generate

   ErrorException  : file_get_contents(/var/www/laravel/.env): failed to open stream: No such file or directory

  at /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96
     92|     {
     93|         file_put_contents($this->laravel->environmentFilePath(), preg_replace(
     94|             $this->keyReplacementPattern(),
     95|             'APP_KEY='.$key,
  >  96|             file_get_contents($this->laravel->environmentFilePath())
     97|         ));
     98|     }
     99|
    100|     /**

  Exception trace:

  1   file_get_contents("/var/www/laravel/.env")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96

  2   Illuminate\Foundation\Console\KeyGenerateCommand::writeNewEnvironmentFileWith("base64:soTdeaCmsY1ELnpJLCcYkBJjY6SWiLYwY+Mvoxl9wOw=")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:80

  Please use the argument -v to see more details.
[root@server laravel]#

</code>```

答: Did you created the var/www/laravel/.env file from your var/www/laravel/.env.example file?

Body:
As the title says, I have a VPS running on CentOS 7, I installed all the requisites for Laravel, PHP 7.3, but it still giving me 'Server Error 500'.

Note that this is a fresh installation of Laravel with composer.

My CentOS version is CentOS Linux release 7.2.1511 (Core)

PHP version is PHP 7.3.6 (cli)

I manually installed all the necessary modules from PHP

What I have already tried

I already did quite a lot of research:

Laravel giving 500 internal error on centos 7 with apache and php 7

I followed what the answer to that questions says and still the same for me.

I did also set up permissions correctly following this other post:

How to set up File Permissions for Laravel 5 (and others)

Also these ones

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

https://www.ionos.com/community/server-cloud-infrastructure/apache/how-to-fix-http-error-code-500-internal-server-error/

And a bunch of more articles I read on another websites.

These are the permissions for the project folder:

drwxr-xr-x 13 apache apache 4096 May 31 05:23 laravel

And for storage:

drwxr-xr-x  5 apache apache   4096 May 31 04:44 storage

Tried generating the key and got this:

[root@server laravel]# php artisan key:generate

   ErrorException  : file_get_contents(/var/www/laravel/.env): failed to open stream: No such file or directory

  at /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96
     92|     {
     93|         file_put_contents($this->laravel->environmentFilePath(), preg_replace(
     94|             $this->keyReplacementPattern(),
     95|             'APP_KEY='.$key,
  >  96|             file_get_contents($this->laravel->environmentFilePath())
     97|         ));
     98|     }
     99|
    100|     /**

  Exception trace:

  1   file_get_contents("/var/www/laravel/.env")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96

  2   Illuminate\Foundation\Console\KeyGenerateCommand::writeNewEnvironmentFileWith("base64:soTdeaCmsY1ELnpJLCcYkBJjY6SWiLYwY+Mvoxl9wOw=")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:80

  Please use the argument -v to see more details.
[root@server laravel]#


问:
Is there any way to add an iVar that's not in the header file (not using LLVM 2.0 or later) in Objective-C?
I recently learned that you can add ivar in a class extension with LLVM2.0. (gcc can't do this)
This is somehow really private iVar because other users don't it's existence since it's not in the header file.
like:

```<code>//SomeClass.h
@interface SomeClass : NSObject {

}
@end

//SomeClass.m
@interface SomeClass ()
{
    NSString *reallyPrivateString;
}
@end

@implementation SomeClass

@end
</code>```

But this does rely on the compiler. Is there any other way to declare an ivar that's not in the header file?

答:
If you are implementing a library and want to hide your instance variables take a look at what Apple does in the interface for UIWebView. They have an internal webview that does not expose a header file.</p>

```<code>@class UIWebViewInternal;
@protocol UIWebViewDelegate;

UIKIT_CLASS_AVAILABLE(2_0) @interface UIWebView : UIView <NSCoding, UIScrollViewDelegate> {
 @private
    UIWebViewInternal *_internal;
}
</code>```

Body:
I recently learned that you can add ivar in a class extension with LLVM2.0. (gcc can't do this)
This is somehow really private iVar because other users don't it's existence since it's not in the header file.
like:

//SomeClass.h
@interface SomeClass : NSObject {

}
@end

//SomeClass.m
@interface SomeClass ()
{
    NSString *reallyPrivateString;
}
@end

@implementation SomeClass

@end

But this does rely on the compiler. Is there any other way to declare an ivar that's not in the header file?

Body:
If you are implementing a library and want to hide your instance variables take a look at what Apple does in the interface for UIWebView. They have an internal webview that does not expose a header file.

@class UIWebViewInternal;
@protocol UIWebViewDelegate;

UIKIT_CLASS_AVAILABLE(2_0) @interface UIWebView : UIView <NSCoding, UIScrollViewDelegate> {
 @private
    UIWebViewInternal *_internal;
}


问:
Rownum between clause not working - Oracle
I have a table:

table1

```<code>user_id
1
2
3
4
</code>```

When I run this query:

```<code>SELECT
rownum, user_id
FROM
table1 where rownum between 1 and 4;
</code>```

But when I run, it does not work:

```<code>SELECT
rownum, user_id
FROM
table1 where rownum between 2 and 4;
</code>```

What am I doing wrong?

答:
The first row to return has number 1.

This doesn't match the criterion so it will not be returned.

The same criterion applies for each row.

Therefore, no rows will be returned.

Body:
I have a table:

table1

user_id
1
2
3
4

When I run this query:

SELECT
rownum, user_id
FROM
table1 where rownum between 1 and 4;

But when I run, it does not work:

SELECT
rownum, user_id
FROM
table1 where rownum between 2 and 4;

What am I doing wrong?