问:
how to call handler within asyncTask
```<code>class GET_DOC_CONTACT_DELAY_TIME extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(PdfView.this);
            pDialog.setMessage("Processing...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("dhw_gp_id",String.valueOf(Login.reg_id)));
            params.add(new BasicNameValuePair("dreg_id",String.valueOf(E_patId)));
            params.add(new BasicNameValuePair("dslno",String.valueOf(E_slno)));
            params.add(new BasicNameValuePair("ddos",String.valueOf(dosString)));
            params.add(new BasicNameValuePair("ddocid",String.valueOf(doc_id)));
            params.add(new BasicNameValuePair("dimei",String.valueOf(Login.imei)));

            JSONObject json = jsonParser.makeHttpRequest(DOC_SMS, "POST", params);

            final String dm = doc_contaclist.get(current_doc).get("vdocmobile");
            final String delay = doc_contaclist.get(current_doc).get("vdoctime");

            // check for success tag
            try {
                 rsuccess = json.getInt(TAG_RMSUCCESS);

                if (rsuccess == 1) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            final String message = "Patient "  + patFirstName + " " + patLastName +" with Id : "+ E_patId + "\n"+" is having an emergency and needs diagnosis immediately,";
                            SmsManager.getDefault().sendTextMessage(String.valueOf(dm), null,message, null, null);

                            new AlertDialog.Builder(PdfView.this)
                                    .setTitle("Confirmation Message")
                                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            Intent i = new Intent(PdfView.this,Patient_Register.class);
                                            i.putExtra("clear_text",status_info);
                                            startActivity(i);
                                        }
                                    })
                                    .setMessage("ECG Sent to Doctor")
                                    .setIcon(R.drawable.alert1)
                                    .show();

                        }
                    });
                } else if (rsuccess == 0) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Required fields missing", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 2) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Database selection failed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 3) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Failed to insert", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 4) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            current_doc++ ;

                             Toast toast = Toast.makeText(PdfView.this, "SMS to next doctor", Toast.LENGTH_SHORT);
                             toast.setGravity(Gravity.CENTER,0,0);
                             toast.show();

                       }
                   });
                }  else if (rsuccess == 5) {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            loop_exit= true;

                            Toast toast = Toast.makeText(PdfView.this, "Processed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }

          Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Send_sms();
            }
       }, 20000);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            if ((pDialog != null) && pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
    }
</code>```

Trying to call handler inside asyncTask method but its throwing the error (application crahing). This handler should be called with a delay of 1 min or 2mins. Tried with multiple methods.  Anybody pls help me out in calling handler inside asynctask.

答:
Make sure you create your Handler outside of the AsyncTask, maybe in the Activity or Fragment you're starting the Task. You can pass the Handler as a parameter to the AsyncTask.
With this way the handler is bound to the MainThread and can even post changes on the UI-Thread.

Title: how to call handler within asyncTask

Body:
class GET_DOC_CONTACT_DELAY_TIME extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(PdfView.this);
            pDialog.setMessage("Processing...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("dhw_gp_id",String.valueOf(Login.reg_id)));
            params.add(new BasicNameValuePair("dreg_id",String.valueOf(E_patId)));
            params.add(new BasicNameValuePair("dslno",String.valueOf(E_slno)));
            params.add(new BasicNameValuePair("ddos",String.valueOf(dosString)));
            params.add(new BasicNameValuePair("ddocid",String.valueOf(doc_id)));
            params.add(new BasicNameValuePair("dimei",String.valueOf(Login.imei)));

            JSONObject json = jsonParser.makeHttpRequest(DOC_SMS, "POST", params);

            final String dm = doc_contaclist.get(current_doc).get("vdocmobile");
            final String delay = doc_contaclist.get(current_doc).get("vdoctime");

            // check for success tag
            try {
                 rsuccess = json.getInt(TAG_RMSUCCESS);

                if (rsuccess == 1) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            final String message = "Patient "  + patFirstName + " " + patLastName +" with Id : "+ E_patId + "\n"+" is having an emergency and needs diagnosis immediately,";
                            SmsManager.getDefault().sendTextMessage(String.valueOf(dm), null,message, null, null);

                            new AlertDialog.Builder(PdfView.this)
                                    .setTitle("Confirmation Message")
                                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            Intent i = new Intent(PdfView.this,Patient_Register.class);
                                            i.putExtra("clear_text",status_info);
                                            startActivity(i);
                                        }
                                    })
                                    .setMessage("ECG Sent to Doctor")
                                    .setIcon(R.drawable.alert1)
                                    .show();

                        }
                    });
                } else if (rsuccess == 0) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Required fields missing", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 2) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Database selection failed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 3) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast toast = Toast.makeText(PdfView.this, "Failed to insert", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }else if (rsuccess == 4) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            current_doc++ ;

                             Toast toast = Toast.makeText(PdfView.this, "SMS to next doctor", Toast.LENGTH_SHORT);
                             toast.setGravity(Gravity.CENTER,0,0);
                             toast.show();

                       }
                   });
                }  else if (rsuccess == 5) {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            loop_exit= true;

                            Toast toast = Toast.makeText(PdfView.this, "Processed", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER,0,0);
                            toast.show();

                        }
                    });
                }

          Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Send_sms();
            }
       }, 20000);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            if ((pDialog != null) && pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
    }

Trying to call handler inside asyncTask method but its throwing the error (application crahing). This handler should be called with a delay of 1 min or 2mins. Tried with multiple methods.  Anybody pls help me out in calling handler inside asynctask.


来源: stackexchange

问:
Git cherry-pick ,can't find "<<<<<HEAD" marker in conflict files
I met a problem when I cherry-pick a commit on my branch. Below is what I did:

```<code>$ git cherry-pick  50658
$ git status
</code>```

Error messages:

```<code>Not currently on any branch.
You are currently cherry-picking commit 5065872.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:      drivers/media/dvb-core/dvb_frontend.c
</code>```

But when I input git diff. It tells below :

```<code>diff --cc drivers/media/dvb-core/dvb_frontend.c
index 7023d5f,72fc718..0000000
--- a/drivers/media/dvb-core/dvb_frontend.c
+++ b/drivers/media/dvb-core/dvb_frontend.c
</code>```

I didn't find any conflict massage, as <<<<<<HEAD in dvb_frontend.c files. Why it tells conflicts exiting ?

答:
When you are in the middle of a conflict; you should not use git diff; you should use any editor you like to resolve the conflicts, then

```<code>git add <filename>
</code>```

at that moment you can use

```<code>git diff --cached
</code>```

to see what your final commit will actually look like. When that is ok for you; you can use

```<code>git cherry-pick --continue
</code>```

to finalize the commit you are cherry-picking.

ContentLicense: CC BY-SA 3.0

Body:
I met a problem when I cherry-pick a commit on my branch. Below is what I did:

$ git cherry-pick  50658
$ git status

Error messages:

Not currently on any branch.
You are currently cherry-picking commit 5065872.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:      drivers/media/dvb-core/dvb_frontend.c

But when I input git diff. It tells below :

diff --cc drivers/media/dvb-core/dvb_frontend.c
index 7023d5f,72fc718..0000000
--- a/drivers/media/dvb-core/dvb_frontend.c
+++ b/drivers/media/dvb-core/dvb_frontend.c

I didn't find any conflict massage, as <<<<<<HEAD in dvb_frontend.c files. Why it tells conflicts exiting ?

Body:
When you are in the middle of a conflict; you should not use git diff; you should use any editor you like to resolve the conflicts, then

git add <filename>

at that moment you can use

git diff --cached

to see what your final commit will actually look like. When that is ok for you; you can use

git cherry-pick --continue

to finalize the commit you are cherry-picking.


问:
pandas: New column by combining numbers of two columns as strings
I want to combine the two columns 'Day/Night?' and 'Abbreviated' as strings to get another column that displays the numbers in the form of the 'Abbreviated' value, followed by the 'Day/Night?' value.

The DataFrame I currently have:

```<code>    Route       Date        Collection Type Tonnage Day/Night?  Abbreviated
0   321-2_2     2014-07-11  2               12.96   2           1107
0   325-1_1     2014-07-14  1               1.85    1           1407
1   321-323_2   2014-07-14  1               4.42    2           1407
1   325-2_1     2014-07-15  3               13.20   1           1507
2   321-2_2     2014-07-15  1               3.25    2           1507
</code>```

For example, I would have the extra column output as:

```<code>11072
14071
14072
15071
15072
</code>```

I have tried this code:

```<code>daily['New'] = daily['Abbreviated']+str(daily['Day/Night?'])
</code>```

where Daily is the name of the DF.

The output is strange though:

```<code>New
11070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...
</code>```

Does anyone have any advice on how I could do this?

thanks.

Body:
I want to combine the two columns 'Day/Night?' and 'Abbreviated' as strings to get another column that displays the numbers in the form of the 'Abbreviated' value, followed by the 'Day/Night?' value.

The DataFrame I currently have:

    Route       Date        Collection Type Tonnage Day/Night?  Abbreviated
0   321-2_2     2014-07-11  2               12.96   2           1107
0   325-1_1     2014-07-14  1               1.85    1           1407
1   321-323_2   2014-07-14  1               4.42    2           1407
1   325-2_1     2014-07-15  3               13.20   1           1507
2   321-2_2     2014-07-15  1               3.25    2           1507

For example, I would have the extra column output as:

11072
14071
14072
15071
15072

I have tried this code:

daily['New'] = daily['Abbreviated']+str(daily['Day/Night?'])

where Daily is the name of the DF.

The output is strange though:

New
11070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
14070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...
15070 2\n0 1\n1 2\n1 1\n2 ...

Does anyone have any advice on how I could do this?

thanks.

Body:
cols = ['Abbreviated', 'Day/Night?']
df.assign(New=df[cols].astype(str).apply(''.join, 1))

   Route       Date  Collection  Type  Tonnage  Day/Night?  Abbreviated    New
0      0    321-2_2  2014-07-11     2    12.96           2         1107  11072
1      0    325-1_1  2014-07-14     1     1.85           1         1407  14071
2      1  321-323_2  2014-07-14     1     4.42           2         1407  14072
3      1    325-2_1  2014-07-15     3    13.20           1         1507  15071
4      2    321-2_2  2014-07-15     1     3.25           2         1507  15072


问:
Open terminal here in Mac OS finder
Is there something similar to the "Open Command Window Here" Windows Powertoy for Mac OS? I've found a couple plugins through a google search but wanted to see what works best for developers out there.</p>

答:
If you install Big Cat Scripts (http://www.ranchero.com/bigcat/) you can add your own contextual menu (right click) items.  I don't think it comes with an Open Terminal Here applescript but I use this script (which I don't honestly remember if I wrote myself, or lifted from someone else's example):

```<code>on main(filelist)
    tell application "Finder"
        try
            activate
            set frontWin to folder of front window as string
            set frontWinPath to (get POSIX path of frontWin)
            tell application "Terminal"
                activate
                do script with command "cd \"" & frontWinPath & "\""
            end tell
        on error error_message
            beep
            display dialog error_message buttons ¬
                {"OK"} default button 1
        end try
    end tell
end main
</code>```

Similar scripts can also get you the complete path to a file on right-click, which is even more useful, I find.

OwnerDisplayName: Abdullah Jibaly

ContentLicense: CC BY-SA 2.5

Title: Open terminal here in Mac OS finder

LastEditorDisplayName: sblundy

Body:
If you install Big Cat Scripts (http://www.ranchero.com/bigcat/) you can add your own contextual menu (right click) items.  I don't think it comes with an Open Terminal Here applescript but I use this script (which I don't honestly remember if I wrote myself, or lifted from someone else's example):

on main(filelist)
    tell application "Finder"
        try
            activate
            set frontWin to folder of front window as string
            set frontWinPath to (get POSIX path of frontWin)
            tell application "Terminal"
                activate
                do script with command "cd \"" & frontWinPath & "\""
            end tell
        on error error_message
            beep
            display dialog error_message buttons ¬
                {"OK"} default button 1
        end try
    end tell
end main

Similar scripts can also get you the complete path to a file on right-click, which is even more useful, I find.

OwnerDisplayName: iayork


问:
Unit testing a menu in ASP.NET MVC 2
I have done some reading on unit testing and want to start with my first test.  I am using ASP.NET MVC 2.

We determine the type of user by getting the staff number and checking it against the Roles table.  If the user exists in this table then the UserType property is set.

We have a menu for each type of user, and each of the menu items are different for each type of user.

How would a test look like for this displaying the menu items for each type of user?

答:
Unit test is a "microscopic" testing unit, so you have to write Unit test for each method in the class you want to test.
With Visual Studio Unit testing is quite easy, you just have to right clic on the class and change generate unit tests.
He Make for you the Test class and you just have to write the code who test the method.

Every unit test have to test ONLY the method and not an another method of a an another class. So if the method you are testing call another one you have to test the CALL with mock objects..

A great and useful book about unit testing. Art of Unit Testing

Title: Unit testing a menu in ASP.NET MVC 2


问:
How to add CSS-Class to a GoogleMaps marker?
I want to animate (fadein, fadeout) a marker in my GoogleMaps application (Web).

How can i assign any css class to a marker?

Or how can i access the specific marker? Do they have selectors like :after or something?

If not, whats the easiest way of applying animations to them?

答:
There is a trick that can work if you for example want to change the cursor for the marker
Add this:

```<code>google.maps.event.addListener(YOURMARKER,'mouseover',function(){$(".gm-style   div").addClass("markerClass")});
google.maps.event.addListener(YOURMARKER,'mouseout',function(){$(".gm-style div").removeClass("markerClass")});
</code>```

and

```<code>#YOUR-CANVAS .gm-style div {cursor: default !important;}
#YOUR-CANVAS .gm-style div.markerClass{cursor:pointer !important}
</code>```

works like a charm

Body:
There is a trick that can work if you for example want to change the cursor for the marker
Add this:

google.maps.event.addListener(YOURMARKER,'mouseover',function(){$(".gm-style   div").addClass("markerClass")});
google.maps.event.addListener(YOURMARKER,'mouseout',function(){$(".gm-style div").removeClass("markerClass")});

and

#YOUR-CANVAS .gm-style div {cursor: default !important;}
#YOUR-CANVAS .gm-style div.markerClass{cursor:pointer !important}

works like a charm


问:
Calculate Text box values of form after submit html
I am trying to design a form. which takes input and after clicking on calculate gives output.
 text field 'State' accepts only 2 uppercase letters

I am stuck in creating Calculate button.

The calculate button needs to determine the number of miles traveled by the customer and the total charge due from the customer.

below is my form:

function ValidateData() {
  var InputText = document.getElementById('state').value;
  var Expression = /^[zA-Z]*$/
  if (InputText.search(Expression) == -1) {
    alert("Must contain only A-Z");
    return false;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: powderblue;
}

.upper {
  text-transform: uppercase;
}</code>```

<!DOCTYPE html>

Calculate Rental Charges

  <form action="/action_page.php">
    First name:

    <input type="text" name="firstname" value="">

 Address:

    <input type="text" name="address" value="">

 city:

    <input type="text" name="city" value="">

 State:

    <input type="text" id="state" name="State" cssclass="upper" value="">

 Zip code:

    <input type="text" name="zipcode" value="">

 Beginning odometer reading(in miles):

    <input type="text" name="zipcode" value="">

 Ending odometer reading(in miles):

    <input type="text" name="zipcode" value="" maxlength="10">

    <input type="submit" value="Submit" OnClientClick="return ValidateData()">
  </form>```

I have designed one script which validates that state should have only upper case letters.

I want to calculate no. of miles driven which can be done by getting difference of starting miles and ending miles.

For calculating the total charge due from the customer.:
         i have to use a constant for the $15 per day charge and the $0.12 mileage rate.

IS there any way to get all this result on single click of submit button.

答:
I created 2 input fields, one to store the total distance and other one is to store the cost. Both are disabled.

Add a button to calculate.

Then add a function like this and call it on button click.

```<code>function calc(){
 var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
 document.getElementById("result").value=totalMile;
 var cost=(totalMile*0.12)+15
 document.getElementById("cost").value='$'+cost;
}
</code>```

function ValidateData() {
  var InputText = document.getElementById('state').value;
  var Expression = /^[A-Z]*$/
  if (InputText.search(Expression) == -1) {
    alert("Must contain only A-Z");
    return false;
  }
}
function calc(){
 var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
 document.getElementById("result").value=totalMile;
 var cost=(totalMile*0.12)+15
 document.getElementById("cost").value='$'+cost;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: powderblue;
}

.upper {
  text-transform: uppercase;
}</code>```

<!DOCTYPE html>

Calculate Rental Charges

  <form method="post" action="/action_page.php">
    First name:

    <input type="text" name="firstname" value="">

 Address:

    <input type="text" name="address" value="">

 city:

    <input type="text" name="city" value="">

 State:

    <input type="text" id="state" name="State" cssclass="upper" value="">

 Zip code:

    <input type="text" name="zipcode" value="">

 Beginning odometer reading(in miles):

    <input type="text" name="startMile" value="">

 Ending odometer reading(in miles):

    <input type="text" name="endMile" value="" maxlength="10">

    <button type="button" onclick="calc();">Calc</button>

    Total Miles :

    <input disabled id="result" />

    Total Cost

    <input disabled id="cost" />

    <input type="submit" value="Submit" Onclick="return ValidateData();">
  </form>```

Body:
I am trying to design a form. which takes input and after clicking on calculate gives output.
 text field 'State' accepts only 2 uppercase letters

I am stuck in creating Calculate button.

The calculate button needs to determine the number of miles traveled by the customer and the total charge due from the customer.

below is my form:

function ValidateData() {
  var InputText = document.getElementById('state').value;
  var Expression = /^[zA-Z]*$/
  if (InputText.search(Expression) == -1) {
    alert("Must contain only A-Z");
    return false;
  }
}

body {
  background-color: powderblue;
}

.upper {
  text-transform: uppercase;
}

<!DOCTYPE html>

Calculate Rental Charges

  <form action="/action_page.php">
    First name:

    <input type="text" name="firstname" value="">

 Address:

    <input type="text" name="address" value="">

 city:

    <input type="text" name="city" value="">

 State:

    <input type="text" id="state" name="State" cssclass="upper" value="">

 Zip code:

    <input type="text" name="zipcode" value="">

 Beginning odometer reading(in miles):

    <input type="text" name="zipcode" value="">

 Ending odometer reading(in miles):

    <input type="text" name="zipcode" value="" maxlength="10">

    <input type="submit" value="Submit" OnClientClick="return ValidateData()">
  </form>

I have designed one script which validates that state should have only upper case letters.

I want to calculate no. of miles driven which can be done by getting difference of starting miles and ending miles.

For calculating the total charge due from the customer.:
         i have to use a constant for the $15 per day charge and the $0.12 mileage rate.

IS there any way to get all this result on single click of submit button.

Body:
I created 2 input fields, one to store the total distance and other one is to store the cost. Both are disabled.

Add a button to calculate.

Then add a function like this and call it on button click.

function calc(){
 var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
 document.getElementById("result").value=totalMile;
 var cost=(totalMile*0.12)+15
 document.getElementById("cost").value='$'+cost;
}

function ValidateData() {
  var InputText = document.getElementById('state').value;
  var Expression = /^[A-Z]*$/
  if (InputText.search(Expression) == -1) {
    alert("Must contain only A-Z");
    return false;
  }
}
function calc(){
 var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
 document.getElementById("result").value=totalMile;
 var cost=(totalMile*0.12)+15
 document.getElementById("cost").value='$'+cost;
}

body {
  background-color: powderblue;
}

.upper {
  text-transform: uppercase;
}

<!DOCTYPE html>
<html>

<head><b>Calculate Rental Charges</b></head><br>

<body>

  <form method="post" action="/action_page.php">
    First name:<br>
    <input type="text" name="firstname" value="">
    <br> Address:
    <br>
    <input type="text" name="address" value="">
    <br> city:
    <br>
    <input type="text" name="city" value="">
    <br> State:
    <br>
    <input type="text" id="state" name="State" cssclass="upper" value="">
    <br> Zip code:<br>
    <input type="text" name="zipcode" value="">
    <br> Beginning odometer reading(in miles):<br>
    <input type="text" name="startMile" value="">
    <br> Ending odometer reading(in miles):<br>
    <input type="text" name="endMile" value="" maxlength="10">
    <br>
    <button type="button" onclick="calc();">Calc</button>
    <br />
    Total Miles : <br />
    <input disabled id="result" />
    <br />
    Total Cost <br />
    <input disabled id="cost" />
    <br />
    <br>
    <input type="submit" value="Submit" Onclick="return ValidateData();">
  </form>


问:
How to write to a memory buffer with a FILE*?
Is there any way to create a memory buffer as a FILE*. In TiXml it can print the xml to a FILE* but i cant seem to make it print to a memory buffer.</p>

答:
C++ basic_streambuf inheritance

In C++, you should avoid FILE* if you can.

Using only the C++ stdlib, it is possible to make a single interface that transparently uses file or memory IO.

This uses techniques mentioned at: Setting the internal buffer used by a standard stream (pubsetbuf)

```<code>#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>

/* This can write either to files or memory. */
void write(std::ostream& os) {
    os << "abc";
}

template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> > {
    ostreambuf(char_type* buffer, std::streamsize bufferLength) {
        this->setp(buffer, buffer + bufferLength);
    }
};

int main() {
    /* To memory, in our own externally supplied buffer. */
    {
        char c[3];
        ostreambuf<char> buf(c, sizeof(c));
        std::ostream s(&buf);
        write(s);
        assert(memcmp(c, "abc", sizeof(c)) == 0);
    }

    /* To memory, but in a hidden buffer. */
    {
        std::stringstream s;
        write(s);
        assert(s.str() == "abc");
    }

    /* To file. */
    {
        std::ofstream s("a.tmp");
        write(s);
        s.close();
    }

    /* I think this is implementation defined.
     * pusetbuf calls basic_filebuf::setbuf(). */
    {
        char c[3];
        std::ofstream s;
        s.rdbuf()->pubsetbuf(c, sizeof c);
        write(s);
        s.close();
        //assert(memcmp(c, "abc", sizeof(c)) == 0);
    }
}
</code>```

Unfortunately, it does not seem possible to interchange FILE* and fstream: Getting a FILE* from a std::fstream

OwnerDisplayName: Lodle

Body:
C++ basic_streambuf inheritance

In C++, you should avoid FILE* if you can.

Using only the C++ stdlib, it is possible to make a single interface that transparently uses file or memory IO.

This uses techniques mentioned at: Setting the internal buffer used by a standard stream (pubsetbuf)

#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>

/* This can write either to files or memory. */
void write(std::ostream& os) {
    os << "abc";
}

template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> > {
    ostreambuf(char_type* buffer, std::streamsize bufferLength) {
        this->setp(buffer, buffer + bufferLength);
    }
};

int main() {
    /* To memory, in our own externally supplied buffer. */
    {
        char c[3];
        ostreambuf<char> buf(c, sizeof(c));
        std::ostream s(&buf);
        write(s);
        assert(memcmp(c, "abc", sizeof(c)) == 0);
    }

    /* To memory, but in a hidden buffer. */
    {
        std::stringstream s;
        write(s);
        assert(s.str() == "abc");
    }

    /* To file. */
    {
        std::ofstream s("a.tmp");
        write(s);
        s.close();
    }

    /* I think this is implementation defined.
     * pusetbuf calls basic_filebuf::setbuf(). */
    {
        char c[3];
        std::ofstream s;
        s.rdbuf()->pubsetbuf(c, sizeof c);
        write(s);
        s.close();
        //assert(memcmp(c, "abc", sizeof(c)) == 0);
    }
}

Unfortunately, it does not seem possible to interchange FILE* and fstream: Getting a FILE* from a std::fstream


问:
Data are not shown in BroadcastReceiver using Android
I want to use Firebase in my application and show the token when calling the service and Broadcast! I write the below codes, but it didn't show any more in the textview!

MyFCMInstance :

```<code>public class MyFCMInstance extends FirebaseInstanceIdService {

    public static final String TOKEN_BROADCAST = "fcmtokenbroadcast";

    @Override
    public void onCreate() {
        super.onCreate();
        String CurrentToken = FirebaseInstanceId.getInstance().getToken();
        if (CurrentToken != null) {
            Intent intent = new Intent("Token");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d("token", "Refreshed token: " + CurrentToken);
            storeToken(CurrentToken);
            getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));

        } else {
            onTokenRefresh();
        }
    }

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.e("FCM Instance", "Token : " + refreshedToken);

        // store token
        storeToken(refreshedToken);

        // send broadcast
        getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));
    }

    private void storeToken(String token) {
        SharedPrefsManager.getInstance(getApplicationContext()).storeToken(token);
    }
}
</code>```

SharedPrefsManager codes:

```<code>public class SharedPrefsManager {

    private static final String SHARED_PREF_NAME = "FCMPrefs";
    private static final String KEY_ACCESS_TOKEN = "Token";
    private static Context mContext;
    private static SharedPrefsManager mInstance;

    public SharedPrefsManager(Context context) {
        mContext = context;
    }

    public static synchronized SharedPrefsManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefsManager(context);
        }
        return mInstance;
    }

    public boolean storeToken(String token) {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, token);
        editor.apply();

        return true;
    }

    public String getToken() {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String token = preferences.getString(KEY_ACCESS_TOKEN, null);

        return token;
    }
}
</code>```

MainActivity codes:

```<code>public class MainActivity extends AppCompatActivity {

    private TextView tokenTV;
    private BroadcastReceiver broadcastReceiver;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tokenTV = (TextView) findViewById(R.id.tokenText);
        context = MainActivity.this;
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                tokenTV.setText(SharedPrefsManager.getInstance(context).getToken());
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(MyFCMInstance.TOKEN_BROADCAST));
    }
}
</code>```

How can I fix it and show the token in TextView ?

答:
You need to set broadcast call after save shared pref call.</p>

```<code>public class MyFCMInstance extends FirebaseInstanceIdService {

    public static final String TOKEN_BROADCAST = "fcmtokenbroadcast";

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.e("FCM Instance", "Token : " + refreshedToken);

        // store token
        storeToken(refreshedToken);

        // send broadcast
        getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));
    }

    private void storeToken(String token){
        SharedPrefsManager.getInstance(getApplicationContext()).storeToken(token);
    }
}

public boolean storeToken(String token) {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, token);
        editor.commit();

        return true;
    }
</code>```

Body:
I want to use Firebase in my application and show the token when calling the service and Broadcast! I write the below codes, but it didn't show any more in the textview!

MyFCMInstance :

public class MyFCMInstance extends FirebaseInstanceIdService {

    public static final String TOKEN_BROADCAST = "fcmtokenbroadcast";

    @Override
    public void onCreate() {
        super.onCreate();
        String CurrentToken = FirebaseInstanceId.getInstance().getToken();
        if (CurrentToken != null) {
            Intent intent = new Intent("Token");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d("token", "Refreshed token: " + CurrentToken);
            storeToken(CurrentToken);
            getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));

        } else {
            onTokenRefresh();
        }
    }

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.e("FCM Instance", "Token : " + refreshedToken);

        // store token
        storeToken(refreshedToken);

        // send broadcast
        getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));
    }

    private void storeToken(String token) {
        SharedPrefsManager.getInstance(getApplicationContext()).storeToken(token);
    }
}

SharedPrefsManager codes:

public class SharedPrefsManager {

    private static final String SHARED_PREF_NAME = "FCMPrefs";
    private static final String KEY_ACCESS_TOKEN = "Token";
    private static Context mContext;
    private static SharedPrefsManager mInstance;

    public SharedPrefsManager(Context context) {
        mContext = context;
    }

    public static synchronized SharedPrefsManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefsManager(context);
        }
        return mInstance;
    }

    public boolean storeToken(String token) {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, token);
        editor.apply();

        return true;
    }

    public String getToken() {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String token = preferences.getString(KEY_ACCESS_TOKEN, null);

        return token;
    }
}

MainActivity codes:

public class MainActivity extends AppCompatActivity {

    private TextView tokenTV;
    private BroadcastReceiver broadcastReceiver;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tokenTV = (TextView) findViewById(R.id.tokenText);
        context = MainActivity.this;
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                tokenTV.setText(SharedPrefsManager.getInstance(context).getToken());
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter(MyFCMInstance.TOKEN_BROADCAST));
    }
}

How can I fix it and show the token in TextView ?

Body:
You need to set broadcast call after save shared pref call.

public class MyFCMInstance extends FirebaseInstanceIdService {

    public static final String TOKEN_BROADCAST = "fcmtokenbroadcast";

    @Override
    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.e("FCM Instance", "Token : " + refreshedToken);

        // store token
        storeToken(refreshedToken);

        // send broadcast
        getApplicationContext().sendBroadcast(new Intent(TOKEN_BROADCAST));
    }

    private void storeToken(String token){
        SharedPrefsManager.getInstance(getApplicationContext()).storeToken(token);
    }
}

public boolean storeToken(String token) {
        SharedPreferences preferences = mContext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, token);
        editor.commit();

        return true;
    }


问:
Proxies in Maven's settings.xml
Coming from this question I'm trying to get my setup to work, but the tests keep failing as they can't connect to the remote site. I upgraded to Maven 3.3.9.

This is my settings.xml that I want to get working:

```<code><settings>

  <proxies>
    <proxy>
      <id>httpProxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.local</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
    <proxy>
      <id>httpsProxy</id>
      <active>true</active>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
  </proxies>
:
</code>```

This is a small part, which already doesn't work:

```<code><settings>

  <proxies>
    <proxy>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
    </proxy>
  </proxies>
:
</code>```

I also tried to put IP-addresses in there.

I know that Maven picks that XML, because Maven says so in its debug messages and if I break the syntax of it Maven complains.

The only thing that really works is passing -Dhttps.proxyHost=proxy.local -Dhttps.proxyPort=3128 to Maven.

What is it that I'm doing wrong in my XML?

答:
After reading the checked answer I tried to make it all work and actually only had to fix the plug-in configuration of maven-failsafe-plugin:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.8</version>
    <executions>
      <execution>
        <id>integration-test</id>
        <goals>
          <goal>integration-test</goal>
        </goals>
        <configuration>

          <argLine>-Xmx512m -XX:MaxPermSize=512m -Dhttps.proxyHost=proxy.local -Dhttps.proxyPort=3128</argLine>
          <includes>
            <include>**/*ITest.java</include>
          </includes>
        </configuration>
      </execution>
      <execution>
        <id>verify</id>
        <goals>
          <goal>verify</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
```

So I leave this here in case anyone stumbles across the same misunderstanding...

Title: Proxies in Maven's settings.xml

Body:
Coming from this question I'm trying to get my setup to work, but the tests keep failing as they can't connect to the remote site. I upgraded to Maven 3.3.9.

This is my settings.xml that I want to get working:

<settings>

  <proxies>
    <proxy>
      <id>httpProxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.local</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
    <proxy>
      <id>httpsProxy</id>
      <active>true</active>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
  </proxies>
:

This is a small part, which already doesn't work:

<settings>

  <proxies>
    <proxy>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
    </proxy>
  </proxies>
:

I also tried to put IP-addresses in there.

I know that Maven picks that XML, because Maven says so in its debug messages and if I break the syntax of it Maven complains.

The only thing that really works is passing -Dhttps.proxyHost=proxy.local -Dhttps.proxyPort=3128 to Maven.

What is it that I'm doing wrong in my XML?

Body:
After reading the checked answer I tried to make it all work and actually only had to fix the plug-in configuration of maven-failsafe-plugin:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.8</version>
    <executions>
      <execution>
        <id>integration-test</id>
        <goals>
          <goal>integration-test</goal>
        </goals>
        <configuration>
          <!-- added -Dhttps.proxyHost and -Dhttps.proxyPort -->
          <argLine>-Xmx512m -XX:MaxPermSize=512m -Dhttps.proxyHost=proxy.local -Dhttps.proxyPort=3128</argLine>
          <includes>
            <include>**/*ITest.java</include>
          </includes>
        </configuration>
      </execution>
      <execution>
        <id>verify</id>
        <goals>
          <goal>verify</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

So I leave this here in case anyone stumbles across the same misunderstanding...


问:
Passing Array (not Object) for Auth in Laravel
I've some problem with passing array, please give me some advice so I can solve this matter.

Here is My Controller:

```<code>$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,produk,username,masalah,id_departemen'))
->where('status','=','Proses')->get();
return view('layanankonsumen.lihattindaklanjut',compact('keluhan_list');
</code>```

And this is part of my Blade view:

```<code>@if (Auth::check() && (Auth::user()->level == 'MR' || Auth::user()->level == 'PDD' || Auth::user()->id_departemen ==' @foreach ($keluhan_list as $keluhan) {{$keluhan->id_departemen}} @endforeach' ))
</code>```

It's not error but it's not pass the auth. When I try to replace with Auth::user()->id_departemen == '10' it's working.

答:
Use in_array().

Checks if a value exists in an array

```<code>@if (.... || in_array(Auth::user()->id_departemen, array_column($keluhan_list, 'id_departemen'))
</code>```

Body:
I've some problem with passing array, please give me some advice so I can solve this matter.

Here is My Controller:

$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,produk,username,masalah,id_departemen'))
->where('status','=','Proses')->get();
return view('layanankonsumen.lihattindaklanjut',compact('keluhan_list');

And this is part of my Blade view:

@if (Auth::check() && (Auth::user()->level == 'MR' || Auth::user()->level == 'PDD' || Auth::user()->id_departemen ==' @foreach ($keluhan_list as $keluhan) {{$keluhan->id_departemen}} @endforeach' ))

It's not error but it's not pass the auth. When I try to replace with Auth::user()->id_departemen == '10' it's working.

Body:
Use in_array().

Checks if a value exists in an array

@if (.... || in_array(Auth::user()->id_departemen, array_column($keluhan_list, 'id_departemen'))


问:
Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined in ionic 2 app
I'm trying to do native facebook login and I get this error

Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined

I show you all my project code.
just saying it let me to connect to facebook successfully but it shows me these errors.

```<code>import { Component, ViewChild } from '@angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar, Splashscreen, NativeStorage } from 'ionic-native';

import { LoginPage } from '../pages/login/login';
import { UserPage } from '../pages/user/user';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {

  @ViewChild(Nav) nav: Nav;
  rootPage: any;

  constructor(platform: Platform) {
    platform.ready().then(() => {

      // Here we will check if the user is already logged in
      // because we don't want to ask users to log in each time they open the app
      let env = this;
      NativeStorage.getItem('user')
      .then( function (data) {
        // user is previously logged and we have his data
        // we will let him access the app
        env.nav.push(UserPage);
        Splashscreen.hide();
      }, function (error) {
        //we don't have the user data so we will ask him to log in
        env.nav.push(LoginPage);
        Splashscreen.hide();
      });

      StatusBar.styleDefault();
    });
  }
}

/*import { Component,ViewChild } from '@angular/core';
import { Platform,Nav, LoadingController} from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

//import pages
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { SignupPage } from '../pages/signup/signup';
import { TabsPage } from '../pages/tabs/tabs';
import { AboutPage } from '../pages/about/about';
import {StudentsPage} from '../pages/students/students';

//import plugins
import firebase from 'firebase';
//import {AngularFire, FirebaseListObservable} from 'angularfire2';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
   public rootPage:any;
   //ref firebase
  public semesters:any;
  public userProfile: any;
  //user variables
  public currentUser: any;
  public id_user:any;
  public reg_boolean:any;
  public department:any;
  public year:any;
  public semester:any;
  public semesterdetails:any;

  constructor(platform: Platform, public loadingCtrl: LoadingController) {
    firebase.initializeApp({
    apiKey: "AIzaSyDOpRshkjuy_tGXSzw34RFHXmAFelyAUt0",
    authDomain: "haversami.firebaseapp.com",
    databaseURL: "https://haversami.firebaseio.com",
    storageBucket: "haversami.appspot.com",
    messagingSenderId: "704224601349"
    });

    //get user details
   // this.currentUser = firebase.auth().currentUser;//to uncomment
    this.userProfile = firebase.database().ref('/users');
    this.semesters = firebase.database().ref('/Semesters/sem');

    // this.id_user=this.af.auth.getAuth().uid; // to uncomment
    this.currentUser='1qfcMAQnglX9jsW5GdLpPko1HqE2';

      this.getUserProfile().on('value', (data) => {
      this.userProfile = data.val();
      this.reg_boolean = this.userProfile.reg_boolean;
      this.department=this.userProfile.depName;
      this.year=this.userProfile.year;

      console.log("enter:"+this.department+this.year);
      console.log(this.reg_boolean);
    });

      this.getSemester().on('value', (data) => {
      this.semesterdetails = data.val();
      this.semester = this.semesterdetails.sem_id;
      console.log(this.semester);
    });

    //check if user connected
     firebase.auth().onAuthStateChanged((user) => {
       var that=this;
       console.log("#1"+user);
      if (user) {
        if(this.reg_boolean==true){
          console.log("adirush");
           this.nav.setRoot(TabsPage,{
           dep:this.department,year:this.year,semester:this.semester

        })
          //this.rootPage=TabsPage;
          this.rootPage=TabsPage;
        }
        else{
        this.rootPage = SignupPage;
        }
        console.log("I'm here! HomePage");
      } else {
        this.rootPage = LoginPage;
        console.log("I'm here! LoginPage");
      }
    });

    let loader = this.loadingCtrl.create();
    loader.present();
   this.listenToUserStatusUpdate(loader);
   /*
    let fireBaseUser = firebase.auth().currentUser;
    console.log(fireBaseUser);
   if (fireBaseUser) {
        if(this.reg_boolean=="true"){
          console.log("adirush");
           this.nav.setRoot(TabsPage,{
           dep:this.department,year:this.year,semester:this.semester

        })
          this.rootPage=TabsPage;
        }
        else{
        this.rootPage = SignupPage;
        }
        console.log("I'm here! HomePage");
      } else {
        this.rootPage = LoginPage;
        console.log("I'm here! LoginPage");
      }

    //this.rootPage = fireBaseUser ? SignupPage : LoginPage;

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }
  listenToUserStatusUpdate(loader: any) {
    firebase.auth().onAuthStateChanged((user) => {
      if(loader)
       loader.dismiss();
      console.log("The User:", user);
      if (user) {
          if(this.reg_boolean=="true"){
          console.log("adirush");
           this.nav.setRoot(TabsPage,{
           dep:this.department,year:this.year,semester:this.semester

        })
          this.rootPage=TabsPage;
        }
        else{
        this.nav.setRoot(SignupPage);
        }
      } else {
        this.nav.setRoot(LoginPage);
      }
    });
  }

   getUserProfile(): any {
    //return this.userProfile.child(this.currentUser.uid); to uncomment
    return this.userProfile.child(this.currentUser);
  }
  getSemester():any{
    return this.semesters.child("0");
  }

}
*/
</code>```

LoginPage.ts

```<code>import { Component } from '@angular/core';
import { Facebook, NativeStorage } from 'ionic-native';
import { NavController } from 'ionic-angular';
import { UserPage } from '../user/user';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  FB_APP_ID: number = 1816752771906363;

  constructor(public navCtrl: NavController) {
    Facebook.browserInit(this.FB_APP_ID, "v2.8");
  }

  doFbLogin(){
    let permissions = new Array<string>();
    let nav = this.navCtrl;
    //the permissions your facebook app needs from the user
    permissions = ["public_profile"];

    Facebook.login(permissions)
    .then(function(response){
      let userId = response.authResponse.userID;
      let params = new Array<string>();

      //Getting name and gender properties
      Facebook.api("/me?fields=name,gender", params)
      .then(function(user) {
        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
        //now we have the users info, let's save it in the NativeStorage
        NativeStorage.setItem('user',
        {
          name: user.name,
          gender: user.gender,
          picture: user.picture
        })
        .then(function(){
          nav.push(UserPage);
        }, function (error) {
          console.log(error);
        })
      })
    }, function(error){
      console.log(error);
    });
  }
}
</code>```

UserPage.ts

```<code>    import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook, NativeStorage } from 'ionic-native';
import { LoginPage } from '../login/login';

@Component({
  selector: 'page-user',
  templateUrl: 'user.html'
})

export class UserPage {

  user: any;
  userReady: boolean = false;

  constructor(public navCtrl: NavController) {}

  ionViewCanEnter(){
    let env = this;
    NativeStorage.getItem('user')
    .then(function (data){
      env.user = {
        name: data.name,
        gender: data.gender,
        picture: data.picture
      };
        env.userReady = true;
    }, function(error){
      console.log(error);
    });
  }

  doFbLogout(){
    var nav = this.navCtrl;
    Facebook.logout()
    .then(function(response) {
      //user logged out so we will remove him from the NativeStorage
      NativeStorage.remove('user');
      nav.push(LoginPage);
    }, function(error){
      console.log(error);
    });
  }
}
</code>```

答:
I found the answer

```<code>export class LoginPage {
    FB_APP_ID: number = 1816752771906363;

    constructor(public navCtrl: NavController) {
        Facebook.browserInit(this.FB_APP_ID, "v2.8");
    }
}
</code>```

Remove

```<code>`FB_APP_ID: number = 1816752771906363;`
</code>```

and

```<code>`Facebook.browserInit(this.FB_APP_ID, "v2.8");`
</code>```

And it will work perfectly.

Body:
I'm trying to do native facebook login and I get this error

Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined

I show you all my project code.
just saying it let me to connect to facebook successfully but it shows me these errors.

import { Component, ViewChild } from '@angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar, Splashscreen, NativeStorage } from 'ionic-native';

import { LoginPage } from '../pages/login/login';
import { UserPage } from '../pages/user/user';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {

  @ViewChild(Nav) nav: Nav;
  rootPage: any;

  constructor(platform: Platform) {
    platform.ready().then(() => {

      // Here we will check if the user is already logged in
      // because we don't want to ask users to log in each time they open the app
      let env = this;
      NativeStorage.getItem('user')
      .then( function (data) {
        // user is previously logged and we have his data
        // we will let him access the app
        env.nav.push(UserPage);
        Splashscreen.hide();
      }, function (error) {
        //we don't have the user data so we will ask him to log in
        env.nav.push(LoginPage);
        Splashscreen.hide();
      });

      StatusBar.styleDefault();
    });
  }
}

/*import { Component,ViewChild } from '@angular/core';
import { Platform,Nav, LoadingController} from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

//import pages
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { SignupPage } from '../pages/signup/signup';
import { TabsPage } from '../pages/tabs/tabs';
import { AboutPage } from '../pages/about/about';
import {StudentsPage} from '../pages/students/students';

//import plugins
import firebase from 'firebase';
//import {AngularFire, FirebaseListObservable} from 'angularfire2';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
   public rootPage:any;
   //ref firebase
  public semesters:any;
  public userProfile: any;
  //user variables
  public currentUser: any;
  public id_user:any;
  public reg_boolean:any;
  public department:any;
  public year:any;
  public semester:any;
  public semesterdetails:any;

  constructor(platform: Platform, public loadingCtrl: LoadingController) {
    firebase.initializeApp({
    apiKey: "AIzaSyDOpRshkjuy_tGXSzw34RFHXmAFelyAUt0",
    authDomain: "haversami.firebaseapp.com",
    databaseURL: "https://haversami.firebaseio.com",
    storageBucket: "haversami.appspot.com",
    messagingSenderId: "704224601349"
    });

    //get user details
   // this.currentUser = firebase.auth().currentUser;//to uncomment
    this.userProfile = firebase.database().ref('/users');
    this.semesters = firebase.database().ref('/Semesters/sem');

    // this.id_user=this.af.auth.getAuth().uid; // to uncomment
    this.currentUser='1qfcMAQnglX9jsW5GdLpPko1HqE2';

      this.getUserProfile().on('value', (data) => {
      this.userProfile = data.val();
      this.reg_boolean = this.userProfile.reg_boolean;
      this.department=this.userProfile.depName;
      this.year=this.userProfile.year;

      console.log("enter:"+this.department+this.year);
      console.log(this.reg_boolean);
    });

      this.getSemester().on('value', (data) => {
      this.semesterdetails = data.val();
      this.semester = this.semesterdetails.sem_id;
      console.log(this.semester);
    });

    //check if user connected
     firebase.auth().onAuthStateChanged((user) => {
       var that=this;
       console.log("#1"+user);
      if (user) {
        if(this.reg_boolean==true){
          console.log("adirush");
           this.nav.setRoot(TabsPage,{
           dep:this.department,year:this.year,semester:this.semester

        })
          //this.rootPage=TabsPage;
          this.rootPage=TabsPage;
        }
        else{
        this.rootPage = SignupPage;
        }
        console.log("I'm here! HomePage");
      } else {
        this.rootPage = LoginPage;
        console.log("I'm here! LoginPage");
      }
    });

    let loader = this.loadingCtrl.create();
    loader.present();
   this.listenToUserStatusUpdate(loader);
   /*
    let fireBaseUser = firebase.auth().currentUser;
    console.log(fireBaseUser);
   if (fireBaseUser) {
        if(this.reg_boolean=="true"){
          console.log("adirush");
           this.nav.setRoot(TabsPage,{
           dep:this.department,year:this.year,semester:this.semester

        })
          this.rootPage=TabsPage;
        }
        else{
        this.rootPage = SignupPage;
        }
        console.log("I'm here! HomePage");
      } else {
        this.rootPage = LoginPage;
        console.log("I'm here! LoginPage");
      }

    //this.rootPage = fireBaseUser ? SignupPage : LoginPage;

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }
  listenToUserStatusUpdate(loader: any) {
    firebase.auth().onAuthStateChanged((user) => {
      if(loader)
       loader.dismiss();
      console.log("The User:", user);
      if (user) {
          if(this.reg_boolean=="true"){
          console.log("adirush");
           this.nav.setRoot(TabsPage,{
           dep:this.department,year:this.year,semester:this.semester

        })
          this.rootPage=TabsPage;
        }
        else{
        this.nav.setRoot(SignupPage);
        }
      } else {
        this.nav.setRoot(LoginPage);
      }
    });
  }

   getUserProfile(): any {
    //return this.userProfile.child(this.currentUser.uid); to uncomment
    return this.userProfile.child(this.currentUser);
  }
  getSemester():any{
    return this.semesters.child("0");
  }

}
*/

LoginPage.ts

import { Component } from '@angular/core';
import { Facebook, NativeStorage } from 'ionic-native';
import { NavController } from 'ionic-angular';
import { UserPage } from '../user/user';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  FB_APP_ID: number = 1816752771906363;

  constructor(public navCtrl: NavController) {
    Facebook.browserInit(this.FB_APP_ID, "v2.8");
  }

  doFbLogin(){
    let permissions = new Array<string>();
    let nav = this.navCtrl;
    //the permissions your facebook app needs from the user
    permissions = ["public_profile"];

    Facebook.login(permissions)
    .then(function(response){
      let userId = response.authResponse.userID;
      let params = new Array<string>();

      //Getting name and gender properties
      Facebook.api("/me?fields=name,gender", params)
      .then(function(user) {
        user.picture = "https://graph.facebook.com/" + userId + "/picture?type=large";
        //now we have the users info, let's save it in the NativeStorage
        NativeStorage.setItem('user',
        {
          name: user.name,
          gender: user.gender,
          picture: user.picture
        })
        .then(function(){
          nav.push(UserPage);
        }, function (error) {
          console.log(error);
        })
      })
    }, function(error){
      console.log(error);
    });
  }
}

UserPage.ts

    import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook, NativeStorage } from 'ionic-native';
import { LoginPage } from '../login/login';

@Component({
  selector: 'page-user',
  templateUrl: 'user.html'
})

export class UserPage {

  user: any;
  userReady: boolean = false;

  constructor(public navCtrl: NavController) {}

  ionViewCanEnter(){
    let env = this;
    NativeStorage.getItem('user')
    .then(function (data){
      env.user = {
        name: data.name,
        gender: data.gender,
        picture: data.picture
      };
        env.userReady = true;
    }, function(error){
      console.log(error);
    });
  }

  doFbLogout(){
    var nav = this.navCtrl;
    Facebook.logout()
    .then(function(response) {
      //user logged out so we will remove him from the NativeStorage
      NativeStorage.remove('user');
      nav.push(LoginPage);
    }, function(error){
      console.log(error);
    });
  }
}

Body:
I found the answer

export class LoginPage {
    FB_APP_ID: number = 1816752771906363;

    constructor(public navCtrl: NavController) {
        Facebook.browserInit(this.FB_APP_ID, "v2.8");
    }
}

Remove

`FB_APP_ID: number = 1816752771906363;`

and

`Facebook.browserInit(this.FB_APP_ID, "v2.8");`

And it will work perfectly.


问:
SDN doesn't work if I activate `-parameters` compiler's argument
I use Spring Data Neo4j 4.2.0.RELEASE and experience the following exception:

```<code>org.neo4j.ogm.exception.CypherException: Error executing Cypher "Neo.ClientError.Statement.ParameterMissing"; Code: Neo.ClientError.Statement.ParameterMissing; Description: Expected a parameter named 0
</code>```

in the following place:

```<code>@Query("" +
        "MATCH (u:User)-[:LOCATION]-(l:Location)-[r]-(p:PostalCode) " +
        "WHERE id(u)={0} " +
        "RETURN l, r, p"
)
Location findUserLocation(long userId);
</code>```

in case if I use -parameters argument for my java compiler.

Do anyone know, why it may not work?

答:
It's because compilation with -parameters allows the framework to get real parameter names from the source code.

In other words, it works the same way as : findUserLocation(@Param("userId") long userId)

Changing the query to use {userId} instead of {0} should work. If you need to be compatible with different compilation options, use @Param as stated above.

Body:
I use Spring Data Neo4j 4.2.0.RELEASE and experience the following exception:

org.neo4j.ogm.exception.CypherException: Error executing Cypher "Neo.ClientError.Statement.ParameterMissing"; Code: Neo.ClientError.Statement.ParameterMissing; Description: Expected a parameter named 0

in the following place:

@Query("" +
        "MATCH (u:User)-[:LOCATION]-(l:Location)-[r]-(p:PostalCode) " +
        "WHERE id(u)={0} " +
        "RETURN l, r, p"
)
Location findUserLocation(long userId);

in case if I use -parameters argument for my java compiler.

Do anyone know, why it may not work?


问:
Can an endless/perpetual counter be built using jQuery?
A client asks:

...Our company hauls sand and to date, we've hauled 1.7 billion
  pounds and counting. I am looking to have a counter made; it needs to be
  continuously counting and not revert back to the original number after
  the page is refreshed. I need the counter to start at 1.7 billion
  pounds and be adding 154 pounds per second.

Would there need to be a data source, or would such a calculation be tied to time? (eg: current server time)

I assuming there's probably a need to lock-in the current actual value, so the calculation would need to be adjusted weekly/monthly to reflect what's real. But it's really only SAND (not rocket science).

答:
I think you need 3 things on your server:

Initial value

Initial date+time

Speed

Then using those 3 you can calculate value at any moment.

If you want

so the calculation would need to be adjusted weekly/monthly to reflect what's real.

you can make them customizable properties on some Admin UI. You even can let user enter new date and value and calculate speed using difference with the previous value. But still it makes sense to provide user some UI to override speed in case there would be some typo.

Now back to the main business. To make it more or less reliable I'd do calculation in two steps: first on the server side and then on the client side. First on the server-side you calculate current value as:

```<code>initial_value_for_client = initial_value + speed * (current_time - initial_time)
</code>```

and put it into the page's JS together with speed. Then on the client side using simple setInterval you add speed to initial_value_for_client and update the HTML. By doing it in two steps you are not dependent on the client-side time zone. Your value is only wrong by the time it takes to download page and start its execution and that shouldn't be too much.

Body:
I think you need 3 things on your server:

Initial value

Initial date+time

Speed

Then using those 3 you can calculate value at any moment.

If you want

so the calculation would need to be adjusted weekly/monthly to reflect what's real.

you can make them customizable properties on some Admin UI. You even can let user enter new date and value and calculate speed using difference with the previous value. But still it makes sense to provide user some UI to override speed in case there would be some typo.

Now back to the main business. To make it more or less reliable I'd do calculation in two steps: first on the server side and then on the client side. First on the server-side you calculate current value as:

initial_value_for_client = initial_value + speed * (current_time - initial_time)

and put it into the page's JS together with speed. Then on the client side using simple setInterval you add speed to initial_value_for_client and update the HTML. By doing it in two steps you are not dependent on the client-side time zone. Your value is only wrong by the time it takes to download page and start its execution and that shouldn't be too much.


问:
Unable to show content of array as checkboxes using ng-repeat
I have the following in my controller:

```<code>var myApp = angular.module("myApp", []);

myApp.controller("TestCtrl", ['$scope', function($scope) {
  $scope.rows = [
    'Facebook',
    'Twitter',
    'Pinterest',
    'Instagram',
    'Tumblr',
    'Google'
  ];
}]);
</code>```

and I'm trying to show the content like this

```<code><div class="container">
  <div ng-app="myApp">
    <div ng-controller="TestCtrl">
          <label ng-repeat="row in rows">
            <input type="checkbox" ng-checked="row.selected" ng-model="row.selected" />{{row}}</label>
    </div>
  </div>
</code>```

right now the items show, but I can't check the checkboxes,
check this Plunker

答:
In order to have your checkbox checkable, you need to pass a valid ng-model there. In your case, row.selected is invalid since every row is a string and not object.

You can have your $scope.rows array like this instead:

```<code>$scope.rows = [{
    name: 'Facebook',
    selected: false
  }, {
    name: 'Twitter',
    selected: false
  }, {
    name: 'Pinterest',
    selected: false
  }, {
    name: 'Instagram',
    selected: false
  }, {
    name: 'Tumblr',
    selected: false
  }];
</code>```

Here's a forked plunker which has checkboxes checkable

Body:
I have the following in my controller:

var myApp = angular.module("myApp", []);

myApp.controller("TestCtrl", ['$scope', function($scope) {
  $scope.rows = [
    'Facebook',
    'Twitter',
    'Pinterest',
    'Instagram',
    'Tumblr',
    'Google'
  ];
}]);

and I'm trying to show the content like this

            <input type="checkbox" ng-checked="row.selected" ng-model="row.selected" />{{row}}

right now the items show, but I can't check the checkboxes,
check this Plunker

Body:
In order to have your checkbox checkable, you need to pass a valid ng-model there. In your case, row.selected is invalid since every row is a string and not object.

You can have your $scope.rows array like this instead:

$scope.rows = [{
    name: 'Facebook',
    selected: false
  }, {
    name: 'Twitter',
    selected: false
  }, {
    name: 'Pinterest',
    selected: false
  }, {
    name: 'Instagram',
    selected: false
  }, {
    name: 'Tumblr',
    selected: false
  }];

Here's a forked plunker which has checkboxes checkable


问:
Convert string OAuth token to ClaimsPrincipal
I have my own custom OAuthAuthorizationServerProvider implementation. I am using token-based security to communicate with WebApi.

In the headers there is a Authorization header with the bearer token. This works perfectly with WebApi.

My app has a dependency on a 3rd party MVC component. I want to pass the bearer token as part of the query string and the convert it to a ClaimsPrincipal to retrieve the current user.

What can I call in C# to convert a bearer token as a string to a ClaimsPrincipal (or any object which will enable me to read the user id claim)?

答:
You can access the OAuthAuthorizationServerOptions (in my case named OAuthOptions )and then you access the token format and use the unprotect function.

```<code>ticket = Startup.OAuthOptions.AccessTokenFormat.Unprotect(token);
</code>```

Once you have the token, you can easily get the claims.

Body:
You can access the OAuthAuthorizationServerOptions (in my case named OAuthOptions )and then you access the token format and use the unprotect function.

ticket = Startup.OAuthOptions.AccessTokenFormat.Unprotect(token);

Once you have the token, you can easily get the claims.


问:
Extract date from apache/niginx userid cookie
Both webservers Apache and Nginx can give visitors uniqid cookie with mod_unique_id/userid modules. Such a cookie looks like four uint32 values encoded to base64 string. Second byte is a timestamp when the cookie was issued.

I'd like to extract the date and time of it.

```<code>from base64 import b64decode
from datetime import datetime
import shlex, gzip, glob
from struct import unpack

import pandas as pd
import numpy as np

def get_data() -> pd.DataFrame:
    filenames = glob.glob('data/user_cookie/stat-*.gz')
    for filename in filenames:
        print(filename)
        f = gzip.open(filename, 'rt')
        for row in f.readlines():
            parts = shlex.split(row)
            useragent, raw_cookie = parts[9], parts[16]
            if raw_cookie == '-':
                raw_visit_date = parts[3][1:]
                # this is a first visit
                visit_date = datetime.strptime(raw_visit_date,
                                               '%d/%b/%Y:%H:%M:%S')
            else:
                visit_date = datetime.fromtimestamp(unpack('IIII',
                                                           b64decode(raw_cookie))[1])
            print(useragent, visit_date)

if __name__ == '__main__':
    get_data()
</code>```

This line seems to me especially "artificial". How to make all code  more "pythonic" and faster?

```<code>datetime.fromtimestamp(unpack('IIII', b64decode(raw_cookie))[1])
</code>```

答:
I don't know what you mean exactly by "artificial" and "pythonic", but at least on my machine, that code is incorrect. And it's incorrect in a way that will give you bogus data which might not be noticed.

The 'IIII' format code for unpack does not specify a byte order, which on my (x86) machine results in an incorrect timestamp. The documentation says that omitting the byte order will cause it to default to your machine's byte order. But in mod_uid version 2, the cookie uses network byte order.  Specify network byte order with the format code !IIII'.

If by "pythonic" you mean spread it across a few lines instead of packing it into one, here is how that could look:

```<code>binary_cookie = b64decode(raw_cookie)
fields = unpack('!IIII', binary_cookie)
visit_date = datetime.fromtimestamp(fields[1])
</code>```

Body:
Both webservers Apache and Nginx can give visitors uniqid cookie with mod_unique_id/userid modules. Such a cookie looks like four uint32 values encoded to base64 string. Second byte is a timestamp when the cookie was issued.

I'd like to extract the date and time of it.

from base64 import b64decode
from datetime import datetime
import shlex, gzip, glob
from struct import unpack

import pandas as pd
import numpy as np

def get_data() -> pd.DataFrame:
    filenames = glob.glob('data/user_cookie/stat-*.gz')
    for filename in filenames:
        print(filename)
        f = gzip.open(filename, 'rt')
        for row in f.readlines():
            parts = shlex.split(row)
            useragent, raw_cookie = parts[9], parts[16]
            if raw_cookie == '-':
                raw_visit_date = parts[3][1:]
                # this is a first visit
                visit_date = datetime.strptime(raw_visit_date,
                                               '%d/%b/%Y:%H:%M:%S')
            else:
                visit_date = datetime.fromtimestamp(unpack('IIII',
                                                           b64decode(raw_cookie))[1])
            print(useragent, visit_date)

if __name__ == '__main__':
    get_data()

This line seems to me especially "artificial". How to make all code  more "pythonic" and faster?

datetime.fromtimestamp(unpack('IIII', b64decode(raw_cookie))[1])

Body:
I don't know what you mean exactly by "artificial" and "pythonic", but at least on my machine, that code is incorrect. And it's incorrect in a way that will give you bogus data which might not be noticed.

The 'IIII' format code for unpack does not specify a byte order, which on my (x86) machine results in an incorrect timestamp. The documentation says that omitting the byte order will cause it to default to your machine's byte order. But in mod_uid version 2, the cookie uses network byte order.  Specify network byte order with the format code !IIII'.

If by "pythonic" you mean spread it across a few lines instead of packing it into one, here is how that could look:

binary_cookie = b64decode(raw_cookie)
fields = unpack('!IIII', binary_cookie)
visit_date = datetime.fromtimestamp(fields[1])


问:
uiwebview does not scroll till bottom
i am new to iPad developer,

i am making ePub reader for my application, in which i am loading my ePub pages in UIWebView

when i load my pages in webview it scrolls unto some limits only,

here is my code snippet,

```<code>- (void)viewDidLoad {
...

    _webview=[[UIWebView alloc]init];
    _webview.frame=CGRectMake(0, 0, 770, 960);
    [_webview setBackgroundColor:[UIColor grayColor]];
    _webview.delegate=self;
    [self.view addSubview:_webview];

    [self loadPage];
...
}

 - (void)loadPage{

  [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:_pagesPath]]];

    [self._webview sizeToFit];
    _webview.scalesPageToFit=TRUE;
    _webview.scrollView.bounces = NO;
    _webview.autoresizesSubviews = YES;

}
</code>```

答:
1)try to hide NavigationBar

```<code>self.navigationController.hidesBarsOnSwipe = YES;
</code>```

2)Try to make WebViewScale to fit to View

```<code>webView.scalesPageToFit=YES;
webView.scrollView.bounces = NO;
</code>```

3)Or may Be issue with Frame of WebView then Try

```<code>UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-self.navigationController.navigationBar.frame.size.height)];
</code>```

Title: uiwebview does not scroll till bottom

Body:
i am new to iPad developer,

i am making ePub reader for my application, in which i am loading my ePub pages in UIWebView

when i load my pages in webview it scrolls unto some limits only,

here is my code snippet,

- (void)viewDidLoad {
...

    _webview=[[UIWebView alloc]init];
    _webview.frame=CGRectMake(0, 0, 770, 960);
    [_webview setBackgroundColor:[UIColor grayColor]];
    _webview.delegate=self;
    [self.view addSubview:_webview];

    [self loadPage];
...
}

 - (void)loadPage{

  [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:_pagesPath]]];

    [self._webview sizeToFit];
    _webview.scalesPageToFit=TRUE;
    _webview.scrollView.bounces = NO;
    _webview.autoresizesSubviews = YES;

}

Body:
1)try to hide NavigationBar

self.navigationController.hidesBarsOnSwipe = YES;

2)Try to make WebViewScale to fit to View

webView.scalesPageToFit=YES;
webView.scrollView.bounces = NO;

3)Or may Be issue with Frame of WebView then Try

UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-self.navigationController.navigationBar.frame.size.height)];


问:
How to round to the closest whole number without using known functions in c?
like 52.7-->53, 5.5-->6, 3.2->3</p>

答:
```<code>int round(float num) {
  return (int)(num + 0.5);
}
</code>```

Edit: This will not work for large value of float and negative numbers.

Edit Again: This was the simple idea of how rounding works, but after reading comment on question this thread : Concise way to implement round() in C?
has everything explained for a proper implementation of round() function

Body: like 52.7-->53, 5.5-->6, 3.2->3

Body:
int round(float num) {
  return (int)(num + 0.5);
}

Edit: This will not work for large value of float and negative numbers.

Edit Again: This was the simple idea of how rounding works, but after reading comment on question this thread : Concise way to implement round() in C?
has everything explained for a proper implementation of round() function


问:
Setting persistentStoreDescriptions causes no CoreData objects to be saved
I am trying to ensure that all of our CoreData is protected using Data Protection.  When I try to set a NSPersistentStoreDescription on my container, no CoreData objects are saved.  If I comment out the line indicated below, all objects are saved (and read) just fine.  If I enable the line, nothing gets saved (or perhaps the read silently fails?).  There are no errors generated and there are no logs generated.  I do have the Data Protection entitlement in my provisioning profile (matching completeUnlessOpen).  I've gotta be missing something very basic.

This is Xcode 8.2.1 (8C1002)

Can anyone offer any insight / advice?

```<code>lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "my_app")
    let description = NSPersistentStoreDescription()

    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.setOption(FileProtectionType.completeUnlessOpen as NSObject?, forKey: NSPersistentStoreFileProtectionKey)

    // *** ALLOWING THIS NEXT LINE TO EXECUTE CAUSES PROBLEM ***
    container.persistentStoreDescriptions = [description]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            print("Unresolved error \(error), \(error.userInfo)")
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()
</code>```

答:
Your error is actually because you're setting options that should relate to Core Data. File protection is done under FileManager setAttributes function calls.

However, the answer to the underlying question is that you don't need to add file protection to individual files - they're set to the default protection you declare in your entitlement.

This can be verified by printing the output of:

let attributes = try FileManager.default.attributesOfItem(atPath: url.relativePath)

Body:
I am trying to ensure that all of our CoreData is protected using Data Protection.  When I try to set a NSPersistentStoreDescription on my container, no CoreData objects are saved.  If I comment out the line indicated below, all objects are saved (and read) just fine.  If I enable the line, nothing gets saved (or perhaps the read silently fails?).  There are no errors generated and there are no logs generated.  I do have the Data Protection entitlement in my provisioning profile (matching completeUnlessOpen).  I've gotta be missing something very basic.

This is Xcode 8.2.1 (8C1002)

Can anyone offer any insight / advice?

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "my_app")
    let description = NSPersistentStoreDescription()

    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.setOption(FileProtectionType.completeUnlessOpen as NSObject?, forKey: NSPersistentStoreFileProtectionKey)

    // *** ALLOWING THIS NEXT LINE TO EXECUTE CAUSES PROBLEM ***
    container.persistentStoreDescriptions = [description]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            print("Unresolved error \(error), \(error.userInfo)")
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()


问:
Calling your own Action method that returns IHttpActionResult
It seems maybe my question was unclear.  Here is what I am looking to do.

I am writing a web api that makes calls into another web api.  Inside of my API I would like to call to the UpdateAssignmentStatus method from the MarkAllTasksDone method.  I don't know what to do with the return type of IHttpActionResult, meaning how to process it.  How do I get the information that is being returned in the method.  In the UpdateAssignmentStatus method it returns a BadRequest with a message, a InternalServerError with a message, or an Ok with a message.  How do I get to that data?  Sorry, I should have provided that info before.

Just to add more here.  When I debug I can see that the actionResultUAS object is one of my return types that I stated in my UpdateAssignmentStatus method.  BadRequest returns System.Web.Http.Results.BadRequestErrorMessageResult, an Ok returns System.Web.Http.Results.OkNegotiatedContentResult, and InternalServerError returns System.Web.Http.Results.ExceptionResult.  I would assume that I will need to cast to each of these types.  Is there a good way to do that, maybe a generic way.

```<code>    [HttpGet]
    public IHttpActionResult MarkAllTasksDone(string projectID)
    {
        try
        {
            var assignments = GetAssignments("ASSGN/search?projectID=" + projectID + "&fields=taskID&fields=status" + "&apiKey=" + ApiKey);

            foreach (var assignment in assignments.Where(a => a.AssignmentStatus != "DN"))
            {
                var actionResultUAS = UpdateAssignmentStatus(assignment.AssignmentID, "DONE");
                //****how to get the ok or failure code and the returned data from the actionResultUAS object

                var responseMessageUT = UpdateTaskPercentComplete(assignment.TaskID, 100);
                }
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

        return Ok();

    }

[HttpGet]
public IHttpActionResult UpdateAssignmentStatus(string assignmentID, string assignmentStatus)
{
    HttpResponseMessage httpResponse = new HttpResponseMessage();
    try
    {
        var convertedStatus = ConvertAssignmentStatus(assignmentStatus);
        httpResponse = Put("ASSGN?ID=" + assignmentID + "&status=" + convertedStatus + "&apiKey=" + ApiKey);
    }
    catch (ApplicationException ae)
    {
        return BadRequest(ae.Message);

    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }
    HttpResponseData httpResponseData = new HttpResponseData();
    httpResponseData.IsSuccessful = httpResponse.IsSuccessStatusCode;
    httpResponseData.Content = httpResponse.Content.ReadAsStringAsync().Result;
    httpResponseData.StatusCode = httpResponse.StatusCode.ToString();

    return Ok(httpResponseData);
}
</code>```

答:
You can use this:

```<code>  return Content(httpResponse.StatusCode, httpResponse);
</code>```

EDIT : as you requested the object from result, You can check the status code and read the response in object.

```<code>if (httpResponse.StatusCode == HttpStatusCode.OK)
{
 var result = httpResponse.Content.ReadAsAsync<'Your Model of assignment here'>();
}
</code>```

This will return the model with the response.

Body:
It seems maybe my question was unclear.  Here is what I am looking to do.

I am writing a web api that makes calls into another web api.  Inside of my API I would like to call to the UpdateAssignmentStatus method from the MarkAllTasksDone method.  I don't know what to do with the return type of IHttpActionResult, meaning how to process it.  How do I get the information that is being returned in the method.  In the UpdateAssignmentStatus method it returns a BadRequest with a message, a InternalServerError with a message, or an Ok with a message.  How do I get to that data?  Sorry, I should have provided that info before.

Just to add more here.  When I debug I can see that the actionResultUAS object is one of my return types that I stated in my UpdateAssignmentStatus method.  BadRequest returns System.Web.Http.Results.BadRequestErrorMessageResult, an Ok returns System.Web.Http.Results.OkNegotiatedContentResult, and InternalServerError returns System.Web.Http.Results.ExceptionResult.  I would assume that I will need to cast to each of these types.  Is there a good way to do that, maybe a generic way.

    [HttpGet]
    public IHttpActionResult MarkAllTasksDone(string projectID)
    {
        try
        {
            var assignments = GetAssignments("ASSGN/search?projectID=" + projectID + "&fields=taskID&fields=status" + "&apiKey=" + ApiKey);

            foreach (var assignment in assignments.Where(a => a.AssignmentStatus != "DN"))
            {
                var actionResultUAS = UpdateAssignmentStatus(assignment.AssignmentID, "DONE");
                //****how to get the ok or failure code and the returned data from the actionResultUAS object

                var responseMessageUT = UpdateTaskPercentComplete(assignment.TaskID, 100);
                }
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

        return Ok();

    }

[HttpGet]
public IHttpActionResult UpdateAssignmentStatus(string assignmentID, string assignmentStatus)
{
    HttpResponseMessage httpResponse = new HttpResponseMessage();
    try
    {
        var convertedStatus = ConvertAssignmentStatus(assignmentStatus);
        httpResponse = Put("ASSGN?ID=" + assignmentID + "&status=" + convertedStatus + "&apiKey=" + ApiKey);
    }
    catch (ApplicationException ae)
    {
        return BadRequest(ae.Message);

    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }
    HttpResponseData httpResponseData = new HttpResponseData();
    httpResponseData.IsSuccessful = httpResponse.IsSuccessStatusCode;
    httpResponseData.Content = httpResponse.Content.ReadAsStringAsync().Result;
    httpResponseData.StatusCode = httpResponse.StatusCode.ToString();

    return Ok(httpResponseData);
}

Body:
You can use this:

  return Content(httpResponse.StatusCode, httpResponse);

EDIT : as you requested the object from result, You can check the status code and read the response in object.

if (httpResponse.StatusCode == HttpStatusCode.OK)
{
 var result = httpResponse.Content.ReadAsAsync<'Your Model of assignment here'>();
}

This will return the model with the response.


问:
command "pm2 reload all" can't restart
1.I use command

```<code>pm2 start pm2.json
</code>```

my pm2.json is

```<code>{
  "apps": [{
    "name": "test_pm2",
    "script": "www/app.js",
    "cwd": "/var/www/test_pm2",
    "exec_mode": "cluster",
    "instances": 0,
    "max_memory_restart": "1G",
    "autorestart": true,
    "node_args": [],
    "args": [],
    "env": {

    }
  }]
}
</code>```

2.then i use command

```<code>pm2 reload all
</code>```

and pm2 stop all process,but can't relaod my project,The command line is always waiting.
To visit my project throgh browser,the Nginx 502 error showed.
So i have to use commond pm2 start pm2.json to start.

My environment:
pm2 v2.4.0; node v6.9.5; npm v3.10.10

I hope someone can answer the confusion, thanks！

答:
Just looking over your file these may be the problems. (not sure)

```<code>"apps": [{
"name": "test_pm2",
"script": "www/app.js",
"cwd": "/var/www/test_pm2",
"exec_mode": "cluster",
"instances": 0,
"max_memory_restart": "1G",
"autorestart": true,
"node_args": [],
"args": [],
"env": {

}
</code>```

script: --> are you sure this is the correct path?? Usually it would read:
"./app.js",

cwd: ---> maybe it is var\html\www ???
If all else fails try instances: 'max'
and get rid of the max_memory_restart

Also make sure you are running the app.js by way of the pm2.json file (kind of obvious).

To see where the problem is coming from do it step by step. Some of the commands in your pm2.json file may be problematic.

Hope this helps.

Title: command "pm2 reload all" can't restart

Body:
1.I use command

pm2 start pm2.json

my pm2.json is

{
  "apps": [{
    "name": "test_pm2",
    "script": "www/app.js",
    "cwd": "/var/www/test_pm2",
    "exec_mode": "cluster",
    "instances": 0,
    "max_memory_restart": "1G",
    "autorestart": true,
    "node_args": [],
    "args": [],
    "env": {

    }
  }]
}

2.then i use command

pm2 reload all

and pm2 stop all process,but can't relaod my project,The command line is always waiting.
To visit my project throgh browser,the Nginx 502 error showed.
So i have to use commond pm2 start pm2.json to start.

My environment:
pm2 v2.4.0; node v6.9.5; npm v3.10.10

I hope someone can answer the confusion, thanks！

Body:
Just looking over your file these may be the problems. (not sure)

"apps": [{
"name": "test_pm2",
"script": "www/app.js",
"cwd": "/var/www/test_pm2",
"exec_mode": "cluster",
"instances": 0,
"max_memory_restart": "1G",
"autorestart": true,
"node_args": [],
"args": [],
"env": {

}

script: --> are you sure this is the correct path?? Usually it would read:
"./app.js",

cwd: ---> maybe it is var\html\www ???
If all else fails try instances: 'max'
and get rid of the max_memory_restart

Also make sure you are running the app.js by way of the pm2.json file (kind of obvious).

To see where the problem is coming from do it step by step. Some of the commands in your pm2.json file may be problematic.

Hope this helps.