问:
My class does not override abstract method compareTo
My class details attributes of restaurants downtown, said attributes being x/y locations and rank. The problem is, whenever I run the program It throws an error, saying that non-abstract class "Downtown" does not override abstract method "compareTo". I cannot make this class abstract because I need to initialise the object outside this block of code.  Where does my program go wrong? Is there a problem with my compareTo implementation? Any suggestions will be much appreciated.</p>

```<code>public class Downtown implements Comparable<Downtown> {//Throws error on this line
    private int x;
    private int y;
    private int rank;

    public Downtown(int x, int y, int rank) {
        this.x = x;
        this.y = y;
        this.rank = rank;
    }
    //Appropriate setters and getters for x , y and rank
    public int getX() {
         return x;
    }
    public void setX(int x) {
    this.x = x;
    }
    public int getY() {
    return y;
    }
    public void setY(int y) {
    this.y = y;
    }
    public int getRank() {
    return rank;
    }
    public void setRank(int rank) {
    this.rank = rank;
    }

    public int compareTo(Downtown p1, Downtown p2)//Actual comparison
    {
        // This is so that the sort goes x first, y second and rank last

        // First by x- stop if this gives a result.
        int xResult = Integer.compare(p1.getX(),p1.getX());
        if (xResult != 0)
        {
            return xResult;
        }

        // Next by y
        int yResult = Integer.compare(p1.getY(),p2.getY());
        if (yResult != 0)
        {
            return yResult;
        }

        // Finally by rank
        return Integer.compare(p1.getRank(),p2.getRank());
    }

    @Override
    public String toString() {
        return "["+x+' '+y+' '+rank+' '+"]";
    }
</code>```

答:
The compareTo method should compare the current object (this) to just one other.  It shouldn't have two parameters for comparison.  You could write your method like this.

```<code>public int compareTo(Downtown p2)//Actual comparison
{
    // This is so that the sort goes x first, y second and rank last

    // First by x- stop if this gives a result.
    int xResult = Integer.compare(getX(),p2.getX());
    if (xResult != 0)
    {
        return xResult;
    }

    // Next by y
    int yResult = Integer.compare(getY(),p2.getY());
    if (yResult != 0)
    {
        return yResult;
    }

    // Finally by rank
    return Integer.compare(getRank(),p2.getRank());
}
</code>```

Notice how I've replace all the calls on p1 to calls on the current object.

Body:
My class details attributes of restaurants downtown, said attributes being x/y locations and rank. The problem is, whenever I run the program It throws an error, saying that non-abstract class "Downtown" does not override abstract method "compareTo". I cannot make this class abstract because I need to initialise the object outside this block of code.  Where does my program go wrong? Is there a problem with my compareTo implementation? Any suggestions will be much appreciated.

public class Downtown implements Comparable<Downtown> {//Throws error on this line
    private int x;
    private int y;
    private int rank;

    public Downtown(int x, int y, int rank) {
        this.x = x;
        this.y = y;
        this.rank = rank;
    }
    //Appropriate setters and getters for x , y and rank
    public int getX() {
         return x;
    }
    public void setX(int x) {
    this.x = x;
    }
    public int getY() {
    return y;
    }
    public void setY(int y) {
    this.y = y;
    }
    public int getRank() {
    return rank;
    }
    public void setRank(int rank) {
    this.rank = rank;
    }

    public int compareTo(Downtown p1, Downtown p2)//Actual comparison
    {
        // This is so that the sort goes x first, y second and rank last

        // First by x- stop if this gives a result.
        int xResult = Integer.compare(p1.getX(),p1.getX());
        if (xResult != 0)
        {
            return xResult;
        }

        // Next by y
        int yResult = Integer.compare(p1.getY(),p2.getY());
        if (yResult != 0)
        {
            return yResult;
        }

        // Finally by rank
        return Integer.compare(p1.getRank(),p2.getRank());
    }

    @Override
    public String toString() {
        return "["+x+' '+y+' '+rank+' '+"]";
    }

Body:
The compareTo method should compare the current object (this) to just one other.  It shouldn't have two parameters for comparison.  You could write your method like this.

public int compareTo(Downtown p2)//Actual comparison
{
    // This is so that the sort goes x first, y second and rank last

    // First by x- stop if this gives a result.
    int xResult = Integer.compare(getX(),p2.getX());
    if (xResult != 0)
    {
        return xResult;
    }

    // Next by y
    int yResult = Integer.compare(getY(),p2.getY());
    if (yResult != 0)
    {
        return yResult;
    }

    // Finally by rank
    return Integer.compare(getRank(),p2.getRank());
}

Notice how I've replace all the calls on p1 to calls on the current object.


来源: stackexchange

问:
importing network in Statnet in R
I am new to STATNET and know nothing about it. I have a data set which has 3 columns. The first and second column contain nodes whereas the third contains edge value. How should I import this to STATNET? I suspect I need to convert this dataset to a matrix. How can I do that in R?</p>

答:
No need to change it into a matrix, you can use a weighted edgelist right away. Try something like</p>

```<code>library(statnet)

dat <- structure(
    list(a = c(1, 2, 4), b = c(2, 3, 5), c = c(10, 1, 1)),
    .Names    = c("a", "b", "c"),
    row.names = c(NA, -3L),
    class     = "data.frame"
)

g <- as.network(
    dat,
    ignore.eval = FALSE,
    names.eval  = 'weight',
    matrix.type = 'edgelist',
    directed    = FALSE
    )
</code>```

ContentLicense: CC BY-SA 3.0

Title: importing network in Statnet in R

Body:
No need to change it into a matrix, you can use a weighted edgelist right away. Try something like

library(statnet)

dat <- structure(
    list(a = c(1, 2, 4), b = c(2, 3, 5), c = c(10, 1, 1)),
    .Names    = c("a", "b", "c"),
    row.names = c(NA, -3L),
    class     = "data.frame"
)

g <- as.network(
    dat,
    ignore.eval = FALSE,
    names.eval  = 'weight',
    matrix.type = 'edgelist',
    directed    = FALSE
    )

ContentLicense: CC BY-SA 4.0


答:
Java's Comparable<T> interface defines compareTo method as follows:

```<code>int compareTo(T o);
</code>```

This means that the method must take one parameter; the other parameter is the object itself, i.e. this. You need to implement this one-argument method in place of your two-argument method to fix this problem.

Compiler will help you figure out issues like this by using @Override annotation on your method:

```<code>@Override // Issues an error
public int compareTo(Downtown p1, Downtown p2)

@Override // Compiles fine
public int compareTo(Downtown other)
</code>```

Title: My class does not override abstract method compareTo

Body:
Java's Comparable<T> interface defines compareTo method as follows:

int compareTo(T o);

This means that the method must take one parameter; the other parameter is the object itself, i.e. this. You need to implement this one-argument method in place of your two-argument method to fix this problem.

Compiler will help you figure out issues like this by using @Override annotation on your method:

@Override // Issues an error
public int compareTo(Downtown p1, Downtown p2)

@Override // Compiles fine
public int compareTo(Downtown other)


问:
How to get a specific json key value from post request response in Android?
I have following response from post request using HttpURLConnection:

Post Request Response:

```<code>{
    "LatestData": [{
        "ExtraData": null,
        "ID": 0,
        "season": false,
        "latest": 0,
        "url": "http://www.awebsite.com/images/12.jpg"
    }]
}
</code>```

How to get value of URL? I tried following but Android Studio keeps giving me error:

```<code>String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
</code>```

Android Studio Error:

```<code>error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)
</code>```

could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks

android code:

```<code> if (myURLConnection.getResponseCode() == 200) {
                br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
                while (true) {
                    line = br.readLine();
                    if (line != null) {
                        sb.append(line + "\n");

                        //String newURL = sb.getJSONObject("LatestData").getString("url");
                        String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
                        mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
                    } else {
                        br.close();
                        return sb.toString();
                    }
                }
            }
</code>```

答:
Your approach should be like this.</p>

```<code>try {
        List<String> urlist = new ArrayList<>();
        JSONObject jsonObject = new JSONObject(sb.toString());
        JSONArray jsonArray =  jsonObject.getJSONArray("LatestData");
        for (int count = 0; count<jsonArray.length(); count++){
            JSONObject jsonInner =  jsonArray.getJSONObject(count);
            String url = jsonInner.getString("url");
            //store your url in some list
            urlist.add(url);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Body:
I have following response from post request using HttpURLConnection:

Post Request Response:

{
    "LatestData": [{
        "ExtraData": null,
        "ID": 0,
        "season": false,
        "latest": 0,
        "url": "http://www.awebsite.com/images/12.jpg"
    }]
}

How to get value of URL? I tried following but Android Studio keeps giving me error:

String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");

Android Studio Error:

error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)

could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks

android code:

 if (myURLConnection.getResponseCode() == 200) {
                br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
                while (true) {
                    line = br.readLine();
                    if (line != null) {
                        sb.append(line + "\n");

                        //String newURL = sb.getJSONObject("LatestData").getString("url");
                        String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
                        mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
                    } else {
                        br.close();
                        return sb.toString();
                    }
                }
            }

Body:
Your approach should be like this.

try {
        List<String> urlist = new ArrayList<>();
        JSONObject jsonObject = new JSONObject(sb.toString());
        JSONArray jsonArray =  jsonObject.getJSONArray("LatestData");
        for (int count = 0; count<jsonArray.length(); count++){
            JSONObject jsonInner =  jsonArray.getJSONObject(count);
            String url = jsonInner.getString("url");
            //store your url in some list
            urlist.add(url);
        }

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


问:
Emacs in Windows
How do you run Emacs in Windows?

What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the .emacs file located?

答:
I suggest you to use development version of GNU Emacs 23, which is pretty stable and to be released relatively soon. You can get weekly binary builds from the link below.

Latest GNU Emacs as a zip archive

OwnerDisplayName: sverrejoh

ContentLicense: CC BY-SA 2.5

Title: Emacs in Windows

LastEditorDisplayName: ΤΖΩΤΖΙΟΥ

OwnerDisplayName: boskom


问:
ViewDidAppear animation false
I wanted to disable animated in viewDidAppear. I've set the code below but it shows me this error:

"cannot assign to value: 'animated' is a 'let' constant"

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated = false)
}
</code>```

答:
You are trying to assign a value to the animated parameter and parameters are let constants, hence the error.

If you simply want to pass false to super.viewDidAppear then simply pass false:

```<code>super.viewDidAppear(false)
</code>```

There is no need to attempt to assign a value to the original animated property.

Title: ViewDidAppear animation false

Body:
I wanted to disable animated in viewDidAppear. I've set the code below but it shows me this error:

"cannot assign to value: 'animated' is a 'let' constant"

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated = false)
}

Body:
You are trying to assign a value to the animated parameter and parameters are let constants, hence the error.

If you simply want to pass false to super.viewDidAppear then simply pass false:

super.viewDidAppear(false)

There is no need to attempt to assign a value to the original animated property.


问:
AttributeError: object has no attribute 'reader' online when CSV used inside of a METHOD
When I access csv.reader from a script, every thing works well but when I access it from a method inside my class, I get the following error:

```<code>AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
</code>```

I have looked at these two similar issues my problem is different

AttributeError: 'module' object has no attribute 'reader'

CSV Module AttributeError

Based on those two links, I have ensured that

A. I am pointing to the correct CSV libray

B. I don't have a csv.py file in my project

I am new to Python so it could just be a simple oversight, but I have included the code and comments on what works and what doesn't

```<code>import csv

print(csv.__file__)
# displays:
# D:\ProgramData\Anaconda2\lib\csv.pyc

reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))

print(list(reader))
# displays
# [['user_name'], ['mensfashionpost'], ['creativefasion']]

class GetInstgramUsernames(object):

    def read(self):
        # same line as above but produces an error
        # AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
        self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
        print(list(self.xyz))

csv = GetInstgramUsernames()

csv.read()
</code>```

And the actual console output

```<code>python xmen.py
D:\ProgramData\Anaconda2\lib\csv.pyc
[['user_name'], ['mensfashionpost'], ['creativefasion']]
Traceback (most recent call last):
File "xmen.py", line 25, in <module>
    csv.read()
File "xmen.py", line 18, in read
    self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'    D:\dev\scrapy\instagram_influencers>
</code>```

答:
My mistake was similar to the other questions.

I did not have a file called csv.py but I did use a variable name called csv.

Thanks @user2357112 for pointing this out

Body:
When I access csv.reader from a script, every thing works well but when I access it from a method inside my class, I get the following error:

AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'

I have looked at these two similar issues my problem is different

AttributeError: 'module' object has no attribute 'reader'

CSV Module AttributeError

Based on those two links, I have ensured that

A. I am pointing to the correct CSV libray

B. I don't have a csv.py file in my project

I am new to Python so it could just be a simple oversight, but I have included the code and comments on what works and what doesn't

import csv

print(csv.__file__)
# displays:
# D:\ProgramData\Anaconda2\lib\csv.pyc

reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))

print(list(reader))
# displays
# [['user_name'], ['mensfashionpost'], ['creativefasion']]

class GetInstgramUsernames(object):

    def read(self):
        # same line as above but produces an error
        # AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
        self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
        print(list(self.xyz))

csv = GetInstgramUsernames()

csv.read()

And the actual console output

python xmen.py
D:\ProgramData\Anaconda2\lib\csv.pyc
[['user_name'], ['mensfashionpost'], ['creativefasion']]
Traceback (most recent call last):
File "xmen.py", line 25, in <module>
    csv.read()
File "xmen.py", line 18, in read
    self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'    D:\dev\scrapy\instagram_influencers>


问:
How to compare two array and alert the result?
I have two simple arrays:

```<code>var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.
</code>```

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

```<code>arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)
</code>```

I use $.each but it's only check the array. Not comparing them.

```<code>$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});
</code>```

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

答:
It can be done in javascript using forEach & join array methods

var arr_must_exist = ["1", "2", "3"];
var arr_created = ["2", "4", "7", "8"];

// An array to store the elements which are not in arr_created
var missingElements = [];

// looping over arr_must_exist and checking if
// element is present in arr_created using indexOf
arr_must_exist.forEach(function(item) {
  if (arr_created.indexOf(item) === -1) {
    // if not push the element in the array
    missingElements.push(item)

  }
})

// if missingElements length is greater than 1 mean if it contain
// any element then join all the element ,create string with a comma
//separator
if (missingElements.length > 0) {
  alert(missingElements.join(','))
}```

Body:
I have two simple arrays:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)

I use $.each but it's only check the array. Not comparing them.

$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)


答:
Try it using loadJSONArray

```<code>String url = loadJSONArray(sb)..getJSONObject(0).getString("url");
</code>```

Title: How to get a specific json key value from post request response in Android?

Body:
Try it using loadJSONArray

String url = loadJSONArray(sb)..getJSONObject(0).getString("url");


问:
iOS PortSIP Initialize failure ErrorCode = -60098
I'm currently trying out PortSIP SDK for iOS to make a VoIP App. I'm not familiar with this error, anyone have an idea what this means?</p>

答:
I'm not sure if/how this relates to iOS, but on Android I learned that you also need to declare certain permissions:</p>

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
</code>```

Body:
I'm not sure if/how this relates to iOS, but on Android I learned that you also need to declare certain permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />


问:
Checking remainder in Javascript
I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.

What I have is:

```<code>var i = 0;

  do {
    i++;
    console.log(i)
    }

 while (i <= 9);

 if(i % 2 = 1) {
   console.log("odd")
   }

 else {
   console.log("even")
    }
</code>```

Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment

What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?

Thanks!

答:
So the problem in you code is , you are using an assignment operator "=" in your if condition, instead use "==" (comparision operator).

You can find more information on comparision operators in Javascript here :
https://www.w3schools.com/js/js_comparisons.asp

Title: Checking remainder in Javascript

Body:
I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.

What I have is:

var i = 0;

  do {
    i++;
    console.log(i)
    }

 while (i <= 9);

 if(i % 2 = 1) {
   console.log("odd")
   }

 else {
   console.log("even")
    }

Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment

What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?

Thanks!


问:
How to set options value with object in knockoutjs
I have:

```<code> <select name="test" id="test" class=""
  data-bind="
  options: myArray,
  value: idSelected,
  optionsText: 'name',
  optionsValue: 'id',
 optionsCaption: 'All'">
</code>```

I dont want only id, i want set in object a id and name of my array when you select an item from the list. Sample:

I want this result:

```<code>  idSelected = {id:1, name:'Test'};
</code>```

答:
Just remove the optionsValue from your bindings. This will set the idSelected to be the objects of observableArray rather than a string (documentation)

Here's a working snippet:

var viewModel = function() {
  var self = this;

  self.myArray = ko.observableArray([{
    id: 1,
    name: 'Test 1'
  }, {
    id: 2,
    name: 'Test 2'
  }]);

  self.idSelected = ko.observable();

  self.idSelected.subscribe((selected) => {
    console.log(self.idSelected());
  });
}

ko.applyBindings(new viewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select name="test" id="test" class="" data-bind="
  options: myArray,
  value: idSelected,
  optionsText: 'name',
 optionsCaption: 'All'"></code>```

Body:
I have:

 <select name="test" id="test" class=""
  data-bind="
  options: myArray,
  value: idSelected,
  optionsText: 'name',
  optionsValue: 'id',
 optionsCaption: 'All'">

I dont want only id, i want set in object a id and name of my array when you select an item from the list. Sample:

I want this result:

  idSelected = {id:1, name:'Test'};

Body:
Just remove the optionsValue from your bindings. This will set the idSelected to be the objects of observableArray rather than a string (documentation)

Here's a working snippet:

var viewModel = function() {
  var self = this;

  self.myArray = ko.observableArray([{
    id: 1,
    name: 'Test 1'
  }, {
    id: 2,
    name: 'Test 2'
  }]);

  self.idSelected = ko.observable();

  self.idSelected.subscribe((selected) => {
    console.log(self.idSelected());
  });
}

ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select name="test" id="test" class="" data-bind="
  options: myArray,
  value: idSelected,
  optionsText: 'name',
 optionsCaption: 'All'">


问:
PHP Mobile Detect Script Slowdown
I'm trying to integrate the PHP version of the mobile detection script from http://mobiledetect.net/ into my Wordpress installation.

I've used the following code to call and detect mobile usage

```<code><?php
    include 'includes/Mobile_Detect.php';
    $detect = new Mobile_Detect;
    $isMobile = $detect->isMobile();
    if($isMobile) {
        //Do a thing;
    };
?>
</code>```

While the code does work, I've found that the loading time of the page has risen by 1-2 seconds on a consistent basis. I've run some tests and just the include statement itself is causing a major slowdown.

Is this normal when using this script or is there supposed to be a better way to implement it?

答:
```<code>if ( wp_is_mobile() )
{
    //Do a thing;
}
else
{
    //Do a thing;
}
</code>```

Title: PHP Mobile Detect Script Slowdown

Body:
I'm trying to integrate the PHP version of the mobile detection script from http://mobiledetect.net/ into my Wordpress installation.

I've used the following code to call and detect mobile usage

<?php
    include 'includes/Mobile_Detect.php';
    $detect = new Mobile_Detect;
    $isMobile = $detect->isMobile();
    if($isMobile) {
        //Do a thing;
    };
?>

While the code does work, I've found that the loading time of the page has risen by 1-2 seconds on a consistent basis. I've run some tests and just the include statement itself is causing a major slowdown.

Is this normal when using this script or is there supposed to be a better way to implement it?


问:
How powerful is OpenGL?
I want to create an application which will capture one by camera and will manipulate the live images taken by it in milliseconds of the time.

The goal is that the application should change my clothes with some other clothes which I will supply.

I have few questions:

Does OpenGL have such power of modifying live images in a way it will change my clothes in the computer image? I will be moving my hands and the like, can it be that accurate so it'll just look like I am in changed clothes and not the original I am wearing?

答:
OpenGL is a rendering library; it's purpose is to draw things on your screen. It could probably be used as a part of a solution to your problem, but only the rendering part. Your problem also requires some rather serious image-processing, to take the source image from the camera, recognize the human body and all its various parts and poses, and then narrow that down to the clothes.

What if you're wearing e.g. a trenchcoat, and the replacement outfit (to be rendered) is something form-fitting like a professional ice skating suit? Clearly the replacement process needs information that is not available from the source image, in that case. This calls for either a pre-generated database that describes your body, or limiting the range of possible replacement outfits (to, perhaps, just changing the pattern and/or color of the trenchcoat).

Look into OpenCV, and what people are doing with the Kinect controller. This will not be easy.

Title: How powerful is OpenGL?


问:
How to optimize group_concat sub query in mysql?
How can i optimize this query? It's taking a lot of time to execute.</p>

```<code>SELECT GROUP_CONCAT(`details_value`), details_key
  FROM `correspondence_package_details`
 WHERE `correspondence_id` IN (SELECT GROUP_CONCAT(`correspondence_id`)
                                 FROM `correspondence_package_header`
                                WHERE create_date BETWEEN '2017-11-01' AND '2017-11-30'
                               GROUP BY `manual_package_id`,account_id)
   AND (`details_key` = 'to' OR `details_key` = 'cc')
 GROUP BY details_key;
</code>```

答:
Query optimization is both an art and science. By simply looking at the sql, you are limiting your options.

Run an explain plan on your query. Check for low performing join types and scans.

Add appropriate indexes on all join columns.

For date fields, sort the index based on whether you would normally be querying most recent or oldest records.

Regular run the optimize command on your databases so that the indexes and tablespaces get a quick tune up.

The query plan will be your best tool for this.

Body:
How can i optimize this query? It's taking a lot of time to execute.

SELECT GROUP_CONCAT(`details_value`), details_key
  FROM `correspondence_package_details`
 WHERE `correspondence_id` IN (SELECT GROUP_CONCAT(`correspondence_id`)
                                 FROM `correspondence_package_header`
                                WHERE create_date BETWEEN '2017-11-01' AND '2017-11-30'
                               GROUP BY `manual_package_id`,account_id)
   AND (`details_key` = 'to' OR `details_key` = 'cc')
 GROUP BY details_key;


问:
PostgreSQL database size (tablespace size) much bigger then calculated total sum of relations
Hallo all,

I see a very big difference between the actual database size (on the HDD and displayed by pg_database_size() call) and the size, calculated by summing up total relation sizes retrieved by pg_total_relation_size().

The first is 62G and the last is 16G (right the difference of the deleted data from the biggest table)

Here is a simplified query, that can show that difference on my system:

```<code>select current_database(),
       pg_size_pretty( sum(total_relation_raw_size)::bigint ) as calculated_database_size,
       pg_size_pretty( pg_database_size(current_database()) ) as database_size
  from (select pg_total_relation_size(relid) as total_relation_raw_size
          from pg_stat_all_tables -- this includes also system tables shared between databases
         where schemaname != 'pg_toast'
       ) as stats;
</code>```

It seems like there is some dangling data there. As this situation appeared, after we dumped and full vacuumed lots of unused data from that DB.

P.S.: I suppose, that it was a database corruption of some sort... The only way to recover from this situation was to switch to the Hot-Standby database...

答: Your query is specifically screening out pg_toast tables, which can be big.  See if getting rid of that where schemaname != 'pg_toast' gets you a more accurate answer.

Body:
Hallo all,

I see a very big difference between the actual database size (on the HDD and displayed by pg_database_size() call) and the size, calculated by summing up total relation sizes retrieved by pg_total_relation_size().

The first is 62G and the last is 16G (right the difference of the deleted data from the biggest table)

Here is a simplified query, that can show that difference on my system:

select current_database(),
       pg_size_pretty( sum(total_relation_raw_size)::bigint ) as calculated_database_size,
       pg_size_pretty( pg_database_size(current_database()) ) as database_size
  from (select pg_total_relation_size(relid) as total_relation_raw_size
          from pg_stat_all_tables -- this includes also system tables shared between databases
         where schemaname != 'pg_toast'
       ) as stats;

It seems like there is some dangling data there. As this situation appeared, after we dumped and full vacuumed lots of unused data from that DB.

P.S.: I suppose, that it was a database corruption of some sort... The only way to recover from this situation was to switch to the Hot-Standby database...


问:
How to send asynchronous state fetch to component?
I am currently working on a little app for fun. I ran into an issue with using axios and returning the response to my App component as updated state.

I then try to allow another component to use that piece of state, but I am not able to actually access the data. I can console.log(props) from within the List component, but I am not sure how to output the actual data as I am only able to output the promise results. I want to be able to output props.currentUser and have it be the googleId (using google Oauth2.0)..I am sure the solution is simple but, here is my code:

App.js ->

```<code>import React from 'react';
import helpers from '../helpers';
import List from './List';

class App extends React.Component{

  state = {
    currentUser: null
  }

  componentDidMount() {
    this.setState(prevState => ({
      currentUser: helpers.fetchUser()
    }));
  }

  render() {
    return (
      <div>
        <List currentUser={this.state.currentUser}/>
      </div>
    );
  }
};

export default App;
</code>```

helpers.js ->

```<code>import axios from 'axios';

var helpers = {
  fetchUser: async () => {
      const user = await axios.get('/api/current_user');

      return user.data;
  }
};

export default helpers;
</code>```

List Component ->

```<code>import React from 'react';

const List = (props) => {

  const renderContent = () => {
      console.log(props);
      return <li>{props.currentUser}</li>
  }

  renderContent();

  return (
    <div>
      <h1>Grocery List</h1>
      <ul>

      </ul>
    </div>
  );
}

export default List;
</code>```

Output ->

```<code>{currentUser: null}
{currentUser: Promise}
    currentUser: Promise__proto__: Promise[[PromiseStatus]]: "resolved"
</code>```

答:
Okay all you need to change is :

```<code>componentDidMount() {
    this.setState(prevState => ({
        currentUser: helpers.fetchUser()
    }));
}
</code>```

to

```<code>componentDidMount() {
    helpers.fetchUser().then(data => {
        this.setState(prevState => ({
            currentUser: data
        }));
    })
}
</code>```

WORKING DEMO (checkout the console)

NOTE : async await always returns the promise it just make
  synchronousonus behaviour inside the async function but end ot the
  function it will always returns the promise.

Body:
I am currently working on a little app for fun. I ran into an issue with using axios and returning the response to my App component as updated state.

I then try to allow another component to use that piece of state, but I am not able to actually access the data. I can console.log(props) from within the List component, but I am not sure how to output the actual data as I am only able to output the promise results. I want to be able to output props.currentUser and have it be the googleId (using google Oauth2.0)..I am sure the solution is simple but, here is my code:

App.js ->

import React from 'react';
import helpers from '../helpers';
import List from './List';

class App extends React.Component{

  state = {
    currentUser: null
  }

  componentDidMount() {
    this.setState(prevState => ({
      currentUser: helpers.fetchUser()
    }));
  }

  render() {
    return (

        <List currentUser={this.state.currentUser}/>

    );
  }
};

export default App;

helpers.js ->

import axios from 'axios';

var helpers = {
  fetchUser: async () => {
      const user = await axios.get('/api/current_user');

      return user.data;
  }
};

export default helpers;

List Component ->

import React from 'react';

const List = (props) => {

  const renderContent = () => {
      console.log(props);
      return
{props.currentUser}

  }

  renderContent();

  return (

Grocery List

  );
}

export default List;

Output ->

{currentUser: null}
{currentUser: Promise}
    currentUser: Promise__proto__: Promise[[PromiseStatus]]: "resolved"

Body:
Okay all you need to change is :

componentDidMount() {
    this.setState(prevState => ({
        currentUser: helpers.fetchUser()
    }));
}

to

componentDidMount() {
    helpers.fetchUser().then(data => {
        this.setState(prevState => ({
            currentUser: data
        }));
    })
}

WORKING DEMO (checkout the console)

NOTE : async await always returns the promise it just make
  synchronousonus behaviour inside the async function but end ot the
  function it will always returns the promise.


问:
How bind the scroll event on a Live()?
A while ago I've solve an issue for someone that wanted his textarea to grow. I've made a function that listens to the scroll and keyup events of the area and recalculates the number of rows. I wanted to use the code in another project, but there's a problem. The textarea's are not know  To solve this, I'm using live instead of bind, so that future area's will be bound as well.

Now I'm finding that the live executes a lot slower than a bind. I've created a simplified example on jsFiddle. The upper textarea behaves as I want, but newly added ones flicker due to the late signaling (I'm using Chrome).

How can I make the live as fast as the bind? The problem is that the scroll can't be used with a live statement. Is there a way to enable scroll for live? Is there maybe a jQuery event that signals me that a new TextArea has been added, so I can use a bind to add the scroll on the newly created element?

I'm looking forward to your ideas.

EDIT: Changed link to the code. Removed scrollingCode. Added another button to create a different textarea. The problem has to do with 'scroll'. It doesn't fire.

Clarification: I will not know what function will create the textarea's. I see flickering on the dynamically added boxes in Chrome.

For future readers:

In jQuery 1.3.x only the following
  JavaScript events (in addition to
  custom events) could be bound with
  .live(): click, dblclick, keydown,
  keypress, keyup, mousedown, mousemove,
  mouseout, mouseover, and mouseup. As
  of jQuery 1.4 the .live() method
  supports custom events as well as all
  JavaScript events that bubble. As of
  jQuery 1.4.1 even focus and blur work
  with live (mapping to the more
  appropriate, bubbling, events focusin
  and focusout). As of jQuery 1.4.1 the
  hover event can be specified (mapping
  to mouseenter and mouseleave, which,
  in turn, are mapped to mouseover and
  mouseout).

答:
Try this (JSFiddle):

```<code>$('#Add').click(function(){
    var id = "newtextarea"+Math.floor(Math.random()*1000);
   $('#pane').append($('<textarea class="new" rows="1" cols="40" id="'+id+'"></textarea><br/>'));
    $('textarea:last').focus();
    bindAgain(id);
});

//inital resize
resizeTextArea($('#tst'));

//'live' event
$('textarea.new').bind('keyup scroll', function() {
    resizeTextArea($(this));
});

function bindAgain(id)
{
    $('#'+id).bind('keyup scroll', function() {
    resizeTextArea($(this));
});

}
</code>```

Basically, it rebinds the event using a dynamically created ID. Not as elegant as karim79's solution, but it works.

Title: How bind the scroll event on a Live()?

Body:
Try this (JSFiddle):

$('#Add').click(function(){
    var id = "newtextarea"+Math.floor(Math.random()*1000);
   $('#pane').append($('<textarea class="new" rows="1" cols="40" id="'+id+'"></textarea><br/>'));
    $('textarea:last').focus();
    bindAgain(id);
});

//inital resize
resizeTextArea($('#tst'));

//'live' event
$('textarea.new').bind('keyup scroll', function() {
    resizeTextArea($(this));
});

function bindAgain(id)
{
    $('#'+id).bind('keyup scroll', function() {
    resizeTextArea($(this));
});

}

Basically, it rebinds the event using a dynamically created ID. Not as elegant as karim79's solution, but it works.


问:
presentViewController called infinitely in viewDidAppear
I am trying to implement a fullscreen UIImagePickerController in my app. I couldn't present the view controller in viewDidLoad because presenting view controllers on detached view controllers is discouraged. However, my viewDidAppear gets called infinitely and the image picker controller gets added and then drops from the screen with each call. I tried dispatching to the main queue, but that did not resolve the issue.

```<code>- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    ipc = [[UIImagePickerController alloc] init];
    ipc.delegate = self;

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.showsCameraControls = NO;

        CGAffineTransform translate = CGAffineTransformMakeTranslation(0.0, 71.0);
        ipc.cameraViewTransform = translate;

        CGAffineTransform scale = CGAffineTransformScale(translate, 1.333333, 1.333333);
        ipc.cameraViewTransform = scale;

        ipc.showsCameraControls = NO;
        ipc.tabBarController.tabBar.hidden = YES;
        ipc.allowsEditing = NO;
        [self presentViewController:ipc animated:YES completion:nil];

    }

}

#pragma mark - ImagePickerController Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage* theImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    if( picker.sourceType == UIImagePickerControllerSourceTypeCamera )
    {
        UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);
    }
    int height = -1;
    if([[NSUserDefaults standardUserDefaults] integerForKey:@"reduce_image"] == 0){
        height = 640;
    } else if ([[NSUserDefaults standardUserDefaults] integerForKey:@"reduce_image"] == 1) {
        height = 1024;
    } else {
        height = 1600;
    }

    UIImage* resizedImageForUpload = [UtilityFunctions scaleAndRotateImage:theImage maxResolution:height];
    NSData* imageDataForUpload = UIImageJPEGRepresentation(resizedImageForUpload, 1);   // reduced image! //

    NSString *userDataset = [UtilityFunctions retrieveFromUserDefaults:@"dataset"];

    [self didPickImage:imageDataForUpload atLocation:currentLocation
                     userDataset: userDataset];

    [picker dismissViewControllerAnimated:YES completion:nil];

    [mLocationManager stopUpdatingLocation];

}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    /*navigate to home tab*/
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.tabBarController.tabBar.hidden = NO;
    [self.tabBarController setSelectedIndex:0];

}
</code>```

答:
You're dismissing the image picker view controller in response to its delegate method being called, which in turn calls your -viewDidAppear: method, which just presents another image picker view controller. You need to break the cycle somehow, with the code you've written the behavior you described is what I'd expect.

One approach would be to set ipc to an instance of UIImagePickerController in -viewDidLoad (which is only called once), the present it if it's non-nil in -viewDidAppear:, then nil it out in the image picker delegate methods to it's not re-presented the next time -viewDidAppear: is called.

Body:
I am trying to implement a fullscreen UIImagePickerController in my app. I couldn't present the view controller in viewDidLoad because presenting view controllers on detached view controllers is discouraged. However, my viewDidAppear gets called infinitely and the image picker controller gets added and then drops from the screen with each call. I tried dispatching to the main queue, but that did not resolve the issue.

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    ipc = [[UIImagePickerController alloc] init];
    ipc.delegate = self;

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.showsCameraControls = NO;

        CGAffineTransform translate = CGAffineTransformMakeTranslation(0.0, 71.0);
        ipc.cameraViewTransform = translate;

        CGAffineTransform scale = CGAffineTransformScale(translate, 1.333333, 1.333333);
        ipc.cameraViewTransform = scale;

        ipc.showsCameraControls = NO;
        ipc.tabBarController.tabBar.hidden = YES;
        ipc.allowsEditing = NO;
        [self presentViewController:ipc animated:YES completion:nil];

    }

}

#pragma mark - ImagePickerController Delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage* theImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    if( picker.sourceType == UIImagePickerControllerSourceTypeCamera )
    {
        UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);
    }
    int height = -1;
    if([[NSUserDefaults standardUserDefaults] integerForKey:@"reduce_image"] == 0){
        height = 640;
    } else if ([[NSUserDefaults standardUserDefaults] integerForKey:@"reduce_image"] == 1) {
        height = 1024;
    } else {
        height = 1600;
    }

    UIImage* resizedImageForUpload = [UtilityFunctions scaleAndRotateImage:theImage maxResolution:height];
    NSData* imageDataForUpload = UIImageJPEGRepresentation(resizedImageForUpload, 1);   // reduced image! //

    NSString *userDataset = [UtilityFunctions retrieveFromUserDefaults:@"dataset"];

    [self didPickImage:imageDataForUpload atLocation:currentLocation
                     userDataset: userDataset];

    [picker dismissViewControllerAnimated:YES completion:nil];

    [mLocationManager stopUpdatingLocation];

}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    /*navigate to home tab*/
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.tabBarController.tabBar.hidden = NO;
    [self.tabBarController setSelectedIndex:0];

}


问:
adding waypoints in the react-google-maps
editable samplecode how to use waypoints in the following code  does the waypoints helps to plot the way which I updated in the database wheather the ponits will be based on the points I have updated               </p>

```<code>const DirectionsService = new google.maps.DirectionsService();
                 const  DirectionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true},{strokeColor:"#4a4a4a"});

      DirectionsService.route({

        origin: new google.maps.LatLng(this.state.orgin.latitude ,this.state.orgin.longitude),
         destination: new google.maps.LatLng(this.state.destination.latitude ,this.state.destination.longitude),
          travelMode: google.maps.TravelMode.DRIVING,

      },
       (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result,
          });
        } else {
          console.error(`error fetching directions ${result}`);
        }
      });

            }).catch(function (err) {

            });

    }

  })

)(props =>
  <GoogleMap
    defaultZoom={50}>
     <DirectionsRenderer directions={props.directions}   />

  < Marker

  position={{  lat:props.delivery!=undefined?props.delivery.latitude:null, lng:  props.delivery!=undefined?props.delivery.longitude:null }} />

  </GoogleMap>

);
    return (
      <MapWithADirectionsRenderer />
    )
  }
</code>```

答:
You can add waypoints by adding waypoints[] array of DirectionsWaypoint in your Directions Request.

You can check this documentation to learn more: https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests

Here's a sample waypoints array:

```<code>waypoints: [
    {
        location: new google.maps.LatLng(14.546748, 121.05455)
    },
    {
        location: new google.maps.LatLng(14.552444,121.044488)
    }
]
</code>```

Here's a sample Direction Request with waypoints:

```<code>DirectionsService.route({
   origin: new google.maps.LatLng(14.533593, 121.053128),
   destination: new google.maps.LatLng(14.550895, 121.025079),
   travelMode: google.maps.TravelMode.DRIVING,
   waypoints: [
        {
           location: new google.maps.LatLng(14.546748, 121.05455)
        },
        {
           location: new google.maps.LatLng(14.552444,121.044488)
        }
   ]
}, (result, status) => {
   if (status === google.maps.DirectionsStatus.OK) {
      this.setState({
         directions: result,
      });
   } else {
     console.error(`error fetching directions ${result}`);
   }
});
</code>```

Body:
editable samplecode how to use waypoints in the following code  does the waypoints helps to plot the way which I updated in the database wheather the ponits will be based on the points I have updated

const DirectionsService = new google.maps.DirectionsService();
                 const  DirectionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true},{strokeColor:"#4a4a4a"});

      DirectionsService.route({

        origin: new google.maps.LatLng(this.state.orgin.latitude ,this.state.orgin.longitude),
         destination: new google.maps.LatLng(this.state.destination.latitude ,this.state.destination.longitude),
          travelMode: google.maps.TravelMode.DRIVING,

      },
       (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result,
          });
        } else {
          console.error(`error fetching directions ${result}`);
        }
      });

            }).catch(function (err) {

            });

    }

  })

)(props =>
  <GoogleMap
    defaultZoom={50}>
     <DirectionsRenderer directions={props.directions}   />

  < Marker

  position={{  lat:props.delivery!=undefined?props.delivery.latitude:null, lng:  props.delivery!=undefined?props.delivery.longitude:null }} />

  </GoogleMap>

);
    return (
      <MapWithADirectionsRenderer />
    )
  }

Body:
You can add waypoints by adding waypoints[] array of DirectionsWaypoint in your Directions Request.

You can check this documentation to learn more: https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests

Here's a sample waypoints array:

waypoints: [
    {
        location: new google.maps.LatLng(14.546748, 121.05455)
    },
    {
        location: new google.maps.LatLng(14.552444,121.044488)
    }
]

Here's a sample Direction Request with waypoints:

DirectionsService.route({
   origin: new google.maps.LatLng(14.533593, 121.053128),
   destination: new google.maps.LatLng(14.550895, 121.025079),
   travelMode: google.maps.TravelMode.DRIVING,
   waypoints: [
        {
           location: new google.maps.LatLng(14.546748, 121.05455)
        },
        {
           location: new google.maps.LatLng(14.552444,121.044488)
        }
   ]
}, (result, status) => {
   if (status === google.maps.DirectionsStatus.OK) {
      this.setState({
         directions: result,
      });
   } else {
     console.error(`error fetching directions ${result}`);
   }
});


问:
Read from csv first word and word first word after v
I am wanting to read from csv, put it into dataframe and get the very first word and first word after v.

Csv to dataframe looks like:

```<code>       A
0 choclate v dairy cakes
1 ice cake v ka ka1
2 cc dd v ee fff gg hh
3 iii  v kkkk
</code>```

Desired:

```<code>   A
0 choclate v dairy
1 ice v ka
2 cc v ee
3 iii  v kkkk
</code>```

I try:

```<code>df1 = pd.read_csv('C:\\THE.csv',
                  index_col=False,
                  usecols=[0],
                  names=["AA"],
                  header=None)
zz = df1['AA'].str.split('v', expand=True)\
  .apply(lambda x: x.str.extract('(\w+)', expand=False))\
  .apply(lambda x: ' v '.join(x), 1)
</code>```

Error:

```<code>    .apply(lambda x: ' v '.join(x), 1)
TypeError: ('sequence item 1: expected str instance, float found', 'occurred at index 1')
</code>```

How can I get my desired output?

答:
You can try this</p>

```<code>df.A.str.split(' v ').apply(lambda x : [y.split(' ')[0] for y in x]).apply(' v '.join)
Out[198]:
0    choclate v dairy
1            ice v ka
2             cc v ee
3          iii v kkkk
Name: A, dtype: object
</code>```

Body:
I am wanting to read from csv, put it into dataframe and get the very first word and first word after v.

Csv to dataframe looks like:

       A
0 choclate v dairy cakes
1 ice cake v ka ka1
2 cc dd v ee fff gg hh
3 iii  v kkkk

Desired:

   A
0 choclate v dairy
1 ice v ka
2 cc v ee
3 iii  v kkkk

I try:

df1 = pd.read_csv('C:\\THE.csv',
                  index_col=False,
                  usecols=[0],
                  names=["AA"],
                  header=None)
zz = df1['AA'].str.split('v', expand=True)\
  .apply(lambda x: x.str.extract('(\w+)', expand=False))\
  .apply(lambda x: ' v '.join(x), 1)

Error:

    .apply(lambda x: ' v '.join(x), 1)
TypeError: ('sequence item 1: expected str instance, float found', 'occurred at index 1')

How can I get my desired output?

Body:
You can try this

df.A.str.split(' v ').apply(lambda x : [y.split(' ')[0] for y in x]).apply(' v '.join)
Out[198]:
0    choclate v dairy
1            ice v ka
2             cc v ee
3          iii v kkkk
Name: A, dtype: object


问:
Selecting a drop-down box option does not affect page
I'm trying to make an extension that selects facilitates filling out info on checkout page of a website (you'll probably have to add to cart before you can go to the checkout page). Currently I'm just setting the "selected" value of a certain option tag to be true, but it seems not to affect the page as intended. I'm talking about the Country and State selection on the checkout page (I want it to be Canada and BC). Would prefer vanilla Javascript

Here's my code:

```<code>var checkoutSelects = document.querySelectorAll("select:not([type=hidden])");

for(var i = 0; i < checkoutSelects.length; i++) {
  if(checkoutSelects[i].getAttribute("id").toLowerCase().includes('country')) {
      var countryOptions = checkoutSelects[i].querySelectorAll('option');

      for(var a = 0; a < countryOptions.length; a++) {
        if(countryOptions[a].value.toLowerCase().includes("canada")) {
            countryOptions[a].selected = true;
        }
    }
  }
}
</code>```

答:
Can you try countryOptions.selectedIndex = a;
instead of
countryOptions[a].selected = true;</p>

Body:
I'm trying to make an extension that selects facilitates filling out info on checkout page of a website (you'll probably have to add to cart before you can go to the checkout page). Currently I'm just setting the "selected" value of a certain option tag to be true, but it seems not to affect the page as intended. I'm talking about the Country and State selection on the checkout page (I want it to be Canada and BC). Would prefer vanilla Javascript

Here's my code:

var checkoutSelects = document.querySelectorAll("select:not([type=hidden])");

for(var i = 0; i < checkoutSelects.length; i++) {
  if(checkoutSelects[i].getAttribute("id").toLowerCase().includes('country')) {
      var countryOptions = checkoutSelects[i].querySelectorAll('option');

      for(var a = 0; a < countryOptions.length; a++) {
        if(countryOptions[a].value.toLowerCase().includes("canada")) {
            countryOptions[a].selected = true;
        }
    }
  }
}


问:
UPDATE two rows - MySQL
I'm trying to update two rows in my database using a query (which is going to be run from a PHP script) and there is just one Condition (WHERE). What I've tried is:

```<code>$sql = 'UPDATE ' . CANNED_MESSAGES . "
                SET canned_message_content = '" . $db->sql_escape($content) . "',
                    canned_message_title = '" . $db->sql_escape($title) . "'
                WHERE id = '" . intval($id) . "'" ;
$db->sql_query($sql);
</code>```

Can you tell me whats wrong with my query? :)

答: I highly doubt that two rows can have the same id column. Do they? If not, how could you update 2 rows by specifying a condition on a column with such a constraint?</p>

Title: UPDATE two rows - MySQL

Body:
I'm trying to update two rows in my database using a query (which is going to be run from a PHP script) and there is just one Condition (WHERE). What I've tried is:

$sql = 'UPDATE ' . CANNED_MESSAGES . "
                SET canned_message_content = '" . $db->sql_escape($content) . "',
                    canned_message_title = '" . $db->sql_escape($title) . "'
                WHERE id = '" . intval($id) . "'" ;
$db->sql_query($sql);

Can you tell me whats wrong with my query? :)


问:
My Listview is not refresh after update database row
My ListView is not refreshing after i am using notifyDataSetChanged();
but i dont know what is wrong in my code please help me how to update my listview when my database is update.

```<code>import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;

public class EventsView extends Fragment {
    ListView list4;
    String json_string;
    String JSON_STRING;
    JSONObject JO;
    JSONObject jsonObject;
    JSONArray jsonArray;
    int count = 0;
    HashMap<String, Object> obj;
    String topic,description,event_date,event_id;
    private Context mContext;
    private PopupWindow mPopupWindow;
    private LinearLayout linearLayout;
    private Activity mActivity;
    ProgressDialog pDialog;
    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    String HttpURL = "http://192.168.1.10:8081/sms/update_event.php";
    String HttpURLDelete = "http://192.168.1.10:8081/sms/delete_event.php";
    SimpleAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.events_view, container, false);
        mContext = getContext();
        mActivity = getActivity();
        linearLayout = (LinearLayout) view.findViewById(R.id.r2);
        list4=(ListView)view.findViewById(R.id.list4);
        new show_event().execute();

        list4.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                obj = (HashMap<String, Object>) list4.getAdapter().getItem(position);
                new show_list().execute();
            }
        });

        return view;
    }

    class show_event extends AsyncTask<String,String,String> {

        ProgressDialog pdLoading = new ProgressDialog(getActivity());
        String json_url;
        @Override
        protected void onPreExecute() {
            json_url = "http://192.168.1.10:8081/sms/select_event.php";
            pdLoading.setMessage("\tLoading...");
            pdLoading.isIndeterminate();
            pdLoading.setIndeterminate(true);
            pdLoading.setCancelable(false);
            pdLoading.show();
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();

                while ((JSON_STRING = bufferedReader.readLine()).equals("null")) ;
                {
                    stringBuilder.append(JSON_STRING +"\n");
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            List<Map<String, String>> data2 = null;
            data2 = new ArrayList<Map<String, String>>();
            json_string = result;
            try {
                jsonObject = new JSONObject(json_string);
                jsonArray = jsonObject.getJSONArray("server_response");
                if (jsonArray.length() != 0) {

                    for (count = 0; count < jsonArray.length(); count++) {
                        JO = jsonArray.getJSONObject(count);
                        HashMap<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A",JO.getString("Id"));
                        datanum.put("B",JO.getString("Topic"));
                        datanum.put("C",JO.getString("Description"));
                        datanum.put("D",JO.getString("Event_Date"));
                        data2.add(datanum);

                    }

                    adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
                    list4.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

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

            pdLoading.dismiss();

        }

    }

    class show_list extends AsyncTask<String,String,String> {
        private int mYear, mMonth, mDay;
        ProgressDialog pdLoading = new ProgressDialog(getActivity());

        @Override
        protected String doInBackground(String... strings) {

            event_id=(String)obj.get("A");
            topic = (String) obj.get("B");
            description=(String)obj.get("C");
            event_date=(String)obj.get("D");
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdLoading.setMessage("\tLoading...");
            pdLoading.isIndeterminate();
            pdLoading.setIndeterminate(true);
            pdLoading.setCancelable(false);
            pdLoading.show();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            final View customView = inflater.inflate(R.layout.edit_event,null);
            mPopupWindow = new PopupWindow(customView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
            mPopupWindow.setOutsideTouchable(true);

            if(Build.VERSION.SDK_INT>=21){
                mPopupWindow.setElevation(5.0f);
            }

            final EditText edit_topic=(EditText)customView.findViewById(R.id.edit_topic);
            final EditText edit_description=(EditText)customView.findViewById(R.id.edit_description);
            final EditText edit_date=(EditText)customView.findViewById(R.id.edit_Date);
            Button delete_btn=(Button)customView.findViewById(R.id.delete);

            Button update_btn=(Button)customView.findViewById(R.id.update);

            edit_topic.setText(topic);
            edit_description.setText(description);
            edit_date.setText(event_date);
            final String id=String.valueOf(event_id);

            edit_date.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Get Current Date
                    final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                    edit_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
                                }
                            }, mYear, mMonth, mDay);
                    datePickerDialog.show();
                }

            });

            update_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String topic= edit_topic.getText().toString();
                    String description=  edit_description.getText().toString();
                    String edit_event_date=edit_date.getText().toString();
                    StudentRecordUpdate(id,topic,description,edit_event_date);
                    mPopupWindow.dismiss();

                }
            });
            delete_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    StudentDelete(id);
                }
            });

            mPopupWindow.showAtLocation(linearLayout, Gravity.CENTER,0,0);
            mPopupWindow.setFocusable(true);
            mPopupWindow.update();
            pdLoading.dismiss();

        }

    }
    public void StudentRecordUpdate(final String id, final String topic, final String description, final String  event_date){

        class StudentRecordUpdateClass extends AsyncTask<String,Void,String> {

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

                pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);
                pDialog.dismiss();

                Toast.makeText(getActivity(),httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            }

            @Override
            protected String doInBackground(String... params) {

                hashMap.put("Id",params[0]);
                hashMap.put("Topic",params[1]);
                hashMap.put("Description",params[2]);
                hashMap.put("Event_Date",params[3]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        StudentRecordUpdateClass studentRecordUpdateClass = new StudentRecordUpdateClass();

        studentRecordUpdateClass.execute(id,topic,description,event_date);
    }

    // Method to Delete Student Record
    public void StudentDelete(final String ID) {

        class StudentDeleteClass extends AsyncTask<String, Void, String> {

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

                pDialog = ProgressDialog.show(getActivity(), "Loading Data", null, true, true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                pDialog.dismiss();

                Toast.makeText(getContext(), httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

               getActivity().finish();

            }

            @Override
            protected String doInBackground(String... params) {

                // Sending STUDENT id.
                hashMap.put("Id", params[0]);

                finalResult = httpParse.postRequest(hashMap, HttpURLDelete);

                return finalResult;
            }
        }

        StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

        studentDeleteClass.execute(ID);
    }

}
</code>```

答:
Try this set Adapter with empty list as soon as you initialize your ListView, then just add data to list and call notifyDataSetChanged() on adapter

Make list global

```<code>List<Map<String, String>> data2 = new ArrayList<Map<String, String>>();
</code>```

Then in onCreateView, add below code under listview initialization

```<code> list4=(ListView)view.findViewById(R.id.list4);
 adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
 list4.setAdapter(adapter);
</code>```

Then in onPostExecute of your AsyncTask, clear the existing list and new data,then just call notifyDataSetChanged() as in

```<code>        @Override
        protected void onPostExecute(String result) {
            data2.clear(); //< --add this
            json_string = result;
            try {
                jsonObject = new JSONObject(json_string);
                jsonArray = jsonObject.getJSONArray("server_response");
                if (jsonArray.length() != 0) {

                    for (count = 0; count < jsonArray.length(); count++) {
                        JO = jsonArray.getJSONObject(count);
                        HashMap<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A",JO.getString("Id"));
                        datanum.put("B",JO.getString("Topic"));
                        datanum.put("C",JO.getString("Description"));
                        datanum.put("D",JO.getString("Event_Date"));
                        data2.add(datanum);

                    }
                   adapter.notifyDataSetChanged(); //< --- call this
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            pdLoading.dismiss();

        }
</code>```

Body:
My ListView is not refreshing after i am using notifyDataSetChanged();
but i dont know what is wrong in my code please help me how to update my listview when my database is update.

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;

public class EventsView extends Fragment {
    ListView list4;
    String json_string;
    String JSON_STRING;
    JSONObject JO;
    JSONObject jsonObject;
    JSONArray jsonArray;
    int count = 0;
    HashMap<String, Object> obj;
    String topic,description,event_date,event_id;
    private Context mContext;
    private PopupWindow mPopupWindow;
    private LinearLayout linearLayout;
    private Activity mActivity;
    ProgressDialog pDialog;
    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    String HttpURL = "http://192.168.1.10:8081/sms/update_event.php";
    String HttpURLDelete = "http://192.168.1.10:8081/sms/delete_event.php";
    SimpleAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.events_view, container, false);
        mContext = getContext();
        mActivity = getActivity();
        linearLayout = (LinearLayout) view.findViewById(R.id.r2);
        list4=(ListView)view.findViewById(R.id.list4);
        new show_event().execute();

        list4.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                obj = (HashMap<String, Object>) list4.getAdapter().getItem(position);
                new show_list().execute();
            }
        });

        return view;
    }

    class show_event extends AsyncTask<String,String,String> {

        ProgressDialog pdLoading = new ProgressDialog(getActivity());
        String json_url;
        @Override
        protected void onPreExecute() {
            json_url = "http://192.168.1.10:8081/sms/select_event.php";
            pdLoading.setMessage("\tLoading...");
            pdLoading.isIndeterminate();
            pdLoading.setIndeterminate(true);
            pdLoading.setCancelable(false);
            pdLoading.show();
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();

                while ((JSON_STRING = bufferedReader.readLine()).equals("null")) ;
                {
                    stringBuilder.append(JSON_STRING +"\n");
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            List<Map<String, String>> data2 = null;
            data2 = new ArrayList<Map<String, String>>();
            json_string = result;
            try {
                jsonObject = new JSONObject(json_string);
                jsonArray = jsonObject.getJSONArray("server_response");
                if (jsonArray.length() != 0) {

                    for (count = 0; count < jsonArray.length(); count++) {
                        JO = jsonArray.getJSONObject(count);
                        HashMap<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A",JO.getString("Id"));
                        datanum.put("B",JO.getString("Topic"));
                        datanum.put("C",JO.getString("Description"));
                        datanum.put("D",JO.getString("Event_Date"));
                        data2.add(datanum);

                    }

                    adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
                    list4.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

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

            pdLoading.dismiss();

        }

    }

    class show_list extends AsyncTask<String,String,String> {
        private int mYear, mMonth, mDay;
        ProgressDialog pdLoading = new ProgressDialog(getActivity());

        @Override
        protected String doInBackground(String... strings) {

            event_id=(String)obj.get("A");
            topic = (String) obj.get("B");
            description=(String)obj.get("C");
            event_date=(String)obj.get("D");
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdLoading.setMessage("\tLoading...");
            pdLoading.isIndeterminate();
            pdLoading.setIndeterminate(true);
            pdLoading.setCancelable(false);
            pdLoading.show();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            final View customView = inflater.inflate(R.layout.edit_event,null);
            mPopupWindow = new PopupWindow(customView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
            mPopupWindow.setOutsideTouchable(true);

            if(Build.VERSION.SDK_INT>=21){
                mPopupWindow.setElevation(5.0f);
            }

            final EditText edit_topic=(EditText)customView.findViewById(R.id.edit_topic);
            final EditText edit_description=(EditText)customView.findViewById(R.id.edit_description);
            final EditText edit_date=(EditText)customView.findViewById(R.id.edit_Date);
            Button delete_btn=(Button)customView.findViewById(R.id.delete);

            Button update_btn=(Button)customView.findViewById(R.id.update);

            edit_topic.setText(topic);
            edit_description.setText(description);
            edit_date.setText(event_date);
            final String id=String.valueOf(event_id);

            edit_date.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Get Current Date
                    final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                    edit_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
                                }
                            }, mYear, mMonth, mDay);
                    datePickerDialog.show();
                }

            });

            update_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String topic= edit_topic.getText().toString();
                    String description=  edit_description.getText().toString();
                    String edit_event_date=edit_date.getText().toString();
                    StudentRecordUpdate(id,topic,description,edit_event_date);
                    mPopupWindow.dismiss();

                }
            });
            delete_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    StudentDelete(id);
                }
            });

            mPopupWindow.showAtLocation(linearLayout, Gravity.CENTER,0,0);
            mPopupWindow.setFocusable(true);
            mPopupWindow.update();
            pdLoading.dismiss();

        }

    }
    public void StudentRecordUpdate(final String id, final String topic, final String description, final String  event_date){

        class StudentRecordUpdateClass extends AsyncTask<String,Void,String> {

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

                pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);
                pDialog.dismiss();

                Toast.makeText(getActivity(),httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            }

            @Override
            protected String doInBackground(String... params) {

                hashMap.put("Id",params[0]);
                hashMap.put("Topic",params[1]);
                hashMap.put("Description",params[2]);
                hashMap.put("Event_Date",params[3]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        StudentRecordUpdateClass studentRecordUpdateClass = new StudentRecordUpdateClass();

        studentRecordUpdateClass.execute(id,topic,description,event_date);
    }

    // Method to Delete Student Record
    public void StudentDelete(final String ID) {

        class StudentDeleteClass extends AsyncTask<String, Void, String> {

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

                pDialog = ProgressDialog.show(getActivity(), "Loading Data", null, true, true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                pDialog.dismiss();

                Toast.makeText(getContext(), httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

               getActivity().finish();

            }

            @Override
            protected String doInBackground(String... params) {

                // Sending STUDENT id.
                hashMap.put("Id", params[0]);

                finalResult = httpParse.postRequest(hashMap, HttpURLDelete);

                return finalResult;
            }
        }

        StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

        studentDeleteClass.execute(ID);
    }

}

Body:
Try this set Adapter with empty list as soon as you initialize your ListView, then just add data to list and call notifyDataSetChanged() on adapter

Make list global

List<Map<String, String>> data2 = new ArrayList<Map<String, String>>();

Then in onCreateView, add below code under listview initialization

 list4=(ListView)view.findViewById(R.id.list4);
 adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
 list4.setAdapter(adapter);

Then in onPostExecute of your AsyncTask, clear the existing list and new data,then just call notifyDataSetChanged() as in

        @Override
        protected void onPostExecute(String result) {
            data2.clear(); //< --add this
            json_string = result;
            try {
                jsonObject = new JSONObject(json_string);
                jsonArray = jsonObject.getJSONArray("server_response");
                if (jsonArray.length() != 0) {

                    for (count = 0; count < jsonArray.length(); count++) {
                        JO = jsonArray.getJSONObject(count);
                        HashMap<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A",JO.getString("Id"));
                        datanum.put("B",JO.getString("Topic"));
                        datanum.put("C",JO.getString("Description"));
                        datanum.put("D",JO.getString("Event_Date"));
                        data2.add(datanum);

                    }
                   adapter.notifyDataSetChanged(); //< --- call this
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            pdLoading.dismiss();

        }


问:
Horizontal line with different colours
How I can modify this code to have different colors for lines (for example Black, red, green)

```<code>library(ggplot2)

    lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                     grp  = factor(c(1, 1, 2, 2, 3, 3),
                                   levels = 1:3,
                                   labels = c("Group 1", "Group 2", "Group 3")))

    ggplot(mtcars, aes(mpg, disp)) +
          geom_point(aes(colour=factor(vs),
          fill = factor(vs)), shape=21, size = 4) +
          scale_fill_manual(values=c("blue", "pink")) +
          scale_colour_manual(values=c("black", "black"))+
          geom_hline(data = lt,
                     mapping = aes(yintercept = yint, linetype = grp))
</code>```

I tried to use this function buT I got the error

```<code>ggplot(DataSet, aes(AGE, RESULT)) +
      geom_point(aes(colour=PATIENT.SEX,
      fill = PATIENT.SEX), shape=21, size = 1.4) +
      scale_fill_manual(values=c("hotpink", "skyblue2")) +
      scale_colour_manual(values=c("hotpink", "skyblue2"))+
      ylab("Potassium (mmol/L) ")+xlab("Age (month) ")+ggtitle("Alberta observations")+theme_bw()+
      theme(plot.title = element_text(lineheight=.8, face="bold",size=13))+
      theme(axis.text=element_text(size=12),axis.title=element_text(size=12,face="bold"))+
      theme(panel.border = element_blank(), panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))+
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint,linetype = RI),colour
=c("blue","blue", "red", "red", "black","black" ))
</code>```

答:
A solution is to modify the scale_color_manual call.  Set the values and the limits for the factor levels for vs (as already done in your post) and for the three group levels.  In the example below I've set the color for the factor(vs) to black for both levels, as was done in the original post, and then set the colors for Group 1, Group 2, and Group 3 as purple, green, and yellow.

```<code>library(ggplot2)

lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                 grp  = factor(c(1, 1, 2, 2, 3, 3),
                               levels = 1:3,
                               labels = c("Group 1", "Group 2", "Group 3")))

ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs), fill = factor(vs)), shape=21, size = 4) +
      scale_fill_manual(values=c("blue", "pink")) +
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint, linetype = grp, color = grp)) +
      scale_color_manual(name   = "",
                         values = c("black", "black", "Purple", "Green", "Yellow"),
                         limits = c(0, 1, "Group 1", "Group 2", "Group 3"))
</code>```

Title: Horizontal line with different colours

Body:
How I can modify this code to have different colors for lines (for example Black, red, green)

library(ggplot2)

    lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                     grp  = factor(c(1, 1, 2, 2, 3, 3),
                                   levels = 1:3,
                                   labels = c("Group 1", "Group 2", "Group 3")))

    ggplot(mtcars, aes(mpg, disp)) +
          geom_point(aes(colour=factor(vs),
          fill = factor(vs)), shape=21, size = 4) +
          scale_fill_manual(values=c("blue", "pink")) +
          scale_colour_manual(values=c("black", "black"))+
          geom_hline(data = lt,
                     mapping = aes(yintercept = yint, linetype = grp))

I tried to use this function buT I got the error

ggplot(DataSet, aes(AGE, RESULT)) +
      geom_point(aes(colour=PATIENT.SEX,
      fill = PATIENT.SEX), shape=21, size = 1.4) +
      scale_fill_manual(values=c("hotpink", "skyblue2")) +
      scale_colour_manual(values=c("hotpink", "skyblue2"))+
      ylab("Potassium (mmol/L) ")+xlab("Age (month) ")+ggtitle("Alberta observations")+theme_bw()+
      theme(plot.title = element_text(lineheight=.8, face="bold",size=13))+
      theme(axis.text=element_text(size=12),axis.title=element_text(size=12,face="bold"))+
      theme(panel.border = element_blank(), panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))+
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint,linetype = RI),colour
=c("blue","blue", "red", "red", "black","black" ))

Body:
A solution is to modify the scale_color_manual call.  Set the values and the limits for the factor levels for vs (as already done in your post) and for the three group levels.  In the example below I've set the color for the factor(vs) to black for both levels, as was done in the original post, and then set the colors for Group 1, Group 2, and Group 3 as purple, green, and yellow.

library(ggplot2)

lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                 grp  = factor(c(1, 1, 2, 2, 3, 3),
                               levels = 1:3,
                               labels = c("Group 1", "Group 2", "Group 3")))

ggplot(mtcars, aes(mpg, disp)) +
      geom_point(aes(colour=factor(vs), fill = factor(vs)), shape=21, size = 4) +
      scale_fill_manual(values=c("blue", "pink")) +
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint, linetype = grp, color = grp)) +
      scale_color_manual(name   = "",
                         values = c("black", "black", "Purple", "Green", "Yellow"),
                         limits = c(0, 1, "Group 1", "Group 2", "Group 3"))


问:
Table View Cells Not Selectable After Resigning UITextView as First Responder
I have a UITextView in a UITableViewCell. I have set it to become first responder when the cell is selected as so:

```<code>TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

thisCell.txtHidden.text=@"";
[thisCell.txtHidden becomeFirstResponder];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goAwayKeyboard)];
[self.view addGestureRecognizer:tap];
</code>```

So when the cell is selected txtHidden becomes first responder. And then the selector goAwayKeyboard is triggered when you click out of the keyboard.

```<code>-(void)goAwayKeyboard
{
    TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [thisCell.txtHidden resignFirstResponder];
}
</code>```

This works, however after the keyboard is resigned I can no longer select a cell in the table view. I can scroll the table view, but the cells aren't selectable and I can't figure out why.

答: The tap gesture recognizer is probably swallowing all touch events after it's added to the view. Perhaps removing it in -goAwayKeyboard would restore touch interaction.

Body:
I have a UITextView in a UITableViewCell. I have set it to become first responder when the cell is selected as so:

TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

thisCell.txtHidden.text=@"";
[thisCell.txtHidden becomeFirstResponder];

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goAwayKeyboard)];
[self.view addGestureRecognizer:tap];

So when the cell is selected txtHidden becomes first responder. And then the selector goAwayKeyboard is triggered when you click out of the keyboard.

-(void)goAwayKeyboard
{
    TPNTableViewCell *thisCell = (TPNTableViewCell *)[tblMain cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [thisCell.txtHidden resignFirstResponder];
}

This works, however after the keyboard is resigned I can no longer select a cell in the table view. I can scroll the table view, but the cells aren't selectable and I can't figure out why.


问:
Creating pdf files in App Engine Cron Job
I am using Python 2.7 and Reportlab to create .pdf files for display/print in my app engine system.  I am using ndb.Model to store the data if that matters.

I am able to produce the equivalent of a bank statement for a single client on-line.  That is; the user clicks the on-screen 'pdf' button and the .pdf statement appears on screen in a new tab, exactly as it should.

However, I have to produce multiple statements overnight to be printed and posted the next morning.  One (largish) .pdf would be fine.

So, I can produce the pdf but how do I get it back to the user for printing?  I had thought of email but the size may (not sure) be too great and I'm not sure if this has too much risk for financial information.

At this stage statements for up to 20 clients per night (a total of 30-60 pages) must be produced but this number will increase to at least 200 statements per night during 2018.  Any thoughts or ideas for me?

Thanks
David

答:
One possibility would be to save the generated PDFs into Cloud Storage (GCS) and create a signed URL for each saved PDF which you could then send by email to the respective users. They can then download the PDFs using those emailed URLs and print them.

Or you can dynamically serve the saved PDFs on-demand, via actions on your app in response to subsequent user requests (view/print) etc.