问:
Displaying Decimal Points In C++, Problems with Calculations
I'm taking a C++ online class (probably a mistake) and I'm trying to figure out how to correct this code. I had to write a program from scratch and I'm totally stumped as to what I'm doing incorrectly.

This is what should come out:

Blockquote  Welcome to name’s carpet calculator!

Enter the name of the room to be carpeted:  bedroom

Enter the length of the room in feet: 10

Enter the width of the room in feet: 10

Enter the price of the carpet per yard: 3.49

Enter the padding cost: 35

```<code>                                         Carpet estimate for bedroom
</code>```

Total square feet of the room: 100

Total square yards of the room: 12

Total cost of the carpet needed:          41.88

Total cost of labor (at $6.03/yd):        72.36

Padding Cost:                                       35.00

Subtotal:                                             149.24

Tax:                                                        8.50

Total:                                                   157.74

Blockquote

Some additional rules are: Square yardage for a room is calculated by dividing the total square feet by 9. Add 1 yard for any fractional differences.
The labor cost of installing the carpet is $6.03/yard
Tax rate is currently 5.7%

Here's my current code:

```<code>    // John Mayer Learning Unit 2 Assessment

#include <iostream>
using namespace std;

int main()
{
    string roomName; // declarations
    int roomLength;
    int roomWidth;
    int squareFeet;
    int carpetPrice;
    int paddingCost;
    int totalCarpetCost;
    const int TAX_RATE = .057;
    int laborCost;
    const int LABOR_RATE = 6.03;
    int squareYard;
    int subtotal;
    int taxCost;
    int totalCost;

    cout << "Welcome to John Mayer's Carpet Calculator!"; // displays this at the top
    cout << "\n\n What is the name of the room to be carpeted?"; // asks for the room name
    cin >> roomName; // stores the room name
    cout << "\n What is the length of the room (in feet)?"; // asks for the length
    cin >> roomLength; // stores the length
    cout << "\n What is the width of the room (in feet)?"; // asks for the width
    cin >> roomWidth; // stores the width
    cout << "\n What is the price of the carpet per yard?"; // asks for the price of the carpet
    cin >> carpetPrice; // stores the price
    cout << "\n What is the padding cost?"; // asks for the padding cost
    cin >> paddingCost; // stores the padding cost **DOES NOT WORK**

    squareFeet = roomLength * roomWidth; // finds square feet by multiplying length and width
    squareYard = (squareFeet / 9) + 1; // finds the square feet and rounds up to the next yard
    totalCarpetCost = carpetPrice * squareYard; // finds the carpet cost by multiplying the input carpet price by the square yardage
    laborCost = squareYard * LABOR_RATE; // finds the labor cost by multiplying the yardage by the labor rate of 6.03
    subtotal = (totalCarpetCost + paddingCost + laborCost); // finds the subtotal by adding the labor cost, carpet cost, and padding cost
    taxCost = subtotal * TAX_RATE; // finds the tax cost by multiplying the subtotal by the tax rate of .057 (5.7%)
    totalCost = taxCost + subtotal; // adds the subtotal and tax to find the total overall cost

    cout << "\n Carpet estimate for " << roomName; // displays text and the room name

    cout << "\n Total square feet of the room: " << squareFeet; //displays the square feet calculation **CORRECT
    cout << "\n Total square yards of the room: " << squareYard; // displays the square yards calculation **CORRECT
    cout << "\n\n Total cost of the carpet needed: " << totalCarpetCost; // displays the carpet cost **INCORRECT
    cout << "\n Total cost of labor (at $6.03/yd): " << laborCost; // displays the labor cost
    cout << "\n Padding Cost: " << paddingCost; // displays the padding cost
    cout << "\n\n Subtotal: " << subtotal; // displays the subtotal
    cout << "\n Tax: " << taxCost; // displays the tax calculation
    cout << "\n Total: " << totalCost;  // displays the final total cost
    cout << "\n"; // line break

    system("PAUSE");
  return 0;

}
</code>```

答:
I figured it out, the only issue is that the tax is off by a penny. I dunno why but it's close enough.

Final code:

```<code>    // John Mayer Learning Unit 2 Assessment

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    string roomName; // declarations
    double roomLength;
    double roomWidth;
    double squareFeet;
    double carpetPrice;
    double paddingCost;
    double totalCarpetCost;
    const double TAX_RATE = .057;
    double laborCost;
    const double LABOR_RATE = 6.03;
    int squareYard;
    double subtotal;
    double taxCost;
    double totalCost;

    cout << setw(15)<<""<< "Welcome to John Mayer's Carpet Calculator!"; // displays this at the top
    cout << "\n\n What is the name of the room to be carpeted? "; // asks for the room name
    cin >> roomName; // stores the room name
    cout << "\n What is the length of the room (in feet)? "; // asks for the length
    cin >> roomLength; // stores the length
    cout << "\n What is the width of the room (in feet)? "; // asks for the width
    cin >> roomWidth; // stores the width
    cout << "\n What is the price of the carpet per yard? "; // asks for the price of the carpet
    cin >> carpetPrice; // stores the price
    cout << "\n What is the padding cost? "; // asks for the padding cost
    cin >> paddingCost; // stores the padding cost (this didn't originally work because carpetPrice was int, not double

    squareFeet = roomLength * roomWidth; // finds square feet by multiplying length and width
    //squareYard = (squareFeet / 9) + 1; // (Original code before realizing a 3x3 room would not work correctly
    squareYard = squareFeet / 9; // finds square yardage
    if ((int)squareFeet % 9 != 0)  // if the remainder does not equal 0 after dividing by nine, then...
        {squareYard++;} // ...round up 1
    totalCarpetCost = carpetPrice * squareYard; // finds the carpet cost by multiplying the input carpet price by the square yardage
    laborCost = squareYard * LABOR_RATE; // finds the labor cost by multiplying the yardage by the labor rate of 6.03
    subtotal = (totalCarpetCost + paddingCost + laborCost); // finds the subtotal by adding the labor cost, carpet cost, and padding cost
    taxCost = subtotal * TAX_RATE; // finds the tax cost by multiplying the subtotal by the tax rate of .057 (5.7%)
    totalCost = taxCost + subtotal; // adds the subtotal and tax to find the total overall cost
    cout << "\n\n" << setw(20) << "" << "Carpet estimate for " << roomName; // displays text and the room name

    cout << "\n\n Total square feet of the room: " << squareFeet; //displays the square feet calculation **CORRECT
    cout << "\n\n Total square yards of the room: " << squareYard; // displays the square yards calculation **CORRECT
    cout << "\n\n\n Total cost of the carpet needed: " << totalCarpetCost; // displays the carpet cost **INCORRECT
    cout << "\n\n Total cost of labor (at $6.03/yd): " << laborCost; // displays the labor cost
    cout << std::fixed << std::setprecision(2) << "\n\n Padding Cost: " << paddingCost; // displays the padding cost
    cout << std::fixed << std::setprecision(2) << "\n\n\n Subtotal: " << subtotal; // displays the subtotal
    cout << std::fixed << std::setprecision(2) << "\n\n Tax: " << taxCost; // displays the tax calculation
    cout << std::fixed << std::setprecision(2) << "\n\n Total: " << totalCost; // displays the final total cost
    cout << "\n\n"; // line break

    system("PAUSE");
  return 0;

}
</code>```

Body:
I'm taking a C++ online class (probably a mistake) and I'm trying to figure out how to correct this code. I had to write a program from scratch and I'm totally stumped as to what I'm doing incorrectly.

This is what should come out:

Blockquote  Welcome to name’s carpet calculator!

Enter the name of the room to be carpeted:  bedroom

Enter the length of the room in feet: 10

Enter the width of the room in feet: 10

Enter the price of the carpet per yard: 3.49

Enter the padding cost: 35

                                         Carpet estimate for bedroom

Total square feet of the room: 100

Total square yards of the room: 12

Total cost of the carpet needed:          41.88

Total cost of labor (at $6.03/yd):        72.36

Padding Cost:                                       35.00

Subtotal:                                             149.24

Tax:                                                        8.50

Total:                                                   157.74

Blockquote

Some additional rules are: Square yardage for a room is calculated by dividing the total square feet by 9. Add 1 yard for any fractional differences.
The labor cost of installing the carpet is $6.03/yard
Tax rate is currently 5.7%

Here's my current code:

    // John Mayer Learning Unit 2 Assessment

#include <iostream>
using namespace std;

int main()
{
    string roomName; // declarations
    int roomLength;
    int roomWidth;
    int squareFeet;
    int carpetPrice;
    int paddingCost;
    int totalCarpetCost;
    const int TAX_RATE = .057;
    int laborCost;
    const int LABOR_RATE = 6.03;
    int squareYard;
    int subtotal;
    int taxCost;
    int totalCost;

    cout << "Welcome to John Mayer's Carpet Calculator!"; // displays this at the top
    cout << "\n\n What is the name of the room to be carpeted?"; // asks for the room name
    cin >> roomName; // stores the room name
    cout << "\n What is the length of the room (in feet)?"; // asks for the length
    cin >> roomLength; // stores the length
    cout << "\n What is the width of the room (in feet)?"; // asks for the width
    cin >> roomWidth; // stores the width
    cout << "\n What is the price of the carpet per yard?"; // asks for the price of the carpet
    cin >> carpetPrice; // stores the price
    cout << "\n What is the padding cost?"; // asks for the padding cost
    cin >> paddingCost; // stores the padding cost **DOES NOT WORK**

    squareFeet = roomLength * roomWidth; // finds square feet by multiplying length and width
    squareYard = (squareFeet / 9) + 1; // finds the square feet and rounds up to the next yard
    totalCarpetCost = carpetPrice * squareYard; // finds the carpet cost by multiplying the input carpet price by the square yardage
    laborCost = squareYard * LABOR_RATE; // finds the labor cost by multiplying the yardage by the labor rate of 6.03
    subtotal = (totalCarpetCost + paddingCost + laborCost); // finds the subtotal by adding the labor cost, carpet cost, and padding cost
    taxCost = subtotal * TAX_RATE; // finds the tax cost by multiplying the subtotal by the tax rate of .057 (5.7%)
    totalCost = taxCost + subtotal; // adds the subtotal and tax to find the total overall cost

    cout << "\n Carpet estimate for " << roomName; // displays text and the room name

    cout << "\n Total square feet of the room: " << squareFeet; //displays the square feet calculation **CORRECT
    cout << "\n Total square yards of the room: " << squareYard; // displays the square yards calculation **CORRECT
    cout << "\n\n Total cost of the carpet needed: " << totalCarpetCost; // displays the carpet cost **INCORRECT
    cout << "\n Total cost of labor (at $6.03/yd): " << laborCost; // displays the labor cost
    cout << "\n Padding Cost: " << paddingCost; // displays the padding cost
    cout << "\n\n Subtotal: " << subtotal; // displays the subtotal
    cout << "\n Tax: " << taxCost; // displays the tax calculation
    cout << "\n Total: " << totalCost;  // displays the final total cost
    cout << "\n"; // line break

    system("PAUSE");
  return 0;

}

Body:
I figured it out, the only issue is that the tax is off by a penny. I dunno why but it's close enough.

Final code:

    // John Mayer Learning Unit 2 Assessment

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    string roomName; // declarations
    double roomLength;
    double roomWidth;
    double squareFeet;
    double carpetPrice;
    double paddingCost;
    double totalCarpetCost;
    const double TAX_RATE = .057;
    double laborCost;
    const double LABOR_RATE = 6.03;
    int squareYard;
    double subtotal;
    double taxCost;
    double totalCost;

    cout << setw(15)<<""<< "Welcome to John Mayer's Carpet Calculator!"; // displays this at the top
    cout << "\n\n What is the name of the room to be carpeted? "; // asks for the room name
    cin >> roomName; // stores the room name
    cout << "\n What is the length of the room (in feet)? "; // asks for the length
    cin >> roomLength; // stores the length
    cout << "\n What is the width of the room (in feet)? "; // asks for the width
    cin >> roomWidth; // stores the width
    cout << "\n What is the price of the carpet per yard? "; // asks for the price of the carpet
    cin >> carpetPrice; // stores the price
    cout << "\n What is the padding cost? "; // asks for the padding cost
    cin >> paddingCost; // stores the padding cost (this didn't originally work because carpetPrice was int, not double

    squareFeet = roomLength * roomWidth; // finds square feet by multiplying length and width
    //squareYard = (squareFeet / 9) + 1; // (Original code before realizing a 3x3 room would not work correctly
    squareYard = squareFeet / 9; // finds square yardage
    if ((int)squareFeet % 9 != 0)  // if the remainder does not equal 0 after dividing by nine, then...
        {squareYard++;} // ...round up 1
    totalCarpetCost = carpetPrice * squareYard; // finds the carpet cost by multiplying the input carpet price by the square yardage
    laborCost = squareYard * LABOR_RATE; // finds the labor cost by multiplying the yardage by the labor rate of 6.03
    subtotal = (totalCarpetCost + paddingCost + laborCost); // finds the subtotal by adding the labor cost, carpet cost, and padding cost
    taxCost = subtotal * TAX_RATE; // finds the tax cost by multiplying the subtotal by the tax rate of .057 (5.7%)
    totalCost = taxCost + subtotal; // adds the subtotal and tax to find the total overall cost
    cout << "\n\n" << setw(20) << "" << "Carpet estimate for " << roomName; // displays text and the room name

    cout << "\n\n Total square feet of the room: " << squareFeet; //displays the square feet calculation **CORRECT
    cout << "\n\n Total square yards of the room: " << squareYard; // displays the square yards calculation **CORRECT
    cout << "\n\n\n Total cost of the carpet needed: " << totalCarpetCost; // displays the carpet cost **INCORRECT
    cout << "\n\n Total cost of labor (at $6.03/yd): " << laborCost; // displays the labor cost
    cout << std::fixed << std::setprecision(2) << "\n\n Padding Cost: " << paddingCost; // displays the padding cost
    cout << std::fixed << std::setprecision(2) << "\n\n\n Subtotal: " << subtotal; // displays the subtotal
    cout << std::fixed << std::setprecision(2) << "\n\n Tax: " << taxCost; // displays the tax calculation
    cout << std::fixed << std::setprecision(2) << "\n\n Total: " << totalCost; // displays the final total cost
    cout << "\n\n"; // line break

    system("PAUSE");
  return 0;

}


来源: stackexchange

问:
How do you set text color of disabled form control button
I am trying to set the color of text in a control button to the same color of the control when it is disabled.
In other words... I don't want any text to show when button is disabled.

I don't know how else to phrase this question.

It is just important for the text not to appear when disabled.

Thank you for your help.

答:
Updated Answer

Possible approaches other than setting the Button1.ForeColor:

Set the Text property to String.Empty

You can set an alternate image which can be displayed instead of the control when it is disabled.

ContentLicense: CC BY-SA 2.5


问:
Remove dropzone of thumbs and hide the div containing dropzone
I'm using the dropzone.js file uploader. Everything works fine but once I've uploaded I want to clear the dropzone of thumbs and hide the div containing dropzone. That's where things go awry. The thumbs still stay in place despite my efforts to clear them.

I've tried all the suggestions in the Dropzone.js site but nothing seems to work. I can get separate remove buttons to work using their example but can't have a master remove button. And yes, I've tried the FAQ example as well. I took the code straight from the tutorial and just added the references to the libraries and it still wouldn't remove the thumbs.

```<code><!doctype html>
<html>
<head>
<link href="style/dropzone.css?v=1.2" type="text/css" rel="stylesheet" />
<script src="js/dropzone.min.js"></script>
<script language="javascript">
function ClearDZ() {
            myDropzone.removeAllFiles();
            document.getElementById("container").style.display = "none";
  }
</script>
<meta charset="UTF-8">
</head>

<body>
<div id=container>
<form id="myDropzone" action="/target-url" class="dropzone"></form>
<button onclick="ClearDZ()">Clear All</button>
<div>
</body>
</html>
</code>```

答:
try this on your library dropzone dropzone.js; but set time out to auto close 2500</p>

```<code>success: function(file) {
    if (file.previewElement) {
      return file.previewElement.classList.add("dz-success"),
      $(function(){
        setTimeout(function(){
          $('.dz-success').fadeOut('slow');
        },2500);
      });
    }
  },
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the dropzone.js file uploader. Everything works fine but once I've uploaded I want to clear the dropzone of thumbs and hide the div containing dropzone. That's where things go awry. The thumbs still stay in place despite my efforts to clear them.

I've tried all the suggestions in the Dropzone.js site but nothing seems to work. I can get separate remove buttons to work using their example but can't have a master remove button. And yes, I've tried the FAQ example as well. I took the code straight from the tutorial and just added the references to the libraries and it still wouldn't remove the thumbs.

<!doctype html>

<link href="style/dropzone.css?v=1.2" type="text/css" rel="stylesheet" />

<meta charset="UTF-8">

<form id="myDropzone" action="/target-url" class="dropzone"></form>
<button onclick="ClearDZ()">Clear All</button>

Body:
try this on your library dropzone dropzone.js; but set time out to auto close 2500

success: function(file) {
    if (file.previewElement) {
      return file.previewElement.classList.add("dz-success"),
      $(function(){
        setTimeout(function(){
          $('.dz-success').fadeOut('slow');
        },2500);
      });
    }
  },


问:
Returning words from a string array with symbols between them in java?
```<code>public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}
</code>```

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

答:
Though there is already an accepted answer, I am giving some alternatives:

Java 8 String join

If you are using Java 8, it already provides a join method that you can make use of:

```<code>return "https://www.google.com/#q=" + String.join("+", args);
</code>```

(If you are using Java < 8, there are still lots of similar util you can find, like Commons Lang)

Join with Loop

It is also not difficult to write a proper and concise loop for this:

```<code>StringBuilder result = new StringBuilder("https://www.google.com/#q=");
boolean first=true;
for (String arg : args) {
    result.append(first? "" : "+").append(arg);
    first = false;
}
return result;
</code>```

Yet other form, as someone in comment seems does not like a boolean flag:

```<code>StringBuilder result = new StringBuilder();
for (String arg : args) {
    result.append(result.length() == 0 ? "https://www.google.com/#q=" : "+")
          .append(arg);
}
return result;
</code>```

Body:
public String onGoogleCommand(String[] args) {
    if(args.length == 0){
        return "Type in a question after the google command!";
    }
    if(args.length >= 1){
        return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
    }
    return "What?";
}

What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?

Body:
Though there is already an accepted answer, I am giving some alternatives:

Java 8 String join

If you are using Java 8, it already provides a join method that you can make use of:

return "https://www.google.com/#q=" + String.join("+", args);

(If you are using Java < 8, there are still lots of similar util you can find, like Commons Lang)

Join with Loop

It is also not difficult to write a proper and concise loop for this:

StringBuilder result = new StringBuilder("https://www.google.com/#q=");
boolean first=true;
for (String arg : args) {
    result.append(first? "" : "+").append(arg);
    first = false;
}
return result;

Yet other form, as someone in comment seems does not like a boolean flag:

StringBuilder result = new StringBuilder();
for (String arg : args) {
    result.append(result.length() == 0 ? "https://www.google.com/#q=" : "+")
          .append(arg);
}
return result;


问:
Problems returning false after using XMLHttpRequest
I have found this Related entry and a few others but I have not quite found my answer so I am posting new. I am trying to run a database query from JavaScript using what I understand of Ajax. I need to return false if the email is already in the database and return true if it does not, but I cannot seem to figure out what I am doing wrong. I have posted my first attempt before I started messing around and making it messy.

JavaScript: It seems to return true no matter what.

```<code>function emailvalid(){

var email = document.getElementById('email').value;
var confirmemail = document.getElementById('cemail').value;
if(email != '' && confirmemail != '')
{
    if(email == '')
    {
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'You must enter a valid email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
    }

xmlhttp = new XMLHttpRequest();
var url="phpfiles/checkemail.php";
url = url+"?email="+email+"&cemail="+confirmemail;
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState==4)
    {
        var answer = xmlhttp.responseText;
        if(answer == 'r0')
        {

        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'This email address is already associated with an exiting account. Please login or use a different email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
        }
        else if(answer == 'r1')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Emails match and are valid";
        document.getElementById('tdcemail').style.color = 'green';
        document.getElementById('tdcemail').innerHTML = "Emails match and are valid";
        document.getElementById('cemail').style.backgroundColor ='green';
        return true;
        }
        else if(answer == 'r2')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = "Email is not valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Email is not valid.";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r3')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Email is valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Emails do not match";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r4')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
    }
}
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);

}
else
{
    document.getElementById('tdemail').style.color = 'red';
    document.getElementById('email').style.backgroundColor ='red';
    document.getElementById('tdemail').innerHTML = "Email is not valid";
    document.getElementById('tdcemail').style.color = 'red';
    document.getElementById('tdcemail').innerHTML = "Email is not valid.";
    document.getElementById('cemail').style.backgroundColor ='red';
    return false;
}
}
</code>```

The innerHTML stuff works just fine which is also why I am confused.

PHP: works fine as far as I can tell.

```<code><?php
$email = $_GET['email'];
$cemail = $_GET['cemail'];
$emailvalidstring = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
include('connection.php');

$checkemailquery = "SELECT email FROM users WHERE email='".$email."'";
$checkemailresult = mysql_query($checkemailquery);

// if query failed.
if(!$checkemailresult)
{
    $error = mysql_error();
    print $error;
    exit;
}
//if the query did run, the email exists. Print error and exit.
if(mysql_affected_rows() != 0)
{
    echo "r0";
    return false;
}
else{
    if(preg_match($emailvalidstring, $email) && $email == $cemail)
    {
        echo "r1";
        return true;
    }
    else if(!preg_match($emailvalidstring, $email) && $email == $cemail)
    {
            echo "r2";
            return false;
    }
    else if(preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r3";
        return false;
    }
    else if(!preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r4";
        return false;
    }
}
?>
</code>```

html: I have it do a double check, once to alert the user if it is already taken, and then a second check on the server to make sure it is still true. cemail is the confirmation email.

```<code><form  id="newaccount" name="newaccount" method="post" action="phpfiles/accountcode.php" onSubmit="return emailvalid()" >
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="cemail" onBlur="emailvalid()" />
<input type="submit" value="New"/>
</form>
</code>```

I hope I have laid it out well enough. I am open to ANY ideas as I am rather new at this.

答:
Not related to the issue: I spotted unreachable code here

```<code>    if(email != '' && confirmemail != '')
{
    if(email == '')
    {
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'You must enter a valid email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
    }
</code>```

The code inside 2nd "if" will never be executed because email != '' according to 1st "if".

ContentLicense: CC BY-SA 4.0

Body:
I have found this Related entry and a few others but I have not quite found my answer so I am posting new. I am trying to run a database query from JavaScript using what I understand of Ajax. I need to return false if the email is already in the database and return true if it does not, but I cannot seem to figure out what I am doing wrong. I have posted my first attempt before I started messing around and making it messy.

JavaScript: It seems to return true no matter what.

function emailvalid(){

var email = document.getElementById('email').value;
var confirmemail = document.getElementById('cemail').value;
if(email != '' && confirmemail != '')
{
    if(email == '')
    {
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'You must enter a valid email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
    }

xmlhttp = new XMLHttpRequest();
var url="phpfiles/checkemail.php";
url = url+"?email="+email+"&cemail="+confirmemail;
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState==4)
    {
        var answer = xmlhttp.responseText;
        if(answer == 'r0')
        {

        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'This email address is already associated with an exiting account. Please login or use a different email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
        }
        else if(answer == 'r1')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Emails match and are valid";
        document.getElementById('tdcemail').style.color = 'green';
        document.getElementById('tdcemail').innerHTML = "Emails match and are valid";
        document.getElementById('cemail').style.backgroundColor ='green';
        return true;
        }
        else if(answer == 'r2')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = "Email is not valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Email is not valid.";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r3')
        {

        document.getElementById('tdemail').style.color = 'green';
        document.getElementById('email').style.backgroundColor ='green';
        document.getElementById('tdemail').innerHTML = "Email is valid";
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = "Emails do not match";
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
        else if(answer == 'r4')
        {

        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('tdcemail').style.color = 'red';
        document.getElementById('tdcemail').innerHTML = 'Please enter a valid email address.';
        document.getElementById('cemail').style.backgroundColor ='red';
        return false;
        }
    }
}
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);

}
else
{
    document.getElementById('tdemail').style.color = 'red';
    document.getElementById('email').style.backgroundColor ='red';
    document.getElementById('tdemail').innerHTML = "Email is not valid";
    document.getElementById('tdcemail').style.color = 'red';
    document.getElementById('tdcemail').innerHTML = "Email is not valid.";
    document.getElementById('cemail').style.backgroundColor ='red';
    return false;
}
}

The innerHTML stuff works just fine which is also why I am confused.

PHP: works fine as far as I can tell.

<?php
$email = $_GET['email'];
$cemail = $_GET['cemail'];
$emailvalidstring = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
include('connection.php');

$checkemailquery = "SELECT email FROM users WHERE email='".$email."'";
$checkemailresult = mysql_query($checkemailquery);

// if query failed.
if(!$checkemailresult)
{
    $error = mysql_error();
    print $error;
    exit;
}
//if the query did run, the email exists. Print error and exit.
if(mysql_affected_rows() != 0)
{
    echo "r0";
    return false;
}
else{
    if(preg_match($emailvalidstring, $email) && $email == $cemail)
    {
        echo "r1";
        return true;
    }
    else if(!preg_match($emailvalidstring, $email) && $email == $cemail)
    {
            echo "r2";
            return false;
    }
    else if(preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r3";
        return false;
    }
    else if(!preg_match($emailvalidstring, $email) && $email != $cemail)
    {
        echo "r4";
        return false;
    }
}
?>

html: I have it do a double check, once to alert the user if it is already taken, and then a second check on the server to make sure it is still true. cemail is the confirmation email.

<form  id="newaccount" name="newaccount" method="post" action="phpfiles/accountcode.php" onSubmit="return emailvalid()" >
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="cemail" onBlur="emailvalid()" />
<input type="submit" value="New"/>
</form>

I hope I have laid it out well enough. I am open to ANY ideas as I am rather new at this.

Body:
Not related to the issue: I spotted unreachable code here

    if(email != '' && confirmemail != '')
{
    if(email == '')
    {
        document.getElementById('email').style.backgroundColor ='red';
        document.getElementById('tdemail').style.color = 'red';
        document.getElementById('tdemail').innerHTML = 'You must enter a valid email address.';
        document.getElementById('tdcemail').innerHTML = '';
        document.getElementById('cemail').value = '';
        return false;
    }

The code inside 2nd "if" will never be executed because email != '' according to 1st "if".


问:
play specific start and end duration within audio using html-5
I would like a create a webpage like explained in this question:
How to play specific start and end duration in HTML5 audio?
My question is how to create such table and the necessary ajax to play audio with specific start and end duration. Thank you.</p>

答:
You can use Media Fragments URI to play specific time ranges of media resource

Play first 30 seconds of audio
<audio controls src="https://upload.wikimedia.org/wikipedia/commons/b/be/Hidden_Tribe_-_Didgeridoo_1_Live.ogg#t=0,30"></audio>

Play from 30 to 50 seconds of audio
<audio controls src="https://upload.wikimedia.org/wikipedia/commons/b/be/Hidden_Tribe_-_Didgeridoo_1_Live.ogg#t=30,50"></audio>```

Body:
You can use Media Fragments URI to play specific time ranges of media resource

<label>Play first 30 seconds of audio</label><br><audio controls src="https://upload.wikimedia.org/wikipedia/commons/b/be/Hidden_Tribe_-_Didgeridoo_1_Live.ogg#t=0,30"></audio><br><br>
<label>Play from 30 to 50 seconds of audio</label><br><audio controls src="https://upload.wikimedia.org/wikipedia/commons/b/be/Hidden_Tribe_-_Didgeridoo_1_Live.ogg#t=30,50"></audio>


问:
how can we change the button size in java code
I created the button in java code and i cant change the size of the button.I used

```<code>            btn = new Button(Activity.this);
    btn.setText("\t\t" + lbl + "\t\t\t  ");
            btn.setBackgroundResource(R.drawable.blue_button);
    btn.setwidth(100);
</code>```

but no use.Any idea?  Thanks

答:
```<code>//converting dps to pixels dip-pixel
//username refers to edittext in the main UI thread
</code>```

You need

```<code>Resources r = getResources();
int px =(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP
                                  ,200
                                  ,r.DisplayMetrics());
username.setWidth(px);
</code>```

you need to convert device pixels into pixels to set the width. Here, 200 is the width of edittext UI widget in dp.

Watch this tutorial

Body:
I created the button in java code and i cant change the size of the button.I used

            btn = new Button(Activity.this);
    btn.setText("\t\t" + lbl + "\t\t\t  ");
            btn.setBackgroundResource(R.drawable.blue_button);
    btn.setwidth(100);

but no use.Any idea?  Thanks

Body:
//converting dps to pixels dip-pixel
//username refers to edittext in the main UI thread

You need

Resources r = getResources();
int px =(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP
                                  ,200
                                  ,r.DisplayMetrics());
username.setWidth(px);

you need to convert device pixels into pixels to set the width. Here, 200 is the width of edittext UI widget in dp.

Watch this tutorial


问:
Live Search with Node.js and MongoDB
So I am trying to make a live search feature where a user can search for other users based on username and the relevant results will be shown on the webpage. So far, I have only come across resources that show how to do this for PHP and MySQL. How can this be achieved for Node.js and MongoDB? I'm using socket.io in my project, could this be used at all?

Thanks for the help, and if any of my code is needed, just let me know!

答:
In your requirement, it doesn't depend much on which backend to use.

On the backend just create a rest API to handle the search request (if you want to use NodeJS, you can refer this article https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4).

On the frontend, you can use just XHR request to make live search, no need socket. Each time user type on an input, detect the input change event and send the search request to the backend api (you can do it by just pure javascript XHR request, or use ajax module in JQuery ...), fetch the result from response, print to the screen.
After you can achieve this, you can improve your search performance on the frontend by limiting request in amount of time (not sending request each time use press a key, but after an amount of time, example each 200ms, this technique call "debounce").

Title: Live Search with Node.js and MongoDB


问:
"Email already taken" redirect_to login page
If the validation fails...

user.rb

```<code>  validates :name,  presence: true, length: { maximum: 20 }
  validates :last_name,  presence: true, length: { maximum: 20 }
  validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, unless: -> { from_omniauth? }
  has_secure_password
</code>```

because "Email already taken" the user should be redirected to sessions/new to login otherwise the users/new page should refresh with the appropriate error message such as, "Password can't be blank".

users_controller

```<code>  if # How to make conditional work where if email is already taken do this...
    flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
    render 'sessions/new'
  else
    render 'new'
  end
</code>```

User put email that already exists...

```<code>Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"teFpI/xcFe4Ngdtcj8+7DEj+3ipMBObjzBjs143ILQ/bpefsZSuWWh7cxKJJRXqmCAW+35/H9UPKB56SDdO+6A==", "user"=>{"name"=>"test", "last_name"=>"mon", "email"=>"testmonkey@gmail.com", "password"=>"[FILTERED]", "time_zone"=>"Eastern Time (US & Canada)", "subscribe"=>"0"}, "button"=>""}
   (0.2ms)  BEGIN
  User Exists (0.5ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('testmonkey@gmail.com') LIMIT 1
   (0.2ms)  ROLLBACK
  Rendered sessions/new.html.erb within layouts/application (2.0ms)
  Rendered layouts/_header.html.erb (1.4ms)
Completed 200 OK in 496ms (Views: 159.6ms | ActiveRecord: 4.7ms)
</code>```

user.rb

```<code>  validates :name,  presence: true, length: { maximum: 20 }
  validates :last_name,  presence: true, length: { maximum: 20 }
  validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, unless: -> { from_omniauth? }
  has_secure_password
</code>```

答:
I will do something like this:</p>

```<code>def create
  if User.find_by(email: params[:user][:email]).present?
    flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
    render 'sessions/new'
  else
    @user = User.new(user_params)

    if @user.save
      # handle successful save
    else
      render 'new'
    end
  end
end
</code>```

Body:
If the validation fails...

user.rb

  validates :name,  presence: true, length: { maximum: 20 }
  validates :last_name,  presence: true, length: { maximum: 20 }
  validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, unless: -> { from_omniauth? }
  has_secure_password

because "Email already taken" the user should be redirected to sessions/new to login otherwise the users/new page should refresh with the appropriate error message such as, "Password can't be blank".

users_controller

  if # How to make conditional work where if email is already taken do this...
    flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
    render 'sessions/new'
  else
    render 'new'
  end

User put email that already exists...

Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"teFpI/xcFe4Ngdtcj8+7DEj+3ipMBObjzBjs143ILQ/bpefsZSuWWh7cxKJJRXqmCAW+35/H9UPKB56SDdO+6A==", "user"=>{"name"=>"test", "last_name"=>"mon", "email"=>"testmonkey@gmail.com", "password"=>"[FILTERED]", "time_zone"=>"Eastern Time (US & Canada)", "subscribe"=>"0"}, "button"=>""}
   (0.2ms)  BEGIN
  User Exists (0.5ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('testmonkey@gmail.com') LIMIT 1
   (0.2ms)  ROLLBACK
  Rendered sessions/new.html.erb within layouts/application (2.0ms)
  Rendered layouts/_header.html.erb (1.4ms)
Completed 200 OK in 496ms (Views: 159.6ms | ActiveRecord: 4.7ms)

user.rb

  validates :name,  presence: true, length: { maximum: 20 }
  validates :last_name,  presence: true, length: { maximum: 20 }
  validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, unless: -> { from_omniauth? }
  has_secure_password

Body:
I will do something like this:

def create
  if User.find_by(email: params[:user][:email]).present?
    flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
    render 'sessions/new'
  else
    @user = User.new(user_params)

    if @user.save
      # handle successful save
    else
      render 'new'
    end
  end
end


问:
AWS SNS : Case of multiple subscribers
I am a beginner in using AWS services. I have a requirement recently in which I wanted to send some data from service 1 to service 2 and service 3. So, what I am thinking to do is, I will push notification to SNS from service 1 and service 2 and service 3 would be subscribers to this SNS topic. So, this is the case of multiple subscribers subscribed to the same topic and both subscribers want same data.

I have some doubts regarding the basic functionality of AWS SNS. If someone could help in that, that would be really helpful.

Say, there are 2 notifications A, B pushed to SNS topic, so will both the subscribers get both of the notification?

For the same scenario, when does the 2 notifications gets deleted from SNS topic?

Does SNS store the notifications somewhere? Or it simply passes through the messages to subscribers?

What would happen if one of the subscribers fails and it is not able to get some notifications? Will it get those notifications when it would again connect to SNS topic or it would not get those?

Please provide your answers to some of the above questions. These would really help me in understanding how SNS work internally.

Thanks for help.

答:
Messages sent to SNS topics go to all subscribers.

Publishers send messages to topics. Once a new message is published, Amazon SNS attempts to deliver that message to every endpoint that is subscribed to the topic. (emphasis added)

http://docs.aws.amazon.com/sns/latest/dg/PublishTopic.html

Messages do not actually get "deleted" from a topic (you may be thinking of SQS)... but they don't persist, either.  They are published, and then they are gone.

An apparent exception to this -- retry policies -- is not really an exception.  The message, in this case, has been published and conceptually is already gone from the topic, but SNS can still retry delivery to a specific target.

Everything SNS does is a push.  Subscribers don't connect to SNS and ask for messages.   Once a message is published, it's published.  No future subscribers will ever see an old message, and no subscriber that "missed" it can come back to get it.

However... SNS fanout can send messages to multiple SQS queues.  In that case, you subscribe the queues to the topic, and consume messages from the queues.  Each queue gets a copy of each message, and one consumer from each queue will receive a copy whenever it goes to poll SQS.

An SQS Queue also makes a good backup temporary message retention location.  If you send an SNS messages to some other kind of endpoint -- HTTPS or Lambda for example, you can also send the messages to an SQS queue,   but then under normal operation, don't actually poll the queue.  The messages will automatically be purged from the queue after the maximum message retention period, which defaults to 4 days, but can be configured for a max of 14 days.  If anything goes wrong with the topic subscriber and messages are lost, you can go retrieve them from this backup queue, but otherwise they eventually just disappear on their own when the timeout expires.  There is no limit to the number of messages that can wait, unread, in a queue.

Title: AWS SNS : Case of multiple subscribers


答:
You can check if find_by_email returns something different to nil when looking for the email in the existing records:

```<code>if User.find_by(email: params[:user][:email])
  flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
  render 'sessions/new'
else
  render 'new'
end
</code>```

Or if you want to be more specific, you can use ActiveRecord#exists?:

```<code>if User.exists?(email: params[:user][:email])
  flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
  render 'sessions/new'
else
  render 'new'
end
</code>```

Title: "Email already taken" redirect_to login page

Body:
You can check if find_by_email returns something different to nil when looking for the email in the existing records:

if User.find_by(email: params[:user][:email])
  flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
  render 'sessions/new'
else
  render 'new'
end

Or if you want to be more specific, you can use ActiveRecord#exists?:

if User.exists?(email: params[:user][:email])
  flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
  render 'sessions/new'
else
  render 'new'
end


问:
file.delete() in Android leaves a small unreadable file
I am trying to delete an image from my gallery. I'm using the code I got from here:

android : deleting an image

It seems to work for some people, but unfortunately not for me. If I run it, a small, unreadable file remains behind. I'm on Android 4.1.2.

Here is the code:

```<code>public void deleteImage(File fdelete) {
    //String file_dj_path = Environment.getExternalStorageDirectory() + "/ECP_Screenshots/abc.jpg";
    //File fdelete = new File(file_dj_path);
    if (fdelete.exists()) {
        if (fdelete.delete()) {
            Log.e("-->", "file Deleted :" + fdelete);
            callBroadCast();
        } else {
            Log.e("-->", "file not Deleted :" + fdelete);
        }
    }
}

public void callBroadCast() {
    if (Build.VERSION.SDK_INT >= 14) {
        Log.e("-->", " >= 14");
        MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
            /*
             *   (non-Javadoc)
             * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
             */
            public void onScanCompleted(String path, Uri uri) {
                Log.e("ExternalStorage", "Scanned " + path + ":");
                Log.e("ExternalStorage", "-> uri=" + uri);
            }
        });
    } else {
        Log.e("-->", " < 14");
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }
}
</code>```

答:
If by

small unreadable file

you mean zero, you can do something like this:

```<code>long fileSize = fdelete.length();
if (fdelete.exists() || fileSize==0){
    fdelete.delete();
}
</code>```

Then do

```<code>    if (fdelete.delete()) {
        Log.e("-->", "file Deleted :" + fdelete);
        callBroadCast();
    } else {
        Log.e("-->", "file not Deleted :" + fdelete);
    }
</code>```

Body:
I am trying to delete an image from my gallery. I'm using the code I got from here:

android : deleting an image

It seems to work for some people, but unfortunately not for me. If I run it, a small, unreadable file remains behind. I'm on Android 4.1.2.

Here is the code:

public void deleteImage(File fdelete) {
    //String file_dj_path = Environment.getExternalStorageDirectory() + "/ECP_Screenshots/abc.jpg";
    //File fdelete = new File(file_dj_path);
    if (fdelete.exists()) {
        if (fdelete.delete()) {
            Log.e("-->", "file Deleted :" + fdelete);
            callBroadCast();
        } else {
            Log.e("-->", "file not Deleted :" + fdelete);
        }
    }
}

public void callBroadCast() {
    if (Build.VERSION.SDK_INT >= 14) {
        Log.e("-->", " >= 14");
        MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
            /*
             *   (non-Javadoc)
             * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
             */
            public void onScanCompleted(String path, Uri uri) {
                Log.e("ExternalStorage", "Scanned " + path + ":");
                Log.e("ExternalStorage", "-> uri=" + uri);
            }
        });
    } else {
        Log.e("-->", " < 14");
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }
}

Body:
If by

small unreadable file

you mean zero, you can do something like this:

long fileSize = fdelete.length();
if (fdelete.exists() || fileSize==0){
    fdelete.delete();
}

Then do

    if (fdelete.delete()) {
        Log.e("-->", "file Deleted :" + fdelete);
        callBroadCast();
    } else {
        Log.e("-->", "file not Deleted :" + fdelete);
    }


问:
Download the .exe file instead of .htm file
My website has an option of downloading a .exe file. I uploaded this .exe file in dropbox and use the shared link in my website for the users to download the file.

I use href in my index.php page to create a link to that file:

```<code><a href="https://www.dropbox.com/s/........./File.exe?dl=0" download="File">
</code>```

But when users click that link in my website it downloads the .htm file. The users need to click this .htm file again which then leads to the download of the .exe file. At times users also get the error "There was an error downloading your file." while downloading the file from dropbox. I would like to know how to get the link to download the .exe file directly. Thanks!!!

答:
When you use  ?d1=0 at the end of your file path it will show the file in a preview page. Try changing it to ?dl=1to force the download.

https://www.dropbox.com/help/desktop-web/force-download

Body:
My website has an option of downloading a .exe file. I uploaded this .exe file in dropbox and use the shared link in my website for the users to download the file.

I use href in my index.php page to create a link to that file:

But when users click that link in my website it downloads the .htm file. The users need to click this .htm file again which then leads to the download of the .exe file. At times users also get the error "There was an error downloading your file." while downloading the file from dropbox. I would like to know how to get the link to download the .exe file directly. Thanks!!!


问:
node-google-image-search error message 'Invalid Value'
I am making a node app which can return google images, I'm using the node-google-image-search app to help me do this. I created a .env file named "env.env" and imported the app with

```<code>const imageSearch = require('node-google-image-search');
const dotenv = require('dotenv').config({path: './env.env'});
</code>```

Then I tried to search something with the following code.

var results = imageSearch('google', callback, 0, 5);

function callback(results) {
    console.log(results);
}```

This caused me to get the following error in the console:

[ { domain: 'global', reason: 'invalid', message: 'Invalid Value' } ]

答:
Are you sure that your account is set up correctly to use Google Custom Search  and that you have the correct keys in your .env file?

Maybe worth just using Google's customsearch example than using a separate module.

Body:
I am making a node app which can return google images, I'm using the node-google-image-search app to help me do this. I created a .env file named "env.env" and imported the app with

const imageSearch = require('node-google-image-search');
const dotenv = require('dotenv').config({path: './env.env'});

Then I tried to search something with the following code.

var results = imageSearch('google', callback, 0, 5);

function callback(results) {
    console.log(results);
}

This caused me to get the following error in the console:

[ { domain: 'global', reason: 'invalid', message: 'Invalid Value' } ]


问:
Clear dropzone.js thumbnail image after uploading an image
I have using dropzone.js in mvc by following this tutorial for uploading images but after uploading the image the thumbnail image still showing and I need it to be removed after every time I upload an image.

I have tried to replace the generated HTML after uploading the image using jQuery but it not showing correctly as the first time I need to refresh the page to show correctly but I don't want to do that.

```<code> $("#ImageUpload").replaceWith('<form action="/Products/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone dz-clickable" id="dropzoneForm">'
 +'<div class="fallback">'
 +'<input name="file" type="file" multiple />'
 +'<input type="submit" value="Upload" />'
 +'</div>');
</code>```

答:
try this on your library dropzone dropzone.js; but set time out to auto close 2500</p>

```<code>success: function(file) {
  if (file.previewElement) {
    return file.previewElement.classList.add("dz-success"),
    $(function(){
      setTimeout(function(){
        $('.dz-success').fadeOut('slow');
      },2500);
    });
  }
},
</code>```

Body:
I have using dropzone.js in mvc by following this tutorial for uploading images but after uploading the image the thumbnail image still showing and I need it to be removed after every time I upload an image.

I have tried to replace the generated HTML after uploading the image using jQuery but it not showing correctly as the first time I need to refresh the page to show correctly but I don't want to do that.

 $("#ImageUpload").replaceWith('<form action="/Products/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone dz-clickable" id="dropzoneForm">'
 +'
'
 +'<input name="file" type="file" multiple />'
 +'<input type="submit" value="Upload" />'
 +'
');

Body:
try this on your library dropzone dropzone.js; but set time out to auto close 2500

success: function(file) {
  if (file.previewElement) {
    return file.previewElement.classList.add("dz-success"),
    $(function(){
      setTimeout(function(){
        $('.dz-success').fadeOut('slow');
      },2500);
    });
  }
},


问:
R: Conditionally replacing values based on column pre-fixes and suffixes
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

```<code>library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")
</code>```

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

```<code>  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6
</code>```

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?

答:
Another attempt which should essentially only be one assignment operation. Using @alistaire's data again:</p>

```<code>vars <- c("x","y")
foo[vars] <- Map(pmax, foo[vars], bar[match(foo$id, bar$id), vars], na.rm=TRUE)
foo

#  id  x y z
#1  1 10 1 1
#2  2  9 2 2
#3  3 NA 3 3
#4  4  1 4 4
#5  5  3 5 5
#6  6  8 6 6
</code>```

Body:
I have two data frames. Data frame A has many observations/rows, an ID for each observation, and many additional columns. For a subset of observations X, the values for a set of columns are missing/NA. Data frame B contains a subset of the observations in X (which can be matched across data frames using the ID) and variables with identical names as in data frame A, but containing values to replace the missing values in the set of columns with missing/NA.

My code below (using a join operation) merely adds columns rather than replacing missing values. For each of the additional variables (let's name them W) in B, the resulting table produces W.x and W.y.

library(dplyr)

foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")

I am trying to replace the missing values in A using the values in B based on the ID, but do so in an efficient manner since I have many columns and many rows. My goal is this:

  id   x z
1  1  10 1
2  2   9 2
3  3  NA 3
4  4   1 4
5  5   3 5
6  6   8 6

One thought was to use ifelse() after joining, but typing out ifelse() functions for all of the variables is not feasible. Is there a way to do this simply without the database join or is there a way to apply a function across all columns ending in .x to replace the values in .x with the value in .y if the value in .x is missing?

Body:
Another attempt which should essentially only be one assignment operation. Using @alistaire's data again:

vars <- c("x","y")
foo[vars] <- Map(pmax, foo[vars], bar[match(foo$id, bar$id), vars], na.rm=TRUE)
foo

#  id  x y z
#1  1 10 1 1
#2  2  9 2 2
#3  3 NA 3 3
#4  4  1 4 4
#5  5  3 5 5
#6  6  8 6 6


问:
Python's requests "Missing dependencies for SOCKS support" when using SOCKS5 from Terminal
I'm trying to interact with an API from my Python 2.7 shell using a package that relies on Python's requests. Thing is the remote address is blocked by my network (university library).

So to speak to the API I do the following:

```<code>~$ ssh -D 8080 name@myserver.com
</code>```

And then, in new terminal, in local computer:

```<code>~$ export http_proxy=socks5://127.0.0.1:8080 https_proxy=socks5://127.0.0.1:8080
</code>```

Then I run the program in Python console but fails:

```<code>~$ python
>>> import myscript
>>> id = '1213'
>>> token = 'jd87jd9'
>>> connect(id,token)

File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 518, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 585, in send
    r = adapter.send(request, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 370, in send
    conn = self.get_connection(request.url, proxies)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 273, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 169, in proxy_manager_for
    **proxy_kwargs
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 43, in SOCKSProxyManager
    raise InvalidSchema("Missing dependencies for SOCKS support.")
requests.exceptions.InvalidSchema: Missing dependencies for SOCKS support.
</code>```

This excerpt is from the adapters.py requests module:

```<code>> try:
>     from .packages.urllib3.contrib.socks import SOCKSProxyManager except ImportError:
>     def SOCKSProxyManager(*args, **kwargs):
>         raise InvalidSchema("Missing dependencies for SOCKS support.")
</code>```

Now problem seems to be originated in urllib3's SOCKSProxyManager.

So I read you can use SOCKSProxyManager with SOCKS5 if you have install PySocks or you do a pip install urllib3[socks]

Alas, I tried both PySocks and urllib3 with Socks without any success.

Any idea of another workaround?

EDIT:

I also tried pip install requests[socks] (that's requests 2.10.0 with Socks support) and I am getting this:

```<code>  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 467, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='api-server.com', port=443): Max retries exceeded with url: /auth (Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x95c7ccc>: Failed to establish a new connection: SOCKS5 proxy server sent invalid data',))
</code>```

答:
I got the same error just a few mins ago.Then re-installed request[socks] via pip.
It seems that there was a missing part of socks which is win-inet_pton. Pip installed it and the problem is solved.

Body:
I'm trying to interact with an API from my Python 2.7 shell using a package that relies on Python's requests. Thing is the remote address is blocked by my network (university library).

So to speak to the API I do the following:

~$ ssh -D 8080 name@myserver.com

And then, in new terminal, in local computer:

~$ export http_proxy=socks5://127.0.0.1:8080 https_proxy=socks5://127.0.0.1:8080

Then I run the program in Python console but fails:

~$ python
>>> import myscript
>>> id = '1213'
>>> token = 'jd87jd9'
>>> connect(id,token)

File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 518, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 585, in send
    r = adapter.send(request, **kwargs)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 370, in send
    conn = self.get_connection(request.url, proxies)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 273, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 169, in proxy_manager_for
    **proxy_kwargs
  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 43, in SOCKSProxyManager
    raise InvalidSchema("Missing dependencies for SOCKS support.")
requests.exceptions.InvalidSchema: Missing dependencies for SOCKS support.

This excerpt is from the adapters.py requests module:

> try:
>     from .packages.urllib3.contrib.socks import SOCKSProxyManager except ImportError:
>     def SOCKSProxyManager(*args, **kwargs):
>         raise InvalidSchema("Missing dependencies for SOCKS support.")

Now problem seems to be originated in urllib3's SOCKSProxyManager.

So I read you can use SOCKSProxyManager with SOCKS5 if you have install PySocks or you do a pip install urllib3[socks]

Alas, I tried both PySocks and urllib3 with Socks without any success.

Any idea of another workaround?

EDIT:

I also tried pip install requests[socks] (that's requests 2.10.0 with Socks support) and I am getting this:

  File "/home/username/.virtualenvs/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 467, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='api-server.com', port=443): Max retries exceeded with url: /auth (Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x95c7ccc>: Failed to establish a new connection: SOCKS5 proxy server sent invalid data',))


问:
customization on emmet's snippets.json file
ENV:debian+vim+emmet.

no backslah at the end of tag when to expand abbreviation

Here is link abbreviation on my .vim/snippets.json file.

```<code>"link": "<link rel=\"stylesheet\" href=\"\" />",
</code>```

When to expand link in emmet, i get the below output:

```<code><link rel="stylesheet" href="">
</code>```

Why can't get

```<code><link rel="stylesheet" href="" />
</code>```

as output?

fail to customize script tag

I expect to expand script as

```<code>sudo vim .vim/snippets.json
"script": "<script !src=\"\">",
</code>```

What does ! here mean?

to rewrite

```<code>"script": "<script !src=\"\">",
</code>```

as

```<code>"script": "<script src=\"\" type=\"text/javascript\">",
</code>```

It take no effect when to reboot vim.

No  as expand of script.

答:
```<code>vim .vimrc
let g:emmet_html5 = 0
</code>```

Body:
ENV:debian+vim+emmet.

no backslah at the end of tag when to expand abbreviation

Here is link abbreviation on my .vim/snippets.json file.

"link": "<link rel=\"stylesheet\" href=\"\" />",

When to expand link in emmet, i get the below output:

<link rel="stylesheet" href="">

Why can't get

<link rel="stylesheet" href="" />

as output?

fail to customize script tag

I expect to expand script as

sudo vim .vim/snippets.json
"script": " as expand of script.

Body:
vim .vimrc
let g:emmet_html5 = 0


问:
PHP to JQuery code conversion [If else]
How can I do it on JQuery? When I click hide, the element will be hidden, same goes for show, the element will be shown. How am I going to do it? Thanks!

```<code><form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="submit" >Show</button>

</form>

<?php

    if (isset($_POST['hidden']) == true){
        echo '*hidden*';
    } else if ($_POST['']) {
        echo 'shown';
    }

?>
</code>```

答:
You can use js like this,</p>

```<code>document.getElementById('domid').style.visibility='hidden';

document.getElementById('domid').style.visibility='visible';
</code>```

Title: PHP to JQuery code conversion [If else]

Body:
How can I do it on JQuery? When I click hide, the element will be hidden, same goes for show, the element will be shown. How am I going to do it? Thanks!

<form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="submit" >Show</button>

</form>

<?php

    if (isset($_POST['hidden']) == true){
        echo '*hidden*';
    } else if ($_POST['']) {
        echo 'shown';
    }

?>

Body:
You can use js like this,

document.getElementById('domid').style.visibility='hidden';

document.getElementById('domid').style.visibility='visible';


答:
```<code>$(document).ready(function(){
   $(input([name='hidden']).click(function(){
      $(this).hide();
   });
    $(input([name='submit']).click(function(){
      $(input([name='hidden']).show();
   });
});
</code>```

Title: PHP to JQuery code conversion [If else]


问:
js can't add timezone offset to '1900-01-01T00:00:00'?
I try to new Date() to get UTC local time,

but now js can't add timezone offset (eg. add 8 hours for china).

before it works right.

In the blog On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API

WebAPI json result with ISO 8601 date format is

'2017-05-10T07:50:16'.

答:
change the default DatetimeConverter :

```<code> IsoDateTimeConverter converter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
        };

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(converter);
</code>```

How to get JSON.NET to serialize date/time to ISO 8601?

Body:
change the default DatetimeConverter :

 IsoDateTimeConverter converter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
        };

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(converter);

How to get JSON.NET to serialize date/time to ISO 8601?


问:
Execute Azure Automation Runbooks Across Tenants
I am able to execute Runbooks within my Azure tenant/subscription, but would like to use a single Azure Automation Account in my tenant to execute Runbooks against other tenants and their subscriptions.

I have found this article for running against multiple subscriptions, but is it possible to have a centralized Azure Automation Account in one tenant that can connect and execute against other tenants and their subscriptions?

https://blogs.technet.microsoft.com/knightly/2017/05/26/using-azure-automation-with-multiple-subscriptions/

答:
Based on my knowledge, if your account is a Auzre AD account, it is possible. Also, your account is Microsoft account, you also could create a Azure AD account. More information about how to create a new Azure AD user please refer to this link.

You could create a credential and store your account and password in it.

You can retrieve the credential in a runbook using the Get-AutomationPSCredential activity and then use it with Add-AzureRmAccount to connect to your Azure subscription. The following commands work for me.

```<code>$cred = Get-AutomationPSCredential –Name "shuitest"
Add-AzureRmAccount –Credential $cred
Select-AzureRmSubscription –SubscriptionName "Your Subscription Name"
</code>```

More information about this, you could refer to this link.

If you want to login multiple tenants in one runbook, you need to sign in separately and execute your PowerShell cmdlets.

Body:
Based on my knowledge, if your account is a Auzre AD account, it is possible. Also, your account is Microsoft account, you also could create a Azure AD account. More information about how to create a new Azure AD user please refer to this link.

You could create a credential and store your account and password in it.

You can retrieve the credential in a runbook using the Get-AutomationPSCredential activity and then use it with Add-AzureRmAccount to connect to your Azure subscription. The following commands work for me.

$cred = Get-AutomationPSCredential –Name "shuitest"
Add-AzureRmAccount –Credential $cred
Select-AzureRmSubscription –SubscriptionName "Your Subscription Name"

More information about this, you could refer to this link.

If you want to login multiple tenants in one runbook, you need to sign in separately and execute your PowerShell cmdlets.


问:
AngularJS form Cannot read property '$setPristine' of undefined
I know there is other similar questions to this, but i've read them all and none of them is working for me.

When i try to set my form to a pristine, I keep getting this error:

TypeError: Cannot read property '$setPristine' of undefined

The controller and my angular version (1.4.2) are everything ok, because i also have other thing happening within the same function calling the $setPristine(); method and that one is working.

This is the code i'm using:

html

```<code><form name="cadTel" novalidate>
    <div class="form_group">
        <label class="col-md-4 f--label"><i class="fa fa-asterisk"></i>Nome</label>
        <div class="col-md-8 f--input">
            <input type="text" name="ds_contato" ng-model="tel.ds_contato" ng-required="true" />
        </div>
    </div>
    <div class="form_group">
        <label class="col-md-4 f--label"><i class="fa fa-asterisk"></i>Telefone</label>
        <div class="col-md-8 f--input">
            <input type="text" name="num_tel" mask="(99) 9?9999-9999" ng-model="tel.num_tel" ng-required="true" />
        </div>
    </div>
    <input type="button" class="bt-m bt-suc" name="cadastrar" value="Salvar" ng-click="add_telefone(tel)">
    <div class="bt-m bt-war" ng-click="reset()">Limpar</div>
</form>
</code>```

app.js

```<code>$scope.tel = {};

$scope.add_telefone = function(tel) {
    $scope.tel = angular.copy(tel);
    $http({
        method: 'POST',
        url:'dist/php/db.php?action=add_telefone',
        data:$scope.tel,
    })
    .success(function (data, status, headers, config) {
        $scope.reset();
    })
    .error(function (data, status, headers, config) {
    });
};
$scope.reset = function() {
    $scope.tel = {};
    $scope.cadTel.$setPristine();
};
</code>```

The option to clean the values are working but to set pristine none.

Any ideas?

答:
I am using bootstrap modal to show the forms and when I click Cancel or click outside of modal I wanted to reset the form. I spent hours troubleshooting AngularJS form Cannot read property '$setPristine' of undefined error and solved it by adding a simple condition before reseting the form:

$('#myform-modal').on('hidden.bs.modal', function () {
  resetModal();
});
resetModal = function() {
    if ( $scope.MyForm ) {
      $scope.MyForm.$setPristine();
      $scope.MyForm.$setUntouched();
      $scope.MyForm.$submitted = false;
      delete $scope.data;
    }
}```

Body:
I know there is other similar questions to this, but i've read them all and none of them is working for me.

When i try to set my form to a pristine, I keep getting this error:

TypeError: Cannot read property '$setPristine' of undefined

The controller and my angular version (1.4.2) are everything ok, because i also have other thing happening within the same function calling the $setPristine(); method and that one is working.

This is the code i'm using:

html

<form name="cadTel" novalidate>

        Nome

            <input type="text" name="ds_contato" ng-model="tel.ds_contato" ng-required="true" />

        Telefone

            <input type="text" name="num_tel" mask="(99) 9?9999-9999" ng-model="tel.num_tel" ng-required="true" />

    <input type="button" class="bt-m bt-suc" name="cadastrar" value="Salvar" ng-click="add_telefone(tel)">

Limpar

</form>

app.js

$scope.tel = {};

$scope.add_telefone = function(tel) {
    $scope.tel = angular.copy(tel);
    $http({
        method: 'POST',
        url:'dist/php/db.php?action=add_telefone',
        data:$scope.tel,
    })
    .success(function (data, status, headers, config) {
        $scope.reset();
    })
    .error(function (data, status, headers, config) {
    });
};
$scope.reset = function() {
    $scope.tel = {};
    $scope.cadTel.$setPristine();
};

The option to clean the values are working but to set pristine none.

Any ideas?


问:
Angular $http service not getting objects from .JSON file
Here is my http service code:

```<code>app.controller('StoreController', ['$http', function($http){
    var store = this;
    store.products = [];
    $http.get('/store-products.json').then(function(data){
        store.products = data;
    });
}]);
</code>```

And here is my JSON code:

```<code>[
    {
        "name": "...",
        "price": 20.00,
        "description": "...",
        "canPurchase": false,
        "images": [
            "...jpg",
            "...jpg",
            "...jpg"
        ],
        "reviews": []
    },
    {
        "name": "...",
        "price": 15.95,
        "description": "...",
        "canPurchase": true,
        "images": [],
        "reviews": []
    }
]
</code>```

When I run the code on localhost server, it does not show my objects. There is also no errors in the console that show so I cannot see where I am going wrong. Can anyone see the issue here?

答:
your json data is wrapped at response.data of $http.get.

change to below code will solve the problem(also make sure your json file is at right location).

```<code>$http.get('/store-products.json').then(function(res){
    store.products = res.data;
});
</code>```

Plunker demo.

Body:
Here is my http service code:

app.controller('StoreController', ['$http', function($http){
    var store = this;
    store.products = [];
    $http.get('/store-products.json').then(function(data){
        store.products = data;
    });
}]);

And here is my JSON code:

[
    {
        "name": "...",
        "price": 20.00,
        "description": "...",
        "canPurchase": false,
        "images": [
            "...jpg",
            "...jpg",
            "...jpg"
        ],
        "reviews": []
    },
    {
        "name": "...",
        "price": 15.95,
        "description": "...",
        "canPurchase": true,
        "images": [],
        "reviews": []
    }
]

When I run the code on localhost server, it does not show my objects. There is also no errors in the console that show so I cannot see where I am going wrong. Can anyone see the issue here?

Body:
your json data is wrapped at response.data of $http.get.

change to below code will solve the problem(also make sure your json file is at right location).

$http.get('/store-products.json').then(function(res){
    store.products = res.data;
});

Plunker demo.


问:
shared_from_this called from constructor
I have to register an object in a container upon its creation.
Without smart pointers I'd use something like this:

```<code>a_class::a_class()
{
    register_somewhere(this);
}
</code>```

With smart pointers I should use shared_from_this but I can't use that in the constructor.

Is there a clean way to solve this problem? What would you do in a similar situation?
I'm thinking about introducing an init method to call just after creation and put everything in a factory function like this:

```<code>boost::shared_ptr<a_class> create_a()
{
    boost::shared_ptr<a_class> ptr(new a_class);
    ptr->init();
    return ptr;
}
</code>```

Is it fine or there is a standard procedure to follow in such cases?

EDIT: Actually my case is more complex. I have 2 object which shall maintain pointers each other. So the truth is I'm not "registering" but creating another object (let's say b_class) which requires this as a parameter. b_class receives this as a weak pointer and stores it.

I'm adding this because since you are giving me design advices (which are very appreciated) at least you can know what I'm doing:

```<code>a_class::a_class()
{
    b = new b_class(this);
}
</code>```

In my program a_class is an entity and b_class is one of the concrete classes representing the state (in the constructor it's just the starting state). a_class needs a pointer to the current state and b_class needs to manipulate the entity.

a_class is responsible for creating and destroying b_class instances and thus maintains a shared_ptr to them but b_class need to manipulate a_class and thus maintains a weak pointer. a_class instance "survives" b_class instances.

Do you suggest to avoid using smart pointers in this case?

答:
Here's my solution:

```<code>class MyClass: enable_shared_from_this<MyClass>
{
    public:
        //If you use this, you will die.
        MyClass(bool areYouBeingAnIdiot = true)
        {
            if (areYouBeingAnIdiot)
            {
                throw exception("Don't call this constructor! Use the Create function!");
            }

            //Can't/Don't use this or shared_from_this() here.
        }

        static shared_ptr<MyClass> Create()
        {
            shared_ptr<MyClass> myClass = make_shared<MyClass>(false);

            //Use myClass or myClass.get() here, now that it is created.

            return myClass;
        }
}

//Somewhere.
shared_ptr<MyClass> myClass = MyClass::Create();
</code>```

(The constructor has to be public to be callable from a static member function, even an internal one...)

Body:
I have to register an object in a container upon its creation.
Without smart pointers I'd use something like this:

a_class::a_class()
{
    register_somewhere(this);
}

With smart pointers I should use shared_from_this but I can't use that in the constructor.

Is there a clean way to solve this problem? What would you do in a similar situation?
I'm thinking about introducing an init method to call just after creation and put everything in a factory function like this:

boost::shared_ptr<a_class> create_a()
{
    boost::shared_ptr<a_class> ptr(new a_class);
    ptr->init();
    return ptr;
}

Is it fine or there is a standard procedure to follow in such cases?

EDIT: Actually my case is more complex. I have 2 object which shall maintain pointers each other. So the truth is I'm not "registering" but creating another object (let's say b_class) which requires this as a parameter. b_class receives this as a weak pointer and stores it.

I'm adding this because since you are giving me design advices (which are very appreciated) at least you can know what I'm doing:

a_class::a_class()
{
    b = new b_class(this);
}

In my program a_class is an entity and b_class is one of the concrete classes representing the state (in the constructor it's just the starting state). a_class needs a pointer to the current state and b_class needs to manipulate the entity.

a_class is responsible for creating and destroying b_class instances and thus maintains a shared_ptr to them but b_class need to manipulate a_class and thus maintains a weak pointer. a_class instance "survives" b_class instances.

Do you suggest to avoid using smart pointers in this case?

Body:
Here's my solution:

class MyClass: enable_shared_from_this<MyClass>
{
    public:
        //If you use this, you will die.
        MyClass(bool areYouBeingAnIdiot = true)
        {
            if (areYouBeingAnIdiot)
            {
                throw exception("Don't call this constructor! Use the Create function!");
            }

            //Can't/Don't use this or shared_from_this() here.
        }

        static shared_ptr<MyClass> Create()
        {
            shared_ptr<MyClass> myClass = make_shared<MyClass>(false);

            //Use myClass or myClass.get() here, now that it is created.

            return myClass;
        }
}

//Somewhere.
shared_ptr<MyClass> myClass = MyClass::Create();

(The constructor has to be public to be callable from a static member function, even an internal one...)


问:
How can i refresh data table after updating the data and retain on the pagination page
I used ajax.reload(), but it is not working.

I try the other method to refresh the data but how can i stay on the current pagination table after data been edited.

```<code>$.ajax({
            type: 'GET',
            url: '/test',
            dataType: 'HTML',
            success: function (html) {
                $('#group').html(html);
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
</code>```

I able to refresh the page if using above method but it will always return back to first pagination table. Anyone got idea how to make it how can i stay on the current pagination table after data been edited?

答:
First, you need to get your current page (example: 3).
When you call the function to refresh the content, you need to pass your current page as parameter. For example:

```<code>var myCurrentPage = 3;
$.ajax({
    type: 'GET',
    url: '/test',
    dataType: 'HTML',
    data: {page: myCurrentPage}
    success: function (html) {
        $('#group').html(html);
    },
    error: function (data) {
        console.log('Error:', data);
    }
});
</code>```

The var could be dynamic using input hidden or some element attribute

I hope that you have understood the logic. Tell me if not.

Body:
I used ajax.reload(), but it is not working.

I try the other method to refresh the data but how can i stay on the current pagination table after data been edited.

$.ajax({
            type: 'GET',
            url: '/test',
            dataType: 'HTML',
            success: function (html) {
                $('#group').html(html);
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });

I able to refresh the page if using above method but it will always return back to first pagination table. Anyone got idea how to make it how can i stay on the current pagination table after data been edited?

Body:
First, you need to get your current page (example: 3).
When you call the function to refresh the content, you need to pass your current page as parameter. For example:

var myCurrentPage = 3;
$.ajax({
    type: 'GET',
    url: '/test',
    dataType: 'HTML',
    data: {page: myCurrentPage}
    success: function (html) {
        $('#group').html(html);
    },
    error: function (data) {
        console.log('Error:', data);
    }
});

The var could be dynamic using input hidden or some element attribute

I hope that you have understood the logic. Tell me if not.


问:
How to pass a (byte[] lpData) with integer value to RegSetValueExW P/Invoke
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C#

```<code>[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
            uint lpReserved,
            uint lpType,
            byte[] lpData,
            uint lpcbData);
</code>```

I'm having a problem with the 4th param byte[] lpdata. I need to pass a DWORD with a value of 5 (int) in it. Everything is OK if I pass a string (REG_SZ), just need to convert using the GetBytes function.

If I call GetBytes("5") it converts it to ascii value
of 53 so it writes 53 on the registry value instead of 5

答:
I've got to start by asking why you are using PInvoke here when there is already a method for setting registry values in the Microsoft.Win32.RegistryKey class? Or are you stuck using an old version of the Compact Framework?

Assuming you have a good reason for the PInvoke, the easiest answer is just to overload the PInvoke declaration for integer values. i.e.:

```<code>[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
        uint lpReserved,
        uint lpType,
        ref int lpData,
        uint lpcbData);
</code>```

OwnerDisplayName: Roy Astro

Body:
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C#

[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
            uint lpReserved,
            uint lpType,
            byte[] lpData,
            uint lpcbData);

I'm having a problem with the 4th param byte[] lpdata. I need to pass a DWORD with a value of 5 (int) in it. Everything is OK if I pass a string (REG_SZ), just need to convert using the GetBytes function.

If I call GetBytes("5") it converts it to ascii value
of 53 so it writes 53 on the registry value instead of 5

Body:
I've got to start by asking why you are using PInvoke here when there is already a method for setting registry values in the Microsoft.Win32.RegistryKey class? Or are you stuck using an old version of the Compact Framework?

Assuming you have a good reason for the PInvoke, the easiest answer is just to overload the PInvoke declaration for integer values. i.e.:

[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
        uint lpReserved,
        uint lpType,
        ref int lpData,
        uint lpcbData);

OwnerDisplayName: Stephen Martin


问:
regopenkeyex returns 2 on Windows 8.1
I have a 32 bit program which is running in two lanes in the same store. The program tries top open a registry key for query. The operating system is Windows 8.1 64 bit.

On one lane it succeeds, and on the other it fails and regopenkeyex returns 2. GetLastError returns 0.

The key it tries to open is under WOW6432Node.

The program is running under the same Windows user on both machines, the key exists on both. the UAC is set to "Never notify" (lowest), windows version is the same. Everything is supposed to be the same...

I am deliberately not specifying KEY_WOW64_64KEY because the code is supposed to work without it. But even when I do use it I get the same result.

What could be causing this?

The code:

```<code>rc = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
               szKey,
                0,
                KEY_QUERY_VALUE,
                &m_hKey);
</code>```

Thank you.

答:
You actually need to read about the functions you are using on MSDN. The registry functions return the error code directly, they do not use GetLastError!

2 is ERROR_FILE_NOT_FOUND so whatever you are hiding in szKey is not a valid subkey path.

WOW6432Node is a reserved key name that you really should not be using, use KEY_WOW64_32KEY if you need to access the 32-bit registry view in a 64-bit application. A 32-bit application reads keys under the WOW6432Node key by default.

Use Process Monitor to make sure you are accessing the correct key.

Title: regopenkeyex returns 2 on Windows 8.1

Body:
I have a 32 bit program which is running in two lanes in the same store. The program tries top open a registry key for query. The operating system is Windows 8.1 64 bit.

On one lane it succeeds, and on the other it fails and regopenkeyex returns 2. GetLastError returns 0.

The key it tries to open is under WOW6432Node.

The program is running under the same Windows user on both machines, the key exists on both. the UAC is set to "Never notify" (lowest), windows version is the same. Everything is supposed to be the same...

I am deliberately not specifying KEY_WOW64_64KEY because the code is supposed to work without it. But even when I do use it I get the same result.

What could be causing this?

The code:

rc = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
               szKey,
                0,
                KEY_QUERY_VALUE,
                &m_hKey);

Thank you.


问:
How to avoid circular dependency in code first entity framework design
I am trying to create modular (component based) application.

My scenario is so simple, I have a SalesManagement component which contains Invoice, and I have PartyManagement component which contains Customer,

so far so good,
Then I defined a class for Customer as

```<code>public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
}
</code>```

and Invoice as

```<code>public class Invoice {
   public int ID {get;set;}
   public int CustomerID {get;set;}
   public Customer Customer {get;set;}
}
</code>```

in order to have Customer reference in Invoice I referenced PartyManagement in SalesManagement component

then I tried to add a collection of Invoice under customer as

```<code>public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
   public virtual ICollection<Invoice> Invoices {get;set;}
}
</code>```

to make it happen I have to reference InvoiceManagement in PartyManagement which makes a circular dependency between assemblies in compile time

Any idea how to resolve this design issue?

p.s If I keep everything in 1 assembly there is no problem, I want to keep them in separate assemblies

答:
"p.s If I keep everything in 1 assembly there is no problem, I want to keep them in separate assemblies"

Don't. Unless you absolutely have to, this is just going to cause you repeated problems like what you're already seeing.

But, if there is a valid reason to keep your entities in separate assemblies then you either:
A) define shared entities in a common assembly shared across other business-specific assemblies, (chances are this will bubble out to a point where you might as well have just 1 assembly.)
B) use bounded contexts so that a "Customer" and/or "invoice" as it relates to one set of business entities can remain independent and unique compared to references consumed by other business entities.

If the parent entities cannot exist in the same assembly with each other, then you should strongly reconsider attempting to "share" any of their children. Given Assembly A deals heavily with Customers, and Assembly B deals heavily with Invoices, but would cause a circular reference back to (A) to associate a Customer with an Invoice, then what you should look at having is a concept of a Customer and Invoice (if needed) within Assembly A, and a Customer and Invoice defined in Assembly B.  Chances are if Logic using Assembly A entities "uses" any data from Invoices it would be minimal, or not even used at all. The entity for an "Invoice" could be kept very lightweight. Assembly B might deal more heavily with Invoices, and only need token information about Customers.

By splitting the domain you can keep the implementation of entities fit for purpose which can improve performance. So for instance when you're dealing with something from Assembly A where you want Customer details and don't care about invoices, the Customer implementation in A doesn't even have Invoices mapped, or a simple invoice entity serving as a summary view. (I refer to these entities in my bounded contexts as "lightweights") Just keep in mind that only one context should serve as the responsible party for any given entity. (Only one bounded context mapping a "heavyweight" entity) In the above example, the heavyweight Customer would reside in assembly A, with the heavyweight Invoice in Assembly B. Lightweights can be shared between bounded contexts by using file links in the projects but that's often more trouble than it's worth.

Body:
I am trying to create modular (component based) application.

My scenario is so simple, I have a SalesManagement component which contains Invoice, and I have PartyManagement component which contains Customer,

so far so good,
Then I defined a class for Customer as

public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
}

and Invoice as

public class Invoice {
   public int ID {get;set;}
   public int CustomerID {get;set;}
   public Customer Customer {get;set;}
}

in order to have Customer reference in Invoice I referenced PartyManagement in SalesManagement component

then I tried to add a collection of Invoice under customer as

public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
   public virtual ICollection<Invoice> Invoices {get;set;}
}

to make it happen I have to reference InvoiceManagement in PartyManagement which makes a circular dependency between assemblies in compile time

Any idea how to resolve this design issue?

p.s If I keep everything in 1 assembly there is no problem, I want to keep them in separate assemblies