问:
$.ajax not working in IE, it is fine in Firefox
```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript">

    function funcSendSMS(numbers, smsmessage)
    {
    alert(numbers);
      var num = numbers;
      var msg = smsmessage;
  $.ajax({
    type: "GET",
    url: "http://sms.vrksolutions.com/messageapi.asp",
    data: "username=xxxxxx&password=xxxxxx&sender=xxxxxx&mobile="+num+"&message="+msg,
    async: false,
    cache: false,
    success: function(resp){
      // we have the response
      alert("Server said:\n '" + resp + "'");
    },
    error: function(e){
      alert('Error: ' + e);
    }
  });
}
</script>
<script  language="javascript">
funcSendSMS('<?php echo $phnos ?>', '<?php echo $smsmsg;?>');
</script>
</code>```

I got below error in IE

Webpage error details

User Agent: Mozilla/4.0 (compatible;
  MSIE 7.0; Windows NT 6.1; Trident/4.0;
  GTB6.6; SLCC2; .NET CLR 2.0.50727;
  .NET CLR 3.5.30729; .NET CLR
  3.0.30729; Media Center PC 6.0; InfoPath.2) Timestamp: Tue, 12 Apr
  2011 13:22:58 UTC

Message: Access is denied.

Line: 138
Char: 355
Code: 0
URI: https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

at this lane i found

below code in min.js file

```<code>A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){
if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete"))
{C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);
A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}
r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();
if(w){b.username?w.open(h,b.url,b.async,b.username,b.password)
:w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&
a.contentType)w.setRequestHeader("Content-Type",
</code>```

答:
try this:

```<code>$(function(){
     funcSendSMS('<?php echo $phnos ?>', '<?php echo $smsmsg;?>');
});
</code>```

or

```<code>function Load() {
            var a = false;
            try {
                var test = $('*');
                if(test == null)
                    throw 1;
            }
            catch (e) { a = true; }
            if (a){setTimeout(Load, 300);return;}

            funcSendSMS('<?php echo $phnos ?>', '<?php echo $smsmsg;?>');
        }
setTimeout(Load, 300);
</code>```

Make sure you are not doing a cross domain request through AJAX.

Body:
I got below error in IE

Webpage error details

User Agent: Mozilla/4.0 (compatible;
  MSIE 7.0; Windows NT 6.1; Trident/4.0;
  GTB6.6; SLCC2; .NET CLR 2.0.50727;
  .NET CLR 3.5.30729; .NET CLR
  3.0.30729; Media Center PC 6.0; InfoPath.2) Timestamp: Tue, 12 Apr
  2011 13:22:58 UTC

Message: Access is denied.

Line: 138
Char: 355
Code: 0
URI: https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

at this lane i found

below code in min.js file

A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){
if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete"))
{C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);
A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}
r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();
if(w){b.username?w.open(h,b.url,b.async,b.username,b.password)
:w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&
a.contentType)w.setRequestHeader("Content-Type",

Body:
try this:

$(function(){
     funcSendSMS('<?php echo $phnos ?>', '<?php echo $smsmsg;?>');
});

or

function Load() {
            var a = false;
            try {
                var test = $('*');
                if(test == null)
                    throw 1;
            }
            catch (e) { a = true; }
            if (a){setTimeout(Load, 300);return;}

            funcSendSMS('<?php echo $phnos ?>', '<?php echo $smsmsg;?>');
        }
setTimeout(Load, 300);

Make sure you are not doing a cross domain request through AJAX.


来源: stackexchange

问:
Getting elements in certain range of list
I have a Python list, for example list = [1,2,3,4,5,6,7,8,9]. In addition, I have another list list2 = ['a','b','c','d','e','f','g','h','j']. Now I would like to do the following:

```<code>idx = (list > 3) & (list < 7)
list2 = list2[idx]
</code>```

This should yield ['d','e','f']. Of course, this is not possible with lists. How can this be done with lists?

答:
Try this:</p>

```<code>#Make sure all lists are numpy arrays.
import numpy as np
idx = np.where((list > 3) & (list < 7))
list2 = list2[idx]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Python list, for example list = [1,2,3,4,5,6,7,8,9]. In addition, I have another list list2 = ['a','b','c','d','e','f','g','h','j']. Now I would like to do the following:

idx = (list > 3) & (list < 7)
list2 = list2[idx]

This should yield ['d','e','f']. Of course, this is not possible with lists. How can this be done with lists?

Body:
Try this:

#Make sure all lists are numpy arrays.
import numpy as np
idx = np.where((list > 3) & (list < 7))
list2 = list2[idx]


问:
How can I send an Api file to the server using the Api? With Retrofit2
I want to use this Api to send the file to the server using retrofit2 .. how can help me?

```<code>{
    "id": 6,
    "title": "sometitle",
    "image": "http://kavehkm.pythonanywhere.com/media/images/Koala.jpg",
    "description": "some",
    "price": 1000,
    "tell": "09303747240",
    "address": "some",
    "category": 2,
    "owner": 5
}
</code>```

this is true ?

```<code>@Multipart
@Post("ads")
Call<ResponseBody> uploadPost(@Header("Authorization") String Token
                                      ,@Part("title") RequestBody title
                                      ,@Part("description") RequestBody description
                                      ,@Part("price) RequestBody price
                                      ,@Part MultipartBody.Part image
                                      ,@Part("category") RequestBody category)
</code>```

答:
You have to use multipart to upload a file to the server using retrofit2. See this. For better understanding check here </p>

```<code>    @Multipart
    @POST("your api url")
    Observable<ResponseBody> uploadFile(@Part("id") RequestBody id,
                                           @Part("title") RequestBody title,
                                           @Part MultipartBody.Part image,
                                           @Part("other") RequestBody other);

    //pass it like this
    File file = new File("/storage/../image.jpg");
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("image", file.getName(), requestFile);

    // add another part within the multipart request
    RequestBody fullName =
            RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

    service.uploadFile(id, fullName, body, other);
</code>```

Body:
I want to use this Api to send the file to the server using retrofit2 .. how can help me?

{
    "id": 6,
    "title": "sometitle",
    "image": "http://kavehkm.pythonanywhere.com/media/images/Koala.jpg",
    "description": "some",
    "price": 1000,
    "tell": "09303747240",
    "address": "some",
    "category": 2,
    "owner": 5
}

this is true ?

@Multipart
@Post("ads")
Call<ResponseBody> uploadPost(@Header("Authorization") String Token
                                      ,@Part("title") RequestBody title
                                      ,@Part("description") RequestBody description
                                      ,@Part("price) RequestBody price
                                      ,@Part MultipartBody.Part image
                                      ,@Part("category") RequestBody category)

Body:
You have to use multipart to upload a file to the server using retrofit2. See this. For better understanding check here

    @Multipart
    @POST("your api url")
    Observable<ResponseBody> uploadFile(@Part("id") RequestBody id,
                                           @Part("title") RequestBody title,
                                           @Part MultipartBody.Part image,
                                           @Part("other") RequestBody other);

    //pass it like this
    File file = new File("/storage/../image.jpg");
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("image", file.getName(), requestFile);

    // add another part within the multipart request
    RequestBody fullName =
            RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

    service.uploadFile(id, fullName, body, other);


问:
How can I replace a variable inside an object?
I try to replace a variable inside my object method:

```<code> $fieldname = "project";

 $test = $page->getTemplate()->getProject();
</code>```

This is my approach:

```<code> $test = $page->getTemplate()->'get'.$fieldname();
</code>```

But I get the error message

syntax error, unexpected ''get'' (T_CONSTANT_ENCAPSED_STRING),
  expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

答:
```<code>$test = $page->getTemplate()->{'get' . $fieldname}();
</code>```

Also, I will mention that although getproject and getProject are the same method, this is not correct for properties.

Body:
I try to replace a variable inside my object method:

 $fieldname = "project";

 $test = $page->getTemplate()->getProject();

This is my approach:

 $test = $page->getTemplate()->'get'.$fieldname();

But I get the error message

syntax error, unexpected ''get'' (T_CONSTANT_ENCAPSED_STRING),
  expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

Body:
$test = $page->getTemplate()->{'get' . $fieldname}();

Also, I will mention that although getproject and getProject are the same method, this is not correct for properties.


问:
Calculations for ordered observations using mutate() based on conditional statements
I am trying to calculate growth rates between the specific rows after grouping by another variable (similar to other users).

Here is a sample of my data:

```<code>squirrel_id    wt   age    trialdate
   22639      9.7     0    2017-04-20
   22639      45.9   24    2017-05-14
   22639     130     53    2017-06-12 #caught 3x, 1 trial
   22640     10.3    0     2017-04-20
   22640     49.2    24    2017-05-14
   22640     121     52    2017-06-11
   22640     196     84    2017-07-13 #caught 4x, 2 trials
   23943     12.9     1    2018-04-27
   23943     57.2    26    2018-05-23 #caught 2x, 1 trial
   23760     150     73    2018-06-18
   23760     165     84    2018-06-29 #caught 2x, 2 trials
</code>```

To get this data in this form, I made sure to arrange_by(squirrel_id) first using the library(dplyr) package.

What I am trying to do is calculate the growth rate between:

last observation and second last observation divided by time that has passed (last_wt-second_last_wt/last_age-second_last_age): [using squirrel_id 22640: (196-121)/(84-52)] and then add a column called “trial” that says “2”

second last observation and third last observation divided by time that has passed (second_last_wt-third_last_wt/second_last_age-third_last_age): [using squirrel_id 22640: (121-49.2)/(52-24)] and then add a column called “trial” that says “1”

There is a catch though:

if a squirrel_id is seen 3 times or less in total (like squirrel_id 22639 and 23943), then they would usually only have had 1 trial and therefore 1 growth rate calculation.

BUT, if 2 of the observations are with an age > 40 days old (like squirrel_id 23760), then they had 2 trials.

My hope is to have a final dataset that looks like:

```<code>squirrel_id    wt   age    trialdate    g.rate     trial
   22639      9.7     0    2017-04-20   NA         NA
   22639      45.9   24    2017-05-14   NA         NA
   22639     130     53    2017-06-12   3.0        1     #caught 3x, 1 trial
   22640     10.3    0     2017-04-20   NA         NA
   22640     49.2    24    2017-05-14   NA         NA
   22640     121     52    2017-06-11   2.6         1
   22640     196     84    2017-07-13   2.3         2     #caught 4x, 2 trials
   23943     12.9     1    2018-04-27   NA         NA
   23943     57.2    26    2018-05-23   1.7         1     #caught 2x, 1 trial
   23760     150     73    2018-06-18    NA        1
   23760     165     84    2018-06-29    1.4        2     #caught 2x, 2 trials
</code>```

I’d prefer a dplyr() solution, if possible.

答:
Here is one way of doing it, using dplyr, assuming your data is df as set out above...

```<code>library(dplyr)
df %>%
  arrange(squirrel_id, age) %>%                        #sort by id and age
  group_by(squirrel_id) %>%                            #group by id
  mutate(g.rate = c(NA, diff(wt) / diff(age)),         #calculate g.rate
         trial = row_number() - n() + 2                #counting up to 2 at end
                 - (n() <= 3)                          #-1 if 3 or fewer in group
                 + (n() <= 3 & sort(-age)[2] <= -40),  #+1 if also both age>40
         trial = ifelse(trial<1, NA, trial),           #set to NA if less than 1
         g.rate = ifelse(is.na(trial), NA, g.rate))    #set to NA if trial is NA

   squirrel_id    wt   age trialdate  g.rate trial
 1       22639   9.7     0 2017-04-20  NA       NA
 2       22639  45.9    24 2017-05-14  NA       NA
 3       22639 130      53 2017-06-12   2.9      1
 4       22640  10.3     0 2017-04-20  NA       NA
 5       22640  49.2    24 2017-05-14  NA       NA
 6       22640 121      52 2017-06-11   2.56     1
 7       22640 196      84 2017-07-13   2.34     2
 8       23760 150      73 2018-06-18  NA        1
 9       23760 165      84 2018-06-29   1.36     2
10       23943  12.9     1 2018-04-27  NA       NA
11       23943  57.2    26 2018-05-23   1.77     1
</code>```

Note that the last two ids are in a different order than your data.  You can avoid this by just doing arrange(age) in the first step.

Body:
I am trying to calculate growth rates between the specific rows after grouping by another variable (similar to other users).

Here is a sample of my data:

squirrel_id    wt   age    trialdate
   22639      9.7     0    2017-04-20
   22639      45.9   24    2017-05-14
   22639     130     53    2017-06-12 #caught 3x, 1 trial
   22640     10.3    0     2017-04-20
   22640     49.2    24    2017-05-14
   22640     121     52    2017-06-11
   22640     196     84    2017-07-13 #caught 4x, 2 trials
   23943     12.9     1    2018-04-27
   23943     57.2    26    2018-05-23 #caught 2x, 1 trial
   23760     150     73    2018-06-18
   23760     165     84    2018-06-29 #caught 2x, 2 trials

To get this data in this form, I made sure to arrange_by(squirrel_id) first using the library(dplyr) package.

What I am trying to do is calculate the growth rate between:

last observation and second last observation divided by time that has passed (last_wt-second_last_wt/last_age-second_last_age): [using squirrel_id 22640: (196-121)/(84-52)] and then add a column called “trial” that says “2”

second last observation and third last observation divided by time that has passed (second_last_wt-third_last_wt/second_last_age-third_last_age): [using squirrel_id 22640: (121-49.2)/(52-24)] and then add a column called “trial” that says “1”

There is a catch though:

if a squirrel_id is seen 3 times or less in total (like squirrel_id 22639 and 23943), then they would usually only have had 1 trial and therefore 1 growth rate calculation.

BUT, if 2 of the observations are with an age > 40 days old (like squirrel_id 23760), then they had 2 trials.

My hope is to have a final dataset that looks like:

squirrel_id    wt   age    trialdate    g.rate     trial
   22639      9.7     0    2017-04-20   NA         NA
   22639      45.9   24    2017-05-14   NA         NA
   22639     130     53    2017-06-12   3.0        1     #caught 3x, 1 trial
   22640     10.3    0     2017-04-20   NA         NA
   22640     49.2    24    2017-05-14   NA         NA
   22640     121     52    2017-06-11   2.6         1
   22640     196     84    2017-07-13   2.3         2     #caught 4x, 2 trials
   23943     12.9     1    2018-04-27   NA         NA
   23943     57.2    26    2018-05-23   1.7         1     #caught 2x, 1 trial
   23760     150     73    2018-06-18    NA        1
   23760     165     84    2018-06-29    1.4        2     #caught 2x, 2 trials

I’d prefer a dplyr() solution, if possible.

Body:
Here is one way of doing it, using dplyr, assuming your data is df as set out above...

library(dplyr)
df %>%
  arrange(squirrel_id, age) %>%                        #sort by id and age
  group_by(squirrel_id) %>%                            #group by id
  mutate(g.rate = c(NA, diff(wt) / diff(age)),         #calculate g.rate
         trial = row_number() - n() + 2                #counting up to 2 at end
                 - (n() <= 3)                          #-1 if 3 or fewer in group
                 + (n() <= 3 & sort(-age)[2] <= -40),  #+1 if also both age>40
         trial = ifelse(trial<1, NA, trial),           #set to NA if less than 1
         g.rate = ifelse(is.na(trial), NA, g.rate))    #set to NA if trial is NA

   squirrel_id    wt   age trialdate  g.rate trial
 1       22639   9.7     0 2017-04-20  NA       NA
 2       22639  45.9    24 2017-05-14  NA       NA
 3       22639 130      53 2017-06-12   2.9      1
 4       22640  10.3     0 2017-04-20  NA       NA
 5       22640  49.2    24 2017-05-14  NA       NA
 6       22640 121      52 2017-06-11   2.56     1
 7       22640 196      84 2017-07-13   2.34     2
 8       23760 150      73 2018-06-18  NA        1
 9       23760 165      84 2018-06-29   1.36     2
10       23943  12.9     1 2018-04-27  NA       NA
11       23943  57.2    26 2018-05-23   1.77     1

Note that the last two ids are in a different order than your data.  You can avoid this by just doing arrange(age) in the first step.


问:
Uploadify suddenly stopped working completely in Chrome 10
I'm using Uploadify to allow for multi file uploading in my web application. It has always worked across IE 7,8, 9, FF 3.6, Safari and Chrome.

Today I discovered by accident that it was working in each browser yet not in Chrome. I'm currently on Chrome 10.0.648.82 beta. The issue there is that I can select files to upload, yet after that nothing happens. I put alerts in all Uploadify events and non get fired. Then I went to the official demo site:

http://www.uploadify.com/demos/

...and discovered that it does not work for Chrome there anymore either. I am running Chrome as default as can be, so it updated to this version itself. I have all default settings intact and no popup-blockers, ad blockers or any other add-in installed. I tried to debug using HTTP Fiddler, only to conclude no HTTP request is made at all after selecting files to upload.

Does anybody knows what is going on? Is this a Chrome issue or Flash issue? Are there any known resolutions?

PS: I am on Windows 7 64-bit.

答:
I agree, I think it is a Chrome or Flash issue (since Google ship Flash inside Chrome).

The uploadify demo page is working for me in Chrome 12.0.725.0 (which is the current dev release). You could try switching to the dev or beta channel to see if the issue is fixed for you.

Also, I found this other question that could help - Uploadify IO error #2038 random on Google Chrome

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Android Activity is Restarting Itself
I am making an app in which one of the features, the users location is updated once every 10 seconds. So far the app is not updating it's location because the activity is paused and restarted before the location is retrieved.  I don't understand why the activity is being restarted.  My best guess is, since there is not a whole lot going on, the OS is pausing the activity, but what will trigger the activity to restart?  I have attempted to built the app before, and then I restarted from scratch because I made too many mistakes but even then, I have not seen this problem before.

```<code>D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
D/myLocation: Connection Requested
V/FA: Activity resumed, time: 8562145
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 32
V/FA: Activity paused, time: 8562177
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
D/myLocation: Connection Requested
V/FA: Activity resumed, time: 8562374
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 162
V/FA: Activity paused, time: 8562535
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
V/FA: Activity resumed, time: 8562971
D/myLocation: Connection Requested
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 20
V/FA: Activity paused, time: 8562991
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
V/FA: Activity resumed, time: 8563169
D/myLocation: Connection Requested
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
I/art: Background partial concurrent mark sweep GC freed 25697(1746KB) AllocSpace objects, 6(96KB) LOS objects, 33% free, 31MB/47MB, paused 3.173ms total 176.879ms
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 171
V/FA: Activity paused, time: 8563339
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
V/FA: Activity resumed, time: 8563432
D/myLocation: Connection Requested
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@21fc22ec time:3722364
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@39b2d053 time:3722365
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@2c7d74f4 time:3722366
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@14c588fb time:3722366
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@447b885 time:3722366
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@32c680a3 time:3722367
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3948204 time:3722367
V/ActivityThread: updateVisibility : ActivityRecord{252a28bb token=android.os.BinderProxy@247ca0d3 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{26fe81d8 token=android.os.BinderProxy@3948204 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{2afd4931 token=android.os.BinderProxy@32c680a3 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{70b4816 token=android.os.BinderProxy@447b885 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{6c89597 token=android.os.BinderProxy@14c588fb {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{ac5e384 token=android.os.BinderPr
</code>```

Here is the class I made to update the location automatically:

```<code>    package user.com.commuterapp;

        import android.Manifest;

        import android.app.Activity;
        import android.app.PendingIntent;
        import android.content.Context;
        import android.support.annotation.NonNull;
        import android.support.annotation.Nullable;
        import android.support.v4.app.ActivityCompat;
        import android.os.Bundle;
        import android.content.pm.PackageManager;

        import com.google.android.gms.common.api.GoogleApiClient;
        import com.google.android.gms.location.LocationServices;
        import com.google.android.gms.location.LocationListener;
        import com.google.android.gms.location.LocationRequest;
        import com.google.android.gms.common.ConnectionResult;

        import android.location.Location;
        import android.content.IntentSender;

        import android.util.Log;
        import android.support.v4.content.ContextCompat;
        import android.content.Context;

        /**
         * Created by XXX XXXXX on 11/27/2016.
         *
         * Function: A simple interface that utilizes Google API CLient to update the users location
         * once every 15 seconds.  Used when the user wants the select his/her current location as his travel
         * origin.
         *
         * This class implements the Google API Client Connection Callbacks to async process successful connection requests
         * This class implements the Google API Client onConnectionFailedListener to async process failed connec

tion requests
     * This class implements the Google API Client onRequestPermissionResultCallback to async process user permission requests
     * for location updtaes
     */

    public class myLocation implements
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            ActivityCompat.OnRequestPermissionsResultCallback,
            LocationListener {
        private final static String TAG = "myLocation"; // for debugging purposes, to tell user the origin class for debug information
        private final static int MY_PERMISSION_ACCESS_FINE_LOCATION = 1;
        private final static long ONE_SECOND = 1000;
        private final static long UPDATE_INTERVAL = ONE_SECOND;
        private final static long FASTEST_UPDATE_INTERVAL = ONE_SECOND;

        public GoogleApiClient mGoogleApiClient = null;  //Google API Client object
        public Location mCurrentLocation; //current location of phone

        private Context mParentBase; //Global information on app environment from parent class to be used to create Google API Client Object
        private Activity mParentActivity; //Contains parent classes information on presentation layer
        private PendingIntent mParentIntent; //Passes on the rights to the application to another activity
        private LocationRequest requestLocation; //Object that contains auto location update paramaters

        /**
         * Constructor for my location, recieves calling classes Conxtext, Intent and Activity
         * Information
         *
         * @param Base
         * @param activitiyBase
         * @param intent
         */
        public myLocation(Context Base, Activity activitiyBase, PendingIntent intent) {
            mParentBase = Base;
            mParentActivity = activitiyBase;
            mParentIntent = intent;
            initialLocationService();
        }

        /**
         *  Public class to initiate connection to the API
         */
        public void connect() {
            mGoogleApiClient.connect();
            Log.d(TAG, "Connection Requested");
        }

        /**
         * Override public class from Google API Connection Callback,
         * Called when application has connected to the API.
         * @param bundle
         */

        @Override
        public void onConnected(@Nullable Bundle bundle) {

            Log.d(TAG, "OnConnected");

            if (PackageManager.PERMISSION_GRANTED ==
                    (ContextCompat.checkSelfPermission(mParentBase,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)))

            {
                Log.d(TAG, "Permission Was Granted");
                //mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, requestLocation, mParentIntent);

                if (mCurrentLocation == null) {

                } else {
                    Log.d(TAG, mCurrentLocation.toString());
                }

            } else {
                ActivityCompat.requestPermissions(mParentActivity,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSION_ACCESS_FINE_LOCATION);
                Log.d(TAG, "Permission Was Requested");
            }
        }

        /**
         * Override from GoogleAPI connection override failed listener.  Used when the connection o the API
         * has failed
         * @param connectionResult
         */

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
            Log.i(TAG, "Connection Failed");
            // just logging for now
        }

        /**
         * Not added, but will be used when permission to access phone location is not granted
         * @param requestCode
         * @param permissions
         * @param grantResults
         */
        @Override
        public void onRequestPermissionsResult(int requestCode,
                                               @NonNull String[] permissions, @NonNull int[] grantResults) {
            // loading from Android Studio, not going to worry about this now
        }

        @Override
        public void onConnectionSuspended(int i) {
            Log.i(TAG, "Connection Suspended");
            // just logging for now, not trying to resolve failure
        }

        /**
         * Callback for when a new location is recieved
         * @param location
         */

        @Override
        public void onLocationChanged(Location location) {
            Log.i(TAG, "Entered the onLocationChanged() method");
            // this calls one or the other private methods that don't
            //    matter to your problem.  I can post them if you like.
            if (location != null) {
                Log.d(TAG, location.toString());
                mCurrentLocation = location;
            } else {
                Log.d(TAG, "Can't get last location");

            }
        }

        /**
         * Initializes new Google API Client and Automatic Location Updates
         */

        private void initialLocationService() {
            if (mGoogleApiClient == null) {
                mGoogleApiClient = new GoogleApiClient.Builder(mParentBase)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();

                requestLocation = LocationRequest.create()
                        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                        .setInterval(1 * 1000)        // 15 seconds, in milliseconds
                        .setFastestInterval(1 * 1000); // 15 second, in milliseconds
            }

        }

    }
</code>```

Here is the main activity code:

```<code>package user.com.commuterapp;

import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

import user.com.commuterapp.R;

import static java.lang.Boolean.TRUE;

    public class selectRouteAndTransportMethod extends AppCompatActivity {

        Intent mIntent;
        PendingIntent mPendingIntent;
        myLocation mCurrentLocation;
        public static final String TAG = selectRouteAndTransportMethod.class.getSimpleName();
        /**
         * ATTENTION: This was auto-generated to implement the App Indexing API.
         * See https://g.co/AppIndexing/AndroidStudio for more information.
         */
        private GoogleApiClient client;

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

            mIntent = new Intent(this, selectRouteAndTransportMethod.class);
            mPendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);
            mCurrentLocation = new myLocation(this, this, mPendingIntent);
            // ATTENTION: This was auto-generated to implement the App Indexing API.

            // See https://g.co/AppIndexing/AndroidStudio for more information.

        }

        @Override
        protected void onStart() {
            super.onStart();

            Log.d(TAG, "On Start");

            mCurrentLocation.connect();

            boolean connecting = mCurrentLocation.mGoogleApiClient.isConnecting();
            boolean registered = mCurrentLocation.mGoogleApiClient.isConnectionCallbacksRegistered(mCurrentLocation);
                //ConnectionResult connectionResult = mCurrentLocation.mGoogleApiClient.getConnectionResult(LocationServices.API);

            if (connecting == TRUE) {
                Log.d(TAG, "Connecting");
                }

            if (registered == TRUE) {
                Log.d(TAG, "registered");
            }
        }

        @Override
        protected void onResume() {
            super.onResume();
            mCurrentLocation.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
         //   mCurrentLocation.disconnect();
        }

}
</code>```

答:
Is the requested permission included in the manifest?

This is an old question, but I found it when I ran into the same problem:

App keeps pausing and resuming, in an endless loop, but doesn't throw an exception

In my case, the line where permissions were requested was causing the problem.

```<code>ActivityCompat.requestPermissions(mParentActivity,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSION_ACCESS_FINE_LOCATION);
</code>```

I was requesting the CALL_PHONE permission, but had removed it (because I wasn't using it anymore), but did not remove the permission check. Two possible solutions:

Add the requested permission to the manifest.

uses-permission android:name="android.permission.CALL_PHONE"

Remove the line requesting the permission (only if you don't need it anymore, of course.)

Title: Android Activity is Restarting Itself

Body:
I am making an app in which one of the features, the users location is updated once every 10 seconds. So far the app is not updating it's location because the activity is paused and restarted before the location is retrieved.  I don't understand why the activity is being restarted.  My best guess is, since there is not a whole lot going on, the OS is pausing the activity, but what will trigger the activity to restart?  I have attempted to built the app before, and then I restarted from scratch because I made too many mistakes but even then, I have not seen this problem before.

D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
D/myLocation: Connection Requested
V/FA: Activity resumed, time: 8562145
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 32
V/FA: Activity paused, time: 8562177
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
D/myLocation: Connection Requested
V/FA: Activity resumed, time: 8562374
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 162
V/FA: Activity paused, time: 8562535
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
V/FA: Activity resumed, time: 8562971
D/myLocation: Connection Requested
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 20
V/FA: Activity paused, time: 8562991
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
V/FA: Activity resumed, time: 8563169
D/myLocation: Connection Requested
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
I/art: Background partial concurrent mark sweep GC freed 25697(1746KB) AllocSpace objects, 6(96KB) LOS objects, 33% free, 31MB/47MB, paused 3.173ms total 176.879ms
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 171
V/FA: Activity paused, time: 8563339
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
V/FA: onActivityCreated
D/Activity: performCreate Call secproduct feature valuefalse
D/Activity: performCreate Call debug elastic valuetrue
D/selectRouteAndTransportMethod: On Start
D/myLocation: Connection Requested
D/selectRouteAndTransportMethod: Connecting
D/selectRouteAndTransportMethod: registered
V/FA: Activity resumed, time: 8563432
D/myLocation: Connection Requested
D/myLocation: OnConnected
D/myLocation: Permission Was Granted
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@21fc22ec time:3722364
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@39b2d053 time:3722365
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@2c7d74f4 time:3722366
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@14c588fb time:3722366
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@447b885 time:3722366
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@32c680a3 time:3722367
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3948204 time:3722367
V/ActivityThread: updateVisibility : ActivityRecord{252a28bb token=android.os.BinderProxy@247ca0d3 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{26fe81d8 token=android.os.BinderProxy@3948204 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{2afd4931 token=android.os.BinderProxy@32c680a3 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{70b4816 token=android.os.BinderProxy@447b885 {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{6c89597 token=android.os.BinderProxy@14c588fb {user.com.commuterapp/user.com.commuterapp.selectRouteAndTransportMethod}} show : false
V/ActivityThread: updateVisibility : ActivityRecord{ac5e384 token=android.os.BinderPr

Here is the class I made to update the location automatically:

    package user.com.commuterapp;

        import android.Manifest;

        import android.app.Activity;
        import android.app.PendingIntent;
        import android.content.Context;
        import android.support.annotation.NonNull;
        import android.support.annotation.Nullable;
        import android.support.v4.app.ActivityCompat;
        import android.os.Bundle;
        import android.content.pm.PackageManager;

        import com.google.android.gms.common.api.GoogleApiClient;
        import com.google.android.gms.location.LocationServices;
        import com.google.android.gms.location.LocationListener;
        import com.google.android.gms.location.LocationRequest;
        import com.google.android.gms.common.ConnectionResult;

        import android.location.Location;
        import android.content.IntentSender;

        import android.util.Log;
        import android.support.v4.content.ContextCompat;
        import android.content.Context;

        /**
         * Created by XXX XXXXX on 11/27/2016.
         *
         * Function: A simple interface that utilizes Google API CLient to update the users location
         * once every 15 seconds.  Used when the user wants the select his/her current location as his travel
         * origin.
         *
         * This class implements the Google API Client Connection Callbacks to async process successful connection requests
         * This class implements the Google API Client onConnectionFailedListener to async process failed connec

tion requests
     * This class implements the Google API Client onRequestPermissionResultCallback to async process user permission requests
     * for location updtaes
     */

    public class myLocation implements
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            ActivityCompat.OnRequestPermissionsResultCallback,
            LocationListener {
        private final static String TAG = "myLocation"; // for debugging purposes, to tell user the origin class for debug information
        private final static int MY_PERMISSION_ACCESS_FINE_LOCATION = 1;
        private final static long ONE_SECOND = 1000;
        private final static long UPDATE_INTERVAL = ONE_SECOND;
        private final static long FASTEST_UPDATE_INTERVAL = ONE_SECOND;

        public GoogleApiClient mGoogleApiClient = null;  //Google API Client object
        public Location mCurrentLocation; //current location of phone

        private Context mParentBase; //Global information on app environment from parent class to be used to create Google API Client Object
        private Activity mParentActivity; //Contains parent classes information on presentation layer
        private PendingIntent mParentIntent; //Passes on the rights to the application to another activity
        private LocationRequest requestLocation; //Object that contains auto location update paramaters

        /**
         * Constructor for my location, recieves calling classes Conxtext, Intent and Activity
         * Information
         *
         * @param Base
         * @param activitiyBase
         * @param intent
         */
        public myLocation(Context Base, Activity activitiyBase, PendingIntent intent) {
            mParentBase = Base;
            mParentActivity = activitiyBase;
            mParentIntent = intent;
            initialLocationService();
        }

        /**
         *  Public class to initiate connection to the API
         */
        public void connect() {
            mGoogleApiClient.connect();
            Log.d(TAG, "Connection Requested");
        }

        /**
         * Override public class from Google API Connection Callback,
         * Called when application has connected to the API.
         * @param bundle
         */

        @Override
        public void onConnected(@Nullable Bundle bundle) {

            Log.d(TAG, "OnConnected");

            if (PackageManager.PERMISSION_GRANTED ==
                    (ContextCompat.checkSelfPermission(mParentBase,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)))

            {
                Log.d(TAG, "Permission Was Granted");
                //mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, requestLocation, mParentIntent);

                if (mCurrentLocation == null) {

                } else {
                    Log.d(TAG, mCurrentLocation.toString());
                }

            } else {
                ActivityCompat.requestPermissions(mParentActivity,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSION_ACCESS_FINE_LOCATION);
                Log.d(TAG, "Permission Was Requested");
            }
        }

        /**
         * Override from GoogleAPI connection override failed listener.  Used when the connection o the API
         * has failed
         * @param connectionResult
         */

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
            Log.i(TAG, "Connection Failed");
            // just logging for now
        }

        /**
         * Not added, but will be used when permission to access phone location is not granted
         * @param requestCode
         * @param permissions
         * @param grantResults
         */
        @Override
        public void onRequestPermissionsResult(int requestCode,
                                               @NonNull String[] permissions, @NonNull int[] grantResults) {
            // loading from Android Studio, not going to worry about this now
        }

        @Override
        public void onConnectionSuspended(int i) {
            Log.i(TAG, "Connection Suspended");
            // just logging for now, not trying to resolve failure
        }

        /**
         * Callback for when a new location is recieved
         * @param location
         */

        @Override
        public void onLocationChanged(Location location) {
            Log.i(TAG, "Entered the onLocationChanged() method");
            // this calls one or the other private methods that don't
            //    matter to your problem.  I can post them if you like.
            if (location != null) {
                Log.d(TAG, location.toString());
                mCurrentLocation = location;
            } else {
                Log.d(TAG, "Can't get last location");

            }
        }

        /**
         * Initializes new Google API Client and Automatic Location Updates
         */

        private void initialLocationService() {
            if (mGoogleApiClient == null) {
                mGoogleApiClient = new GoogleApiClient.Builder(mParentBase)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .addApi(LocationServices.API)
                        .build();

                requestLocation = LocationRequest.create()
                        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                        .setInterval(1 * 1000)        // 15 seconds, in milliseconds
                        .setFastestInterval(1 * 1000); // 15 second, in milliseconds
            }

        }

    }

Here is the main activity code:

package user.com.commuterapp;

import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

import user.com.commuterapp.R;

import static java.lang.Boolean.TRUE;

    public class selectRouteAndTransportMethod extends AppCompatActivity {

        Intent mIntent;
        PendingIntent mPendingIntent;
        myLocation mCurrentLocation;
        public static final String TAG = selectRouteAndTransportMethod.class.getSimpleName();
        /**
         * ATTENTION: This was auto-generated to implement the App Indexing API.
         * See https://g.co/AppIndexing/AndroidStudio for more information.
         */
        private GoogleApiClient client;

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

            mIntent = new Intent(this, selectRouteAndTransportMethod.class);
            mPendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);
            mCurrentLocation = new myLocation(this, this, mPendingIntent);
            // ATTENTION: This was auto-generated to implement the App Indexing API.

            // See https://g.co/AppIndexing/AndroidStudio for more information.

        }

        @Override
        protected void onStart() {
            super.onStart();

            Log.d(TAG, "On Start");

            mCurrentLocation.connect();

            boolean connecting = mCurrentLocation.mGoogleApiClient.isConnecting();
            boolean registered = mCurrentLocation.mGoogleApiClient.isConnectionCallbacksRegistered(mCurrentLocation);
                //ConnectionResult connectionResult = mCurrentLocation.mGoogleApiClient.getConnectionResult(LocationServices.API);

            if (connecting == TRUE) {
                Log.d(TAG, "Connecting");
                }

            if (registered == TRUE) {
                Log.d(TAG, "registered");
            }
        }

        @Override
        protected void onResume() {
            super.onResume();
            mCurrentLocation.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
         //   mCurrentLocation.disconnect();
        }

}

Body:
Is the requested permission included in the manifest?

This is an old question, but I found it when I ran into the same problem:

App keeps pausing and resuming, in an endless loop, but doesn't throw an exception

In my case, the line where permissions were requested was causing the problem.

ActivityCompat.requestPermissions(mParentActivity,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSION_ACCESS_FINE_LOCATION);

I was requesting the CALL_PHONE permission, but had removed it (because I wasn't using it anymore), but did not remove the permission check. Two possible solutions:

Add the requested permission to the manifest.

uses-permission android:name="android.permission.CALL_PHONE"

Remove the line requesting the permission (only if you don't need it anymore, of course.)


问:
how to check if (c#) ControlCollection.Find() has returned a result
I am using ControlCollection.Find() method in C# to find some picture boxes present in my form.

I am storing the returned result in a Control[] array. How do I find out if the Find() was successful or not???

Code

```<code>Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
    UpdateRes = update_status(TagNo, Status);
</code>```

where TagNo is a string containing the Control's exact name.

Yes. I'm using the control's exact name. And I have used the Find() method successfully earlier (when the Control was surely present in the Collection). I am having a problem this time because the control may or may not be present in the Collection.

答:
Safest way will be to check if the returned array is not null and has Length of more than 0:

```<code>Control[] children = this.Find("mypic", true);
if (children != null && children.Length > 0)
{
   //OK to proceed...
}
</code>```

Body:
I am using ControlCollection.Find() method in C# to find some picture boxes present in my form.

I am storing the returned result in a Control[] array. How do I find out if the Find() was successful or not???

Code

Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
    UpdateRes = update_status(TagNo, Status);

where TagNo is a string containing the Control's exact name.

Yes. I'm using the control's exact name. And I have used the Find() method successfully earlier (when the Control was surely present in the Collection). I am having a problem this time because the control may or may not be present in the Collection.

Body:
Safest way will be to check if the returned array is not null and has Length of more than 0:

Control[] children = this.Find("mypic", true);
if (children != null && children.Length > 0)
{
   //OK to proceed...
}


问:
How can my node.js server on AWS handle multiple users generating images when node calls Python program?
I have containerized node.js code that runs on ECS. When multiple users use node.js to call a .py image generating problem, only 1 user gets the image, the rest get errors. I wonder if it appropriate to use Lambda so that the image generation multithreads.

For some reason, the containerized code which uses docker works locally, but not on AWS when multiple users access the .py function.

答:
If users send images from mobile application, you can use aws-sdk to upload images from mobile device to AWS S3, and configure Lambda trigger for image upload.
This Lambda will process image data and return you the result.

Since Lambda from serverless world, it can handle really big amount of invocations.

So, in case if you/your team can add aws-sdk to mobile application, it's nice approach to upload image directly from device to S3, trigger Lambda to image processing and change user's data in some storage.

If you have untrusted environment, like user's browser, it's not O.K. to upload image directly from browser to S3, since to achieve this goal you have to provide AWS access keys.

So, in this case, it's O.K. to upload image to server and transfer image from server to S3.

After this, the logic keeps the same: trigger AWS Lambda, process data and update it in storage.

This behaviour will reduce load to the server and allows you to work on features, instead of working on image storing and other stuff, which will just bother your server.


问:
Adding restrictions to validate json data send to Rails API
So I've been creating a Rails API (A school project) and everything works fine, but now I want to add some restrictions to the POST endpoint.
So here is my create endpoint when I'm going to foo.com/api/v1/slogans :

```<code>def create
  slogan = Slogan.new(slogan_params)
  if(slogan.save)
    render json: {
      status: 'SUCCESS',
      message: 'Saved slogan',
      data: slogan
    }, status: :ok
  else
    render json: {
      status: 'ERROR',
      message: 'Slogan not saved',
      data: slogan.error
    }, status: :unprocessable_entity
  end
end
</code>```

And these are my slogan_params :

```<code>private def slogan_params
  params.permit(:firstname, :lastname, :email, :slogan)
end
</code>```

Now how do I add restrictions to this, for example a character limit? I've already added one on my front end but I want to be sure that even if the front end is manipulated that the data don't get submitted if valid.

I thought about adding something in def create but not sure if that is the way to do it.

答:
You can use

class Slogan < ActiveRecord::Base
  validates :email, presence: true
end
```

<p>And in controller you can do</p>

<pre class="lang-rb prettyprint-override"><code>def create
  slogan = Slogan.new(slogan_params)
  if slogan.valid?
    slogan.save
    render json: {
      status: 'SUCCESS',
      message: 'Saved slogan',
      data: slogan
    }, status: :ok
  else
    render json: {
      status: 'ERROR',
      message: 'Slogan not saved',
      data: slogan.errors
    }, status: :unprocessable_entity
  end
end
</code>```

Body:
So I've been creating a Rails API (A school project) and everything works fine, but now I want to add some restrictions to the POST endpoint.
So here is my create endpoint when I'm going to foo.com/api/v1/slogans :

def create
  slogan = Slogan.new(slogan_params)
  if(slogan.save)
    render json: {
      status: 'SUCCESS',
      message: 'Saved slogan',
      data: slogan
    }, status: :ok
  else
    render json: {
      status: 'ERROR',
      message: 'Slogan not saved',
      data: slogan.error
    }, status: :unprocessable_entity
  end
end

And these are my slogan_params :

private def slogan_params
  params.permit(:firstname, :lastname, :email, :slogan)
end

Now how do I add restrictions to this, for example a character limit? I've already added one on my front end but I want to be sure that even if the front end is manipulated that the data don't get submitted if valid.

I thought about adding something in def create but not sure if that is the way to do it.

Body:
You can use

class Slogan < ActiveRecord::Base
  validates :email, presence: true
end

And in controller you can do

def create
  slogan = Slogan.new(slogan_params)
  if slogan.valid?
    slogan.save
    render json: {
      status: 'SUCCESS',
      message: 'Saved slogan',
      data: slogan
    }, status: :ok
  else
    render json: {
      status: 'ERROR',
      message: 'Slogan not saved',
      data: slogan.errors
    }, status: :unprocessable_entity
  end
end


问:
how to Get behaviour of super.onbackpressed() within overrided onbackpressed()
I was tried to go back with confirmation dialog so that i was decided to handle onbackpressed() and then i had put my code for confirm dialog with ok and cancel button for null listener.

```<code>@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Confirmation");
    builder.setMessage("Are you sure want to exit?");
    builder.setPositiveButton("OK",null);
    builder.setNegativeButton("Cancel", null);
    builder.show();
}
</code>```

It was worked fine but the problem is if i click ok but it should continue for behaviour of super.onbackpressed() otherwise it should be in same activity.

the following code that i had tried.

```<code>@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Confirmation");
    builder.setMessage("Are you sure want to exit?");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            //super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", null);
    builder.show();
}
</code>```

答:
To call the exact same super method:</p>

```<code>YourActivity.super.onBackPressed();
</code>```

Body:
I was tried to go back with confirmation dialog so that i was decided to handle onbackpressed() and then i had put my code for confirm dialog with ok and cancel button for null listener.

@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Confirmation");
    builder.setMessage("Are you sure want to exit?");
    builder.setPositiveButton("OK",null);
    builder.setNegativeButton("Cancel", null);
    builder.show();
}

It was worked fine but the problem is if i click ok but it should continue for behaviour of super.onbackpressed() otherwise it should be in same activity.

the following code that i had tried.

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Confirmation");
    builder.setMessage("Are you sure want to exit?");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            //super.onBackPressed();
        }
    });
    builder.setNegativeButton("Cancel", null);
    builder.show();
}

Body:
To call the exact same super method:

YourActivity.super.onBackPressed();


问:
JSON returning as undefined
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

```<code>$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });
</code>```

答:
how do you return the $succes array?

You should echo the array in a way that would preserve it's format and would be understandable to javascript (not print_r or var_dump):

```<code>echo json_decode($success);
</code>```

that will return a json string representing your php array, which js automatically converts into an object.

Hope this helps.

Title: JSON returning as undefined

Body:
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });

Body:
how do you return the $succes array?

You should echo the array in a way that would preserve it's format and would be understandable to javascript (not print_r or var_dump):

echo json_decode($success);

that will return a json string representing your php array, which js automatically converts into an object.

Hope this helps.


问:
How can I rebase multiple branches at once?
I currently work on a project in which SVN is used as a repository. Locally, I do several "experiments" with the code that I don't want to commit to the repo. Therefore I use git locally on top of the SVN working directory and use multiple branches for different "experiments". So it looks e.g. like this.

```<code>C0 ---- C7 (master)
 \
  \---- C1 ---- C2 ---- C4 (exp1)
   \     \       \
    \     \       \---- C3 (exp2)
     \     \
      \     \---- C5 (exp3)
       \
        \---- C6 (exp4)
</code>```

On branch master I want to have the untainted SVN repo, i.e. C0 is SVN Repo Revision x and C7 is SVN Repo Revision x + n.

Is it somehow easily possible to rebase all the exp branches onto C7 at once in such a way that the tree will look like the following diagram?

```<code>C0 ---- C7 (master)
         \
          \---- C1' ---- C2' ---- C4' (exp1)
           \     \         \
            \     \         \---- C3' (exp2)
             \     \
              \     \---- C5' (exp3)
               \
                \---- C6' (exp4)
</code>```

I want to use rebase since I don't want to modify the state of my local SVN Checkout and want to have my changes built on top of the SVN revisions.

I'm also interested in solutions that work from within SourceTree without having to use the shell.

答:
You can rebase multiple branches / trees with a small trick.

Create a DUMMY_BRANCH e.g. at location of master

Merge all branches you like to move into DUMMY_BRANCH (Using a --no-ff Merge) - Update for comments from @kdb, @franckspike

rebase DUMMY_BRANCH to your desired new point and add --preserve-merges option to your rebase-command

After rebasing manually each of you branches to the rebased commits (e.g. for C4 git reset --hard [Commit-hash of C4' (exp1)]

when you have moved all your branches, delete the rebased DUMMY_BRANCH

Body:
I currently work on a project in which SVN is used as a repository. Locally, I do several "experiments" with the code that I don't want to commit to the repo. Therefore I use git locally on top of the SVN working directory and use multiple branches for different "experiments". So it looks e.g. like this.

C0 ---- C7 (master)
 \
  \---- C1 ---- C2 ---- C4 (exp1)
   \     \       \
    \     \       \---- C3 (exp2)
     \     \
      \     \---- C5 (exp3)
       \
        \---- C6 (exp4)

On branch master I want to have the untainted SVN repo, i.e. C0 is SVN Repo Revision x and C7 is SVN Repo Revision x + n.

Is it somehow easily possible to rebase all the exp branches onto C7 at once in such a way that the tree will look like the following diagram?

C0 ---- C7 (master)
         \
          \---- C1' ---- C2' ---- C4' (exp1)
           \     \         \
            \     \         \---- C3' (exp2)
             \     \
              \     \---- C5' (exp3)
               \
                \---- C6' (exp4)

I want to use rebase since I don't want to modify the state of my local SVN Checkout and want to have my changes built on top of the SVN revisions.

I'm also interested in solutions that work from within SourceTree without having to use the shell.


问:
How to write response filter?
Is there a way to handle only response in a filter .

Is the code written below correct ?

```<code>  public void doFilter(request , response , chain) {
        //code to handle request
          chain.doFilter(request, response);
        //code to handle response .
  }
</code>```

答:
It depends on what you want. In general, your sample is not correct though. After chain.doFilter has returned, it's too late to do anything with the response. At this point, entire response was already sent to the client and your code has no access to it.

What you need to do is to wrap request and/or response into your own classes, pass these wrappers into doFilter method and handle any processing in your wrappers.

To make it easier, there are already wrappers available in servlet api: see HttpServletRequestWrapper and HttpServletResponseWrapper classes. If you want to process output that is actually sent to client, you also need to write custom OutputStream or Writer wrappers, and return those from your HttpServletResponse wrapper. Yeah, lot of wrapping :)

Some simpler filters can work without wrapping request or response: e.g. before calling doFilter, you can already access request headers or you can send custom response without calling doFilter. But if you want to process request body, you cannot just read it, otherwise it won't be available to the rest of the chain. In this case you need to use the wrapping technique again.

Title: How to write response filter?

Body:
Is there a way to handle only response in a filter .

Is the code written below correct ?

  public void doFilter(request , response , chain) {
        //code to handle request
          chain.doFilter(request, response);
        //code to handle response .
  }


问:
serving images with graphql
I have graphql server built by express-graphql and I use mongoDb to store images in normal database collection since they are < 16MB.

I have react and android app. What is the best way to serve these images to the clients.

In my schema I have something like this.

```<code>const productSchema = new Schema({
views: {type: Number, default: 0},
//Storing only thumbnail in this document.
thumbnail: {data: Buffer, contentType: String},
</code>```

});
And in my schema I have something like

```<code>const productType = new GraphQLObjectType({
    name: 'Product',
    fields: () => ({
        //.........
        thumbnail: {type: 'WHAT TO DO HERE'},
        views: {type: new GraphQLNonNull(GraphQLInt)}
        //.........
    }),
});
</code>```

Edit:
I created a router like this.

```<code>router.get('/t/:productId', function (req, res) {
    const productId = req.params.productId;

    Product.findById(productId, {thumbnail: true}).then(thumbnail => {
        res.contentType(thumbnail.contentType);
        res.end(thumbnail.data, "binary");
    }).catch(e => {
        console.error(e);
        res.sendStatus(404);
    });
});
</code>```

答: GraphQL.js responses are serialized as JSON, which means you can't serve images with it. You can return either a URL or a Base64-encoded string representing the image, as described in this answer. Either way the type for your field would be GraphQLString.

Title: serving images with graphql

Body:
I have graphql server built by express-graphql and I use mongoDb to store images in normal database collection since they are < 16MB.

I have react and android app. What is the best way to serve these images to the clients.

In my schema I have something like this.

const productSchema = new Schema({
views: {type: Number, default: 0},
//Storing only thumbnail in this document.
thumbnail: {data: Buffer, contentType: String},

});
And in my schema I have something like

const productType = new GraphQLObjectType({
    name: 'Product',
    fields: () => ({
        //.........
        thumbnail: {type: 'WHAT TO DO HERE'},
        views: {type: new GraphQLNonNull(GraphQLInt)}
        //.........
    }),
});

Edit:
I created a router like this.

router.get('/t/:productId', function (req, res) {
    const productId = req.params.productId;

    Product.findById(productId, {thumbnail: true}).then(thumbnail => {
        res.contentType(thumbnail.contentType);
        res.end(thumbnail.data, "binary");
    }).catch(e => {
        console.error(e);
        res.sendStatus(404);
    });
});


问:
Why can't Bouncycastle's PEMReader read this M2Crypto-generated PEM?
I use the following Python code, using M2Crypto, to generate an RSA key pair in PEM format:

```<code>bio = BIO.MemoryBuffer()
key_pair = RSA.gen_key(1024, 65537)
key_pair.save_key_bio(bio, cipher=None)
return bio.read()
</code>```

And the following Java code, using Bouncycastle, to try to read it:

```<code>String signPem = ...;
PEMReader pemReader = new PEMReader(new StringReader(signPem));
Object signingKey = pemReader.readObject();
</code>```

The signPem string is the same as what bio.read() returned; no data that I can see is getting munged between the two programs; it's -----BEGIN RSA PRIVATE KEY-----\n etc.

However, the readObject() call throws a ClassCastException:

```<code>java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence
    at org.bouncycastle.asn1.ASN1Object.fromByteArray(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readKeyPair(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readObject(Unknown Source)
</code>```

So obviously BC misidentifies the data in the PEM is not a key pair for some reason - but why?

答:
After taking a debugger to Bouncycastle, I have discovered the "cause", but it only puzzles me more; the cast is failing even though all types seem to be correct.

If A extends B extends C, why can I cast to A but get a ClassCastException casting to C?

Body:
I use the following Python code, using M2Crypto, to generate an RSA key pair in PEM format:

bio = BIO.MemoryBuffer()
key_pair = RSA.gen_key(1024, 65537)
key_pair.save_key_bio(bio, cipher=None)
return bio.read()

And the following Java code, using Bouncycastle, to try to read it:

String signPem = ...;
PEMReader pemReader = new PEMReader(new StringReader(signPem));
Object signingKey = pemReader.readObject();

The signPem string is the same as what bio.read() returned; no data that I can see is getting munged between the two programs; it's -----BEGIN RSA PRIVATE KEY-----\n etc.

However, the readObject() call throws a ClassCastException:

java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence
    at org.bouncycastle.asn1.ASN1Object.fromByteArray(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readKeyPair(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readObject(Unknown Source)

So obviously BC misidentifies the data in the PEM is not a key pair for some reason - but why?


问:
corrplot: Changing to times new roman corrplot() output
I've like to create an image using corrplot() function in corrplot package in times new roman without success. I try to use par(family="Times"), but doesn't work and in help of the function don't have font type control. I try to make:

```<code>library(corrplot)
data(mtcars)
M <- cor(mtcars)
## plot
par(family="Times")
corrplot(M, method = "number", col = "black", cl.pos = "n")
#
</code>```

Please, any ideas? Thanks

答:
I'm not sure it will work but I think this post will help you :

Changing fonts in ggplot2

It will not help you but it is a really good post on font for R so I leave it on my answer.

Are you on windows or unix ? If you are on windows this following answer will help you, if not I don't know.

The problem is just coming from the fact that you are using Times wherease it is Times New Roman needed.

You can check it with the following line of code :

```<code>windowsFonts()
par(family="Times New Roman")
corrplot(M, method = "number", col = "black", cl.pos = "n")
</code>```

In fact TT is the first letter of TrueType and it is common for all fonts. If you want a specific font you should not use TT. See :

https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/windowsFonts.html

Body:
I've like to create an image using corrplot() function in corrplot package in times new roman without success. I try to use par(family="Times"), but doesn't work and in help of the function don't have font type control. I try to make:

library(corrplot)
data(mtcars)
M <- cor(mtcars)
## plot
par(family="Times")
corrplot(M, method = "number", col = "black", cl.pos = "n")
#

Please, any ideas? Thanks

Body:
I'm not sure it will work but I think this post will help you :

Changing fonts in ggplot2

It will not help you but it is a really good post on font for R so I leave it on my answer.

Are you on windows or unix ? If you are on windows this following answer will help you, if not I don't know.

The problem is just coming from the fact that you are using Times wherease it is Times New Roman needed.

You can check it with the following line of code :

windowsFonts()
par(family="Times New Roman")
corrplot(M, method = "number", col = "black", cl.pos = "n")

In fact TT is the first letter of TrueType and it is common for all fonts. If you want a specific font you should not use TT. See :

https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/windowsFonts.html


问:
Consuming a queue based on its consumer count in Spring AMQP
I want a queue to be consumed by only one subscriber at a time. So if one subscriber drops, then another one(s) will have the chance of subscribing.

I am looking for the correct way of doing it in Spring AMQP. I did this in pure Java, based on the example in RabbitMQ's website. I passively declare the queue, check its consumer count, if it is 0, then start to consume it.

Here's the code.

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

int count = channel.queueDeclarePassive(QUEUE_NAME).getConsumerCount();

System.out.println("count is "+count);
if (count == 0) {
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
        System.out.println(" [x] Received '" + message + "'");
    };
    channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
} else{
    System.out.println("subscribed by some other processor(s)");
}
```
<p>I also can check the subscriber count in Spring AMQP this way. But it is too late, because it already listens to the queue.</p>
<pre class="lang-java prettyprint-override"><code>@RabbitListener(queues = "q1")
public void receivedMessageQ1(String message, Channel channel){
    try {
        int q1 = channel.queueDeclarePassive("q1").getConsumerCount();
        // do something.
    } catch (IOException e) {
        System.out.println("exception occurred");
    }
}
</code>```

In a nutshell, I want to consume a queue based on its consumer count. I hope I am clear.

答:
Set the exclusive flag on the @RabbitListener; RabbitMQ will only allow one instance to consume. The other instance(s) will attempt to listen every 5 seconds (by default). To increase the interval, set the container factory's recoveryBackOff.

@SpringBootApplication
public class So56319999Application {

    public static void main(String[] args) {
        SpringApplication.run(So56319999Application.class, args);
    }

    @RabbitListener(queues = "so56319999", exclusive = true)
    public void listen (String in) {

    }

    @Bean
    public Queue queue() {
        return new Queue("so56319999");
    }

}
```

Body:
I want a queue to be consumed by only one subscriber at a time. So if one subscriber drops, then another one(s) will have the chance of subscribing.

I am looking for the correct way of doing it in Spring AMQP. I did this in pure Java, based on the example in RabbitMQ's website. I passively declare the queue, check its consumer count, if it is 0, then start to consume it.

Here's the code.

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

int count = channel.queueDeclarePassive(QUEUE_NAME).getConsumerCount();

System.out.println("count is "+count);
if (count == 0) {
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
        System.out.println(" [x] Received '" + message + "'");
    };
    channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
} else{
    System.out.println("subscribed by some other processor(s)");
}

I also can check the subscriber count in Spring AMQP this way. But it is too late, because it already listens to the queue.

@RabbitListener(queues = "q1")
public void receivedMessageQ1(String message, Channel channel){
    try {
        int q1 = channel.queueDeclarePassive("q1").getConsumerCount();
        // do something.
    } catch (IOException e) {
        System.out.println("exception occurred");
    }
}

In a nutshell, I want to consume a queue based on its consumer count. I hope I am clear.


问:
How does the size of memory region argument in read() and write() affect the IO performance?
There is an IO example from Advanced Programming in Unix Environment:

```<code>#include "apue.h"
#define BUFFSIZE 4096
int
main(void)
{
    int  n;
    char  buf[BUFFSIZE];
    while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
    if (write(STDOUT_FILENO, buf, n) != n)
    err_sys("write error");
    if (n < 0)
    err_sys("read error");
    exit(0);
}
</code>```

All normal UNIX system shells provide a way to open a ﬁle for reading
  on standard input  and  to  create  (or  rewrite)  a  ﬁle  on
  standard output, and allows the user to take advantage of the shell’s
  I/O redirection facilities.

Figure 3.6  shows  the  results  for  reading  a  516,581,760-byte
  ﬁle,  using  20 different buffer sizes,  with  standard output
  redirected  to /dev/null. The  ﬁle  system  used  for  this  test  was
  the  Linux ext4 ﬁle system  with  4,096-byte  blocks. (The st_blksize
  value is 4,096.) This accounts for the minimum in the system time
  occurring at the  few  timing  measurements  starting  around  a
  BUFFSIZE of  4,096. Increasing  the buffer size beyond this limit has
  little positive effect.

How does BUFFSIZE affect the performance of reading a file?

As BUFFSIZE increases up to 4096, why does the performance
improve? As BUFFSIZE increases above 4096, why does the
performance have no significant improvement?

Does the kernel buffer (not the one buf with size BUFFSIZE in
the program) help in the performance, in relation to BUFFSIZE?

When BUFFSIZE is small, does the kernel buffer  help to accumulate
the small  writes, so to improve the performance?

答:
Each call to read() and write() requires a system call (to communicate with the kernel), plus the time to do the actual copying of into to (or from) the kernel's memory space.

The system-call itself imposes a fixed (per-call) overhead/cost, while the cost of copying the data is of course proportional to the amount of data there is to copy.

Therefore, if you read()/write() very small buffers, the overhead of making the system call will be relatively high compared to the number of bytes of data copied; and since you'll have to make a large number of calls, the overall runtime will be longer than if you had done larger transfers.

Calling read()/write() a smaller number of times with larger buffers allows the system to amortize the overhead of the system call over a larger number of bytes-per-call, avoiding that inefficiency.  However, at some point as sizes get larger, the system-call overhead becomes completely negligible, and at that point the program's efficiency is governed entirely by the cost of transferring the data, which is determined by the speed of the hardware.  That's why you see performance leveling out as sizes get larger.

read() and write() do not accumulate small writes together, since they represent direct system calls.  If you want small reads/writes to be buffered that way, the C runtime provides fread() and fwrite() wrappers that will do that for you inside your process-space.

Body:
There is an IO example from Advanced Programming in Unix Environment:

#include "apue.h"
#define BUFFSIZE 4096
int
main(void)
{
    int  n;
    char  buf[BUFFSIZE];
    while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
    if (write(STDOUT_FILENO, buf, n) != n)
    err_sys("write error");
    if (n < 0)
    err_sys("read error");
    exit(0);
}

All normal UNIX system shells provide a way to open a ﬁle for reading
  on standard input  and  to  create  (or  rewrite)  a  ﬁle  on
  standard output, and allows the user to take advantage of the shell’s
  I/O redirection facilities.

Figure 3.6  shows  the  results  for  reading  a  516,581,760-byte
  ﬁle,  using  20 different buffer sizes,  with  standard output
  redirected  to /dev/null. The  ﬁle  system  used  for  this  test  was
  the  Linux ext4 ﬁle system  with  4,096-byte  blocks. (The st_blksize
  value is 4,096.) This accounts for the minimum in the system time
  occurring at the  few  timing  measurements  starting  around  a
  BUFFSIZE of  4,096. Increasing  the buffer size beyond this limit has
  little positive effect.

How does BUFFSIZE affect the performance of reading a file?

As BUFFSIZE increases up to 4096, why does the performance
improve? As BUFFSIZE increases above 4096, why does the
performance have no significant improvement?

Does the kernel buffer (not the one buf with size BUFFSIZE in
the program) help in the performance, in relation to BUFFSIZE?

When BUFFSIZE is small, does the kernel buffer  help to accumulate
the small  writes, so to improve the performance?


问:
How to toggle-off the react-native-elements tooltip from another component
I want to manually close the tooltip but there are no documents on the react-native-elements site.

So I look over the tooltip code from github and noticed that it has a toggleTooltip function to toggle. Unfortunately I couldn't make it work.

This is the sample code for the tooltip

```<code>import { Tooltip } from 'react-native-elements';

render() {
  return (
    <Tooltip
      ref="tooltip"
      popover={
        <ComponentTest
          toggle={this.refs.tooltip}
        >
    >
      <Text>Click me</Text>
    </Tooltip>
  );
}
</code>```

The sample code for the ComponentTest

```<code>import { Button } from 'react-native-elements';

toggleOff = () => {
  this.props.toggleTooltip;
}

render() {
  return (
      <Button
        title="hide"
        type="outline"
        onPress={this.toggleOff}
      />
  );
}
</code>```

And this is the function from the tooltip.js that I am trying to use. The full code of the tooltip can found here https://github.com/react-native-training/react-native-elements/blob/master/src/tooltip/Tooltip.js

```<code>toggleTooltip = () => {
  const { onClose } = this.props;
  this.getElementPosition();
  this.setState(prevState => {
    if (prevState.isVisible && !isIOS) {
      onClose && onClose();
    }

    return { isVisible: !prevState.isVisible };
  });
};
</code>```

答:
On line 191 of Tooltip.js:

```<code> <TouchableOpacity onPress={this.toggleTooltip}>
     {this.renderContent(true)}
 </TouchableOpacity>
</code>```

and in the definition of renderContent:112 on line 137, it is rendered your popover:
Thus wherever you touch in your popover will make it disappear. I don't know how to disable this behaviour, but I still want to know if and how the visibility of the popover can be controlled from the Tooltip's child element at least.

Body:
I want to manually close the tooltip but there are no documents on the react-native-elements site.

So I look over the tooltip code from github and noticed that it has a toggleTooltip function to toggle. Unfortunately I couldn't make it work.

This is the sample code for the tooltip

import { Tooltip } from 'react-native-elements';

render() {
  return (
    <Tooltip
      ref="tooltip"
      popover={
        <ComponentTest
          toggle={this.refs.tooltip}
        >
    >
      <Text>Click me</Text>
    </Tooltip>
  );
}

The sample code for the ComponentTest

import { Button } from 'react-native-elements';

toggleOff = () => {
  this.props.toggleTooltip;
}

render() {
  return (
      <Button
        title="hide"
        type="outline"
        onPress={this.toggleOff}
      />
  );
}

And this is the function from the tooltip.js that I am trying to use. The full code of the tooltip can found here https://github.com/react-native-training/react-native-elements/blob/master/src/tooltip/Tooltip.js

toggleTooltip = () => {
  const { onClose } = this.props;
  this.getElementPosition();
  this.setState(prevState => {
    if (prevState.isVisible && !isIOS) {
      onClose && onClose();
    }

    return { isVisible: !prevState.isVisible };
  });
};

Body:
On line 191 of Tooltip.js:

 <TouchableOpacity onPress={this.toggleTooltip}>
     {this.renderContent(true)}
 </TouchableOpacity>

and in the definition of renderContent:112 on line 137, it is rendered your popover:
Thus wherever you touch in your popover will make it disappear. I don't know how to disable this behaviour, but I still want to know if and how the visibility of the popover can be controlled from the Tooltip's child element at least.


问:
What is a Python mapping?
Say I have a function func and an object obj of class Class. I have the following error:

>>> func(**obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() argument after ** must be a mapping, not Class
```

Hence my question: what is a mapping? Are all mappings subclasses of dict? Or is there a list of methods (e.g. __getitem__, __iter__, ...) that Class has to implement to be considered a mapping?

答:
The term "mapping" is described here as:

A container object that supports arbitrary key lookups and implements
  the methods specified in the Mapping or MutableMapping abstract base
  classes. Examples include dict, collections.defaultdict,
  collections.OrderedDict and collections.Counter.

The requirements to subclass collections.abc.Mapping are described in its docstring:

```<code>"""A Mapping is a generic container for associating key/value
pairs.

This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__.

"""
</code>```

So you can define a new mapping type by subclassing collections.abc.Mapping, and implementing three methods: __len__, __getitem__, and __iter__.

```<code>>>> from collections.abc import Mapping
>>> def func(**kwargs):
...   print(kwargs)
...
>>> class MyMapping(Mapping):
...   def __len__(self):
...     return 1
...   def __getitem__(self, k):
...     return 'bananas'
...   def __iter__(self):
...     return iter(['custard'])
...
>>> func(**MyMapping())
{'custard': 'bananas'}
</code>```

Title: What is a Python mapping?

Body:
Say I have a function func and an object obj of class Class. I have the following error:

>>> func(**obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() argument after ** must be a mapping, not Class

Hence my question: what is a mapping? Are all mappings subclasses of dict? Or is there a list of methods (e.g. __getitem__, __iter__, ...) that Class has to implement to be considered a mapping?

Body:
The term "mapping" is described here as:

A container object that supports arbitrary key lookups and implements
  the methods specified in the Mapping or MutableMapping abstract base
  classes. Examples include dict, collections.defaultdict,
  collections.OrderedDict and collections.Counter.

The requirements to subclass collections.abc.Mapping are described in its docstring:

"""A Mapping is a generic container for associating key/value
pairs.

This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__.

"""

So you can define a new mapping type by subclassing collections.abc.Mapping, and implementing three methods: __len__, __getitem__, and __iter__.

>>> from collections.abc import Mapping
>>> def func(**kwargs):
...   print(kwargs)
...
>>> class MyMapping(Mapping):
...   def __len__(self):
...     return 1
...   def __getitem__(self, k):
...     return 'bananas'
...   def __iter__(self):
...     return iter(['custard'])
...
>>> func(**MyMapping())
{'custard': 'bananas'}


问:
Integrating weather information in iphone
Can anyone tell me the steps to integrate weather information into my iPhone App. I found some API's are there, but didn't found steps for this. Thanks in advance.</p>


问:
Filter one column by matching to another column
I have a data frame with a variable containing elements to drop if they match to an element in another variable - see a small example below:

df <- data.frame(pair = c(1, 1, 2, 2, 3, 3),
                 animal = rep(c("dog", "cat"), 3),
                 value = seq(1, 12, 2),
                 drop = c("no", "no", "dog", "dog", "cat", "cat"))

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
3    2    dog     5  dog
4    2    cat     7  dog
5    3    dog     9  cat
6    3    cat    11  cat
```

<p>I'm trying to want to filter the data frame according to whether the value of <code>animal</code> matches the value of <code>drop</code>. I want something like <code>filter(df, animal != drop)</code> to remove rows where only the value of animal matches the value of drop:</p>

<pre class="lang-r prettyprint-override"><code>  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
4    2    cat     7  dog
5    3    dog     9  cat
</code>```

I also tried writing a simple loop to test whether animal matches drop for each row and remove the row if true, but I couldn't get it working. (I'm not very confident with loops and would prefer not to use one if possible as my data frame is very large but I was getting desperate!)

for(i in nrow(df)){
  if(df$animal[i] == df$drop[i]){
    df <- df[-i,]
    return(df)
  }
}
```

Is there a way of doing this using dplyr?

答:
An option would be to convert to character class with mutate_at and then use filter on non-matching elements

```<code>library(dplyr)
df %>%
  mutate_at(vars(animal, drop), as.character) %>%
  filter(animal != drop)
#  pair animal value drop
#1    1    dog     1   no
#2    1    cat     3   no
#3    2    cat     7  dog
#4    3    dog     9  cat
</code>```

Body:
I have a data frame with a variable containing elements to drop if they match to an element in another variable - see a small example below:

df <- data.frame(pair = c(1, 1, 2, 2, 3, 3),
                 animal = rep(c("dog", "cat"), 3),
                 value = seq(1, 12, 2),
                 drop = c("no", "no", "dog", "dog", "cat", "cat"))

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
3    2    dog     5  dog
4    2    cat     7  dog
5    3    dog     9  cat
6    3    cat    11  cat

I'm trying to want to filter the data frame according to whether the value of animal matches the value of drop. I want something like filter(df, animal != drop) to remove rows where only the value of animal matches the value of drop:

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
4    2    cat     7  dog
5    3    dog     9  cat

I also tried writing a simple loop to test whether animal matches drop for each row and remove the row if true, but I couldn't get it working. (I'm not very confident with loops and would prefer not to use one if possible as my data frame is very large but I was getting desperate!)

for(i in nrow(df)){
  if(df$animal[i] == df$drop[i]){
    df <- df[-i,]
    return(df)
  }
}

Is there a way of doing this using dplyr?

Body:
An option would be to convert to character class with mutate_at and then use filter on non-matching elements

library(dplyr)
df %>%
  mutate_at(vars(animal, drop), as.character) %>%
  filter(animal != drop)
#  pair animal value drop
#1    1    dog     1   no
#2    1    cat     3   no
#3    2    cat     7  dog
#4    3    dog     9  cat


问:
Fibonacci Word Series in java
For any two strings of digits,A and B, we define Fa,b to be the sequence (A,B ,AB ,BAB ,ABBAB ,...) in which each term is the concatenation of the previous two.

Further, we define Da,b(n)
to be the n-th digit in the first term of Fa,b that contains at least

n digits.

Example:

Let A=1415926535
,B=8979323846 . We wish to find Da,b(35)

, say.

The first few terms of Fa,b are:

1415926535
8979323846
141592653589793233846
897932384614159265358979323846
14159265358979323846897932384614159265358979323846

Then Da,b(35) is the 35-th digit in the fifth term, which is

9.

You are given
q triples (A,B,n). For all of them find

Da,b(n).

Input Format

First line of each test file contains a single integer
q that is the number of triples. Then q lines follow, each containing two strings of decimal digits a and b and positive integer n.

Output Format

Print exactly q
lines with a single decimal digit on each: value of Da,b(n) for the corresponding triple.

```<code>public void fibo(String a,String b,int n){
    String n1=Integer.toString(n);
    char n2;
    n2=n1.charAt(1);
    int n3=Character.getNumericValue(n2);
    String c;
    for(int i=2;i<n3;i++){
        c=a+b;
        System.out.printf(c+" ");
        a=b;
        b=c;
    }

    System.out.println(c.charAt(n));
}
</code>```

Compile Message

Solution.java:26: error: variable c might not have been initialized
        System.out.println(c.charAt(n));
                           ^
1 error

Exit Status

1

答:
Solution.java:23: error: variable c might not have been initialized String d=Integer.toString(c); ^ 1 error

You are not assigning a value to c prior to your loop. The compiler can't know whether that loop will ever be entered.

Conclusion: you can reach that print statement without ever assigning a value to c.

Can be fixed easily:

```<code>int c = 0;
</code>```

And note: you need that because c is a local variable in a method. Those aren't initalized by default (in contrast to fields of a class for example).

Beyond that: look into naming. Your code is super hard to understand, just because your overly excessive use of one-character names. Use names that mean something, that tell you what the variable is intended to be used for.

Title: Fibonacci Word Series in java

Body:
For any two strings of digits,A and B, we define Fa,b to be the sequence (A,B ,AB ,BAB ,ABBAB ,...) in which each term is the concatenation of the previous two.

Further, we define Da,b(n)
to be the n-th digit in the first term of Fa,b that contains at least

n digits.

Example:

Let A=1415926535
,B=8979323846 . We wish to find Da,b(35)

, say.

The first few terms of Fa,b are:

1415926535
8979323846
141592653589793233846
897932384614159265358979323846
14159265358979323846897932384614159265358979323846

Then Da,b(35) is the 35-th digit in the fifth term, which is

9.

You are given
q triples (A,B,n). For all of them find

Da,b(n).

Input Format

First line of each test file contains a single integer
q that is the number of triples. Then q lines follow, each containing two strings of decimal digits a and b and positive integer n.

Output Format

Print exactly q
lines with a single decimal digit on each: value of Da,b(n) for the corresponding triple.

public void fibo(String a,String b,int n){
    String n1=Integer.toString(n);
    char n2;
    n2=n1.charAt(1);
    int n3=Character.getNumericValue(n2);
    String c;
    for(int i=2;i<n3;i++){
        c=a+b;
        System.out.printf(c+" ");
        a=b;
        b=c;
    }

    System.out.println(c.charAt(n));
}

Compile Message

Solution.java:26: error: variable c might not have been initialized
        System.out.println(c.charAt(n));
                           ^
1 error

Exit Status

1

Body:
Solution.java:23: error: variable c might not have been initialized String d=Integer.toString(c); ^ 1 error

You are not assigning a value to c prior to your loop. The compiler can't know whether that loop will ever be entered.

Conclusion: you can reach that print statement without ever assigning a value to c.

Can be fixed easily:

int c = 0;

And note: you need that because c is a local variable in a method. Those aren't initalized by default (in contrast to fields of a class for example).

Beyond that: look into naming. Your code is super hard to understand, just because your overly excessive use of one-character names. Use names that mean something, that tell you what the variable is intended to be used for.