问:
Why I can't create an index on temporary table?
First I created a temporary table

```<code>CREATE GLOBAL TEMPORARY TABLE TMP ON COMMIT PRESERVE ROWS AS
SELECT *
FROM A
</code>```

then

```<code>INSERT INTO TMP
SELECT *
FROM B

COMMIT
</code>```

finally

```<code>CREATE INDEX IDX ON TMP (COLA, COLB, COLC);
</code>```

Upon creating the index, I got the following error

ORA-14452: attempt to create, alter or drop an index on temporary table already in use

I followd these steps in the same session.

What I want to do(with temporary table) is

Disable/Drop index

Insert large data

Enable/Create index

How can I acheive this?

答:
I have to admit to being surprised by this. The only solution I have come up with so far is to re-establish the session</p>

```<code>SQL> drop table tmp;

Table dropped.

SQL>
SQL> CREATE GLOBAL TEMPORARY TABLE TMP ON COMMIT PRESERVE ROWS AS
  2  SELECT *
  3  FROM emp
  4  ;

Table created.

SQL>
SQL>
SQL> INSERT INTO TMP
  2  SELECT *
  3  FROM emp
  4  ;

14 rows created.

SQL>
SQL> COMMIT
  2  ;

Commit complete.

SQL>
SQL> connect scott/tiger
Connected.
SQL>
SQL> CREATE INDEX IDX ON TMP (empno);

Index created.
</code>```

Body:
First I created a temporary table

CREATE GLOBAL TEMPORARY TABLE TMP ON COMMIT PRESERVE ROWS AS
SELECT *
FROM A

then

INSERT INTO TMP
SELECT *
FROM B

COMMIT

finally

CREATE INDEX IDX ON TMP (COLA, COLB, COLC);

Upon creating the index, I got the following error

ORA-14452: attempt to create, alter or drop an index on temporary table already in use

I followd these steps in the same session.

What I want to do(with temporary table) is

Disable/Drop index

Insert large data

Enable/Create index

How can I acheive this?

Body:
I have to admit to being surprised by this. The only solution I have come up with so far is to re-establish the session

SQL> drop table tmp;

Table dropped.

SQL>
SQL> CREATE GLOBAL TEMPORARY TABLE TMP ON COMMIT PRESERVE ROWS AS
  2  SELECT *
  3  FROM emp
  4  ;

Table created.

SQL>
SQL>
SQL> INSERT INTO TMP
  2  SELECT *
  3  FROM emp
  4  ;

14 rows created.

SQL>
SQL> COMMIT
  2  ;

Commit complete.

SQL>
SQL> connect scott/tiger
Connected.
SQL>
SQL> CREATE INDEX IDX ON TMP (empno);

Index created.


来源: stackexchange

问:
Generating CSV file from SqlDataSource/GridView
I need to be able to generate a basic CSV file of the results returned from an SqlDataSource/GridView upon the user clicking a button, then allow them to save this file.

Is this simple to do?

Thanks

答:
For a GridView you could use this:</p>

```<code>            StreamWriter writer = new StreamWriter("file.csv");

            // Write columns
            writer.Write(myGridView.Columns[0].HeaderText);
            for (int i = 1; i < myGridView.Columns.Count; i++)
                writer.Write("," + myGridView.Columns[i].HeaderText);

            writer.Write("\n");

            // Write values
            for (int x = 0; x < myGridView.Rows.Count; x++)
            {
                writer.Write(myGridView.Rows[x].Cells[0].Text);
                for (int i = 1; i < myGridView.Rows[x].Cells.Count; i++)
                    writer.Write("," + myGridView.Rows[x].Cells[i].Text);

                writer.Write("\n");
            }

            writer.Close();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For a GridView you could use this:

            StreamWriter writer = new StreamWriter("file.csv");

            // Write columns
            writer.Write(myGridView.Columns[0].HeaderText);
            for (int i = 1; i < myGridView.Columns.Count; i++)
                writer.Write("," + myGridView.Columns[i].HeaderText);

            writer.Write("\n");

            // Write values
            for (int x = 0; x < myGridView.Rows.Count; x++)
            {
                writer.Write(myGridView.Rows[x].Cells[0].Text);
                for (int i = 1; i < myGridView.Rows[x].Cells.Count; i++)
                    writer.Write("," + myGridView.Rows[x].Cells[i].Text);

                writer.Write("\n");
            }

            writer.Close();


问:
why interpolate is not a function in d3
I'm trying to make line chart using D3. Here is my code. I am getting this error:

interpolate is not a function

https://jsbin.com/ruvumocijo/edit?html,output

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.4/d3.js"></script>

    <script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>
</head>
<body>

<script>
     var w = 200,
        h = 200,
        data = [{
            month: 2,
            winper: 20
        }, {
            month: 4,
            winper: 80
        },{
                month: 6,
                winper: 90
            }];
    var svg = d3.select('body').append('svg').attrs({
        width: w,
        height: h
    })
    var line_one= d3.line().x(function (d) {
         return d.month*2
     }).y(function (d) {
        return h- (d.winper*3)
    }).interpolate("linear")

    svg.append("path").attrs({
        d:line_one(data),
        fill:"none",
        "stroke-width":2,
        "stroke":"blue"
    })

</script>
</body>
</html>
</code>```

答:
interpolate has removed in d3 version 4 (the version you are using).  From the changes documentation:

4.0 introduces a new curve API for specifying how line and area shapes interpolate between data points. The line.interpolate and
  area.interpolate methods have been replaced with line.curve and
  area.curve. Curves are implemented using the curve interface rather
  than as a function that returns an SVG path data string; this allows
  curves to render to either SVG or Canvas. In addition, line.curve and
  area.curve now take a function which instantiates a curve for a given
  context, rather than a string.

If you want a linear interpolation, it's the default and you don't need to specify anything:

```<code>var line_one= d3.line().x(function (d) {
  return d.month*2
}).y(function (d) {
  return h- (d.winper*3)
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: why interpolate is not a function in d3

Body:
I'm trying to make line chart using D3. Here is my code. I am getting this error:

interpolate is not a function

https://jsbin.com/ruvumocijo/edit?html,output

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Body:
interpolate has removed in d3 version 4 (the version you are using).  From the changes documentation:

4.0 introduces a new curve API for specifying how line and area shapes interpolate between data points. The line.interpolate and
  area.interpolate methods have been replaced with line.curve and
  area.curve. Curves are implemented using the curve interface rather
  than as a function that returns an SVG path data string; this allows
  curves to render to either SVG or Canvas. In addition, line.curve and
  area.curve now take a function which instantiates a curve for a given
  context, rather than a string.

If you want a linear interpolation, it's the default and you don't need to specify anything:

var line_one= d3.line().x(function (d) {
  return d.month*2
}).y(function (d) {
  return h- (d.winper*3)
});


问:
PHP email and url validation
So I've made myself a little contact form with php, css, and html. But when I try to add a email validation it still sends the email and doesn't change the style of the input to red (Like I would like it to). Another issue I'm having is the button redirecting to the top of the page (which I do not want it to do). Last I can I make the input keep the text rather than remove it once submitted

HTML:

```<code><div id="contact">
        <div class="container">
            <form id="contact-form" method="post">
            <h1>Contact Form</h1>
            <fieldset>
                <input placeholder="Your Name" type="text" name="name" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Email Address" type="email" name="email" id="email-input" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Web Site (optional)" type="url" name="site" required>
            </fieldset>
            <fieldset>
                <textarea placeholder="Type your message here...." name="message" required></textarea>
            </fieldset>
            <fieldset>
                <button type="submit" id="contact-submit" name="submit">Submit</button>
            </fieldset>
            </form>
        </div>
    </div>
</code>```

PHP:

```<code><?php
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $visitors_site = $_POST['site'];
        $message = $_POST['message'];

        $email_from = 'mattmowen1@gmail.com';
        $email_subject = 'New Contact Submission';

        $to = 'mattmowen1@gmail.com';
        $headers = "From:" . $email;
        $headers = "Contact Submission From: " . $email;
        $message1 = "Name: " . $name;
        $message2 = "\n\nEmail: " . $email;
        $message3 = "\n\nPhone: " . $phone;
        $message4 = "\n\nTheir Site: " . $visitors_site;
        $message5 = "\n\nMessage: " . $message;
        $email_body = $message1 . $message2 . $message3 . $message4 . $message5;

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            mail($to, $email_subject, $email_body,$headers);
        } else {
            echo "<style>#email-input {color:red}</style";
        }
?>
</code>```

答:
Try this for email validation in php

```<code><?php

if (isset($_POST) && !empty($_POST)) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $visitors_site = $_POST['site'];
        $message = $_POST['message'];

        $email_from = 'mattmowen1@gmail.com';
        $email_subject = 'New Contact Submission';

        $to = 'mattmowen1@gmail.com';
        $headers = "From:" . $email;
        $headers = "Contact Submission From: " . $email;
        $message1 = "Name: " . $name;
        $message2 = "\n\nEmail: " . $email;
        $message3 = "\n\nPhone: " . $phone;
        $message4 = "\n\nTheir Site: " . $visitors_site;
        $message5 = "\n\nMessage: " . $message;
        $email_body = $message1 . $message2 . $message3 . $message4 . $message5;

        if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
          mail($to, $email_subject, $email_body,$headers);
        } else {
          echo "<style>#email-input {color:red}</style>";
        }
}
?>
</code>```

As per our chat conversation. I am adding jquery ajax function according to your form requirement.
You need to create new file email.php and put your php code into this separate php file

```<code><script>
    var url = 'email.php';
    $.ajax({
        url : url,
        type : "POST",
        dataType : "JSON",
        data : $('#contact-form').serialize(),
        success : function(response) {
            if (response.error == 0) { // success
                $('#contact-form')[0].reset();
                alert('Form submitted successfully. We will contact you asap.');
            } else { // error
                $('#email-input').css('color', 'red');//in case of email error
                alert('ERROR MESSAGE');//form is invalid
            }
        }
    })

</script>
</code>```

To handle JSON request you need to send JSON object in response. So change you php code snippet like this:

```<code>if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  mail($to, $email_subject, $email_body,$headers);
  exit(json_encode(array('error' => 0)));
} else {
  exit(json_encode(array('error' => 1)));
}
</code>```

Title: PHP email and url validation

Body:
So I've made myself a little contact form with php, css, and html. But when I try to add a email validation it still sends the email and doesn't change the style of the input to red (Like I would like it to). Another issue I'm having is the button redirecting to the top of the page (which I do not want it to do). Last I can I make the input keep the text rather than remove it once submitted

HTML:

            <form id="contact-form" method="post">

Contact Form

            <fieldset>
                <input placeholder="Your Name" type="text" name="name" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Email Address" type="email" name="email" id="email-input" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
            </fieldset>
            <fieldset>
                <input placeholder="Your Web Site (optional)" type="url" name="site" required>
            </fieldset>
            <fieldset>
                <textarea placeholder="Type your message here...." name="message" required></textarea>
            </fieldset>
            <fieldset>
                <button type="submit" id="contact-submit" name="submit">Submit</button>
            </fieldset>
            </form>

PHP:

<?php
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $visitors_site = $_POST['site'];
        $message = $_POST['message'];

        $email_from = 'mattmowen1@gmail.com';
        $email_subject = 'New Contact Submission';

        $to = 'mattmowen1@gmail.com';
        $headers = "From:" . $email;
        $headers = "Contact Submission From: " . $email;
        $message1 = "Name: " . $name;
        $message2 = "\n\nEmail: " . $email;
        $message3 = "\n\nPhone: " . $phone;
        $message4 = "\n\nTheir Site: " . $visitors_site;
        $message5 = "\n\nMessage: " . $message;
        $email_body = $message1 . $message2 . $message3 . $message4 . $message5;

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            mail($to, $email_subject, $email_body,$headers);
        } else {
            echo "

Body:
Try this for email validation in php

<?php

if (isset($_POST) && !empty($_POST)) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $visitors_site = $_POST['site'];
        $message = $_POST['message'];

        $email_from = 'mattmowen1@gmail.com';
        $email_subject = 'New Contact Submission';

        $to = 'mattmowen1@gmail.com';
        $headers = "From:" . $email;
        $headers = "Contact Submission From: " . $email;
        $message1 = "Name: " . $name;
        $message2 = "\n\nEmail: " . $email;
        $message3 = "\n\nPhone: " . $phone;
        $message4 = "\n\nTheir Site: " . $visitors_site;
        $message5 = "\n\nMessage: " . $message;
        $email_body = $message1 . $message2 . $message3 . $message4 . $message5;

        if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
          mail($to, $email_subject, $email_body,$headers);
        } else {
          echo "<style>#email-input {color:red}</style>";
        }
}
?>

As per our chat conversation. I am adding jquery ajax function according to your form requirement.
You need to create new file email.php and put your php code into this separate php file

<script>
    var url = 'email.php';
    $.ajax({
        url : url,
        type : "POST",
        dataType : "JSON",
        data : $('#contact-form').serialize(),
        success : function(response) {
            if (response.error == 0) { // success
                $('#contact-form')[0].reset();
                alert('Form submitted successfully. We will contact you asap.');
            } else { // error
                $('#email-input').css('color', 'red');//in case of email error
                alert('ERROR MESSAGE');//form is invalid
            }
        }
    })

</script>

To handle JSON request you need to send JSON object in response. So change you php code snippet like this:

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  mail($to, $email_subject, $email_body,$headers);
  exit(json_encode(array('error' => 0)));
} else {
  exit(json_encode(array('error' => 1)));
}


问:
Need help spotting my mistake in Python
For my class assignment we had to create a Python quiz that asks users to type capitals for states. Their video gave us the answer, but even typing it in as they have it displayed I keep getting an error and my program will not run. My professor is out until Monday, I am hoping someone in here can help me find my error. I am thinking I either have a misspelled word or a IDK... I have been staring at it for hours and line by line it looks the same as the example given.

Thank you for any help.

Here is my code:

```<code># Constant for the number of states to quiz the user on.
NUM_STATES = 5

def main ():
# Initialize the state_caps dictionary.
state_caps = state_cap_dictionary ()

# Initial variables to keep count of the number
# of correct and incorrect answers.
correct = 0
incorrect = 0

#Quiz the user.
for count in range (NUM_STATES) :
     # Get a random entry from the dictionary.
     state, capital = state_caps.popitem ()

#Quiz the user.
print ('What is the capital of ', state, '? ', end=' ')
response = input ()

# Is the user correct?
if response.lower () == capital.lower ():
    correct += 1
    print ('Correct!')
else:
    incorrect += 1
    print ('Incorrect.')

#Display the results
print ('Correct responses: ', correct)
print ('Incorrect answers: ', incorrect)

def state_cap_dictionary ():
  sc = { 'Alabama' : 'Montgomery' ,
      'Alaska' : 'Juneau' ,
      'Arizona' : 'Phoenix' ,
      'Arkansas' : 'Little Rock' ,
      'California' : 'Sacremento' ,
      'Colorado' : 'Denver' ,
      'Conneticut' : 'Hartford' ,
      'Delaware' : 'Dover' ,
      'Florida' : 'Tallahassee' ,
      'Georgia' : 'Atlanta' ,
      'Hawaii' : 'Honolulu' ,
      'Idaho' : 'Boise' ,
      'Illinois' : 'Springfield' ,
      'Indiana' : 'Indianapolis' ,
      'Iowa' : 'Des Moines' ,
      'Kansas' : 'Topeka' ,
      'Kentucky' : 'Frankfurt' ,
      'Lousianna' : 'Baton Rouge' ,
      'Maine' : 'Augusta' ,
      'Maryland' : 'Annapolis' ,
      'Massachusetts' : 'Boston' ,
      'Michigan' : 'Lansing' ,
      'Minnesota' : 'Saint Paul' ,
      'Mississippi' : 'Jackson' ,
      'Missouri' : 'Jefferson City' ,
      'Montana' : 'Helena' ,
      'Nebraska' : 'Lincoln' ,
      'Nevada' : 'Carson City' ,
      'New Hampshire' : 'Concord' ,
      'New Jersey' : 'Trenton' ,
      'New Mexico' : 'Santa Fe' ,
      'New York' : 'Albany' ,
      'North Carolina' : 'Raleigh' ,
      'North Dakota' : 'Bismarck' ,
      'Ohio' : 'Columbus' ,
      'Oklahoma' : 'Oklahoma City' ,
      'Oregon' : 'Salem' ,
      'Pennsylvania' : 'Harrisburg' ,
      'Rhode Island' : 'Providence' ,
      'South Carolina' : 'Columbia' ,
      'South Dakota' : 'Pierre' ,
      'Tennessee' : 'Nashville' ,
      'Texas' : 'Houston' ,
      'Utah' : 'Salt Lake City' ,
      'Vermont' : 'Montpelier' ,
      'Virginia' : 'Richmond' ,
      'Washington' : 'Olympia' ,
      'West Virginia' : 'Charleston' ,
      'Wisconsin' : 'Madison' ,
      'Wyoming' : 'Cheyenne' }
  return sc

main ()
</code>```

答:
With this indentation it works for me:</p>

```<code># Constant for the number of states to quiz the user on.
NUM_STATES = 5

def main():
# Initialize the state_caps dictionary.
     state_caps = state_cap_dictionary()

     # Initial variables to keep count of the number
     # of correct and incorrect answers.
     correct = 0
     incorrect = 0

     #Quiz the user.
     for count in range(NUM_STATES) :
          # Get a random entry from the dictionary.
          state, capital = state_caps.popitem()

          #Quiz the user.
          print('What is the capital of ', state, '? ', end=' ')
          response = input()

          # Is the user correct?
          if response.lower() == capital.lower():
              correct += 1
              print('Correct!')
          else:
              incorrect += 1
              print('Incorrect.')

     # Display the results
     print ('Correct responses: ', correct)
     print ('Incorrect answers: ', incorrect)

def state_cap_dictionary():
  sc = { 'Alabama' : 'Montgomery' ,
      'Alaska' : 'Juneau' ,
      'Arizona' : 'Phoenix' ,
      'Arkansas' : 'Little Rock' ,
      'California' : 'Sacremento' ,
      'Colorado' : 'Denver' ,
      'Conneticut' : 'Hartford' ,
      'Delaware' : 'Dover' ,
      'Florida' : 'Tallahassee' ,
      'Georgia' : 'Atlanta' ,
      'Hawaii' : 'Honolulu' ,
      'Idaho' : 'Boise' ,
      'Illinois' : 'Springfield' ,
      'Indiana' : 'Indianapolis' ,
      'Iowa' : 'Des Moines' ,
      'Kansas' : 'Topeka' ,
      'Kentucky' : 'Frankfurt' ,
      'Lousianna' : 'Baton Rouge' ,
      'Maine' : 'Augusta' ,
      'Maryland' : 'Annapolis' ,
      'Massachusetts' : 'Boston' ,
      'Michigan' : 'Lansing' ,
      'Minnesota' : 'Saint Paul' ,
      'Mississippi' : 'Jackson' ,
      'Missouri' : 'Jefferson City' ,
      'Montana' : 'Helena' ,
      'Nebraska' : 'Lincoln' ,
      'Nevada' : 'Carson City' ,
      'New Hampshire' : 'Concord' ,
      'New Jersey' : 'Trenton' ,
      'New Mexico' : 'Santa Fe' ,
      'New York' : 'Albany' ,
      'North Carolina' : 'Raleigh' ,
      'North Dakota' : 'Bismarck' ,
      'Ohio' : 'Columbus' ,
      'Oklahoma' : 'Oklahoma City' ,
      'Oregon' : 'Salem' ,
      'Pennsylvania' : 'Harrisburg' ,
      'Rhode Island' : 'Providence' ,
      'South Carolina' : 'Columbia' ,
      'South Dakota' : 'Pierre' ,
      'Tennessee' : 'Nashville' ,
      'Texas' : 'Houston' ,
      'Utah' : 'Salt Lake City' ,
      'Vermont' : 'Montpelier' ,
      'Virginia' : 'Richmond' ,
      'Washington' : 'Olympia' ,
      'West Virginia' : 'Charleston' ,
      'Wisconsin' : 'Madison' ,
      'Wyoming' : 'Cheyenne' }
  return sc

main()
</code>```

Title: Need help spotting my mistake in Python

Body:
For my class assignment we had to create a Python quiz that asks users to type capitals for states. Their video gave us the answer, but even typing it in as they have it displayed I keep getting an error and my program will not run. My professor is out until Monday, I am hoping someone in here can help me find my error. I am thinking I either have a misspelled word or a IDK... I have been staring at it for hours and line by line it looks the same as the example given.

Thank you for any help.

Here is my code:

# Constant for the number of states to quiz the user on.
NUM_STATES = 5

def main ():
# Initialize the state_caps dictionary.
state_caps = state_cap_dictionary ()

# Initial variables to keep count of the number
# of correct and incorrect answers.
correct = 0
incorrect = 0

#Quiz the user.
for count in range (NUM_STATES) :
     # Get a random entry from the dictionary.
     state, capital = state_caps.popitem ()

#Quiz the user.
print ('What is the capital of ', state, '? ', end=' ')
response = input ()

# Is the user correct?
if response.lower () == capital.lower ():
    correct += 1
    print ('Correct!')
else:
    incorrect += 1
    print ('Incorrect.')

#Display the results
print ('Correct responses: ', correct)
print ('Incorrect answers: ', incorrect)

def state_cap_dictionary ():
  sc = { 'Alabama' : 'Montgomery' ,
      'Alaska' : 'Juneau' ,
      'Arizona' : 'Phoenix' ,
      'Arkansas' : 'Little Rock' ,
      'California' : 'Sacremento' ,
      'Colorado' : 'Denver' ,
      'Conneticut' : 'Hartford' ,
      'Delaware' : 'Dover' ,
      'Florida' : 'Tallahassee' ,
      'Georgia' : 'Atlanta' ,
      'Hawaii' : 'Honolulu' ,
      'Idaho' : 'Boise' ,
      'Illinois' : 'Springfield' ,
      'Indiana' : 'Indianapolis' ,
      'Iowa' : 'Des Moines' ,
      'Kansas' : 'Topeka' ,
      'Kentucky' : 'Frankfurt' ,
      'Lousianna' : 'Baton Rouge' ,
      'Maine' : 'Augusta' ,
      'Maryland' : 'Annapolis' ,
      'Massachusetts' : 'Boston' ,
      'Michigan' : 'Lansing' ,
      'Minnesota' : 'Saint Paul' ,
      'Mississippi' : 'Jackson' ,
      'Missouri' : 'Jefferson City' ,
      'Montana' : 'Helena' ,
      'Nebraska' : 'Lincoln' ,
      'Nevada' : 'Carson City' ,
      'New Hampshire' : 'Concord' ,
      'New Jersey' : 'Trenton' ,
      'New Mexico' : 'Santa Fe' ,
      'New York' : 'Albany' ,
      'North Carolina' : 'Raleigh' ,
      'North Dakota' : 'Bismarck' ,
      'Ohio' : 'Columbus' ,
      'Oklahoma' : 'Oklahoma City' ,
      'Oregon' : 'Salem' ,
      'Pennsylvania' : 'Harrisburg' ,
      'Rhode Island' : 'Providence' ,
      'South Carolina' : 'Columbia' ,
      'South Dakota' : 'Pierre' ,
      'Tennessee' : 'Nashville' ,
      'Texas' : 'Houston' ,
      'Utah' : 'Salt Lake City' ,
      'Vermont' : 'Montpelier' ,
      'Virginia' : 'Richmond' ,
      'Washington' : 'Olympia' ,
      'West Virginia' : 'Charleston' ,
      'Wisconsin' : 'Madison' ,
      'Wyoming' : 'Cheyenne' }
  return sc

main ()

Body:
With this indentation it works for me:

# Constant for the number of states to quiz the user on.
NUM_STATES = 5

def main():
# Initialize the state_caps dictionary.
     state_caps = state_cap_dictionary()

     # Initial variables to keep count of the number
     # of correct and incorrect answers.
     correct = 0
     incorrect = 0

     #Quiz the user.
     for count in range(NUM_STATES) :
          # Get a random entry from the dictionary.
          state, capital = state_caps.popitem()

          #Quiz the user.
          print('What is the capital of ', state, '? ', end=' ')
          response = input()

          # Is the user correct?
          if response.lower() == capital.lower():
              correct += 1
              print('Correct!')
          else:
              incorrect += 1
              print('Incorrect.')

     # Display the results
     print ('Correct responses: ', correct)
     print ('Incorrect answers: ', incorrect)

def state_cap_dictionary():
  sc = { 'Alabama' : 'Montgomery' ,
      'Alaska' : 'Juneau' ,
      'Arizona' : 'Phoenix' ,
      'Arkansas' : 'Little Rock' ,
      'California' : 'Sacremento' ,
      'Colorado' : 'Denver' ,
      'Conneticut' : 'Hartford' ,
      'Delaware' : 'Dover' ,
      'Florida' : 'Tallahassee' ,
      'Georgia' : 'Atlanta' ,
      'Hawaii' : 'Honolulu' ,
      'Idaho' : 'Boise' ,
      'Illinois' : 'Springfield' ,
      'Indiana' : 'Indianapolis' ,
      'Iowa' : 'Des Moines' ,
      'Kansas' : 'Topeka' ,
      'Kentucky' : 'Frankfurt' ,
      'Lousianna' : 'Baton Rouge' ,
      'Maine' : 'Augusta' ,
      'Maryland' : 'Annapolis' ,
      'Massachusetts' : 'Boston' ,
      'Michigan' : 'Lansing' ,
      'Minnesota' : 'Saint Paul' ,
      'Mississippi' : 'Jackson' ,
      'Missouri' : 'Jefferson City' ,
      'Montana' : 'Helena' ,
      'Nebraska' : 'Lincoln' ,
      'Nevada' : 'Carson City' ,
      'New Hampshire' : 'Concord' ,
      'New Jersey' : 'Trenton' ,
      'New Mexico' : 'Santa Fe' ,
      'New York' : 'Albany' ,
      'North Carolina' : 'Raleigh' ,
      'North Dakota' : 'Bismarck' ,
      'Ohio' : 'Columbus' ,
      'Oklahoma' : 'Oklahoma City' ,
      'Oregon' : 'Salem' ,
      'Pennsylvania' : 'Harrisburg' ,
      'Rhode Island' : 'Providence' ,
      'South Carolina' : 'Columbia' ,
      'South Dakota' : 'Pierre' ,
      'Tennessee' : 'Nashville' ,
      'Texas' : 'Houston' ,
      'Utah' : 'Salt Lake City' ,
      'Vermont' : 'Montpelier' ,
      'Virginia' : 'Richmond' ,
      'Washington' : 'Olympia' ,
      'West Virginia' : 'Charleston' ,
      'Wisconsin' : 'Madison' ,
      'Wyoming' : 'Cheyenne' }
  return sc

main()


问:
What is the syntax for an inner join in LINQ to SQL?
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.

How do you represent the following in LINQ to SQL:

```<code>select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
</code>```

答:
Inner join two tables in linq C#</p>

```<code>var result = from q1 in table1
             join q2 in table2
             on q1.Customer_Id equals q2.Customer_Id
             select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
</code>```

OwnerDisplayName: Glenn Slaven

Body:
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.

How do you represent the following in LINQ to SQL:

select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID

LastEditorDisplayName: Kevin Fairchild

Body:
Inner join two tables in linq C#

var result = from q1 in table1
             join q2 in table2
             on q1.Customer_Id equals q2.Customer_Id
             select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }

ContentLicense: CC BY-SA 4.0


答:
You were missing some indents.
This version works under Python 3, link here

You need to remember that is function A uses B, then both need to have same indent, in your pasted code, state_cap_dictionary was a private function of main, and you wer using it before declaring.

```<code># Constant for the number of states to quiz the user on.
NUM_STATES = 5

def main ():
    # Initialize the state_caps dictionary.
    state_caps = state_cap_dictionary()

    # Initial variables to keep count of the number
    # of correct and incorrect answers.
    correct = 0
    incorrect = 0

    #Quiz the user.
    for count in range (NUM_STATES) :
         # Get a random entry from the dictionary.
        state, capital = state_caps.popitem()

        #Quiz the user.
        print ('What is the capital of ', state, '? ')
        response = input()

        # Is the user correct?
        if response.lower() == capital.lower():
            correct += 1
            print ('Correct!')
        else:
            incorrect += 1
            print ('Incorrect.')

        #Display the results
        print ('Correct responses: ', correct)
        print ('Incorrect answers: ', incorrect)

def state_cap_dictionary ():
      sc = { 'Alabama' : 'Montgomery' ,
          'Alaska' : 'Juneau' ,
          'Arizona' : 'Phoenix' ,
          'Arkansas' : 'Little Rock' ,
          'California' : 'Sacremento' ,
          'Colorado' : 'Denver' ,
          'Conneticut' : 'Hartford' ,
          'Delaware' : 'Dover' ,
          'Florida' : 'Tallahassee' ,
          'Georgia' : 'Atlanta' ,
          'Hawaii' : 'Honolulu' ,
          'Idaho' : 'Boise' ,
          'Illinois' : 'Springfield' ,
          'Indiana' : 'Indianapolis' ,
          'Iowa' : 'Des Moines' ,
          'Kansas' : 'Topeka' ,
          'Kentucky' : 'Frankfurt' ,
          'Lousianna' : 'Baton Rouge' ,
          'Maine' : 'Augusta' ,
          'Maryland' : 'Annapolis' ,
          'Massachusetts' : 'Boston' ,
          'Michigan' : 'Lansing' ,
          'Minnesota' : 'Saint Paul' ,
          'Mississippi' : 'Jackson' ,
          'Missouri' : 'Jefferson City' ,
          'Montana' : 'Helena' ,
          'Nebraska' : 'Lincoln' ,
          'Nevada' : 'Carson City' ,
          'New Hampshire' : 'Concord' ,
          'New Jersey' : 'Trenton' ,
          'New Mexico' : 'Santa Fe' ,
          'New York' : 'Albany' ,
          'North Carolina' : 'Raleigh' ,
          'North Dakota' : 'Bismarck' ,
          'Ohio' : 'Columbus' ,
          'Oklahoma' : 'Oklahoma City' ,
          'Oregon' : 'Salem' ,
          'Pennsylvania' : 'Harrisburg' ,
          'Rhode Island' : 'Providence' ,
          'South Carolina' : 'Columbia' ,
          'South Dakota' : 'Pierre' ,
          'Tennessee' : 'Nashville' ,
          'Texas' : 'Houston' ,
          'Utah' : 'Salt Lake City' ,
          'Vermont' : 'Montpelier' ,
          'Virginia' : 'Richmond' ,
          'Washington' : 'Olympia' ,
          'West Virginia' : 'Charleston' ,
          'Wisconsin' : 'Madison' ,
          'Wyoming' : 'Cheyenne' }
      return sc

main ()
</code>```

Title: Need help spotting my mistake in Python

Body:
You were missing some indents.
This version works under Python 3, link here

You need to remember that is function A uses B, then both need to have same indent, in your pasted code, state_cap_dictionary was a private function of main, and you wer using it before declaring.

# Constant for the number of states to quiz the user on.
NUM_STATES = 5

def main ():
    # Initialize the state_caps dictionary.
    state_caps = state_cap_dictionary()

    # Initial variables to keep count of the number
    # of correct and incorrect answers.
    correct = 0
    incorrect = 0

    #Quiz the user.
    for count in range (NUM_STATES) :
         # Get a random entry from the dictionary.
        state, capital = state_caps.popitem()

        #Quiz the user.
        print ('What is the capital of ', state, '? ')
        response = input()

        # Is the user correct?
        if response.lower() == capital.lower():
            correct += 1
            print ('Correct!')
        else:
            incorrect += 1
            print ('Incorrect.')

        #Display the results
        print ('Correct responses: ', correct)
        print ('Incorrect answers: ', incorrect)

def state_cap_dictionary ():
      sc = { 'Alabama' : 'Montgomery' ,
          'Alaska' : 'Juneau' ,
          'Arizona' : 'Phoenix' ,
          'Arkansas' : 'Little Rock' ,
          'California' : 'Sacremento' ,
          'Colorado' : 'Denver' ,
          'Conneticut' : 'Hartford' ,
          'Delaware' : 'Dover' ,
          'Florida' : 'Tallahassee' ,
          'Georgia' : 'Atlanta' ,
          'Hawaii' : 'Honolulu' ,
          'Idaho' : 'Boise' ,
          'Illinois' : 'Springfield' ,
          'Indiana' : 'Indianapolis' ,
          'Iowa' : 'Des Moines' ,
          'Kansas' : 'Topeka' ,
          'Kentucky' : 'Frankfurt' ,
          'Lousianna' : 'Baton Rouge' ,
          'Maine' : 'Augusta' ,
          'Maryland' : 'Annapolis' ,
          'Massachusetts' : 'Boston' ,
          'Michigan' : 'Lansing' ,
          'Minnesota' : 'Saint Paul' ,
          'Mississippi' : 'Jackson' ,
          'Missouri' : 'Jefferson City' ,
          'Montana' : 'Helena' ,
          'Nebraska' : 'Lincoln' ,
          'Nevada' : 'Carson City' ,
          'New Hampshire' : 'Concord' ,
          'New Jersey' : 'Trenton' ,
          'New Mexico' : 'Santa Fe' ,
          'New York' : 'Albany' ,
          'North Carolina' : 'Raleigh' ,
          'North Dakota' : 'Bismarck' ,
          'Ohio' : 'Columbus' ,
          'Oklahoma' : 'Oklahoma City' ,
          'Oregon' : 'Salem' ,
          'Pennsylvania' : 'Harrisburg' ,
          'Rhode Island' : 'Providence' ,
          'South Carolina' : 'Columbia' ,
          'South Dakota' : 'Pierre' ,
          'Tennessee' : 'Nashville' ,
          'Texas' : 'Houston' ,
          'Utah' : 'Salt Lake City' ,
          'Vermont' : 'Montpelier' ,
          'Virginia' : 'Richmond' ,
          'Washington' : 'Olympia' ,
          'West Virginia' : 'Charleston' ,
          'Wisconsin' : 'Madison' ,
          'Wyoming' : 'Cheyenne' }
      return sc

main ()


问:
remove the subviews from the contentView of UITableViewCell (reset the UITableView)
Any idea on how to reset a UITableView?

I want to display a new set of data at the press of a button and also remove all the subviews from the cell's contentView and refresh them with a new set of subviews.  I tried [tableView reloadData] but the data did get refreshed but the subviews added to the contentView of the cells previously persisted.

答:
I know this question is old, but i found a problem with the solution, if you remove one subview from one prototype cell, this view will be removed from all reused cells, this will create a null pointer in the next cell that will be reused.

If you subclass UITableViewCell and remove the subview from there, you will have to do this verification first:

```<code>if (mySubView != nil ) {
        mySubView.removeFromSuperview()
    }
</code>```

This also will work inside your cellForRow at indexPath method

```<code>  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCustomCell

    if (cell.mySubView != nil) {
       cell.mySubView.removeFromSuperview()
     }
    return cell
}
</code>```

Whit this you avoid the null pointer, the code is for swift 3. Hope this help somebody. :)

Body:
I know this question is old, but i found a problem with the solution, if you remove one subview from one prototype cell, this view will be removed from all reused cells, this will create a null pointer in the next cell that will be reused.

If you subclass UITableViewCell and remove the subview from there, you will have to do this verification first:

if (mySubView != nil ) {
        mySubView.removeFromSuperview()
    }

This also will work inside your cellForRow at indexPath method

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCustomCell

    if (cell.mySubView != nil) {
       cell.mySubView.removeFromSuperview()
     }
    return cell
}

Whit this you avoid the null pointer, the code is for swift 3. Hope this help somebody. :)


问:
How to handle GZip/Deflate on HTTP Actions
I have an HTTP Action in Azure Logic Apps that calls a StackExchange API, fundamentally, it could be any API that returned GZip or Deflate content by default:

Because the response is neither Plain Text nor JSON the output from the HTTP Action is:

```<code>{
  "$content-encoding": "gzip",
  "$content-type": "application/json; charset=utf-8",
  "$content": "H4sIAAAAAAAEAGWPzY7CMAyE38XnqsrPFtq+ClpFoXghEkm6iVtWQrw7Lt3mAEd/Hs+M7+AIfYb+cIeAN2MHcjOaKWNiKCqgSPa6zZ2SFRzt6YzZjJiMd2EiZF0tvjbpuoZe7rrdxuZIC9KNLo5D9B4DLUIl2gpsyDfOeLflvN8JM7kYPnbF6/+WA/ZNYcOAI+Hp5V/eCKv0heVGSwD0SnRcZXQm4ewyM+hBCbmvda3aWjVaS3h8V3Cx2fiYuMePvWZcSrKV8faPSyzF1jmhty64cGbnVjyeRIHcnG0BAAA="
}
</code>```

If you went to the trouble of passing the $content field through @base64toString() you would end up with the Gzip binary representation of the JSON, and that is as far as I can take it.

Question: How can I either force the HTTP Action to behave like a HttpClient and Accept GZip data and emit the JSON from the Action, or more laboriously take the GZip Base64/Binary data and decompress it before acting further upon it?

答:
I wasn't able to find a way to "solve" the problem directly, so I created an Azure Function that made the request to the URL with the appropriate HttpClientHandler passed into the HttpClient:

#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log) {
  string jsonContent = await req.Content.ReadAsStringAsync();
  dynamic data = JsonConvert.DeserializeObject(jsonContent);

  if (data.url == null) {
    return req.CreateResponse(HttpStatusCode.BadRequest, new {
      error = "Please pass a URL in the input object"
    });
  }

  HttpClientHandler handler = new HttpClientHandler() {
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
  };

  var client = new HttpClient(handler);
  var result = await client.GetAsync((string)data.url);
  var response = req.CreateResponse(HttpStatusCode.OK);
  response.Content = result.Content;
  return response;
}
```

By swapping the built-in HTTP Action from the original question, I was able to get this working:

And the configuration for the Azure Function is as follows:

Body:
I have an HTTP Action in Azure Logic Apps that calls a StackExchange API, fundamentally, it could be any API that returned GZip or Deflate content by default:

Because the response is neither Plain Text nor JSON the output from the HTTP Action is:

{
  "$content-encoding": "gzip",
  "$content-type": "application/json; charset=utf-8",
  "$content": "H4sIAAAAAAAEAGWPzY7CMAyE38XnqsrPFtq+ClpFoXghEkm6iVtWQrw7Lt3mAEd/Hs+M7+AIfYb+cIeAN2MHcjOaKWNiKCqgSPa6zZ2SFRzt6YzZjJiMd2EiZF0tvjbpuoZe7rrdxuZIC9KNLo5D9B4DLUIl2gpsyDfOeLflvN8JM7kYPnbF6/+WA/ZNYcOAI+Hp5V/eCKv0heVGSwD0SnRcZXQm4ewyM+hBCbmvda3aWjVaS3h8V3Cx2fiYuMePvWZcSrKV8faPSyzF1jmhty64cGbnVjyeRIHcnG0BAAA="
}

If you went to the trouble of passing the $content field through @base64toString() you would end up with the Gzip binary representation of the JSON, and that is as far as I can take it.

Question: How can I either force the HTTP Action to behave like a HttpClient and Accept GZip data and emit the JSON from the Action, or more laboriously take the GZip Base64/Binary data and decompress it before acting further upon it?

Body:
I wasn't able to find a way to "solve" the problem directly, so I created an Azure Function that made the request to the URL with the appropriate HttpClientHandler passed into the HttpClient:

#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log) {
  string jsonContent = await req.Content.ReadAsStringAsync();
  dynamic data = JsonConvert.DeserializeObject(jsonContent);

  if (data.url == null) {
    return req.CreateResponse(HttpStatusCode.BadRequest, new {
      error = "Please pass a URL in the input object"
    });
  }

  HttpClientHandler handler = new HttpClientHandler() {
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
  };

  var client = new HttpClient(handler);
  var result = await client.GetAsync((string)data.url);
  var response = req.CreateResponse(HttpStatusCode.OK);
  response.Content = result.Content;
  return response;
}

By swapping the built-in HTTP Action from the original question, I was able to get this working:

And the configuration for the Azure Function is as follows:


问:
WPF - ObservableCollection casting
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

```<code>public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}
</code>```

答:
If you don't mind generics:  </p>

```<code>private void PersonsMeeting<T>(ObservableCollection<T> persons) where T: Person
{
    // ....
}
</code>```

Title: WPF - ObservableCollection casting

Body:
I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}

Body:
If you don't mind generics:

private void PersonsMeeting<T>(ObservableCollection<T> persons) where T: Person
{
    // ....
}


问:
ASP NET SQL - select * from where author
I'm having a problem showing equal results from SQL database

```<code>"select * from Log where Author=" + User.Identity.Name
</code>```

That's the current command I've tried, but can't get it working.

while this works:

```<code>"select * from Log where Author='markus'"
</code>```

Thanks for any help.

答:
Try the following:

```<code>"Select * from Log where Author='" + User.Identity.Name + "'"
</code>```

Actually your query is missing single quotes for name that is a string..

Body:
I'm having a problem showing equal results from SQL database

"select * from Log where Author=" + User.Identity.Name

That's the current command I've tried, but can't get it working.

while this works:

"select * from Log where Author='markus'"

Thanks for any help.

Body:
Try the following:

"Select * from Log where Author='" + User.Identity.Name + "'"

Actually your query is missing single quotes for name that is a string..


问:
How to map java.time.Year and others java.time types using Hibernate
There's hibernate-java8 JAR providing adapters for a couple of classes like Instant, LocalDate, etc., but some classes from java.time, e.g., Year, Month, YearMonth are missing. These classes get stored like an unknown Serializable, which is needlessly wasteful.

Surely I could use an int year instead of Year year, but I don't think, it's a good idea.

It looks like writing the YearJavaDescriptor should be pretty easy, however, I wonder why it's missing. Especially in case of YearMonth, I'd strongly prefer an existing adapter, ist there any? Or am I doing something stupid?

I'm unsure as googling returns nothing.

答:
Try to create a converter - AttributeConverter implementation for this purpose.

I used in the past something like following:

```<code>@Entity
public class RealEstateAgency {
    @Column(name = "createdAt")
    @Convert(converter = ZonedDateTimeConverter.class)
    private ZonedDateTime creationDate;
}

@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {

    public Date convertToDatabaseColumn(ZonedDateTime toConvert) {
        return toConvert == null ? null : Date.from(toConvert.toInstant());
    }

    public ZonedDateTime convertToEntityAttribute(Date toConvert) {
        return toConvert == null ? null : ZonedDateTime.from(toConvert.toInstant());
    }
}
</code>```

Body:
Try to create a converter - AttributeConverter implementation for this purpose.

I used in the past something like following:

@Entity
public class RealEstateAgency {
    @Column(name = "createdAt")
    @Convert(converter = ZonedDateTimeConverter.class)
    private ZonedDateTime creationDate;
}

@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {

    public Date convertToDatabaseColumn(ZonedDateTime toConvert) {
        return toConvert == null ? null : Date.from(toConvert.toInstant());
    }

    public ZonedDateTime convertToEntityAttribute(Date toConvert) {
        return toConvert == null ? null : ZonedDateTime.from(toConvert.toInstant());
    }
}


问:
loop break not working inside switch block on array of strings
Please refer the below code in which loop break does not work inside the switch block, can you help?</p>

```<code>    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    //For loop is not breaking after getting the correct value
    for (int t = 0; t < Books.length; t++) {
      switch (Books[t]) {
        case "Harry Potter":
             System.out.println("Getting from switch case " + t + " " + Books[t]);
            break;
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
    }
</code>```

答:
break when used inside the switch statement breaks ONLY the switch flow, but not the for loop, so
If you wanted to break the for loop, use return when the correct value is found which will break the loop and returns from the method, as shown below:

```<code>String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };
    for (int t = 0; t < Books.length; t++) {
      switch (Books[t]) {
        case "Harry Potter":
             System.out.println("Getting from switch case " + t + " " + Books[t]);
            return;//use return when CORRECT CONDITION is found
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
    }
</code>```

In simple terms, your break will be applied to the inner code block which is a switch here, so it doesn't break the for loop. So, if you wanted to break both switch & for together, use return statement so that it returns from the method.

One important point is that do not use the labels (to jump between lines) in the code which is against to the structured programming.

OPTION(2):

If you don't want to return from the method, you need to refactor your code and move the book finding logic to a separate method like checkBookExists as shown below:

```<code>private boolean checkBookExists(String book, int t) {
      boolean bookFound = false;
      switch (book) {
        case "Harry Potter":
            bookFound = true;
            System.out.println("Getting from switch case " + t + " " + book);
            break;
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
        return bookFound;
   }
</code>```

Now call that checkBookExists method inside the for loop as shown below and when the book is found, for will break.

```<code>String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };
    for (int t = 0; t < Books.length; t++) {
        if(checkBookExists(Books[t], t)) {
            break;
        }
    }
</code>```

Body:
Please refer the below code in which loop break does not work inside the switch block, can you help?

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    //For loop is not breaking after getting the correct value
    for (int t = 0; t < Books.length; t++) {
      switch (Books[t]) {
        case "Harry Potter":
             System.out.println("Getting from switch case " + t + " " + Books[t]);
            break;
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
    }

Body:
break when used inside the switch statement breaks ONLY the switch flow, but not the for loop, so
If you wanted to break the for loop, use return when the correct value is found which will break the loop and returns from the method, as shown below:

String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };
    for (int t = 0; t < Books.length; t++) {
      switch (Books[t]) {
        case "Harry Potter":
             System.out.println("Getting from switch case " + t + " " + Books[t]);
            return;//use return when CORRECT CONDITION is found
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
    }

In simple terms, your break will be applied to the inner code block which is a switch here, so it doesn't break the for loop. So, if you wanted to break both switch & for together, use return statement so that it returns from the method.

One important point is that do not use the labels (to jump between lines) in the code which is against to the structured programming.

OPTION(2):

If you don't want to return from the method, you need to refactor your code and move the book finding logic to a separate method like checkBookExists as shown below:

private boolean checkBookExists(String book, int t) {
      boolean bookFound = false;
      switch (book) {
        case "Harry Potter":
            bookFound = true;
            System.out.println("Getting from switch case " + t + " " + book);
            break;
        default:
            System.out.println("Invalid search for book from switch case");
            break;
        }
        return bookFound;
   }

Now call that checkBookExists method inside the for loop as shown below and when the book is found, for will break.

String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };
    for (int t = 0; t < Books.length; t++) {
        if(checkBookExists(Books[t], t)) {
            break;
        }
    }


问:
SASS Susy and Flexbox for vertically aligned LI in Susy Grid
I've looked at about a dozen various stack questions about vertically aligning items and a few websites with tutorials for aligning / working with SASS Susy. It seems perhaps my use case is unique and I just don't have the skills to work it out.

I've got a Full-Width Container and inside that I have a Wrapper. The container uses susy span full because its just full-width of the site container and the flex wrap is width of the actual content 1200px (hopefully that makes sense). It might seem redundant in the code but section needs to be full-width for background elements that span the screen and the wrap is the container for the content size throughout the rest of the layout.

HTML

```<code><section class="sectionid section"><div class="flexwrap">All the Code for the children elements here</div></section>
</code>```

CSS

```<code>.section{ @include span(full); }
.flexwrap{ @include container(1200px); }
</code>```

Thats the core of the elements of the container. Inside the flexwrap I have 2 columns (left and right).

HTML (don't know is pastebin is allowed but my code isn't working on here)

```<code><section class="sectionid section">
<h3>text</h3>
    <div class="flexwrap">
    <div class="item_left">
        <ul class="item_bullets">
        <li><div class="bullet_left">img</div><div class="bullet_right">item</div></li>
        <li><div class="bullet_left">img</div><div class="bullet_right">item</div></li>
        <li><div class="bullet_left">img</div><div class="bullet_right">item</div></li>
        </ul>
        </div>
        <div class="item_right">HEADING & TEXT</div>
    </div>
</section>
</code>```

CSS

```<code>.item_bullets {
        @include span(full);
        margin:0;
        list-style:none;
        li {
            @include span(full);
        }
        .bullet_left {
            @include span(1.5 of 12);
        }
        .bullet_right {
            @include span(9.5 of 12 last);
        }
    }
</code>```

Now without any flexbox I've got this with Susy (I've colored the div containers here for the markup):

Now adding flexbox I thought based on what I read adding display:flex; to flexwrap and then display:flex; flex-direction:column; justify-content:space-between; to item_bullets would work, but all it did was flex position my header text even after trying to find ways to exclude it.

So I added another inner div to just house the left & right items, but it never vertically spaces / aligns the list items. I assume using Susy and Flexbox together there are some complications but the whole project has been done with Susy so I was hoping someone more clever than I had an idea.

答:
It's very hard to follow exactly what you are trying to do, so I acn't give a full code solution, but I'd guess that part of your problem comes from the span mixin outputting a float property, which will conflict with display:flex settings. Try using the span function instead, to set widths without accidentally setting other properties.

```<code>.bullet_left {
  width: span(1.5 of 12);
}
</code>```

It's also worth noting that span(full) is almost always useless. Block elements default to 100% width, so span(full) becomes redundant bloat.

Body:
I've looked at about a dozen various stack questions about vertically aligning items and a few websites with tutorials for aligning / working with SASS Susy. It seems perhaps my use case is unique and I just don't have the skills to work it out.

I've got a Full-Width Container and inside that I have a Wrapper. The container uses susy span full because its just full-width of the site container and the flex wrap is width of the actual content 1200px (hopefully that makes sense). It might seem redundant in the code but section needs to be full-width for background elements that span the screen and the wrap is the container for the content size throughout the rest of the layout.

HTML

All the Code for the children elements here

CSS

.section{ @include span(full); }
.flexwrap{ @include container(1200px); }

Thats the core of the elements of the container. Inside the flexwrap I have 2 columns (left and right).

HTML (don't know is pastebin is allowed but my code isn't working on here)

text

img

item

img

item

img

item

HEADING & TEXT

CSS

.item_bullets {
        @include span(full);
        margin:0;
        list-style:none;
        li {
            @include span(full);
        }
        .bullet_left {
            @include span(1.5 of 12);
        }
        .bullet_right {
            @include span(9.5 of 12 last);
        }
    }

Now without any flexbox I've got this with Susy (I've colored the div containers here for the markup):

Now adding flexbox I thought based on what I read adding display:flex; to flexwrap and then display:flex; flex-direction:column; justify-content:space-between; to item_bullets would work, but all it did was flex position my header text even after trying to find ways to exclude it.

So I added another inner div to just house the left & right items, but it never vertically spaces / aligns the list items. I assume using Susy and Flexbox together there are some complications but the whole project has been done with Susy so I was hoping someone more clever than I had an idea.

Body:
It's very hard to follow exactly what you are trying to do, so I acn't give a full code solution, but I'd guess that part of your problem comes from the span mixin outputting a float property, which will conflict with display:flex settings. Try using the span function instead, to set widths without accidentally setting other properties.

.bullet_left {
  width: span(1.5 of 12);
}

It's also worth noting that span(full) is almost always useless. Block elements default to 100% width, so span(full) becomes redundant bloat.


问:
Laravel 5 Sanitizing Required Field Behavior
I am trying to sanitize the user input in my application following this article

Below is my request

```<code>class TestRequest extends Request
{

   public function authorize()
   {
      return true;
   }

   public function rules()
   {
       $this->sanitize();

      return [
          'title'=>'required|max:100'

      ];
   }

   public function sanitize()
   {

      $input = $this->all();
      if(!empty($input))
      {
        $input['title'] = trim(strip_tags($input['title']));
        $this->replace($input);

      }

    }
}
</code>```

Tough the title is required field, if I try to put

 as input in the title field, as per the logic in sanitize() function the tags are stripped away, but an empty string is saved in the database. The required field validation in the rules in not taking any effect.

How to handle this?

Update:

Below is the controller method for saving the request.

```<code>public function save(TestRequest $request)
{
   $input = $request->all();
   ...
}
</code>```

答:
First option is to use merge() instead of replace() in your code, i.e.:

```<code>$this->merge( ['title' => trim(strip_tags($input['title']))] );
</code>```

Second option is to override the all() function, i.e.:

```<code>public function all()
{
    $input = parent::all();
    if( !empty($input) )
    {
        $input['title'] = trim(strip_tags($input['title']));
    }
    return $input;
}
</code>```

In the last code example you dont have to use the sanitize() function.

Body:
I am trying to sanitize the user input in my application following this article

Below is my request

class TestRequest extends Request
{

   public function authorize()
   {
      return true;
   }

   public function rules()
   {
       $this->sanitize();

      return [
          'title'=>'required|max:100'

      ];
   }

   public function sanitize()
   {

      $input = $this->all();
      if(!empty($input))
      {
        $input['title'] = trim(strip_tags($input['title']));
        $this->replace($input);

      }

    }
}

Tough the title is required field, if I try to put

 as input in the title field, as per the logic in sanitize() function the tags are stripped away, but an empty string is saved in the database. The required field validation in the rules in not taking any effect.

How to handle this?

Update:

Below is the controller method for saving the request.

public function save(TestRequest $request)
{
   $input = $request->all();
   ...
}

Body:
First option is to use merge() instead of replace() in your code, i.e.:

$this->merge( ['title' => trim(strip_tags($input['title']))] );

Second option is to override the all() function, i.e.:

public function all()
{
    $input = parent::all();
    if( !empty($input) )
    {
        $input['title'] = trim(strip_tags($input['title']));
    }
    return $input;
}

In the last code example you dont have to use the sanitize() function.


问:
How to show edit and delete buttons on datatables when right clicking a row?
I am using datatables. Is it possible to show working edit and delete buttons on right click like the example here?
The only working example I found is this. But it is not what I am trying to achieve.

Example for click events: https://datatables.net/examples/advanced_init/events_live.html

答:
Here is the modification of the javascript used in your first example:

```<code>$(document).ready( function () {
  var oTable = $('#example').dataTable({
    "bJQueryUI": true,
    "sDom": 'l<"H"Rf>t<"F"ip>'
  });
  $(document).contextmenu({
    delegate: ".dataTable td",
    menu: [
      {title: "Delete", cmd: "delete"},
      {title: "Edit", cmd: "edit"}
    ],
    select: function(event, ui) {
        switch(ui.cmd){
            case "delete":
                $(ui.target).parent().remove();
                break;
            case "edit":
              $(ui.target).html(
                $('<input type="text"/>').val(
                  $(ui.target).text()
                ).bind( "keypress focusout",function (e) {
                  if (e.type=="keypress"?(e.keyCode ==13?true:false):true) {
                      $(this).parent().html(
                        $(this).val()
                      );
                    }
                  })
              );
                break;
        }
    },
    beforeOpen: function(event, ui) {
        var $menu = ui.menu,
            $target = ui.target
        ui.menu.zIndex(0);
    }
  });
} );
</code>```

The working example has been posted here:

http://live.datatables.net/munonapo/1/embed

Body:
Here is the modification of the javascript used in your first example:

$(document).ready( function () {
  var oTable = $('#example').dataTable({
    "bJQueryUI": true,
    "sDom": 'l<"H"Rf>t<"F"ip>'
  });
  $(document).contextmenu({
    delegate: ".dataTable td",
    menu: [
      {title: "Delete", cmd: "delete"},
      {title: "Edit", cmd: "edit"}
    ],
    select: function(event, ui) {
        switch(ui.cmd){
            case "delete":
                $(ui.target).parent().remove();
                break;
            case "edit":
              $(ui.target).html(
                $('<input type="text"/>').val(
                  $(ui.target).text()
                ).bind( "keypress focusout",function (e) {
                  if (e.type=="keypress"?(e.keyCode ==13?true:false):true) {
                      $(this).parent().html(
                        $(this).val()
                      );
                    }
                  })
              );
                break;
        }
    },
    beforeOpen: function(event, ui) {
        var $menu = ui.menu,
            $target = ui.target
        ui.menu.zIndex(0);
    }
  });
} );

The working example has been posted here:

http://live.datatables.net/munonapo/1/embed


问:
JavaFX TableView how to get cell's data?
I'm using that method to get whole object.

```<code>tableView.getSelectionModel().getSelectedItem()
</code>```

How can I get data from single cell?

I mean like get S20BJ9DZ300266 as String?

答:
I solved it. I get the string, for example, "[1, proveedor1, calzado1, Rojo, 39, 600, 2, 1200]", and get the frist cell (id) whit substring. saludos</p>

```<code>TablePosition pos = (TablePosition) tableVenta.getSelectionModel().getSelectedCells().get(0);
int index = pos.getRow();
String selected = tableVenta.getItems().get(index).toString();
selected = selected.substring(1, selected.indexOf(","));
System.out.println(selected);
</code>```

Body:
I'm using that method to get whole object.

tableView.getSelectionModel().getSelectedItem()

How can I get data from single cell?

I mean like get S20BJ9DZ300266 as String?

Body:
I solved it. I get the string, for example, "[1, proveedor1, calzado1, Rojo, 39, 600, 2, 1200]", and get the frist cell (id) whit substring. saludos

TablePosition pos = (TablePosition) tableVenta.getSelectionModel().getSelectedCells().get(0);
int index = pos.getRow();
String selected = tableVenta.getItems().get(index).toString();
selected = selected.substring(1, selected.indexOf(","));
System.out.println(selected);


问:
Take int of day, month, year and convert to DD/MM/YYYY
I am writing a method to take a DOB of 3 integers - day, month, year and return the formatted version DD/MM/YYYY.

I am currently using dateFormatter and simple date format. Although when I run this it defaults to 01/01/1970 and I cannot change the date.

Any suggestions?

Update

Guys thanks for the below posts, problem solved!

答:
tl;dr

```<code>LocalDate.of( 2017 , 1 , 23 )
         .format( DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
</code>```

23/01/2017

java.time

The modern way uses the java.time classes.

Avoid the old legacy date-time classes such as Date and Calendar as they are poorly designed, confusing, troublesome, and flawed.

LocalDate

LocalDate represents a date-only value without time-of-day and without time zone. Note that unlike the legacy classes, here the months have sane numbering 1-12 for January-December.

```<code>LocalDate ld = LocalDate.of( 2017 , 1 , 23 );
</code>```

DateTimeFormatter

Generate a String representing that value by using a formatter object.

```<code>DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );

String output = ld.format( f );
</code>```

Body:
tl;dr

LocalDate.of( 2017 , 1 , 23 )
         .format( DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )

23/01/2017

java.time

The modern way uses the java.time classes.

Avoid the old legacy date-time classes such as Date and Calendar as they are poorly designed, confusing, troublesome, and flawed.

LocalDate

LocalDate represents a date-only value without time-of-day and without time zone. Note that unlike the legacy classes, here the months have sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 2017 , 1 , 23 );

DateTimeFormatter

Generate a String representing that value by using a formatter object.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );

String output = ld.format( f );


问:
Caliburn Micro disable buttons which have no Property?
At the moment i'm working with Caliburn Micro. But i got to a problem which i don't know how to solve.

The problem is i want to disable Buttons, but every website has only a solution with propertys. the functions of my buttons for example just start a thread to establish a connection over tcp with Netmq. So i don't know how i'll be able to disable them. Searched a lot through google but didn't find anything helpful.

Example of a button function

```<code>public void startPubButton()
    {
        Thread entryThread = new Thread(startPublisher);
        entryThread.IsBackground = true;
        entryThread.Start();
    }
</code>```

is there maybe a possibility to enable the Buttons only when the thread runs ?

答:
That is the one premise behind CM wiring up by convention all you have to do is provide a CanstartPubButton Boolean property run a code check to see if you can enable or disable button according to the logic with that guard property.  Call with NotifyOfPropertyChange(() => CanstartPubButton); in some fashion to do what you want.  The logic with in the property (get only needed) is up to you.  one other thing I will drop on you is a thread presently in the GitHub discussions on the repository itself.  Might help and it might not

https://github.com/Caliburn-Micro/Caliburn.Micro/issues/422

Body:
At the moment i'm working with Caliburn Micro. But i got to a problem which i don't know how to solve.

The problem is i want to disable Buttons, but every website has only a solution with propertys. the functions of my buttons for example just start a thread to establish a connection over tcp with Netmq. So i don't know how i'll be able to disable them. Searched a lot through google but didn't find anything helpful.

Example of a button function

public void startPubButton()
    {
        Thread entryThread = new Thread(startPublisher);
        entryThread.IsBackground = true;
        entryThread.Start();
    }

is there maybe a possibility to enable the Buttons only when the thread runs ?


问:
Natively access JSON POST payload from Node.js server
Consider the following HTTP POST call to a Node.js server:

```<code>curl -H "Content-Type: application/json" \
     -X POST \
     -d '{"jsonKey":"jsonValue"}' \
     'http://localhost:8080?abcd=efgh'
</code>```

I would like to access both the URL parameters and the JSON payload of the POST request.

Accessing the URL params is pretty straightforward by importing url.parse:

```<code>var server = http.createServer(function(req, res) {
        // Parse the params - prints "{ abcd: 'efgh' }"
        var URLParams = url.parse(req.url, true).query;
        console.log(URLParams);

        // How do I access the JSON payload as an object?
}
</code>```

But how do I access the JSON payload, using native Node.js library (without any npm import)?

What have I tried

Printed req to console.log, but did not find the POST object

Read the documentation of req, which is of type http.IncomingMessage

答:
req is a stream so how you access it depends on how you want to use it. If you just want to get it as text and parse that as JSON, you can do the following:

```<code>let data = "";
req.on("readable", text => data += text);
req.on("end", () => {
  try {
    const json = JSON.parse(data);
  }
  catch (err) {
    console.error("request body was not JSON");
  }
  /* now you can do something with JSON */
});
</code>```

Body:
Consider the following HTTP POST call to a Node.js server:

curl -H "Content-Type: application/json" \
     -X POST \
     -d '{"jsonKey":"jsonValue"}' \
     'http://localhost:8080?abcd=efgh'

I would like to access both the URL parameters and the JSON payload of the POST request.

Accessing the URL params is pretty straightforward by importing url.parse:

var server = http.createServer(function(req, res) {
        // Parse the params - prints "{ abcd: 'efgh' }"
        var URLParams = url.parse(req.url, true).query;
        console.log(URLParams);

        // How do I access the JSON payload as an object?
}

But how do I access the JSON payload, using native Node.js library (without any npm import)?

What have I tried

Printed req to console.log, but did not find the POST object

Read the documentation of req, which is of type http.IncomingMessage

Body:
req is a stream so how you access it depends on how you want to use it. If you just want to get it as text and parse that as JSON, you can do the following:

let data = "";
req.on("readable", text => data += text);
req.on("end", () => {
  try {
    const json = JSON.parse(data);
  }
  catch (err) {
    console.error("request body was not JSON");
  }
  /* now you can do something with JSON */
});


问:
Return pointer to node in insert method of binary search tree
I would like to know why we have to return the pointer to root node in insert function of BST.
Wouldn't the BST  be updated even if we don't return the pointer to root node, since we are updating the data in the memory, to which the pointer is mapped?
The following code</p>

```<code>struct node* insert(struct node* node, int data)
{
    /* 1. If the tree is empty, return a new, single node */
    if (node == NULL)
        return(newNode(data));

    /* 2. Otherwise, recurse down the tree */
    else
    {
        if (data <= node->data)
            node->left  = insert(node->left, data);
        else
            node->right = insert(node->right, data);

        /* return the (unchanged) node pointer */
        return node;
    }
}
</code>```

答:
As others have suggested, it is just a part of algorithm, otherwise node->left  = insert(node->left, data); would not work.

Here is an algorithm (in C/C++) that does not return anything:

```<code>void Insert(struct node** node, int key)
{
    if(*node == NULL) *node = newNode(key);
    else insert(*node, key);
}

void insert(struct node* node, int key)
{
    if (key < node->key)
    {
        if(node->left == NULL) node->left = newNode(key);
        else insert(node->left, key);
    }

    else if (key > node->key)
    {
        if(node->right == NULL) node->right = newNode(key);
        insert(node->right, key);
    }
}
</code>```

Here, newNode(key) is a function that creates a new node and set its key value as supplied in the argument.

Note that using only theinsert function given at the bottom would do the job, except for when node is NULL (that is, the tree is empty). That is why I have used separate Insert function to handle this case.

You would insert elements as:

```<code>Insert(&root,50);
</code>```

I hope this clarifies your doubt.

Body:
I would like to know why we have to return the pointer to root node in insert function of BST.
Wouldn't the BST  be updated even if we don't return the pointer to root node, since we are updating the data in the memory, to which the pointer is mapped?
The following code

struct node* insert(struct node* node, int data)
{
    /* 1. If the tree is empty, return a new, single node */
    if (node == NULL)
        return(newNode(data));

    /* 2. Otherwise, recurse down the tree */
    else
    {
        if (data <= node->data)
            node->left  = insert(node->left, data);
        else
            node->right = insert(node->right, data);

        /* return the (unchanged) node pointer */
        return node;
    }
}

Body:
As others have suggested, it is just a part of algorithm, otherwise node->left  = insert(node->left, data); would not work.

Here is an algorithm (in C/C++) that does not return anything:

void Insert(struct node** node, int key)
{
    if(*node == NULL) *node = newNode(key);
    else insert(*node, key);
}

void insert(struct node* node, int key)
{
    if (key < node->key)
    {
        if(node->left == NULL) node->left = newNode(key);
        else insert(node->left, key);
    }

    else if (key > node->key)
    {
        if(node->right == NULL) node->right = newNode(key);
        insert(node->right, key);
    }
}

Here, newNode(key) is a function that creates a new node and set its key value as supplied in the argument.

Note that using only theinsert function given at the bottom would do the job, except for when node is NULL (that is, the tree is empty). That is why I have used separate Insert function to handle this case.

You would insert elements as:

Insert(&root,50);

I hope this clarifies your doubt.


问:
combining items in a json
I was able to write a solution, but I was wondering if there is a more elegant and efficient way to do it.

```<code>    var arr = [];

//I have a array like this:
    arr = [{
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 1,
        studentName: 'A',
        studentAge: 10
      },
      {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 2,
        studentName: 'B',
        studentAge: 11
      }, {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 3,
        studentName: 'C',
        studentAge: 12
      },

      {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 4,
        studentName: 'D',
        studentAge: 9
      }, {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 5,
        studentName: 'E',
        studentAge: 12
      }
    ];

//want to group the students info in each indiviual teacher like this:
//*
    [{
      "teacherid": 10,
      "teacherName": "andy",
      "age": 30,
      "studentArr": [{
        "studentid": 1,
        "studentName": "A",
        "studentAge": 10
      }, {
        "studentid": 2,
        "studentName": "B",
        "studentAge": 11
      }, {
        "studentid": 3,
        "studentName": "C",
        "studentAge": 12
      }]
    }, {
      "teacherid": 11,
      "teacherName": "May",
      "age": 40,
      "studentArr": [{
        "studentid": 4,
        "studentName": "D",
        "studentAge": 9
      }, {
        "studentid": 5,
        "studentName": "E",
        "studentAge": 12
      }]
    }
    }]
*//

//my solution
    var result = [];
    var first = true;
    arr = _.sortBy(arr, 'teacherid');

    (function() {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i; j < arr.length; j++) {
          console.log("comparing i:" + i + " with j:" + j);

          if (i === j && j === arr.length) {
            console.log("exit " + i + " : " + j)
            return;
          } else if (arr[i].teacherid === arr[j].teacherid) {
            if (first) {
              result.push({
                teacherid: arr[j].teacherid,
                teacherName: arr[j].teacherName,
                age: arr[j].age,
                studentArr: [{
                  studentid: arr[j].studentid,
                  studentName: arr[j].studentName,
                  studentAge: arr[j].studentAge
                }]
              })
            } else {
              //find in result arr, the obj that contain this teacher and push the student in the array
              var teacher = _.find(result, function(item) {
                return (item.teacherid === arr[j].teacherid)
              })
              teacher.studentArr.push({
                studentid: arr[j].studentid,
                studentName: arr[j].studentName,
                studentAge: arr[j].studentAge
              })
            }
            first = false;

          } else {
            first = true;
            i = j - 1;
            j = arr.length; //end inner loop, go back to outer loop and check next teacherID
          }
        }
      }

    })()

    console.log(JSON.stringify(result));
</code>```

This would be a headache if another programmer were to read it. I was wondering if there is a better solution (more efficient and/or more readable) than this. I feel like I brute-forced this

答:
```<code>function group(data, column) {
  var generatedData = {};
  $.each(data, function(i, dt) {
    var key = dt[column];
    if (!(key in generatedData)) {
      generatedData[key] = [];
    }
    generatedData[key].push(dt);
  });
  return generatedData;
}

var g = group([
 {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 1,
        studentName: 'A',
        studentAge: 10
      },
      {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 2,
        studentName: 'B',
        studentAge: 11
      }, {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 3,
        studentName: 'C',
        studentAge: 12
      },

      {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 4,
        studentName: 'D',
        studentAge: 9
      }, {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 5,
        studentName: 'E',
        studentAge: 12
      }
], 'teacherid');

document.write(JSON.stringify(g));
</code>```

Title: combining items in a json

Body:
I was able to write a solution, but I was wondering if there is a more elegant and efficient way to do it.

    var arr = [];

//I have a array like this:
    arr = [{
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 1,
        studentName: 'A',
        studentAge: 10
      },
      {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 2,
        studentName: 'B',
        studentAge: 11
      }, {
        teacherid: 10,
        teacherName: 'andy',
        age: 30,
        studentid: 3,
        studentName: 'C',
        studentAge: 12
      },

      {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 4,
        studentName: 'D',
        studentAge: 9
      }, {
        teacherid: 11,
        teacherName: 'May',
        age: 40,
        studentid: 5,
        studentName: 'E',
        studentAge: 12
      }
    ];

//want to group the students info in each indiviual teacher like this:
//*
    [{
      "teacherid": 10,
      "teacherName": "andy",
      "age": 30,
      "studentArr": [{
        "studentid": 1,
        "studentName": "A",
        "studentAge": 10
      }, {
        "studentid": 2,
        "studentName": "B",
        "studentAge": 11
      }, {
        "studentid": 3,
        "studentName": "C",
        "studentAge": 12
      }]
    }, {
      "teacherid": 11,
      "teacherName": "May",
      "age": 40,
      "studentArr": [{
        "studentid": 4,
        "studentName": "D",
        "studentAge": 9
      }, {
        "studentid": 5,
        "studentName": "E",
        "studentAge": 12
      }]
    }
    }]
*//

//my solution
    var result = [];
    var first = true;
    arr = _.sortBy(arr, 'teacherid');

    (function() {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i; j < arr.length; j++) {
          console.log("comparing i:" + i + " with j:" + j);

          if (i === j && j === arr.length) {
            console.log("exit " + i + " : " + j)
            return;
          } else if (arr[i].teacherid === arr[j].teacherid) {
            if (first) {
              result.push({
                teacherid: arr[j].teacherid,
                teacherName: arr[j].teacherName,
                age: arr[j].age,
                studentArr: [{
                  studentid: arr[j].studentid,
                  studentName: arr[j].studentName,
                  studentAge: arr[j].studentAge
                }]
              })
            } else {
              //find in result arr, the obj that contain this teacher and push the student in the array
              var teacher = _.find(result, function(item) {
                return (item.teacherid === arr[j].teacherid)
              })
              teacher.studentArr.push({
                studentid: arr[j].studentid,
                studentName: arr[j].studentName,
                studentAge: arr[j].studentAge
              })
            }
            first = false;

          } else {
            first = true;
            i = j - 1;
            j = arr.length; //end inner loop, go back to outer loop and check next teacherID
          }
        }
      }

    })()

    console.log(JSON.stringify(result));

This would be a headache if another programmer were to read it. I was wondering if there is a better solution (more efficient and/or more readable) than this. I feel like I brute-forced this


问:
8 meassurements (cube) in 3D space - interpolate between the values by one 3D position
I measured data in a 3d space. lets say temperature in a room for example. the 8 measurement points are arranged like the edges of a cube. I have room coordinates and temperature data for each point.

Now I track a moving person within the same space. Based on the person's actual position I want to interpolate between the 8 values to assume the temperature at that point in space.

答: Try the trilinear interpolation. See this Wiki link for details </p>


问:
ClassNotFoundException when submitting JAR to Spark via spark-submit
I'm struggling to submit a JAR to Apache Spark using spark-submit.

To make things easier, I've experimented using this blog post. The code is

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/toddmcgrath/Development/spark-1.6.1-bin-hadoop2.4/README.md" // I've replaced this with the path to an existing file
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}
</code>```

I'm running building this with Intellij Idea 2017.1 and running on Spark 2.1.0. Everything is running fine when I run it in the IDE.

I then build it as a JAR and attempt to use spark-submit as follows

```<code>./spark-submit --class SimpleScalaSpark --master local[*] ~/Documents/Spark/Scala/supersimple/out/artifacts/supersimple_jar/supersimple.jar
</code>```

This results in the following error

```<code>java.lang.ClassNotFoundException: SimpleScalaSpark
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

I'm at a loss as to what I'm missing...especially given that it runs as expected in the IDE.

答:
As per your description above
,You are not giving the correct class name, so it is not able to find that class.

Just replace SimpleSparkScala with SimpleScalaSpark

Try running this command:

./spark-submit --class SimpleScalaSpark --master local[*] ~/Documents/Spark/Scala/supersimple/out/artifacts/supersimple_jar/supersimple.jar

Body:
I'm struggling to submit a JAR to Apache Spark using spark-submit.

To make things easier, I've experimented using this blog post. The code is

import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/toddmcgrath/Development/spark-1.6.1-bin-hadoop2.4/README.md" // I've replaced this with the path to an existing file
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}

I'm running building this with Intellij Idea 2017.1 and running on Spark 2.1.0. Everything is running fine when I run it in the IDE.

I then build it as a JAR and attempt to use spark-submit as follows

./spark-submit --class SimpleScalaSpark --master local[*] ~/Documents/Spark/Scala/supersimple/out/artifacts/supersimple_jar/supersimple.jar

This results in the following error

java.lang.ClassNotFoundException: SimpleScalaSpark
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

I'm at a loss as to what I'm missing...especially given that it runs as expected in the IDE.


问:
Convert Ruby Time to HTML5 global date & time String
In Ruby, how do I convert theFixnum 1291132740128 (milliseconds since the epoch) to the equivalent HTML5 global time & date string (Also see HTML5 time element explanation. E.g., 1979-10-14T12:00:00.001-04:00)?

My first attempt is:

```<code>> Time.at(1291132740128/1000.0).strftime("%Y-%m-%dT%H:%M:%S-%Z")
=> "2010-11-30T10:59:00-EST"
</code>```

But, (1) how do I get the milliseconds? Does Time store the milliseconds?

And, (2) how do I get the timezone to be -0400 or -0500, depending on whether it's daylight savings time?

EDIT: Now that I think about it, perhaps it's better to keep it as 1291132740128 and do the conversion with JavaScript according to the browser location. What do you think?

答:
1) %3N in strftime will give you milliseconds:

```<code>Time.at(1291132740128/1000.0).strftime("%Y-%m-%dT%H:%M:%S.%3N-%Z")
=> "2010-11-30T16:59:00.128-CET"
</code>```

2) Isn't that automatic?

EDIT: What would happen if the user had his JS turned off in that case? I think it depends on the usage.

Body:
In Ruby, how do I convert theFixnum 1291132740128 (milliseconds since the epoch) to the equivalent HTML5 global time & date string (Also see HTML5 time element explanation. E.g., 1979-10-14T12:00:00.001-04:00)?

My first attempt is:

> Time.at(1291132740128/1000.0).strftime("%Y-%m-%dT%H:%M:%S-%Z")
=> "2010-11-30T10:59:00-EST"

But, (1) how do I get the milliseconds? Does Time store the milliseconds?

And, (2) how do I get the timezone to be -0400 or -0500, depending on whether it's daylight savings time?

EDIT: Now that I think about it, perhaps it's better to keep it as 1291132740128 and do the conversion with JavaScript according to the browser location. What do you think?

Body:
1) %3N in strftime will give you milliseconds:

Time.at(1291132740128/1000.0).strftime("%Y-%m-%dT%H:%M:%S.%3N-%Z")
=> "2010-11-30T16:59:00.128-CET"

2) Isn't that automatic?

EDIT: What would happen if the user had his JS turned off in that case? I think it depends on the usage.


问:
Horizontal Div Scroll
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
        #container{
            max-width: 938px;
            height: 500px;
            border: 2px solid black;
            margin-left: auto;
            margin-right: auto;
            overflow: scroll;
            /*display: table;*/
        }
        .picsdiv{
            display: table-cell;
            min-width: 286px;
            padding-right: 80px;
            height: 508px;
            border: 2px solid pink;

        }

        .prev, .next {
          cursor: pointer;
          position: absolute;
          top: 250px;
          width: auto;
          margin-top: -22px;
          padding: 16px;
          color: white;
          font-weight: bold;
          font-size: 18px;
          transition: 0.6s ease;
          border-radius: 0 3px 3px 0;
            border: 2px solid pink;
        }

        .next {
          right: 170px;
          border-radius: 3px 0 0 3px;
        }
        .prev{
            left: 170px;
        }

        .prev:hover, .next:hover {
          background-color: rgba(0,0,0,0.8);
        }
    </style></code>```

       ❮
      ❯

```

答:
take out the semi-colon on this line and it should work</p>

```<code>scrollLeft: pos - 200;
</code>```

Title: Horizontal Div Scroll

Body:
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

       ❮
      ❯

Body:
take out the semi-colon on this line and it should work

scrollLeft: pos - 200;


问:
Strcpy Null Value Obtained From MySQL in C
I am using Connector C to connect to my MySQL database.  A modification that I have made to the database recently now allows the data in my url field to be NULL. Connector C does not appear to have any problems reading the NULL value, but when I try and pass the value to my array structure using strcpy, the program crashes. Here is a simplified version of my code:

```<code>mysql_real_connect(conn, server,user,password,database, port, NULL, 0);
mysql_query(conn, "SELECT * FROM main WHERE propType IN ('Single Family', 'Condominium')");
res = mysql_use_result(conn);

while (((row = mysql_fetch_row(res)) != NULL) && (row[0] != NULL)) {

    props[count].uniqueID = atol(row[0]);
    strcpy(props[count].address, row[1]);
    .
    .
    .
    strcpy(props[count].url, row[55]);
    count++;
}
</code>```

By tracing out output of the rows, I have determined that it is this line of code that is failing, and it is ONLY failing when row[55] is (null):

```<code>strcpy(props[count].url, row[55]);
</code>```

I am fairly new to C, and I assume that the problem lies in trying to use strcpy with a null string.

Any suggestions?

答:
As is suggested above in the comment the problem is that row[55] has the value NULL and so strcpy() will crash. Maybe you want to try the following:

```<code>if (row[55] != NULL)
    strcpy(props[count].url, row[55]);
else
    props[count].url[0] = '\0';
</code>```

Here is another example code which use a bit to store if the database contains NULL or a empty value:

```<code>if (row[55] != NULL)
{
    strcpy(props[count].url, row[55]);
    props[count].urlEmpty = false;
}
else
{
    props[count].url = '\0';          // Maybe you can skip this
    props[count].urlEmpty = true;
}
</code>```

In this case you need to expand your structure.

Body:
I am using Connector C to connect to my MySQL database.  A modification that I have made to the database recently now allows the data in my url field to be NULL. Connector C does not appear to have any problems reading the NULL value, but when I try and pass the value to my array structure using strcpy, the program crashes. Here is a simplified version of my code:

mysql_real_connect(conn, server,user,password,database, port, NULL, 0);
mysql_query(conn, "SELECT * FROM main WHERE propType IN ('Single Family', 'Condominium')");
res = mysql_use_result(conn);

while (((row = mysql_fetch_row(res)) != NULL) && (row[0] != NULL)) {

    props[count].uniqueID = atol(row[0]);
    strcpy(props[count].address, row[1]);
    .
    .
    .
    strcpy(props[count].url, row[55]);
    count++;
}

By tracing out output of the rows, I have determined that it is this line of code that is failing, and it is ONLY failing when row[55] is (null):

strcpy(props[count].url, row[55]);

I am fairly new to C, and I assume that the problem lies in trying to use strcpy with a null string.

Any suggestions?

Body:
As is suggested above in the comment the problem is that row[55] has the value NULL and so strcpy() will crash. Maybe you want to try the following:

if (row[55] != NULL)
    strcpy(props[count].url, row[55]);
else
    props[count].url[0] = '\0';

Here is another example code which use a bit to store if the database contains NULL or a empty value:

if (row[55] != NULL)
{
    strcpy(props[count].url, row[55]);
    props[count].urlEmpty = false;
}
else
{
    props[count].url = '\0';          // Maybe you can skip this
    props[count].urlEmpty = true;
}

In this case you need to expand your structure.


问:
What does "+ 3" in while (*(MPcore_private_timer_ptr + 3) == 0) mean?
I am currently reading through DE0-Nano-SoC Computer System
with ARM Cortex-A9 user guide i found a c code in it and i don't understand what does  "+ 3"  in "*(MPcore_private_timer_ptr + 3)" mean?  </p>

```<code>while (1)
{
*HPS_GPIO1_ptr = HPS_LEDG; // turn on/off LEDG
while (*(MPcore_private_timer_ptr + 3) == 0)
; // wait for timer to expire
*(MPcore_private_timer_ptr + 3) = 1; // reset timer flag bit
HPS_LEDG ^= bit_24_pattern; // toggle bit that controls LEDG
}
</code>```

答:
*(MPcore_private_timer_ptr + 3) is the same as MPcore_private_timer_ptr[3].
You dereference an incremented pointer.

Body:
I am currently reading through DE0-Nano-SoC Computer System
with ARM Cortex-A9 user guide i found a c code in it and i don't understand what does  "+ 3"  in "*(MPcore_private_timer_ptr + 3)" mean?

while (1)
{
*HPS_GPIO1_ptr = HPS_LEDG; // turn on/off LEDG
while (*(MPcore_private_timer_ptr + 3) == 0)
; // wait for timer to expire
*(MPcore_private_timer_ptr + 3) = 1; // reset timer flag bit
HPS_LEDG ^= bit_24_pattern; // toggle bit that controls LEDG
}


问:
How to get mapid for a map created in an editor using mapbox.js?
I have created a map using mapbox.js for various layer. I have the html file for it. I want to get the mapid for this map so that I can embed it in my website. How should I get the mapid?</p>

答:
https://www.mapbox.com/studio/tilesets/

Click on the drop down for the tilesets as shown in screenshot.
This will get you the id for that chosen tileset view.


问:
Preserving login session across multiple Android apps
I have two apps that both log in to the same system but they have separate functions and may not both be installed at the same time. I can sign the two apps with the same signature no problem, even make them run in the same process.

How can I store the login cookie (among other things) in such a way that it is shared by both apps and still be secured from unknown apps?

答: Shared user ID should get you access to each other's private storage, you would just need to figure out if the other was already installed, figure out the absolute path to its private storage and then look and see if it had the cookie.  Hopefully you won't starve at the table of philosophers.</p>