问:
Hide Output if output is less than zero
I finished a savings calculator but I realized that I want to display a different div with alternative options if the savings output is a negative number. I have tried a few different things and nothings has worked. I am newer to jQuery and I am having a bit of trouble. Any help is appreciated. Below is my code:</p>

```<code>    function toCurrency(str) {
    let ret = parseFloat(str[0] === '$' ? str.substr(1) : str).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (!isNaN(ret))
    return str;
    return ret;
}

function calculate(){
 var savingsVal = (jQuery('#savingsVal').val());
 var totalSavings = 0;
 var regType = (jQuery('#reg-type').val());

 if (filterValues(savingsVal)) {
 totalSavings = savingsVal * 0.15 * 3 - regType * 3;
 }
 jQuery('#totalSavings').val('$' + toCurrency(totalSavings));
 }

if (totalSavings < 0) {
    jQuery("#negative-numbers").show();
}

else{
  jQuery("#negative-numbers").hide();
}

 function filterValues(eVal){
 return true;

 }

 jQuery('.results-area').hide();

 jQuery('#calculator').submit(function(e){
 e.preventDefault();
 calculate();
 jQuery('.results-area').show("slow");
 });
</code>```

答:
You have some logical errors in your code that are preventing it from working as expected. The number 1 mistake, is common, serious and preventable:

Forgetting to declare a variable.

In your code, totalSavings is used in two scopes but one of them neglects to declare it.

To prevent this error, and to provide enhanced performance and security, always start every script with "use strict"; to enable ES5 strict mode.

Under strict mode, undeclared variables throw an error.

Furthermore, the toggling error itself was due to placing your if, if (totalSavings < 0) statement in global scope instead of within the calculate function or the event handler itself.

Coupled with failing to declare the totalSavings variable, making the condition initially false as well, undefined is neither greater than nor less than 0.

I have corrected these errors in the code below.

'use strict';
(function() {
  var totalSavings = 0;

  function toCurrency(value) {
    let result = parseFloat(
      value[0] === '$' ? value.substr(1) : value
    ).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    return isNaN(result) ? value : result;

  }

  function calculate() {
    var savingsVal = jQuery('#savingsVal').val();
    var totalSavings = 0;
    var regType = jQuery('#reg-type').val();

    if (filterValues(savingsVal)) {
      totalSavings = savingsVal * 0.15 * 3 - regType * 3;
    }

    return totalSavings;
  }

  function filterValues(eVal) {
    return true;
  }

  jQuery('#calculator').click(function(e) {
    e.preventDefault();
    totalSavings = calculate();
    jQuery('.results-area').show("slow");
    jQuery('#totalSavings').text('$' + toCurrency(totalSavings));

    if (totalSavings < 0) {
      jQuery('#negative-numbers')
        .show()
        .find('#negative-value')
        .text(totalSavings)
        .show();
      jQuery('.results-area').hide();
    } else {
      jQuery('#negative-numbers').hide();
    }
  });
}());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<label>Reg Type</label>
<input type="text" id="reg-type">
<br>
<label>Savings</label>
<input type="text" id="savingsVal">
<br>
<button id="calculator">Submit</button>

<div></div>
<div id="negative-numbers">Negative Numbers
  <div id="negative-value"></div>
</div>
<div class="results-area">Results

  <div id="totalSavings">Total </div>
</div></code>```

Title: Hide Output if output is less than zero

Body:
I finished a savings calculator but I realized that I want to display a different div with alternative options if the savings output is a negative number. I have tried a few different things and nothings has worked. I am newer to jQuery and I am having a bit of trouble. Any help is appreciated. Below is my code:

    function toCurrency(str) {
    let ret = parseFloat(str[0] === '$' ? str.substr(1) : str).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (!isNaN(ret))
    return str;
    return ret;
}

function calculate(){
 var savingsVal = (jQuery('#savingsVal').val());
 var totalSavings = 0;
 var regType = (jQuery('#reg-type').val());

 if (filterValues(savingsVal)) {
 totalSavings = savingsVal * 0.15 * 3 - regType * 3;
 }
 jQuery('#totalSavings').val('$' + toCurrency(totalSavings));
 }

if (totalSavings < 0) {
    jQuery("#negative-numbers").show();
}

else{
  jQuery("#negative-numbers").hide();
}

 function filterValues(eVal){
 return true;

 }

 jQuery('.results-area').hide();

 jQuery('#calculator').submit(function(e){
 e.preventDefault();
 calculate();
 jQuery('.results-area').show("slow");
 });

Body:
You have some logical errors in your code that are preventing it from working as expected. The number 1 mistake, is common, serious and preventable:

Forgetting to declare a variable.

In your code, totalSavings is used in two scopes but one of them neglects to declare it.

To prevent this error, and to provide enhanced performance and security, always start every script with "use strict"; to enable ES5 strict mode.

Under strict mode, undeclared variables throw an error.

Furthermore, the toggling error itself was due to placing your if, if (totalSavings < 0) statement in global scope instead of within the calculate function or the event handler itself.

Coupled with failing to declare the totalSavings variable, making the condition initially false as well, undefined is neither greater than nor less than 0.

I have corrected these errors in the code below.

'use strict';
(function() {
  var totalSavings = 0;

  function toCurrency(value) {
    let result = parseFloat(
      value[0] === '$' ? value.substr(1) : value
    ).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    return isNaN(result) ? value : result;

  }

  function calculate() {
    var savingsVal = jQuery('#savingsVal').val();
    var totalSavings = 0;
    var regType = jQuery('#reg-type').val();

    if (filterValues(savingsVal)) {
      totalSavings = savingsVal * 0.15 * 3 - regType * 3;
    }

    return totalSavings;
  }

  function filterValues(eVal) {
    return true;
  }

  jQuery('#calculator').click(function(e) {
    e.preventDefault();
    totalSavings = calculate();
    jQuery('.results-area').show("slow");
    jQuery('#totalSavings').text('$' + toCurrency(totalSavings));

    if (totalSavings < 0) {
      jQuery('#negative-numbers')
        .show()
        .find('#negative-value')
        .text(totalSavings)
        .show();
      jQuery('.results-area').hide();
    } else {
      jQuery('#negative-numbers').hide();
    }
  });
}());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<label>Reg Type</label>
<input type="text" id="reg-type">
<br>
<label>Savings</label>
<input type="text" id="savingsVal">
<br>
<button id="calculator">Submit</button>

<div></div>
<div id="negative-numbers">Negative Numbers
  <div id="negative-value"></div>
</div>
<div class="results-area">Results

  <div id="totalSavings">Total </div>
</div>


来源: stackexchange

问:
Two inserts, two tables, one PDO transaction, double SQL result
EDIT I dont believe this is a duplucatie question of that mysqli question, and do believe it deserves to be a question on its own.

So I'm trying to get some  data from a form into the correct tables, using PDO Transactions (this is new to me).

The SQL inserts correctly into the tables, but double. So I end up with a double result in each table.

I read about there being an issue with the page refreshing twice because of the favicon, or this being a browser issue. But even after a restart of the server and multiple browsers tested, I think it's just my code.

```<code>try {
    //$mysqli->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $mysqli->begin_transaction();

    $stmt = $mysqli->prepare("INSERT $table1 (status, customer, product, ord_num, return_code, dop, sn, problem_descr, repair_descr, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssss", $status, $customer, $product, $ord_num, $return_code, $dop, $sn, $problem_descr, $repair_descr, $comments);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $stmt = $mysqli->prepare("INSERT $table2 (part1, part2, part3, part4, part5, part6, part7, part8, part9, part10, part11, part12, part13, part14, part15, part16, part17, part18, part19, part20) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssssssssssssss", $part1, $part2, $part3, $part4, $part5, $part6, $part7, $part8, $part9, $part10, $part11, $part12, $part13, $part14, $part15, $part16, $part17, $part18, $part19, $part20);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $mysqli->commit();
} catch(PDOException $ex) {
    //Something went wrong, rolback!
    $mysqli->rollBack();
    echo $ex-getMessage();
}
</code>```

答:
This needs to change:

```<code>$stmt->execute();
        if (!$stmt->execute()) {
</code>```

just

```<code>if (!$stmt->execute()) {
</code>```

is enough.

Once you run $stmt->execute(); ones and then again put it inside the if statement to see if it returns true, you endup executing the statement twice. For which you are seeing the double entries.

ContentLicense: CC BY-SA 3.0

Body:
EDIT I dont believe this is a duplucatie question of that mysqli question, and do believe it deserves to be a question on its own.

So I'm trying to get some  data from a form into the correct tables, using PDO Transactions (this is new to me).

The SQL inserts correctly into the tables, but double. So I end up with a double result in each table.

I read about there being an issue with the page refreshing twice because of the favicon, or this being a browser issue. But even after a restart of the server and multiple browsers tested, I think it's just my code.

try {
    //$mysqli->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $mysqli->begin_transaction();

    $stmt = $mysqli->prepare("INSERT $table1 (status, customer, product, ord_num, return_code, dop, sn, problem_descr, repair_descr, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssss", $status, $customer, $product, $ord_num, $return_code, $dop, $sn, $problem_descr, $repair_descr, $comments);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $stmt = $mysqli->prepare("INSERT $table2 (part1, part2, part3, part4, part5, part6, part7, part8, part9, part10, part11, part12, part13, part14, part15, part16, part17, part18, part19, part20) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssssssssssssss", $part1, $part2, $part3, $part4, $part5, $part6, $part7, $part8, $part9, $part10, $part11, $part12, $part13, $part14, $part15, $part16, $part17, $part18, $part19, $part20);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $mysqli->commit();
} catch(PDOException $ex) {
    //Something went wrong, rolback!
    $mysqli->rollBack();
    echo $ex-getMessage();
}

Body:
This needs to change:

$stmt->execute();
        if (!$stmt->execute()) {

just

if (!$stmt->execute()) {

is enough.

Once you run $stmt->execute(); ones and then again put it inside the if statement to see if it returns true, you endup executing the statement twice. For which you are seeing the double entries.


问:
Make VSCode Variables have Colour
I would like to make variables displayed with colours.

This is how it looks:

This is how I want it to be:

Looking through here, I cannot find any settings that allow me to change this.

答:
Try this setting in your settings.json:

```<code> "editor.tokenColorCustomizations": {
    "variables": "#f00"
 },
</code>```

There are a few such simple token color customizations available: variables, comments, keywords, functions, numbers, strings and types.  Those only allow setting the color though.

If you use  "textMateRules" you can set more properties.  For example:

```<code>"editor.tokenColorCustomizations": {
  "textMateRules": [
    {
      "scope": "comment",
      "settings": {
        "fontStyle": "italic",
        "foreground": "#C69650"
      }
    }
  ]
},
</code>```

Title: Make VSCode Variables have Colour

Body:
Try this setting in your settings.json:

 "editor.tokenColorCustomizations": {
    "variables": "#f00"
 },

There are a few such simple token color customizations available: variables, comments, keywords, functions, numbers, strings and types.  Those only allow setting the color though.

If you use  "textMateRules" you can set more properties.  For example:

"editor.tokenColorCustomizations": {
  "textMateRules": [
    {
      "scope": "comment",
      "settings": {
        "fontStyle": "italic",
        "foreground": "#C69650"
      }
    }
  ]
},


问:
How to take out certain elements from a pdb file
I am trying to take out certain columns from a pdb file. I already have taken out all lines that start out with ATOM in my code. For some reason my sub functions are not working and I do not know where or how to call them.
My code is:</p>

```<code>open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
 while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

my $atomcount = @newlines;
#print "@newlines\n";
#print "$atomcount\n";

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters

sub atomfreq {
    foreach my $record1(@newlines) {
      my $element = substr($record1, 76, 2);
      print "$element\n";
      return;
    }
}

################################################################
#This function will take out the residue name from each line
#The element is from column 18 and contains 3 letters

sub resfreq {
    foreach my $record2(@newlines) {
      my $residue = substr($record2, 17, 3);
      print "$residue\n";
      return;
    }
}
</code>```

答:
You can just call them right under your other code like this:</p>

```<code>atomfreq();
resfreq();
</code>```

Body:
I am trying to take out certain columns from a pdb file. I already have taken out all lines that start out with ATOM in my code. For some reason my sub functions are not working and I do not know where or how to call them.
My code is:

open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
 while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

my $atomcount = @newlines;
#print "@newlines\n";
#print "$atomcount\n";

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters

sub atomfreq {
    foreach my $record1(@newlines) {
      my $element = substr($record1, 76, 2);
      print "$element\n";
      return;
    }
}

################################################################
#This function will take out the residue name from each line
#The element is from column 18 and contains 3 letters

sub resfreq {
    foreach my $record2(@newlines) {
      my $residue = substr($record2, 17, 3);
      print "$residue\n";
      return;
    }
}

Body:
You can just call them right under your other code like this:

atomfreq();
resfreq();


问:
ICO takes forever to load
How do I tell a webpage that I don't want an ICO so it doesn't waste loadtime looking for it??

```<code><link rel="icon" type="images/png" href="" />
</code>```

If it's omitted, then it looks too!

答:
you can add the following to your apache config</p>

```<code>Redirect 404 /favicon.ico
</code>```

ContentLicense: CC BY-SA 2.5

Title: ICO takes forever to load

Body:
How do I tell a webpage that I don't want an ICO so it doesn't waste loadtime looking for it??

<link rel="icon" type="images/png" href="" />

If it's omitted, then it looks too!

Body:
you can add the following to your apache config

Redirect 404 /favicon.ico


问:
Split aggregate root to avoid concurrency conflicts
Readying more and more about Aggregate Roots, specially I-DDD from Vaughn Vernon, I came with a question about concurrency.

A system is accessed by a number of users concurrently. The (current) Core Domain is about "enrolments" to an educational center, so there is a Student entity representing the main customer of the business. Student is an Aggregate Root and has, of course, a lot of information.

Let's say a Student has a PersonalAddress and AcademicInformation (past schools, grades, ...) both modeled as Value Objects inside the Aggregate, and -for the sake of argument- there is no other Entity in the same Aggregate. The Student Aggregate uses optimistic concurrency with something like version property in the Entity, so any change to its data will increment that version.

The thing is if two different users try to modify the PersonalAddress and the AcademicInformation of the same Student at the same time, one of those attempts will fail, even though address and academic information are totally unrelated; while both are VO, they belong to the same Aggregate.

I thought I could split the Aggregate to avoid concurrency conflicts since there is no truly invariants related to PersonalAddress and AcademicInformation besides both "belongs" to the same Student. But those are VO without identity for themselves. I would have to create another Entity and put both in different Aggregate Roots, both containing pieces of information related to the same student, so those can be modified concurrently.

So the questions are:

How could avoid the concurrency conflict of modifying unrelated information of the same Entity (Student) that is modeled as Value Objects (PersonalAddress, AcademicInformation)?

Is a "good approach"™ to split the Student Aggregate in two or more different Aggregate Roots, as I explained before?

Even if this particular situation could be solved by other means (I would be grateful if share that), how is that problem addressed in a more general perspective?

I think all depends in how frequently users try to modify the information concurrently and, based on that, decide if split the aggregate is worthwhile... but I don't know.

Thank you so much.

答:
1) You can use optimistic concurrency in other way: based on old values, not on version number. E.g. command to change Student should looks like new ChaneStudentCmd { StudentId = ...; OldAddressStreet = "xxx"; NewAddressStreet = "yyy" }, implementation should ensure that current strret is "xxx" before changing it. If it is not "xxx" concurrency exception should be thrown.

2) I think there are no reasons to split the aggregate.

3) The general approach can be using more specific update commands, not simple "update all student properties". Business layer should have information about that exacly user wants to update. With this information it will be able to process update gracefully, in consideration of concurrency and other demands.


问:
Issue with taking out a segment of an character array in C
I have a source.txt file here:
https://palomar.blackboard.com/bbcswebdav/pid-1168887-dt-content-rid-3710280_1/courses/2177-70219/payfile%281%29.txt

```<code>void readData() { // Scans each line from the .txt and puts each line into an element in the array
    FILE *fp;
    fp = fopen("info.txt", "r");

    char Line[100];
    int i = 0;

    while (!feof(fp)) {

        char agetemp[3];
        char tenuretemp[2];
        char salarytemp[7];

        fgets(Line, 100, fp);
        strsub(Line, employee[i].first, 0, 6);
        strsub(Line, employee[i].initial, 8, 9);
        strsub(Line, employee[i].last, 10, 18);
        strsub(Line, employee[i].street, 20, 35);
        strsub(Line, employee[i].city, 37, 46);
        strsub(Line, employee[i].state, 49, 50);
        strsub(Line, employee[i].zip, 52, 56);
        strsub(Line, employee[i].sex, 61, 61);

        strsub(Line, agetemp, 58, 59);
        employee[i].age = atoi(agetemp); // converted the age column to an int

        strsub(Line, tenuretemp, 63, 63);
        employee[i].tenure = atoi(tenuretemp); // converted tenure column to an int

        strsub(Line, salarytemp, 65, 70);
        employee[i].salary = atof(salarytemp); // converted the salary column to float

        i++;
    }
}
</code>```

And my assignment is giving me a user-made function, called strsub, which is defined here:

```<code>void strsub(char buf[], char sub[], int start, int end) { // function template for strsub
    int i, j;

    for (j = 0, i = start; i <= end; i++, j++) {
        sub[j] = buf[i];
    }
    sub[j] = '\0';
}
</code>```

So basically when I scan the source .txt file the strsub function is singling out particular segments and putting them into it's respective array of structure. It works fine for the most part, for example when I print out employee[2].city:

https://prnt.sc/hl25n7

Nothing is wrong there. However, when I try to print out the employee[i].first variable, it clumps together a bunch of letters, more than what I told it to do, and I don't know why. Here's a picture of when I try to print out employee[2].first:

https://prnt.sc/hl26gt

In the readData(), I only told it to go from 0 to 6, why is it taking in more input than what I told it do rather than just the first 7 characters?

Oh, and also this is my structure right here; I put it in a separate header file:

```<code>struct info {
    char first[7];
    char initial[1];
    char last[9];
    char street[16];
    char city[11];
    char state[2];
    char zip[5];
    int age;
    char sex[1];
    int tenure;
    double salary;
};
</code>```

答: We need to see the record structure of employee.  If first is defined as char[7] then it does not have enough memory to hold 0-6 (which is 7 char) + null termination.  Also, if initial is 1 char, your function is coping 2 char if input is 8, 9.</p>

Body:
I have a source.txt file here:
https://palomar.blackboard.com/bbcswebdav/pid-1168887-dt-content-rid-3710280_1/courses/2177-70219/payfile%281%29.txt

void readData() { // Scans each line from the .txt and puts each line into an element in the array
    FILE *fp;
    fp = fopen("info.txt", "r");

    char Line[100];
    int i = 0;

    while (!feof(fp)) {

        char agetemp[3];
        char tenuretemp[2];
        char salarytemp[7];

        fgets(Line, 100, fp);
        strsub(Line, employee[i].first, 0, 6);
        strsub(Line, employee[i].initial, 8, 9);
        strsub(Line, employee[i].last, 10, 18);
        strsub(Line, employee[i].street, 20, 35);
        strsub(Line, employee[i].city, 37, 46);
        strsub(Line, employee[i].state, 49, 50);
        strsub(Line, employee[i].zip, 52, 56);
        strsub(Line, employee[i].sex, 61, 61);

        strsub(Line, agetemp, 58, 59);
        employee[i].age = atoi(agetemp); // converted the age column to an int

        strsub(Line, tenuretemp, 63, 63);
        employee[i].tenure = atoi(tenuretemp); // converted tenure column to an int

        strsub(Line, salarytemp, 65, 70);
        employee[i].salary = atof(salarytemp); // converted the salary column to float

        i++;
    }
}

And my assignment is giving me a user-made function, called strsub, which is defined here:

void strsub(char buf[], char sub[], int start, int end) { // function template for strsub
    int i, j;

    for (j = 0, i = start; i <= end; i++, j++) {
        sub[j] = buf[i];
    }
    sub[j] = '\0';
}

So basically when I scan the source .txt file the strsub function is singling out particular segments and putting them into it's respective array of structure. It works fine for the most part, for example when I print out employee[2].city:

https://prnt.sc/hl25n7

Nothing is wrong there. However, when I try to print out the employee[i].first variable, it clumps together a bunch of letters, more than what I told it to do, and I don't know why. Here's a picture of when I try to print out employee[2].first:

https://prnt.sc/hl26gt

In the readData(), I only told it to go from 0 to 6, why is it taking in more input than what I told it do rather than just the first 7 characters?

Oh, and also this is my structure right here; I put it in a separate header file:

struct info {
    char first[7];
    char initial[1];
    char last[9];
    char street[16];
    char city[11];
    char state[2];
    char zip[5];
    int age;
    char sex[1];
    int tenure;
    double salary;
};


问:
HTML: Why float:left is required when children blocks width sum equals parent width
Sorry if my question is duplicate, I just could not choose the appropriate search request.

So, consider the parent
 with two inline-block children, each one has width: 50%. If do not setup overflow: hidden for parent and float: left for children, children will not form one row inside the parent.

But why? Why 50% + 50% is not equal one full row? Why we need the float?

答:
The most common scenario is because you have white spaces between the chlidren nodes:

#container{
  background: red;
  height: 50px;
}
#container div{
  width: 50%;
  display: inline-block;
  background: green;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div></div>
  <div></div>
</div></code>```

The solution is to remove the whitespace:

#container{
  background: red;
  height: 50px;
}
#container div{
  width: 50%;
  display: inline-block;
  background: green;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div></div><!--
  --><div></div>
</div></code>```

The second most common scenario is due to the preset margin usually found in browsers:

#container{
  background: red;
  height: 50px;
}

#container div{
  width: 50%;
  display: inline-block;
  background: green;
  height: 100%;
  margin: 8px;  /* browser default */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div></div><!--
  --><div></div>
</div></code>```

Override it with margin: 0 to fix it.

Body:
The most common scenario is because you have white spaces between the chlidren nodes:

#container{
  background: red;
  height: 50px;
}
#container div{
  width: 50%;
  display: inline-block;
  background: green;
  height: 100%;
}

<div id="container">
  <div></div>
  <div></div>
</div>

The solution is to remove the whitespace:

#container{
  background: red;
  height: 50px;
}
#container div{
  width: 50%;
  display: inline-block;
  background: green;
  height: 100%;
}

<div id="container">
  <div></div><!--
  --><div></div>
</div>

The second most common scenario is due to the preset margin usually found in browsers:

#container{
  background: red;
  height: 50px;
}

#container div{
  width: 50%;
  display: inline-block;
  background: green;
  height: 100%;
  margin: 8px;  /* browser default */
}

<div id="container">
  <div></div><!--
  --><div></div>
</div>

Override it with margin: 0 to fix it.


问:
How to select all columns not containing a certain substring in Postgresql?
If I have a table with column names like that:

```<code>name,
name_raw,
item,
item_raw,
message,
message_raw
...
... etc.
</code>```

How can I select every column that does not end with _raw dynamically?

Is something like this:

```<code>SELECT
   [SOME REGEX LOGIC HERE]
FROM
   mytable
</code>```

or similar possible?

答:
If you have so many columns that you cannot write a (static) query, you probably have to change the schema of your db.

If you cannot change the schema, here's a quick and dirty solution that utilizes postgresql's JSON capabilities. It does not return a traditional table with multiple columns, instead it returns a single column that contains json objects which contain all the columns from the original table whose name ends with _raw.

```<code>SELECT (
    SELECT json_object_agg(key,value)
    FROM json_each(to_json(t))
    WHERE key ~ 'raw$'
) FROM mytable;
</code>```

The idea is convert every row from mytable to a JSON object and then use JSON functions to filter the members of the object.

Body:
If I have a table with column names like that:

name,
name_raw,
item,
item_raw,
message,
message_raw
...
... etc.

How can I select every column that does not end with _raw dynamically?

Is something like this:

SELECT
   [SOME REGEX LOGIC HERE]
FROM
   mytable

or similar possible?

Body:
If you have so many columns that you cannot write a (static) query, you probably have to change the schema of your db.

If you cannot change the schema, here's a quick and dirty solution that utilizes postgresql's JSON capabilities. It does not return a traditional table with multiple columns, instead it returns a single column that contains json objects which contain all the columns from the original table whose name ends with _raw.

SELECT (
    SELECT json_object_agg(key,value)
    FROM json_each(to_json(t))
    WHERE key ~ 'raw$'
) FROM mytable;

The idea is convert every row from mytable to a JSON object and then use JSON functions to filter the members of the object.


问:
Plot histogram with colors taken from colormap
I want to plot a simple 1D histogram where the bars should follow the color-coding of a given colormap.

Here's an MWE:

```<code>import numpy as n
import matplotlib.pyplot as plt

# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

# This is  the colormap I'd like to use.
cm = plt.cm.get_cmap('RdYlBu_r')

# Plot histogram.
n, bins, patches = plt.hist(data, 25, normed=1, color='green')

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

which outputs this:

Instead of the color being green for the entire histogram, I'd like the columns to follow a color-coding given by the colormap defined in cm and the values of the bins. This would mean that bins closer to zero (not in height but in position) should look bluer and those closer to one redder, according to the chosen colormap RdYlBu_r.

Since plt.histo doesn't take a cmap argument I don't know how to tell it to use the colormap defined in cm.

答:
I like Bas Swinckels answer, but given that the colormap cm take as parameter a value between 0 and 1, a simpler algorithm would be like this</p>

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

Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

cm = plt.cm.RdBu_r

n, bins, patches = plt.hist(data, 25, normed=1, color='green')
for i, p in enumerate(patches):
    plt.setp(p, 'facecolor', cm(i/25)) # notice the i/25

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

Body:
I want to plot a simple 1D histogram where the bars should follow the color-coding of a given colormap.

Here's an MWE:

import numpy as n
import matplotlib.pyplot as plt

# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

# This is  the colormap I'd like to use.
cm = plt.cm.get_cmap('RdYlBu_r')

# Plot histogram.
n, bins, patches = plt.hist(data, 25, normed=1, color='green')

plt.show()

which outputs this:

Instead of the color being green for the entire histogram, I'd like the columns to follow a color-coding given by the colormap defined in cm and the values of the bins. This would mean that bins closer to zero (not in height but in position) should look bluer and those closer to one redder, according to the chosen colormap RdYlBu_r.

Since plt.histo doesn't take a cmap argument I don't know how to tell it to use the colormap defined in cm.

Body:
I like Bas Swinckels answer, but given that the colormap cm take as parameter a value between 0 and 1, a simpler algorithm would be like this

import matplotlib.pyplot as plt

Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

cm = plt.cm.RdBu_r

n, bins, patches = plt.hist(data, 25, normed=1, color='green')
for i, p in enumerate(patches):
    plt.setp(p, 'facecolor', cm(i/25)) # notice the i/25

plt.show()


问:
Need help comparing arrays for lottery simulation
I probably messed up somewhere here, but this is what I have so far. So how do I compare 6 random generated Winning Numbers for lottery to the User inputed 6 numbers. The instructions says to "display the winning numbers, player’s numbers, and how many numbers matched. For instance, if your winning numbers are 3,5,9,1,4,7 and your player’s numbers are 2,5, 7,1, 9,8, then you have two matches (5 and 1). 5 is on the second position and 1 is on the fourth position in both arrays." Also, I tried to generate the 6 random Winning Numbers using randomInts, but not sure if I was supposed to use "i < list.Length" or something else. Any help appreciated. </p>

```<code>    static void Main(string[] args)
    {
        //array declarations
        const int SIZE = 6;
        int[] myLottery = new int[SIZE];
        int winning;
        int player;

        //methods call
        FillLottery(myLottery);
        PrintLottery(myLottery);

    }
    //generate 6 random numbers to fill the array
    static void FillLottery(int[] list)
    {
        Random randomInts = new Random();
        for (int i = 0; i < list.Length; i++)
        {
            list[i] = randomInts.Next(1, 10);
        }
    }
    //print the array
    static void PrintLottery(int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write($"{list[i],2}");
            if ((i + 1) % 10 == 0)
                Console.WriteLine();
        }
    }
</code>```

答:
I suggest separating this out into 3 separate for loops, and anif/else statements.

For time saving purposes I have set the max number that the lottery will generate to 1, although it can be easily changed.   It helps to do each step one by one and slowly build on it rather than doing all at the same time.  I've found this especially true when checking randomly generated numbers against user input.

To keep track of if there is a match between the user's number and the lottery number you can use a bool[].

```<code>static void Main(string[] args)
{
    //create size, and random object
    const int SIZE = 6;
    const int maxNumberInLottery = 1;
    Random rnd = new Random();
    //create int[] for the lot numbers
    int[] lotteryNumbers = new int[SIZE];
    string[] usersNumbers = new string[SIZE];

    //Create a bool[] for each case
    bool[] matches = new bool[SIZE];

    //Create lottery numbers
    for (int i = 0; i < SIZE; i++)
    {
        lotteryNumbers[i] = rnd.Next(1, maxNumberInLottery + 1);
    }
    //Read user input
    for(int j = 0; j < SIZE; j++)
    {
        Console.Write("Enter user pick #{0}:", j+1);
        string userInput = Console.ReadLine();
        usersNumbers[j] = userInput;
    }
    //check if matching
    for(int k = 0; k < SIZE; k++)
    {
        Console.Write("You entered: {0}. Lottery generated: {1}", usersNumbers[k], lotteryNumbers[k]);
        Console.WriteLine();
        try
        {

            if (int.Parse(usersNumbers[k]) == lotteryNumbers[k])
            {
                Console.WriteLine("       !MATCH!");
                matches[k] = true;
            }
        }
        catch
        {

        }
    }
    //check if the bool[] contains any false values at all
    if(!matches.Contains(false))
    {
        Console.WriteLine("WE HAVE A WINNER");
    }
    Console.ReadKey();
}
</code>```

Output:

```<code> Enter user pick#1:1
 Enter user pick#2:21
 Enter user pick#3:1
 Enter user pick#4:2
 Enter user pick#5:1
 Enter user pick#6:3

 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 21. Lottery generated: 1
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 2. Lottery generated: 1
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 3. Lottery generated: 1
</code>```

Output 2:

```<code> Enter user pick#1:1
 Enter user pick#2:1
 Enter user pick#3:1
 Enter user pick#4:1
 Enter user pick#5:1
 Enter user pick#6:1

 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
WE HAVE A WINNER!
</code>```

Hope this helps.

Body:
I probably messed up somewhere here, but this is what I have so far. So how do I compare 6 random generated Winning Numbers for lottery to the User inputed 6 numbers. The instructions says to "display the winning numbers, player’s numbers, and how many numbers matched. For instance, if your winning numbers are 3,5,9,1,4,7 and your player’s numbers are 2,5, 7,1, 9,8, then you have two matches (5 and 1). 5 is on the second position and 1 is on the fourth position in both arrays." Also, I tried to generate the 6 random Winning Numbers using randomInts, but not sure if I was supposed to use "i < list.Length" or something else. Any help appreciated.

    static void Main(string[] args)
    {
        //array declarations
        const int SIZE = 6;
        int[] myLottery = new int[SIZE];
        int winning;
        int player;

        //methods call
        FillLottery(myLottery);
        PrintLottery(myLottery);

    }
    //generate 6 random numbers to fill the array
    static void FillLottery(int[] list)
    {
        Random randomInts = new Random();
        for (int i = 0; i < list.Length; i++)
        {
            list[i] = randomInts.Next(1, 10);
        }
    }
    //print the array
    static void PrintLottery(int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write($"{list[i],2}");
            if ((i + 1) % 10 == 0)
                Console.WriteLine();
        }
    }

Body:
I suggest separating this out into 3 separate for loops, and anif/else statements.

For time saving purposes I have set the max number that the lottery will generate to 1, although it can be easily changed.   It helps to do each step one by one and slowly build on it rather than doing all at the same time.  I've found this especially true when checking randomly generated numbers against user input.

To keep track of if there is a match between the user's number and the lottery number you can use a bool[].

static void Main(string[] args)
{
    //create size, and random object
    const int SIZE = 6;
    const int maxNumberInLottery = 1;
    Random rnd = new Random();
    //create int[] for the lot numbers
    int[] lotteryNumbers = new int[SIZE];
    string[] usersNumbers = new string[SIZE];

    //Create a bool[] for each case
    bool[] matches = new bool[SIZE];

    //Create lottery numbers
    for (int i = 0; i < SIZE; i++)
    {
        lotteryNumbers[i] = rnd.Next(1, maxNumberInLottery + 1);
    }
    //Read user input
    for(int j = 0; j < SIZE; j++)
    {
        Console.Write("Enter user pick #{0}:", j+1);
        string userInput = Console.ReadLine();
        usersNumbers[j] = userInput;
    }
    //check if matching
    for(int k = 0; k < SIZE; k++)
    {
        Console.Write("You entered: {0}. Lottery generated: {1}", usersNumbers[k], lotteryNumbers[k]);
        Console.WriteLine();
        try
        {

            if (int.Parse(usersNumbers[k]) == lotteryNumbers[k])
            {
                Console.WriteLine("       !MATCH!");
                matches[k] = true;
            }
        }
        catch
        {

        }
    }
    //check if the bool[] contains any false values at all
    if(!matches.Contains(false))
    {
        Console.WriteLine("WE HAVE A WINNER");
    }
    Console.ReadKey();
}

Output:

 Enter user pick#1:1
 Enter user pick#2:21
 Enter user pick#3:1
 Enter user pick#4:2
 Enter user pick#5:1
 Enter user pick#6:3

 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 21. Lottery generated: 1
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 2. Lottery generated: 1
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 3. Lottery generated: 1

Output 2:

 Enter user pick#1:1
 Enter user pick#2:1
 Enter user pick#3:1
 Enter user pick#4:1
 Enter user pick#5:1
 Enter user pick#6:1

 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
 You entered: 1. Lottery generated: 1
        !MATCH!
WE HAVE A WINNER!

Hope this helps.


问:
rMarkdown trouble loading csv in R
I am trying to create an R markdown using the csv NFL_DATA.csv. However when I try to use knitr I get the error:

Error in nrow(NFL_DATA): object 'NFL_DATA' not found Calls:
  ... in_dir -> inline_exec -> withVisible -> eval -> eval ->
  nrow Execution halted

Here is the beginning of my code:

```<code>title: "XXXXXX"
author: "XXXXXX"
date: "December 11, 2017"
output: html_document
font-family: "Arial"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

---

## Introduction

XXXXXXXXXXXXX.

---

## Data

 We used the site data.world.com to find my data. The dataset can be retrieved at [NFL_DATA.csv](https://data.world/alice-c/nfl-fines-and-suspensions/workspace/file?filename=All+Penalties.csv).

There are `r nrow(NFL_DATA)` observations in the NFL data set and `r length(NFL_DATA)` variables. The variables are:

```{r echo=FALSE, comment=""}
names(NFL_DATA)
```
</code>```

When I run it the knitr does not work and gives an error message. However when I just run the last piece of code for names(NFL_DATA) it does work and it displays all the variable names. How can I resolve this?

答:
Try this after editing the code to point to wherever you stored the csv file locally. </p>

```<code>---
title: "NFL Fines and Suspensions Analysis"
author: "anAuthor"
date: "12/8/2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Read Data

Here is example code to read the nfl data

```{r readData,echo=FALSE}
nfldata <- read.csv("./data/All Penalties.csv",header=TRUE)
```

There are `r nrow(nfldata)` observations in the NFL data set and `r length(nfldata)` variables. The variables are:

```{r}
names(nfldata)
```
</code>```

Title: rMarkdown trouble loading csv in R

Body:
I am trying to create an R markdown using the csv NFL_DATA.csv. However when I try to use knitr I get the error:

Error in nrow(NFL_DATA): object 'NFL_DATA' not found Calls:
  ... in_dir -> inline_exec -> withVisible -> eval -> eval ->
  nrow Execution halted

Here is the beginning of my code:

title: "XXXXXX"
author: "XXXXXX"
date: "December 11, 2017"
output: html_document
font-family: "Arial"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

---

## Introduction

XXXXXXXXXXXXX.

---

## Data

 We used the site data.world.com to find my data. The dataset can be retrieved at [NFL_DATA.csv](https://data.world/alice-c/nfl-fines-and-suspensions/workspace/file?filename=All+Penalties.csv).

There are `r nrow(NFL_DATA)` observations in the NFL data set and `r length(NFL_DATA)` variables. The variables are:

```{r echo=FALSE, comment=""}
names(NFL_DATA)
```

When I run it the knitr does not work and gives an error message. However when I just run the last piece of code for names(NFL_DATA) it does work and it displays all the variable names. How can I resolve this?

Body:
Try this after editing the code to point to wherever you stored the csv file locally.

---
title: "NFL Fines and Suspensions Analysis"
author: "anAuthor"
date: "12/8/2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Read Data

Here is example code to read the nfl data

```{r readData,echo=FALSE}
nfldata <- read.csv("./data/All Penalties.csv",header=TRUE)
```

There are `r nrow(nfldata)` observations in the NFL data set and `r length(nfldata)` variables. The variables are:

```{r}
names(nfldata)
```


问:
python database insert formatting
I am trying to insert into a postgresql database in python 3.6 and currently am trying to execute this line

```<code>        cur.execute("INSERT INTO "+table_name+"(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)",(exchange_rate, buy_rate, sell_rate, date))
</code>```

but every time it tries to run the table name has ' ' around it so it turns out like INSERT INTO table_name('12', ..., ..., ...) ... instead of
INSERT INTO table_name(12, ..., ..., ...) ... how can I make the string formatter leave the quotes out or remove them or something? It is causing a syntax error around the 12 because it doesn't need the single quotes.

答:
Use the new string formatting to have a clean representation. %s is explicitly converting to a string, you don't want that. Format chooses the most fitting type for you.

```<code>table_name = "myTable"
exchange_rate = 1
buy_rate = 2
sell_rate = 3
date = 123
x = "INSERT INTO {0} (price, buy, sell, timestamp) VALUES ({1}, {2}, {2}, {4})".format(
    table_name, exchange_rate, buy_rate, sell_rate, date)

print x
>INSERT INTO myTable (price, buy, sell, timestamp) VALUES (1, 2, 2, 123)
</code>```

ContentLicense: CC BY-SA 4.0

Title: python database insert formatting

Body:
I am trying to insert into a postgresql database in python 3.6 and currently am trying to execute this line

        cur.execute("INSERT INTO "+table_name+"(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)",(exchange_rate, buy_rate, sell_rate, date))

but every time it tries to run the table name has ' ' around it so it turns out like INSERT INTO table_name('12', ..., ..., ...) ... instead of
INSERT INTO table_name(12, ..., ..., ...) ... how can I make the string formatter leave the quotes out or remove them or something? It is causing a syntax error around the 12 because it doesn't need the single quotes.

Body:
Use the new string formatting to have a clean representation. %s is explicitly converting to a string, you don't want that. Format chooses the most fitting type for you.

table_name = "myTable"
exchange_rate = 1
buy_rate = 2
sell_rate = 3
date = 123
x = "INSERT INTO {0} (price, buy, sell, timestamp) VALUES ({1}, {2}, {2}, {4})".format(
    table_name, exchange_rate, buy_rate, sell_rate, date)

print x
>INSERT INTO myTable (price, buy, sell, timestamp) VALUES (1, 2, 2, 123)


答:
or you can do like this

```<code>$run = $stmt->execute();
if (!$run) {
</code>```

We Just need to run the execute statement once.

Title: Two inserts, two tables, one PDO transaction, double SQL result

Body:
EDIT I dont believe this is a duplucatie question of that mysqli question, and do believe it deserves to be a question on its own.

So I'm trying to get some  data from a form into the correct tables, using PDO Transactions (this is new to me).

The SQL inserts correctly into the tables, but double. So I end up with a double result in each table.

I read about there being an issue with the page refreshing twice because of the favicon, or this being a browser issue. But even after a restart of the server and multiple browsers tested, I think it's just my code.

try {
    //$mysqli->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $mysqli->begin_transaction();

    $stmt = $mysqli->prepare("INSERT $table1 (status, customer, product, ord_num, return_code, dop, sn, problem_descr, repair_descr, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssss", $status, $customer, $product, $ord_num, $return_code, $dop, $sn, $problem_descr, $repair_descr, $comments);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $stmt = $mysqli->prepare("INSERT $table2 (part1, part2, part3, part4, part5, part6, part7, part8, part9, part10, part11, part12, part13, part14, part15, part16, part17, part18, part19, part20) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssssssssssssssss", $part1, $part2, $part3, $part4, $part5, $part6, $part7, $part8, $part9, $part10, $part11, $part12, $part13, $part14, $part15, $part16, $part17, $part18, $part19, $part20);
    $stmt->execute();
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $stmt->close();

    $mysqli->commit();
} catch(PDOException $ex) {
    //Something went wrong, rolback!
    $mysqli->rollBack();
    echo $ex-getMessage();
}

Body:
or you can do like this

$run = $stmt->execute();
if (!$run) {

We Just need to run the execute statement once.


问:
Why hbm2ddl.auto 'update' property is not working or how does it works?
I am new to Hibernate, As per my knowledge, when hbm2ddl.auto is set to 'update', it should create a table if its doesn't exist, it should create a new column automatically if the new 'property' tag for column is added in mapping file. Right?
But whenever i am trying to run my class, it is throwing "Table or view doesn't exist" instead of creating it. I am using hibernate v5.10

Here's my POC example i am trying to run. Thanks in advance.

Mapping file

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.nt.domain.Customer" table="CUSTOMER">
   <id name="custNo" length="10" type="int" column="CUSTNO"/>
   <property name="customerName" length="20" type="string" column="CUSTNAME"/>
   <property name="billAmt" length="10" type="int" column="BILLAMT"/>
  </class>
</hibernate-mapping>
</code>```

Configuration

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-// Hibernate/ Hibernate Configuration DTD 3.0 //EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:sys</property>
    <property name="connection.username">Asif123</property>
    <property name="connection.password">Asif123</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">true</property>
    <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
    <property name="hbm2ddl.auto">update</property>
    <mapping resource="com/nt/domain/customer.hbm.xml"/>
</session-factory>
</code>```

Main

```<code>package com.nt.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.nt.domain.Customer;

public class UpdateTest {
  public static void main(String[] args) {
    Configuration cfg = new Configuration().configure();
    SessionFactory factory = cfg.buildSessionFactory();
    Session ses= factory.openSession();
    Transaction tx= ses.beginTransaction();

    Customer customer = new Customer();
    customer.setCustNo(101);
    customer.setCustomerName("Asif");
    customer.setBillAmt(1245);

    ses.save(customer);
    tx.commit();

    ses.close();
    factory.close();
  }
}
</code>```

Customer

```<code>package com.nt.domain;

public class Customer {
  int custNo;
  String customerName;
  int billAmt;

//All getters and setters

}
</code>```

Exception

```<code>Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist

at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
....
</code>```

答: For anyone still searching for an answer, If you want to experience all the functionalities of "update" property like auto table creation, auto adding of columns (both case : if already not available), then go for the 5.0.1.Final version, it is the most stable version supporting them.</p>

Body:
I am new to Hibernate, As per my knowledge, when hbm2ddl.auto is set to 'update', it should create a table if its doesn't exist, it should create a new column automatically if the new 'property' tag for column is added in mapping file. Right?
But whenever i am trying to run my class, it is throwing "Table or view doesn't exist" instead of creating it. I am using hibernate v5.10

Here's my POC example i am trying to run. Thanks in advance.

Mapping file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.nt.domain.Customer" table="CUSTOMER">
   <id name="custNo" length="10" type="int" column="CUSTNO"/>
   <property name="customerName" length="20" type="string" column="CUSTNAME"/>
   <property name="billAmt" length="10" type="int" column="BILLAMT"/>
  </class>
</hibernate-mapping>

Configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-// Hibernate/ Hibernate Configuration DTD 3.0 //EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:sys</property>
    <property name="connection.username">Asif123</property>
    <property name="connection.password">Asif123</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">true</property>
    <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
    <property name="hbm2ddl.auto">update</property>
    <mapping resource="com/nt/domain/customer.hbm.xml"/>
</session-factory>

Main

package com.nt.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.nt.domain.Customer;

public class UpdateTest {
  public static void main(String[] args) {
    Configuration cfg = new Configuration().configure();
    SessionFactory factory = cfg.buildSessionFactory();
    Session ses= factory.openSession();
    Transaction tx= ses.beginTransaction();

    Customer customer = new Customer();
    customer.setCustNo(101);
    customer.setCustomerName("Asif");
    customer.setBillAmt(1245);

    ses.save(customer);
    tx.commit();

    ses.close();
    factory.close();
  }
}

Customer

package com.nt.domain;

public class Customer {
  int custNo;
  String customerName;
  int billAmt;

//All getters and setters

}

Exception

Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist

at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
....


问:
What is the fastest way to insert text into a
 element with javascript?
I am writing a long series of numbers to my document, one at a time. document.write() handles this fine, but using innerHTML with a
 element is sluggish, and rather quickly crashes my tab.  Is there some way to insert text into a
 element that is as fast as document.write?

答:
cloneNode and appendChild are quite fast on modern browsers.

If the JS takes too long consider using a queue and timer events (e.g. setInterval) to "yield" control periodically and prevent "script timeout" errors.

Perhaps there is a better way to approach the situation -- how many divs and why?

Title: What is the fastest way to insert text into a <div> element with javascript?


答: Because also the spaces take place. If you don't want to use floats you have almost two choices: commenting out the spaces between html tags or setting font-size: 0px on the parent and then back on the children.</p>

Title: HTML: Why float:left is required when children blocks width sum equals parent width

Body:
Sorry if my question is duplicate, I just could not choose the appropriate search request.

So, consider the parent
 with two inline-block children, each one has width: 50%. If do not setup overflow: hidden for parent and float: left for children, children will not form one row inside the parent.

But why? Why 50% + 50% is not equal one full row? Why we need the float?


问:
Verbose patch output with git merge similar to git commit
I have the following global setting in my .gitconfig file:

```<code>commit.verbose=true
</code>```

I really like seeing the file edits in vim when I'm writing a commit message. Is is also possible to have this functionality when using git merge?

The verbose flag in when merging doesn't have the same behavior as the commit verbose flag.

EDIT: Here are some screen shots to explain what I'm talking about:

Committing some edits to my develop branch and writing the message in vim could look something like. The commit.verbose flag is set to true as I noted above:

```<code>$ git commit -a
</code>```

Now attempting to merge the changes into another branch (i.e. master) results in the following:

```<code>$ git checkout master && git merge -v --no-ff develop
</code>```

I think the verbose option you see on the the git docs, and I used in the command above, and related to the output after a successful merge. In my example case the output was:

```<code>Merge made by the 'recursive' strategy.
 README | 2 ++
 1 file changed, 2 insertions(+)
</code>```

Bumping up the verbosity to level 5 doesn't do what I'm asking:

```<code>$ GIT_MERGE_VERBOSITY=5 git merge -v --no-ff develop
Merging:
1b4c630 Initial commit
virtual develop
found 1 common ancestor:
1b4c630 Initial commit
Merge made by the 'recursive' strategy.
 README | 2 ++
 1 file changed, 2 insertions(+)
</code>```

EDIT: The closest answer to my question is found in one of the answers listed HERE, essentially I get the entire diff if I execute the following before the merge

```<code>git diff <commit1> <commit2>
</code>```

EDIT 2: Another way to see the full merge commit the same as a commit message is by first merging the branch, and then running

```<code>git commit --amend
</code>```

This makes it possible to see the merge commit as a normal commit, at least with respect to seeing the full diff.

答:
I think you might be looking for merge.verbosity:

merge.verbosity

Controls the amount of output shown by the recursive merge strategy. Level 0 outputs nothing except a final error message if conflicts were detected. Level 1 outputs only conflicts, 2 outputs conflicts and file changes. Level 5 and above outputs debugging information. The default is level 2. Can be overridden by the GIT_MERGE_VERBOSITY environment variable.

https://git-scm.com/docs/git-merge#git-merge-mergeverbosity

Edit: based on your update with screenshots, I think I have to change my answer to: no, near as I can tell there is no way to do what you're asking with vanilla Git. Even fugitive (which I highly recommend BTW) doesn't really provide anything like that. I note this possibly relevant question.

Body:
I have the following global setting in my .gitconfig file:

commit.verbose=true

I really like seeing the file edits in vim when I'm writing a commit message. Is is also possible to have this functionality when using git merge?

The verbose flag in when merging doesn't have the same behavior as the commit verbose flag.

EDIT: Here are some screen shots to explain what I'm talking about:

Committing some edits to my develop branch and writing the message in vim could look something like. The commit.verbose flag is set to true as I noted above:

$ git commit -a

Now attempting to merge the changes into another branch (i.e. master) results in the following:

$ git checkout master && git merge -v --no-ff develop

I think the verbose option you see on the the git docs, and I used in the command above, and related to the output after a successful merge. In my example case the output was:

Merge made by the 'recursive' strategy.
 README | 2 ++
 1 file changed, 2 insertions(+)

Bumping up the verbosity to level 5 doesn't do what I'm asking:

$ GIT_MERGE_VERBOSITY=5 git merge -v --no-ff develop
Merging:
1b4c630 Initial commit
virtual develop
found 1 common ancestor:
1b4c630 Initial commit
Merge made by the 'recursive' strategy.
 README | 2 ++
 1 file changed, 2 insertions(+)

EDIT: The closest answer to my question is found in one of the answers listed HERE, essentially I get the entire diff if I execute the following before the merge

git diff <commit1> <commit2>

EDIT 2: Another way to see the full merge commit the same as a commit message is by first merging the branch, and then running

git commit --amend

This makes it possible to see the merge commit as a normal commit, at least with respect to seeing the full diff.


问:
Second shortcode generated div inside the first shortcode div
I am trying to add multiple shortcode generate blog post loops to one page

Problem: when i add two shortcodes including blog post loop to one page,  the shortcode plants itself inside the first shortcodes outer div, this happens to some of my php code as well, perhaps you can save the day, by spotting the error?

Here you will see, that the second row (this is where the second loop from shortcode starts, the row is wider, which essentially is the problem):

https://ibb.co/jB352w

If I were to add another loop with same build of shortcode, it would be wider than the second and so on..

The html output, here you can see that the second loops  has implanted itself into first loops "row".
https://ibb.co/h7pOpb

My shortcode.php:

```<code><?php

$city = the_terms( $post->ID , "'.$city.'");

/*** HOME ***/
function blog_loop_mtl( $atts ) {
    extract( shortcode_atts( array(
                                    'type' => 'post',
                                    'perpage' => 20,
                                    'city'   => 'Montreal'
                                  ), $atts ) );
      echo '<div class="clear"></div>';// Outter Container open
                      $args = array(
                                    'post_type' => $type,
                                    'posts_per_page' => $perpage,
                                    'city'   => $city
                                    );
                      $splendid_query = new  WP_Query( $args );

    echo '<div class="row">';// Row Open

    while ( $splendid_query->have_posts() ) : $splendid_query->the_post();
      $category = get_the_category();
      echo           '<div class="col-xs-6 col-sm-4 grid-entry-wrapper"> <!-- grid-entry-wrapper open -->

                            <div class="post_grid_entry">

                                <div id="grid_entry_meta">

                                      <div class="boujee">

                                          <a href="' . get_category_link($cats[0]->cat_ID) . '" style="color: white">' . $category[0]->cat_name . '</a>

                                      </div>
                                      <div>
                                        ' . $city . ' <i class="fa fa-map-marker" aria-hidden="true"></i>
                                      </div>

                                </div>
                                <a href="' . get_permalink() . '">
                                  <div class="grid_thumbnail" >
                                  <div class="grid_thumbnail" style="background-image: url('.get_the_post_thumbnail_url().')" alt="">
                                  </div>
                                </a>
                                <a href="'.get_author_posts_url( get_current_user_id()). '">'. get_avatar(get_the_author_meta( 'id' )) . '</a>
                            </div>
                            <div>
                              <a href="' . get_permalink() . '"></a>
                                <h3 class="post_grid_title">
                                  <a href="' . get_permalink() . '">'. get_the_title(). '</a>
                                </h3>
                            </div>
                            <div id="grid_entry_meta_publ">
                              <div>
                                Published ' . time_elapsed_string(get_the_date()). '
                              </div>
                              <div>
                                by <a href="'.get_author_posts_url(get_the_author_meta( 'id' )). '">'. get_the_author_meta( 'display_name' ) . '</a>
                              </div>
                            </div>

                      </div><!-- grid-entry-wrapper close -->
          </div>'; // Row Close

    endwhile;
    wp_reset_query();

}
add_shortcode('blog_loop_mtl', 'blog_loop_mtl');
</code>```

答:
Shortcode only works when you return the output.

```<code><?php

$city = the_terms( $post->ID , "'.$city.'");

/*** HOME ***/
function blog_loop_mtl( $atts ) {
    extract( shortcode_atts( array(
                                    'type' => 'post',
                                    'perpage' => 20,
                                    'city'   => 'Montreal'
                                  ), $atts ) );
      echo '<div class="clear"></div>';// Outter Container open
                      $args = array(
                                    'post_type' => $type,
                                    'posts_per_page' => $perpage,
                                    'city'   => $city
                                    );
                      $splendid_query = new  WP_Query( $args );

    $output = '<div class="row">';// Row Open

    while ( $splendid_query->have_posts() ) : $splendid_query->the_post();
      $category = get_the_category();
      $output .=           '<div class="col-xs-6 col-sm-4 grid-entry-wrapper"> <!-- grid-entry-wrapper open -->

                            <div class="post_grid_entry">

                                <div id="grid_entry_meta">

                                      <div class="boujee">

                                          <a href="' . get_category_link($cats[0]->cat_ID) . '" style="color: white">' . $category[0]->cat_name . '</a>

                                      </div>
                                      <div>
                                        ' . $city . ' <i class="fa fa-map-marker" aria-hidden="true"></i>
                                      </div>

                                </div>
                                <a href="' . get_permalink() . '">
                                  <div class="grid_thumbnail" >
                                    <div class="grid_thumbnail" style="background-image: url('.get_the_post_thumbnail_url().')" alt=""></div>
                                  </div>
                                </a>
                                <a href="'.get_author_posts_url( get_current_user_id()). '">'. get_avatar(get_the_author_meta( 'id' )) . '</a>
                            </div>
                            <div>
                              <a href="' . get_permalink() . '"></a>
                                <h3 class="post_grid_title">
                                  <a href="' . get_permalink() . '">'. get_the_title(). '</a>
                                </h3>
                            </div>
                            <div id="grid_entry_meta_publ">
                              <div>
                                Published ' . time_elapsed_string(get_the_date()). '
                              </div>
                              <div>
                                by <a href="'.get_author_posts_url(get_the_author_meta( 'id' )). '">'. get_the_author_meta( 'display_name' ) . '</a>
                              </div>
                            </div>

                      </div><!-- grid-entry-wrapper close -->';

    endwhile;
    wp_reset_query();

    $output .= '</div>'; // Row Close

    return $output;
}
add_shortcode('blog_loop_mtl', 'blog_loop_mtl');
</code>```

The second wrong thing in the code you were doing is "Row div close" within while loop while you started row div outside while loop.

Body:
I am trying to add multiple shortcode generate blog post loops to one page

Problem: when i add two shortcodes including blog post loop to one page,  the shortcode plants itself inside the first shortcodes outer div, this happens to some of my php code as well, perhaps you can save the day, by spotting the error?

Here you will see, that the second row (this is where the second loop from shortcode starts, the row is wider, which essentially is the problem):

https://ibb.co/jB352w

If I were to add another loop with same build of shortcode, it would be wider than the second and so on..

The html output, here you can see that the second loops  has implanted itself into first loops "row".
https://ibb.co/h7pOpb

My shortcode.php:

<?php

$city = the_terms( $post->ID , "'.$city.'");

/*** HOME ***/
function blog_loop_mtl( $atts ) {
    extract( shortcode_atts( array(
                                    'type' => 'post',
                                    'perpage' => 20,
                                    'city'   => 'Montreal'
                                  ), $atts ) );
      echo '

';// Outter Container open
                      $args = array(
                                    'post_type' => $type,
                                    'posts_per_page' => $perpage,
                                    'city'   => $city
                                    );
                      $splendid_query = new  WP_Query( $args );

    echo '
';// Row Open

    while ( $splendid_query->have_posts() ) : $splendid_query->the_post();
      $category = get_the_category();
      echo           '

                                          cat_ID) . '" style="color: white">' . $category[0]->cat_name . '

                                        ' . $city . '

                                '. get_avatar(get_the_author_meta( 'id' )) . '

                                  '. get_the_title(). '

                                Published ' . time_elapsed_string(get_the_date()). '

                                by '. get_the_author_meta( 'display_name' ) . '

'; // Row Close

    endwhile;
    wp_reset_query();

}
add_shortcode('blog_loop_mtl', 'blog_loop_mtl');

Body:
Shortcode only works when you return the output.

<?php

$city = the_terms( $post->ID , "'.$city.'");

/*** HOME ***/
function blog_loop_mtl( $atts ) {
    extract( shortcode_atts( array(
                                    'type' => 'post',
                                    'perpage' => 20,
                                    'city'   => 'Montreal'
                                  ), $atts ) );
      echo '<div class="clear"></div>';// Outter Container open
                      $args = array(
                                    'post_type' => $type,
                                    'posts_per_page' => $perpage,
                                    'city'   => $city
                                    );
                      $splendid_query = new  WP_Query( $args );

    $output = '<div class="row">';// Row Open

    while ( $splendid_query->have_posts() ) : $splendid_query->the_post();
      $category = get_the_category();
      $output .=           '<div class="col-xs-6 col-sm-4 grid-entry-wrapper"> <!-- grid-entry-wrapper open -->

                            <div class="post_grid_entry">

                                <div id="grid_entry_meta">

                                      <div class="boujee">

                                          <a href="' . get_category_link($cats[0]->cat_ID) . '" style="color: white">' . $category[0]->cat_name . '</a>

                                      </div>
                                      <div>
                                        ' . $city . ' <i class="fa fa-map-marker" aria-hidden="true"></i>
                                      </div>

                                </div>
                                <a href="' . get_permalink() . '">
                                  <div class="grid_thumbnail" >
                                    <div class="grid_thumbnail" style="background-image: url('.get_the_post_thumbnail_url().')" alt=""></div>
                                  </div>
                                </a>
                                <a href="'.get_author_posts_url( get_current_user_id()). '">'. get_avatar(get_the_author_meta( 'id' )) . '</a>
                            </div>
                            <div>
                              <a href="' . get_permalink() . '"></a>
                                <h3 class="post_grid_title">
                                  <a href="' . get_permalink() . '">'. get_the_title(). '</a>
                                </h3>
                            </div>
                            <div id="grid_entry_meta_publ">
                              <div>
                                Published ' . time_elapsed_string(get_the_date()). '
                              </div>
                              <div>
                                by <a href="'.get_author_posts_url(get_the_author_meta( 'id' )). '">'. get_the_author_meta( 'display_name' ) . '</a>
                              </div>
                            </div>

                      </div><!-- grid-entry-wrapper close -->';

    endwhile;
    wp_reset_query();

    $output .= '</div>'; // Row Close

    return $output;
}
add_shortcode('blog_loop_mtl', 'blog_loop_mtl');

The second wrong thing in the code you were doing is "Row div close" within while loop while you started row div outside while loop.


问:
python inotify to monitor for In_closted_write and in_moved_to events
I am monitoring a directory for new files to be moved to or created.
Upon detecting the new file I call a another python script to process the file.

```<code>#!/usr/bin/python

import os
import signal
import sys
import logging
import inotify.adapters
import subprocess

_DEFAULT_LOG_FORMAT = ''

_LOGGER = logging.getLogger(__name__)

def _configure_logging():
    _LOGGER.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()

    formatter = logging.Formatter(_DEFAULT_LOG_FORMAT)
    ch.setFormatter(formatter)

    _LOGGER.addHandler(ch)

def exit_gracefully(signum, frame):
    signal.signal(signal.SIGINT, original_sigint)
    sys.exit(1)

    signal.signal(signal.SIGINT, exit_gracefully)

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(b'/home/sort/tmp')

    try:
        for event in i.event_gen():
            if event is not None:
                if 'IN_MOVED_TO' in event[1] or 'IN_CLOSE_WRITE' in event[1]:
                    (header, type_names, watch_path, filename) = event
                    _LOGGER.info("%s" #"WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s "
                         #"WATCH-PATH=[%s]"
                         "FILENAME=%s" + "/" + "%s",
                         type_names,#header.wd, header.mask, header.cookie, header.len, type_names,
                         watch_path.decode('utf-8'), filename.decode('utf-8'))
                fnp = str(event[2] + "/" + event[3])
                print fnp
                proc = subprocess.Popen([orgpath, fnp], stderr=subprocess.STDOUT, bufsize=1)
                #proc.communicate()
    finally:
        i.remove_watch(b'/home/sort/tmp')

if __name__ == '__main__':
    _configure_logging()

    orgdir = os.path.dirname(os.path.realpath(sys.argv[0]))
    orgpath = os.path.join(orgdir, "organize.py")

    original_sigint = signal.getsignal(signal.SIGINT)
    signal.signal(signal.SIGINT, exit_gracefully)
    print("Watching /home/sort/tmp for new files")
    main()
</code>```

The end goal is to only process one file at a time as I call to an API to scrape for metadata. To many calls to the API in a short period of time could result in the API key to be banned or temporarily blocked.

Right now when I copy more than a single file into the monitoring directory the script gets called on each file at the same time.

答:
Try putting a for loop to run the python file..

```<code>for files in directory:
    ...code that runs the python file
</code>```

if it is still running too fast, you can put a timer on to throttle the API calls

```<code>import time
for files in directory:
    ...code that runs the python file
    time.sleep(5)
</code>```

Body:
I am monitoring a directory for new files to be moved to or created.
Upon detecting the new file I call a another python script to process the file.

#!/usr/bin/python

import os
import signal
import sys
import logging
import inotify.adapters
import subprocess

_DEFAULT_LOG_FORMAT = ''

_LOGGER = logging.getLogger(__name__)

def _configure_logging():
    _LOGGER.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()

    formatter = logging.Formatter(_DEFAULT_LOG_FORMAT)
    ch.setFormatter(formatter)

    _LOGGER.addHandler(ch)

def exit_gracefully(signum, frame):
    signal.signal(signal.SIGINT, original_sigint)
    sys.exit(1)

    signal.signal(signal.SIGINT, exit_gracefully)

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(b'/home/sort/tmp')

    try:
        for event in i.event_gen():
            if event is not None:
                if 'IN_MOVED_TO' in event[1] or 'IN_CLOSE_WRITE' in event[1]:
                    (header, type_names, watch_path, filename) = event
                    _LOGGER.info("%s" #"WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s "
                         #"WATCH-PATH=[%s]"
                         "FILENAME=%s" + "/" + "%s",
                         type_names,#header.wd, header.mask, header.cookie, header.len, type_names,
                         watch_path.decode('utf-8'), filename.decode('utf-8'))
                fnp = str(event[2] + "/" + event[3])
                print fnp
                proc = subprocess.Popen([orgpath, fnp], stderr=subprocess.STDOUT, bufsize=1)
                #proc.communicate()
    finally:
        i.remove_watch(b'/home/sort/tmp')

if __name__ == '__main__':
    _configure_logging()

    orgdir = os.path.dirname(os.path.realpath(sys.argv[0]))
    orgpath = os.path.join(orgdir, "organize.py")

    original_sigint = signal.getsignal(signal.SIGINT)
    signal.signal(signal.SIGINT, exit_gracefully)
    print("Watching /home/sort/tmp for new files")
    main()

The end goal is to only process one file at a time as I call to an API to scrape for metadata. To many calls to the API in a short period of time could result in the API key to be banned or temporarily blocked.

Right now when I copy more than a single file into the monitoring directory the script gets called on each file at the same time.

Body:
Try putting a for loop to run the python file..

for files in directory:
    ...code that runs the python file

if it is still running too fast, you can put a timer on to throttle the API calls

import time
for files in directory:
    ...code that runs the python file
    time.sleep(5)


问:
How to use key fields with Java Arrays?
I'm trying to use a key field with my array with Java but I'm confused on where to begin. My program is supposed to be that the user enters a name which would be the unique identifier and all this information would show up relating to the name kind of a mini Google. I have two classes, one is my abstract class and my other would be my main method class. If anyone could help me that would be great and very much appericated.

Here is my class.

```<code>import java.util.HashMap;
public class DataBase {

private  String name;
private  int year;
private  String status;
private  String habitat;
private  String lifespan;

public DataBase() {
}

HashMap list=new HashMap();
public DataBase(String name, int year, String status, String habitat, String lifespan) {
    this.name = name;
    this.year = year;
    this.status = status;
    this.habitat = habitat;
    this.lifespan = lifespan;
}

public  String getName() {
    return name;
}

public  void setName(String name) {
    this.name = name;
}

public  int getYear() {
    return year;
}

public  void setYear(int year) {
    this.year = year;
}

public  String getStatus() {
    return status;
}

public  void setStatus(String status) {
    this.status = status;
}

 public  String getHabitat() {
    return habitat;
}

public  void setHabitat(String habitat) {
    this.habitat = habitat;
   }

 public  String getLifeSpan() {
    return lifespan;
}

public  void setLifeSpan(String lifespan) {
   this.lifespan = lifespan;
}

    public String toString()
{
    String result = "";
    result += "\nName: "+ getName() + "\nYear: "+getYear()+ "\nStatus: "+getStatus()+ "\nHabitat: "+getHabitat()+"\nLifeSpan: "+getLifeSpan();
    return result;
}

}
</code>```

Here is my main method class.

```<code>import java.util.HashMap;
import java.util.Scanner;
public class DB
{
public static void main(String[] args)
 {
    Scanner in = new Scanner (System.in);

    String fName;
    System.out.print("Enter Name:");
    fName=in.next();

    String name;
    name=fName+" ";

    System.out.println(name);

    DataBase turtle1 = new DataBase("Diamondback terrapin", 1793, "Near Threatened","East Coast of US","8 years");
    DataBase turtle2 = new DataBase("Galápagos tortoise", 1535, "Vulnerable"," Galápagos Islands","At least 100 years");
    DataBase turtle3 = new DataBase("West African mud turtle", 1812, "Least Concern","West and Central Africa","25 years");
    DataBase turtle4 = new DataBase("Black softshell turtle", 1875, "Extinct in the Wild","South Asia","Unknown");
    DataBase turtle5 = new DataBase("Radiated tortoise", 1802, "Critically Endangered","Southern Madagascar","At least 150 years");
    DataBase turtle6 = new DataBase("Painted terrapin", 1844, "Critically Endangered","East Asia","Unknown");
    DataBase turtle7 = new DataBase("Philippine pond turtle", 1920, "Critically Endangered ","Philippines","Unknown");
    DataBase turtle8 = new DataBase("Flattened musk turtle", 1955, "Critically Endangered","Southern US","20-50 years");
    DataBase turtle9 = new DataBase("McCord's box turtle", 1988, "Critically Endangered","China","Around 50 years");
    DataBase turtle10 = new DataBase("Leatherback sea turtle", 1761, "Vulnerable","Atlantic and Pacfic Oceans","Around 30 years");

    System.out.println(turtle1);

    HashMap<String,DataBase> turtles = new HashMap<>();
    turtles.put("Diamondback terrapin", new DataBase("Diamondback terrapin", 1793, "Near Threatened","East Coast of US","8 years"));
    turtles.put("Galapagos tortoise", new DataBase("Galapagos tortoise", 1535, "Vulnerable"," Galapagos Islands","At least 100 years"));
    turtles.put("West African mud turtle", new DataBase("West African mud turtle", 1812, "Least Concern","West and Central Africa","25 years"));
    turtles.put("Black softshell turtle", new DataBase("Black softshell turtle", 1875, "Extinct in the Wild","South Asia","Unknown"));
    turtles.put("Radiated tortoise", new DataBase("Radiated tortoise", 1802, "Critically Endangered","Southern Madagascar","At least 150 years"));
    turtles.put("Painted terrapin", new DataBase("Painted terrapin", 1844, "Critically Endangered","East Asia","Unknown"));
    turtles.put("Philippine pond turtle", new DataBase("Philippine pond turtle", 1920, "Critically Endangered ","Philippines","Unknown"));
    turtles.put("Flattened musk turtle", new DataBase("Flattened musk turtle", 1955, "Critically Endangered","Southern US","20-50 years"));
    turtles.put("McCord's box turtle", new DataBase("McCord's box turtle", 1988, "Critically Endangered","China","Around 50 years"));
    turtles.put("Leatherback sea turtle", new DataBase("Leatherback sea turtle", 1761, "Vulnerable","Atlantic and Pacfic Oceans","Around 30 years"));

    DataBase database = turtles.get("Diamondback terrapin");
    DataBase databas = turtles.get("Galapagos tortoise");
    DataBase databse = turtles.get("West African mud turtle");
    DataBase databa = turtles.get("Black softshell turtle");
    DataBase dataase = turtles.get("Radiated tortoise");
    DataBase datab = turtles.get("Painted terrapin");
    DataBase datase = turtles.get("Philippine pond turtle");
    DataBase datae = turtles.get("Flattened musk turtle");
    DataBase dataae = turtles.get("McCord's box turtle");
    DataBase datbase = turtles.get("Leatherback sea turtle");
    System.out.println(turtles.get(name));

}

}
</code>```

UPDATE:

I can print out both the name and the information but I don't know how to connect the two together.

答:
Keys are used with Maps.

Try replacing your ArrayList with a java.util.HashMap.

```<code>HashMap<String,DataBase> turtles = new HashMap<>();
turtles.put("Diamondback terrapin", new DataBase("Diamondback terrapin", 1793, "Near Threatened","East Coast of US","8 years"));
...
DataBase database = turtles.get("Diamondback terrapin");
</code>```

Title: How to use key fields with Java Arrays?

Body:
I'm trying to use a key field with my array with Java but I'm confused on where to begin. My program is supposed to be that the user enters a name which would be the unique identifier and all this information would show up relating to the name kind of a mini Google. I have two classes, one is my abstract class and my other would be my main method class. If anyone could help me that would be great and very much appericated.

Here is my class.

import java.util.HashMap;
public class DataBase {

private  String name;
private  int year;
private  String status;
private  String habitat;
private  String lifespan;

public DataBase() {
}

HashMap list=new HashMap();
public DataBase(String name, int year, String status, String habitat, String lifespan) {
    this.name = name;
    this.year = year;
    this.status = status;
    this.habitat = habitat;
    this.lifespan = lifespan;
}

public  String getName() {
    return name;
}

public  void setName(String name) {
    this.name = name;
}

public  int getYear() {
    return year;
}

public  void setYear(int year) {
    this.year = year;
}

public  String getStatus() {
    return status;
}

public  void setStatus(String status) {
    this.status = status;
}

 public  String getHabitat() {
    return habitat;
}

public  void setHabitat(String habitat) {
    this.habitat = habitat;
   }

 public  String getLifeSpan() {
    return lifespan;
}

public  void setLifeSpan(String lifespan) {
   this.lifespan = lifespan;
}

    public String toString()
{
    String result = "";
    result += "\nName: "+ getName() + "\nYear: "+getYear()+ "\nStatus: "+getStatus()+ "\nHabitat: "+getHabitat()+"\nLifeSpan: "+getLifeSpan();
    return result;
}

}

Here is my main method class.

import java.util.HashMap;
import java.util.Scanner;
public class DB
{
public static void main(String[] args)
 {
    Scanner in = new Scanner (System.in);

    String fName;
    System.out.print("Enter Name:");
    fName=in.next();

    String name;
    name=fName+" ";

    System.out.println(name);

    DataBase turtle1 = new DataBase("Diamondback terrapin", 1793, "Near Threatened","East Coast of US","8 years");
    DataBase turtle2 = new DataBase("Galápagos tortoise", 1535, "Vulnerable"," Galápagos Islands","At least 100 years");
    DataBase turtle3 = new DataBase("West African mud turtle", 1812, "Least Concern","West and Central Africa","25 years");
    DataBase turtle4 = new DataBase("Black softshell turtle", 1875, "Extinct in the Wild","South Asia","Unknown");
    DataBase turtle5 = new DataBase("Radiated tortoise", 1802, "Critically Endangered","Southern Madagascar","At least 150 years");
    DataBase turtle6 = new DataBase("Painted terrapin", 1844, "Critically Endangered","East Asia","Unknown");
    DataBase turtle7 = new DataBase("Philippine pond turtle", 1920, "Critically Endangered ","Philippines","Unknown");
    DataBase turtle8 = new DataBase("Flattened musk turtle", 1955, "Critically Endangered","Southern US","20-50 years");
    DataBase turtle9 = new DataBase("McCord's box turtle", 1988, "Critically Endangered","China","Around 50 years");
    DataBase turtle10 = new DataBase("Leatherback sea turtle", 1761, "Vulnerable","Atlantic and Pacfic Oceans","Around 30 years");

    System.out.println(turtle1);

    HashMap<String,DataBase> turtles = new HashMap<>();
    turtles.put("Diamondback terrapin", new DataBase("Diamondback terrapin", 1793, "Near Threatened","East Coast of US","8 years"));
    turtles.put("Galapagos tortoise", new DataBase("Galapagos tortoise", 1535, "Vulnerable"," Galapagos Islands","At least 100 years"));
    turtles.put("West African mud turtle", new DataBase("West African mud turtle", 1812, "Least Concern","West and Central Africa","25 years"));
    turtles.put("Black softshell turtle", new DataBase("Black softshell turtle", 1875, "Extinct in the Wild","South Asia","Unknown"));
    turtles.put("Radiated tortoise", new DataBase("Radiated tortoise", 1802, "Critically Endangered","Southern Madagascar","At least 150 years"));
    turtles.put("Painted terrapin", new DataBase("Painted terrapin", 1844, "Critically Endangered","East Asia","Unknown"));
    turtles.put("Philippine pond turtle", new DataBase("Philippine pond turtle", 1920, "Critically Endangered ","Philippines","Unknown"));
    turtles.put("Flattened musk turtle", new DataBase("Flattened musk turtle", 1955, "Critically Endangered","Southern US","20-50 years"));
    turtles.put("McCord's box turtle", new DataBase("McCord's box turtle", 1988, "Critically Endangered","China","Around 50 years"));
    turtles.put("Leatherback sea turtle", new DataBase("Leatherback sea turtle", 1761, "Vulnerable","Atlantic and Pacfic Oceans","Around 30 years"));

    DataBase database = turtles.get("Diamondback terrapin");
    DataBase databas = turtles.get("Galapagos tortoise");
    DataBase databse = turtles.get("West African mud turtle");
    DataBase databa = turtles.get("Black softshell turtle");
    DataBase dataase = turtles.get("Radiated tortoise");
    DataBase datab = turtles.get("Painted terrapin");
    DataBase datase = turtles.get("Philippine pond turtle");
    DataBase datae = turtles.get("Flattened musk turtle");
    DataBase dataae = turtles.get("McCord's box turtle");
    DataBase datbase = turtles.get("Leatherback sea turtle");
    System.out.println(turtles.get(name));

}

}

UPDATE:

I can print out both the name and the information but I don't know how to connect the two together.

Body:
Keys are used with Maps.

Try replacing your ArrayList with a java.util.HashMap.

HashMap<String,DataBase> turtles = new HashMap<>();
turtles.put("Diamondback terrapin", new DataBase("Diamondback terrapin", 1793, "Near Threatened","East Coast of US","8 years"));
...
DataBase database = turtles.get("Diamondback terrapin");


问:
How to determine the relative path to a file from within an asp.net mvc3 area
I want to know what's the best way using the Razor syntax to determine the relative path to the ClientBin folder from within an Area's View.

Thank you,
Stephen

答:
The problem was solved by luck, I had been using the first multi-line expression, then by chance went back to the second one.. Has nothing to do with the mapping of the file, or where it's running from </p>

```<code><div>
    @{
        com.patten.root.Helpers.Silverlight.SilverlightHost("/ClientBin/jounce.xap");
    }
</div>

<div>
    @com.patten.root.Helpers.Silverlight.SilverlightHost("/ClientBin/jounce.xap");
</div>
</code>```

Body:
The problem was solved by luck, I had been using the first multi-line expression, then by chance went back to the second one.. Has nothing to do with the mapping of the file, or where it's running from

<div>
    @{
        com.patten.root.Helpers.Silverlight.SilverlightHost("/ClientBin/jounce.xap");
    }
</div>

<div>
    @com.patten.root.Helpers.Silverlight.SilverlightHost("/ClientBin/jounce.xap");
</div>


问:
What does this RegExp pattern /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/ mean in Javascript?
This regex

```<code>/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/
</code>```

pattern is intended to match a valid password.

I've searched the answer on regexper.com, here is the link.

I know the meaning of the contents in each parenthesis, but I don't know why here are there parentheses and how they work together..

答:
The pattern  (?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,} asserts

6 or more characters

a digit

a lower-case letter

an upper-case letter

That's it.

Explanation of the moving parts:

(?=.*\d) checks if a digit exists using a positive lookahead.

(?=.*[a-z]) checks in the same fashing to see if a lowercase letter exists.

(?=.*[A-Z]) .. and an uppercase letter exists as well.

.{6,} The 6+ quantifier is obvious.

The beauty of using a lookahead here is it makes it easy to (spot and) maintain the password rules.

Body:
This regex

/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/

pattern is intended to match a valid password.

I've searched the answer on regexper.com, here is the link.

I know the meaning of the contents in each parenthesis, but I don't know why here are there parentheses and how they work together..


问:
Counting zeros in a recursive manner
I am trying to count TRAILING zeros from a recursive manner. Basically I split the final recursive result and then created a var counter that will count all the zeros.

```<code>function countingZeros(n) {
  if (n < 0) {
    // Termination condition to prevent infinite recursion
    return;
  }
  // Base case
  if (n === 0) {
    return 1;
  }

  // Recursive case
  let final = n * countingZeros(n -1);

  let counter = 0;

  String(final).split('').forEach(function(item){
    item === 0 ? counter++ : counter;
  });

  return counter;
}

countingZeros(12) // => suppose to output 2 since there are 2 trailing zeros from 479001600 but got 0

countingZeros(6) // => suppose to get 1 since 720 is the final result.
</code>```

I am expecting to get 2 in return as the counter must return but instead I got 0. Any idea what am I missing on my function? How should I fix it?

答:
I think you're working too hard.  First of all, in response to a comment, you don't actually need to calculate the factorial, since all you really need is to count factors of 5 and of 2.  And since there are many more factors of 2, your real answer is just counting factors of 5.  But each factor of 5 must be a factor of one of {1, 2, 3, ... n}, so we just have to add up the highest powers of five that evenly divide into each of {1, 2, 3, ... n}.

We can do that with some simple recursion:

```<code> const fiveFactors = (n, acc = 0) => (n % 5 == 0)
       ? fiveFactors(n / 5, acc + 1)
       : acc
 const factZeros = (n, acc = 0) => (n > 0)
       ? factZeros(n - 1, acc + fiveFactors(n))
       : acc

 factZeros(1000) //=> 249
</code>```

Note that both functions are eligible for tail-call optimization.

Also, although this does involve a double recursion, it's not really ill-performant.  Four out of five times, the internal recursion stops on the first call, and of the remainder, four out of five stop on the second call, and so on.

Title: Counting zeros in a recursive manner

Body:
I am trying to count TRAILING zeros from a recursive manner. Basically I split the final recursive result and then created a var counter that will count all the zeros.

function countingZeros(n) {
  if (n < 0) {
    // Termination condition to prevent infinite recursion
    return;
  }
  // Base case
  if (n === 0) {
    return 1;
  }

  // Recursive case
  let final = n * countingZeros(n -1);

  let counter = 0;

  String(final).split('').forEach(function(item){
    item === 0 ? counter++ : counter;
  });

  return counter;
}

countingZeros(12) // => suppose to output 2 since there are 2 trailing zeros from 479001600 but got 0

countingZeros(6) // => suppose to get 1 since 720 is the final result.

I am expecting to get 2 in return as the counter must return but instead I got 0. Any idea what am I missing on my function? How should I fix it?

Body:
I think you're working too hard.  First of all, in response to a comment, you don't actually need to calculate the factorial, since all you really need is to count factors of 5 and of 2.  And since there are many more factors of 2, your real answer is just counting factors of 5.  But each factor of 5 must be a factor of one of {1, 2, 3, ... n}, so we just have to add up the highest powers of five that evenly divide into each of {1, 2, 3, ... n}.

We can do that with some simple recursion:

 const fiveFactors = (n, acc = 0) => (n % 5 == 0)
       ? fiveFactors(n / 5, acc + 1)
       : acc
 const factZeros = (n, acc = 0) => (n > 0)
       ? factZeros(n - 1, acc + fiveFactors(n))
       : acc

 factZeros(1000) //=> 249

Note that both functions are eligible for tail-call optimization.

Also, although this does involve a double recursion, it's not really ill-performant.  Four out of five times, the internal recursion stops on the first call, and of the remainder, four out of five stop on the second call, and so on.


问:
scrapy CrawlSpider: modify deny rules list while crawling
I need to update deny list in crawl rule while crawling website. (i.e. i want to dynamically modify deny rules list while my spider is working)

what i tried is

```<code>deny = ['a','b','c']
rules = ( Rule(LinkExtractor(allow=('/r/','/p/' ), deny=deny), callback='parse_item', follow=True), )
</code>```

and then performed self.deny.append(unique_category) in parse_item() function but it did not worked as I expected: updated deny list was ignored(crawler still went to same category again and again).

I would appreciate any suggestions. thanks

答:
There are two ways to do this:

Poke around in the internal APIs of the link extractors, which isn't guaranteed to survive version changes:

```<code>self.rules[0].deny_res.append(re.compile('d'))
</code>```

Make your own version (or subclass) of CrawlSpider that does exactly what you want.

Body:
I need to update deny list in crawl rule while crawling website. (i.e. i want to dynamically modify deny rules list while my spider is working)

what i tried is

deny = ['a','b','c']
rules = ( Rule(LinkExtractor(allow=('/r/','/p/' ), deny=deny), callback='parse_item', follow=True), )

and then performed self.deny.append(unique_category) in parse_item() function but it did not worked as I expected: updated deny list was ignored(crawler still went to same category again and again).

I would appreciate any suggestions. thanks

Body:
There are two ways to do this:

Poke around in the internal APIs of the link extractors, which isn't guaranteed to survive version changes:

self.rules[0].deny_res.append(re.compile('d'))

Make your own version (or subclass) of CrawlSpider that does exactly what you want.


答:
(?=.*\d) This is a positive lookahead to see if a digit exists

(?=.*[a-z]) This is a positive lookahead to see if a lowercase letter exists

(?=.*[A-Z]) This is a positive lookahead to see if an uppercase letter exists

.{6,} This matches for 6 or more of any character

So overall, it expects a string of 6 or more characters that contains at least one number, one lowercase letter, and one uppercase letter.

Title: What does this RegExp pattern /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/ mean in Javascript?