问:
Compression to Improve Hard Disk Write Performance
On a modern system can local hard disk write speeds be improved by compressing the output stream?

This question derives from a case I'm working with where a program serially generates and dumps around 1-2GB of text logging data to a raw text file on the hard disk and I think it is IO bound. Would I expect to be able to decrease runtimes by compressing the data before it goes to disk or would the overhead of compression eat up any gain I could get? Would having an idle second core affect this?

I know this would be affected by how much CPU is being used to generate the data so rules of thumb on how much idle CPU time would be needed would be good.

I recall a video talk where someone used compression to improve read speeds for a database but IIRC compressing is a lot more CPU intensive than decompressing.

答: If it's just text, then compression could definitely help. Just choose an compression algorithm and settings that make the compression cheap. "gzip" is cheaper than "bzip2" and both have parameters that you can tweak to favor speed or compression ratio.</p>

OwnerDisplayName: BCS

LastEditorDisplayName: BCS

OwnerDisplayName: saua


来源: stackexchange

问:
How do I pass variable inside find and bash -c?
I have issues with passing variable to %exe part of the code.

Here is my working code that I use inside bash script:

```<code>## Function
targz() {
  find $1 -type f -name "*.$2" -exec \
    bash -c 'old=$(basename {}); new=${old/%exe/tar\.gz}; \
      tar -zcvf $new $old; ' \;
}

## Function Call
## targz [directory] [extension]
targz . 'exe';
</code>```

and yes I've tried using it some thing like this:

```<code>new=${old/%$2/tar\.gz};
</code>```

but it generates filenames like: file.exetar.gz .

答:
Try:

```<code>targz() {
  find $1 -type f -name "*.$2" -exec \
    bash -c 'old=$(basename {}); new=${old/'"$2"'/tar\.gz}; \
      tar -zcvf $new $old; ' \;
}
</code>```

The trick is to get out of the single quote, so that variable expansion will be performed.

ContentLicense: CC BY-SA 4.0

Body:
I have issues with passing variable to %exe part of the code.

Here is my working code that I use inside bash script:

## Function
targz() {
  find $1 -type f -name "*.$2" -exec \
    bash -c 'old=$(basename {}); new=${old/%exe/tar\.gz}; \
      tar -zcvf $new $old; ' \;
}

## Function Call
## targz [directory] [extension]
targz . 'exe';

and yes I've tried using it some thing like this:

new=${old/%$2/tar\.gz};

but it generates filenames like: file.exetar.gz .

Body:
Try:

targz() {
  find $1 -type f -name "*.$2" -exec \
    bash -c 'old=$(basename {}); new=${old/'"$2"'/tar\.gz}; \
      tar -zcvf $new $old; ' \;
}

The trick is to get out of the single quote, so that variable expansion will be performed.

ContentLicense: CC BY-SA 2.5


问:
How to store the full HTML table in JTable after parsing with JSoup?
I want to load the table from http://www.espn.com/nba/hollinger/teamstats into a JTable. After parsing the table with JSoup, I managed to load the table header, but I have problem to load the data rows. First I tried only the odd rows, but JSoup loaded only the last odd row, I don't know how to load all of them.
I tried to load from the first row using .first(), but then loaded only the first row, nothing else.
Here is my code:

```<code>Document doc = null;
try {
  doc = Jsoup.connect("http://www.espn.com/nba/hollinger/teamstats").get();
} catch (IOException e) {
    e.printStackTrace();
}
String [][] data = new String[30][12];
String [] header = new String[12];
for (Element table : doc.select("table.tablehead .colhead")) {
    for (Element row : table.select("tr")) {
        Elements tds = row.select("td");
        for (int i=0;i<12;i++) {
            header[i]=tds.get(i).text();
        }
    }
}
for (Element table : doc.select("table.tablehead .oddRow")) {
    for (int j=0;j<15;j++) {
        for (Element row : table.select("tr")) {
            for (int i=0;i<12;i++) {
                Elements tds = row.select("td");
                data[j][i]=tds.get(i).text();
            }
        }
    }
}
</code>```

The HTML table has 30 data rows, I want to load all of them into my JTable.
How to modify my code? Thanks for the help!

答:
It looks like you are ocercomplicating things. To get text from headers

select table row
 holding header data

iterate over its table data

get their text()

store it in array

For data

select all rows from table except first two since they are used for info and header (:gt(1) selector can be helpful here :gt(n): find elements whose sibling index is greater than n since we want to get tr siblings starting at indexes 2,3,4,... in other words greater than 1)

repeat what you did for headers but resulting array store as rows of 2D String array

Code:

```<code>Document doc = Jsoup.connect("http://www.espn.com/nba/hollinger/teamstats").get();

//headers: pick specific row, get its td, convert them to text() store as array
String[] headers = doc.select("table.tablehead tr.colhead td")
                      .stream()
                      .map(Element::text)
                      .toArray(String[]::new);

System.out.println(Arrays.toString(headers));

//data: select rows with data, convert row to array, hold each row array in 2D array
String[][] data = doc.select("table.tablehead tr:gt(1)")
                     .stream()
                     .map(row -> row.select("td")
                                    .stream()
                                    .map(Element::text)
                                    .toArray(String[]::new)
                      ).toArray(String[][]::new);

System.out.println("----");
for (String[] row : data){
    System.out.println(Arrays.toString(row));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to load the table from http://www.espn.com/nba/hollinger/teamstats into a JTable. After parsing the table with JSoup, I managed to load the table header, but I have problem to load the data rows. First I tried only the odd rows, but JSoup loaded only the last odd row, I don't know how to load all of them.
I tried to load from the first row using .first(), but then loaded only the first row, nothing else.
Here is my code:

Document doc = null;
try {
  doc = Jsoup.connect("http://www.espn.com/nba/hollinger/teamstats").get();
} catch (IOException e) {
    e.printStackTrace();
}
String [][] data = new String[30][12];
String [] header = new String[12];
for (Element table : doc.select("table.tablehead .colhead")) {
    for (Element row : table.select("tr")) {
        Elements tds = row.select("td");
        for (int i=0;i<12;i++) {
            header[i]=tds.get(i).text();
        }
    }
}
for (Element table : doc.select("table.tablehead .oddRow")) {
    for (int j=0;j<15;j++) {
        for (Element row : table.select("tr")) {
            for (int i=0;i<12;i++) {
                Elements tds = row.select("td");
                data[j][i]=tds.get(i).text();
            }
        }
    }
}

The HTML table has 30 data rows, I want to load all of them into my JTable.
How to modify my code? Thanks for the help!

Body:
It looks like you are ocercomplicating things. To get text from headers

select table row <tr> holding header data

iterate over its table data <td>

get their text()

store it in array

For data

select all rows from table except first two since they are used for info and header (:gt(1) selector can be helpful here :gt(n): find elements whose sibling index is greater than n since we want to get tr siblings starting at indexes 2,3,4,... in other words greater than 1)

repeat what you did for headers but resulting array store as rows of 2D String array

Code:

Document doc = Jsoup.connect("http://www.espn.com/nba/hollinger/teamstats").get();

//headers: pick specific row, get its td, convert them to text() store as array
String[] headers = doc.select("table.tablehead tr.colhead td")
                      .stream()
                      .map(Element::text)
                      .toArray(String[]::new);

System.out.println(Arrays.toString(headers));

//data: select rows with data, convert row to array, hold each row array in 2D array
String[][] data = doc.select("table.tablehead tr:gt(1)")
                     .stream()
                     .map(row -> row.select("td")
                                    .stream()
                                    .map(Element::text)
                                    .toArray(String[]::new)
                      ).toArray(String[][]::new);

System.out.println("----");
for (String[] row : data){
    System.out.println(Arrays.toString(row));
}


问:
Identity Aware Proxy(IAP) in GCP
I was learning about IAP in GCP, which is used for authentication and authorization to GCP hosted apps.

Thoughts

Even before IAP was introduced in GCP, users could be authenticated and authorized using login credentials and google IAM policies.

Okay, IAP replaces VPN, users can work from untrusted networks.

Query

Please correct me if i am thinking wrong.

But if my app./resource is hosted in GCP, than it is accessible publicly with proper authentication and authorization, there is obviously no need of VPN. In this scenario, what is the significance of IAP.

What is the new thing in IAP, as IAP also does the same thing for authentication and authorization?

答:
You wouldn't technically need IAP if you've already got an app which is secured with proper authentication and authorization, though it still may be desirable. One reason is that IAP gives you the ability to configure individual access outside of your application, rather than needing to control ACLs internally in your app's code. The App Engine IAP quickstart has a good overview of how IAP config works for securing an app.

You can think of IAP as filling the role of a VPN while also giving you the flexibility of OAuth. It is mainly targeted towards perimeter security which is traditionally accomplished by using firewalls and VPNs to secure privileged network resources like intranets which are hosted on premises. IAP allows you to set up a cloud-hosted intranet in much the same way as you'd do on-premises, with access control handled at the perimeter by IAP. This is explained very well in the Google research paper "BeyondCorp - A New Approach to Enterprise Security".

Title: Identity Aware Proxy(IAP) in GCP


问:
Unexplainable difference between same html/css code on jsfiddle and codepen
I have the same html / css code but the output only works on codepen and not on jsfiddle. How come?

html

```<code><div class="spring">
  <div class="text">These are words</div>
  <div class="sect sect1">
    <div class="text">written down</div>
    <div class="sect sect2">
      <div class="text">and</div>
      <div class="sect sect3">
        <div class="text">even further down.</div>
      </div>
    </div>
  </div>
</div>
</code>```

css

```<code>@import url('https://fonts.googleapis.com/css?family=PT+Sans');

body {
  perspective: 100000px;
  transform-style: preserve-3d;
  font-size:2em;
  font-family:"PT Sans",sans-serif;
  text-align:center;
  color:#4a4a4a;
  background-color:#eee;
  box-sizing:border-box;
}

.spring {
  padding:1em 2em;
  margin-top:2em;
  background-color:#4a4a4a;
  color:#fff;
  border-radius:3px;
  display:inline-block;
  transform: rotateX(50deg) rotateY(-22.5deg);
  transform-style: preserve-3d;
  transition:0.4s all;

  &:hover {
    transform: rotateX(40deg) rotateY(-10.5deg);
  }

  .text {
    transform:scaleY(1.5);
  }

  .sect {
    position:absolute;
    display:block;
    border:4px solid #4a4a4a;
    top:0;
    transform-style: preserve-3d;
    border-radius:3px;
  }

  .sect1 {
    background-color:#fff;
    color:#4a4a4a;
    border:4px solid #4a4a4a;
    transform:rotateY(30deg);
    transform-origin:0 0;
    left:0;
    padding:1em 1em 1em 3em;
  }

  .sect2 {
    background-color:#4a4a4a;
    color:#fff;
    transform:rotateY(-30deg);
    transform-origin:100% 0;
    right:0;
    padding:1em 3em 1em 1em;
  }

  .sect3 {
    background-color:#fff;
    color:#4a4a4a;
    border:3px solid #4a4a4a;
    transform:rotateY(30deg);
    transform-origin:0 0;
    left:0;
    width:300px;
    padding:1em 1em 1em 3em;
  }
}
</code>```

The jsfiddle: https://jsfiddle.net/snaL0cj8/5/

The codepen: http://codepen.io/stephenjbell/pen/BWvgXw

答:
Thats because the css setting in jsfiddle is set to css wheras it need to be scss .

Click on the Setting option in the css section and from the dropdown for Language select SCSS in jsfiddle and that does the trick

See this fiddle: https://jsfiddle.net/seofbrse/

Body:
I have the same html / css code but the output only works on codepen and not on jsfiddle. How come?

html

These are words

written down

and

even further down.

css

@import url('https://fonts.googleapis.com/css?family=PT+Sans');

body {
  perspective: 100000px;
  transform-style: preserve-3d;
  font-size:2em;
  font-family:"PT Sans",sans-serif;
  text-align:center;
  color:#4a4a4a;
  background-color:#eee;
  box-sizing:border-box;
}

.spring {
  padding:1em 2em;
  margin-top:2em;
  background-color:#4a4a4a;
  color:#fff;
  border-radius:3px;
  display:inline-block;
  transform: rotateX(50deg) rotateY(-22.5deg);
  transform-style: preserve-3d;
  transition:0.4s all;

  &:hover {
    transform: rotateX(40deg) rotateY(-10.5deg);
  }

  .text {
    transform:scaleY(1.5);
  }

  .sect {
    position:absolute;
    display:block;
    border:4px solid #4a4a4a;
    top:0;
    transform-style: preserve-3d;
    border-radius:3px;
  }

  .sect1 {
    background-color:#fff;
    color:#4a4a4a;
    border:4px solid #4a4a4a;
    transform:rotateY(30deg);
    transform-origin:0 0;
    left:0;
    padding:1em 1em 1em 3em;
  }

  .sect2 {
    background-color:#4a4a4a;
    color:#fff;
    transform:rotateY(-30deg);
    transform-origin:100% 0;
    right:0;
    padding:1em 3em 1em 1em;
  }

  .sect3 {
    background-color:#fff;
    color:#4a4a4a;
    border:3px solid #4a4a4a;
    transform:rotateY(30deg);
    transform-origin:0 0;
    left:0;
    width:300px;
    padding:1em 1em 1em 3em;
  }
}

The jsfiddle: https://jsfiddle.net/snaL0cj8/5/

The codepen: http://codepen.io/stephenjbell/pen/BWvgXw


问:
put page number when create PDF with iTextSharp
I'm working with ASP MVC and i use iTextSharp to generate PDF's in my application. But now i have a problem: I printing lists and when exist more than one page, i want to show the page number (ex.: Page 1 to 4). I found some examples, but i think it is more complexes than i need to do (like exameple).

EDIT:
I found this example 2. I can count number of pages, but i cant print the number in pages.

What i did:

```<code>public ActionResult downloadListaISCC(DateTime? DataFimFiltro)
{

//Code to generate list to PDF

   //My document
   Document doc1 = new Document();
   doc1.SetPageSize(iTextSharp.text.PageSize.A4);
   doc1.SetMargins(0f, 0f, 0f, 0f);
   doc1.NewPage();

   MemoryStream pdfStream = new MemoryStream();
   PdfWriter pdfWriter = PdfWriter.GetInstance(doc1, pdfStream);

   //Code to create table
   doc1.Add(table); //table list in document

   //Follow the example 2 (link)
   pdfWriter.CloseStream = true;
   doc1.Close();

   //E fui seguindo o exemplo do segundo link
   string file = "D:/gerarPDFOleotorres/"+ nomeDoc +"";

   // add page numbers
   Document copyDoc = new Document();
   PdfCopy copyPdf = new PdfCopy(copyDoc, new FileStream(file, FileMode.Create));
   copyPdf.SetPageSize(PageSize.A4.Rotate());
   copyDoc.Open();

   // read the initial pdf document
   PdfReader reader = new PdfReader(pdfStream.ToArray());
   int totalPages = reader.NumberOfPages;

   PdfImportedPage copiedPage = null;
   iTextSharp.text.pdf.PdfCopy.PageStamp stamper = null;

   for (int i = 0; i < totalPages; i++)
   {

       // get the page and create a stamper for that page
       copiedPage = copyPdf.GetImportedPage(reader, (i + 1));
       stamper = copyPdf.CreatePageStamp(copiedPage);

       // add a page number to the page
       ColumnText.ShowTextAligned(stamper.GetUnderContent(), Element.ALIGN_CENTER, new Phrase((i + 1) + "/" + totalPages, fontetexto), 820f, 15, 0);
        stamper.AlterContents();

       // add the altered page to the new document
       copyPdf.AddPage(copiedPage);
   }

   copyDoc.Close();
   reader.Close();

   // flush and clear the document from memory
   pdfStream.Flush();
   pdfStream.Close();
    }
</code>```

答:
For the records - I used this way

```<code>byte[] bytes = memoryStream.ToArray();

                //Save pdf in the temporary location.
System.IO.File.WriteAllBytes(Server.MapPath("~/TempReports/") + lbReports.Text + "_JEA.pdf", bytes);

/*This is a page counter - it stamps the number of pages in the document.
 It will read dynamically the 'document' that was just closed above [document.Close();] from the location,
 then in memory will write the new content plus the one from [byte[] bytes = memoryStream.ToArray();]
 Solution has been applied from: https://www.aspsnippets.com/Articles/iTextSharp-Add-Page-numbers-to-existing-PDF-using-C-and-VBNet.aspx
 */
try
{
    File.ReadAllBytes(Server.MapPath("~/TempReports/") + lbReports.Text + "_JEA.pdf");
    iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
    using (MemoryStream stream = new MemoryStream())
    {
        PdfReader reader = new PdfReader(bytes);
        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            int pages = reader.NumberOfPages;
            for (int i = 1; i <= pages; i++)
            {
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i),
                 @Element.ALIGN_LEFT, new Phrase(lbReports.Text + " - HD - JEA", blackFont), 63f, 24f, 0);

                ColumnText.ShowTextAligned(stamper.GetUnderContent(i),
                @Element.ALIGN_CENTER, new Phrase("Page " + i.ToString() + " of " + pages, blackFont), 300f, 24f, 0);

                ColumnText.ShowTextAligned(stamper.GetUnderContent(i),
                @Element.ALIGN_RIGHT, new Phrase("" + DateTime.Now, blackFont), 549f, 24f, 0);
            }

            txConnection.Text = "This report contains " + pages + " page(s)";
        }

        bytes = stream.ToArray();

    }//End of page counter

    /*System.IO.File.WriteAllBytes will write all bytes to file again*/

    System.IO.File.WriteAllBytes(Server.MapPath("~/TempReports/") + lbReports.Text + "_JEA.pdf", bytes);

    // Temporary path that is used to display the pdf in the embed.
    System.IO.File.WriteAllBytes(Server.MapPath("~/TempReports/ReportsEmbed/") + lbReports.Text + "_JEA.pdf", bytes);

    /*this is what sends the PDF to the embed viewer object
     The ltEmbed is what receives the plugin to dispplay the file*/

    string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"698px\" height=\"450px\">";
    embed += "If you are unable to view file, you can download it from <a href = \"{0}\">here</a>";
    embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view it.";
    embed += "</object>";

    ltEmbed.Text = string.Format(embed, ("http://localhost:65423/TempReports/ReportsEmbed/") + lbReports.Text + "_JEA.pdf");
    memoryStream.Close();

    this.Context.ApplicationInstance.CompleteRequest();
}
catch (DocumentException exe)
{
    txConnection.Text = "There has been an error generating the file. Please try again. Error: " + exe;
}
</code>```

Body:
I'm working with ASP MVC and i use iTextSharp to generate PDF's in my application. But now i have a problem: I printing lists and when exist more than one page, i want to show the page number (ex.: Page 1 to 4). I found some examples, but i think it is more complexes than i need to do (like exameple).

EDIT:
I found this example 2. I can count number of pages, but i cant print the number in pages.

What i did:

public ActionResult downloadListaISCC(DateTime? DataFimFiltro)
{

//Code to generate list to PDF

   //My document
   Document doc1 = new Document();
   doc1.SetPageSize(iTextSharp.text.PageSize.A4);
   doc1.SetMargins(0f, 0f, 0f, 0f);
   doc1.NewPage();

   MemoryStream pdfStream = new MemoryStream();
   PdfWriter pdfWriter = PdfWriter.GetInstance(doc1, pdfStream);

   //Code to create table
   doc1.Add(table); //table list in document

   //Follow the example 2 (link)
   pdfWriter.CloseStream = true;
   doc1.Close();

   //E fui seguindo o exemplo do segundo link
   string file = "D:/gerarPDFOleotorres/"+ nomeDoc +"";

   // add page numbers
   Document copyDoc = new Document();
   PdfCopy copyPdf = new PdfCopy(copyDoc, new FileStream(file, FileMode.Create));
   copyPdf.SetPageSize(PageSize.A4.Rotate());
   copyDoc.Open();

   // read the initial pdf document
   PdfReader reader = new PdfReader(pdfStream.ToArray());
   int totalPages = reader.NumberOfPages;

   PdfImportedPage copiedPage = null;
   iTextSharp.text.pdf.PdfCopy.PageStamp stamper = null;

   for (int i = 0; i < totalPages; i++)
   {

       // get the page and create a stamper for that page
       copiedPage = copyPdf.GetImportedPage(reader, (i + 1));
       stamper = copyPdf.CreatePageStamp(copiedPage);

       // add a page number to the page
       ColumnText.ShowTextAligned(stamper.GetUnderContent(), Element.ALIGN_CENTER, new Phrase((i + 1) + "/" + totalPages, fontetexto), 820f, 15, 0);
        stamper.AlterContents();

       // add the altered page to the new document
       copyPdf.AddPage(copiedPage);
   }

   copyDoc.Close();
   reader.Close();

   // flush and clear the document from memory
   pdfStream.Flush();
   pdfStream.Close();
    }

Body:
For the records - I used this way

byte[] bytes = memoryStream.ToArray();

                //Save pdf in the temporary location.
System.IO.File.WriteAllBytes(Server.MapPath("~/TempReports/") + lbReports.Text + "_JEA.pdf", bytes);

/*This is a page counter - it stamps the number of pages in the document.
 It will read dynamically the 'document' that was just closed above [document.Close();] from the location,
 then in memory will write the new content plus the one from [byte[] bytes = memoryStream.ToArray();]
 Solution has been applied from: https://www.aspsnippets.com/Articles/iTextSharp-Add-Page-numbers-to-existing-PDF-using-C-and-VBNet.aspx
 */
try
{
    File.ReadAllBytes(Server.MapPath("~/TempReports/") + lbReports.Text + "_JEA.pdf");
    iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
    using (MemoryStream stream = new MemoryStream())
    {
        PdfReader reader = new PdfReader(bytes);
        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            int pages = reader.NumberOfPages;
            for (int i = 1; i <= pages; i++)
            {
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i),
                 @Element.ALIGN_LEFT, new Phrase(lbReports.Text + " - HD - JEA", blackFont), 63f, 24f, 0);

                ColumnText.ShowTextAligned(stamper.GetUnderContent(i),
                @Element.ALIGN_CENTER, new Phrase("Page " + i.ToString() + " of " + pages, blackFont), 300f, 24f, 0);

                ColumnText.ShowTextAligned(stamper.GetUnderContent(i),
                @Element.ALIGN_RIGHT, new Phrase("" + DateTime.Now, blackFont), 549f, 24f, 0);
            }

            txConnection.Text = "This report contains " + pages + " page(s)";
        }

        bytes = stream.ToArray();

    }//End of page counter

    /*System.IO.File.WriteAllBytes will write all bytes to file again*/

    System.IO.File.WriteAllBytes(Server.MapPath("~/TempReports/") + lbReports.Text + "_JEA.pdf", bytes);

    // Temporary path that is used to display the pdf in the embed.
    System.IO.File.WriteAllBytes(Server.MapPath("~/TempReports/ReportsEmbed/") + lbReports.Text + "_JEA.pdf", bytes);

    /*this is what sends the PDF to the embed viewer object
     The ltEmbed is what receives the plugin to dispplay the file*/

    string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"698px\" height=\"450px\">";
    embed += "If you are unable to view file, you can download it from <a href = \"{0}\">here</a>";
    embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view it.";
    embed += "</object>";

    ltEmbed.Text = string.Format(embed, ("http://localhost:65423/TempReports/ReportsEmbed/") + lbReports.Text + "_JEA.pdf");
    memoryStream.Close();

    this.Context.ApplicationInstance.CompleteRequest();
}
catch (DocumentException exe)
{
    txConnection.Text = "There has been an error generating the file. Please try again. Error: " + exe;
}


问:
Android: WebView's method goBack() shows a blank page
I have an android application that loads web pages in an activity with a WebView. I am using the retrieving the page manually and using WebView's loadDataWithBaseURL to display it on screen. Everything there is fine.

Now, i am trying to override the Back button press to simulate going back in the WebView history stack. I am able to override the Back button press, i can see that there is a history stack in the WebView, i can see that the history url is correct, but when i call WebView's goBack() method, it displays a blank page.

Anyone encountered this before or give me a couple of suggestions to proceed from this?

Edit: If i use WebView's loadUrl method, the Back button with an override works as intended. But why.... If i need to handle this manually, how do i start messing with history pages?

答:
The way I deal with this is keeping a local stack pointer to the number of loaded pages after the root page loaded using loadDataWithBaseURL . When going back, if my pointer hits 1 I am at root level and reload the root page with  loadDataWithBaseURL.

FYI, I use this code in Activities with fragments, so the fragments implement the interface IBackButtonListener which helps me to capture the back button in the main activity and propagate the event to the current fragment. If the fragment returns true it means it has taken care of the event.

IBackbuttonListener.java

```<code>public interface IBackButtonListener {
    public boolean onBackButtonPressed();
}
</code>```

Fragment that implements IBackButtonListener and has a webview loaded from html data.

```<code>    private int historyStackPointer = 0;

    ...

         @Override
            public boolean onBackButtonPressed() {
                boolean rtn = false;

                if (webView.canGoBack()) {
                    if(historyStackPointer > 1) {
                        webView.goBack();
                        historyStackPointer--;
                        rtn = true;
                    }else{
                        if(historyStackPointer == 1) {
                            // Reload the html data
                            webView.loadDataWithBaseURL("file:///android_asset/", html_data, "text/html", "UTF-8", null);
                            historyStackPointer = 0;
                            rtn = true;
                        }else{
                            webView.loadUrl("about:blank");
                            rtn = false;
                        }
                    }
                } else {
                    rtn = false;
                }
                return rtn;
            }
</code>```

html_data is a String with the page's html.

Body:
The way I deal with this is keeping a local stack pointer to the number of loaded pages after the root page loaded using loadDataWithBaseURL . When going back, if my pointer hits 1 I am at root level and reload the root page with  loadDataWithBaseURL.

FYI, I use this code in Activities with fragments, so the fragments implement the interface IBackButtonListener which helps me to capture the back button in the main activity and propagate the event to the current fragment. If the fragment returns true it means it has taken care of the event.

IBackbuttonListener.java

public interface IBackButtonListener {
    public boolean onBackButtonPressed();
}

Fragment that implements IBackButtonListener and has a webview loaded from html data.

    private int historyStackPointer = 0;

    ...

         @Override
            public boolean onBackButtonPressed() {
                boolean rtn = false;

                if (webView.canGoBack()) {
                    if(historyStackPointer > 1) {
                        webView.goBack();
                        historyStackPointer--;
                        rtn = true;
                    }else{
                        if(historyStackPointer == 1) {
                            // Reload the html data
                            webView.loadDataWithBaseURL("file:///android_asset/", html_data, "text/html", "UTF-8", null);
                            historyStackPointer = 0;
                            rtn = true;
                        }else{
                            webView.loadUrl("about:blank");
                            rtn = false;
                        }
                    }
                } else {
                    rtn = false;
                }
                return rtn;
            }

html_data is a String with the page's html.


问:
PHP - For statement creates a second empty element
```<code><?php
include_once "removed.php";

$user = $conn -> real_escape_string($_SESSION['username']);

$query = "SELECT * FROM REMOVED WHERE removed ='$user' AND removed='1'";
$result = $conn -> query($query);

if(!$result){
  die($conn -> error);
}

else {
  $row = $result -> num_rows;

  for ($i = 0; $i < $row; ++$i)
  {
    $result -> data_seek($i);
    $row = $result -> fetch_array(MYSQLI_ASSOC);
    ?>
    <h4><?= $row['Group_name'];?></h4>
    <?php
  }
}
mysqli_close($conn);
?>
</code>```

So this code that I have written has given me one issue it successfully creates the
 element with the $row data. However, it also creates an empty
 element as well.

Chrome inspector shows:

```<code><h4> content that I want </h4>
<h4></h4>
</code>```

I only have one entry in the database for test purposes.

答:
```<code>for ($i = 0; $i < $row; ++$i)
  {
    $result -> data_seek($i);
    while ($row = $result -> fetch_array(MYSQLI_ASSOC)){
      ?>
      <h4><?= $row['Group_name'];?></h4>
      <?php
    }
  }
</code>```

When I add the while statement it sorts the issue and only displays the one correct element. The second element does not load. Rather weird, as I still do not know how the for loop ended create the empty second element.

Body:
<?php
include_once "removed.php";

$user = $conn -> real_escape_string($_SESSION['username']);

$query = "SELECT * FROM REMOVED WHERE removed ='$user' AND removed='1'";
$result = $conn -> query($query);

if(!$result){
  die($conn -> error);
}

else {
  $row = $result -> num_rows;

  for ($i = 0; $i < $row; ++$i)
  {
    $result -> data_seek($i);
    $row = $result -> fetch_array(MYSQLI_ASSOC);
    ?>

<?= $row['Group_name'];?>

    <?php
  }
}
mysqli_close($conn);
?>

So this code that I have written has given me one issue it successfully creates the
 element with the $row data. However, it also creates an empty
 element as well.

Chrome inspector shows:

 content that I want

I only have one entry in the database for test purposes.

Body:
for ($i = 0; $i < $row; ++$i)
  {
    $result -> data_seek($i);
    while ($row = $result -> fetch_array(MYSQLI_ASSOC)){
      ?>
      <h4><?= $row['Group_name'];?></h4>
      <?php
    }
  }

When I add the while statement it sorts the issue and only displays the one correct element. The second element does not load. Rather weird, as I still do not know how the for loop ended create the empty second element.


问:
Clear the "Where to build the binaries" history in cmake gui
It's a simple question, yet for the life of me, can't find a simple answer to this question.</p>

答:
I don't believe there is a way to clear the cached build paths through the CMake GUI nor through the command line interface; however, in windows you can use the registry editor and navigate to HKEY_CURRENT_USER/SOFTWARE/Kitware/CMakeSetup/Settings/StartPath. There, you'll see some indexed variables prefixed by "WhereBuild". You can modify these paths or delete them entirely.

On OS X, these variables are stored in a properties list located in $HOME/Library/Preferences/com.kitware.CMakeSetup.plist.

On other Unix/Linux-based systems, you may find it in $HOME/.config/Kitware/CMakeSetup.conf


答:
```<code>public class JavaApplication21 {
    public static void main(String[] args) {
        for(int i=1;i<13;i++) {
            for(int j=1;j<=12;j++) {
                System.out.printf("%d x %d = %d  \n",i,j,(i*j));
                System.out.println();
            }
        }
    }
}
</code>```

Title: format 12 by 12 multiplication table

Body:
My program outputs the table like this:

1  2  3  4  5  6  7  8  9  10  11  12
2  4  6  8  10  12  14  16  18  20  22  24
3  6  9  12  15  18  21  24  27  30  33  36
4  8  12  16  20  24  28  32  36  40  44  48
5  10  15  20  25  30  35  40  45  50  55  60
6  12  18  24  30  36  42  48  54  60  66  72
7  14  21  28  35  42  49  56  63  70  77  84
8  16  24  32  40  48  56  64  72  80  88  96
9  18  27  36  45  54  63  72  81  90  99  108
10  20  30  40  50  60  70  80  90  100  110  120
11  22  33  44  55  66  77  88  99  110  121  132
12  24  36  48  60  72  84  96  108  120  132  144

I need to make it look a little better. Need your help.

This is my code:

int a;
int b;
for (a=1; a<=12; ++a)
{
    for (b=1; b<=12; ++b)
    {
        System.out.print(a*b+"  ");
    }
    System.out.println();
}


问:
java.sql.SQLException: No value specified for parameter 1 error
I looked for this error in other stackoverflow problems but basically the solutions given are the same thing as my code I don't know what I'm doing wrong.</p>

```<code>public List<ProjectUser> findProjectUserId(int id){
     List <ProjectUser> users= new ArrayList<>();
     ProjectUser projectuser= null;
     try {
         String req="select * from projectuser where project=?";
         PreparedStatement ps= cnx.getConnection().prepareStatement(req);
         ResultSet rs= ps.executeQuery();
         ps.setInt(1,id);
         while (rs.next()){
            projectuser= new ProjectUser(rs.getInt(1), rs.getInt(2), rs.getInt(3));
             users.add(projectuser);
         }
     } catch (SQLException ex){
         ex.printStackTrace();
     }
     return users;
}
</code>```

答:
You should to execute your Stetement after you set Paramettres :</p>

```<code>ps.setInt(1,id);//set param
ResultSet rs= ps.executeQuery();//then execute your statement
</code>```

Body:
I looked for this error in other stackoverflow problems but basically the solutions given are the same thing as my code I don't know what I'm doing wrong.

public List<ProjectUser> findProjectUserId(int id){
     List <ProjectUser> users= new ArrayList<>();
     ProjectUser projectuser= null;
     try {
         String req="select * from projectuser where project=?";
         PreparedStatement ps= cnx.getConnection().prepareStatement(req);
         ResultSet rs= ps.executeQuery();
         ps.setInt(1,id);
         while (rs.next()){
            projectuser= new ProjectUser(rs.getInt(1), rs.getInt(2), rs.getInt(3));
             users.add(projectuser);
         }
     } catch (SQLException ex){
         ex.printStackTrace();
     }
     return users;
}

Body:
You should to execute your Stetement after you set Paramettres :

ps.setInt(1,id);//set param
ResultSet rs= ps.executeQuery();//then execute your statement


问:
How can i get x indexed row from a table in PL/SQL?
First of all feel free to correct my English and
I have just started PL/SQL.

Here is my PL/SQL code.
There is table called 'EMP' with employees's information.

My goal is to get the median of the employees's wage.
So if the number of employees is odd then i need the middle one.

If it is even then i need the two mid ones's average.

It does the job so far, im just confused after the "if" statement.
What is the easiest way to get the nth indexed row's value?

```<code>SET SERVEROUTPUT ON

DECLARE
    counter Int(4);
    osszeg Int(5);
    temp EMP.sal%TYPE;

CURSOR wage IS
  SELECT EMP.SAL
  FROM EMP
  ORDER BY EMP.SAL ASC;

BEGIN
     OPEN wage;
     counter := 0;

LOOP
  FETCH wage
  INTO temp;
  EXIT WHEN wage%NOTFOUND;
  counter := counter + 1;
END LOOP;
CLOSE wage;
</code>```

AND i need help from here

```<code>IF MOD(counter,2) = 0 THEN

ELSE

END IF;

END;
</code>```

答:
I hope it easiest but not proper</p>

```<code>IF MOD(counter,2) = 0 THEN
    //first_number = counter/2
    //second_number = first_number+1
    //avg= (first_number+second_number)/2

ELSE
    //first_number = counter/2;
    //avg = first_number+1

END IF;
</code>```

Body:
First of all feel free to correct my English and
I have just started PL/SQL.

Here is my PL/SQL code.
There is table called 'EMP' with employees's information.

My goal is to get the median of the employees's wage.
So if the number of employees is odd then i need the middle one.

If it is even then i need the two mid ones's average.

It does the job so far, im just confused after the "if" statement.
What is the easiest way to get the nth indexed row's value?

SET SERVEROUTPUT ON

DECLARE
    counter Int(4);
    osszeg Int(5);
    temp EMP.sal%TYPE;

CURSOR wage IS
  SELECT EMP.SAL
  FROM EMP
  ORDER BY EMP.SAL ASC;

BEGIN
     OPEN wage;
     counter := 0;

LOOP
  FETCH wage
  INTO temp;
  EXIT WHEN wage%NOTFOUND;
  counter := counter + 1;
END LOOP;
CLOSE wage;

AND i need help from here

IF MOD(counter,2) = 0 THEN

ELSE

END IF;

END;

Body:
I hope it easiest but not proper

IF MOD(counter,2) = 0 THEN
    //first_number = counter/2
    //second_number = first_number+1
    //avg= (first_number+second_number)/2

ELSE
    //first_number = counter/2;
    //avg = first_number+1

END IF;


问:
How to backup/replicate Azure store onsite
I have a Azure website that allows customers to upload documents. There are a lot of documenet (~200Gb so far).

I need a way to backup the documents to another location (Azure or other location), or have live replication to a server. Is there anything I can use that will do this?

答: You can use Cloudberry. Here is the link to their website.  The tool will not give you cloud storage, but will assist in backup process. It can back up either to the cloud or to the local storages.</p>


问:
CSS: Height not correct when resized
I've been stuck with this problem for a long time now. Whenever i resize my window the CSS acts really weird. I'll show you pictures because it's hard for me to explain.

How it should be:

How it shouldn't be:

Even though I use procentage height instead of pixels it gets all wrong.

I've linked the source code here, same problem occours on resize window:

jsfiddle.net/nxa747ca/

答:
It's not working because you have position:fixed and position: absolute on your classes.

First thing first fix the order of your html:

 <input type="text" class="chat-name" placeholder="Type your message">

On your css remove position: absolute; on chat-messages and position: fixed; on .chat-name they should be just the default position: relative;

Title: CSS: Height not correct when resized

Body:
It's not working because you have position:fixed and position: absolute on your classes.

First thing first fix the order of your html:

<div class="chat-messages"></div>
 <input type="text" class="chat-name" placeholder="Type your message">

On your css remove position: absolute; on chat-messages and position: fixed; on .chat-name they should be just the default position: relative;


问:
Javascript - How to remove all active classes unless the element being clicked on already has a active class
```<code>    const offCanvasLinks = document.querySelectorAll('.off-canvas__link');

    [].forEach.call(offCanvasLinks, function(link) {
        link.addEventListener('click', (event) => {
            const typeVal = link.getAttribute('data-type')

            if (typeVal === "star") {
                document.querySelector('[data-star-links]').classList.toggle('active');
            } else if (typeVal === "how-to") {
                document.querySelector('[data-how-to]').classList.toggle('active');
            } else {
                document.querySelector('[data-presenters]').classList.toggle('active');
            }
        })
    });
</code>```

I have the above code that clicks on a navigation to toggle a class of active.

If I click on another element in the navigation I need to remove all active classes unless the clicked on element already has a active class.

In Jquery this is super easy with the ability to use .not(). Where you can just past through the event target to check and remove all other active classes.

So to make this more clear what I'm looking for is a way to remove all active classes unless the element being clicked has already got an active class.

Let me know your thoughts

*********** UPDATE ******************
Ok...
Click on a link at the bottom it'll show a screen nicely if you then click on another link it will close the previous one then open the next one. HOWEVER if you click on the same link it does not close the menu.

how do I remove the class if it is already open?

Link: https://jsfiddle.net/2oqm0r2n/3/

答:
If I understand correctly, you want to toggle the active class of the element corresponding to the clicked item, and you want to remove the active class from all other elements.

This you can do as follows:

```<code>  if (typeVal === containerVal) {
    container.classList.toggle('active')
  } else {
    container.classList.remove('active')
  }
</code>```

See your updated fiddle

Or in one "line":

```<code>container.classList.toggle('active', typeVal === containerVal &&
                                     !container.classList.contains('active'));
</code>```

...in this fiddle

Body:
    const offCanvasLinks = document.querySelectorAll('.off-canvas__link');

    [].forEach.call(offCanvasLinks, function(link) {
        link.addEventListener('click', (event) => {
            const typeVal = link.getAttribute('data-type')

            if (typeVal === "star") {
                document.querySelector('[data-star-links]').classList.toggle('active');
            } else if (typeVal === "how-to") {
                document.querySelector('[data-how-to]').classList.toggle('active');
            } else {
                document.querySelector('[data-presenters]').classList.toggle('active');
            }
        })
    });

I have the above code that clicks on a navigation to toggle a class of active.

If I click on another element in the navigation I need to remove all active classes unless the clicked on element already has a active class.

In Jquery this is super easy with the ability to use .not(). Where you can just past through the event target to check and remove all other active classes.

So to make this more clear what I'm looking for is a way to remove all active classes unless the element being clicked has already got an active class.

Let me know your thoughts

*********** UPDATE ******************
Ok...
Click on a link at the bottom it'll show a screen nicely if you then click on another link it will close the previous one then open the next one. HOWEVER if you click on the same link it does not close the menu.

how do I remove the class if it is already open?

Link: https://jsfiddle.net/2oqm0r2n/3/

Body:
If I understand correctly, you want to toggle the active class of the element corresponding to the clicked item, and you want to remove the active class from all other elements.

This you can do as follows:

  if (typeVal === containerVal) {
    container.classList.toggle('active')
  } else {
    container.classList.remove('active')
  }

See your updated fiddle

Or in one "line":

container.classList.toggle('active', typeVal === containerVal &&
                                     !container.classList.contains('active'));

...in this fiddle


问:
How to fake time in javascript?
I would like to mock the Date constructor so that whenever I call new Date(), it always return specific time.

I found Sinon.js provide useFakeTimers to mock time. But the following code doesn't work for me.

```<code>sinon.useFakeTimers(new Date(2011,9,1));

//expect : 'Sat Oct 01 2011 00:00:00' ,

//result : 'Thu Oct 27 2011 10:59:44‘
var d = new Date();
</code>```

答:
You can also use Proxies:</p>

```<code>window.Date = new Proxy(Date, {
    construct: function(target, args) {
        if (args.length === 0) {
            return new target(2017, 04, 13, 15, 03, 0);
        }
        return new target(...args);
    }
});
</code>```

Title: How to fake time in javascript?

Body:
I would like to mock the Date constructor so that whenever I call new Date(), it always return specific time.

I found Sinon.js provide useFakeTimers to mock time. But the following code doesn't work for me.

sinon.useFakeTimers(new Date(2011,9,1));

//expect : 'Sat Oct 01 2011 00:00:00' ,

//result : 'Thu Oct 27 2011 10:59:44‘
var d = new Date();

Body:
You can also use Proxies:

window.Date = new Proxy(Date, {
    construct: function(target, args) {
        if (args.length === 0) {
            return new target(2017, 04, 13, 15, 03, 0);
        }
        return new target(...args);
    }
});


问:
How do I create .swiftlint.yml file & where I need to put it?
I want to use Swiftlint in my Swift project.
I followed the Realm instruction and installed Swiftlint by brew install swiftlint. Further I face the problem to create .swiftlint.yml file.

So please suggest me how I proceed?

答:
I found this video helpful:
https://www.youtube.com/watch?v=3MAlqOVIAwI

You can create a .swiftlint.yml in XCode and save it in your project directory. Just select File -> New -> File -> Empty


答:
You are attempting to set the bind value after executing the query, instead of before it. Flip the order around, and you should be OK:</p>

```<code>PreparedStatement ps = cnx.getConnection().prepareStatement(req);
ps.setInt(1,id);
ResultSet rs = ps.executeQuery();
</code>```

Title: java.sql.SQLException: No value specified for parameter 1 error

Body:
You are attempting to set the bind value after executing the query, instead of before it. Flip the order around, and you should be OK:

PreparedStatement ps = cnx.getConnection().prepareStatement(req);
ps.setInt(1,id);
ResultSet rs = ps.executeQuery();


问:
Bins for histogram
I have a data frame which looks like this:

```<code>     legal    value
0    1        3
1    1        7
2    0        10
3    1        12
4    1        4
5    1        17
6    0        21
7    1        19
8    1        3
9    0        18
10   1        17
11   1        17
12   0        11
13   1        23
</code>```

and I'm trying to split only the legal 1 values into 6 bin intervals for a histogram. The intervals look like:

```<code>[0-6], [6-9], [9-12], [12-16], [16-20], [20-24]
</code>```

The data gathered would then look like this:

```<code>bin    frequency   values
0-6    3           3, 4, 3
6-9    1           7
9-12   1           12
12-16  1           12
16-20  4           17, 17, 19, 17
20-24  1           23
</code>```

I am trying to create a histogram with the bin intervals on the c x axis, and the the frequency of the valid 1 values on the y axis. Basically trying to create a histogram which looks like this example.

So far I have written this:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict

bins = ['0-6', '6-9', '9-12', '12-16', '16-20', '20-24']
df = pd.read_csv('data.csv', encoding = 'ISO-8859-1')

d = defaultdict(int)
for legal, value in zip(df['legal'], df['value']):
    if (legal == 1):
        if (0 <= value <= 6):
            d[bins[0]] += 1
</code>```

Which is trying to group the bins with dictionaries, but this seems over complicated and their must be a better way using the pandas library.

How can I use something like pandas.Dataframe.groupby to group the bins with their respective frequencies, then plot these values on a histogram using matplotlib.pyplot?

答:
No need to do any grouping, the dataframe can just be filtered by the "legal" column values.

```<code>import matplotlib.pyplot as plt
import pandas as pd

legal= [1,1,0,1,1,1,0,1,1,0,1,1,0,1]
value = [3,7,10,12,4,17,21,19,3,18,17,17,11,23]
df = pd.DataFrame({"legal":legal, "value":value})

df2 = df[df["legal"] == 1]

bins = [0,6,9,12,16,20,24]
plt.hist(df2["value"], bins=bins, edgecolor="k")
plt.xticks(bins)

plt.show()
</code>```

Title: Bins for histogram

Body:
I have a data frame which looks like this:

     legal    value
0    1        3
1    1        7
2    0        10
3    1        12
4    1        4
5    1        17
6    0        21
7    1        19
8    1        3
9    0        18
10   1        17
11   1        17
12   0        11
13   1        23

and I'm trying to split only the legal 1 values into 6 bin intervals for a histogram. The intervals look like:

[0-6], [6-9], [9-12], [12-16], [16-20], [20-24]

The data gathered would then look like this:

bin    frequency   values
0-6    3           3, 4, 3
6-9    1           7
9-12   1           12
12-16  1           12
16-20  4           17, 17, 19, 17
20-24  1           23

I am trying to create a histogram with the bin intervals on the c x axis, and the the frequency of the valid 1 values on the y axis. Basically trying to create a histogram which looks like this example.

So far I have written this:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict

bins = ['0-6', '6-9', '9-12', '12-16', '16-20', '20-24']
df = pd.read_csv('data.csv', encoding = 'ISO-8859-1')

d = defaultdict(int)
for legal, value in zip(df['legal'], df['value']):
    if (legal == 1):
        if (0 <= value <= 6):
            d[bins[0]] += 1

Which is trying to group the bins with dictionaries, but this seems over complicated and their must be a better way using the pandas library.

How can I use something like pandas.Dataframe.groupby to group the bins with their respective frequencies, then plot these values on a histogram using matplotlib.pyplot?

Body:
No need to do any grouping, the dataframe can just be filtered by the "legal" column values.

import matplotlib.pyplot as plt
import pandas as pd

legal= [1,1,0,1,1,1,0,1,1,0,1,1,0,1]
value = [3,7,10,12,4,17,21,19,3,18,17,17,11,23]
df = pd.DataFrame({"legal":legal, "value":value})

df2 = df[df["legal"] == 1]

bins = [0,6,9,12,16,20,24]
plt.hist(df2["value"], bins=bins, edgecolor="k")
plt.xticks(bins)

plt.show()


问:
How can I merge new previously-uncommitted changes from a former subversion working directory into a newly imported bazaar repository?
I had upgraded to Ubuntu server 10.04 - however it removed SVK which I had been using for distributed-vc needs, as much of my old projects were still wrapped up in self-hosted subversion repositories on various servers. This was working adequately for the time being between my various systems. I decided to migrate onto Bazaar which I was already evaluating using in newer projects.

I have installed the bzr-svn plugin to allow the use of svn-import - and successfully set up repositories in /var/bzr/repos/ where all the projects were imported into their own set (using the auto-detected trunk2 layout). bzr log confirms successful importation of all the projects.

Unfortunately, several of my projects have several uncommitted changes in a working folder - these I would like to remerge back into the central /var/bzr/repos/projectname repository. I would like these to be new revisions on top of the newly imported repositories.

How should I go about this?

These working folders are i.e. /var/www/projectname/htdocs - some are on the development server, and some are on a windows laptop (which already has bazaar and subversion installed)

I have tried running bzr init and bzr merge file://var/bzr/repos/projectname/trunk - this creates a large number of conflicts; alternatively I have tried: bzr init; bzr add, and bzr merge .

In each case I have tried erasing the newly generated files from the merge - and renaming .moved files back, and committing - this has the effect of causing the revision numbers to start from 1, and running backwards to -301. Another different result was the total loss of log history when I tried to "bzr push" locally committed changes back up. Fortunately I have been able to reset and reimport the repository from the original subversion source each time.

The long route would be to simply branch/checkout into a new folder, and diff/redo the new changes over, but I would like to avoid recoding changes or running a kdiff directory merge operation.

The desired result would be to have the new changes applied onto the central /var/bzr/repos/projectname branch while preserving the revision numbers and log.

答:
If I understand correctly, I would:
copy the .bzr dir from the branch you want to base the other changes on (mainline/main) into the workingdir with the other changes.
Then you can do a bzr commit in there and push it to your mainline/main branch.
Repeat for each workingtree with uncommitted changes.</p>


问:
SDL inputs only working sometimes
I am experimenting with keyboard input in SDL and I have encountered a strange problem. Whenever I get input it only outputs the appropriate response sometimes (Clicking X only sometimes closes the program, pressing 1 only sometimes outputs "you pressed 1". Here is my main code:

```<code>#include <iostream>
#include <SDL.h>

#include "Screen.h"
#include "Input.h"
using namespace std;

int main(int argc, char *argv[]) {
    Screen screen;
    Input input;
    if (screen.init() == false) {
        cout << "Failure initializing SDL" << endl;
    }

    while (true) {

        if (input.check_event() == "1") {
            cout << "You pressed 1" << endl;
        } else if (input.check_event() == "quit") {
            break;
        }

    }

    SDL_Quit();
    return 0;
</code>```

and here is my Input class:

```<code>#include <iostream>
#include <SDL.h>
#include "Input.h"
using namespace std;
string Input::check_event() {
    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_QUIT) {
            return "quit";
        }
        else if(event.type == SDL_KEYDOWN){
            switch(event.key.keysym.sym){
            case SDLK_1:
                return "1";
            }
        }
    }
    return "null";
}
</code>```

Any help would be appreciated!

答:
From the documentation of SDL_PollEvent():

If event is not NULL, the next event is removed from the queue and
  stored in the SDL_Event structure pointed to by event.

Analyzing your code:

```<code>    if (input.check_event() == "1") {
</code>```

This removes the event, whatever it is, from the queue.

```<code>    } else if (input.check_event() == "quit") {
</code>```

Say the return value of the 1st call to check_event() was "quit", then this call won't return "quit" again, because this information is now lost.

To fix that, call check_event() only once per loop iteration and store the result in a temporary variable. Then use only that variable in the conditions:

```<code>while (true) {
    string event = input.check_event();
    if (event == "1") {
        cout << "You pressed 1" << endl;
    } else if (event == "quit") {
        break;
    }
}
</code>```

Title: SDL inputs only working sometimes

Body:
I am experimenting with keyboard input in SDL and I have encountered a strange problem. Whenever I get input it only outputs the appropriate response sometimes (Clicking X only sometimes closes the program, pressing 1 only sometimes outputs "you pressed 1". Here is my main code:

#include <iostream>
#include <SDL.h>

#include "Screen.h"
#include "Input.h"
using namespace std;

int main(int argc, char *argv[]) {
    Screen screen;
    Input input;
    if (screen.init() == false) {
        cout << "Failure initializing SDL" << endl;
    }

    while (true) {

        if (input.check_event() == "1") {
            cout << "You pressed 1" << endl;
        } else if (input.check_event() == "quit") {
            break;
        }

    }

    SDL_Quit();
    return 0;

and here is my Input class:

#include <iostream>
#include <SDL.h>
#include "Input.h"
using namespace std;
string Input::check_event() {
    while (SDL_PollEvent(&event)) {
        if (event.type == SDL_QUIT) {
            return "quit";
        }
        else if(event.type == SDL_KEYDOWN){
            switch(event.key.keysym.sym){
            case SDLK_1:
                return "1";
            }
        }
    }
    return "null";
}

Any help would be appreciated!

Body:
From the documentation of SDL_PollEvent():

If event is not NULL, the next event is removed from the queue and
  stored in the SDL_Event structure pointed to by event.

Analyzing your code:

    if (input.check_event() == "1") {

This removes the event, whatever it is, from the queue.

    } else if (input.check_event() == "quit") {

Say the return value of the 1st call to check_event() was "quit", then this call won't return "quit" again, because this information is now lost.

To fix that, call check_event() only once per loop iteration and store the result in a temporary variable. Then use only that variable in the conditions:

while (true) {
    string event = input.check_event();
    if (event == "1") {
        cout << "You pressed 1" << endl;
    } else if (event == "quit") {
        break;
    }
}


问:
canvas and stage losing global scope in easel.js
Here's the code. At the top, you can see that canvas and stage are declared as global variables. Then the initializeCanvas() function runs on page load and assigns those variables and loads a background image.

Strangely, though, stage and canvas end up undefined.

Why? And what can I do about it?

Roger

```<code>var canvas, stage

function initializeCanvas() {
    canvas = document.getElementById("starCanvas")
    canvas.width = window.innerWidth
    canvas.height = 720

    stage = new createjs.Stage("starCanvas")

    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded
}

function handleBackgroundImage_Loaded(evt) {
    background.x = 0
    background.y = 0
    stage.addChildAt(background,0);
    stage.update()
}

alert(canvas)
alert(stage)
</code>```

答:
make initializeCanvas, an immediately invoked function. also, always use console.log to output an object for inspection.

var canvas, stage;

(function initializeCanvas() {
    canvas = document.getElementById("starCanvas");
    canvas.width = window.innerWidth;
    canvas.height = 720;
    stage = new createjs.Stage("starCanvas");
    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded;
})();

function handleBackgroundImage_Loaded(evt) {
    background.x = 0;
    background.y = 0;
    stage.addChildAt(background, 0);
    stage.update();
}
console.log(canvas);
console.log(stage);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<canvas id="starCanvas"></canvas></code>```

Body:
Here's the code. At the top, you can see that canvas and stage are declared as global variables. Then the initializeCanvas() function runs on page load and assigns those variables and loads a background image.

Strangely, though, stage and canvas end up undefined.

Why? And what can I do about it?

Roger

var canvas, stage

function initializeCanvas() {
    canvas = document.getElementById("starCanvas")
    canvas.width = window.innerWidth
    canvas.height = 720

    stage = new createjs.Stage("starCanvas")

    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded
}

function handleBackgroundImage_Loaded(evt) {
    background.x = 0
    background.y = 0
    stage.addChildAt(background,0);
    stage.update()
}

alert(canvas)
alert(stage)

Body:
make initializeCanvas, an immediately invoked function. also, always use console.log to output an object for inspection.

var canvas, stage;

(function initializeCanvas() {
    canvas = document.getElementById("starCanvas");
    canvas.width = window.innerWidth;
    canvas.height = 720;
    stage = new createjs.Stage("starCanvas");
    background = new createjs.Bitmap("background1.jpg");
    background.image.onload = handleBackgroundImage_Loaded;
})();

function handleBackgroundImage_Loaded(evt) {
    background.x = 0;
    background.y = 0;
    stage.addChildAt(background, 0);
    stage.update();
}
console.log(canvas);
console.log(stage);

<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<canvas id="starCanvas"></canvas>


问:
git - treat sub git repository as normal repository for unittests?
I'm writing a module that integrates one system with git. I'm writing tests and want to have test repository inside tests directory, so I could run unittests on it.

Module and project structure looks like this:

```<code>myproject/
  mymodule/
    some_dir/
    tests/
      __init__.py
      testrepo/
        /.git
      test_some.py
  /.git
</code>```

Now while I'm developing, it is working. I can run tests using testrepo. Though I noticed, when I committed, git started treating testrepo as subproject automatically. So basically it does not track all changes that occurred. If actual code changes, then it recognizes as subproject/submodule change. But if I let say add new branch, those changes are not recognized (unless I would check out to it etc).

So I'm wondering what could be best way to use testrepo for unittests. I want it to be in source control, so whole structure would be intact with unittests.

If understood correctly from how can I add git submodule into git repo as normal directory? it is not really possible (only by somewhat hacking git name back and forth) to treat sub git repository as normal repository.

So how I could preserve all changes in sub repository, so I would need to just pull myproject and get testrepo with all branches etc?

Or I can only use it as real submodule and need to initialize it after cloning myproject?

Update

If I use testrepo as real submodule, then my tests stop working, because it is no longer recognized as normal git repo.

答:
So after trying submodule and real git repo inside repo, I went with using simple repo set up and tear down between tests.

I bet this is not very optimal solution, but for now I do not see any better one (the faster might be to somehow hide git as normal directory and when running tests, change it to be recognized as git repo and after tests, hide it again: though kind of hacky).

If anyone has better ideas, please write it as an answer.

My implementation sample (it is built using setUpClass and removed using tearDownClass):

```<code># -*- coding: utf-8 -*-
import os
import sh
import shutil

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

def build_test_repo(dir_path):
    """Build testrepo for unittests."""
    def git_add_file(g, txt):
        """create, add and commit dummy file."""
        with open('%s.txt' % txt, 'w') as f:
            f.write('%s content' % txt)
        # add and commit
        g.add('%s.txt' % txt)
        g.commit('-m', '[ADD] %s.txt' % txt)

    path = "%s/%s" % (dir_path, 'testrepo')
    os.makedirs(path)
    # change dir to initialize repo. We use context manager, so after
    # setting up repo, we would get back to previous working directory.
    with cd(path):
        # git from shell
        g = sh.git
        g.init()
        git_add_file(g, 't0')
        # create f1 branch
        g.checkout('-b', 'f1')
        # add and commit for f1
        git_add_file(g, 't1')
        # create f2 branch from master
        g.checkout('master')
        g.checkout('-b', 'f2')
        git_add_file(g, 't2')
        # create copy of master without any difference.
        g.checkout('master')
        g.checkout('-b', 'master_copy')
</code>```

Body:
I'm writing a module that integrates one system with git. I'm writing tests and want to have test repository inside tests directory, so I could run unittests on it.

Module and project structure looks like this:

myproject/
  mymodule/
    some_dir/
    tests/
      __init__.py
      testrepo/
        /.git
      test_some.py
  /.git

Now while I'm developing, it is working. I can run tests using testrepo. Though I noticed, when I committed, git started treating testrepo as subproject automatically. So basically it does not track all changes that occurred. If actual code changes, then it recognizes as subproject/submodule change. But if I let say add new branch, those changes are not recognized (unless I would check out to it etc).

So I'm wondering what could be best way to use testrepo for unittests. I want it to be in source control, so whole structure would be intact with unittests.

If understood correctly from how can I add git submodule into git repo as normal directory? it is not really possible (only by somewhat hacking git name back and forth) to treat sub git repository as normal repository.

So how I could preserve all changes in sub repository, so I would need to just pull myproject and get testrepo with all branches etc?

Or I can only use it as real submodule and need to initialize it after cloning myproject?

Update

If I use testrepo as real submodule, then my tests stop working, because it is no longer recognized as normal git repo.

Body:
So after trying submodule and real git repo inside repo, I went with using simple repo set up and tear down between tests.

I bet this is not very optimal solution, but for now I do not see any better one (the faster might be to somehow hide git as normal directory and when running tests, change it to be recognized as git repo and after tests, hide it again: though kind of hacky).

If anyone has better ideas, please write it as an answer.

My implementation sample (it is built using setUpClass and removed using tearDownClass):

# -*- coding: utf-8 -*-
import os
import sh
import shutil

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

def build_test_repo(dir_path):
    """Build testrepo for unittests."""
    def git_add_file(g, txt):
        """create, add and commit dummy file."""
        with open('%s.txt' % txt, 'w') as f:
            f.write('%s content' % txt)
        # add and commit
        g.add('%s.txt' % txt)
        g.commit('-m', '[ADD] %s.txt' % txt)

    path = "%s/%s" % (dir_path, 'testrepo')
    os.makedirs(path)
    # change dir to initialize repo. We use context manager, so after
    # setting up repo, we would get back to previous working directory.
    with cd(path):
        # git from shell
        g = sh.git
        g.init()
        git_add_file(g, 't0')
        # create f1 branch
        g.checkout('-b', 'f1')
        # add and commit for f1
        git_add_file(g, 't1')
        # create f2 branch from master
        g.checkout('master')
        g.checkout('-b', 'f2')
        git_add_file(g, 't2')
        # create copy of master without any difference.
        g.checkout('master')
        g.checkout('-b', 'master_copy')


问:
printing summary of results in Python
I have a python script which makes an http request to an API in order to pull "member" data. It then runs a loop to hit several different member ID's (listed in a text file) to see if each of them are "expired" or not. What I would like to do is print out a summary of these results instead of printing out the individual results for each of the members. Here is my Python script:

```<code>import requests
import json

qa_members = open("numbers_members.txt")
arraylist = []
    for line in qa_members.readlines():
    arraylist.extend(line.split())
qa_members.close()

arraylist = map(int, arraylist)

authorization_code = raw_input("please enter your authorization code: ")
members = arraylist
print "Member Check Starting"

for member in members:
    url = "http://api22.wiki.com/v1.12/member?id="+str(member)

    header = {"Authorization": authorization_code}

    response = requests.get(url, headers=header)

    member_check = json.loads(response.text)

    final_member_status = member_check["response"]["member"]
    ["is_expired"]

    print str(member) + " expired status: " + str(final_member_status)

if final_member_status == False:
    print "All Members Passed"
else:
    print "Some members are expired, please refer to log"

print "Member Check Complete"
</code>```

From this, I get several terminal outputs like:

```<code>123 expired status: False
567 expired status: False
</code>```

Is there way to instead, print out a summary of the results? It could be something like:

```<code>"24 members returned False"
"11 members returned True"
</code>```

It would also be helpful to find out the ID of a particular member if the status returned was "true":

```<code>"Member 1234 returned True"
</code>```

Or something similar to that. Any help is greatly appreciated.

Thanks!

答:
A first thought:

```<code>falsecount = 0
truecount = 0
for member in members:
    url = "http://api22.wiki.com/v1.12/member?id="+str(member)

    header = {"Authorization": authorization_code}

    response = requests.get(url, headers=header)

    member_check = json.loads(response.text)

    final_member_status = member_check["response"]["member"]["is_expired"]

    if final_member_status = False:
        falsecount += 1
    else:
        truecount +=1

print str(falsecount) + "members returned False"
print str(truecount) + "members returned False"
</code>```

EDIT

I am unable to check however what the output of final_member_status = member_check["response"]["member"]["is_expired"] is. This could be "False" or False (thus, a string or an actual evaluation), if it is "False" (a string) then my line should read if final_member_status = "False", however, if it is an evaluation (returning False if the mentioned son field does not exist) the above code is correct.

Title: printing summary of results in Python

Body:
I have a python script which makes an http request to an API in order to pull "member" data. It then runs a loop to hit several different member ID's (listed in a text file) to see if each of them are "expired" or not. What I would like to do is print out a summary of these results instead of printing out the individual results for each of the members. Here is my Python script:

import requests
import json

qa_members = open("numbers_members.txt")
arraylist = []
    for line in qa_members.readlines():
    arraylist.extend(line.split())
qa_members.close()

arraylist = map(int, arraylist)

authorization_code = raw_input("please enter your authorization code: ")
members = arraylist
print "Member Check Starting"

for member in members:
    url = "http://api22.wiki.com/v1.12/member?id="+str(member)

    header = {"Authorization": authorization_code}

    response = requests.get(url, headers=header)

    member_check = json.loads(response.text)

    final_member_status = member_check["response"]["member"]
    ["is_expired"]

    print str(member) + " expired status: " + str(final_member_status)

if final_member_status == False:
    print "All Members Passed"
else:
    print "Some members are expired, please refer to log"

print "Member Check Complete"

From this, I get several terminal outputs like:

123 expired status: False
567 expired status: False

Is there way to instead, print out a summary of the results? It could be something like:

"24 members returned False"
"11 members returned True"

It would also be helpful to find out the ID of a particular member if the status returned was "true":

"Member 1234 returned True"

Or something similar to that. Any help is greatly appreciated.

Thanks!

Body:
A first thought:

falsecount = 0
truecount = 0
for member in members:
    url = "http://api22.wiki.com/v1.12/member?id="+str(member)

    header = {"Authorization": authorization_code}

    response = requests.get(url, headers=header)

    member_check = json.loads(response.text)

    final_member_status = member_check["response"]["member"]["is_expired"]

    if final_member_status = False:
        falsecount += 1
    else:
        truecount +=1

print str(falsecount) + "members returned False"
print str(truecount) + "members returned False"

EDIT

I am unable to check however what the output of final_member_status = member_check["response"]["member"]["is_expired"] is. This could be "False" or False (thus, a string or an actual evaluation), if it is "False" (a string) then my line should read if final_member_status = "False", however, if it is an evaluation (returning False if the mentioned son field does not exist) the above code is correct.


问:
Using fgets(char* c, int i, file* f) with printf() for C in Eclipse - CDT. The order of output is not correct.!
```<code>#include <stdio.h>
enum { max_string = 127 };
static char ch[max_string+1] = "";

int main(int argc, char ** argv){
    printf("Type a String: \n");
    fgets(ch, max_string, stdin);
    printf("the string is: %s", ch);
    return 0;
}
</code>```

I have used this code and the output in the console was

```<code>hello world
Type a String:
the string is: hello world
</code>```

'hello world' is the input which I give.

My question is why isn't the order not maintained in this case. As printf() should work before fgets(), but here it isn't that way. I have checked with the same compiler in Code::Blocks. There it works in order.
But in case of Eclipse-MARS CDT I find it erroneous.

答:
I assume you're running on Windows, and running into a longstanding problem  with console output in Eclipse CDT on Windows.

The bug is marked as "WONTFIX", and the comments explain why it's a hard problem to fix. They do suggest several workarounds:

Call fflush(stdout) after each call to printf. This flushes the output buffer explicitly after each output operation.

Call setvbuf(stdout, NULL, _IONBF, 0) once at the beginning of your program. This disables output buffering altogether.

Use CDT's experimental "winpty" support as described here. This attempts to make Eclipse's console have the same behaviour as a real terminal, including line buffering.

I have a much simpler solution to suggest: build your program with Eclipse, but run it directly from a terminal (Command Prompt). Then you will get proper terminal behaviour without any workarounds.

Body:
#include <stdio.h>
enum { max_string = 127 };
static char ch[max_string+1] = "";

int main(int argc, char ** argv){
    printf("Type a String: \n");
    fgets(ch, max_string, stdin);
    printf("the string is: %s", ch);
    return 0;
}

I have used this code and the output in the console was

hello world
Type a String:
the string is: hello world

'hello world' is the input which I give.

My question is why isn't the order not maintained in this case. As printf() should work before fgets(), but here it isn't that way. I have checked with the same compiler in Code::Blocks. There it works in order.
But in case of Eclipse-MARS CDT I find it erroneous.


问:
Segmentation Fault with string array
I'm experiencing some problems with an array of strings that seem to be invading a reserved space of memory. The code is too large to post here, so I'll post the important part below:

```<code>int main (  ){

 int i = 0, j = 0, k = 0, count = 0, numLinhas = 0, l = 0;
 char string[100][100];
 char line [17];
 char str[4];
 char str1[5];
 char str2[4];
 char str3[4];

 FILE *p;
 p = fopen("text.txt", "r");
 while(fgets(line, sizeof line, p)!=NULL){
  printf("%s", line);
  strncpy(string[i], line, 17);
  i++;
  numLinhas++;
  }
  fclose(p);
  char *temp[numLinhas];
</code>```

After that it goes into a loop in which stores in string [i] the meaning of the statement contained in the file. The beginning of the for and three examples are shown below:

```<code>    for (i = 0; i<numLinhas; i++){
    sscanf( string[i], "%s %s %s %s" ,str1, str,str2, str3);
    if(str[0]=='0' && str[1] == '0' && str[2]!= 'd') {
    temp[i] = "NOP";
    count++;
    }
    if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }

    if(str[0]=='0'&& str[1] == '7' && str[2]!= 'd') {
    temp[i] = "RLC";
    count++;
    }
</code>```

The error is casual - it does not always happen. And it usually occurs when there is a call to sprintf.
Ah yes! And below is the txt file I'm loading as an example:

```<code>0000 21a 11r 00r
0003 7Ea
0004 21a 12r 00r
0007 46a
0008 80a
0009 21a 13r 00r
000C 77a
000D 3Ea 01a
000F 3Da
0010 76a
0011 0Ad
0012 03d
0013 01d
</code>```

Just saw something new. here's the compile window i'm getting:

```<code>marcos@john:~/Desktop$ ./paraler
0000 21a 11r 00rValor de l: 16

Valor de l: 1
0003 7Ea
Valor de l: 9
0004 21a 12r 00rValor de l: 16

Valor de l: 1
0007 46a
Valor de l: 9
0008 80a
Valor de l: 9
0009 21a 13r 00rValor de l: 16

Valor de l: 1
000C 77a
Valor de l: 9
000D 3Ea 01a
Valor de l: 13
000F 3Da
Valor de l: 9
0010 76a
Valor de l: 9
0011 0Ad
Valor de l: 9
0012 03d
Valor de l: 9
0013 01d
Valor de l: 9
string:0000 21a 11r 00r
string:

string:0003 7Ea

string:0004 21a 12r 00r
string:

string:0007 46a

string:0008 80a

string:0009 21a 13r 00r
string:

string:000C 77a

string:000D 3Ea 01a

string:000F 3Da

string:0010 76a

string:0011 0Ad

string:0012 03d

string:0013 01d

Segmentation fault
</code>```

The strange thing is that I get some empty spaces of the string array... Does it have anything to do with the error?

答:
```<code>if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    /* allocate memory to store instruction - to be freed later */
    temp[i] = malloc(5 + strlen(str2) + 2); /* +2 for the comma */
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }
</code>```

The problem arises when a mnemonic starting with 06 and no ending with d is encountered; the sprintf() writes in a non-allocated area as temp[i] is not initialized. You shall allocate some space to store the result of sprintf.

Title: Segmentation Fault with string array

Body:
I'm experiencing some problems with an array of strings that seem to be invading a reserved space of memory. The code is too large to post here, so I'll post the important part below:

int main (  ){

 int i = 0, j = 0, k = 0, count = 0, numLinhas = 0, l = 0;
 char string[100][100];
 char line [17];
 char str[4];
 char str1[5];
 char str2[4];
 char str3[4];

 FILE *p;
 p = fopen("text.txt", "r");
 while(fgets(line, sizeof line, p)!=NULL){
  printf("%s", line);
  strncpy(string[i], line, 17);
  i++;
  numLinhas++;
  }
  fclose(p);
  char *temp[numLinhas];

After that it goes into a loop in which stores in string [i] the meaning of the statement contained in the file. The beginning of the for and three examples are shown below:

    for (i = 0; i<numLinhas; i++){
    sscanf( string[i], "%s %s %s %s" ,str1, str,str2, str3);
    if(str[0]=='0' && str[1] == '0' && str[2]!= 'd') {
    temp[i] = "NOP";
    count++;
    }
    if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }

    if(str[0]=='0'&& str[1] == '7' && str[2]!= 'd') {
    temp[i] = "RLC";
    count++;
    }

The error is casual - it does not always happen. And it usually occurs when there is a call to sprintf.
Ah yes! And below is the txt file I'm loading as an example:

0000 21a 11r 00r
0003 7Ea
0004 21a 12r 00r
0007 46a
0008 80a
0009 21a 13r 00r
000C 77a
000D 3Ea 01a
000F 3Da
0010 76a
0011 0Ad
0012 03d
0013 01d

Just saw something new. here's the compile window i'm getting:

marcos@john:~/Desktop$ ./paraler
0000 21a 11r 00rValor de l: 16

Valor de l: 1
0003 7Ea
Valor de l: 9
0004 21a 12r 00rValor de l: 16

Valor de l: 1
0007 46a
Valor de l: 9
0008 80a
Valor de l: 9
0009 21a 13r 00rValor de l: 16

Valor de l: 1
000C 77a
Valor de l: 9
000D 3Ea 01a
Valor de l: 13
000F 3Da
Valor de l: 9
0010 76a
Valor de l: 9
0011 0Ad
Valor de l: 9
0012 03d
Valor de l: 9
0013 01d
Valor de l: 9
string:0000 21a 11r 00r
string:

string:0003 7Ea

string:0004 21a 12r 00r
string:

string:0007 46a

string:0008 80a

string:0009 21a 13r 00r
string:

string:000C 77a

string:000D 3Ea 01a

string:000F 3Da

string:0010 76a

string:0011 0Ad

string:0012 03d

string:0013 01d

Segmentation fault

The strange thing is that I get some empty spaces of the string array... Does it have anything to do with the error?

Body:
if(str[0]=='0'&& str[1] == '6' && str[2]!= 'd') {
    /* allocate memory to store instruction - to be freed later */
    temp[i] = malloc(5 + strlen(str2) + 2); /* +2 for the comma */
    sprintf(temp[i],"%s,%s" , "MVI B", str2);
    count = count+2;
    }

The problem arises when a mnemonic starting with 06 and no ending with d is encountered; the sprintf() writes in a non-allocated area as temp[i] is not initialized. You shall allocate some space to store the result of sprintf.


问:
How to solve "Uncaught (in promise) TypeError: response.body.forEach is not a function" ? (vue.js 2)
My component vue.js is like this :

```<code><script>
  export default{
    name: 'CategoryBsSelect',

    template: '\
      <select class="form-control" v-model="selected" required>\
        <option v-for="option in options" v-bind:value="option.id" v-bind:disabled="option.disabled">{{ option.name }}</option>\
      </select>',

    //props: {list: {type: String, default: ''}},

    mounted() {
        this.fetchList();
    },

    data() {
      return {
        selected: '',
        options: [{id: '', name: 'Select Category'}]
      };
    },

    methods: {
        fetchList: function() {
            this.$http.post(window.BaseUrl+'/member/category/list').then(function (response) {
                //this.$set('list', response.data);
                console.log(JSON.stringify(response.body))
                response.body.forEach(function(item){
                    this.$set(this.options, item.id, item);
                }, this);
            });
        },
    }

  };

</script>
</code>```

The result of console.log(JSON.stringify(response.body)) :

{"20":"Category 1","21":"Category 2","22":"Category 3"}

I want display the response on the value of select. But when executed, on the console exist error like this :

Uncaught (in promise) TypeError: response.body.forEach is not a
  function
      at VueComponent.

Is there anyone who can help me?

答:
Use</p>

```<code>Object.keys(response.body).map(function(key) {
    this.$set(this.options, key, response.body[key]);
});
</code>```

Body:
My component vue.js is like this :

The result of console.log(JSON.stringify(response.body)) :

{"20":"Category 1","21":"Category 2","22":"Category 3"}

I want display the response on the value of select. But when executed, on the console exist error like this :

Uncaught (in promise) TypeError: response.body.forEach is not a
  function
      at VueComponent.

Is there anyone who can help me?

Body:
Use

Object.keys(response.body).map(function(key) {
    this.$set(this.options, key, response.body[key]);
});


问:
Calling std::~basic_string() in gdb
As per @EvanED in https://stackoverflow.com/a/11311786/890753 I created a gdb command newstr to create a new std::string and put it in a gdb convenience variable:

```<code>define newstr
set ($arg0)=(std::string*)malloc(sizeof(std::string))
call ($arg0)->basic_string()
# 'assign' returns *this; casting return to void avoids printing of the struct.
call (void)( ($arg0)->assign($arg1) )
end
</code>```

It works great:

```<code>(gdb) newstr $foo "hello world"
(gdb) p $foo->c_str()
$57 = 0xb22e388 "hello world"
</code>```

I use newstr in other custom gdb commands, so for tidyness I also created delstr:

```<code>define delstr
call ($arg0)->~basic_string($arg0)
call free($arg0)
set ($arg0)=(void*)0
end
</code>```

It works, but the destructor call produces an annoying message:

```<code>(gdb) delstr $foo
warning: Using non-standard conversion to match method std::string::~basic_string to supplied arguments
$62 = 0
</code>```

Can I avoid the "non-standard conversion" message?  (I'm using gdb 7.10.)

答:
TL;DR: Pass 0 to the destructor, instead of $foo.

```<code>define delstr
call ($arg0)->~basic_string(0)
#                           ^
call free($arg0)
set ($arg0)=(void*)0
end
</code>```

OK so what is going on... We can first check the signature of a destructor. It indeed takes an integer:

```<code>(gdb) p ((Foo*) 0)->~Foo
$1 = {void (Foo * const, int)} 0x555555554c00 <Foo::~Foo()>

(gdb) p (('std::__cxx11::string'*) 0)->~basic_string
$2 = {void (std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > * const, int)} 0x7ffff7b75010 <std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()>

(gdb) ptype Foo
type = struct Foo {
  public:
    Foo(void);
    ~Foo(int);
}
</code>```

So the "non-standard conversion" warning is about converting a pointer to an integer, which is indeed non-standard. (The warning has nothing to do with the destructor.)

But for what profound reason do we need to pass an extra integer to the destructor in the first place? Turns out it is … a bug  A GCC issue (as of gcc 6.3.0) actually, because the same program compiled using clang (as of clang 3.8.1) does not have that extra int argument.

One should know that, in the Italium C++ ABI there are actually three destructors (D0, D1, D2).

GCC has an optimization -fdeclone-ctor-dtor which refactors the common parts of the three destructors into a "D4" destructor. This "D4" destructor takes an extra argument __in_chrg to determine which of D0/D1/D2 is the source, to know whether to call the virtual base destructors.

This "D4" destructor is somehow also used as the canonical destructor declaration of the DWARF symbol generated by GCC. If we check the GCC issue linked from the GDB bug report, the reason of using "D4" is because the GCC developers didn't want to pick which of D0, D1 or D2 to bless.

And the result is an extra int which GDB didn't ignore.

The __in_chrg value is 2 when the destructor is capable of "complete object destruction" (D0, D1), and 0 when it is just a "base object destructor" (D2). Since a std::string does not have virtual base classes, you should just pass 0 to that argument.

Note: I used this program to test against GDB:

```<code>#include <string>
#include <iostream>
std::string aa;
struct Foo {
        Foo() { std::cout << "Constructing: this = " << this << std::endl; }
        ~Foo() { std::cout << "Destroying: this = " << this << std::endl; }
};
int main() {
        Foo foo;
        return 0;
}
</code>```

Title: Calling std::~basic_string() in gdb

Body:
As per @EvanED in https://stackoverflow.com/a/11311786/890753 I created a gdb command newstr to create a new std::string and put it in a gdb convenience variable:

define newstr
set ($arg0)=(std::string*)malloc(sizeof(std::string))
call ($arg0)->basic_string()
# 'assign' returns *this; casting return to void avoids printing of the struct.
call (void)( ($arg0)->assign($arg1) )
end

It works great:

(gdb) newstr $foo "hello world"
(gdb) p $foo->c_str()
$57 = 0xb22e388 "hello world"

I use newstr in other custom gdb commands, so for tidyness I also created delstr:

define delstr
call ($arg0)->~basic_string($arg0)
call free($arg0)
set ($arg0)=(void*)0
end

It works, but the destructor call produces an annoying message:

(gdb) delstr $foo
warning: Using non-standard conversion to match method std::string::~basic_string to supplied arguments
$62 = 0

Can I avoid the "non-standard conversion" message?  (I'm using gdb 7.10.)

Body:
TL;DR: Pass 0 to the destructor, instead of $foo.

define delstr
call ($arg0)->~basic_string(0)
#                           ^
call free($arg0)
set ($arg0)=(void*)0
end

OK so what is going on... We can first check the signature of a destructor. It indeed takes an integer:

(gdb) p ((Foo*) 0)->~Foo
$1 = {void (Foo * const, int)} 0x555555554c00 <Foo::~Foo()>

(gdb) p (('std::__cxx11::string'*) 0)->~basic_string
$2 = {void (std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > * const, int)} 0x7ffff7b75010 <std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()>

(gdb) ptype Foo
type = struct Foo {
  public:
    Foo(void);
    ~Foo(int);
}

So the "non-standard conversion" warning is about converting a pointer to an integer, which is indeed non-standard. (The warning has nothing to do with the destructor.)

But for what profound reason do we need to pass an extra integer to the destructor in the first place? Turns out it is … a bug  A GCC issue (as of gcc 6.3.0) actually, because the same program compiled using clang (as of clang 3.8.1) does not have that extra int argument.

One should know that, in the Italium C++ ABI there are actually three destructors (D0, D1, D2).

GCC has an optimization -fdeclone-ctor-dtor which refactors the common parts of the three destructors into a "D4" destructor. This "D4" destructor takes an extra argument __in_chrg to determine which of D0/D1/D2 is the source, to know whether to call the virtual base destructors.

This "D4" destructor is somehow also used as the canonical destructor declaration of the DWARF symbol generated by GCC. If we check the GCC issue linked from the GDB bug report, the reason of using "D4" is because the GCC developers didn't want to pick which of D0, D1 or D2 to bless.

And the result is an extra int which GDB didn't ignore.

The __in_chrg value is 2 when the destructor is capable of "complete object destruction" (D0, D1), and 0 when it is just a "base object destructor" (D2). Since a std::string does not have virtual base classes, you should just pass 0 to that argument.

Note: I used this program to test against GDB:

#include <string>
#include <iostream>
std::string aa;
struct Foo {
        Foo() { std::cout << "Constructing: this = " << this << std::endl; }
        ~Foo() { std::cout << "Destroying: this = " << this << std::endl; }
};
int main() {
        Foo foo;
        return 0;
}


问:
Nodejs -- req and res arguments of callback function in createServer()

I am confused about 'parser = this' mean, because I can't find there is calling about this function, so what 'this' mean in this native code?

This is the link of github: https://github.com/nodejs/node/blob/v0.12/lib/_http_common.js

答:
I find the basic c language, these are called by itself when you put into httpParse free list
enter image description here
This is the address of github: https://github.com/joyent/http-parser</p>


问:
java.sql.SQLException: No value specified for parameter 1 error
I looked for this error in other stackoverflow problems but basically the solutions given are the same thing as my code I don't know what I'm doing wrong.</p>

```<code>public List<ProjectUser> findProjectUserId(int id){
     List <ProjectUser> users= new ArrayList<>();
     ProjectUser projectuser= null;
     try {
         String req="select * from projectuser where project=?";
         PreparedStatement ps= cnx.getConnection().prepareStatement(req);
         ResultSet rs= ps.executeQuery();
         ps.setInt(1,id);
         while (rs.next()){
            projectuser= new ProjectUser(rs.getInt(1), rs.getInt(2), rs.getInt(3));
             users.add(projectuser);
         }
     } catch (SQLException ex){
         ex.printStackTrace();
     }
     return users;
}
</code>```

答:
You are executing the query before setting the parameters of the PreparedStatement. That is why your code is giving Exception. The order of the statements should be</p>

```<code>ps.setInt(1,id);
ResultSet rs= ps.executeQuery();
</code>```

Body:
I looked for this error in other stackoverflow problems but basically the solutions given are the same thing as my code I don't know what I'm doing wrong.

public List<ProjectUser> findProjectUserId(int id){
     List <ProjectUser> users= new ArrayList<>();
     ProjectUser projectuser= null;
     try {
         String req="select * from projectuser where project=?";
         PreparedStatement ps= cnx.getConnection().prepareStatement(req);
         ResultSet rs= ps.executeQuery();
         ps.setInt(1,id);
         while (rs.next()){
            projectuser= new ProjectUser(rs.getInt(1), rs.getInt(2), rs.getInt(3));
             users.add(projectuser);
         }
     } catch (SQLException ex){
         ex.printStackTrace();
     }
     return users;
}

Body:
You are executing the query before setting the parameters of the PreparedStatement. That is why your code is giving Exception. The order of the statements should be

ps.setInt(1,id);
ResultSet rs= ps.executeQuery();


问:
Count the text in a listbox together
Hello Stackoverflow community,
I have the following problem.
I created a listbox with this format (the data is always different):

```<code>item1
item2
item1
item2
item1
item3
item1
</code>```

but now i want to sort this and count it together like that:

```<code>4 x item1
2 x item2
1 x item3
</code>```

I just can't think of a method that would be able to do this with a dynamic text. Thanks for all your help in advance.

答:
Let's say your listBox content consists of strings only or they are distinguishable by their ToString().

You may create a dictionary and add each item to it. Then count them in the value field:

```<code>Dictionary<string, int> counts = new Dictionary<string, int>();
foreach(var i in listBox1.Items)
{
    if (!counts.ContainsKey(i.ToString()))
        counts.Add(i.ToString(), 0);
        counts[i.ToString()]++;
    }
}
</code>```

You may then print them all out similar to this (latest C# version required):

```<code>foreach (KeyValuePair<string, int> entry in counts)
    Console.WriteLine($"{entry.Value}x {entry.Key}");
</code>```

You may find your own solution to sorting the data from the dictionary. Please, be aware of the fact that the data inside of the dictionary cannot be sorted inside of this class, as dictionaries do not keep track of any order. There is however an approach to this with Linq: StackOverflow: how-do-you-sort-a-dictionary-by-value

Title: Count the text in a listbox together

Body:
Hello Stackoverflow community,
I have the following problem.
I created a listbox with this format (the data is always different):

item1
item2
item1
item2
item1
item3
item1

but now i want to sort this and count it together like that:

4 x item1
2 x item2
1 x item3

I just can't think of a method that would be able to do this with a dynamic text. Thanks for all your help in advance.

Body:
Let's say your listBox content consists of strings only or they are distinguishable by their ToString().

You may create a dictionary and add each item to it. Then count them in the value field:

Dictionary<string, int> counts = new Dictionary<string, int>();
foreach(var i in listBox1.Items)
{
    if (!counts.ContainsKey(i.ToString()))
        counts.Add(i.ToString(), 0);
        counts[i.ToString()]++;
    }
}

You may then print them all out similar to this (latest C# version required):

foreach (KeyValuePair<string, int> entry in counts)
    Console.WriteLine($"{entry.Value}x {entry.Key}");

You may find your own solution to sorting the data from the dictionary. Please, be aware of the fact that the data inside of the dictionary cannot be sorted inside of this class, as dictionaries do not keep track of any order. There is however an approach to this with Linq: StackOverflow: how-do-you-sort-a-dictionary-by-value