问:
Gmail SMTP Error With PHP Mailer
I know this question has been asked a lot and I've read through most of them.

I'm getting this error when trying to use my Gmail account to send email from PHP using PHP Mailer and WAMP Server.

It was working till yesterday without any problems (since about 3 months).

I have not changed any code in the mailer helper function.

php-openssl.dll is enabled in my wamp settings.

Tried with ssl & 465, Doesn't connect.

I have "Allow less secured apps" turned on in my google settings.

I've tried using gethostbyname(). it doesn't work.

It is working with my organisation's email server, which doesn't use any security.

This is my phpmailer function code. All the settings are being retrieved from the database. As it is a multi user application.

```<code>// Email Settings
    $from=$details->from;
    $mailer=$details->mailer;
    $subject=$details->subject;

    $mail = new PHPMailer(true);                                // Passing `true` enables exceptions
    try {
        //Server settings
        $mail->SMTPDebug = $settings->debug;                    // Enable verbose debug output
        $mail->isSMTP();                                        // Set mailer to use SMTP
        $mail->Host = $settings->host;          // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                                 // Enable SMTP authentication
        $mail->Username = $settings->login;                     // SMTP username
        $mail->Password = $pass;                                // SMTP password
        $mail->SMTPSecure = $settings->security;                // Enable TLS encryption, `ssl` also accepted
        $mail->Port = $settings->port;                          // TCP port to connect to

        //From
        $mail->setFrom($from, $mailer);

        //Recipients
        $mail->addAddress($details->to,$details->recipientName);     // Add a recipient           // Name is optional
        $mail->addReplyTo($from, $mailer);
        foreach($quote->cc as $cc)
        {
            $mail->addCC($cc);
        }
        //Attachments
        foreach($quote->attachments as $file)
        {
            $mail->addAttachment($file);    // Add attachments  // Optional name
        }
        //Content
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body    = $message;
        $mail->AltBody = 'Non-HTML Mail Clients Not Supported, Please View This email in a browser or get a HTML friendly Email Client.';
        $mail->send();
    }
    catch (Exception $e)
    {
        $return=array(1,'Error: '.$mail->ErrorInfo);
    }
return $return;
}
</code>```

The error That I'm getting is

```<code>2017-12-04 07:15:26 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP w9sm23070345pfk.16 - gsmtp<br>
2017-12-04 07:15:26 CLIENT -> SERVER: EHLO projects<br>
2017-12-04 07:15:26 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [49.213.37.11]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8<br>
2017-12-04 07:15:26 CLIENT -> SERVER: STARTTLS<br>
2017-12-04 07:15:27 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS<br>
SMTP Error: Could not connect to SMTP host.<br>
2017-12-04 07:15:27 CLIENT -> SERVER: QUIT<br>
2017-12-04 07:15:27 <br>
2017-12-04 07:15:27 <br>
SMTP Error: Could not connect to SMTP host.<br>
[1,"Error: SMTP Error: Could not connect to SMTP host."]
</code>```

Any help is appreciated.

PS : The settings I'm using are

Host : smtp.gmail.com.

Username and password : I've checked and I can log into my account on gmail web.

Security : tsl

Port : 587.

I doubt if its my code. coz if it was my code, then It would't have worked with my organisation's email server, which is not as sophisticated as gmail.

答:
i see an error like your question, and i solve my problem by:

Enable extentsion ssl from apache

Update the lastest code from PHPMailer

Add some code:

```<code>$mail->SMTPOptions = array(

'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
)
</code>```

);

And it's work!

Title: Gmail SMTP Error With PHP Mailer

Body:
I know this question has been asked a lot and I've read through most of them.

I'm getting this error when trying to use my Gmail account to send email from PHP using PHP Mailer and WAMP Server.

It was working till yesterday without any problems (since about 3 months).

I have not changed any code in the mailer helper function.

php-openssl.dll is enabled in my wamp settings.

Tried with ssl & 465, Doesn't connect.

I have "Allow less secured apps" turned on in my google settings.

I've tried using gethostbyname(). it doesn't work.

It is working with my organisation's email server, which doesn't use any security.

This is my phpmailer function code. All the settings are being retrieved from the database. As it is a multi user application.

// Email Settings
    $from=$details->from;
    $mailer=$details->mailer;
    $subject=$details->subject;

    $mail = new PHPMailer(true);                                // Passing `true` enables exceptions
    try {
        //Server settings
        $mail->SMTPDebug = $settings->debug;                    // Enable verbose debug output
        $mail->isSMTP();                                        // Set mailer to use SMTP
        $mail->Host = $settings->host;          // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                                 // Enable SMTP authentication
        $mail->Username = $settings->login;                     // SMTP username
        $mail->Password = $pass;                                // SMTP password
        $mail->SMTPSecure = $settings->security;                // Enable TLS encryption, `ssl` also accepted
        $mail->Port = $settings->port;                          // TCP port to connect to

        //From
        $mail->setFrom($from, $mailer);

        //Recipients
        $mail->addAddress($details->to,$details->recipientName);     // Add a recipient           // Name is optional
        $mail->addReplyTo($from, $mailer);
        foreach($quote->cc as $cc)
        {
            $mail->addCC($cc);
        }
        //Attachments
        foreach($quote->attachments as $file)
        {
            $mail->addAttachment($file);    // Add attachments  // Optional name
        }
        //Content
        $mail->isHTML(true);                                  // Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body    = $message;
        $mail->AltBody = 'Non-HTML Mail Clients Not Supported, Please View This email in a browser or get a HTML friendly Email Client.';
        $mail->send();
    }
    catch (Exception $e)
    {
        $return=array(1,'Error: '.$mail->ErrorInfo);
    }
return $return;
}

The error That I'm getting is

2017-12-04 07:15:26 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP w9sm23070345pfk.16 - gsmtp

2017-12-04 07:15:26 CLIENT -> SERVER: EHLO projects

2017-12-04 07:15:26 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [49.213.37.11]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8

2017-12-04 07:15:26 CLIENT -> SERVER: STARTTLS

2017-12-04 07:15:27 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS

SMTP Error: Could not connect to SMTP host.

2017-12-04 07:15:27 CLIENT -> SERVER: QUIT

2017-12-04 07:15:27

2017-12-04 07:15:27

SMTP Error: Could not connect to SMTP host.

[1,"Error: SMTP Error: Could not connect to SMTP host."]

Any help is appreciated.

PS : The settings I'm using are

Host : smtp.gmail.com.

Username and password : I've checked and I can log into my account on gmail web.

Security : tsl

Port : 587.

I doubt if its my code. coz if it was my code, then It would't have worked with my organisation's email server, which is not as sophisticated as gmail.

Body:
i see an error like your question, and i solve my problem by:

Enable extentsion ssl from apache

Update the lastest code from PHPMailer

Add some code:

$mail->SMTPOptions = array(

'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
)

);

And it's work!


来源: stackexchange

问:
Force user to log in when making an in app purchase on iphone
There are many reports of children being able to make in app purchases due to the fact that there is a 15 minute window of opportunity after logging into itunes where a user does not have to log into itunes again.  For instance, a parent downloads an application and then hands the phone to their child.  The child then has 15minutes to make in-app-purchases without having to enter a password.  And yes, I know there are parental control settings that can be set so that no in-app-purchases can be made.  But lets face it, most people are not involved enough to know about this.(Lets please not argue about how parents should be more involved, we all know they should be)  The real questions is:

Is there a way to force the iTunes login?  Or force a log out before running any in app purchase commands?

答: You could require that your app be in the foreground for at least 15 minutes before you allow in-app purchases. That would make it highly unlikely for the situation you describe to occur, with the major downside of making things much harder for your legitimate customers.</p>

ContentLicense: CC BY-SA 2.5


问:
Datatable Enable onclick on a specific column
I have a datatable and I want the 2nd column to be the only clickable column.
Here is a picture of the design.

I intended the Reference ID column (2ndcolumn) to be the one to be clickable in Javascript form please.
When clicked it will get the data from the column just that.

My table is just the usual

.
I also want it to be dynamic so when I have to insert an array from my database the click for the 2nd column will still work.

答:
Do something like this </p>

```<code>$(document).on("click","#dataTbl td:nth-child(2)",function(){
        alert($(this).text());
});
</code>```

<p>Jsfiddle example (click 2nd column) : https://jsfiddle.net/synz/zLykna0p/ </p>

ContentLicense: CC BY-SA 3.0

Body:
Do something like this

$(document).on("click","#dataTbl td:nth-child(2)",function(){
        alert($(this).text());
});

Jsfiddle example (click 2nd column) : https://jsfiddle.net/synz/zLykna0p/


问:
Android equivalence of iOS ActionSheet
What is the Android equivalence of the UIActionSheet in the iOS SDK? I am working on a React-Native project and need to maintain the use of native controls where possible. I have not come across an npm package or other that makes use of the respective plartform 'actionsheet'. They all seem to use native actionsheet in iOS, and a javascript mock of the iOS actionsheet for Android (which makes it non-native on Android). If I can know what android shows where iOS shows an actionsheet then I can make use of the RN Android component for android and actionsheet for iOS. I hope this is a clear question.</p>

答:
We use BottomSheetDialog to do the same work in Android. Not exactly the same and may require a bit more code to write compared to iOS. But the end result is similar.

References:

https://developer.android.com/reference/android/support/design/widget/BottomSheetDialog.html
https://medium.com/glucosio-project/15fb8d140295

Title: Android equivalence of iOS ActionSheet


问:
iOS - awakeFromNib of UITableViewCell gets called when an NSNotification is received
NSNotification observers are added when awakeFromNib is called in my UITableViewCell. Then, I am removing the observers when removeFromSuperView is called.

```<code>- (void)awakeFromNib
{
    [super awakeFromNib];

    [self setNotificationObserver];

    _vHolder.layer.cornerRadius = 10.0f;
    _vHolder.layer.shadowColor = [UIColor blackColor].CGColor;
    _vHolder.layer.shadowRadius = 2.0f;
    _vHolder.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    _vHolder.layer.shadowOpacity = 0.5f;
}

- (void)removeFromSuperview
{
    [super removeFromSuperview];

    [self removeNotificationObserver];
}

- (void)setNotificationObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveESSMQTTMessageNotification:) name:NOTIF_ESSMQTT_MESSAGE_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDeviceStatesMessageNotification:) name:NOTIF_DEVICE_STATES_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDeviceOnOffStateNotification:) name:NOTIF_DEVICE_ON_OFF_STATE_RECEIVED object:nil];
}

- (void)removeNotificationObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_ESSMQTT_MESSAGE_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_DEVICE_STATES_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_DEVICE_ON_OFF_STATE_RECEIVED object:nil];
}
</code>```

I am using NSNotification to refresh states of my buttons and images within this UITableViewCell.

The problem I am facing is, every time an NSNotication is received, the awakeFromNib is called. This will cause the states of my buttons and images to refresh back to its initial states. The strange thing is, I never saw removeFromSuperview getting called before that.

So my questions are:

Why is awakeFromNib getting called when NSNotification is received?

I am just wondering, is adding observer under awakeFromNib the correct thing to do when you want your UITableViewCells to observe NSNotifications? (Well, I've been doing this all the time.)

答:
Because your cell was refreshed content but did not be remove from superview

You had to call removeNotificationObserver when content of cell was refreshed successfully.

I suggest you using protocol instead of notification.

Hope help.

Body:
NSNotification observers are added when awakeFromNib is called in my UITableViewCell. Then, I am removing the observers when removeFromSuperView is called.

- (void)awakeFromNib
{
    [super awakeFromNib];

    [self setNotificationObserver];

    _vHolder.layer.cornerRadius = 10.0f;
    _vHolder.layer.shadowColor = [UIColor blackColor].CGColor;
    _vHolder.layer.shadowRadius = 2.0f;
    _vHolder.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    _vHolder.layer.shadowOpacity = 0.5f;
}

- (void)removeFromSuperview
{
    [super removeFromSuperview];

    [self removeNotificationObserver];
}

- (void)setNotificationObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveESSMQTTMessageNotification:) name:NOTIF_ESSMQTT_MESSAGE_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDeviceStatesMessageNotification:) name:NOTIF_DEVICE_STATES_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveDeviceOnOffStateNotification:) name:NOTIF_DEVICE_ON_OFF_STATE_RECEIVED object:nil];
}

- (void)removeNotificationObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_ESSMQTT_MESSAGE_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_DEVICE_STATES_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIF_DEVICE_ON_OFF_STATE_RECEIVED object:nil];
}

I am using NSNotification to refresh states of my buttons and images within this UITableViewCell.

The problem I am facing is, every time an NSNotication is received, the awakeFromNib is called. This will cause the states of my buttons and images to refresh back to its initial states. The strange thing is, I never saw removeFromSuperview getting called before that.

So my questions are:

Why is awakeFromNib getting called when NSNotification is received?

I am just wondering, is adding observer under awakeFromNib the correct thing to do when you want your UITableViewCells to observe NSNotifications? (Well, I've been doing this all the time.)


问:
Breaking a promise chain (with multiple happy flows and single chain)
This question has been asked before but I wasn't satisfied with solutions like rejecting and handling in catch for breaking for a happy flow. I want to know if we can end up with multiple happy flows in a linear promise chain without rejecting (except in case of errors).

Here's my code sample:

```<code>const goStraight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(steps+2);
  });
};

const turnLeft = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

const turnRight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

goStraight(0)
.then((total_steps_taken) => {
  if (total_steps_taken % 2 === 0)
    return turnLeft(total_steps_taken);
  else
    return null; // This is where I want to break the chain
})
.then((total_steps_taken) => {
  return turnRight(total_steps_taken);
}).then((total_steps_taken) => {
  console.log("Finished with Total Steps : "+total_steps_taken);
})
</code>```

In the case that I start with goStraight(1) the code would flow in the else condition and this is when I want to break the chain.

Just want to know if it can be done without creating branches or using promise rejection.

答:
If you don't want to continue at any point when total steps taken is odd then you can wrap all your functions in a checks if the total steps is not an odd number:</p>

```<code>const checkNotOdd =
  fn                =>
  total_steps_taken =>
    (total_steps_taken%2===0)
      ? Promise.reject("no odd number of steps")
      : fn(total_steps_taken)

checkNotOdd(goStraight)(0)
.then(
  //not checking here, would otherwise reject
  turnLeft
  // checkNotOdd(turnLeft)
)
.then((total_steps_taken) =>
  checkNotOdd(turnRight)
).then(
    total_steps_taken => console.log("Finished with Total Steps : "+total_steps_taken),
    err => console.warn("Failed with:",err)
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This question has been asked before but I wasn't satisfied with solutions like rejecting and handling in catch for breaking for a happy flow. I want to know if we can end up with multiple happy flows in a linear promise chain without rejecting (except in case of errors).

Here's my code sample:

const goStraight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(steps+2);
  });
};

const turnLeft = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

const turnRight = (steps) => {
  return new Promise ((resolve, reject) => {
    resolve(++steps);
  });
};

goStraight(0)
.then((total_steps_taken) => {
  if (total_steps_taken % 2 === 0)
    return turnLeft(total_steps_taken);
  else
    return null; // This is where I want to break the chain
})
.then((total_steps_taken) => {
  return turnRight(total_steps_taken);
}).then((total_steps_taken) => {
  console.log("Finished with Total Steps : "+total_steps_taken);
})

In the case that I start with goStraight(1) the code would flow in the else condition and this is when I want to break the chain.

Just want to know if it can be done without creating branches or using promise rejection.

Body:
If you don't want to continue at any point when total steps taken is odd then you can wrap all your functions in a checks if the total steps is not an odd number:

const checkNotOdd =
  fn                =>
  total_steps_taken =>
    (total_steps_taken%2===0)
      ? Promise.reject("no odd number of steps")
      : fn(total_steps_taken)

checkNotOdd(goStraight)(0)
.then(
  //not checking here, would otherwise reject
  turnLeft
  // checkNotOdd(turnLeft)
)
.then((total_steps_taken) =>
  checkNotOdd(turnRight)
).then(
    total_steps_taken => console.log("Finished with Total Steps : "+total_steps_taken),
    err => console.warn("Failed with:",err)
)


问:
NetSuite Advanced PDF - Transaction footer print at bottom?
Does anyone know of a way to force the transaction footer (ie. totals) to print at the bottom of the page using NetSuite's Advanced PDF templates.

NetSuite uses BFO library out of the box.

Cheers

Steve

答:
You can easily add content to the bottom of every page using a BFO "macro"

```<code><pdf>

  <head>
    <macrolist>
      <macro id="footer">
        <p>This will print at the bottom of every page</p>
      </macro>
    </macrolist>
   </head>

   <body footer="footer" footer-height="20mm">
     Document contents here
   </body>

 </pdf>
</code>```

For more info refer to the BFO User Guide page 16.

However, this won't work if you wanted the footer on only the final page of a possibly multi-page document.

http://bfo.com/support/faq/#17

At the moment we do not have a facility for explicitly assigning a footer or header to the last page in a document when the number of pages is unknown.

Body:
You can easily add content to the bottom of every page using a BFO "macro"

<pdf>

  <head>
    <macrolist>
      <macro id="footer">
        <p>This will print at the bottom of every page</p>
      </macro>
    </macrolist>
   </head>

   <body footer="footer" footer-height="20mm">
     Document contents here
   </body>

 </pdf>

For more info refer to the BFO User Guide page 16.

However, this won't work if you wanted the footer on only the final page of a possibly multi-page document.

http://bfo.com/support/faq/#17

At the moment we do not have a facility for explicitly assigning a footer or header to the last page in a document when the number of pages is unknown.


问:
Liquibase data loading into HSQLDB with a sequence
I'm attempting to load some data into an HSQLDB database using Liquibase 1.9.5. I have a loadData command as follows:

```<code><loadData tableName="LIST_ITEM_TYPE" file="data/global/list_item_type.csv">
    <column name="ID" type="NUMERIC" />
    <column name="NAME" type="STRING" />
    <column name="DESCRIPTION" type="STRING" />
</loadData>
</code>```

In my CSV data file I'm attempting to set the ID value to the next value from an existing sequence:

```<code>id,name,description
next value for SEQ_ITEM_TYPE_ID,Test Name,A test description
</code>```

However, this doesn't work as it generates the following SQL:

```<code>INSERT INTO LIST_ITEM_TYPE (id, description, name) VALUES ('next value for SEQ_ITEM_TYPE_ID', 'A test description', 'Test Name')
</code>```

This is almost correct, except that the single quotes that Liquibase added around the next value for SEQ_ITEM_TYPE_ID cause HSQLDB to give the following error:

```<code>java.sql.SQLException: data exception: invalid character value for cast
</code>```

If I remove the sinqle quotes and run that SQL manually, it works as expected.

So, my question is, how do I use the Liquibase loadData command pulling data from a CSV file while populating one of the columns from a sequence?

答: With liquibase 2.0 you may have more options.  It may no longer quote the id value if it is defined as number, and/or you can extend the loadData change class to include the SQL.</p>

Body:
I'm attempting to load some data into an HSQLDB database using Liquibase 1.9.5. I have a loadData command as follows:

<loadData tableName="LIST_ITEM_TYPE" file="data/global/list_item_type.csv">
    <column name="ID" type="NUMERIC" />
    <column name="NAME" type="STRING" />
    <column name="DESCRIPTION" type="STRING" />
</loadData>

In my CSV data file I'm attempting to set the ID value to the next value from an existing sequence:

id,name,description
next value for SEQ_ITEM_TYPE_ID,Test Name,A test description

However, this doesn't work as it generates the following SQL:

INSERT INTO LIST_ITEM_TYPE (id, description, name) VALUES ('next value for SEQ_ITEM_TYPE_ID', 'A test description', 'Test Name')

This is almost correct, except that the single quotes that Liquibase added around the next value for SEQ_ITEM_TYPE_ID cause HSQLDB to give the following error:

java.sql.SQLException: data exception: invalid character value for cast

If I remove the sinqle quotes and run that SQL manually, it works as expected.

So, my question is, how do I use the Liquibase loadData command pulling data from a CSV file while populating one of the columns from a sequence?


问:
Why does this if true condition in js doesn't work
 I'm trying to display play or pause button when a user clicks on it. I know I can actually compare those links but I think using a variable would be easier to see?
 Thanks.

 `

```<code><!DOCTYPE html>
<html>
<head>
    <title>ch6</title>
</head>
<body>
    <h1>List</h1>
    <h2>audio note</h2>
    <p>Enter note name</p>
    <input type="text" >
<br>
    <img id="pic" onclick="click()" src="http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png" alt="record" style="width:50px;height:60px;">
<script type="text/javascript">
    function click(){
        var butt = true;
        if(butt === true)
        {
            document.getElementById("pic").src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
            butt = false;

        }
        else
        {
            document.getElementById("pic").src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
            butt = true;
        }
    }

</script>

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

`

 I hope to click to change the image.

 The image doesn't change when I click it.

答:
Try use this code:  </p>

```<code>    <img id="pic" src="http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png" alt="record" style="width:50px;height:60px;">
    <script type="text/javascript">
    var butt = true;
    var img = document.getElementById('pic');
    img.addEventListener('click', click);

    function click(e){
        if(butt === true)
        {
            e.target.src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
            butt = false;

        }
        else
        {
            e.target.src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
            butt = true;
        }
    }
</code>```

Body:
 I'm trying to display play or pause button when a user clicks on it. I know I can actually compare those links but I think using a variable would be easier to see?
 Thanks.

 `

<!DOCTYPE html>

    <title>ch6</title>

List

audio note

Enter note name

    <input type="text" >

`

 I hope to click to change the image.

 The image doesn't change when I click it.

Body:
Try use this code:

    <img id="pic" src="http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png" alt="record" style="width:50px;height:60px;">
    <script type="text/javascript">
    var butt = true;
    var img = document.getElementById('pic');
    img.addEventListener('click', click);

    function click(e){
        if(butt === true)
        {
            e.target.src = "https://www.shareicon.net/download/2017/02/07/878546_media_512x512.png";
            butt = false;

        }
        else
        {
            e.target.src = "http://www.clker.com/cliparts/d/b/c/f/13652249372108434179Record%20Button%20Microphone.svg.hi.png";
            butt = true;
        }
    }


问:
jQuery UI DatePicker - Change Date Format
I am using the UI DatePicker from jQuery UI as the stand alone picker. I have this code:

```
<p>And the following JS:</p>
<pre class="lang-js prettyprint-override"><code>$('#datepicker').datepicker();
</code>```

When I try to return the value with this code:

var date = $('#datepicker').datepicker('getDate');
```
<p>I am returned this:</p>
```Tue Aug 25 2009 00:00:00 GMT+0100 (BST)```

Which is totally the wrong format. Is there a way I can get it returned in the format DD-MM-YYYY?

答:
My option is given below:

$(document).ready(function () {
  var userLang = navigator.language || navigator.userLanguage;

  var options = $.extend({},
    $.datepicker.regional["ja"], {
      dateFormat: "yy/mm/dd",
      changeMonth: true,
      changeYear: true,
      highlightWeek: true
    }
  );

  $("#japaneseCalendar").datepicker(options);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ui-datepicker-div {
  font-size: 14px;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">

Japanese JQuery UI Datepicker

<input type="text" id="japaneseCalendar"/>

```

Body:
I am using the UI DatePicker from jQuery UI as the stand alone picker. I have this code:

And the following JS:

$('#datepicker').datepicker();

When I try to return the value with this code:

var date = $('#datepicker').datepicker('getDate');

I am returned this:

Tue Aug 25 2009 00:00:00 GMT+0100 (BST)

Which is totally the wrong format. Is there a way I can get it returned in the format DD-MM-YYYY?

Body:
My option is given below:

$(document).ready(function () {
  var userLang = navigator.language || navigator.userLanguage;

  var options = $.extend({},
    $.datepicker.regional["ja"], {
      dateFormat: "yy/mm/dd",
      changeMonth: true,
      changeYear: true,
      highlightWeek: true
    }
  );

  $("#japaneseCalendar").datepicker(options);
});

#ui-datepicker-div {
  font-size: 14px;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
</head>
<body>
<h3>Japanese JQuery UI Datepicker</h3>
<input type="text" id="japaneseCalendar"/>

</body>
</html>


问:
how to implement breadcrumbs in angular components
i am trying to implement breadcrumb in angular 1.6 using components.
i have around 10 components inside a view(container component) which have different links and one main component which actually displays the data (say a word document) rest are all links to recommended documents.

my hierarchy is Home> Search >ShowAllResults > view

and i want breadcrumbs like Home > {keywords searched} > {categroy of search} > {doc name} .

my problem is that i cannot use    <bread-crumb></bread-crumb> globally because of my website design. i have to call it on every page.
so what would be the best way to retain this hierarchy so that i get a neat and nice navigations?

My idea is to use localstorage as storage medium and render the data in  <bread-crumb></bread-crumb> . and use $destroy to remove the recent url/state

the issue with this approach is the $destroy will execute first. fetch the data from localstorage and modify breadcrumb, but before that my insertion in localstorage will happen. or i think so. so this mess is causing the breadcrumb to break the formation. also i dont know how to handel browser back

答: after some investigation and research i found https://www.npmjs.com/package/angular-breadcrumbs to be the best solution. its already implemented in the best way.</p>


问:
Extra Space In Results? Python Programming
In my program I have an extra space in between the asterisk and apostrophe in test 1 and test 2 extra space within the plus and apostrophe.  Don't need that extra space and here's my code...help haha!

Test 1:

Expected :'3 4*'

Actual   :'3 4* '

Test 2:

Expected :'3 4* -5+'

Actual   :'3 4* -5+ '

```<code>    def empty_case(self, mt_node, inp):

    if (inp is None):
        return ''
    else:
        return inp

def non_empty_case(self, data_node, inp):

    if (inp is None):
        inp = ""

    if (data_node.is_leaf()):
        return inp + (str(data_node.get_data()) + " ")

    inp = data_node.get_left().execute(self, inp)
    inp = data_node.get_right().execute(self, inp)

    return (inp[:-1] + str(data_node.get_data()) + " ")
</code>```

答:
You appear to end on a call to

```<code>empty_case
</code>```

where

```<code>inp is None
</code>```

So, the whitespace ' ' is appended to the end of a string you grew by parsing a tree.

I have not seen enough of your code to tell you how to fix that.
You might want to end on a non_empty_case where inp is None, instead.

Body:
In my program I have an extra space in between the asterisk and apostrophe in test 1 and test 2 extra space within the plus and apostrophe.  Don't need that extra space and here's my code...help haha!

Test 1:

Expected :'3 4*'

Actual   :'3 4* '

Test 2:

Expected :'3 4* -5+'

Actual   :'3 4* -5+ '

    def empty_case(self, mt_node, inp):

    if (inp is None):
        return ''
    else:
        return inp

def non_empty_case(self, data_node, inp):

    if (inp is None):
        inp = ""

    if (data_node.is_leaf()):
        return inp + (str(data_node.get_data()) + " ")

    inp = data_node.get_left().execute(self, inp)
    inp = data_node.get_right().execute(self, inp)

    return (inp[:-1] + str(data_node.get_data()) + " ")

Body:
You appear to end on a call to

empty_case

where

inp is None

So, the whitespace ' ' is appended to the end of a string you grew by parsing a tree.

I have not seen enough of your code to tell you how to fix that.
You might want to end on a non_empty_case where inp is None, instead.


问:
adding two values using react native and display the result
I'm developing simple calculator using react native, just for addition of two numbers. How can I store values to variable and display them using TextInput? And how to add those variables?

答:
Here you go ...</p>

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

    <script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
    <script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

  </head>
  <body>
  <div id="root"></div>
    <script type="text/babel">
        class Calculator extends React.Component{
            constructor(props){
                super(props);
                this.state = {
                    number1 : 0,
                    number2 : 0,
                    result : 0
                }
            }

            doAction = () => {
                this.setState({result : parseInt(this.state.number1) + parseInt(this.state.number2) });
            }

            render(){
                return(
                <div>
                <input type='number' onChange={(event)=>this.setState({number1:event.target.value})}/>
                <input type='number' onChange={(event)=>this.setState({number2:event.target.value})}/>
                <input type="button" onClick={this.doAction} value="Add"/>
                <input type='text' value={this.state.result} readonly/>
                </div>

                )
            }
        }
    React.render(
        <Calculator/>,
        document.getElementById('root')
    )
    </script>
  </body>
  </html>
</code>```

Body:
Here you go ...

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

    <script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
    <script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

  </head>
  <body>
  <div id="root"></div>
    <script type="text/babel">
        class Calculator extends React.Component{
            constructor(props){
                super(props);
                this.state = {
                    number1 : 0,
                    number2 : 0,
                    result : 0
                }
            }

            doAction = () => {
                this.setState({result : parseInt(this.state.number1) + parseInt(this.state.number2) });
            }

            render(){
                return(
                <div>
                <input type='number' onChange={(event)=>this.setState({number1:event.target.value})}/>
                <input type='number' onChange={(event)=>this.setState({number2:event.target.value})}/>
                <input type="button" onClick={this.doAction} value="Add"/>
                <input type='text' value={this.state.result} readonly/>
                </div>

                )
            }
        }
    React.render(
        <Calculator/>,
        document.getElementById('root')
    )
    </script>
  </body>
  </html>


问:
save html table in mysql
Have a website about financial planning. A user can input different values and cell colors in the HTML table. Thus, the HTML tables must be maintained exactly. How do I save the entire HTML table (with values and colors) in MySQL database using db? I don't know PHP, but I'm a beginner in JavaScript and Python. I know there must be a table field of type BLOB, but what do I put in the HTML file. What do I put in SQL?</p>

答:
It's not good to save entire html table to the database since you may have to do calculations on each cell values.

Instead values can be stored in the database

Example for 2 columns (1 for value 1 for color)

Database

```<code>itemName | itemColor
---------|----------
php      | blue
js       | green
</code>```

PHP

Contruct a table and iterate through the mysql result and display each row

```<code>while($node = $result->fetch_assoc()){
    echo "<tr>";
    echo "<td style='background:$node[itemColor]'>$node[itemName]</td>";
    echo "</tr>";
}
</code>```

See this tutorial

Title: save html table in mysql

Body:
It's not good to save entire html table to the database since you may have to do calculations on each cell values.

Instead values can be stored in the database

Example for 2 columns (1 for value 1 for color)

Database

itemName | itemColor
---------|----------
php      | blue
js       | green

PHP

Contruct a table and iterate through the mysql result and display each row

while($node = $result->fetch_assoc()){
    echo "<tr>";
    echo "<td style='background:$node[itemColor]'>$node[itemName]</td>";
    echo "</tr>";
}

See this tutorial


问:
How to insert characters in between in jquery?
I have this data from the database 12345123412 but in my page I need to display it as 12345-1234-12. Any ideas on how to handle this? I'm trying to do the .split()

答:
Simplified approach...with jquery..

Get 3 substrings then format..

```<code>Var id = 12345123412
Function getId(id){
    Var sub1 =id.substring(0,5);
    Var sub2 =id.substring(5,9);
    Var sub3 =id.substring(9,11);
    Var id = sub1 +"-"+sub2+"-"+sub3;
    Return id;
}

getId();
</code>```

Body:
Simplified approach...with jquery..

Get 3 substrings then format..

Var id = 12345123412
Function getId(id){
    Var sub1 =id.substring(0,5);
    Var sub2 =id.substring(5,9);
    Var sub3 =id.substring(9,11);
    Var id = sub1 +"-"+sub2+"-"+sub3;
    Return id;
}

getId();


问:
Python code reflection and modification
Perhaps I'm not using the proper term, but I'm looking to take a block of Python code (in Python), get the token tree for the code, make some kind of modification, and re-assemble it to Python.

For instance, consider this block of code:

```<code>def x(y):
    b = 2
    if y == b:
        foo(y)
</code>```

I would like to be able to take this and programmatically do this:

```<code>def x(y):
    b = 2
    if y == b:
        bar(y)
</code>```

I can't imagine that there's not a library that does something like this. Thanks in advance.

EDIT

Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate arbitrary code, not code that I'm writing. I'd like to be able to modify code on-the-fly. The project I'm working on is a test app: it uses the Netflix philosophy to try to randomly break the functionality of an app in as many ways as it can, running the test suite each time. When the tests don't fail, there's an indication that there's either a gap in code coverage and/or the code is dead.

答:
I'm going to have to guess about the usecase here, but I'll assume that at a certain point in time you want to switch for 1 function to the other. Doing this can be done relatively easily be using a dictionary filled with functions. For example:

```<code>def foo(x): return x
def bar(b): return x+1
fn = { 'foo': foo, 'bar': bar }

def x(y):
    b = 2
    func = 'foo'
    if y == b:
        fn[func](y)
</code>```

This will let you choose which function you want based simply on the dictionary key. You can do so simply by changing the value of func (for example to 'bar').

Title: Python code reflection and modification

Body:
Perhaps I'm not using the proper term, but I'm looking to take a block of Python code (in Python), get the token tree for the code, make some kind of modification, and re-assemble it to Python.

For instance, consider this block of code:

def x(y):
    b = 2
    if y == b:
        foo(y)

I would like to be able to take this and programmatically do this:

def x(y):
    b = 2
    if y == b:
        bar(y)

I can't imagine that there's not a library that does something like this. Thanks in advance.

EDIT

Perhaps I wasn't entirely clear. I'm looking for a tool to read and manipulate arbitrary code, not code that I'm writing. I'd like to be able to modify code on-the-fly. The project I'm working on is a test app: it uses the Netflix philosophy to try to randomly break the functionality of an app in as many ways as it can, running the test suite each time. When the tests don't fail, there's an indication that there's either a gap in code coverage and/or the code is dead.

Body:
I'm going to have to guess about the usecase here, but I'll assume that at a certain point in time you want to switch for 1 function to the other. Doing this can be done relatively easily be using a dictionary filled with functions. For example:

def foo(x): return x
def bar(b): return x+1
fn = { 'foo': foo, 'bar': bar }

def x(y):
    b = 2
    func = 'foo'
    if y == b:
        fn[func](y)

This will let you choose which function you want based simply on the dictionary key. You can do so simply by changing the value of func (for example to 'bar').


问:
How to complete several character vector formatting steps in a single function?
EDITED

I have a simple list of column names that I would like to change the format of, ideally programmatically. This is a sample of the list:

```<code>    vars_list <- c("tBodyAcc.mean...X", "tBodyAcc.mean...Y", "tBodyAcc.mean...Z",
    "tBodyAcc.std...X", "tBodyAcc.std...Y", "tBodyAcc.std...Z",
    "tGravityAcc.mean...X", "tGravityAcc.mean...Y", "tGravityAcc.mean...Z",
    "tGravityAcc.std...X", "tGravityAcc.std...Y", "tGravityAcc.std...Z",
    "fBodyAcc.mean...X", "fBodyAcc.mean...Y", "fBodyAcc.mean...Z",
    "fBodyAcc.std...X", "fBodyAcc.std...Y", "fBodyAcc.std...Z",
    "fBodyAccJerk.mean...X", "fBodyAccJerk.mean...Y", "fBodyAccJerk.mean...Z",
    "fBodyAccJerk.std...X", "fBodyAccJerk.std...Y", "fBodyAccJerk.std...Z")
</code>```

And this is the result I'm hoping for:

```<code> [3]"Time_Body_Acc_Mean_X"                "Time_Body_Acc_Mean_Y"
 [5] "Time_Body_Acc_Mean_Z"                "Time_Body_Acc_Stddev_X"
 [7] "Time_Body_Acc_Stddev_Y"              "Time_Body_Acc_Stddev_Z"
 [9] "Time_Gravity_Acc_Mean_X"             "Time_Gravity_Acc_Mean_Y"
[11] "Time_Gravity_Acc_Mean_Z"             "Time_Gravity_Acc_Stddev_X"
[13] "Time_Gravity_Acc_Stddev_Y"           "Time_Gravity_Acc_Stddev_Z"
</code>```

...

```<code>[43] "Freq_Body_Acc_Mean_X"                "Freq_Body_Acc_Mean_Y"
[45] "Freq_Body_Acc_Mean_Z"                "Freq_Body_Acc_Stddev_X"
[47] "Freq_Body_Acc_Stddev_Y"              "Freq_Body_Acc_Stddev_Z"
[49] "Freq_Body_Acc_Jerk_Mean_X"           "Freq_Body_Acc_Jerk_Mean_Y"
[51] "Freq_Body_Acc_Jerk_Mean_Z"           "Freq_Body_Acc_Jerk_Stddev_X"
[53] "Freq_Body_Acc_Jerk_Stddev_Y"         "Freq_Body_Acc_Jerk_Stddev_Z"
</code>```

I've put together what feels like a really verbose way of making the changes employing regular expressions.

```<code>vars_list <- unlist(lapply(vars_list, function(x){gsub("^t", "Time", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("^f", "Freq", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("std", "Stddev", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("mean", "Mean", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("\\.+", "", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("\\.", "", x)}))
vars_list <- unlist(lapply(vars_list,
                           function(x){gsub("(?<=[a-z]).{0}(?=[A-Z])",
                                            "_", x, perl = TRUE)}))
</code>```

Is there a way to arrive at the same results more efficiently and elegantly by including two or more formatting steps in a single function call?

答:
One alternative is to write your patterns and replacement in two vectors, then use stringi::stri_replace_all_regex which can do this replacement in a vectorized manner:

```<code># patterns correspond to replacement at the same positions
patterns <- c('^t', '^f', 'std', 'mean', '\\.+', '(?<=[a-z])([A-Z])')
replacement <- c('Time', 'Freq', 'Stddev', 'Mean', '', '_$1')

library(stringi)
stri_replace_all_regex(vars_list, patterns, replacement, vectorize_all = F)
# [1] "Time_Body_Acc_Mean_X"      "Time_Body_Acc_Mean_Y"
# [3] "Time_Body_Acc_Mean_Z"      "Time_Body_Acc_Stddev_X"
# [5] "Time_Body_Acc_Stddev_Y"    "Time_Body_Acc_Stddev_Z"
# [7] "Time_Gravity_Acc_Mean_X"   "Time_Gravity_Acc_Mean_Y"
# [9] "Time_Gravity_Acc_Mean_Z"   "Time_Gravity_Acc_Stddev_X"
#[11] "Time_Gravity_Acc_Stddev_Y" "Time_Gravity_Acc_Stddev_Z"
</code>```

Body:
EDITED

I have a simple list of column names that I would like to change the format of, ideally programmatically. This is a sample of the list:

    vars_list <- c("tBodyAcc.mean...X", "tBodyAcc.mean...Y", "tBodyAcc.mean...Z",
    "tBodyAcc.std...X", "tBodyAcc.std...Y", "tBodyAcc.std...Z",
    "tGravityAcc.mean...X", "tGravityAcc.mean...Y", "tGravityAcc.mean...Z",
    "tGravityAcc.std...X", "tGravityAcc.std...Y", "tGravityAcc.std...Z",
    "fBodyAcc.mean...X", "fBodyAcc.mean...Y", "fBodyAcc.mean...Z",
    "fBodyAcc.std...X", "fBodyAcc.std...Y", "fBodyAcc.std...Z",
    "fBodyAccJerk.mean...X", "fBodyAccJerk.mean...Y", "fBodyAccJerk.mean...Z",
    "fBodyAccJerk.std...X", "fBodyAccJerk.std...Y", "fBodyAccJerk.std...Z")

And this is the result I'm hoping for:

 [3]"Time_Body_Acc_Mean_X"                "Time_Body_Acc_Mean_Y"
 [5] "Time_Body_Acc_Mean_Z"                "Time_Body_Acc_Stddev_X"
 [7] "Time_Body_Acc_Stddev_Y"              "Time_Body_Acc_Stddev_Z"
 [9] "Time_Gravity_Acc_Mean_X"             "Time_Gravity_Acc_Mean_Y"
[11] "Time_Gravity_Acc_Mean_Z"             "Time_Gravity_Acc_Stddev_X"
[13] "Time_Gravity_Acc_Stddev_Y"           "Time_Gravity_Acc_Stddev_Z"

...

[43] "Freq_Body_Acc_Mean_X"                "Freq_Body_Acc_Mean_Y"
[45] "Freq_Body_Acc_Mean_Z"                "Freq_Body_Acc_Stddev_X"
[47] "Freq_Body_Acc_Stddev_Y"              "Freq_Body_Acc_Stddev_Z"
[49] "Freq_Body_Acc_Jerk_Mean_X"           "Freq_Body_Acc_Jerk_Mean_Y"
[51] "Freq_Body_Acc_Jerk_Mean_Z"           "Freq_Body_Acc_Jerk_Stddev_X"
[53] "Freq_Body_Acc_Jerk_Stddev_Y"         "Freq_Body_Acc_Jerk_Stddev_Z"

I've put together what feels like a really verbose way of making the changes employing regular expressions.

vars_list <- unlist(lapply(vars_list, function(x){gsub("^t", "Time", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("^f", "Freq", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("std", "Stddev", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("mean", "Mean", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("\\.+", "", x)}))
vars_list <- unlist(lapply(vars_list, function(x){gsub("\\.", "", x)}))
vars_list <- unlist(lapply(vars_list,
                           function(x){gsub("(?<=[a-z]).{0}(?=[A-Z])",
                                            "_", x, perl = TRUE)}))

Is there a way to arrive at the same results more efficiently and elegantly by including two or more formatting steps in a single function call?

Body:
One alternative is to write your patterns and replacement in two vectors, then use stringi::stri_replace_all_regex which can do this replacement in a vectorized manner:

# patterns correspond to replacement at the same positions
patterns <- c('^t', '^f', 'std', 'mean', '\\.+', '(?<=[a-z])([A-Z])')
replacement <- c('Time', 'Freq', 'Stddev', 'Mean', '', '_$1')

library(stringi)
stri_replace_all_regex(vars_list, patterns, replacement, vectorize_all = F)
# [1] "Time_Body_Acc_Mean_X"      "Time_Body_Acc_Mean_Y"
# [3] "Time_Body_Acc_Mean_Z"      "Time_Body_Acc_Stddev_X"
# [5] "Time_Body_Acc_Stddev_Y"    "Time_Body_Acc_Stddev_Z"
# [7] "Time_Gravity_Acc_Mean_X"   "Time_Gravity_Acc_Mean_Y"
# [9] "Time_Gravity_Acc_Mean_Z"   "Time_Gravity_Acc_Stddev_X"
#[11] "Time_Gravity_Acc_Stddev_Y" "Time_Gravity_Acc_Stddev_Z"


问:
How to set up Azure DNS zone for www.domainname.com without affect mail.domainname.com
I have a domainname and webapp currently which I need to do a set up for the domain to point to my webapp server.
I only need to point to www.domainname.com to my Azure DNS zone and mail.domainname.com point to another email provider.
How can I do this?</p>

答:
I only need to point to www.domainname.com to my Azure DNS zone and
  mail.domainname.com point to another email provider. How can I do
  this?

Azure DNS zone works like the domain name manager, we can delegate your domain name to Azure DNS zone, then we can add A record to map www.domainname.com to your application.

About point mail.domainname.com tp another email provider, we can add mx record in your domain name management page.

Here A similar case about Azure DNS zone and custom domain name, please refer to it.


问:
How to find part of a string in a python array
I have an array with a column of numbers and a column of strings. I need to find the indices that contain a certain part of the string. Example:

```<code>array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])
</code>```

I am in Intro Programming so my instructors told me to use if 'stringpart' in array[index] to get a boolean array to use in our problem solving. What I think should happen:

```<code>input:
'red' in array[:,1]
output:
(true,false,true,false)
</code>```

What actually happens is I get all false. I tested the code outside of functions, and applied it to an array with only the strings and it still gives me false. But I tried it with an one of the full strings 'red crayon' and it said true. This partial string code works for the instructors and other students. Why isn't it working for me?

答:
For a vectorized solution you can use the np.char module:

```<code>a = np.array([['4', 'red crayon'],
              ['2', 'purple people eater'],
              ['6', 'red hammer'],
              ['12', 'green screwdriver']])
np.char.find(a[:, 1], 'red') > -1
# array([ True, False,  True, False], dtype=bool)
</code>```

Body:
I have an array with a column of numbers and a column of strings. I need to find the indices that contain a certain part of the string. Example:

array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

I am in Intro Programming so my instructors told me to use if 'stringpart' in array[index] to get a boolean array to use in our problem solving. What I think should happen:

input:
'red' in array[:,1]
output:
(true,false,true,false)

What actually happens is I get all false. I tested the code outside of functions, and applied it to an array with only the strings and it still gives me false. But I tried it with an one of the full strings 'red crayon' and it said true. This partial string code works for the instructors and other students. Why isn't it working for me?

Body:
For a vectorized solution you can use the np.char module:

a = np.array([['4', 'red crayon'],
              ['2', 'purple people eater'],
              ['6', 'red hammer'],
              ['12', 'green screwdriver']])
np.char.find(a[:, 1], 'red') > -1
# array([ True, False,  True, False], dtype=bool)


问:
objective-c metadataOutputRectOfInterestForRect return {{0, 0}, {0, 0}}
Updated!!!

I'm using metadataOutputRectOfInterestForRect to convert rectangle in order to use AVCaptureMetadataOutput rectOfInterest. But when translate to CGRect, it always return 0.

Here is my code:

```<code>NSError *error;

AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

if (!input) {
    NSLog(@"%@", [error localizedDescription]);
    return NO;
}

_captureSession = [[AVCaptureSession alloc] init];
[_captureSession addInput:input];

_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:_viewPreview.bounds];
[_viewPreview.layer addSublayer:_videoPreviewLayer];
[_viewPreview bringSubviewToFront:_lblGuide];
[_viewPreview bringSubviewToFront:_vFocus];

CGRect visibleMetadataOutputRect = [_videoPreviewLayer metadataOutputRectOfInterestForRect:CGRectMake(0, 0, 100, 100)];
NSLog(@"--- log convert: %@", NSStringFromCGRect(visibleMetadataOutputRect));
NSLog(@"--- log _videoPreviewLayer: %@", NSStringFromCGRect(_videoPreviewLayer.bounds));
NSLog(@"--- log _viewPreview: %@", NSStringFromCGRect(_viewPreview.bounds));

_captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
[_captureSession addOutput:_captureMetadataOutput];

_dispatchQueue = dispatch_queue_create("myQueue", NULL);
[_captureMetadataOutput setMetadataObjectsDelegate:self queue:_dispatchQueue];
[_captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
[_captureMetadataOutput setRectOfInterest:visibleMetadataOutputRect];

[_captureSession startRunning];

return YES;
</code>```

And the NSlog resut:

```<code>[5082:1768978] --- log convert: {{0, 0}, {0, 0}}
[5082:1768978] --- log _videoPreviewLayer: {{0, 0}, {320, 468}}
[5082:1768978] --- log _viewPreview: {{0, 0}, {320, 468}}
</code>```

Please help me to resolve it.

答:
I found a simple solution and it worked for me.

Just move 2 line of code right after [_captureSession startRunning]

```<code>CGRect visibleMetadataOutputRect = [_videoPreviewLayer metadataOutputRectOfInterestForRect:self.vFocus.frame];
    [_captureMetadataOutput setRectOfInterest:visibleMetadataOutputRect];
</code>```

It work well!

Body:
Updated!!!

I'm using metadataOutputRectOfInterestForRect to convert rectangle in order to use AVCaptureMetadataOutput rectOfInterest. But when translate to CGRect, it always return 0.

Here is my code:

NSError *error;

AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

if (!input) {
    NSLog(@"%@", [error localizedDescription]);
    return NO;
}

_captureSession = [[AVCaptureSession alloc] init];
[_captureSession addInput:input];

_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:_viewPreview.bounds];
[_viewPreview.layer addSublayer:_videoPreviewLayer];
[_viewPreview bringSubviewToFront:_lblGuide];
[_viewPreview bringSubviewToFront:_vFocus];

CGRect visibleMetadataOutputRect = [_videoPreviewLayer metadataOutputRectOfInterestForRect:CGRectMake(0, 0, 100, 100)];
NSLog(@"--- log convert: %@", NSStringFromCGRect(visibleMetadataOutputRect));
NSLog(@"--- log _videoPreviewLayer: %@", NSStringFromCGRect(_videoPreviewLayer.bounds));
NSLog(@"--- log _viewPreview: %@", NSStringFromCGRect(_viewPreview.bounds));

_captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
[_captureSession addOutput:_captureMetadataOutput];

_dispatchQueue = dispatch_queue_create("myQueue", NULL);
[_captureMetadataOutput setMetadataObjectsDelegate:self queue:_dispatchQueue];
[_captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
[_captureMetadataOutput setRectOfInterest:visibleMetadataOutputRect];

[_captureSession startRunning];

return YES;

And the NSlog resut:

[5082:1768978] --- log convert: {{0, 0}, {0, 0}}
[5082:1768978] --- log _videoPreviewLayer: {{0, 0}, {320, 468}}
[5082:1768978] --- log _viewPreview: {{0, 0}, {320, 468}}

Please help me to resolve it.

Body:
I found a simple solution and it worked for me.

Just move 2 line of code right after [_captureSession startRunning]

CGRect visibleMetadataOutputRect = [_videoPreviewLayer metadataOutputRectOfInterestForRect:self.vFocus.frame];
    [_captureMetadataOutput setRectOfInterest:visibleMetadataOutputRect];

It work well!


答:
How about this using base R's sub?

```<code>sub("t(\\w+)(Acc)\\.(\\w+)\\.+([XYZ])", "Time_\\1_\\2_\\3_\\4", vars_list);
#[1] "Time_Body_Acc_mean_X"    "Time_Body_Acc_mean_Y"
#[3] "Time_Body_Acc_mean_Z"    "Time_Body_Acc_std_X"
#[5] "Time_Body_Acc_std_Y"     "Time_Body_Acc_std_Z"
#[7] "Time_Gravity_Acc_mean_X" "Time_Gravity_Acc_mean_Y"
#[9] "Time_Gravity_Acc_mean_Z" "Time_Gravity_Acc_std_X"
#[11] "Time_Gravity_Acc_std_Y"  "Time_Gravity_Acc_std_Z"
</code>```

Changing mean to Mean, and std to StdDev requires two additional subs.
Ditto for t to Time and f to Freq.

Title: How to complete several character vector formatting steps in a single function?

Body:
How about this using base R's sub?

sub("t(\\w+)(Acc)\\.(\\w+)\\.+([XYZ])", "Time_\\1_\\2_\\3_\\4", vars_list);
#[1] "Time_Body_Acc_mean_X"    "Time_Body_Acc_mean_Y"
#[3] "Time_Body_Acc_mean_Z"    "Time_Body_Acc_std_X"
#[5] "Time_Body_Acc_std_Y"     "Time_Body_Acc_std_Z"
#[7] "Time_Gravity_Acc_mean_X" "Time_Gravity_Acc_mean_Y"
#[9] "Time_Gravity_Acc_mean_Z" "Time_Gravity_Acc_std_X"
#[11] "Time_Gravity_Acc_std_Y"  "Time_Gravity_Acc_std_Z"

Changing mean to Mean, and std to StdDev requires two additional subs.
Ditto for t to Time and f to Freq.


问:
How to get started in layouting subviews manually?
For testing and practicing I would like to implement a real simple layout manager which just aligns one control next to the other as long as there is space to the right and then goes to next line.

For instance: have a UIView and keep on adding UIButtons with random widths as subviews. one "line" is 40 pixels high. First button is added at (0,0), next one at (120, 0), next one is too wide and will go to (0,40), next one to (80,40) and so on.

The question is not how to do that but which methods of MonoTouch are involved? My guess would be to override LayoutSubViews() and in there implement my logic to align the controls - is that correct? Do I have to call base.LayoutSubViews()?
Do I have to override anything else? It should of course realign as buttons get removed or added and also if the view itself changes in size.
Do I have to touch SizeToFit(), too?

René

答: You should checkout the MonoTouch docs for UIView.  Your guess is right in calling LayoutSubViews to position and align your subviews and you'll most likely end up overriding the Draw method on your view.  I think the TweetStation example does a bit of manual view drawing.  You might want to check that for ideas.</p>


问:
Vue - Passing data from child to parent - Basic emit not working
I have a basic Vue2 component and I am trying to pass data from the child to the parent component using $emit. Note, my-component contains a table where when I click on a row, onRowClick fires successfully, outputting 'foobar' to the console. For some reason, I'm not able to get the parent method to fire on $emit and success isn't being logged to console. Any idea why this is?

```<code>import Vue from 'vue';
import MyComponent from "./components/MyComponent.vue";

window.onload = function () {
   var main = new Vue({
      el: '#app-v2',
      components: { MyComponent },
      methods: {
         onCouponApplied(data) {
            console.log("Success, coupon applied, " + data);
            this.saying = "Sunglasses are " + data; //Sunglasses are cool
         }
      },
      data: {
         contactEditPage: {
            saying: ""
         }
      }
   });
}
</code>```

MyComponent.vue

```<code>export default {
        methods: {
            onRowClick(event){
               this.$emit('applied', 'Cool');
               console.log("foobar");
            }
</code>```

HTML

```<code><div id="app-v2">
    <my-component @applied="onCouponApplied"></my-component>
     {{ saying }} //trying to output: sunglasses are cool
</div>
</code>```

答:
I faced the same problem. I fixed this issue by using $root.

For example in parent Vue component

```<code>mounted(){
    this.$root.$on('event-name',function(value){
        // code
    });
},
</code>```

And child component should be like this:

```<code>this.$root.$emit('event-name',[data]);
</code>```

Hope can help you.

Body:
I have a basic Vue2 component and I am trying to pass data from the child to the parent component using $emit. Note, my-component contains a table where when I click on a row, onRowClick fires successfully, outputting 'foobar' to the console. For some reason, I'm not able to get the parent method to fire on $emit and success isn't being logged to console. Any idea why this is?

import Vue from 'vue';
import MyComponent from "./components/MyComponent.vue";

window.onload = function () {
   var main = new Vue({
      el: '#app-v2',
      components: { MyComponent },
      methods: {
         onCouponApplied(data) {
            console.log("Success, coupon applied, " + data);
            this.saying = "Sunglasses are " + data; //Sunglasses are cool
         }
      },
      data: {
         contactEditPage: {
            saying: ""
         }
      }
   });
}

MyComponent.vue

export default {
        methods: {
            onRowClick(event){
               this.$emit('applied', 'Cool');
               console.log("foobar");
            }

HTML

    <my-component @applied="onCouponApplied"></my-component>
     {{ saying }} //trying to output: sunglasses are cool

Body:
I faced the same problem. I fixed this issue by using $root.

For example in parent Vue component

mounted(){
    this.$root.$on('event-name',function(value){
        // code
    });
},

And child component should be like this:

this.$root.$emit('event-name',[data]);

Hope can help you.


问:
gdb error not in executable format: File format not recognized
I am trying to debug a simple "hello world" C++ program on Ubuntu 16.04 but gdb is not able to recognize the executable file format. However, I am able to successfully run the executable on the command line.
Here is the code

```<code>#include <iostream>
using namespace std;

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}
</code>```

I compile the program file TestProject.cpp using the command

```<code>g++ -g TestProject.cpp -o hello
</code>```

Then to debug, I give the command

```<code>gdb ./hello
</code>```

I get the following error message

```<code>GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
"/home/<home>/./hello": not in executable format: File format not recognized
</code>```

Something seems to be corrupt with the Ubuntu machine. Because I am able to debug the same program on another Ubuntu 16.04 virtual machine.

答:
It is almost certain that ks1322's comment is correct one:

You've installed a 64-bit GCC, so your ./hello is a 64-bit binary (use file ./hello to confirm).

You've installed a 32-bit only GDB, so it doesn't know how to debug x86_64 binaries.

The fix is simple: install 64-bit GDB (which is capable of debugging both 32 and 64-bit binaries), or build hello in 32-bit mode (with g++ -m32 ...).

Body:
I am trying to debug a simple "hello world" C++ program on Ubuntu 16.04 but gdb is not able to recognize the executable file format. However, I am able to successfully run the executable on the command line.
Here is the code

#include <iostream>
using namespace std;

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

I compile the program file TestProject.cpp using the command

g++ -g TestProject.cpp -o hello

Then to debug, I give the command

gdb ./hello

I get the following error message

GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
"/home/<home>/./hello": not in executable format: File format not recognized

Something seems to be corrupt with the Ubuntu machine. Because I am able to debug the same program on another Ubuntu 16.04 virtual machine.


问:
Using the same URL for multiple nested ember routes
I have a case using Ember where I want to make the top level URL available (ie. localhost:4200/demo), and have all the routes underneath also display the same URL (localhost:4200/demo). So the route file, if possible would look something like:

```<code>this.route('demo', function() {
  this.route('one', { path: '/' });
  this.route('submit', { path: '/' });
});
</code>```

I understand that ENV.locationtype can be set for the whole app, but is there a way to conditionally set this for specific URLs underneath a parent URL?

答:
Generally when you end up hitting major snags like this it is because Ember is implicitly trying to tell you that what you are doing isn't a good idea.

Is there a particular reason that you don't want your sub-routes to affect the URL in any way? Could you get by with random values in the URL if your prime purpose is to obfuscate things?

Ember uses the URL to work out what state things should be in in your app. If you don't want to use the routes at all you wouldn't have to, but then at that point you are dealing with a nested hierarchy of components that you have to switch between yourself. Which would in essence be akin to using React without a router ...

Body:
I have a case using Ember where I want to make the top level URL available (ie. localhost:4200/demo), and have all the routes underneath also display the same URL (localhost:4200/demo). So the route file, if possible would look something like:

this.route('demo', function() {
  this.route('one', { path: '/' });
  this.route('submit', { path: '/' });
});

I understand that ENV.locationtype can be set for the whole app, but is there a way to conditionally set this for specific URLs underneath a parent URL?


问:
Direction of calculating multiple Arrays stored values and displaying them
I am trying to write up a program that accepts user input and stores it in arrays Its really complex, I looked around a bit and read the book. I just cannot figure out how to do this. Heres the prompt I have

Modify lab 20 to add copy constructors to petRecord, catRecord, dogRecord and birdRecord.  Use your main file from HW 6 as a starting point for main.  When having the user fill in information for each pet, also include having them choose from cat, dog or bird by entering 1, 2 or 3 on the keyboard.  Store the appropriate object into each array slot (catRecord, dogRecord or birdRecord).  When comparing to see if two pets are the same be sure to check if they are the same type of animal as well as matching data, and ensure that numFeathers matches for birds and hasLongHair matches for cats/dogs.

In addition to the array, have main create an additional pet with information given by the user (as for the five in the array), then copy it to a new object using its’ copy constructor.  Test that this worked by showing that they are equal (the same way you tested if any pets in the array were equal to each other).

In main is where I am having trouble calculating all weights and age of the animals. I have no idea what to do, just some direction is needed.

```<code>public class petRecordMain
{
     public static void main(String[] args)
    {  Scanner in = new Scanner(System.in);
        PetRecord[] petArray = new PetRecord[6];
        DogRecord[] dogArray = new DogRecord[6];
        CatRecord[] catArray = new CatRecord[6];
        BirdRecord[] birdArray = new BirdRecord[6];
        double averageWeight = 0;
        double averageAge = 0;
        int whichPet = 0;
        for(int i = 0; i < petArray.length; i++)
       {
           petArray[i] = new PetRecord();
           dogArray[i] = new DogRecord();
           catArray[i] = new CatRecord();
           birdArray[i] = new BirdRecord();
       }

         for(int i = 0; i < 6; i++)
       {
            System.out.println("Please choose, 1 for Cat, 2 for Dog, 3 for Bird: ");
            whichPet = in.nextInt();
            switch(whichPet)
            {
                case 1:
                    System.out.println("Cat");
                     System.out.println("Enter the name of Pet "+ i + " :  ");//Asks user for input
                     catArray[i].setName(in.next());                   //For five animals, weight, age
                     System.out.println("Enter the weight of Pet "+ i + " : "); //add up then divide by all five weight
                     catArray[i].setWeight(in.nextInt());
                     System.out.println("Enter the age of Pet"+ i + " : ");
                     catArray[i].setAge(in.nextInt());

                    break;

                case 2:
                    System.out.println("Dog");
                        System.out.println("Enter the name of Pet "+ i + " :  ");//Asks user for input
                        dogArray[i].setName(in.next());                   //For five animals, weight, age
                        System.out.println("Enter the weight of Pet "+ i + " : "); //add up then divide by all five weight
                        dogArray[i].setWeight(in.nextInt());
                        System.out.println("Enter the age of Pet"+ i + " : ");
                        dogArray[i].setAge(in.nextInt());

                    break;

                case 3:
                    System.out.println("Bird");
                     System.out.println("Enter the name of Pet "+ i + " :  ");//Asks user for input
                     birdArray[i].setName(in.next());                   //For five animals, weight, age
                     System.out.println("Enter the weight of Pet "+ i + " : "); //add up then divide by all five weight
                     birdArray[i].setWeight(in.nextInt());
                     System.out.println("Enter the age of Pet"+ i + " : ");
                     birdArray[i].setAge(in.nextInt());

                    break;

                    default :
                        System.out.println("Invalid input, try again.");

            }

       }
</code>```

Down below the code is a little messy. I have a for loop which I think I can use to calculate all the weights and ages, but this is where I am now stuck.

```<code>     for(int i = 0; i < 6; i++)
   {
        averageWeight += petArray.getWeight[i]; //How would I calculate all weight?
        //How would I caculate all ages?
        System.out.println("");

   }
   /*
    averageWeight = (petOne.getWeight()+petTwo.getWeight()+petThree.getWeight()+petFour.getWeight()+petFive.getWeight()) /5;
    averageAge = (petOne.getAge()+petTwo.getAge()+petThree.getAge()+petFour.getAge()+petFive.getAge()) /5;

    System.out.println("The average weight of all dogs is: "+averageWeight+" Pounds");
    System.out.println("The average age of all dogs is: "+averageAge+" years old");
    System.out.println("");

    if(petOne.getName().equalsIgnoreCase(petTwo.getName()) && petThree.getName().equalsIgnoreCase(petFour.getName()) && petFour.getName().equalsIgnoreCase(petFive.getName()) )
    {
            System.out.println("All five dogs have the same name.");
    }
    else if(petOne.getWeight() == petTwo.getWeight() && petThree.getWeight() == petFour.getWeight() && petFour.getName() == petFive.getName())
    {
        System.out.println("All five dogs have the same weight");
    }
    else if(petOne.getAge() == petTwo.getAge() && petThree.getAge() == petFour.getAge() && petFour.getAge() == petFive.getAge())
    {
        System.out.println("All five dogs are the same age.");
    }
    //Below check if any pets are the same
    //1
     if(petOne.toString().equals(petTwo.toString()))
    {
        System.out.println(petOne.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petOne.toString().equals(petThree.toString()))
    {
        System.out.println(petOne.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petOne.toString().equals(petFour.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFour.toString()+ "are the same");
    }
    else if(petOne.toString().equals(petFive.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFive.toString()+" are the same");
    }
    //2
        if(petTwo.toString().equals(petOne.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petOne.toString()+" are the sae");
    }
    else if(petTwo.toString().equals(petThree.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFour.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFive.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFive.toString()+" are the same");
    }
    //3
        if(petThree.toString().equals(petOne.toString()))
    {
        System.out.println(petThree.toString()+" and "+petOne.toString()+" are the same");
    }
     else if(petThree.toString().equals(petTwo.toString()))
    {
        System.out.println(petThree.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFour.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFive.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFive.toString()+" are the same");
    }
    //4
        if(petFour.toString().equals(petOne.toString()))
    {
        System.out.println(petFour.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFour.toString().equals(petTwo.toString()))
    {
        System.out.println(petFour.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFour.toString().equals(petThree.toString()))
    {
        System.out.println(petFour.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFour.toString().equals(petFive.toString()))
    {
        System.out.println(petFour.toString()+" and "+petFour.toString()+" are the same");
    }
    //5
        if(petFive.toString().equals(petOne.toString()))
    {
        System.out.println(petFive.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFive.toString().equals(petTwo.toString()))
    {
        System.out.println(petFive.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFive.toString().equals(petThree.toString()))
    {
        System.out.println(petFive.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFive.toString().equals(petFour.toString()))
    {
        System.out.println(petFive.toString()+" and "+petFour.toString()+" are the same");
    }
    //Below caculates which pet is the youngest

        if(petOne.getAge() < petTwo.getAge() && petOne.getAge() < petThree.getAge() && petOne.getAge() < petFour.getAge() && petOne.getAge() < petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the youngest pet.");
    }
    else if(petTwo.getAge() < petOne.getAge() && petTwo.getAge() < petThree.getAge() && petTwo.getAge() < petFour.getAge() && petTwo.getAge() < petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the youngest pet.");
    }
    else if(petThree.getAge() < petOne.getAge() && petThree.getAge() < petTwo.getAge() && petThree.getAge() < petFour.getAge() && petThree.getAge() < petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the youngest pet.");
    }
    else if(petFour.getAge() < petOne.getAge() && petFour.getAge() < petTwo.getAge() && petFour.getAge() < petThree.getAge() && petFour.getAge() < petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the youngest pet.");
    }
    else if(petFive.getAge() < petOne.getAge() && petFive.getAge() < petTwo.getAge() && petFive.getAge() < petThree.getAge() && petFive.getAge() < petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the youngest pet.");
    }
    //Below caculates which pet is the oldest
        if(petOne.getAge() > petTwo.getAge() && petOne.getAge() > petThree.getAge() && petOne.getAge() > petFour.getAge() && petOne.getAge() > petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the oldest pet.");
    }
     else if(petTwo.getAge() > petOne.getAge() && petTwo.getAge() > petThree.getAge() && petTwo.getAge() > petFour.getAge() && petTwo.getAge() > petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the oldest pet.");
    }
     else if(petThree.getAge() > petOne.getAge() && petThree.getAge() > petTwo.getAge() && petThree.getAge() > petFour.getAge() && petThree.getAge() > petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the oldest pet.");
    }
     else if(petFour.getAge() > petOne.getAge() && petFour.getAge() > petTwo.getAge() && petFour.getAge() > petThree.getAge() && petFour.getAge() > petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the oldest pet.");
    }
     else if(petFive.getAge() > petOne.getAge() && petFive.getAge() > petTwo.getAge() && petFive.getAge() > petThree.getAge() && petFive.getAge() > petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the oldest pet.");
    }
    //Below caculates which pet is the smallest
        if(petOne.getWeight() < petTwo.getWeight() && petOne.getWeight() < petThree.getWeight() && petOne.getWeight() < petFour.getWeight() && petOne.getWeight() < petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the smallest pet.");
    }
     else if(petTwo.getWeight() < petOne.getWeight() && petTwo.getWeight() < petThree.getWeight() && petTwo.getWeight() < petFour.getWeight() && petTwo.getWeight() < petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the smallest pet.");
    }
     else if(petThree.getWeight() < petOne.getWeight() && petThree.getWeight() < petTwo.getWeight() && petThree.getWeight() < petFour.getWeight() && petThree.getAge() < petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the smallest pet.");
    }
     else if(petFour.getWeight() < petOne.getWeight() && petFour.getWeight() < petTwo.getWeight() && petFour.getWeight() < petThree.getWeight() && petFour.getWeight() < petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the smallest pet.");
    }
     else  if(petFive.getWeight() < petOne.getWeight() && petFive.getWeight() < petTwo.getWeight() && petFive.getWeight() < petThree.getWeight() && petFive.getWeight() < petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the smallest pet.");
    }
    //Below caculates to see which pet is the largest
        if(petOne.getWeight() > petTwo.getWeight() && petOne.getWeight() > petThree.getWeight() && petOne.getWeight() > petFour.getWeight() && petOne.getWeight() > petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the largest pet.");
    }
     else if(petTwo.getWeight() > petOne.getWeight() && petTwo.getWeight() > petThree.getWeight() && petTwo.getWeight() > petFour.getWeight() && petTwo.getWeight() > petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the largest pet.");
    }
     else if(petThree.getWeight() > petOne.getWeight() && petThree.getWeight() > petTwo.getWeight() && petThree.getWeight() > petFour.getWeight() && petThree.getAge() > petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the largest pet.");
    }
    else if(petFour.getWeight() > petOne.getWeight() && petFour.getWeight() > petTwo.getWeight() && petFour.getWeight() > petThree.getWeight() && petFour.getWeight() > petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the largest pet.");
    }
    else if(petFive.getWeight() > petOne.getWeight() && petFive.getWeight() > petTwo.getWeight() && petFive.getWeight() > petThree.getWeight() && petFive.getWeight() > petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the largest pet.");
    }

   */

</code>```

答:
I believe CatRecord must be inheriting PetRecord, would have clarified this in a comment before answering but unfortunately, StackOverflow won't allow me to comment.Hence if the weight is stored in the PetRecord as all Pets have weight regardless of species and that would make sense. Something like this should work:

```<code>averageWeight += petArray[i].getWeight();
</code>```

Also while initialising, write code on the lines of:

```<code>petarray[i] = new CatRecord();
</code>```

Body:
I am trying to write up a program that accepts user input and stores it in arrays Its really complex, I looked around a bit and read the book. I just cannot figure out how to do this. Heres the prompt I have

Modify lab 20 to add copy constructors to petRecord, catRecord, dogRecord and birdRecord.  Use your main file from HW 6 as a starting point for main.  When having the user fill in information for each pet, also include having them choose from cat, dog or bird by entering 1, 2 or 3 on the keyboard.  Store the appropriate object into each array slot (catRecord, dogRecord or birdRecord).  When comparing to see if two pets are the same be sure to check if they are the same type of animal as well as matching data, and ensure that numFeathers matches for birds and hasLongHair matches for cats/dogs.

In addition to the array, have main create an additional pet with information given by the user (as for the five in the array), then copy it to a new object using its’ copy constructor.  Test that this worked by showing that they are equal (the same way you tested if any pets in the array were equal to each other).

In main is where I am having trouble calculating all weights and age of the animals. I have no idea what to do, just some direction is needed.

public class petRecordMain
{
     public static void main(String[] args)
    {  Scanner in = new Scanner(System.in);
        PetRecord[] petArray = new PetRecord[6];
        DogRecord[] dogArray = new DogRecord[6];
        CatRecord[] catArray = new CatRecord[6];
        BirdRecord[] birdArray = new BirdRecord[6];
        double averageWeight = 0;
        double averageAge = 0;
        int whichPet = 0;
        for(int i = 0; i < petArray.length; i++)
       {
           petArray[i] = new PetRecord();
           dogArray[i] = new DogRecord();
           catArray[i] = new CatRecord();
           birdArray[i] = new BirdRecord();
       }

         for(int i = 0; i < 6; i++)
       {
            System.out.println("Please choose, 1 for Cat, 2 for Dog, 3 for Bird: ");
            whichPet = in.nextInt();
            switch(whichPet)
            {
                case 1:
                    System.out.println("Cat");
                     System.out.println("Enter the name of Pet "+ i + " :  ");//Asks user for input
                     catArray[i].setName(in.next());                   //For five animals, weight, age
                     System.out.println("Enter the weight of Pet "+ i + " : "); //add up then divide by all five weight
                     catArray[i].setWeight(in.nextInt());
                     System.out.println("Enter the age of Pet"+ i + " : ");
                     catArray[i].setAge(in.nextInt());

                    break;

                case 2:
                    System.out.println("Dog");
                        System.out.println("Enter the name of Pet "+ i + " :  ");//Asks user for input
                        dogArray[i].setName(in.next());                   //For five animals, weight, age
                        System.out.println("Enter the weight of Pet "+ i + " : "); //add up then divide by all five weight
                        dogArray[i].setWeight(in.nextInt());
                        System.out.println("Enter the age of Pet"+ i + " : ");
                        dogArray[i].setAge(in.nextInt());

                    break;

                case 3:
                    System.out.println("Bird");
                     System.out.println("Enter the name of Pet "+ i + " :  ");//Asks user for input
                     birdArray[i].setName(in.next());                   //For five animals, weight, age
                     System.out.println("Enter the weight of Pet "+ i + " : "); //add up then divide by all five weight
                     birdArray[i].setWeight(in.nextInt());
                     System.out.println("Enter the age of Pet"+ i + " : ");
                     birdArray[i].setAge(in.nextInt());

                    break;

                    default :
                        System.out.println("Invalid input, try again.");

            }

       }

Down below the code is a little messy. I have a for loop which I think I can use to calculate all the weights and ages, but this is where I am now stuck.

     for(int i = 0; i < 6; i++)
   {
        averageWeight += petArray.getWeight[i]; //How would I calculate all weight?
        //How would I caculate all ages?
        System.out.println("");

   }
   /*
    averageWeight = (petOne.getWeight()+petTwo.getWeight()+petThree.getWeight()+petFour.getWeight()+petFive.getWeight()) /5;
    averageAge = (petOne.getAge()+petTwo.getAge()+petThree.getAge()+petFour.getAge()+petFive.getAge()) /5;

    System.out.println("The average weight of all dogs is: "+averageWeight+" Pounds");
    System.out.println("The average age of all dogs is: "+averageAge+" years old");
    System.out.println("");

    if(petOne.getName().equalsIgnoreCase(petTwo.getName()) && petThree.getName().equalsIgnoreCase(petFour.getName()) && petFour.getName().equalsIgnoreCase(petFive.getName()) )
    {
            System.out.println("All five dogs have the same name.");
    }
    else if(petOne.getWeight() == petTwo.getWeight() && petThree.getWeight() == petFour.getWeight() && petFour.getName() == petFive.getName())
    {
        System.out.println("All five dogs have the same weight");
    }
    else if(petOne.getAge() == petTwo.getAge() && petThree.getAge() == petFour.getAge() && petFour.getAge() == petFive.getAge())
    {
        System.out.println("All five dogs are the same age.");
    }
    //Below check if any pets are the same
    //1
     if(petOne.toString().equals(petTwo.toString()))
    {
        System.out.println(petOne.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petOne.toString().equals(petThree.toString()))
    {
        System.out.println(petOne.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petOne.toString().equals(petFour.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFour.toString()+ "are the same");
    }
    else if(petOne.toString().equals(petFive.toString()))
    {
        System.out.println(petOne.toString()+" and "+petFive.toString()+" are the same");
    }
    //2
        if(petTwo.toString().equals(petOne.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petOne.toString()+" are the sae");
    }
    else if(petTwo.toString().equals(petThree.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFour.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petTwo.toString().equals(petFive.toString()))
    {
        System.out.println(petTwo.toString()+" and "+petFive.toString()+" are the same");
    }
    //3
        if(petThree.toString().equals(petOne.toString()))
    {
        System.out.println(petThree.toString()+" and "+petOne.toString()+" are the same");
    }
     else if(petThree.toString().equals(petTwo.toString()))
    {
        System.out.println(petThree.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFour.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFour.toString()+" are the same");
    }
    else if(petThree.toString().equals(petFive.toString()))
    {
        System.out.println(petThree.toString()+" and "+petFive.toString()+" are the same");
    }
    //4
        if(petFour.toString().equals(petOne.toString()))
    {
        System.out.println(petFour.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFour.toString().equals(petTwo.toString()))
    {
        System.out.println(petFour.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFour.toString().equals(petThree.toString()))
    {
        System.out.println(petFour.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFour.toString().equals(petFive.toString()))
    {
        System.out.println(petFour.toString()+" and "+petFour.toString()+" are the same");
    }
    //5
        if(petFive.toString().equals(petOne.toString()))
    {
        System.out.println(petFive.toString()+" and "+petOne.toString()+" are the same");
    }
    else if(petFive.toString().equals(petTwo.toString()))
    {
        System.out.println(petFive.toString()+" and "+petTwo.toString()+" are the same");
    }
    else if(petFive.toString().equals(petThree.toString()))
    {
        System.out.println(petFive.toString()+" and "+petThree.toString()+" are the same");
    }
    else if(petFive.toString().equals(petFour.toString()))
    {
        System.out.println(petFive.toString()+" and "+petFour.toString()+" are the same");
    }
    //Below caculates which pet is the youngest

        if(petOne.getAge() < petTwo.getAge() && petOne.getAge() < petThree.getAge() && petOne.getAge() < petFour.getAge() && petOne.getAge() < petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the youngest pet.");
    }
    else if(petTwo.getAge() < petOne.getAge() && petTwo.getAge() < petThree.getAge() && petTwo.getAge() < petFour.getAge() && petTwo.getAge() < petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the youngest pet.");
    }
    else if(petThree.getAge() < petOne.getAge() && petThree.getAge() < petTwo.getAge() && petThree.getAge() < petFour.getAge() && petThree.getAge() < petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the youngest pet.");
    }
    else if(petFour.getAge() < petOne.getAge() && petFour.getAge() < petTwo.getAge() && petFour.getAge() < petThree.getAge() && petFour.getAge() < petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the youngest pet.");
    }
    else if(petFive.getAge() < petOne.getAge() && petFive.getAge() < petTwo.getAge() && petFive.getAge() < petThree.getAge() && petFive.getAge() < petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the youngest pet.");
    }
    //Below caculates which pet is the oldest
        if(petOne.getAge() > petTwo.getAge() && petOne.getAge() > petThree.getAge() && petOne.getAge() > petFour.getAge() && petOne.getAge() > petFive.getAge())
    {
        System.out.println(petOne.getName()+" is the oldest pet.");
    }
     else if(petTwo.getAge() > petOne.getAge() && petTwo.getAge() > petThree.getAge() && petTwo.getAge() > petFour.getAge() && petTwo.getAge() > petFive.getAge())
    {
        System.out.println(petTwo.getName()+" is the oldest pet.");
    }
     else if(petThree.getAge() > petOne.getAge() && petThree.getAge() > petTwo.getAge() && petThree.getAge() > petFour.getAge() && petThree.getAge() > petFive.getAge())
    {
        System.out.println(petThree.getName()+" is the oldest pet.");
    }
     else if(petFour.getAge() > petOne.getAge() && petFour.getAge() > petTwo.getAge() && petFour.getAge() > petThree.getAge() && petFour.getAge() > petFive.getAge())
    {
        System.out.println(petFour.getName()+" is the oldest pet.");
    }
     else if(petFive.getAge() > petOne.getAge() && petFive.getAge() > petTwo.getAge() && petFive.getAge() > petThree.getAge() && petFive.getAge() > petFour.getAge())
    {
        System.out.println(petFive.getName()+" is the oldest pet.");
    }
    //Below caculates which pet is the smallest
        if(petOne.getWeight() < petTwo.getWeight() && petOne.getWeight() < petThree.getWeight() && petOne.getWeight() < petFour.getWeight() && petOne.getWeight() < petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the smallest pet.");
    }
     else if(petTwo.getWeight() < petOne.getWeight() && petTwo.getWeight() < petThree.getWeight() && petTwo.getWeight() < petFour.getWeight() && petTwo.getWeight() < petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the smallest pet.");
    }
     else if(petThree.getWeight() < petOne.getWeight() && petThree.getWeight() < petTwo.getWeight() && petThree.getWeight() < petFour.getWeight() && petThree.getAge() < petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the smallest pet.");
    }
     else if(petFour.getWeight() < petOne.getWeight() && petFour.getWeight() < petTwo.getWeight() && petFour.getWeight() < petThree.getWeight() && petFour.getWeight() < petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the smallest pet.");
    }
     else  if(petFive.getWeight() < petOne.getWeight() && petFive.getWeight() < petTwo.getWeight() && petFive.getWeight() < petThree.getWeight() && petFive.getWeight() < petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the smallest pet.");
    }
    //Below caculates to see which pet is the largest
        if(petOne.getWeight() > petTwo.getWeight() && petOne.getWeight() > petThree.getWeight() && petOne.getWeight() > petFour.getWeight() && petOne.getWeight() > petFive.getWeight())
    {
        System.out.println(petOne.getName()+" is the largest pet.");
    }
     else if(petTwo.getWeight() > petOne.getWeight() && petTwo.getWeight() > petThree.getWeight() && petTwo.getWeight() > petFour.getWeight() && petTwo.getWeight() > petFive.getWeight())
    {
        System.out.println(petTwo.getName()+" is the largest pet.");
    }
     else if(petThree.getWeight() > petOne.getWeight() && petThree.getWeight() > petTwo.getWeight() && petThree.getWeight() > petFour.getWeight() && petThree.getAge() > petFive.getWeight())
    {
        System.out.println(petThree.getName()+" is the largest pet.");
    }
    else if(petFour.getWeight() > petOne.getWeight() && petFour.getWeight() > petTwo.getWeight() && petFour.getWeight() > petThree.getWeight() && petFour.getWeight() > petFive.getWeight())
    {
        System.out.println(petFour.getName()+" is the largest pet.");
    }
    else if(petFive.getWeight() > petOne.getWeight() && petFive.getWeight() > petTwo.getWeight() && petFive.getWeight() > petThree.getWeight() && petFive.getWeight() > petFour.getWeight())
    {
        System.out.println(petFive.getName()+" is the largest pet.");
    }

   */

Body:
I believe CatRecord must be inheriting PetRecord, would have clarified this in a comment before answering but unfortunately, StackOverflow won't allow me to comment.Hence if the weight is stored in the PetRecord as all Pets have weight regardless of species and that would make sense. Something like this should work:

averageWeight += petArray[i].getWeight();

Also while initialising, write code on the lines of:

petarray[i] = new CatRecord();