问:
Compressing and decompress data through sockets
I'm having issues with this question right now.
For this question, I have to:

Client side: compress each input line from the console, send it to the server and decompress each message from server

Server side: decompress data from client, change the lower-case letters to upper case, compress it and send back to the client

The best I can do is do everything above with only ONE line.

Client Side:

```<code>/* SOCKET CONNECTING STUFF UP HERE */

    /*PROBLEMS START AROUND HERE */
    String line;
    BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));

    DeflaterOutputStream compress = new DeflaterOutputStream(socket.getOutputStream(), true);

    InflaterInputStream decompress = new InflaterInputStream(socket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));

    line = bis.readLine();

    line = line + "\n";
    compress.write(line.getBytes(), 0, line.length());
    compress.finish();
    System.out.println("Message sent: " + line);
    System.out.println("Message Returned : " +fromClient.readLine());

    /* closing the streams here */
    bis.close();
    decompress.close();
    compress.close();
    fromClient.close();
    socket.close();
}

}
</code>```

Server Side:

```<code>String line = "";
    OutputStream outstream = new FileOutputStream("compessserver.txt");

    InflaterInputStream decompress = new InflaterInputStream(clientsocket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));
    DeflaterOutputStream compress = new DeflaterOutputStream(clientsocket.getOutputStream());

    while ((line = fromClient.readLine()) != null) {
        String upperLine = line.toUpperCase();
        System.out.println("Message received and converted: " + upperLine);
        System.out.println();
        upperLine = upperLine + "\n";
        byte[] input = upperLine.getBytes();
        outstream.write(input);
        outstream.write("\r\n".getBytes());
        compress.write(input);
        System.out.println("Message returned : " + upperLine);
        compress.finish();
        if (upperLine.equalsIgnoreCase("x")) {
            break;
        }

    }

    decompress.close();
    compress.close();
    fromClient.close();
    outstream.close();
    socket.close();
}
}
</code>```

I really need help in this please. If I try to make this multiple inputs instead, the whole code just messes up. Been at this for days.

EDIT: Forgot to mention this. What I'm supposed to do is input a line, compress it, send to server, server decompress it and upper case letters, compress it, send back to client. And then I supposed to input more lines until I put in a single letter like "Q" which in case, ends the program

I tried the following code to make it work for multiple lines

Second Try Client Side:

```<code>    String line;
    BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));

    DeflaterOutputStream compress = new DeflaterOutputStream(socket.getOutputStream(), true);

    InflaterInputStream decompress = new InflaterInputStream(socket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));
    line = bis.readLine();
    while ((!line.equalsIgnoreCase("x"))) {
        compress.write(line.getBytes(), 0, line.length());
        System.out.println("Message sent: " + line);
        System.out.println("Message returned:" +fromClient.readLine() );
        line = bis.readLine();
    }

    bis.close();
    fromClient.close();
    socket.close();
}
</code>```

}

Second Try Server Side:

```<code>OutputStream outstream = new FileOutputStream("compessserver.txt");
    InflaterInputStream decompress = new InflaterInputStream(clientsocket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));
    DeflaterOutputStream compress = new DeflaterOutputStream(clientsocket.getOutputStream());

    while ((line = fromClient.readLine()) != null) {
        String upperLine = line.toUpperCase();
        System.out.println("Message received and converted: " + upperLine);
        System.out.println();
        upperLine = upperLine + "\n";
        byte[] input = upperLine.getBytes();
        outstream.write(input);
        outstream.write("\r\n".getBytes());
        compress.write(input);
        System.out.println("Message returned : " + upperLine);

        if (upperLine.equalsIgnoreCase("x")) {
            break;
        }

    }

    decompress.close();
    fromClient.close();
    outstream.close();
    socket.close();
}
</code>```

}

答:
You can't use these streams interactively. You would have to call finish() after every write, or rather before every read, which means you could only do one write. They are designed for large one-way streams, not interactive request/response sessions.

In any case there is no advantage to be gained from compressing single lines. You need a lot of data for compression to start working.

NB compress.write(line.getBytes(), 0, line.length()) isn't valid. It assumes the number of chars in the String is the same as the number of bytes when converted, which isn't always so. It should be compress.write(line.getBytes(), 0, line.getBytes().length()), or more simply compress.write(line.getBytes()).

Body:
I'm having issues with this question right now.
For this question, I have to:

Client side: compress each input line from the console, send it to the server and decompress each message from server

Server side: decompress data from client, change the lower-case letters to upper case, compress it and send back to the client

The best I can do is do everything above with only ONE line.

Client Side:

/* SOCKET CONNECTING STUFF UP HERE */

    /*PROBLEMS START AROUND HERE */
    String line;
    BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));

    DeflaterOutputStream compress = new DeflaterOutputStream(socket.getOutputStream(), true);

    InflaterInputStream decompress = new InflaterInputStream(socket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));

    line = bis.readLine();

    line = line + "\n";
    compress.write(line.getBytes(), 0, line.length());
    compress.finish();
    System.out.println("Message sent: " + line);
    System.out.println("Message Returned : " +fromClient.readLine());

    /* closing the streams here */
    bis.close();
    decompress.close();
    compress.close();
    fromClient.close();
    socket.close();
}

}

Server Side:

String line = "";
    OutputStream outstream = new FileOutputStream("compessserver.txt");

    InflaterInputStream decompress = new InflaterInputStream(clientsocket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));
    DeflaterOutputStream compress = new DeflaterOutputStream(clientsocket.getOutputStream());

    while ((line = fromClient.readLine()) != null) {
        String upperLine = line.toUpperCase();
        System.out.println("Message received and converted: " + upperLine);
        System.out.println();
        upperLine = upperLine + "\n";
        byte[] input = upperLine.getBytes();
        outstream.write(input);
        outstream.write("\r\n".getBytes());
        compress.write(input);
        System.out.println("Message returned : " + upperLine);
        compress.finish();
        if (upperLine.equalsIgnoreCase("x")) {
            break;
        }

    }

    decompress.close();
    compress.close();
    fromClient.close();
    outstream.close();
    socket.close();
}
}

I really need help in this please. If I try to make this multiple inputs instead, the whole code just messes up. Been at this for days.

EDIT: Forgot to mention this. What I'm supposed to do is input a line, compress it, send to server, server decompress it and upper case letters, compress it, send back to client. And then I supposed to input more lines until I put in a single letter like "Q" which in case, ends the program

I tried the following code to make it work for multiple lines

Second Try Client Side:

    String line;
    BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));

    DeflaterOutputStream compress = new DeflaterOutputStream(socket.getOutputStream(), true);

    InflaterInputStream decompress = new InflaterInputStream(socket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));
    line = bis.readLine();
    while ((!line.equalsIgnoreCase("x"))) {
        compress.write(line.getBytes(), 0, line.length());
        System.out.println("Message sent: " + line);
        System.out.println("Message returned:" +fromClient.readLine() );
        line = bis.readLine();
    }

    bis.close();
    fromClient.close();
    socket.close();
}

}

Second Try Server Side:

OutputStream outstream = new FileOutputStream("compessserver.txt");
    InflaterInputStream decompress = new InflaterInputStream(clientsocket.getInputStream());
    BufferedReader fromClient = new BufferedReader(new InputStreamReader(decompress));
    DeflaterOutputStream compress = new DeflaterOutputStream(clientsocket.getOutputStream());

    while ((line = fromClient.readLine()) != null) {
        String upperLine = line.toUpperCase();
        System.out.println("Message received and converted: " + upperLine);
        System.out.println();
        upperLine = upperLine + "\n";
        byte[] input = upperLine.getBytes();
        outstream.write(input);
        outstream.write("\r\n".getBytes());
        compress.write(input);
        System.out.println("Message returned : " + upperLine);

        if (upperLine.equalsIgnoreCase("x")) {
            break;
        }

    }

    decompress.close();
    fromClient.close();
    outstream.close();
    socket.close();
}

}


来源: stackexchange

问:
Angular2 CLI error "@angular/compiler-cli" package was not properly installed
I'm working an Angular 2 project. Now trying to install Angular CLI within the current project with the following

```<code>npm install --save-dev @angular/cli@latest
npm install
</code>```

Problem is when running ng serve I receive error

```<code>The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/myng2project/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/myng2project/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
</code>```

答:
I had the same problem. I resolved it following the "Updating Angular CLI" process in the npm @angular/cli page, that is:

1. Uninstall and clean (global)

```<code>rm -rf node_modules dist
npm uninstall -g @angular/cli
npm cache clean
</code>```

2. Reinstall and play (global)

```<code>npm install -g @angular/cli@latest
npm install
ng serve
</code>```

This worked for me.

ContentLicense: CC BY-SA 3.0

Body:
I'm working an Angular 2 project. Now trying to install Angular CLI within the current project with the following

npm install --save-dev @angular/cli@latest
npm install

Problem is when running ng serve I receive error

The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/myng2project/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/myng2project/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)

Body:
I had the same problem. I resolved it following the "Updating Angular CLI" process in the npm @angular/cli page, that is:

1. Uninstall and clean (global)

rm -rf node_modules dist
npm uninstall -g @angular/cli
npm cache clean

2. Reinstall and play (global)

npm install -g @angular/cli@latest
npm install
ng serve

This worked for me.


问:
Javascript - Having trouble inserting function
I want to add a function that sets vticketqty to 0 if the user enters a non numeric value. I've tried a few things but my code never works properly if i add the function so I'm clearly doing something wrong.

This is the function i was using:

```<code>function NaN(){
    if (isNaN(TicketQty)) TicketQty = 0;
    } else {
    return TicketQty
}
</code>```

I'm not sure if its correct however, and I'm not entirely sure where the function should be placed within the code. This is my javascript code. Any help would be appreciated.

```<code>var vTicketType;
var vTicketQty;
var vTicketPrice;
function calcTotal() {
    vTicketType = prompt("Enter Ticket Type").toUpperCase();
    document.write("<br>");
    vTicketQty = prompt("Enter No. of Tickets");
    calcPrice();
    vTicketQty = parseInt(vTicketQty);
    document.write("<br>");
    document.write("Type of Ticket:" + vTicketType);
    document.write("<br>");
    document.write("Number of Tickets:" + vTicketQty);
    document.write("<br>");
    var vTotalPayment =(vTicketPrice) * (vTicketQty);
    if (vTotalPayment >0) {
        document.write("Total Payment is: $" + vTotalPayment);
        vTicketPrice = parseInt(vTicketPrice);
    } else {
        document.write("INVALID")
    }
}

function calcPrice(){
    if (vTicketType == 'A') {
        vTicketPrice = 50;
    } else if (vTicketType == 'B') {
        vTicketPrice = 30;
    }  else if (vTicketType == 'C'){
      vTicketPrice = 10;
    }
    else {
        vTicketPrice = -1;
    }
}
</code>```

答:
Instead of this:

```<code>document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = parseInt(vTicketQty);
document.write("<br>");
</code>```

Try this.

```<code>document.write("<br>");
while (isNaN(vTicketQty)) {
    vTicketQty = prompt("Enter No. of Tickets");
    calcPrice();
    vTicketQty = parseInt(vTicketQty);
    if (isNaN(vTicketQty)) {
        alert("Quantity must be a number");
    }
}
document.write("<br>");
</code>```

EDIT - As requested.

```<code>document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = parseInt(vTicketQty);
if (isNaN(vTicketQty)) {
    vTicketQty = 0;
}
document.write("<br>");
</code>```

EDITED - more function like

1)

```<code>document.write("<br>");
calcPrice();
vTicketQty = getQty();
document.write("<br>");

function getQty() {
    qty = parseInt(prompt("Enter No. of Tickets"));
    if (isNaN(qty)) {
        return 0;
    }
    return qty;
}
</code>```

2)

```<code>document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = checkNaN(parseInt(vTicketQty));
document.write("<br>");

function checkNaN(qty) {
    if (isNaN(qty)) {
        return 0;
    }
    return qty;
}
</code>```

Body:
I want to add a function that sets vticketqty to 0 if the user enters a non numeric value. I've tried a few things but my code never works properly if i add the function so I'm clearly doing something wrong.

This is the function i was using:

function NaN(){
    if (isNaN(TicketQty)) TicketQty = 0;
    } else {
    return TicketQty
}

I'm not sure if its correct however, and I'm not entirely sure where the function should be placed within the code. This is my javascript code. Any help would be appreciated.

var vTicketType;
var vTicketQty;
var vTicketPrice;
function calcTotal() {
    vTicketType = prompt("Enter Ticket Type").toUpperCase();
    document.write("
");
    vTicketQty = prompt("Enter No. of Tickets");
    calcPrice();
    vTicketQty = parseInt(vTicketQty);
    document.write("
");
    document.write("Type of Ticket:" + vTicketType);
    document.write("
");
    document.write("Number of Tickets:" + vTicketQty);
    document.write("
");
    var vTotalPayment =(vTicketPrice) * (vTicketQty);
    if (vTotalPayment >0) {
        document.write("Total Payment is: $" + vTotalPayment);
        vTicketPrice = parseInt(vTicketPrice);
    } else {
        document.write("INVALID")
    }
}

function calcPrice(){
    if (vTicketType == 'A') {
        vTicketPrice = 50;
    } else if (vTicketType == 'B') {
        vTicketPrice = 30;
    }  else if (vTicketType == 'C'){
      vTicketPrice = 10;
    }
    else {
        vTicketPrice = -1;
    }
}

Body:
Instead of this:

document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = parseInt(vTicketQty);
document.write("<br>");

Try this.

document.write("<br>");
while (isNaN(vTicketQty)) {
    vTicketQty = prompt("Enter No. of Tickets");
    calcPrice();
    vTicketQty = parseInt(vTicketQty);
    if (isNaN(vTicketQty)) {
        alert("Quantity must be a number");
    }
}
document.write("<br>");

EDIT - As requested.

document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = parseInt(vTicketQty);
if (isNaN(vTicketQty)) {
    vTicketQty = 0;
}
document.write("<br>");

EDITED - more function like

1)

document.write("<br>");
calcPrice();
vTicketQty = getQty();
document.write("<br>");

function getQty() {
    qty = parseInt(prompt("Enter No. of Tickets"));
    if (isNaN(qty)) {
        return 0;
    }
    return qty;
}

2)

document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = checkNaN(parseInt(vTicketQty));
document.write("<br>");

function checkNaN(qty) {
    if (isNaN(qty)) {
        return 0;
    }
    return qty;
}


问:
Broadcast receiver working even after app is killed by user
I have a BroadcastReceiver that checks for network connection declared statically as:

```<code><receiver
            android:name=".core.util.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
</code>```

Network change receiver does something like:

```<code>public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

    String status = NetworkUtil.getConnectivityStatusString(context);

    if(status == "Not connected to Internet") {
        Intent i = new Intent(context, Dialog.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}
</code>```

}

The problem is that when I manually kill my app and turn off network (airplane mode), the Dialogue activity launches. How is this possible? Is my broadcast receiver still alive in the background?

Question:

is there a way for me to unregister my broadcast receiver once the application is killed? maybe in the application singleton class of Android?

If it is not possible in Application class, do I have to manually unregister it everywhere in onStop()? and register it in onStart() in every activity?

答:
You expect that registering and unregistering BroadcastReceiver on every activity。
I think the application class is the best solution。
there is a function in Application class which named registerActivityLifecycleCallbacks(),
you can watch your activities lifecycle callback in real time.

Body:
I have a BroadcastReceiver that checks for network connection declared statically as:

<receiver
            android:name=".core.util.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

Network change receiver does something like:

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

    String status = NetworkUtil.getConnectivityStatusString(context);

    if(status == "Not connected to Internet") {
        Intent i = new Intent(context, Dialog.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

}

The problem is that when I manually kill my app and turn off network (airplane mode), the Dialogue activity launches. How is this possible? Is my broadcast receiver still alive in the background?

Question:

is there a way for me to unregister my broadcast receiver once the application is killed? maybe in the application singleton class of Android?

If it is not possible in Application class, do I have to manually unregister it everywhere in onStop()? and register it in onStart() in every activity?


问:
How to put a border-radius on a specific corner of a button
I have a modal that looks like this

As you can see, the modal has border-radius but the buttons at the footer dont. I want to put a border-radius at the bottom left of the purple button and a border-radius at the bottom right of the gray button. Ive tried border-bottom-left-radius and border-bottom-right-radius but it didnt work. Here`s my codes

Modal:

```<code><!--Notifier Modal-->
<div id="notifier-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
   <div class="modal-dialog modal-md" role="document">
       <div class="modal-content">
           <div class="modal-body">
               <div class="row">
                   <div class="col-md-12">
                       <div class="confirm-purchase-label">
                           Only {{size}} out of {{totalsize}} transactions have been loaded <br>
                           <h5>The complete list of transactions will be sent to your email after the process.</h5>
                       </div>
                   </div>
               </div>
           </div>

           <div class="modal-footer g-nopadding">
               <div class="col-md-6 g-nopadding">
                   <button type="button" class="btn btn-purple btn-block col-md-6" ng-click="proceedAction();">PROCEED</button>
               </div>
               <div class="col-md-6 g-nopadding">
                   <button type="button" class="btn btn-gray btn-block col-md-6" data-dismiss="modal">CANCEL</button>
               </div>
           </div>
       </div>
   </div>
</code>```

CSS:

```<code>#notifier-modal .btn,
{
    border: none!important;
    border-radius: 0px!important;
    font-family: 'AvenirMedium';
    height: 50px!important;
}

#notifier-modal .modal-md{
    width: 500px;
}

.modal-footer {
   padding: 15px;
   text-align: right;
   border-top: 1px solid #e5e5e5;
}

.modal-content{
   background:#f0f0f0;
   box-shadow:0px 0px 30px 0px rgba(101,101,101,0.50);
   border: none;
}

.btn-gray {
   color: #797979!important;
   background:#e0e0e0!important;
   font-size:14px!important;
   border: none!important;
}

.btn-purple {
   color: #f0f0f0!important;
   background-color: #9c82cd!important;
   font-size:14px!important;
   border: none!important;
}
</code>```

答:
You can just apply a border-radius to all side of the modal that already has the top left/right border-radius, and assuming the buttons are at the bottom corners of that element, if you also add overflow: hidden to the modal with the border-radius, it will clip the corners of the buttons.

body {
  background: #aaa;
  text-align: center;
}
div {
  background: #fff;
  border-radius: 1em;
  padding: 1em;
  display: inline-block;
  width: 200px;
  height: 100px;
  position: relative;
  overflow: hidden;
}
button {
  position: absolute;
  bottom: 0;
  padding: 0;
  margin: 0;
  width: 50%;
  left: 0;
  padding: .5em 0;
  background: #09c;
  color: white;
  border: 0;
}
button:last-child {
  left: auto;
  right: 0;
  border-left: 1px solid white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <button>button</button>
  <button>button</button>
</div></code>```

Body:
I have a modal that looks like this

As you can see, the modal has border-radius but the buttons at the footer dont. I want to put a border-radius at the bottom left of the purple button and a border-radius at the bottom right of the gray button. Ive tried border-bottom-left-radius and border-bottom-right-radius but it didnt work. Here`s my codes

Modal:

                           Only {{size}} out of {{totalsize}} transactions have been loaded

The complete list of transactions will be sent to your email after the process.

                   <button type="button" class="btn btn-purple btn-block col-md-6" ng-click="proceedAction();">PROCEED</button>

                   <button type="button" class="btn btn-gray btn-block col-md-6" data-dismiss="modal">CANCEL</button>

CSS:

#notifier-modal .btn,
{
    border: none!important;
    border-radius: 0px!important;
    font-family: 'AvenirMedium';
    height: 50px!important;
}

#notifier-modal .modal-md{
    width: 500px;
}

.modal-footer {
   padding: 15px;
   text-align: right;
   border-top: 1px solid #e5e5e5;
}

.modal-content{
   background:#f0f0f0;
   box-shadow:0px 0px 30px 0px rgba(101,101,101,0.50);
   border: none;
}

.btn-gray {
   color: #797979!important;
   background:#e0e0e0!important;
   font-size:14px!important;
   border: none!important;
}

.btn-purple {
   color: #f0f0f0!important;
   background-color: #9c82cd!important;
   font-size:14px!important;
   border: none!important;
}

Body:
You can just apply a border-radius to all side of the modal that already has the top left/right border-radius, and assuming the buttons are at the bottom corners of that element, if you also add overflow: hidden to the modal with the border-radius, it will clip the corners of the buttons.

body {
  background: #aaa;
  text-align: center;
}
div {
  background: #fff;
  border-radius: 1em;
  padding: 1em;
  display: inline-block;
  width: 200px;
  height: 100px;
  position: relative;
  overflow: hidden;
}
button {
  position: absolute;
  bottom: 0;
  padding: 0;
  margin: 0;
  width: 50%;
  left: 0;
  padding: .5em 0;
  background: #09c;
  color: white;
  border: 0;
}
button:last-child {
  left: auto;
  right: 0;
  border-left: 1px solid white;
}

<div>
  <button>button</button>
  <button>button</button>
</div>


问:
How to convert a Facebook Birthday into a Java Date Object?
Facebook returns me a String like:

```<code>06/15/1992
</code>```

How can I convert this string date into a Java Date object?

I tried the following but it returns "Wed Jan 15 00:06:00 UTC 1992" which is not the correct date.

```<code> String t = "06/15/1992";
 SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");
 Date test = dateFormat.parse(t);
</code>```

答:
First, you need MM (month), not mm (minutes).

Facebook could return dates in a different format. Here is the graph documentation:

The person's birthday. This is a fixed format string, like MM/DD/YYYY. However, people can control who can see the year they were born separately from the month and day so this string can be only the year (YYYY) or the month + day (MM/DD)

https://developers.facebook.com/docs/graph-api/reference/user

Your code should check for which date format Facebook provided you.

```<code>    String[] dateParts = birthday.split(birthday, "/");
    try {
        switch (dateParts.length) {
            case 2:
                // A fully formed date: MM/dd/yyyy
                Date dob = new SimpleDateFormat("MM/dd/yyyy, Locale.US).parse(birthday));
                break;
            case 1:
                // Only a day and month: mm/dd.
                String month = dateParts[0];
                String day = dateParts[1];
                // Do something intelligent with the information.
                break;
            case 0:
                // Only a year: yyyy
                // Do something
            default:
                // Unexpected format. Give up!
                return null;
        }
    } catch (ParseException ex) {
        Log.e(LOG_TAG, "getAge: Couldn't parse FB date: " + birthday, ex);
        return null;
    }
</code>```

Body:
Facebook returns me a String like:

06/15/1992

How can I convert this string date into a Java Date object?

I tried the following but it returns "Wed Jan 15 00:06:00 UTC 1992" which is not the correct date.

 String t = "06/15/1992";
 SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");
 Date test = dateFormat.parse(t);

Body:
First, you need MM (month), not mm (minutes).

Facebook could return dates in a different format. Here is the graph documentation:

The person's birthday. This is a fixed format string, like MM/DD/YYYY. However, people can control who can see the year they were born separately from the month and day so this string can be only the year (YYYY) or the month + day (MM/DD)

https://developers.facebook.com/docs/graph-api/reference/user

Your code should check for which date format Facebook provided you.

    String[] dateParts = birthday.split(birthday, "/");
    try {
        switch (dateParts.length) {
            case 2:
                // A fully formed date: MM/dd/yyyy
                Date dob = new SimpleDateFormat("MM/dd/yyyy, Locale.US).parse(birthday));
                break;
            case 1:
                // Only a day and month: mm/dd.
                String month = dateParts[0];
                String day = dateParts[1];
                // Do something intelligent with the information.
                break;
            case 0:
                // Only a year: yyyy
                // Do something
            default:
                // Unexpected format. Give up!
                return null;
        }
    } catch (ParseException ex) {
        Log.e(LOG_TAG, "getAge: Couldn't parse FB date: " + birthday, ex);
        return null;
    }


问:
The prop `history` is marked as required in `Router`, but its value is `undefined`. in Router
I am new to ReactJs. This is my code:

```<code>var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Main = require('Main');
ReactDOM.render(
  <Router history={hashHistory}>
  <Route path="/" component={Main}></Route>
</Router>, document.getElementById('app'));
</code>```

and compiling it with webpack. Also I added Main component to my aliases.
The console throws these errors:

I also read these links :

React Router failed prop 'history', is undefined

How do I resolve history is marked required, when value is undefined?

Upgrading React-Router and replacing hashHistory with browserHistory

and many searches around the web, but I couldn't fix this issue. React Router is version 4

答:
If you are using react-router v4 you need to install react-router-dom as well. After that, import BrowserRouter from react-router-dom and switch Router for BrowserRouter. It seems that v4 change several things. Also, the react-router documentation is outdated. This is my working code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom'
import App from './components/App';

ReactDOM.render((
     <BrowserRouter>
          <Route path="/" component={App}/>
     </BrowserRouter>
     ),
     document.getElementById('root')
);
</code>```

Source

Body:
I am new to ReactJs. This is my code:

var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Main = require('Main');
ReactDOM.render(
  <Router history={hashHistory}>
  <Route path="/" component={Main}></Route>
</Router>, document.getElementById('app'));

and compiling it with webpack. Also I added Main component to my aliases.
The console throws these errors:

I also read these links :

React Router failed prop 'history', is undefined

How do I resolve history is marked required, when value is undefined?

Upgrading React-Router and replacing hashHistory with browserHistory

and many searches around the web, but I couldn't fix this issue. React Router is version 4

Body:
If you are using react-router v4 you need to install react-router-dom as well. After that, import BrowserRouter from react-router-dom and switch Router for BrowserRouter. It seems that v4 change several things. Also, the react-router documentation is outdated. This is my working code:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom'
import App from './components/App';

ReactDOM.render((
     <BrowserRouter>
          <Route path="/" component={App}/>
     </BrowserRouter>
     ),
     document.getElementById('root')
);

Source

ContentLicense: CC BY-SA 4.0


问:
Any advice/proper way to make an Android app who can execute task on Windows/Linux?
I want to make an app who can execute program on my computer or execute music to train myself.
Do you have any advice on how to connect them both ?
Thank you</p>

答:
This may seem obvious, but an Android application, by definition, runs on an Android device.

Given that it's not running on your Windows or Linux computer, it can't "execute a task" on one of those computers.

What it can do is communicate with an application running on the other computer.
The possibilities include IP network communication (TCP or UDP), and Bluetooth.

In either case (or if you pick some other communication protocol) you will likely need to write a custom application that runs on the Windows or Linux computer, so that your Android app has something to talk to. That custom application can then "execute tasks" on the Android application's behalf.

You could either write separate applications for Windows and Linux, or write a single, cross-platform application. There are many ways to write cross-platform applications, what you choose will largely be dictated by what exactly you need it to do, and what programming languages you know.


问:
How to return bool and double simultaneously?
In C, I have a function that calculates the product of a and b. If a < b it returns false otherwise returns true. How can I return the product when the function is defined as boolean?</p>

```<code>bool multiplication(int a, int b)
{
    int c = a*b;
    if (a < b)
        return false;
    else
        return true;
}
</code>```

答:
How to return bool and double simultaneously?

A function can only have one return type. But you can use a workaround of using a struct containing a bool and an int members as stated in one of the comments.

You can achieve your goal of writing a multiplication function of positive integers with a recursion logic the following way too:

```<code>int multiplication(int a, int b) {
    if(b <= 1) return a;
    return a + multiplication(a, --b);
}
</code>```

Body:
In C, I have a function that calculates the product of a and b. If a < b it returns false otherwise returns true. How can I return the product when the function is defined as boolean?

bool multiplication(int a, int b)
{
    int c = a*b;
    if (a < b)
        return false;
    else
        return true;
}

Body:
How to return bool and double simultaneously?

A function can only have one return type. But you can use a workaround of using a struct containing a bool and an int members as stated in one of the comments.

You can achieve your goal of writing a multiplication function of positive integers with a recursion logic the following way too:

int multiplication(int a, int b) {
    if(b <= 1) return a;
    return a + multiplication(a, --b);
}


问:
C Makefile error: ld returned 1 exit
My teacher is not the best at explain C so I'm having a bit of trouble understanding the connection of makefiles. I have already added the code for complex.c, complex.h, and main.c. I'm just having trouble compiling it all using the make command. I followed the example on the powerpoint he handed up and I don't understand why its failing to get to complex.

makefile

```<code>complex: main.o complex.o
    gcc -o complex main.o complex.o
main.o: main.c complex.h
    gcc -c main.c -lm
complex.o: complex.c complex.h
    gcc -c complex.c -lm
clean:
    rm*.o complex
    ls
</code>```

main.o

```<code>main.o: complex.h
    gcc -c main.c
</code>```

complex.o

```<code>complex.o: complex.h
    gcc -c complex.c
</code>```

Error

```<code>mason% make
gcc -o complex main.o complex.o
ld: fatal: file main.o: unknown file type
ld: fatal: file processing errors. No output written to complex
collect2: error: ld returned 1 exit status
*** Error code 1
make: Fatal error: Command failed for target `complex'
</code>```

答:
The "Makefile" defines and controls the build dependencies.

For example, you can't build the main executable binary without first building the binary object/module files that go with it.  In this case, those are main.o and complex.o.

Generally any object file you need also needs a rule (though some rules can use "wildcards" to build more).

This is all rather academic.  Best to take errors at their word and try to disprove them (this one basically says that main.o exists and is incorrect).  In this case the hypothesis that main.o exists is supported by the fact that it didn't compile when you ran the make command.

Until you learn more you could invoke "make" using "targets".  Like: make clean and make complex.  It might help bring clarity.

A lot of makefiles put an "all" target to sort of reset the build.  That then depends on "clean" and the executable and library targets.  Like:

```<code>all: clean complex
</code>```

So then you "make all" to clean and build.

A good tutorial is here.  Mrbook Makefile Tutorial

Title: C Makefile error: ld returned 1 exit

Body:
My teacher is not the best at explain C so I'm having a bit of trouble understanding the connection of makefiles. I have already added the code for complex.c, complex.h, and main.c. I'm just having trouble compiling it all using the make command. I followed the example on the powerpoint he handed up and I don't understand why its failing to get to complex.

makefile

complex: main.o complex.o
    gcc -o complex main.o complex.o
main.o: main.c complex.h
    gcc -c main.c -lm
complex.o: complex.c complex.h
    gcc -c complex.c -lm
clean:
    rm*.o complex
    ls

main.o

main.o: complex.h
    gcc -c main.c

complex.o

complex.o: complex.h
    gcc -c complex.c

Error

mason% make
gcc -o complex main.o complex.o
ld: fatal: file main.o: unknown file type
ld: fatal: file processing errors. No output written to complex
collect2: error: ld returned 1 exit status
*** Error code 1
make: Fatal error: Command failed for target `complex'

Body:
The "Makefile" defines and controls the build dependencies.

For example, you can't build the main executable binary without first building the binary object/module files that go with it.  In this case, those are main.o and complex.o.

Generally any object file you need also needs a rule (though some rules can use "wildcards" to build more).

This is all rather academic.  Best to take errors at their word and try to disprove them (this one basically says that main.o exists and is incorrect).  In this case the hypothesis that main.o exists is supported by the fact that it didn't compile when you ran the make command.

Until you learn more you could invoke "make" using "targets".  Like: make clean and make complex.  It might help bring clarity.

A lot of makefiles put an "all" target to sort of reset the build.  That then depends on "clean" and the executable and library targets.  Like:

all: clean complex

So then you "make all" to clean and build.

A good tutorial is here.  Mrbook Makefile Tutorial


问:
List field in blackberry
How we give onclick event on list in blackberry</p>

答: You can use the Field.html navigationClick method to start handling the click.</p>

ContentLicense: CC BY-SA 2.5

Title: List field in blackberry


问:
Will write() fail in this case using pipes?
If you fork() and create two processes for reading and writing to a pipe and the child process is reading from the pipe and the parent process is writing to the pipe, will writing in the parent process fail if the child process was to close the pipe that writes before the parent process has a chance to write to the pipe?</p>

答:
The child process closing its write end of the pipe only removes its reference to the pipe, it doesn't cause the pipe to "shut down" or any such thing, and thus won't affect the parent's reference to it in any way. This is true for the close(2) call in general.

Further reading:

File descriptors


问:
Asana Python API : Find all tasks that are unassigned in a workspace
I am using the python-asana API,

https://github.com/Asana/python-asana

Using this, it is very easy to get all tasks in a workspace if I specify the task assignee and the workspace, like so,

```<code>task_fields = ["this.workspace", "this.name", "this.created_at", "this.completed", "this.assignee_status", "this.completed_at", "this.name", "this.project"]
tasks=client.tasks.find_all({"opt_fields":task_fields}, assignee = 'xxxxxxxx', workspace = xxxxxx, iterator_type='items')
</code>```

However, I want do some task maintenance/pruning and would like to get a list of all tasks that are not assigned to anyone. I believe the assignee field in this API does not accept 'null' and I cannot make this query without specifying the assignee.

Does anyone know how to do this?

答: While you can create and update tasks with assignee=null, you cannot query for unassigned tasks.  You would need to get all of the tasks you wish to prune and then filter for the unassigned ones on your side.

Body:
I am using the python-asana API,

https://github.com/Asana/python-asana

Using this, it is very easy to get all tasks in a workspace if I specify the task assignee and the workspace, like so,

task_fields = ["this.workspace", "this.name", "this.created_at", "this.completed", "this.assignee_status", "this.completed_at", "this.name", "this.project"]
tasks=client.tasks.find_all({"opt_fields":task_fields}, assignee = 'xxxxxxxx', workspace = xxxxxx, iterator_type='items')

However, I want do some task maintenance/pruning and would like to get a list of all tasks that are not assigned to anyone. I believe the assignee field in this API does not accept 'null' and I cannot make this query without specifying the assignee.

Does anyone know how to do this?


问:
How do I format UITextField text in real time, while it's being edited?
How can I change value of UITextField text while typing?

In other word:

when I type 1 it should show 1

when I type 10 it should show 10

when I type 100 it should show 100
but

when I type 1000 it should show 1,000

Can you give any idea?

答:
Swift:

Be sure to select the text field input as number pad, then:

In your viewDidLoad:

```<code>yourTextField(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)
</code>```

Then, in that same view controller:

```<code>func textFieldDidChange(textField: UITextField) {
        if textField == yourTextField {

            // Some locales use different punctuations.
            var textFormatted = textField.text?.replacingOccurrences(of: ",", with: "")
            textFormatted = textFormatted?.replacingOccurrences(of: ".", with: "")

            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .decimal
            if let text = textFormatted, let textAsInt = Int(text) {
                textField.text = numberFormatter.string(from: NSNumber(value: textAsInt))
            }
        }
    }
</code>```

Body:
Swift:

Be sure to select the text field input as number pad, then:

In your viewDidLoad:

yourTextField(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)

Then, in that same view controller:

func textFieldDidChange(textField: UITextField) {
        if textField == yourTextField {

            // Some locales use different punctuations.
            var textFormatted = textField.text?.replacingOccurrences(of: ",", with: "")
            textFormatted = textFormatted?.replacingOccurrences(of: ".", with: "")

            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .decimal
            if let text = textFormatted, let textAsInt = Int(text) {
                textField.text = numberFormatter.string(from: NSNumber(value: textAsInt))
            }
        }
    }


问:
limit python input to int
How can i make the code limit the input of the user to integers. The code right now works perfect but i want it to instead of giving me an error when it inputs a String, it will just make an exception. </p>

```<code>def miles_to_km():
        miles=eval(input('Amount of miles: '))
        result= float(miles*1.609344)
        print(miles, 'Miles are equivalent to ', result, 'Kilometers')
        print('----------------------------------------------------------------')
def km_to_miles():
        km=eval(input('Amount of kilometers: '))
        result= float(km*0.62137119)
        print(km, 'Kilometers are equivalent to ', result, 'Miles')
        print('----------------------------------------------------------------')
def pounds_to_kg():
        pounds=eval(input('Amount of pounds: '))
        result=float(pounds/2.2046226218)
        print(pounds, 'Pounds are equivalent to ', result, 'Kilograms')
        print('----------------------------------------------------------------')
def kg_to_pounds():
        kg=eval(input('Amount of kilograms: '))
        result=float(kg*2.2046226218)
        print(kg, 'Kilograms are equivalent to ', result, 'Pounds')
        print('----------------------------------------------------------------')
def C_to_F():
    temp=eval(input('Temperature in Celsius: '))
    result= float((temp*1.8)+32)
    print(temp, '°C are equivalent to ', result, '°F')
    print('----------------------------------------------------------------')
def F_to_C():
    temp=eval(input('Temperature in Fahrenheit '))
    result= float((temp-32)/1.8)
    print(temp, '°F are equivalent to ', result, '°C')
    print('----------------------------------------------------------------')
def mph_to_kph():
        mph=eval(input('Amount of Miles per hour: '))
        result= float(mph*1.609344)
        print(mph, 'Miles/Hour are equivalent to ', result, 'Kilometers/Hour')
        print('----------------------------------------------------------------')
def kph_to_mph():
        kph=eval(input('Amount of Kiometers per hour: '))
        result= float(kph*0.62137119)
        print(kph, 'Kilometers/Hour are equivalent to ', result, 'Miles/Hour')
        print('----------------------------------------------------------------')
def exit_function():
    print('Thanks for using the conversion program.')
    print('----------------------------------------------------------------')
    import sys
    sys.exit()

def menu():
    print('----------------------------------------------------------------')
    print('Welcome to the unit conversion program. Please select an option.')
    print('1. Miles to Kilometers')
    print('2. Kilometers to miles')
    print('3. Pounds to Kilograms')
    print('4. Kilograms to Pounds')
    print('5. Celsius to Fahrenheit')
    print('6. Fahrenheit to Celsius')
    print('7. Miles/hour to Kilometers/hour')
    print('8. Kilometers/hour to Miles/Hour')
    print('9. Exit')

screen=True

while screen:
    menu()
    choice=eval(input('Enter option: '))
    if choice==1:
        miles_to_km()
    elif choice==2:
        km_to_miles()
    elif choice==3:
        pounds_to_kg()
    elif choice==4:
        kg_to_pounds()
    elif choice==5:
        C_to_F()
    elif choice==6:
        F_to_C()
    elif choice==7:
        mph_to_kph()
    elif choice==8:
        kph_to_mph()
    elif choice==9:
        exit_function()
    else:
        print('Try a number between 1 and 9!')
</code>```

答:
you could convert the input with try statement.

```<code>while True:
    menu()
    choice = input('Enter option: ')
    try:
        choice = int(choice)
    except ValueError:
        print('invaild choice.')
        print('Try a number between 1 and 9!')
        continue
    if choice==1:
        miles_to_km()
    elif choice==2:
        km_to_miles()
    elif choice==3:
        pounds_to_kg()
    elif choice==4:
        kg_to_pounds()
    elif choice==5:
        C_to_F()
    elif choice==6:
        F_to_C()
    elif choice==7:
        mph_to_kph()
    elif choice==8:
        kph_to_mph()
    elif choice==9:
        exit_function()
    else:
        print('Try a number between 1 and 9!')
</code>```

Title: limit python input to int

Body:
How can i make the code limit the input of the user to integers. The code right now works perfect but i want it to instead of giving me an error when it inputs a String, it will just make an exception.

def miles_to_km():
        miles=eval(input('Amount of miles: '))
        result= float(miles*1.609344)
        print(miles, 'Miles are equivalent to ', result, 'Kilometers')
        print('----------------------------------------------------------------')
def km_to_miles():
        km=eval(input('Amount of kilometers: '))
        result= float(km*0.62137119)
        print(km, 'Kilometers are equivalent to ', result, 'Miles')
        print('----------------------------------------------------------------')
def pounds_to_kg():
        pounds=eval(input('Amount of pounds: '))
        result=float(pounds/2.2046226218)
        print(pounds, 'Pounds are equivalent to ', result, 'Kilograms')
        print('----------------------------------------------------------------')
def kg_to_pounds():
        kg=eval(input('Amount of kilograms: '))
        result=float(kg*2.2046226218)
        print(kg, 'Kilograms are equivalent to ', result, 'Pounds')
        print('----------------------------------------------------------------')
def C_to_F():
    temp=eval(input('Temperature in Celsius: '))
    result= float((temp*1.8)+32)
    print(temp, '°C are equivalent to ', result, '°F')
    print('----------------------------------------------------------------')
def F_to_C():
    temp=eval(input('Temperature in Fahrenheit '))
    result= float((temp-32)/1.8)
    print(temp, '°F are equivalent to ', result, '°C')
    print('----------------------------------------------------------------')
def mph_to_kph():
        mph=eval(input('Amount of Miles per hour: '))
        result= float(mph*1.609344)
        print(mph, 'Miles/Hour are equivalent to ', result, 'Kilometers/Hour')
        print('----------------------------------------------------------------')
def kph_to_mph():
        kph=eval(input('Amount of Kiometers per hour: '))
        result= float(kph*0.62137119)
        print(kph, 'Kilometers/Hour are equivalent to ', result, 'Miles/Hour')
        print('----------------------------------------------------------------')
def exit_function():
    print('Thanks for using the conversion program.')
    print('----------------------------------------------------------------')
    import sys
    sys.exit()

def menu():
    print('----------------------------------------------------------------')
    print('Welcome to the unit conversion program. Please select an option.')
    print('1. Miles to Kilometers')
    print('2. Kilometers to miles')
    print('3. Pounds to Kilograms')
    print('4. Kilograms to Pounds')
    print('5. Celsius to Fahrenheit')
    print('6. Fahrenheit to Celsius')
    print('7. Miles/hour to Kilometers/hour')
    print('8. Kilometers/hour to Miles/Hour')
    print('9. Exit')

screen=True

while screen:
    menu()
    choice=eval(input('Enter option: '))
    if choice==1:
        miles_to_km()
    elif choice==2:
        km_to_miles()
    elif choice==3:
        pounds_to_kg()
    elif choice==4:
        kg_to_pounds()
    elif choice==5:
        C_to_F()
    elif choice==6:
        F_to_C()
    elif choice==7:
        mph_to_kph()
    elif choice==8:
        kph_to_mph()
    elif choice==9:
        exit_function()
    else:
        print('Try a number between 1 and 9!')

Body:
you could convert the input with try statement.

while True:
    menu()
    choice = input('Enter option: ')
    try:
        choice = int(choice)
    except ValueError:
        print('invaild choice.')
        print('Try a number between 1 and 9!')
        continue
    if choice==1:
        miles_to_km()
    elif choice==2:
        km_to_miles()
    elif choice==3:
        pounds_to_kg()
    elif choice==4:
        kg_to_pounds()
    elif choice==5:
        C_to_F()
    elif choice==6:
        F_to_C()
    elif choice==7:
        mph_to_kph()
    elif choice==8:
        kph_to_mph()
    elif choice==9:
        exit_function()
    else:
        print('Try a number between 1 and 9!')


问:
How to update an HTML Table interactively upon selection of one of 4 form fields
I have an HTML page with a form and a table on it.
Using PHP, I would like to use a set of 4 of the form fields to build a mySql query to update the table in real time as the user selects any of the 4 fields.
The query should be built and executed upon the change of any of the 4 form fields.
Here is my code for the form fields:

```<code><form method="post" action="">
    <table cellspacing="0" border-width="1px" height= "28">
        <tr>
            <td class="style4" style="width: 160px">
                <strong>Location
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <select name="Location" style="width: 150px" onchange="SetQuery.php">
                <option hidden selected>Select a Location</option>
                <?php   while($record = mysql_fetch_array($myLocations)){
                            echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
                }
                ?>

                </select>
            </td>
            <td style="width: 59px">
        <tr>
            <td class="style4" style="width: 160px">
                <strong>Customer
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <input name="Customer" type="text" style="width: 150px" onchange="SetQuery.php">
            </td>
        </tr>

        <tr>
            <td class="style4" style="width: 160px">
                <strong>Family
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <input name="Family" type="text" style="width: 150px" onchange="SetQuery.php">
            </td>
        </tr>

        <tr>
            <td class="style4" style="width: 160px">
                <strong>Customer Part Number
            </strong>
            </td>
            <td class="style5" style="width: 150px">
                <input name="CustomerPartNumber" type="text" style="width: 150px" onchange="SetQuery.php">
            </td>
        </tr>
</code>```

I was thinking of using the onchange function to call a routine (I called it SetQuery.php) to build the query and update the table.
I do not know how to write the routine to update the table upon each selection of one of my 4 fields.

Here is my code to build the table initially. It is just a basic query to get all records just to get things going. In proper flow, the table will not populate until one of the 4 fields are chosen.

```<code><table border="1" cellspacing="1" cellpadding="1" style="font-size: xx-small">
<tr>
 <th><font face="Arial, Helvetica, sans-serif">Description</font></th>
 <th><font face="Arial, Helvetica, sans-serif">West Part Number</font></th>
 <th><font face="Arial, Helvetica, sans-serif">Cavities</font></th>
 <th><font face="Arial, Helvetica, sans-serif">Cycle Time</font></th>
 <th><font face="Arial, Helvetica, sans-serif">Material</font></th>
</tr>

<?php
$i=0;
while ($i < $num) {

?>

<tr>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,0); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,1); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,2); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,3); ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo mysql_result($result2,$i,4); ?></font></td>
</tr>

<?php
$i++;
}
?>
</table>
</td>
</tr>
</table>
</code>```

Can anyone help with this onchange routine? I need help in writing it and where to put it and how to call it.

Thanks,
Rich

答:
So far what i got, you have some field in the form, and one table, which will display the result according to number of field,
English is not the first language, so if any confusion let me know

Add onchange event with every input field which will call the javascript function, and that function will sent the value to the php file

```<code><input name="Your Field Name" onchange="setValue(this.value);">
</code>```

setValue is the name for the javascript function which going to set the value for you when ever it changes

if you dont know how to set it, read this link although link does not
  completly solve your problem but it will good for you know how to set
  the value,
  http:stackoverflow.comquestions22461324onchange-change-the-variable-in-php

than create ajax call, if you dont know just google it not every every hard thing to do.

Now comes to php file, as i told this code will only work, when you
  have one table

Now you also have to imagine these two cases, what you want to allow

First Case -- even if the user jump the field, you still want him to show the restult,
 what do i mean by that ? - for example lets say user type some thing, in the first field and than instead of typing some thing in the second and third field, he jumped to the fourth field now what you want you want to run the query according to the first field  and fourth field

Second Case -- You actually dont care, weather he jump or not you only going  to show the result, when he typed first and than he type second field and than third, like in a system basic shell work in both condition you dont have to do any thing,

Only one thing is important, instead of typing the query, we are going to create a query in a way that it depends on how many values are set, means we are going to Generate query according to the value which are set.

Before you go ahead keep this in mind, this is how normal sql query with AND LOOK LIKE

SELECT * FROM myTableName WHERE name = 'my name' AND street = 'this is
  my street'

just read the code and make sure you read the comment in the code as well.

and let's assume our variable names are $name, $address, $street and $qualification

```<code>$name='my name';
//$address='some where on earth';
$street='this is my street';
//$qualification='i am very much qualified';

//now create the array only with the values which are not empty,
//I am using empty with this example you can use any thing.
if(!empty($name)) $query_string_second_part[]=" AND name = '$name'";
if(!empty($address)) $query_string_second_part[]=" AND address = '$address'";
if(!empty($street)) $query_string_second_part[]=" AND street = '$street'";
if(!empty($qualification)) $query_string_second_part[]=" AND qualification = '$qualification'";

//hand type the first part for the query
$query_string_First_Part= "SELECT * FROM myTableName WHERE";
//Implode the array, if you want to see how it look like use echo,
$query_string_second_part= implode(" ", $query_string_second_part);
//as you can see we are adding AND with every value, so we need to remove the first
//with one space
//Make sure you give space in the second parameter. else it wont work means "" not correct but " " is correct
//Hint --> use one space in between the double qoutes
$query_string_second_part=  preg_replace("/AND/", " ", $query_string_second_part, 1);

//Join the first and second part together to create a full query
$query_string=$query_string_First_Part.$query_string_second_part;
echo ($query_string);//see how our query look like at the moment
</code>```

Body:
I have an HTML page with a form and a table on it.
Using PHP, I would like to use a set of 4 of the form fields to build a mySql query to update the table in real time as the user selects any of the 4 fields.
The query should be built and executed upon the change of any of the 4 form fields.
Here is my code for the form fields:

<form method="post" action="">

                Location

                <select name="Location" style="width: 150px" onchange="SetQuery.php">
                <option hidden selected>Select a Location</option>
                <?php   while($record = mysql_fetch_array($myLocations)){
                            echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
                }
                ?>

                </select>

                Customer

                <input name="Customer" type="text" style="width: 150px" onchange="SetQuery.php">

                Family

                <input name="Family" type="text" style="width: 150px" onchange="SetQuery.php">

                Customer Part Number

                <input name="CustomerPartNumber" type="text" style="width: 150px" onchange="SetQuery.php">

I was thinking of using the onchange function to call a routine (I called it SetQuery.php) to build the query and update the table.
I do not know how to write the routine to update the table upon each selection of one of my 4 fields.

Here is my code to build the table initially. It is just a basic query to get all records just to get things going. In proper flow, the table will not populate until one of the 4 fields are chosen.

 Description
 West Part Number
 Cavities
 Cycle Time
 Material

<?php
$i=0;
while ($i < $num) {

?>

<?php echo mysql_result($result2,$i,0); ?>
<?php echo mysql_result($result2,$i,1); ?>
<?php echo mysql_result($result2,$i,2); ?>
<?php echo mysql_result($result2,$i,3); ?>
<?php echo mysql_result($result2,$i,4); ?>

<?php
$i++;
}
?>

Can anyone help with this onchange routine? I need help in writing it and where to put it and how to call it.

Thanks,
Rich

Body:
So far what i got, you have some field in the form, and one table, which will display the result according to number of field,
English is not the first language, so if any confusion let me know

Add onchange event with every input field which will call the javascript function, and that function will sent the value to the php file

<input name="Your Field Name" onchange="setValue(this.value);">

setValue is the name for the javascript function which going to set the value for you when ever it changes

if you dont know how to set it, read this link although link does not
  completly solve your problem but it will good for you know how to set
  the value,
  http:stackoverflow.comquestions22461324onchange-change-the-variable-in-php

than create ajax call, if you dont know just google it not every every hard thing to do.

Now comes to php file, as i told this code will only work, when you
  have one table

Now you also have to imagine these two cases, what you want to allow

First Case -- even if the user jump the field, you still want him to show the restult,
 what do i mean by that ? - for example lets say user type some thing, in the first field and than instead of typing some thing in the second and third field, he jumped to the fourth field now what you want you want to run the query according to the first field  and fourth field

Second Case -- You actually dont care, weather he jump or not you only going  to show the result, when he typed first and than he type second field and than third, like in a system basic shell work in both condition you dont have to do any thing,

Only one thing is important, instead of typing the query, we are going to create a query in a way that it depends on how many values are set, means we are going to Generate query according to the value which are set.

Before you go ahead keep this in mind, this is how normal sql query with AND LOOK LIKE

SELECT * FROM myTableName WHERE name = 'my name' AND street = 'this is
  my street'

just read the code and make sure you read the comment in the code as well.

and let's assume our variable names are $name, $address, $street and $qualification

$name='my name';
//$address='some where on earth';
$street='this is my street';
//$qualification='i am very much qualified';

//now create the array only with the values which are not empty,
//I am using empty with this example you can use any thing.
if(!empty($name)) $query_string_second_part[]=" AND name = '$name'";
if(!empty($address)) $query_string_second_part[]=" AND address = '$address'";
if(!empty($street)) $query_string_second_part[]=" AND street = '$street'";
if(!empty($qualification)) $query_string_second_part[]=" AND qualification = '$qualification'";

//hand type the first part for the query
$query_string_First_Part= "SELECT * FROM myTableName WHERE";
//Implode the array, if you want to see how it look like use echo,
$query_string_second_part= implode(" ", $query_string_second_part);
//as you can see we are adding AND with every value, so we need to remove the first
//with one space
//Make sure you give space in the second parameter. else it wont work means "" not correct but " " is correct
//Hint --> use one space in between the double qoutes
$query_string_second_part=  preg_replace("/AND/", " ", $query_string_second_part, 1);

//Join the first and second part together to create a full query
$query_string=$query_string_First_Part.$query_string_second_part;
echo ($query_string);//see how our query look like at the moment


问:
What is the best way to generate ranks in MYSQL?
What's the best way to get the rank of the rows in addition to the row data in MYSQL?

For instance, say I have a list of students and I want to rank on the GPA. I know I can order by the GPA, but what's the quickest way to have MYSQL return the rank as well in the rowdata I get back?

答:
This will return the students' rank, student ID, and GPA.</p>

```<code>set @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, student_id, gpa
    FROM `students` ORDER BY gpa DESC
</code>```

Body:
This will return the students' rank, student ID, and GPA.

set @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, student_id, gpa
    FROM `students` ORDER BY gpa DESC

OwnerDisplayName: William Brendel


问:
What is the cost of using NULL in database columns?
I use MySQL and SQLite often and plan on bringing more PostgreSQL into my workflow soon. With that in mind, what are the costs of using NULL in each database? I heard that MySQL adds an extra bit to each NULL column value to mark it as nullable.</p>

答:
This question was answered separately for PostgreSQL:
How much disk-space is needed to store a NULL value using postgresql DB?

and for MySQL:
NULL in MySQL (Performance & Storage)

But to recap they both use bitmask fields to mark nulls.


问:
For loop skipping error
I would like get google trend data through a for loop. However, an error is holding me back. After searching through other stack questions I still cannot make it work. The loop in question:

```<code>a2p = for (i in dfurlnames$names1)
{
    x<- paste(i)
    gtrends_function3(x)
}
</code>```

In my for loop I get the following error:

```<code>Error : res$status_code == 200 is not TRUE
</code>```

I use the following packages and function:

Get the new gtrendsR; devtools::install_github('PMassicotte/gtrendsR')

```<code>library(gtrendsR)

gtrends_function3 <- function(x)
{
    trend1 = gtrends(c(x), geo = c(""), time = "2014-01-05 2014-10-04")
    trend_df1 = ldply(trend1)
    return(as.numeric(trend_df1$hits))
}
</code>```

The list:

```<code>dfurlnames$names1 = Ang babaeng humayo, The Bad Batch, Une vie, La La Land,
The Light Between Oceans, El ciudadano ilustre, Spira Mirabilis, La región
salvaje, Nocturnal Animals
</code>```

答:
Status code 200 refers to the HTTP protocol, indicating that everything went ok.  Probably, you are requesting things too fast in the for loop.  Add a sleep command, e.g.:

Sys.sleep(1)

in your for loop to slow things down.  Alternatively, use a tryCatch to bypass:

```<code>a2p = for (i in dfurlnames$names1)
{
    tryCatch({
       x<- paste(i)
       gtrends_function3(x)
    }, error=function(e) {print(e)})
}
</code>```

Title: For loop skipping error

Body:
I would like get google trend data through a for loop. However, an error is holding me back. After searching through other stack questions I still cannot make it work. The loop in question:

a2p = for (i in dfurlnames$names1)
{
    x<- paste(i)
    gtrends_function3(x)
}

In my for loop I get the following error:

Error : res$status_code == 200 is not TRUE

I use the following packages and function:

Get the new gtrendsR; devtools::install_github('PMassicotte/gtrendsR')

library(gtrendsR)

gtrends_function3 <- function(x)
{
    trend1 = gtrends(c(x), geo = c(""), time = "2014-01-05 2014-10-04")
    trend_df1 = ldply(trend1)
    return(as.numeric(trend_df1$hits))
}

The list:

dfurlnames$names1 = Ang babaeng humayo, The Bad Batch, Une vie, La La Land,
The Light Between Oceans, El ciudadano ilustre, Spira Mirabilis, La región
salvaje, Nocturnal Animals

Body:
Status code 200 refers to the HTTP protocol, indicating that everything went ok.  Probably, you are requesting things too fast in the for loop.  Add a sleep command, e.g.:

Sys.sleep(1)

in your for loop to slow things down.  Alternatively, use a tryCatch to bypass:

a2p = for (i in dfurlnames$names1)
{
    tryCatch({
       x<- paste(i)
       gtrends_function3(x)
    }, error=function(e) {print(e)})
}


问:
Corrupt double encoding with Portugese
I have a database that has a lot of corrupt entries, such as:

```<code>IVAM BENEDITO GONÃƒALVES DE QUEIROZ
</code>```

I have tried several encoding conversion to no avail. I've found other reports where by the characters Ãƒ should be Ã. However in this case Ãƒ should be Ç.

Does anyone have any idea how to successfully convert this? At current I am going through locating the problem characters and replacing the with REPLACE().

答:
Not sure of the specific problem, but these replacements fixed the data:</p>

```<code>UPDATE Brazil SET name = REPLACE( name, 'Ãƒ','ç' ) WHERE name LIKE '%Ãƒ%';
UPDATE Brazil SET name = REPLACE( name, 'Ã€','A ' ) WHERE name LIKE '%Ã€%';
UPDATE Brazil SET name = REPLACE( name, 'Â©','ú' ) WHERE name LIKE '%Â©%';
UPDATE Brazil SET name = REPLACE( name, 'â”œÃ¼','A' ) WHERE name LIKE '%â”œÃ¼%';
UPDATE Brazil SET name = REPLACE( name, 'â”œÃ©','A' ) WHERE name LIKE '%â”œÃ©%';
UPDATE Brazil SET name = REPLACE( name, 'Ã©','A' ) WHERE name LIKE '%Ã©%';
UPDATE Brazil SET name = REPLACE( name, 'Â±','é' ) WHERE name LIKE '%Â±%';
UPDATE Brazil SET name = REPLACE( name, 'Ãº','ú' ) WHERE name LIKE '%Ãº%';
UPDATE Brazil SET name = REPLACE( name, 'Âº','í' ) WHERE name LIKE '%Âº%';
UPDATE Brazil SET name = REPLACE( name, 'Â³','ú' ) WHERE name LIKE '%Â³%';
UPDATE Brazil SET name = REPLACE( name, 'Ã´','é' ) WHERE name LIKE '%Ã´%';
UPDATE Brazil SET name = REPLACE( name, 'Ã¶','ê' ) WHERE name LIKE '%Ã¶%';
UPDATE Brazil SET name = REPLACE( name, 'â”œÃ§','ç' ) WHERE name LIKE '%â”œÃ§%';
UPDATE Brazil SET name = REPLACE( name, 'Â¤','á' ) WHERE name LIKE '%Â¤%';
UPDATE Brazil SET name = REPLACE( name, 'ZÂ¡','á' ) WHERE name LIKE '%ZÂ¡%';
UPDATE Brazil SET name = REPLACE( name, 'Â¡','ó' ) WHERE name LIKE '%Â¡%';
UPDATE Brazil SET name = REPLACE( name, 'Ã½','ç' ) WHERE name LIKE '%Ã½%';
UPDATE Brazil SET name = REPLACE( name, 'â”¼','é' ) WHERE name LIKE '%â”¼%';
UPDATE Brazil SET name = REPLACE( name, 'Â¾','á' ) WHERE name LIKE '%Â¾%';
UPDATE Brazil SET name = REPLACE( name, 'Ã˜','ã' ) WHERE name LIKE '%Ã˜%';
UPDATE Brazil SET name = REPLACE( name, 'Ã˜','ã' ) WHERE name LIKE '%Ã˜%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‰','é' ) WHERE name LIKE '%Ã‰%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‡','ç' ) WHERE name LIKE '%Ã‡%';
UPDATE Brazil SET name = REPLACE( name, 'â•”','é' ) WHERE name LIKE '%â•”%';
UPDATE Brazil SET name = REPLACE( name, 'Ã•','ú' ) WHERE name LIKE '%Ã•%';
UPDATE Brazil SET name = REPLACE( name, 'â•','í' ) WHERE name LIKE '%â•%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‚Â¶','ã' ), name = REPLACE( name, 'Ã‚Âµ','á' ), name = REPLACE( name, 'Ã‚','' ) WHERE name LIKE '%Ã‚Â%';
UPDATE Brazil SET name = REPLACE( name, 'Âµ','ñ' ) WHERE name LIKE '%Âµ%';
UPDATE Brazil SET name = REPLACE( name, 'Ãœ','ü' ) WHERE name LIKE '%Ãœ%';
UPDATE Brazil SET name = REPLACE( name, 'â”œ','ã' ) WHERE name LIKE '%â”œ%';
UPDATE Brazil SET name = REPLACE( name, 'Ã«','ã' ) WHERE name LIKE '%Ã«%';
UPDATE Brazil SET name = REPLACE( name, 'Ã”','õ' ) WHERE name LIKE '%Ã”%';
UPDATE Brazil SET name = REPLACE( name, 'Â¨','ã' ) WHERE name LIKE '%Â¨%';
UPDATE Brazil SET name = REPLACE( name, 'ÃŒ','â' ) WHERE name LIKE '%ÃŒ%';
UPDATE Brazil SET name = REPLACE( name, 'Â°','é' ) WHERE name LIKE '%Â°%';
UPDATE Brazil SET name = REPLACE( name, 'Ã¦','í' ) WHERE name LIKE '%Ã¦%';
UPDATE Brazil SET name = REPLACE( name, 'Â¥','ú' ) WHERE name LIKE '%Â¥%';
UPDATE Brazil SET name = REPLACE( name, 'Â¿','ó' ) WHERE name LIKE '%Â¿%';
UPDATE Brazil SET name = REPLACE( name, 'Ã—','ç' ) WHERE name LIKE '%Ã—%';
UPDATE Brazil SET name = REPLACE( name, 'â”¬Ã‚','ã' ) WHERE name LIKE '%â”¬Ã‚%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‚','â' ) WHERE name LIKE '%Ã‚%';
UPDATE Brazil SET name = REPLACE( name, 'ãÃ¢','ã' ) WHERE name LIKE '%ãÃ¢%';
UPDATE Brazil SET name = REPLACE( name, 'ZÂ£','ã' ) WHERE name LIKE '%ZÂ£%';
UPDATE Brazil SET name = REPLACE( name, 'Â£','ú' ) WHERE name LIKE '%Â£%';
UPDATE Brazil SET name = REPLACE( name, 'ZÂ¢','ã' ) WHERE name LIKE '%ZÂ¢%';
UPDATE Brazil SET name = REPLACE( name, 'ãâ”‚','ó' ) WHERE name LIKE '%ãâ”‚%';
UPDATE Brazil SET name = REPLACE( name, 'ãÂ¢','ç' ) WHERE name LIKE '%ãÂ¢%';
UPDATE Brazil SET name = REPLACE( name, 'áâ”Â¢','ç' ) WHERE name LIKE '%áâ”Â¢%';
UPDATE Brazil SET name = REPLACE( name, 'â”¬â”‚','a ' ) WHERE name LIKE '%â”¬â”‚%';
UPDATE Brazil SET name = REPLACE( name, 'ç£','í' ) WHERE name LIKE '%ç£%';
UPDATE Brazil SET name = REPLACE( name, '¶','õ' ) WHERE name LIKE '%¶%';
UPDATE Brazil SET name = REPLACE( name, '§','ú' ) WHERE name LIKE '%§%';
UPDATE Brazil SET name = REPLACE( name, '¾','ó' ) WHERE name LIKE '%¾%';
UPDATE Brazil SET name = REPLACE( name, 'Ã','ç' ) WHERE name LIKE '%Ã%';
</code>```

Title: Corrupt double encoding with Portugese

Body:
I have a database that has a lot of corrupt entries, such as:

IVAM BENEDITO GONÃƒALVES DE QUEIROZ

I have tried several encoding conversion to no avail. I've found other reports where by the characters Ãƒ should be Ã. However in this case Ãƒ should be Ç.

Does anyone have any idea how to successfully convert this? At current I am going through locating the problem characters and replacing the with REPLACE().

Body:
Not sure of the specific problem, but these replacements fixed the data:

UPDATE Brazil SET name = REPLACE( name, 'Ãƒ','ç' ) WHERE name LIKE '%Ãƒ%';
UPDATE Brazil SET name = REPLACE( name, 'Ã€','A ' ) WHERE name LIKE '%Ã€%';
UPDATE Brazil SET name = REPLACE( name, 'Â©','ú' ) WHERE name LIKE '%Â©%';
UPDATE Brazil SET name = REPLACE( name, 'â”œÃ¼','A' ) WHERE name LIKE '%â”œÃ¼%';
UPDATE Brazil SET name = REPLACE( name, 'â”œÃ©','A' ) WHERE name LIKE '%â”œÃ©%';
UPDATE Brazil SET name = REPLACE( name, 'Ã©','A' ) WHERE name LIKE '%Ã©%';
UPDATE Brazil SET name = REPLACE( name, 'Â±','é' ) WHERE name LIKE '%Â±%';
UPDATE Brazil SET name = REPLACE( name, 'Ãº','ú' ) WHERE name LIKE '%Ãº%';
UPDATE Brazil SET name = REPLACE( name, 'Âº','í' ) WHERE name LIKE '%Âº%';
UPDATE Brazil SET name = REPLACE( name, 'Â³','ú' ) WHERE name LIKE '%Â³%';
UPDATE Brazil SET name = REPLACE( name, 'Ã´','é' ) WHERE name LIKE '%Ã´%';
UPDATE Brazil SET name = REPLACE( name, 'Ã¶','ê' ) WHERE name LIKE '%Ã¶%';
UPDATE Brazil SET name = REPLACE( name, 'â”œÃ§','ç' ) WHERE name LIKE '%â”œÃ§%';
UPDATE Brazil SET name = REPLACE( name, 'Â¤','á' ) WHERE name LIKE '%Â¤%';
UPDATE Brazil SET name = REPLACE( name, 'ZÂ¡','á' ) WHERE name LIKE '%ZÂ¡%';
UPDATE Brazil SET name = REPLACE( name, 'Â¡','ó' ) WHERE name LIKE '%Â¡%';
UPDATE Brazil SET name = REPLACE( name, 'Ã½','ç' ) WHERE name LIKE '%Ã½%';
UPDATE Brazil SET name = REPLACE( name, 'â”¼','é' ) WHERE name LIKE '%â”¼%';
UPDATE Brazil SET name = REPLACE( name, 'Â¾','á' ) WHERE name LIKE '%Â¾%';
UPDATE Brazil SET name = REPLACE( name, 'Ã˜','ã' ) WHERE name LIKE '%Ã˜%';
UPDATE Brazil SET name = REPLACE( name, 'Ã˜','ã' ) WHERE name LIKE '%Ã˜%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‰','é' ) WHERE name LIKE '%Ã‰%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‡','ç' ) WHERE name LIKE '%Ã‡%';
UPDATE Brazil SET name = REPLACE( name, 'â•”','é' ) WHERE name LIKE '%â•”%';
UPDATE Brazil SET name = REPLACE( name, 'Ã•','ú' ) WHERE name LIKE '%Ã•%';
UPDATE Brazil SET name = REPLACE( name, 'â•','í' ) WHERE name LIKE '%â•%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‚Â¶','ã' ), name = REPLACE( name, 'Ã‚Âµ','á' ), name = REPLACE( name, 'Ã‚','' ) WHERE name LIKE '%Ã‚Â%';
UPDATE Brazil SET name = REPLACE( name, 'Âµ','ñ' ) WHERE name LIKE '%Âµ%';
UPDATE Brazil SET name = REPLACE( name, 'Ãœ','ü' ) WHERE name LIKE '%Ãœ%';
UPDATE Brazil SET name = REPLACE( name, 'â”œ','ã' ) WHERE name LIKE '%â”œ%';
UPDATE Brazil SET name = REPLACE( name, 'Ã«','ã' ) WHERE name LIKE '%Ã«%';
UPDATE Brazil SET name = REPLACE( name, 'Ã”','õ' ) WHERE name LIKE '%Ã”%';
UPDATE Brazil SET name = REPLACE( name, 'Â¨','ã' ) WHERE name LIKE '%Â¨%';
UPDATE Brazil SET name = REPLACE( name, 'ÃŒ','â' ) WHERE name LIKE '%ÃŒ%';
UPDATE Brazil SET name = REPLACE( name, 'Â°','é' ) WHERE name LIKE '%Â°%';
UPDATE Brazil SET name = REPLACE( name, 'Ã¦','í' ) WHERE name LIKE '%Ã¦%';
UPDATE Brazil SET name = REPLACE( name, 'Â¥','ú' ) WHERE name LIKE '%Â¥%';
UPDATE Brazil SET name = REPLACE( name, 'Â¿','ó' ) WHERE name LIKE '%Â¿%';
UPDATE Brazil SET name = REPLACE( name, 'Ã—','ç' ) WHERE name LIKE '%Ã—%';
UPDATE Brazil SET name = REPLACE( name, 'â”¬Ã‚','ã' ) WHERE name LIKE '%â”¬Ã‚%';
UPDATE Brazil SET name = REPLACE( name, 'Ã‚','â' ) WHERE name LIKE '%Ã‚%';
UPDATE Brazil SET name = REPLACE( name, 'ãÃ¢','ã' ) WHERE name LIKE '%ãÃ¢%';
UPDATE Brazil SET name = REPLACE( name, 'ZÂ£','ã' ) WHERE name LIKE '%ZÂ£%';
UPDATE Brazil SET name = REPLACE( name, 'Â£','ú' ) WHERE name LIKE '%Â£%';
UPDATE Brazil SET name = REPLACE( name, 'ZÂ¢','ã' ) WHERE name LIKE '%ZÂ¢%';
UPDATE Brazil SET name = REPLACE( name, 'ãâ”‚','ó' ) WHERE name LIKE '%ãâ”‚%';
UPDATE Brazil SET name = REPLACE( name, 'ãÂ¢','ç' ) WHERE name LIKE '%ãÂ¢%';
UPDATE Brazil SET name = REPLACE( name, 'áâ”Â¢','ç' ) WHERE name LIKE '%áâ”Â¢%';
UPDATE Brazil SET name = REPLACE( name, 'â”¬â”‚','a ' ) WHERE name LIKE '%â”¬â”‚%';
UPDATE Brazil SET name = REPLACE( name, 'ç£','í' ) WHERE name LIKE '%ç£%';
UPDATE Brazil SET name = REPLACE( name, '¶','õ' ) WHERE name LIKE '%¶%';
UPDATE Brazil SET name = REPLACE( name, '§','ú' ) WHERE name LIKE '%§%';
UPDATE Brazil SET name = REPLACE( name, '¾','ó' ) WHERE name LIKE '%¾%';
UPDATE Brazil SET name = REPLACE( name, 'Ã','ç' ) WHERE name LIKE '%Ã%';


问:
Doubly Linked List Problems (specifically copy constructor and delete function)
I posted this same post to Reddit, but it is not getting any comments, so I've decided to see if I can get some help here.

My current project we are given a doubly linked list .h file and a .cpp file, and we need to implement the .h in the .cpp. I am really struggling with linked lists though, I feel as though even the things i have right or kinda right are sloppy and don't fulfill the full requirements. Here is the .h file:

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

struct Node{
    string ssn;
    string name;
    Node* succ;
    Node* pred;
};

class DLL{
    private:
    Node* headPtr;
    int itemCount;

    public:
    DLL();
    DLL(DLL& n);
    virtual ~DLL();
    Node* getHeadPtr();
    int search(string ss)const;
    bool insert(string ss, string name, int & count);
    bool remove(string ss, int & count);
    int size();
    void display();
};
</code>```

And here is the .cpp file:

```<code>#include "DLL.h"
#include <iostream>
#include <string>
using namespace std;

// default constructor is already implemented
// do not modify the default constructor
DLL::DLL(){
    headPtr = nullptr;
    itemCount=0;
}

// return the head pointer of the list
// it is already implemented, do not modify it
Node* DLL::getHeadPtr(){
    return headPtr;
}

// copy construct, which copies an existing list n
// the new list is a different object from n
// the new list and object n have the same contents
// Please implement it
DLL::DLL(DLL& n){
        /*Node *first = n.getHeadPtr();
    first = headPtr;
    while(headPtr->succ)
        headPtr = headPtr->succ;
    while(headPtr){
        first->succ = headPtr->succ;
        headPtr->succ = headPtr->succ->succ;
    }*/
}

// destructor
// release every node of the list
// Please implement it
DLL::~DLL(){
    Node *tmp = this->headPtr;
    Node *temp;
    while(tmp->pred)
        tmp = tmp->pred;
    while(tmp)
    {
        temp = tmp->succ;
        delete tmp;
        tmp = temp;
    }
    tmp =NULL;
    temp = NULL;
}

// if some node has SSN matcthes string ss
// return the index value of the node
// the index value of the first node is 0, the second node is 1, etc.
// if there is node matching ss, return -1
int DLL::search(string ss)const{
    int count = 0;
    Node *tmp = headPtr;
    while(tmp != NULL){
        count++;
    if(tmp->ssn == ss)
      return count -1;
    tmp = tmp->succ;
  }
    return NULL;
}

// insert (ss, name) to the existing list
// the SSN values are each node are organized in INCREASING order
// if there is a node matching ss value, return false; otherwise true
// else create a node with (ss, name), insert the node to the proper position
// parameter count is the counter of number of valid insertion
// when you implement this method, consider the following situations:
// 1. list is empty
// 2. node should be inserted to the beginning of the list
// 3. node should be inserted to the middle of the list
// 4. node should be inserted to the end of the list
//I use the append function, then sort afterwards
bool DLL::insert(string ss, string name, int & count){
   //Create Node
   Node *newPtr = new Node;
   newPtr->ssn = ss;
   newPtr->succ = NULL;
   //If list is empty
   if(headPtr == NULL){
        headPtr = newPtr;
        return true;
   }
   //If list is not empty
   else{
        Node* temp = headPtr;
        while(temp->succ != NULL){
            temp = temp->succ;
            itemCount++;
            count++;
        }
    temp->succ = newPtr;
    //Following part is to sort from least to greatest (based on Lab 7)
    //Store head to temp node
    temp = headPtr;
    string tempVal;
    int counter = 0;
    //Set temp to next, increase count
    while (temp){
        temp = temp->succ;
        counter++;
    }
    //Make temp head again
    temp = headPtr;
    //While less than count and has next node, check if val at temp is greater than val at next
    for (int j=0; j<count; j++){
        while (temp->succ){
            if (temp->ssn > temp->succ->ssn ){
                //Store val at temp to temp val
                tempVal = temp->ssn ;
                //Make temp's val the value at temp->next
                temp->ssn  = temp->succ->ssn;
                //Make temp->next's val, temp's old val
                temp->succ->ssn  = tempVal;
            }
            //Make temp the next value and check again
            temp = temp->succ;
        }
        //Move temp back to head
        temp = headPtr;
    }
    return true;
   }
    return false;
}

// remove node containing ss value
// if there is no node containing ss, return false; otherwise true
// consider the following situations:
// 1. list is empty
// 2. node containing ss value is the first node
// 3. node containing ss value is in the middle of the list
// 4. node containing ss value is the last node of the list
bool DLL::remove(string ss, int & count){
    /*Node *temp = headPtr;
    while(temp){
        if(temp->ssn == ss){
            temp->pred->succ = temp->succ;
            temp->succ->pred = temp->pred;
            count++;
            return true;
        }
        temp = temp->succ;

    }
    return false;*/
}

// return the number of the nodes
// it is already implemented, do not modify it
int DLL::size(){
    return itemCount;
}

// iterate through each node
// print out SSN and memory address of each node
// do not modify this method
void DLL::display(){
    Node* temp;
    temp = headPtr;
    while (temp!= nullptr) {
        cout << temp->ssn << "\t" << temp << endl;
        temp = temp->succ;
    }
}
</code>```

I think my search function is fine, and the functions with comments that say don't modify are made by the professor so they are fine, and the .h file is fine because it was also included. I am really struggling with the copy constructor and delete function though. The current contents of my delete function are commented out because the test.exe crashes everytime it reaches it. Then the copy constructor I am just all around lost, I've done a lot of research and read other posts, but I just can't figure it out. I have mine commented out because the program crashes everytime it reaches that function, like with the remove function. My insert function is supposed to insert everything in order and not insert it if it was already inserted, mine appends every item to the list then sorts them afterwards into order, never checking if the SSN was already in or not. It works, but obviously not fully. Any advice at all would be very helpful because as you can tell I struggling a lot with doubly linked list. Thank you in advance.

答:
It seems you have a problem with null pointer in the constructor

```<code>    /*Node *first = n.getHeadPtr();
first = headPtr;
while(headPtr->succ)
</code>```

Here headPtr is a nullptr and hence headPtr->succ raises a runtime error.

Body:
I posted this same post to Reddit, but it is not getting any comments, so I've decided to see if I can get some help here.

My current project we are given a doubly linked list .h file and a .cpp file, and we need to implement the .h in the .cpp. I am really struggling with linked lists though, I feel as though even the things i have right or kinda right are sloppy and don't fulfill the full requirements. Here is the .h file:

#include <string>
using namespace std;

struct Node{
    string ssn;
    string name;
    Node* succ;
    Node* pred;
};

class DLL{
    private:
    Node* headPtr;
    int itemCount;

    public:
    DLL();
    DLL(DLL& n);
    virtual ~DLL();
    Node* getHeadPtr();
    int search(string ss)const;
    bool insert(string ss, string name, int & count);
    bool remove(string ss, int & count);
    int size();
    void display();
};

And here is the .cpp file:

#include "DLL.h"
#include <iostream>
#include <string>
using namespace std;

// default constructor is already implemented
// do not modify the default constructor
DLL::DLL(){
    headPtr = nullptr;
    itemCount=0;
}

// return the head pointer of the list
// it is already implemented, do not modify it
Node* DLL::getHeadPtr(){
    return headPtr;
}

// copy construct, which copies an existing list n
// the new list is a different object from n
// the new list and object n have the same contents
// Please implement it
DLL::DLL(DLL& n){
        /*Node *first = n.getHeadPtr();
    first = headPtr;
    while(headPtr->succ)
        headPtr = headPtr->succ;
    while(headPtr){
        first->succ = headPtr->succ;
        headPtr->succ = headPtr->succ->succ;
    }*/
}

// destructor
// release every node of the list
// Please implement it
DLL::~DLL(){
    Node *tmp = this->headPtr;
    Node *temp;
    while(tmp->pred)
        tmp = tmp->pred;
    while(tmp)
    {
        temp = tmp->succ;
        delete tmp;
        tmp = temp;
    }
    tmp =NULL;
    temp = NULL;
}

// if some node has SSN matcthes string ss
// return the index value of the node
// the index value of the first node is 0, the second node is 1, etc.
// if there is node matching ss, return -1
int DLL::search(string ss)const{
    int count = 0;
    Node *tmp = headPtr;
    while(tmp != NULL){
        count++;
    if(tmp->ssn == ss)
      return count -1;
    tmp = tmp->succ;
  }
    return NULL;
}

// insert (ss, name) to the existing list
// the SSN values are each node are organized in INCREASING order
// if there is a node matching ss value, return false; otherwise true
// else create a node with (ss, name), insert the node to the proper position
// parameter count is the counter of number of valid insertion
// when you implement this method, consider the following situations:
// 1. list is empty
// 2. node should be inserted to the beginning of the list
// 3. node should be inserted to the middle of the list
// 4. node should be inserted to the end of the list
//I use the append function, then sort afterwards
bool DLL::insert(string ss, string name, int & count){
   //Create Node
   Node *newPtr = new Node;
   newPtr->ssn = ss;
   newPtr->succ = NULL;
   //If list is empty
   if(headPtr == NULL){
        headPtr = newPtr;
        return true;
   }
   //If list is not empty
   else{
        Node* temp = headPtr;
        while(temp->succ != NULL){
            temp = temp->succ;
            itemCount++;
            count++;
        }
    temp->succ = newPtr;
    //Following part is to sort from least to greatest (based on Lab 7)
    //Store head to temp node
    temp = headPtr;
    string tempVal;
    int counter = 0;
    //Set temp to next, increase count
    while (temp){
        temp = temp->succ;
        counter++;
    }
    //Make temp head again
    temp = headPtr;
    //While less than count and has next node, check if val at temp is greater than val at next
    for (int j=0; j<count; j++){
        while (temp->succ){
            if (temp->ssn > temp->succ->ssn ){
                //Store val at temp to temp val
                tempVal = temp->ssn ;
                //Make temp's val the value at temp->next
                temp->ssn  = temp->succ->ssn;
                //Make temp->next's val, temp's old val
                temp->succ->ssn  = tempVal;
            }
            //Make temp the next value and check again
            temp = temp->succ;
        }
        //Move temp back to head
        temp = headPtr;
    }
    return true;
   }
    return false;
}

// remove node containing ss value
// if there is no node containing ss, return false; otherwise true
// consider the following situations:
// 1. list is empty
// 2. node containing ss value is the first node
// 3. node containing ss value is in the middle of the list
// 4. node containing ss value is the last node of the list
bool DLL::remove(string ss, int & count){
    /*Node *temp = headPtr;
    while(temp){
        if(temp->ssn == ss){
            temp->pred->succ = temp->succ;
            temp->succ->pred = temp->pred;
            count++;
            return true;
        }
        temp = temp->succ;

    }
    return false;*/
}

// return the number of the nodes
// it is already implemented, do not modify it
int DLL::size(){
    return itemCount;
}

// iterate through each node
// print out SSN and memory address of each node
// do not modify this method
void DLL::display(){
    Node* temp;
    temp = headPtr;
    while (temp!= nullptr) {
        cout << temp->ssn << "\t" << temp << endl;
        temp = temp->succ;
    }
}

I think my search function is fine, and the functions with comments that say don't modify are made by the professor so they are fine, and the .h file is fine because it was also included. I am really struggling with the copy constructor and delete function though. The current contents of my delete function are commented out because the test.exe crashes everytime it reaches it. Then the copy constructor I am just all around lost, I've done a lot of research and read other posts, but I just can't figure it out. I have mine commented out because the program crashes everytime it reaches that function, like with the remove function. My insert function is supposed to insert everything in order and not insert it if it was already inserted, mine appends every item to the list then sorts them afterwards into order, never checking if the SSN was already in or not. It works, but obviously not fully. Any advice at all would be very helpful because as you can tell I struggling a lot with doubly linked list. Thank you in advance.

Body:
It seems you have a problem with null pointer in the constructor

    /*Node *first = n.getHeadPtr();
first = headPtr;
while(headPtr->succ)

Here headPtr is a nullptr and hence headPtr->succ raises a runtime error.


问:
PayPal Recurring Payments with express checkout - 10 payment profiles limitation
I have a question about recurring payments using PayPal express checkout. On the PayPal developer documentation the recurring payment page states:

To be able to create a recurring payments profile for the buyer, you
must ensure that the buyer's PayPal account includes an active credit
card.

You can create a maximum of 10 recurring payments profiles
during checkout.

You can increase the profile amount by only 20% in
each 180-day interval after you create the profile.

This previous response (PayPal Recurring Payments with express checkout limitations: What does that means 10 recurring payments profiles during checkout? 10 profiles totally or 10 profiles at once? 10 at one time. Assuming that you can get the buyer to agree to it, you can set up any number of recurring payments profiles with a single buyer, but you'd have to send them back to PayPal multiple times to approve all of them.

When and how would the PayPal user be prompted to re-authorize additional recurring payments (beyond the initial 10)?

答:
Christi,

I've set up recurring payments with Paypal before. If you get 1000 customers in a day, it will set up 1000 profiles, 1 per each of those customers. They will continue to be billed indefinitely for an endless subscription. I believe the 10 different profiles is per customer if they are buying multiple subscription items at once, I'm not a 100% sure on this, as I only sold 1 subscription product at a time.

Once the profile is created, you can raise your prices by 20% every 180 days. The customer does not have to approve it, however if you raise your prices they will get an email, letting them know about the increase. The customer will then have to make a decision, "do nothing" and the price sticks. Or cancel the subscription.


问:
What does Python socket error no 52 (Invalid Exchange) refer to?
I'm trying to set up a Bluetooth link between a Raspberry Pi and an Arduino (Megapi). These are both mounted on a robot for a wireless robotics project. While running the Bluetooth server/listener on the Pi, I get the Invalid Exchange socket error. The troublesome code is shown below-

```<code>    self.host = "00:0D:19:EA:28:52"
    self.port = 3
    self.sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
    self.sock.connect((self.host, self.port))
</code>```

The fourth line is where the error pops up-

```<code>File "Client.py", line 21, in __init__
  self.sock.connect((self.host, self.port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
  return getattr(self._sock,name)(*args)
socket.error: [Errno 52] Invalid exchange
</code>```

Unfortunately, there appears to be very little documentation on socket errors available on the internet, other than one/two word descriptions of what the error codes mean. I was hoping you can help!

答: https://github.com/torvalds/linux/blob/v4.10/net/bluetooth/lib.c#L68 translates Bluetooth errors into C errnos. EBADE (errno 52) is mapped to Bluetooth error code 0x06, defined as "Key Missing".</p>

Body:
I'm trying to set up a Bluetooth link between a Raspberry Pi and an Arduino (Megapi). These are both mounted on a robot for a wireless robotics project. While running the Bluetooth server/listener on the Pi, I get the Invalid Exchange socket error. The troublesome code is shown below-

    self.host = "00:0D:19:EA:28:52"
    self.port = 3
    self.sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
    self.sock.connect((self.host, self.port))

The fourth line is where the error pops up-

File "Client.py", line 21, in __init__
  self.sock.connect((self.host, self.port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
  return getattr(self._sock,name)(*args)
socket.error: [Errno 52] Invalid exchange

Unfortunately, there appears to be very little documentation on socket errors available on the internet, other than one/two word descriptions of what the error codes mean. I was hoping you can help!