问:
PHP Mail attechment dont work
I have a problem because my file attechment via a php doesn't work. I tried different tutorials. My last try was the code here:

```<code>if($isValid === true) {

    // Submit Mail
    $mail = new SimpleMail();
    $mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
    ->setSubject('Neue Mietanfrage')
    ->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
    ->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
    ->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
    ->setMessage(createMessage($_POST))
    ->setWrap(100);

    $mail->send();

    // Submit Client Mail
    $mailClient = new SimpleMail();
    $mailClient->setTo(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
    ->setSubject('Ihre Mietanfrage bei '.YOUR_COMPANY_NAME)
    ->setFrom(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
    ->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
    ->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
    ->setMessage(createClientMessage($_POST))
    ->setWrap(100);

        $mailClient->send();

    $result = array(
        'result' => 'success',
        'msg' => array('Ihre Reservierung wurde erfolgreich übermittelt.')
        );

    echo json_encode($result);

} else {
    $result = array(
        'result' => 'error',
        'msg' => $isValid
        );

    echo json_encode($result);
}

//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
$strFilesName = $_FILES["fileAttach"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}

<input type="file" name="fileAttach" id="fileAttach" hidden>
</code>```

Why doesnt that worked for me? I just followed the tutorial but nothing helped. Do you have any idea what I have to do? The other informations like the text fields are sending without problems.

I get the informations from that form with javascript. Does that script pay any role why the email doesnt send with the attachment?

$( "#umzug-form" ).submit(function() {

  $('#umzug-form-msg').addClass('hidden');
  $('#umzug-form-msg').removeClass('alert-success');
  $('#umzug-form-msg').removeClass('alert-danger');

  $('#umzug-form input[type=submit]').attr('disabled', 'disabled');

  $.ajax({
    type: "POST",
    url: "php/umzug.php",
    data: $("#umzug-form").serialize(),
    dataType: "json",
    success: function(data)  {

      if('success' == data.result)
      {
        $('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-success');
        $('#umzug-form-msg').html(data.msg[0]);
        $('#umzug-form input[type=submit]').removeAttr('disabled');
        $('#umzug-form')[0].reset();
      }

      if('error' == data.result)
      {
        $('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-danger');
        $('#umzug-form-msg').html(data.msg[0]);
        $('#umzug-form input[type=submit]').removeAttr('disabled');
      }

    }
  });

  return false;
});```

答:
You aren't adding the file to the mail object anywhere.

SimpleMail provides the method addAttachment to add attachments to your email.

I'm extending your code with the needed lines:

```<code>// Submit Mail
$mail = new SimpleMail();
$mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
    ->setSubject('Neue Mietanfrage')
    ->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
    ->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
    ->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
    ->setMessage(createMessage($_POST))
    ->setWrap(100);

// add the following lines to your code
if (isset($_FILES['fileAttach']['tmp_name'])) {
    $mail->addAttachment(
        $_FILES['fileAttach']['tmp_name'],
        $_FILES['fileAttach']['name']
    );
}

$mail->send();
</code>```

SimpleMail will load the contents of the file by itself.

Title: PHP Mail attechment dont work

Body:
I have a problem because my file attechment via a php doesn't work. I tried different tutorials. My last try was the code here:

if($isValid === true) {

    // Submit Mail
    $mail = new SimpleMail();
    $mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
    ->setSubject('Neue Mietanfrage')
    ->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
    ->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
    ->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
    ->setMessage(createMessage($_POST))
    ->setWrap(100);

    $mail->send();

    // Submit Client Mail
    $mailClient = new SimpleMail();
    $mailClient->setTo(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
    ->setSubject('Ihre Mietanfrage bei '.YOUR_COMPANY_NAME)
    ->setFrom(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
    ->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
    ->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
    ->setMessage(createClientMessage($_POST))
    ->setWrap(100);

        $mailClient->send();

    $result = array(
        'result' => 'success',
        'msg' => array('Ihre Reservierung wurde erfolgreich übermittelt.')
        );

    echo json_encode($result);

} else {
    $result = array(
        'result' => 'error',
        'msg' => $isValid
        );

    echo json_encode($result);
}

//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
$strFilesName = $_FILES["fileAttach"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}

<input type="file" name="fileAttach" id="fileAttach" hidden>

Why doesnt that worked for me? I just followed the tutorial but nothing helped. Do you have any idea what I have to do? The other informations like the text fields are sending without problems.

I get the informations from that form with javascript. Does that script pay any role why the email doesnt send with the attachment?

$( "#umzug-form" ).submit(function() {

  $('#umzug-form-msg').addClass('hidden');
  $('#umzug-form-msg').removeClass('alert-success');
  $('#umzug-form-msg').removeClass('alert-danger');

  $('#umzug-form input[type=submit]').attr('disabled', 'disabled');

  $.ajax({
    type: "POST",
    url: "php/umzug.php",
    data: $("#umzug-form").serialize(),
    dataType: "json",
    success: function(data)  {

      if('success' == data.result)
      {
        $('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-success');
        $('#umzug-form-msg').html(data.msg[0]);
        $('#umzug-form input[type=submit]').removeAttr('disabled');
        $('#umzug-form')[0].reset();
      }

      if('error' == data.result)
      {
        $('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-danger');
        $('#umzug-form-msg').html(data.msg[0]);
        $('#umzug-form input[type=submit]').removeAttr('disabled');
      }

    }
  });

  return false;
});

Body:
You aren't adding the file to the mail object anywhere.

SimpleMail provides the method addAttachment to add attachments to your email.

I'm extending your code with the needed lines:

// Submit Mail
$mail = new SimpleMail();
$mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
    ->setSubject('Neue Mietanfrage')
    ->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
    ->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
    ->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
    ->setMessage(createMessage($_POST))
    ->setWrap(100);

// add the following lines to your code
if (isset($_FILES['fileAttach']['tmp_name'])) {
    $mail->addAttachment(
        $_FILES['fileAttach']['tmp_name'],
        $_FILES['fileAttach']['name']
    );
}

$mail->send();

SimpleMail will load the contents of the file by itself.


来源: stackexchange

问:
What is the correct way to use classes in CSS?
I see people creating classes for each object, for example:

.content-wrapper {
  display: flex;
  justify-content: center;
  color: white;
}

.images-wrapper {
  display: flex;
  justify-content: center;
  border: 1px solid white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-wrapper"></div>
<div class="images-wrapper"></div></code>```

But also, I see people creating classes by attributes, as for example in Bootstrap:

.centered-content {
  display: flex;
  justify-content: center;
}

.content-wrapper {
  color: blue;
}

.images-wrapper {
  border: 2px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="centered-content content-wrapper"></div>
<div class="centered-content images-wrapper"></div></code>```

答: If you have a group of elements for which you wish to apply a certain styling create a class, if you have a single element for which you wish to apply a style create an ID. I beleive this is the most common and  generally considered best system by which to use CSS.</p>

ContentLicense: CC BY-SA 3.0

Body:
I see people creating classes for each object, for example:

.content-wrapper {
  display: flex;
  justify-content: center;
  color: white;
}

.images-wrapper {
  display: flex;
  justify-content: center;
  border: 1px solid white;
}

But also, I see people creating classes by attributes, as for example in Bootstrap:

.centered-content {
  display: flex;
  justify-content: center;
}

.content-wrapper {
  color: blue;
}

.images-wrapper {
  border: 2px solid black;
}


问:
Weird constraints/UI bug with view from xib
I'm creating a pull-up google-maps-esque bottom drawer view, which looks like this (when it works):

That bottom drawer view is loaded from a xib:

The issue is that sometimes the view shows up like this:

This seems like a constraints issue, but I think my constraints are all correct. CardView is constrained to the superview on all sides and the pink join button is constrained to the right edge, top, and bottom, and has a greater-than-or-equal-to constraint to the text label to the left.

I'm a bit new to using xibs, so maybe this issue has to do with how I'm instantiating it? Here are my xib init methods:

```<code>override init(frame: CGRect) {
    super.init(frame: frame)
    loadFromXib()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    loadFromXib()
}

func loadFromXib() {
    // standard initialization logic
    Bundle.main.loadNibNamed("ChatroomCardView", owner: self, options: nil)
    contentView!.frame = bounds
   // contentView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    addSubview(contentView!)

    cardView.layer.shadowOffset = CGSize(width: 0, height: -3.0)
    cardView.layer.shadowRadius = 3.0
    cardView.layer.shadowOpacity = 0.6
    cardView.layer.masksToBounds = false

    joinButton.setRadiusWithShadow()
}
</code>```

and here is how I instantiate a cardview (the first two lines):

```<code>// create small view
let chatroomCardView = ChatroomCardView(frame: CGRect(x: 0, y: 0, width: 375, height: 139))
chatroomCardView.chatRoom = chatRoom

// create fullsize view
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let chatroomDetailVC = storyboard.instantiateViewController(withIdentifier: "ChatRoomDetailVC") as! ChatRoomDetailVC
chatroomDetailVC.chatroom = chatRoom

bottomDrawerVC.mainFullVC = chatroomDetailVC
bottomDrawerVC.smallDrawerView = chatroomCardView
bottomDrawerVC.view.addSubview(bottomDrawerVC.mainFullVC.view)
bottomDrawerVC.view.addSubview(bottomDrawerVC.smallDrawerView)
</code>```

I'm really stumped on what the issue could be, so any help would be greatly appreciated.

答: You are adding your view as a subview of your view controller's view, but where are you creating the constraints between these two views?  You may have constraints for the subviews of chatroomCardView, but you still need to programmatically create constraints between chatroomCardView and its super view.  ie something along the lines of translatesAutoresizingMaskIntoConstraints = false, and then bottomAnchor to bottomAnchor, leadingAnchor to leadingAnchor, trailingAnchor to trailingAnchor and a constant height constraint, or just shove both subviews into a vertical stackview.</p>

Body:
I'm creating a pull-up google-maps-esque bottom drawer view, which looks like this (when it works):

That bottom drawer view is loaded from a xib:

The issue is that sometimes the view shows up like this:

This seems like a constraints issue, but I think my constraints are all correct. CardView is constrained to the superview on all sides and the pink join button is constrained to the right edge, top, and bottom, and has a greater-than-or-equal-to constraint to the text label to the left.

I'm a bit new to using xibs, so maybe this issue has to do with how I'm instantiating it? Here are my xib init methods:

override init(frame: CGRect) {
    super.init(frame: frame)
    loadFromXib()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    loadFromXib()
}

func loadFromXib() {
    // standard initialization logic
    Bundle.main.loadNibNamed("ChatroomCardView", owner: self, options: nil)
    contentView!.frame = bounds
   // contentView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    addSubview(contentView!)

    cardView.layer.shadowOffset = CGSize(width: 0, height: -3.0)
    cardView.layer.shadowRadius = 3.0
    cardView.layer.shadowOpacity = 0.6
    cardView.layer.masksToBounds = false

    joinButton.setRadiusWithShadow()
}

and here is how I instantiate a cardview (the first two lines):

// create small view
let chatroomCardView = ChatroomCardView(frame: CGRect(x: 0, y: 0, width: 375, height: 139))
chatroomCardView.chatRoom = chatRoom

// create fullsize view
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let chatroomDetailVC = storyboard.instantiateViewController(withIdentifier: "ChatRoomDetailVC") as! ChatRoomDetailVC
chatroomDetailVC.chatroom = chatRoom

bottomDrawerVC.mainFullVC = chatroomDetailVC
bottomDrawerVC.smallDrawerView = chatroomCardView
bottomDrawerVC.view.addSubview(bottomDrawerVC.mainFullVC.view)
bottomDrawerVC.view.addSubview(bottomDrawerVC.smallDrawerView)

I'm really stumped on what the issue could be, so any help would be greatly appreciated.


问:
C: How to find the day name for a given day of the year input by user
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

```<code>int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}
</code>```

答:
How to find the day name for a given day of the year input by user

Use mktime() to calculate the day of the week for a given year, month, day.

```<code>#include <stdio.h>
#include <time.h>

const char *day_name(int year, int month, int day) {
  struct tm tm = { .tm_year = year - 1900, .tm_mon = month - 1, .tm_mday = day,
      .tm_isdst = -1 };
  time_t t = mktime(&tm);
  if (t == -1) {
    return "?";
  }
  static const char *dow[] = { "Sunday", "Monday", "Tuesday", "Wednesday",
      "Thursday", "Friday", "Saturday" };
  return dow[tm.tm_wday];
}

int main(void) {
  puts(day_name(2017, 1, 1));
  puts(day_name(2017, 2, 24));
  puts(day_name(2017, 11, 14));
}
</code>```

Output

```<code>Sunday
Friday
Tuesday
</code>```

With OP's code use a variation on countDays(month, day)

```<code>#define Jan1_2017DOW (0 /* Sunday */)
#define Jan1Number 1
int dow = (countDays(month, day) - Jan1Number + Jan1_2017DOW) % 7;
puts(c[dow]);
</code>```

Body:
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}

Body:
How to find the day name for a given day of the year input by user

Use mktime() to calculate the day of the week for a given year, month, day.

#include <stdio.h>
#include <time.h>

const char *day_name(int year, int month, int day) {
  struct tm tm = { .tm_year = year - 1900, .tm_mon = month - 1, .tm_mday = day,
      .tm_isdst = -1 };
  time_t t = mktime(&tm);
  if (t == -1) {
    return "?";
  }
  static const char *dow[] = { "Sunday", "Monday", "Tuesday", "Wednesday",
      "Thursday", "Friday", "Saturday" };
  return dow[tm.tm_wday];
}

int main(void) {
  puts(day_name(2017, 1, 1));
  puts(day_name(2017, 2, 24));
  puts(day_name(2017, 11, 14));
}

Output

Sunday
Friday
Tuesday

With OP's code use a variation on countDays(month, day)

#define Jan1_2017DOW (0 /* Sunday */)
#define Jan1Number 1
int dow = (countDays(month, day) - Jan1Number + Jan1_2017DOW) % 7;
puts(c[dow]);


问:
iPhone not connected. Xcode will continue when iPhone is connected
I have my iPhone connected to Xcode. It used to work just fine recently. I see it in the Devices and Simulators section, but when I try to compile my app, it says:

D's iPhone 6S is not connected. Xcode will continue when D's iPhone 6S is connected.

In the Devices and Simulators I see it as disconnected.

I tried restarting the phone, turning it's wifi on and off. It's connected to the same wifi network, I tried restarting Xcode, nothing. I run Xcode 9, Beta 6 at the moment. Does anyone has similar issue and hopefully know how to solve it?

答: I had this issue when I changed my network connection on my Mac and in this case reconnecting the phone with an USB cable doesn't work. I had to restart xCode.</p>

ContentLicense: CC BY-SA 4.0


问:
Can css block to insert space?
I have a form where I just can insert a space on inputs. In the textarea I can't (and I need).

As you can see, insert space on textarea works perfectly.

<form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="multipart/form-data" novalidate="novalidate">

<input type="hidden" name="_wpcf7" value="519">
<input type="hidden" name="_wpcf7_version" value="4.9.1">
<input type="hidden" name="_wpcf7_locale" value="pt_BR">
<input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f519-o1">
<input type="hidden" name="_wpcf7_container_post" value="0">

 Name:  <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false">

 E-mail:  <input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false">

 Message:  <textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" aria-required="true" aria-invalid="false"></textarea>

     <input type="submit" value="Send" class="wpcf7-form-control wpcf7-submit">

</form>```

But in my form, I cant.
I'm using Contact Form 7 in wordpress, and I already tried to swith the textarea, but didn't worked.

I take a screenshot showing the css of textarea because I didn't put any JS that points to any textarea (I couldn't see anything that could  block the spaces).

答:
I am not sure, but my guess is that maybe there are listeners attached to your form element that prevents default behavior in case of space key press. Something like:

```<code>var textArea = document.querySelector("textarea[name='your-message']");
textArea.addEventListener("keyup", function(e) {
    // space character
    if (e.keyCode === 32) {
        e.preventDefault();
        e.stopPropagation();
    }
});
</code>```

You could try to unbind all listeners to the textarea element.

Using javascript only:

```<code>var textArea = document.querySelector("textarea[name='your-message']");
var clone = textArea.cloneNode();
while (textArea.firstChild) {
  clone.appendChild(textArea.lastChild);
}
textArea.parentNode.replaceChild(clone, textArea);
</code>```

Using jQuery:

```<code>var textArea = $("textarea[name='your-message']");
textArea.unbind();
textArea.off();
</code>```

Title: Can css block to insert space?

Body:
I have a form where I just can insert a space on inputs. In the textarea I can't (and I need).

As you can see, insert space on textarea works perfectly.

<form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="multipart/form-data" novalidate="novalidate">

<input type="hidden" name="_wpcf7" value="519">
<input type="hidden" name="_wpcf7_version" value="4.9.1">
<input type="hidden" name="_wpcf7_locale" value="pt_BR">
<input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f519-o1">
<input type="hidden" name="_wpcf7_container_post" value="0">

 Name:  <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false">

 E-mail:  <input type="email" name="your-email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false">

 Message:  <textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" aria-required="true" aria-invalid="false"></textarea>

     <input type="submit" value="Send" class="wpcf7-form-control wpcf7-submit">

</form>

But in my form, I cant.
I'm using Contact Form 7 in wordpress, and I already tried to swith the textarea, but didn't worked.

I take a screenshot showing the css of textarea because I didn't put any JS that points to any textarea (I couldn't see anything that could  block the spaces).

Body:
I am not sure, but my guess is that maybe there are listeners attached to your form element that prevents default behavior in case of space key press. Something like:

var textArea = document.querySelector("textarea[name='your-message']");
textArea.addEventListener("keyup", function(e) {
    // space character
    if (e.keyCode === 32) {
        e.preventDefault();
        e.stopPropagation();
    }
});

You could try to unbind all listeners to the textarea element.

Using javascript only:

var textArea = document.querySelector("textarea[name='your-message']");
var clone = textArea.cloneNode();
while (textArea.firstChild) {
  clone.appendChild(textArea.lastChild);
}
textArea.parentNode.replaceChild(clone, textArea);

Using jQuery:

var textArea = $("textarea[name='your-message']");
textArea.unbind();
textArea.off();


问:
Does Microsoft OLE DB Provider for SQL Server support TLS 1.2
Our client recently upgraded from TLS 1.0 to TLS 1.2 and after this our software cannot connect with SQL server. It uses OLE DB provider for connecting to SQL server.
Below is the error which is returned from SQL server-

[DBNETLIB][ConnectionOpen SECDoClientHandshake()]SSL Security error
SQL State: 08001
SQL Error Number: 18

Could not find any useful information related to whether Microsoft OLE DB Provider for SQL Server support TLS 1.2 or not.

One of the links I found seems to suggest that it is not supported.
https://forums.iis.net/t/1233674.aspx?connecing+SQL+server+DB+issue+after+installingTLS1+2+in+SQL+srver+with+classic+asp+application+

Hence, wanted to check on stackoverflow in case anyone has any information on this.

答:
This may not be a solution for you, since it's a future fix your client may not be able to wait for, but apparently Microsoft is undeprecating the OLEDB Driver, with a new release supporting TLS 1.2 out Q1 2018: https://blogs.msdn.microsoft.com/sqlnativeclient/2017/10/06/announcing-the-new-release-of-ole-db-driver-for-sql-server/

The new Microsoft OLE DB Driver for SQL Server, or msoledbsql, will
  also introduce multi-subnet failover capabilities in this first
  upcoming release, and keeps up with latest TLS 1.2 standards.

Also, this first upcoming release will be a stand-alone install
  package that is out-of-band with SQL Server lifecycle. This also means
  the driver will not be packaged in the SNAC library, nor coupled with
  any other driver.


问:
Dynamically instantiate multiple copies of a MC
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

```<code>package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}
</code>```

EDIT:

```<code>package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}
</code>```

答:
The Problem ist that you set PostItNotes as the BaseClass instead of the Class itself.

That means what you add to the stage is a Class that has only the logic and not the graphic elements.

What you need to do is go back to the symbol in the library -> right click -> properties and change the BaseClass to flash.display.MovieClip (or in your case flash.display.Sprite if you don't need the Timeline) and set PostItNotes as the Class.

EDIT:

```<code>package  {

    import flash.display.Sprite;
    import flash.events.MouseEvent;

    public class PostItNotes extends Sprite {

        public function PostItNotes() {
            super();

            addEventListener(MouseEvent.MOUSE_DOWN, onStartDrag);
        }

        protected function onStartDrag (event:MouseEvent):void {

            stage.addEventListener(MouseEvent.MOUSE_UP, onStopDrag);
            startDrag(false);

        }

        protected function onStopDrag (event:MouseEvent):void {

            stage.removeEventListener(MouseEvent.MOUSE_UP, onStopDrag);
            stopDrag();

        }
    }
}
</code>```

I added the drag action to your PostItNotes class because I think this is where it belongs to as the drag really only concerns the post-it itself.

You probably have to remove the drag code where you had it before.

Do you need help on the creation of the new PostIt too?

ContentLicense: CC BY-SA 2.5

Body:
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}

EDIT:

package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}

Body:
The Problem ist that you set PostItNotes as the BaseClass instead of the Class itself.

That means what you add to the stage is a Class that has only the logic and not the graphic elements.

What you need to do is go back to the symbol in the library -> right click -> properties and change the BaseClass to flash.display.MovieClip (or in your case flash.display.Sprite if you don't need the Timeline) and set PostItNotes as the Class.

EDIT:

package  {

    import flash.display.Sprite;
    import flash.events.MouseEvent;

    public class PostItNotes extends Sprite {

        public function PostItNotes() {
            super();

            addEventListener(MouseEvent.MOUSE_DOWN, onStartDrag);
        }

        protected function onStartDrag (event:MouseEvent):void {

            stage.addEventListener(MouseEvent.MOUSE_UP, onStopDrag);
            startDrag(false);

        }

        protected function onStopDrag (event:MouseEvent):void {

            stage.removeEventListener(MouseEvent.MOUSE_UP, onStopDrag);
            stopDrag();

        }
    }
}

I added the drag action to your PostItNotes class because I think this is where it belongs to as the drag really only concerns the post-it itself.

You probably have to remove the drag code where you had it before.

Do you need help on the creation of the new PostIt too?


问:
Making site multi language support using google translate for React js
For simple html projects i can simple refer this link.

https://www.w3schools.com/howto/howto_google_translate.asp

But I'm trying to implement in react app . So I'm not able to replicate the code in react app.

```<code>componentDidMount() {
  googleTranslateElementInit(() => {
    new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
    });
    const script = document.createElement("script");
    script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    script.async = true;
    document.body.appendChild(script);
}
</code>```

And return render element .

```<code>  render() {
    return (
      <div id="google_translate_element"></div>
    );
  }
</code>```

This is showing me error saying google , googleTranslateElementInit is not defined.

How can I use google translator in react app  ?
Also is there any npm packages which can translate whole site ?

Thanks

答:
Move your google translate script to the root index.html of your project.

However, you should leave the below code at your desired location:

```<code>render() {
    return (
      <div id="google_translate_element"></div>
    );
  }
</code>```

Fixes the problem easily.

Body:
For simple html projects i can simple refer this link.

https://www.w3schools.com/howto/howto_google_translate.asp

But I'm trying to implement in react app . So I'm not able to replicate the code in react app.

componentDidMount() {
  googleTranslateElementInit(() => {
    new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
    });
    const script = document.createElement("script");
    script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    script.async = true;
    document.body.appendChild(script);
}

And return render element .

  render() {
    return (

    );
  }

This is showing me error saying google , googleTranslateElementInit is not defined.

How can I use google translator in react app  ?
Also is there any npm packages which can translate whole site ?

Thanks

Body:
Move your google translate script to the root index.html of your project.

However, you should leave the below code at your desired location:

render() {
    return (
      <div id="google_translate_element"></div>
    );
  }

Fixes the problem easily.


问:
Setting workDir for gwt codeserver with tbroyer maven plugin
I'm using the tbroyer multimodule gwt archetype &
finding the codeserver compiles take up too much space.
I have a batch file for deleting them but this takes too long so
I'm trying to change the workDir to a ram disk to speed up the deletes (one possible solution). </p>

<p>I tried various things in the parent pom.xml
which is where launcherDir is set using a workDir tag but this didn't change it. Also no success adding -Dgwt.args to the maven goals in my eclipse codeserver debug configuration.  </p>

答:
Use the codeserverWorkDir property.
https://tbroyer.github.io/gwt-maven-plugin/codeserver-mojo.html#codeserverWorkDir

Body:
I'm using the tbroyer multimodule gwt archetype &
finding the codeserver compiles take up too much space.
I have a batch file for deleting them but this takes too long so
I'm trying to change the workDir to a ram disk to speed up the deletes (one possible solution).

I tried various things in the parent pom.xml
which is where launcherDir is set using a workDir tag but this didn't change it. Also no success adding -Dgwt.args to the maven goals in my eclipse codeserver debug configuration.


问:
Can somebody explain this javascript fragment?

// JavaScript source code
var foo = (function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

})();

foo.bar();```

What is going on? Is foo an object? Is it a named function?
This looks like a hideous way to provide the class concept of private data members....

答:
They are called IIFE's https://developer.mozilla.org/en-US/docs/Glossary/IIFE

Check this example where IIFE's are used http://javascriptissexy.com/understand-javascript-closures-with-ease/

Usually javascript modules are written in the pattern.

```<code>var foo = function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

};

foo().bar();
</code>```

AND

```<code>var foo = (function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

})();

foo.bar();
</code>```

are similar.

Body:
// JavaScript source code
var foo = (function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

})();

foo.bar();

What is going on? Is foo an object? Is it a named function?
This looks like a hideous way to provide the class concept of private data members....

Body:
They are called IIFE's https://developer.mozilla.org/en-US/docs/Glossary/IIFE

Check this example where IIFE's are used http://javascriptissexy.com/understand-javascript-closures-with-ease/

Usually javascript modules are written in the pattern.

var foo = function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

};

foo().bar();

AND

var foo = (function () {
    var o = { bar: "bar" };

    return {
        bar: function () {
            console.log(o.bar);
        }
    };

})();

foo.bar();

are similar.


答:
here is a simple solution :)

```<code>void countDays(int day, int month, int daysInMonth[])
{
    char c[][15] =  {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
    int totaldays=0;
    for(int i=0;i<month-1;i++)
    {
        totaldays+= daysInMonth[i];
    }

    totaldays += day;

    printf("There are %d days \n", totaldays);

    printf("\n day : %s",c[(totaldays-1)%7]);

    return;
}
</code>```

after a little changes to your code with your own approach :)

Title: C: How to find the day name for a given day of the year input by user

Body:
here is a simple solution :)

void countDays(int day, int month, int daysInMonth[])
{
    char c[][15] =  {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
    int totaldays=0;
    for(int i=0;i<month-1;i++)
    {
        totaldays+= daysInMonth[i];
    }

    totaldays += day;

    printf("There are %d days \n", totaldays);

    printf("\n day : %s",c[(totaldays-1)%7]);

    return;
}

after a little changes to your code with your own approach :)


问:
Open report link URL in new blank window
I have dynamic links in my report and when the link is clicked I want it to open in target="_blank".

I have tried the following, but I must be missing a single or double quote somewhere because I am having no luck. The parameters may be throwing me off. For example, I tried these:

="javascript:void(window.open('http://server/folder/filename.aspx?ds='& Parameters!UserName.Value & '&bu=' & Fields!Business_Unit.Value & '&in=' & Fields!Item_No.Value,'_blank'))"
```

<p>And:</p>

<pre class="lang-vb prettyprint-override"><code>="http://server/folder/filename.aspx?ds="& Parameters!UserName.Value & "&bu="& Fields!Business_Unit.Value & "&in=" & Fields!Item_No.Value &rc:LinkTarget=_blank
</code>```

Any suggestions?

答:
This worked for me:</p>

```<code>="javascript:void window.open(" &"'" & Globals!ReportServerUrl & "/Pages/ReportViewer.aspx?" & Globals!ReportFolder & "/SubReportWithMemberInfoUsedByWaiverFinance&rc:Parameters=False&RepParameterSet=50,>64,E," & Fields!YYYYMM.Value & "','_blank')"
</code>```

Body:
I have dynamic links in my report and when the link is clicked I want it to open in target="_blank".

I have tried the following, but I must be missing a single or double quote somewhere because I am having no luck. The parameters may be throwing me off. For example, I tried these:

="javascript:void(window.open('http://server/folder/filename.aspx?ds='& Parameters!UserName.Value & '&bu=' & Fields!Business_Unit.Value & '&in=' & Fields!Item_No.Value,'_blank'))"

And:

="http://server/folder/filename.aspx?ds="& Parameters!UserName.Value & "&bu="& Fields!Business_Unit.Value & "&in=" & Fields!Item_No.Value &rc:LinkTarget=_blank

Any suggestions?

Body:
This worked for me:

="javascript:void window.open(" &"'" & Globals!ReportServerUrl & "/Pages/ReportViewer.aspx?" & Globals!ReportFolder & "/SubReportWithMemberInfoUsedByWaiverFinance&rc:Parameters=False&RepParameterSet=50,>64,E," & Fields!YYYYMM.Value & "','_blank')"


问:
calculate packet loss of libpcap
I'm learning source code of an application. The main usage is capturing and processing packets from interface, mainly based on pcap_open_live and pcap_loop. How to test packet loss? Is there any tool available? OS is Linux.

答:
You can't monitor packet loss on live monitoring since you can't see the packets that are lost!

If you just want to "test" the code (e.g. If you do lengthy computations on each packet which makes you lose packets during that time), simply send packets through the monitored interface at a steady rate, dummy packets.. (whatever.. A ping even)  Then you know how many packets to expect. Compare your expected number of packets to the number sent. You can then try changing the rate and size of packets to see if you miss anything.

I doubt there are any particular tools for this test given the "simplicity" of the test.

Title: calculate packet loss of libpcap


问:
Python inaccurate curve fit
```<code>Temp    k(T)
298   6.66E-63
300   1.48E-62
350   3.58E-55
400   1.25E-49
450   2.57E-45
500   7.30E-42
550   4.90E-39
600   1.12E-36
650   1.11E-34
700   5.72E-33
750   1.75E-31
800   3.49E-30
850   4.92E-29
900   5.17E-28
950   4.24E-25
1000  2.83E-26
</code>```

Above is the given kinetic data, I am trying to fit this data and plot the same.

Curvefitting

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
plt.style.use('ggplot')

#Generate data
df=pd.read_excel('py_curvefit.xlsx')
T=df.Temp  #xdata
def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))
kt=df['k(T)']  #ydata
#rectifying an erroneous value
kt[14]=4.24*10**(-27)
popt,pcov=curve_fit(reacKine,T,kt)
A,n,Ea=popt
plt.plot(T,np.log(kt),'g-',label='given data')
plt.plot(T,np.log(reacKine(T,*popt)),'ro',label='fit')
plt.xlabel('Temperature [K]')
plt.ylabel('log of reaction coefficient')
plt.legend(loc='best')
plt.show()
</code>```

It says optimal parameters not found for the function. How do I rectify this. I am hoping to see a good fit. Is it because of the exponential term?

答:
I get the following parameters and fit statistics using the below code with the pyeq3 fitting library:</p>

```<code>Fitting target of sum of squared absolute error = 7.93711173898e-62
Fitted Parameters:
    A = 3.6814349968228987E-12
    Ea = 2.8663497636217801E+02
    n = 1.6329619761384757E+00

Degress of freedom error 13
Degress of freedom regression 2
Root Mean Squared Error (RMSE): 7.04322002841e-32
R-squared: 0.9999999999
R-squared adjusted: 0.999999999884
Model F-statistic: 64790385432.5
Model F-statistic p-value: 1.11022302463e-16
Model log-likelihood: 1124.98750379
Model AIC: -140.248437973
Model BIC: -140.103577588

Individual Parameter Statistics:
Coefficient A = 3.6814349968228987E-12
    std error: 1.67464E-25
    t-stat: 8.99615E+00
    p-stat: 6.05074E-07
    95 percent confidence intervals: [2.79736E-12, 4.56551E-12]
Coefficient Ea = 2.8663497636217801E+02
    std error: 1.69556E-01
    t-stat: 6.96102E+02
    p-stat: 0.00000E+00
    95 percent confidence intervals: [2.85745E+02, 2.87525E+02]
Coefficient n = 1.6329619761384757E+00
    std error: 2.59159E-03
    t-stat: 3.20770E+01
    p-stat: 9.19265E-14
    95 percent confidence intervals: [1.52298E+00, 1.74294E+00]

Coefficient Covariance Matrix:
    [ 2.74285036e+37   2.75990923e+49  -3.41210380e+48]
    [ 2.75990923e+49   2.77711499e+61  -3.43328442e+60]
    [-3.41210380e+48  -3.43328442e+60   4.24469499e+59]

import os, sys, inspect
import pyeq3

functionString = 'A*((X/298)**n)*exp(-Ea/(0.008314*X))'

data = '''
298   6.66e-63
300   1.48e-62
350   3.58e-55
400   1.25e-49
450   2.57e-45
500   7.30e-42
550   4.90e-39
600   1.12e-36
650   1.11e-34
700   5.72e-33
750   1.75e-31
800   3.49e-30
850   4.92e-29
900   5.17e-28
950   4.24e-27
1000  2.83e-26
'''

# note that the constructor is passed the function string here
equation = pyeq3.Models_2D.UserDefinedFunction.UserDefinedFunction(inUserFunctionString = functionString)

pyeq3.dataConvertorService().ConvertAndSortColumnarASCII(data, equation, False)

equation.Solve()

##########################################################

print("Equation:", equation.GetDisplayName(), str(equation.GetDimensionality()) + "D")
print("Fitting target of", equation.fittingTargetDictionary[equation.fittingTarget], '=', equation.CalculateAllDataFittingTarget(equation.solvedCoefficients))
print("Fitted Parameters:")
for i in range(len(equation.solvedCoefficients)):
    print("    %s = %-.16E" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i]))

equation.CalculateModelErrors(equation.solvedCoefficients, equation.dataCache.allDataCacheDictionary)
print()

##########################################################

equation.CalculateCoefficientAndFitStatistics()

if equation.upperCoefficientBounds or equation.lowerCoefficientBounds:
    print('You entered coefficient bounds. Parameter statistics may')
    print('not be valid for parameter values at or near the bounds.')
    print()

print('Degress of freedom error',  equation.df_e)
print('Degress of freedom regression',  equation.df_r)

if equation.rmse == None:
    print('Root Mean Squared Error (RMSE): n/a')
else:
    print('Root Mean Squared Error (RMSE):',  equation.rmse)

if equation.r2 == None:
    print('R-squared: n/a')
else:
    print('R-squared:',  equation.r2)

if equation.r2adj == None:
    print('R-squared adjusted: n/a')
else:
    print('R-squared adjusted:',  equation.r2adj)

if equation.Fstat == None:
    print('Model F-statistic: n/a')
else:
    print('Model F-statistic:',  equation.Fstat)

if equation.Fpv == None:
    print('Model F-statistic p-value: n/a')
else:
    print('Model F-statistic p-value:',  equation.Fpv)

if equation.ll == None:
    print('Model log-likelihood: n/a')
else:
    print('Model log-likelihood:',  equation.ll)

if equation.aic == None:
    print('Model AIC: n/a')
else:
    print('Model AIC:',  equation.aic)

if equation.bic == None:
    print('Model BIC: n/a')
else:
    print('Model BIC:',  equation.bic)

print()
print("Individual Parameter Statistics:")
for i in range(len(equation.solvedCoefficients)):
    if type(equation.tstat_beta) == type(None):
        tstat = 'n/a'
    else:
        tstat = '%-.5E' %  ( equation.tstat_beta[i])

    if type(equation.pstat_beta) == type(None):
        pstat = 'n/a'
    else:
        pstat = '%-.5E' %  ( equation.pstat_beta[i])

    if type(equation.sd_beta) != type(None):
        print("Coefficient %s = %-.16E, std error: %-.5E" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i], equation.sd_beta[i]))
    else:
        print("Coefficient %s = %-.16E, std error: n/a" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i]))
    print("          t-stat: %s, p-stat: %s, 95 percent confidence intervals: [%-.5E, %-.5E]" % (tstat,  pstat, equation.ci[i][0], equation.ci[i][1]))

print()
print("Coefficient Covariance Matrix:")
for i in  equation.cov_beta:
    print(i)
</code>```

Title: Python inaccurate curve fit

Body:
Temp    k(T)
298   6.66E-63
300   1.48E-62
350   3.58E-55
400   1.25E-49
450   2.57E-45
500   7.30E-42
550   4.90E-39
600   1.12E-36
650   1.11E-34
700   5.72E-33
750   1.75E-31
800   3.49E-30
850   4.92E-29
900   5.17E-28
950   4.24E-25
1000  2.83E-26

Above is the given kinetic data, I am trying to fit this data and plot the same.

Curvefitting

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
plt.style.use('ggplot')

#Generate data
df=pd.read_excel('py_curvefit.xlsx')
T=df.Temp  #xdata
def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))
kt=df['k(T)']  #ydata
#rectifying an erroneous value
kt[14]=4.24*10**(-27)
popt,pcov=curve_fit(reacKine,T,kt)
A,n,Ea=popt
plt.plot(T,np.log(kt),'g-',label='given data')
plt.plot(T,np.log(reacKine(T,*popt)),'ro',label='fit')
plt.xlabel('Temperature [K]')
plt.ylabel('log of reaction coefficient')
plt.legend(loc='best')
plt.show()

It says optimal parameters not found for the function. How do I rectify this. I am hoping to see a good fit. Is it because of the exponential term?

Body:
I get the following parameters and fit statistics using the below code with the pyeq3 fitting library:

Fitting target of sum of squared absolute error = 7.93711173898e-62
Fitted Parameters:
    A = 3.6814349968228987E-12
    Ea = 2.8663497636217801E+02
    n = 1.6329619761384757E+00

Degress of freedom error 13
Degress of freedom regression 2
Root Mean Squared Error (RMSE): 7.04322002841e-32
R-squared: 0.9999999999
R-squared adjusted: 0.999999999884
Model F-statistic: 64790385432.5
Model F-statistic p-value: 1.11022302463e-16
Model log-likelihood: 1124.98750379
Model AIC: -140.248437973
Model BIC: -140.103577588

Individual Parameter Statistics:
Coefficient A = 3.6814349968228987E-12
    std error: 1.67464E-25
    t-stat: 8.99615E+00
    p-stat: 6.05074E-07
    95 percent confidence intervals: [2.79736E-12, 4.56551E-12]
Coefficient Ea = 2.8663497636217801E+02
    std error: 1.69556E-01
    t-stat: 6.96102E+02
    p-stat: 0.00000E+00
    95 percent confidence intervals: [2.85745E+02, 2.87525E+02]
Coefficient n = 1.6329619761384757E+00
    std error: 2.59159E-03
    t-stat: 3.20770E+01
    p-stat: 9.19265E-14
    95 percent confidence intervals: [1.52298E+00, 1.74294E+00]

Coefficient Covariance Matrix:
    [ 2.74285036e+37   2.75990923e+49  -3.41210380e+48]
    [ 2.75990923e+49   2.77711499e+61  -3.43328442e+60]
    [-3.41210380e+48  -3.43328442e+60   4.24469499e+59]

import os, sys, inspect
import pyeq3

functionString = 'A*((X/298)**n)*exp(-Ea/(0.008314*X))'

data = '''
298   6.66e-63
300   1.48e-62
350   3.58e-55
400   1.25e-49
450   2.57e-45
500   7.30e-42
550   4.90e-39
600   1.12e-36
650   1.11e-34
700   5.72e-33
750   1.75e-31
800   3.49e-30
850   4.92e-29
900   5.17e-28
950   4.24e-27
1000  2.83e-26
'''

# note that the constructor is passed the function string here
equation = pyeq3.Models_2D.UserDefinedFunction.UserDefinedFunction(inUserFunctionString = functionString)

pyeq3.dataConvertorService().ConvertAndSortColumnarASCII(data, equation, False)

equation.Solve()

##########################################################

print("Equation:", equation.GetDisplayName(), str(equation.GetDimensionality()) + "D")
print("Fitting target of", equation.fittingTargetDictionary[equation.fittingTarget], '=', equation.CalculateAllDataFittingTarget(equation.solvedCoefficients))
print("Fitted Parameters:")
for i in range(len(equation.solvedCoefficients)):
    print("    %s = %-.16E" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i]))

equation.CalculateModelErrors(equation.solvedCoefficients, equation.dataCache.allDataCacheDictionary)
print()

##########################################################

equation.CalculateCoefficientAndFitStatistics()

if equation.upperCoefficientBounds or equation.lowerCoefficientBounds:
    print('You entered coefficient bounds. Parameter statistics may')
    print('not be valid for parameter values at or near the bounds.')
    print()

print('Degress of freedom error',  equation.df_e)
print('Degress of freedom regression',  equation.df_r)

if equation.rmse == None:
    print('Root Mean Squared Error (RMSE): n/a')
else:
    print('Root Mean Squared Error (RMSE):',  equation.rmse)

if equation.r2 == None:
    print('R-squared: n/a')
else:
    print('R-squared:',  equation.r2)

if equation.r2adj == None:
    print('R-squared adjusted: n/a')
else:
    print('R-squared adjusted:',  equation.r2adj)

if equation.Fstat == None:
    print('Model F-statistic: n/a')
else:
    print('Model F-statistic:',  equation.Fstat)

if equation.Fpv == None:
    print('Model F-statistic p-value: n/a')
else:
    print('Model F-statistic p-value:',  equation.Fpv)

if equation.ll == None:
    print('Model log-likelihood: n/a')
else:
    print('Model log-likelihood:',  equation.ll)

if equation.aic == None:
    print('Model AIC: n/a')
else:
    print('Model AIC:',  equation.aic)

if equation.bic == None:
    print('Model BIC: n/a')
else:
    print('Model BIC:',  equation.bic)

print()
print("Individual Parameter Statistics:")
for i in range(len(equation.solvedCoefficients)):
    if type(equation.tstat_beta) == type(None):
        tstat = 'n/a'
    else:
        tstat = '%-.5E' %  ( equation.tstat_beta[i])

    if type(equation.pstat_beta) == type(None):
        pstat = 'n/a'
    else:
        pstat = '%-.5E' %  ( equation.pstat_beta[i])

    if type(equation.sd_beta) != type(None):
        print("Coefficient %s = %-.16E, std error: %-.5E" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i], equation.sd_beta[i]))
    else:
        print("Coefficient %s = %-.16E, std error: n/a" % (equation.GetCoefficientDesignators()[i], equation.solvedCoefficients[i]))
    print("          t-stat: %s, p-stat: %s, 95 percent confidence intervals: [%-.5E, %-.5E]" % (tstat,  pstat, equation.ci[i][0], equation.ci[i][1]))

print()
print("Coefficient Covariance Matrix:")
for i in  equation.cov_beta:
    print(i)


问:
How do underivable rules affect parsing?
When writing an XText grammar for a simple SQL dialect, I found out, that apparently rules that cannot be derived from the start symbol affect parsing.

E.g. given the following (very simplified) extract of my grammar which should be able to parse expressions like FROM table1;:

```<code>Start:
    subquery ';';

subquery:
    /*select=select_clause */tables=from_clause;

from_clause:
    'FROM' tables;

tables:
    tables+=table (',' tables+=table)*;

table:
    name=table_name (alias=alias)?;

table_name:
    prefix=qualified_name_prefix? name=qualified_name;

qualified_name_prefix:
    ID'.';

qualified_name :
    =>qualified_name_prefix? ID;

alias returns EString:
    'AS'? alias=ID;

with_clause :
    'WITH' elements+=with_list_element (',' elements+=with_list_element)*;

with_list_element :
     name=ID (column_list_clause=column_list_clause)? 'AS' '(' subquery=subquery ')';

column_list_clause :
    '(' names+=ID+ ')';
</code>```

When trying to parse the string FROM table1;, I get the following error:

'no viable alternative at input ';'' on EString

If I remove rule with_clause, the error is gone and the string is parsed properly. How is this possible even though with_clause cannot be derived from Start?

答:
the problem is that the predicate (=>) covers an ambiguity

maybe you can pull together prefix and name

```<code>Table_name:
     name=Qualified_name;

Qualified_name :
   (ID '.' (ID '.')?)? ID;
</code>```

or you try something like

```<code>Table_name:
    ((prefix=ID ".")? =>name=Qualified_name);

Qualified_name :
   =>(ID '.' ID) | ID;
</code>```

Body:
When writing an XText grammar for a simple SQL dialect, I found out, that apparently rules that cannot be derived from the start symbol affect parsing.

E.g. given the following (very simplified) extract of my grammar which should be able to parse expressions like FROM table1;:

Start:
    subquery ';';

subquery:
    /*select=select_clause */tables=from_clause;

from_clause:
    'FROM' tables;

tables:
    tables+=table (',' tables+=table)*;

table:
    name=table_name (alias=alias)?;

table_name:
    prefix=qualified_name_prefix? name=qualified_name;

qualified_name_prefix:
    ID'.';

qualified_name :
    =>qualified_name_prefix? ID;

alias returns EString:
    'AS'? alias=ID;

with_clause :
    'WITH' elements+=with_list_element (',' elements+=with_list_element)*;

with_list_element :
     name=ID (column_list_clause=column_list_clause)? 'AS' '(' subquery=subquery ')';

column_list_clause :
    '(' names+=ID+ ')';

When trying to parse the string FROM table1;, I get the following error:

'no viable alternative at input ';'' on EString

If I remove rule with_clause, the error is gone and the string is parsed properly. How is this possible even though with_clause cannot be derived from Start?

Body:
the problem is that the predicate (=>) covers an ambiguity

maybe you can pull together prefix and name

Table_name:
     name=Qualified_name;

Qualified_name :
   (ID '.' (ID '.')?)? ID;

or you try something like

Table_name:
    ((prefix=ID ".")? =>name=Qualified_name);

Qualified_name :
   =>(ID '.' ID) | ID;


问:
Relation between Linux /proc/meminfo and /sys/devices/system/node/nodex/meminfo
I'd like to get the amount of "free memory" per NUMA node.
When dealing with a whole machine, one usually parses /proc/meminfo like free does (the number wanted is MemFree + Buffers + Cached).
There also exist /sys/devices/system/node/nodex/meminfo, which seem to display numbers per NUMA node. Does anybody know how these numbers can be correlated to the content of /proc/meminfo? My trivial assumption would be to sum up some numbers for all NUMA nodes in the system, and the result is equal to some number in /proc/meminfo. But so far I failed to figure out the relationships, especially for page caches.

答:
The code for proc is in fs/proc/meminfo.c, for the sysfs files it's in drivers/base/node.c. Comparing them might give you some hints.

Note that you'll probably never get the numbers to add up 100%, because you can't atomically read the content of all the files, so the values will change while you're reading them.

There also seems to be an inconsistency in the total RAM reported via both methods. One explanation for that is that free_init_mem doesn't appear to be NUMA aware, and increments total_ram_pages but does not do any NUMA accounting.


问:
ElasticSearch: Count of intersection in terms query
I'm using elasticsearch to implement full user search. I want to return the number of mutual friends shared between the searching user and each of the results. I'm currently using the "terms" query to boost the score of results for users who share mutual friends with the searching user.

For context, the relevant chunk of my query is pasted below:

"should": [
                {
                    "terms": {
                       "friend_ids": [
                          "100", "2", "8", "9", "15", "25"
                       ]
                    }
                }
            ]

Ideally the response would include for each doc a field called "num_mutual_friends"....

答:
One way of achieving this is to use a script_field:</p>

```<code>{
  "query": {...},
  "script_fields": {
    "num_mutual_friends": {
      "script": {
        "inline": "doc['friend_ids'].values.intersect(input_friend_ids).length",
        "params": {
          "input_friend_ids": [
            "101", "9", "8"
          ]
        }
      }
    }
  }
}
</code>```

Body:
One way of achieving this is to use a script_field:

{
  "query": {...},
  "script_fields": {
    "num_mutual_friends": {
      "script": {
        "inline": "doc['friend_ids'].values.intersect(input_friend_ids).length",
        "params": {
          "input_friend_ids": [
            "101", "9", "8"
          ]
        }
      }
    }
  }
}


问:
Issues with parallel Julia code on windows cluster
I'm setting up a small windows cluster for parallel speedup of my Julia code (2x32 cores).

I have following questions:

Is there a way to suppress loading of a module (e.g. "using PyPlot") on the remote machines? In my code, I use my workstation for initialization and data presentation, whereas the cluster is used for heavy calculation without any need for PyPlot, Dataframes etc.

This code loading on the remote machines is even more annoying as the PyPlot (and any other package) fails to populate help database by giving following error message: (actually a lot of errors from every worker)

```<code>exception on : 1: 1ERROR: opening file C:\Users\phlavenk\AppData\Local\Julia-0.3.6\bin/../share/julia\helpdb.jl: No such file or directory
</code>```

Running on Julia 3.6/ x64 / Windows7, identical directory structure and versions everywhere.

My addprocs command is following:

```<code>addprocs(machines,
  sshflags=`-i c:\\cygwin64\\home\\phlavenk\\.ssh\\id_rsa`,
  dir=`/cygdrive/c/Users/phlavenk/AppData/Local/Julia-0.3.6/bin`,
  tunnel=true)
</code>```

Thank you very much for your advice

答:
You could sequence the statements in this order:</p>

```<code>using PyPlot
using ModuleNeededOnMasterProcessOnly
addprocs(...)
using ModuleNeededOnAllProcesses
</code>```

Body:
I'm setting up a small windows cluster for parallel speedup of my Julia code (2x32 cores).

I have following questions:

Is there a way to suppress loading of a module (e.g. "using PyPlot") on the remote machines? In my code, I use my workstation for initialization and data presentation, whereas the cluster is used for heavy calculation without any need for PyPlot, Dataframes etc.

This code loading on the remote machines is even more annoying as the PyPlot (and any other package) fails to populate help database by giving following error message: (actually a lot of errors from every worker)

exception on : 1: 1ERROR: opening file C:\Users\phlavenk\AppData\Local\Julia-0.3.6\bin/../share/julia\helpdb.jl: No such file or directory

Running on Julia 3.6/ x64 / Windows7, identical directory structure and versions everywhere.

My addprocs command is following:

addprocs(machines,
  sshflags=`-i c:\\cygwin64\\home\\phlavenk\\.ssh\\id_rsa`,
  dir=`/cygdrive/c/Users/phlavenk/AppData/Local/Julia-0.3.6/bin`,
  tunnel=true)

Thank you very much for your advice

Body:
You could sequence the statements in this order:

using PyPlot
using ModuleNeededOnMasterProcessOnly
addprocs(...)
using ModuleNeededOnAllProcesses


问:
Variable Column based on Date
VBA noobie here.

I have a spreadsheet with a list of cashiers vertically and each day of the month horizontally. i.e:

```<code>11/1/2017    11/2/2017    11/13/2017

Jesse

Frank

Jessica

Martin
</code>```

The rest of the spreadsheet is populated with sales data for each cashier.

I want to randomly select 5 cashiers and display their names and sales data on a separate sheet.

I have code written that will select 5 random names, however I'm looking to make it dynamic so that the user can choose which column to run the macro on (i.e., they can choose which date).

```<code>`Sub PickNamesAtRandom()

Dim HowMany As Integer
Dim NoOfNames As Long
Dim RandomNumber As Integer
Dim Names() As String 'Array to store randomly selected names
Dim i As Byte
Dim CellsOut As Long 'Variable to be used when entering names onto worksheet
Dim ArI As Byte 'Variable to increment through array indexes

Application.ScreenUpdating = False

HowMany = Range("C43").Value
CellsOut = 6

ReDim Names(1 To HowMany) 'Set the array size to how many names required
NoOfNames = Application.CountA(Range("A:A")) - 1 ' Find how many names in the list
i = 1

Do While i <= HowMany
RandomNo:
    RandomNumber = Application.RandBetween(2, NoOfNames + 1)
    'Check to see if the name has already been picked
    For ArI = LBound(Names) To UBound(Names)
        If Names(ArI) = Cells(RandomNumber, 1).Value Then
            GoTo RandomNo
        End If
    Next ArI
    Names(i) = Cells(RandomNumber, 1).Value ' Assign random name to the array
    i = i + 1
Loop

'Loop through the array and enter names onto the worksheet
For ArI = LBound(Names) To UBound(Names)

    Cells(CellsOut, 4) = Names(ArI)
    CellsOut = CellsOut + 1

Next ArI

Application.ScreenUpdating = True

End Sub`
</code>```

Any help is appreciated!

答:
You could use an InputBox to get which column the user wants to use.

```<code>Dim lRet As Long
lRet = clng(Inputbox("Select column"))
</code>```

You can then use that variable later in your code. Change where you have this:

```<code>Cells(RandomNumber, 1).Value
</code>```

To this:

```<code>Cells(RandomNumber, lRet).Value
</code>```

Edit:
You will also need to change this line:

```<code>NoOfNames = Application.CountA(Range("A:A")) - 1
</code>```

I would suggest adding a function to convert numbers to letters:
Function to convert column number to letter?

```<code>Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function
</code>```

Your line should change to:

```<code>NoOfNames = Application.CountA(Range(Col_Letter(lRet) & ":" & Col_Letter(lRet))) - 1
</code>```

Title: Variable Column based on Date

Body:
VBA noobie here.

I have a spreadsheet with a list of cashiers vertically and each day of the month horizontally. i.e:

11/1/2017    11/2/2017    11/13/2017

Jesse

Frank

Jessica

Martin

The rest of the spreadsheet is populated with sales data for each cashier.

I want to randomly select 5 cashiers and display their names and sales data on a separate sheet.

I have code written that will select 5 random names, however I'm looking to make it dynamic so that the user can choose which column to run the macro on (i.e., they can choose which date).

`Sub PickNamesAtRandom()

Dim HowMany As Integer
Dim NoOfNames As Long
Dim RandomNumber As Integer
Dim Names() As String 'Array to store randomly selected names
Dim i As Byte
Dim CellsOut As Long 'Variable to be used when entering names onto worksheet
Dim ArI As Byte 'Variable to increment through array indexes

Application.ScreenUpdating = False

HowMany = Range("C43").Value
CellsOut = 6

ReDim Names(1 To HowMany) 'Set the array size to how many names required
NoOfNames = Application.CountA(Range("A:A")) - 1 ' Find how many names in the list
i = 1

Do While i <= HowMany
RandomNo:
    RandomNumber = Application.RandBetween(2, NoOfNames + 1)
    'Check to see if the name has already been picked
    For ArI = LBound(Names) To UBound(Names)
        If Names(ArI) = Cells(RandomNumber, 1).Value Then
            GoTo RandomNo
        End If
    Next ArI
    Names(i) = Cells(RandomNumber, 1).Value ' Assign random name to the array
    i = i + 1
Loop

'Loop through the array and enter names onto the worksheet
For ArI = LBound(Names) To UBound(Names)

    Cells(CellsOut, 4) = Names(ArI)
    CellsOut = CellsOut + 1

Next ArI

Application.ScreenUpdating = True

End Sub`

Any help is appreciated!

Body:
You could use an InputBox to get which column the user wants to use.

Dim lRet As Long
lRet = clng(Inputbox("Select column"))

You can then use that variable later in your code. Change where you have this:

Cells(RandomNumber, 1).Value

To this:

Cells(RandomNumber, lRet).Value

Edit:
You will also need to change this line:

NoOfNames = Application.CountA(Range("A:A")) - 1

I would suggest adding a function to convert numbers to letters:
Function to convert column number to letter?

Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function

Your line should change to:

NoOfNames = Application.CountA(Range(Col_Letter(lRet) & ":" & Col_Letter(lRet))) - 1


问:
Single Quote Params vs No Quote Params?
This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params:

```<code>{
    'name': 'Teddy',
    'last': 'Monster'
}
</code>```

But then I also see the more common, no quote params:

```<code>{
    name: 'Teddy',
    last: 'Monster'
}
</code>```

Is there a reason one would use single quote params?
Is it faster to parse?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size.

I'll change my mind if I can get a straight answer :)

答:
Single quoting allow you to use any valid string, including reserved keywords or characters than would be invalid in an identifier

Example:

```<code>{
  'return' : 'ok',
  'with-hyphen' : '123'
}
</code>```

Title: Single Quote Params vs No Quote Params?

Body:
This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params:

{
    'name': 'Teddy',
    'last': 'Monster'
}

But then I also see the more common, no quote params:

{
    name: 'Teddy',
    last: 'Monster'
}

Is there a reason one would use single quote params?
Is it faster to parse?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size.

I'll change my mind if I can get a straight answer :)

Body:
Single quoting allow you to use any valid string, including reserved keywords or characters than would be invalid in an identifier

Example:

{
  'return' : 'ok',
  'with-hyphen' : '123'
}


问:
How to print specific date and time with getters and setters
UPDATED: I never solved my issue with outputting the date in the specific format  needed but the rest of the program works. After messing with the time.format class I did find several different methods of outputting the date in different formats and I was able to get all of them to work with the exception of the last one in the list that is supposed to be a part of the time.format class but unfortunately I was never able to figure out how to implement it. However, this is a good (in my opinion) example of a simple program to calculate interest. I've read a lot of criticisms about getters and setters but they seemed to work just fine for this program. Please note that I am still learning Java and programming as a whole.</p>

```<code>package accountproject;

// two imports needed for date and time
import java.time.format.*;
import java.time.*;
// import standard exception error text
import java.text.ParseException;
// import EVERYTHING!
import java.util.*;

public class Account {

private static int id = 0;
private static double balance = 0;
private static double annualInterestRate = 0;
private static ZonedDateTime dateCreated;
private static double MonthlyInterestRate = annualInterestRate/12;

public Account()
{
    // empty constructor
}

public Account(int id, double balance, double annualInterestRate, ZonedDateTime dateCreated) {
    super();
    Account.id = 0;
    Account.balance = 0;
    Account.annualInterestRate = 4.5;
}

public int getId() {
    return id;
}

public void setId(int id) {
    Account.id = id;
}

public static double getBalance(double d) {
    return balance;
}

public void setBalance(double balance) {
    Account.balance = balance;
}

public double getAnnualInterestRate() {
    return annualInterestRate;
}

public void setAnnualInterestRate(double annualInterestRate) {
    Account.annualInterestRate = annualInterestRate;
}

public static ZonedDateTime ConvertStringToDate(String dateNow) {
    try
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    ZonedDateTime date = ZonedDateTime.parse(dateNow, formatter);

    return date;
}
 catch (DateTimeParseException e)
{
    System.out.println(e);
}
    ZonedDateTime date = null;
    return date;
}

public static double getMonthlyInterestRate(double annualInterestRate2) {

    double temp = annualInterestRate2/12;

    MonthlyInterestRate = temp;

    return MonthlyInterestRate;
}

public static double getMonthlyInterest(double newBalance2) {

    double temp = 100/MonthlyInterestRate;

    double temp2 = newBalance2/temp;

    double temp3 = newBalance2 + temp2;

    newBalance2 = temp3;

    return temp2;
}

public static double deposit(double balance, double deposit) {

    double temp = balance + deposit;

    balance = temp;

    return balance;
}

public static double withdrawal(double balance, double withdrawal) {

    double temp = balance - withdrawal;

    balance = temp;

    return balance;
}

    public static void main(String[] args) throws ParseException {

        // establish a scanner and set example values
        Scanner stdin = new Scanner(System.in);
        id = 1122;
        balance = 20000;
        MonthlyInterestRate = .375;
        double withdrawal = 2500;
        double deposit = 3000;

        double balanceExp = deposit(balance,deposit);
        balanceExp = withdrawal(balanceExp,withdrawal);
        double balanceExp2 = getMonthlyInterest(balanceExp);
        double monthlyInterest = balanceExp2;

        String dateExp = "Fri Oct 06 16:10:59 GMT 2017";
        dateCreated = ConvertStringToDate(dateExp);

        System.out.println("SAMPLE: Account ID " + id + " with a balance of $" + balanceExp
                 + ",\nhas accrued $" + monthlyInterest + " in interest and was opened on "
                + dateCreated + ".");

        System.out.println("Please enter the ID number:");

        // get the id number input
        id = stdin.nextInt();
        stdin.nextLine();

        System.out.println("Typically, the original balance will be $20,000.00.\nPlease enter the balance:");

        // get the starting balance input
        balance = stdin.nextInt();
        stdin.nextLine();

        double newBalance = balance;

        Account.getBalance(20000.00);

        System.out.println("Please enter the deposit amount:");

        // ensure deposit is set to 0 before getting input
        deposit = 0.00;

        // get the deposit amount from input
        deposit = stdin.nextDouble();
        stdin.nextLine();

        newBalance = deposit(balance, deposit);

        System.out.println("Please enter the withdrawal amount:");

        // ensure withdrawal is set to 0 before getting input
        withdrawal = 0.00;

        // get the deposit amount from input
        withdrawal = stdin.nextDouble();
        stdin.nextLine();

        double newBalance2 = withdrawal(newBalance, withdrawal);
        double newBalance3 = getMonthlyInterest(newBalance2);
        double MonthlyInterest = newBalance3;

        print(id, newBalance2, MonthlyInterest, dateCreated);

        stdin.close();
    }

    public static void print(int id, double newBalance2, double MonthlyInterest, ZonedDateTime dateCreated2)
    {
            System.out.println("To verify: the Account ID is " + id + " with a balance of $" + newBalance2
                    + ",\nhas accrued $" + MonthlyInterest + " in interest, and was opened on " + dateCreated2 + ".");
    }
}
</code>```

答:
I never did figure out exactly how to set the formatting to get the date the way my professor wanted but I got 100% so I guess in the end it didn't matter that much. Thanks to Jeremiah Stillings though, I appreciate all the help. This is what I ended up with:</p>

```<code> package accountproject;

 // two imports needed for date and time
 import java.time.format.*;
 import java.time.*;
 // import standard exception error text
 import java.text.ParseException;
 // import EVERYTHING!
 import java.util.*;

 public class Account {

private static int id = 0;
private static double balance = 0;
private static double annualInterestRate = 0;
private static ZonedDateTime dateCreated;
private static double MonthlyInterestRate = annualInterestRate/12;

public Account()
{
    // empty constructor
}

/**
 * @param id
 * @param balance
 * @param annualInterestRate
 * @param dateCreated
 * regular constructors
 */

public Account(int id, double balance, double annualInterestRate, ZonedDateTime dateCreated) {
    super();
    Account.id = 0;
    Account.balance = 0;
    Account.annualInterestRate = 4.5;
}

public int getId() {
    return id;
}

public void setId(int id) {
    Account.id = id;
}

public static double getBalance(double d) {
    return balance;
}

public void setBalance(double balance) {
    Account.balance = balance;
}

public double getAnnualInterestRate() {
    return annualInterestRate;
}

public void setAnnualInterestRate(double annualInterestRate) {
    Account.annualInterestRate = annualInterestRate;
}

public static ZonedDateTime ConvertStringToDate(String dateNow) {
    try
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    ZonedDateTime date = ZonedDateTime.parse(dateNow, formatter);

    return date;
}
 catch (DateTimeParseException e)
{
    System.out.println(e);
}
    ZonedDateTime date = null;
    return date;
}

public static double getMonthlyInterestRate(double annualInterestRate2) {

    double temp = annualInterestRate2/12;

    MonthlyInterestRate = temp;

    return MonthlyInterestRate;
}

public static double getMonthlyInterest(double newBalance2) {

    double temp = 100/MonthlyInterestRate;

    double temp2 = newBalance2/temp;

    double temp3 = newBalance2 + temp2;

    newBalance2 = temp3;

    return temp2;
}

public static double deposit(double balance, double deposit) {

    double temp = balance + deposit;

    balance = temp;

    return balance;
}

public static double withdrawal(double balance, double withdrawal) {

    double temp = balance - withdrawal;

    balance = temp;

    return balance;
}

    public static void main(String[] args) throws ParseException {

        // establish a scanner and set example values
        Scanner stdin = new Scanner(System.in);
        id = 1122;
        balance = 20000;
        MonthlyInterestRate = .375;
        double withdrawal = 2500;
        double deposit = 3000;

        double balanceExp = deposit(balance,deposit);
        balanceExp = withdrawal(balanceExp,withdrawal);
        double balanceExp2 = getMonthlyInterest(balanceExp);
        double monthlyInterest = balanceExp2;

        String dateExp = "Fri Oct 06 16:10:59 GMT 2017";
        dateCreated = ConvertStringToDate(dateExp);

        System.out.println("SAMPLE: Account ID " + id + " with a balance of $" + balanceExp
                 + ",\nhas accrued $" + monthlyInterest + " in interest and was opened on "
                + dateCreated + ".");

        System.out.println("Please enter the ID number:");

        // get the id number input
        id = stdin.nextInt();
        stdin.nextLine();

        System.out.println("Typically, the original balance will be $20,000.00.\nPlease enter the balance:");

        // get the starting balance input
        balance = stdin.nextInt();
        stdin.nextLine();

        double newBalance = balance;

        Account.getBalance(20000.00);

        System.out.println("Please enter the deposit amount:");

        // ensure deposit is set to 0 before getting input
        deposit = 0.00;

        // get the deposit amount from input
        deposit = stdin.nextDouble();
        stdin.nextLine();

        newBalance = deposit(balance, deposit);

        System.out.println("Please enter the withdrawal amount:");

        // ensure withdrawal is set to 0 before getting input
        withdrawal = 0.00;

        // get the deposit amount from input
        withdrawal = stdin.nextDouble();
        stdin.nextLine();

        double newBalance2 = withdrawal(newBalance, withdrawal);
        double newBalance3 = getMonthlyInterest(newBalance2);
        double MonthlyInterest = newBalance3;

        print(id, newBalance2, MonthlyInterest, dateCreated);

        stdin.close();
    }

    public static void print(int id, double newBalance2, double MonthlyInterest, ZonedDateTime dateCreated2)
    {
            System.out.println("To verify: the Account ID is " + id + " with a balance of $" + newBalance2
                    + ",\nhas accrued $" + MonthlyInterest + " in interest, and was opened on " + dateCreated2 + ".");
    }
 }
</code>```

Body:
UPDATED: I never solved my issue with outputting the date in the specific format  needed but the rest of the program works. After messing with the time.format class I did find several different methods of outputting the date in different formats and I was able to get all of them to work with the exception of the last one in the list that is supposed to be a part of the time.format class but unfortunately I was never able to figure out how to implement it. However, this is a good (in my opinion) example of a simple program to calculate interest. I've read a lot of criticisms about getters and setters but they seemed to work just fine for this program. Please note that I am still learning Java and programming as a whole.

package accountproject;

// two imports needed for date and time
import java.time.format.*;
import java.time.*;
// import standard exception error text
import java.text.ParseException;
// import EVERYTHING!
import java.util.*;

public class Account {

private static int id = 0;
private static double balance = 0;
private static double annualInterestRate = 0;
private static ZonedDateTime dateCreated;
private static double MonthlyInterestRate = annualInterestRate/12;

public Account()
{
    // empty constructor
}

public Account(int id, double balance, double annualInterestRate, ZonedDateTime dateCreated) {
    super();
    Account.id = 0;
    Account.balance = 0;
    Account.annualInterestRate = 4.5;
}

public int getId() {
    return id;
}

public void setId(int id) {
    Account.id = id;
}

public static double getBalance(double d) {
    return balance;
}

public void setBalance(double balance) {
    Account.balance = balance;
}

public double getAnnualInterestRate() {
    return annualInterestRate;
}

public void setAnnualInterestRate(double annualInterestRate) {
    Account.annualInterestRate = annualInterestRate;
}

public static ZonedDateTime ConvertStringToDate(String dateNow) {
    try
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    ZonedDateTime date = ZonedDateTime.parse(dateNow, formatter);

    return date;
}
 catch (DateTimeParseException e)
{
    System.out.println(e);
}
    ZonedDateTime date = null;
    return date;
}

public static double getMonthlyInterestRate(double annualInterestRate2) {

    double temp = annualInterestRate2/12;

    MonthlyInterestRate = temp;

    return MonthlyInterestRate;
}

public static double getMonthlyInterest(double newBalance2) {

    double temp = 100/MonthlyInterestRate;

    double temp2 = newBalance2/temp;

    double temp3 = newBalance2 + temp2;

    newBalance2 = temp3;

    return temp2;
}

public static double deposit(double balance, double deposit) {

    double temp = balance + deposit;

    balance = temp;

    return balance;
}

public static double withdrawal(double balance, double withdrawal) {

    double temp = balance - withdrawal;

    balance = temp;

    return balance;
}

    public static void main(String[] args) throws ParseException {

        // establish a scanner and set example values
        Scanner stdin = new Scanner(System.in);
        id = 1122;
        balance = 20000;
        MonthlyInterestRate = .375;
        double withdrawal = 2500;
        double deposit = 3000;

        double balanceExp = deposit(balance,deposit);
        balanceExp = withdrawal(balanceExp,withdrawal);
        double balanceExp2 = getMonthlyInterest(balanceExp);
        double monthlyInterest = balanceExp2;

        String dateExp = "Fri Oct 06 16:10:59 GMT 2017";
        dateCreated = ConvertStringToDate(dateExp);

        System.out.println("SAMPLE: Account ID " + id + " with a balance of $" + balanceExp
                 + ",\nhas accrued $" + monthlyInterest + " in interest and was opened on "
                + dateCreated + ".");

        System.out.println("Please enter the ID number:");

        // get the id number input
        id = stdin.nextInt();
        stdin.nextLine();

        System.out.println("Typically, the original balance will be $20,000.00.\nPlease enter the balance:");

        // get the starting balance input
        balance = stdin.nextInt();
        stdin.nextLine();

        double newBalance = balance;

        Account.getBalance(20000.00);

        System.out.println("Please enter the deposit amount:");

        // ensure deposit is set to 0 before getting input
        deposit = 0.00;

        // get the deposit amount from input
        deposit = stdin.nextDouble();
        stdin.nextLine();

        newBalance = deposit(balance, deposit);

        System.out.println("Please enter the withdrawal amount:");

        // ensure withdrawal is set to 0 before getting input
        withdrawal = 0.00;

        // get the deposit amount from input
        withdrawal = stdin.nextDouble();
        stdin.nextLine();

        double newBalance2 = withdrawal(newBalance, withdrawal);
        double newBalance3 = getMonthlyInterest(newBalance2);
        double MonthlyInterest = newBalance3;

        print(id, newBalance2, MonthlyInterest, dateCreated);

        stdin.close();
    }

    public static void print(int id, double newBalance2, double MonthlyInterest, ZonedDateTime dateCreated2)
    {
            System.out.println("To verify: the Account ID is " + id + " with a balance of $" + newBalance2
                    + ",\nhas accrued $" + MonthlyInterest + " in interest, and was opened on " + dateCreated2 + ".");
    }
}

Body:
I never did figure out exactly how to set the formatting to get the date the way my professor wanted but I got 100% so I guess in the end it didn't matter that much. Thanks to Jeremiah Stillings though, I appreciate all the help. This is what I ended up with:

 package accountproject;

 // two imports needed for date and time
 import java.time.format.*;
 import java.time.*;
 // import standard exception error text
 import java.text.ParseException;
 // import EVERYTHING!
 import java.util.*;

 public class Account {

private static int id = 0;
private static double balance = 0;
private static double annualInterestRate = 0;
private static ZonedDateTime dateCreated;
private static double MonthlyInterestRate = annualInterestRate/12;

public Account()
{
    // empty constructor
}

/**
 * @param id
 * @param balance
 * @param annualInterestRate
 * @param dateCreated
 * regular constructors
 */

public Account(int id, double balance, double annualInterestRate, ZonedDateTime dateCreated) {
    super();
    Account.id = 0;
    Account.balance = 0;
    Account.annualInterestRate = 4.5;
}

public int getId() {
    return id;
}

public void setId(int id) {
    Account.id = id;
}

public static double getBalance(double d) {
    return balance;
}

public void setBalance(double balance) {
    Account.balance = balance;
}

public double getAnnualInterestRate() {
    return annualInterestRate;
}

public void setAnnualInterestRate(double annualInterestRate) {
    Account.annualInterestRate = annualInterestRate;
}

public static ZonedDateTime ConvertStringToDate(String dateNow) {
    try
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    ZonedDateTime date = ZonedDateTime.parse(dateNow, formatter);

    return date;
}
 catch (DateTimeParseException e)
{
    System.out.println(e);
}
    ZonedDateTime date = null;
    return date;
}

public static double getMonthlyInterestRate(double annualInterestRate2) {

    double temp = annualInterestRate2/12;

    MonthlyInterestRate = temp;

    return MonthlyInterestRate;
}

public static double getMonthlyInterest(double newBalance2) {

    double temp = 100/MonthlyInterestRate;

    double temp2 = newBalance2/temp;

    double temp3 = newBalance2 + temp2;

    newBalance2 = temp3;

    return temp2;
}

public static double deposit(double balance, double deposit) {

    double temp = balance + deposit;

    balance = temp;

    return balance;
}

public static double withdrawal(double balance, double withdrawal) {

    double temp = balance - withdrawal;

    balance = temp;

    return balance;
}

    public static void main(String[] args) throws ParseException {

        // establish a scanner and set example values
        Scanner stdin = new Scanner(System.in);
        id = 1122;
        balance = 20000;
        MonthlyInterestRate = .375;
        double withdrawal = 2500;
        double deposit = 3000;

        double balanceExp = deposit(balance,deposit);
        balanceExp = withdrawal(balanceExp,withdrawal);
        double balanceExp2 = getMonthlyInterest(balanceExp);
        double monthlyInterest = balanceExp2;

        String dateExp = "Fri Oct 06 16:10:59 GMT 2017";
        dateCreated = ConvertStringToDate(dateExp);

        System.out.println("SAMPLE: Account ID " + id + " with a balance of $" + balanceExp
                 + ",\nhas accrued $" + monthlyInterest + " in interest and was opened on "
                + dateCreated + ".");

        System.out.println("Please enter the ID number:");

        // get the id number input
        id = stdin.nextInt();
        stdin.nextLine();

        System.out.println("Typically, the original balance will be $20,000.00.\nPlease enter the balance:");

        // get the starting balance input
        balance = stdin.nextInt();
        stdin.nextLine();

        double newBalance = balance;

        Account.getBalance(20000.00);

        System.out.println("Please enter the deposit amount:");

        // ensure deposit is set to 0 before getting input
        deposit = 0.00;

        // get the deposit amount from input
        deposit = stdin.nextDouble();
        stdin.nextLine();

        newBalance = deposit(balance, deposit);

        System.out.println("Please enter the withdrawal amount:");

        // ensure withdrawal is set to 0 before getting input
        withdrawal = 0.00;

        // get the deposit amount from input
        withdrawal = stdin.nextDouble();
        stdin.nextLine();

        double newBalance2 = withdrawal(newBalance, withdrawal);
        double newBalance3 = getMonthlyInterest(newBalance2);
        double MonthlyInterest = newBalance3;

        print(id, newBalance2, MonthlyInterest, dateCreated);

        stdin.close();
    }

    public static void print(int id, double newBalance2, double MonthlyInterest, ZonedDateTime dateCreated2)
    {
            System.out.println("To verify: the Account ID is " + id + " with a balance of $" + newBalance2
                    + ",\nhas accrued $" + MonthlyInterest + " in interest, and was opened on " + dateCreated2 + ".");
    }
 }


问:
Why does the Spring application save logs in two places?
When the application is started (spring-boot), the application saves the logs from the console in two places. How to change it?

This is a multi-module application, and this is the configuration of one of the modules.

pom.xml:

```<code>...
<properties>
    <logs.path>${basedir}/logs</logs.path>
</properties>
...
</code>```

application.yml:

```<code>...
logging.path: @logs.path@
...
</code>```

logback.xml:

```<code><configuration>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <charset>utf-8</charset>
        <pattern>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) %magenta([%thread]) %logger{36}.%M: %msg%n
            </pattern>
        </pattern>
    </encoder>
</appender>

<appender name="CONSOLE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/console.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/archived/console/console.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>90</maxHistory>
    </rollingPolicy>
    <encoder>
        <charset>utf-8</charset>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36}.%M: %msg%n</pattern>
    </encoder>
</appender>

<root level="info">
    <appender-ref ref="CONSOLE"/>
    <appender-ref ref="CONSOLE_FILE"/>
</root>

</configuration>
</code>```

When I run the application logs are saved in the following locations:

modules/LOG_PATH_IS_UNDEFINED/console.log

and

modules/singleModule/logs/console.log

How to fix it.

答:
I added the  tag, where I specified the application.yml file. It helped:

```<code><configuration>

<property resource="application.yml" />

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <charset>utf-8</charset>
        <pattern>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) %magenta([%thread]) %logger{36}.%M: %msg%n
            </pattern>
        </pattern>
    </encoder>
</appender>

<appender name="CONSOLE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${logging.path}/console.log</file>
...
</code>```

The application.yml and logback.xml files are located in the resources folder.

Body:
When the application is started (spring-boot), the application saves the logs from the console in two places. How to change it?

This is a multi-module application, and this is the configuration of one of the modules.

pom.xml:

...
<properties>
    <logs.path>${basedir}/logs</logs.path>
</properties>
...

application.yml:

...
logging.path: @logs.path@
...

logback.xml:

<configuration>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <charset>utf-8</charset>
        <pattern>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) %magenta([%thread]) %logger{36}.%M: %msg%n
            </pattern>
        </pattern>
    </encoder>
</appender>

<appender name="CONSOLE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/console.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/archived/console/console.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>90</maxHistory>
    </rollingPolicy>
    <encoder>
        <charset>utf-8</charset>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36}.%M: %msg%n</pattern>
    </encoder>
</appender>

<root level="info">
    <appender-ref ref="CONSOLE"/>
    <appender-ref ref="CONSOLE_FILE"/>
</root>

</configuration>

When I run the application logs are saved in the following locations:

modules/LOG_PATH_IS_UNDEFINED/console.log

and

modules/singleModule/logs/console.log

How to fix it.

Body:
I added the  tag, where I specified the application.yml file. It helped:

<configuration>

<property resource="application.yml" />

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <charset>utf-8</charset>
        <pattern>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) %magenta([%thread]) %logger{36}.%M: %msg%n
            </pattern>
        </pattern>
    </encoder>
</appender>

<appender name="CONSOLE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${logging.path}/console.log</file>
...

The application.yml and logback.xml files are located in the resources folder.