问:
How to upgrade from HTTPClient to volley
In this class I am sending request to server asynchronously by extending AsyncTask using HttpClient, I have created two custom classes one for Uploading and Downloading of Images from the server, and other for sending JSON Object and array. Beside this I'm also able to differentiate the requests using RequestTag

Can we also do the same using volley?

How can I upgrade to Volley from the HttpClient having same approach like in below class?

```<code>package com.creative.projectmanager;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import org.apache.commons.logging.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
 * server manager class. performs all server requests asynchronously
 */
public class ServerManager {

    final private String SERVER_ADDRESS = "http://192.168.200.10/";

    public void login(String email, String password, int requestTag) {
        String url = SERVER_ADDRESS + "index.php?mobile/" + "login";
        HashMap<String, String> params = new HashMap<>();
        params.put("email", email);
        params.put("password", password);
        params.put("authenticate", "false");
        android.util.Log.w("My App", email + " " + password + " " + requestTag);
        AsyncHttpPost requestSender = new AsyncHttpPost(url, params, requestTag);
        requestSender.execute();
    }
    public void downloadImage(String imageUrl, int imageSize, int requestTag) {
        ImageDownloadTask imageDownloadTask = new ImageDownloadTask(imageUrl, imageSize, requestTag);
        imageDownloadTask.execute();
    }
    private class AsyncHttpPost extends AsyncTask<Void, Void, String> {
        private String url = "";
        private HashMap<String, String> postParams = null;
        private int requestTag;
        private String errorMessage = "";

        public AsyncHttpPost(String url, HashMap<String, String> params, int tag) {
            this.url = url;
            postParams = params;
            this.requestTag = tag;
        }

        @Override
        protected String doInBackground(Void... params) {
            byte[] result;
            String resultString = "";

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            try {
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
                for (String key:postParams.keySet()
                     ) {
                    nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
                }
                android.util.Log.w("My App",nameValuePairs.toString());
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
                HttpResponse response = httpClient.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();

                if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                    errorMessage = "ok";
                    result = EntityUtils.toByteArray(response.getEntity());
                    resultString = new String(result, "UTF-8");
                }
            }
            catch (UnsupportedEncodingException e) {
                errorMessage = "Encoding is not supported";
            }
            catch (Exception e) {
                errorMessage = "An error occurred";
            }
            return resultString;

        }

        @Override
        protected void onPostExecute(String s) {
            if (errorMessage.equals("ok")) {
                sourceActivity.requestFinished(s, requestTag);
            }
            else
                sourceActivity.requestFailed(errorMessage, requestTag);
        }
    }

    private class ImageDownloadTask extends AsyncTask<String, String, String> {
        private String imageUrl;
        private int imageSize;
        private int requestTag;
        Bitmap image;
        public ImageDownloadTask(String imageUrl, int imageSize, int requestTag) {
            this.imageUrl = imageUrl;
            this.imageSize = imageSize;
            this.requestTag = requestTag;
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(imageUrl);
                InputStream inputStream = new BufferedInputStream(url.openStream());
                image = createScaledBitmapFromStream(inputStream, imageSize);
            }
            catch (Exception e){
                //do nothing
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            sourceActivity.imageDownloaded(image, requestTag);
        }
        protected Bitmap createScaledBitmapFromStream(InputStream inputStream, int minimumDesiredBitmapSize) {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 32*1024);
            try {
                BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
                if (minimumDesiredBitmapSize > 0) {
                    BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
                    decodeBoundsOptions.inJustDecodeBounds = true;
                    bufferedInputStream.mark(32 * 1024);
                    BitmapFactory.decodeStream(bufferedInputStream, null, decodeBoundsOptions);
                    bufferedInputStream.reset();
                    int originalWidth = decodeBoundsOptions.outWidth;
                    int originalHeight = decodeBoundsOptions.outHeight;
                    decodeBitmapOptions.inSampleSize = Math.max(1, Math.min(originalWidth/minimumDesiredBitmapSize, originalHeight/minimumDesiredBitmapSize));
                }
                return BitmapFactory.decodeStream(bufferedInputStream, null, decodeBitmapOptions);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    bufferedInputStream.close();
                } catch (IOException ignored) {}
            }
        }
    }
}
</code>```

答:
There are a lot of examples of how to make requests with Volley, so "upgrading" will mean rewriting your code in different way.

Volley, in my opinion is not the best library for HTTP calls, I would recommend you to try
http://square.github.io/retrofit/
for loading images use http://square.github.io/picasso/ or glide. These libraries will help you make you code cleaner whit out boilerplate stuff.

Body:
In this class I am sending request to server asynchronously by extending AsyncTask using HttpClient, I have created two custom classes one for Uploading and Downloading of Images from the server, and other for sending JSON Object and array. Beside this I'm also able to differentiate the requests using RequestTag

Can we also do the same using volley?

How can I upgrade to Volley from the HttpClient having same approach like in below class?

package com.creative.projectmanager;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import org.apache.commons.logging.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
 * server manager class. performs all server requests asynchronously
 */
public class ServerManager {

    final private String SERVER_ADDRESS = "http://192.168.200.10/";

    public void login(String email, String password, int requestTag) {
        String url = SERVER_ADDRESS + "index.php?mobile/" + "login";
        HashMap<String, String> params = new HashMap<>();
        params.put("email", email);
        params.put("password", password);
        params.put("authenticate", "false");
        android.util.Log.w("My App", email + " " + password + " " + requestTag);
        AsyncHttpPost requestSender = new AsyncHttpPost(url, params, requestTag);
        requestSender.execute();
    }
    public void downloadImage(String imageUrl, int imageSize, int requestTag) {
        ImageDownloadTask imageDownloadTask = new ImageDownloadTask(imageUrl, imageSize, requestTag);
        imageDownloadTask.execute();
    }
    private class AsyncHttpPost extends AsyncTask<Void, Void, String> {
        private String url = "";
        private HashMap<String, String> postParams = null;
        private int requestTag;
        private String errorMessage = "";

        public AsyncHttpPost(String url, HashMap<String, String> params, int tag) {
            this.url = url;
            postParams = params;
            this.requestTag = tag;
        }

        @Override
        protected String doInBackground(Void... params) {
            byte[] result;
            String resultString = "";

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            try {
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
                for (String key:postParams.keySet()
                     ) {
                    nameValuePairs.add(new BasicNameValuePair(key, postParams.get(key)));
                }
                android.util.Log.w("My App",nameValuePairs.toString());
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
                HttpResponse response = httpClient.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();

                if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                    errorMessage = "ok";
                    result = EntityUtils.toByteArray(response.getEntity());
                    resultString = new String(result, "UTF-8");
                }
            }
            catch (UnsupportedEncodingException e) {
                errorMessage = "Encoding is not supported";
            }
            catch (Exception e) {
                errorMessage = "An error occurred";
            }
            return resultString;

        }

        @Override
        protected void onPostExecute(String s) {
            if (errorMessage.equals("ok")) {
                sourceActivity.requestFinished(s, requestTag);
            }
            else
                sourceActivity.requestFailed(errorMessage, requestTag);
        }
    }

    private class ImageDownloadTask extends AsyncTask<String, String, String> {
        private String imageUrl;
        private int imageSize;
        private int requestTag;
        Bitmap image;
        public ImageDownloadTask(String imageUrl, int imageSize, int requestTag) {
            this.imageUrl = imageUrl;
            this.imageSize = imageSize;
            this.requestTag = requestTag;
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(imageUrl);
                InputStream inputStream = new BufferedInputStream(url.openStream());
                image = createScaledBitmapFromStream(inputStream, imageSize);
            }
            catch (Exception e){
                //do nothing
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            sourceActivity.imageDownloaded(image, requestTag);
        }
        protected Bitmap createScaledBitmapFromStream(InputStream inputStream, int minimumDesiredBitmapSize) {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 32*1024);
            try {
                BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
                if (minimumDesiredBitmapSize > 0) {
                    BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
                    decodeBoundsOptions.inJustDecodeBounds = true;
                    bufferedInputStream.mark(32 * 1024);
                    BitmapFactory.decodeStream(bufferedInputStream, null, decodeBoundsOptions);
                    bufferedInputStream.reset();
                    int originalWidth = decodeBoundsOptions.outWidth;
                    int originalHeight = decodeBoundsOptions.outHeight;
                    decodeBitmapOptions.inSampleSize = Math.max(1, Math.min(originalWidth/minimumDesiredBitmapSize, originalHeight/minimumDesiredBitmapSize));
                }
                return BitmapFactory.decodeStream(bufferedInputStream, null, decodeBitmapOptions);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    bufferedInputStream.close();
                } catch (IOException ignored) {}
            }
        }
    }
}


来源: stackexchange

问:
Error 404 on delete row codeigniter 2
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

```<code> class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}
</code>```

Post Model

```<code> class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}
</code>```

In the View.php

```<code><?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">
</code>```

Routes.php

```<code>$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

答:
Solved by doing this on the controller and Route

Controller

```<code>class Posts extends CI_Controller{
 ...
  public function delete(){
    $id = $this->uri->segment(3);
       $this->Post_model->delete_post($id);
          redirect('posts');
    }
 }
</code>```

Route.php

```<code>$route['posts/delete/(:num)'] = 'posts/delete/$1'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Error 404 on delete row codeigniter 2

Body:
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

 class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}

Post Model

 class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}

In the View.php

<?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">

Routes.php

$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

Body:
Solved by doing this on the controller and Route

Controller

class Posts extends CI_Controller{
 ...
  public function delete(){
    $id = $this->uri->segment(3);
       $this->Post_model->delete_post($id);
          redirect('posts');
    }
 }

Route.php

$route['posts/delete/(:num)'] = 'posts/delete/$1'


问:
Android getting stuck while building gradle project
While running a project android getting stuck at _debug UnitTest apk.
(https://i.stack.imgur.com/ww3cq.jpg)</p>

答:
Please Check Your System Configuration and Minimum system Requirement For android studio.
If Your System Is Proper For Android studio.
Then YOu Check Your SDK location .
and  Go To File menu on Android studio they have a option invalidate cache and restart and press this option . when You invalidate cache and restart then Your Problem is Solved</p>


问:
Eclipse - how to add a file that has right to left strings
I am writing a Java app using Eclipse. This app read a set of Hebrew strings (that are right-to-left). Assuming I put these strings is a separate file, how do I tell the Eclipse editor that they are right-to-left text.

I tried eclipse -dir rtl but that puts all of Eclipse in RTL mode which is not the behavior I looking for.

答:
One alternative is to carefully use StringBuilder.reverse() to manipulate the strings as needed after they are read in.

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html#reverse%28%29

You could also write some simple string manipulation methods as helpers to handle whatever special needs you have.

This page, found in a quick google search, seems to have some interesting info on how Java handles and renders Hebrew: http://mindprod.com/jgloss/hebrew.html

ContentLicense: CC BY-SA 2.5


问:
JaVers not detecting changes to object attributes inside a collection
I would like to use JaVers to track changes of my Java objects. The basic examples are working fine, but I can't get it to detect changes on objects stored in a collection.

If I extend the ChangeLogExample.class example to change e.g. one of the sub-ordinates:

```<code>public static void main(String[] args) {

    Javers javers = JaversBuilder.javers().build();
    Employee bob = new Employee("Bob", 9_000, "Scrum master" );
    javers.commit("hr.manager", bob);

    // do some changes and commit
    bob.setPosition("Team Lead");
    bob.setSalary(11_000);
    javers.commit("hr.director", bob);

    bob.addSubordinates(new Employee("Trainee One"), new Employee("Trainee Two"));
    javers.commit("hr.manager", bob);

    bob.getSubordinates().get(0).setAge(42); // <<<< This is the change I want to detect
    javers.commit("hr.manager", bob);

    // when:
    List<Change> changes = javers.findChanges(
        QueryBuilder.byInstanceId("Bob", Employee.class).withChildValueObjects().build());
    String changeLog = javers.processChangeList(changes, new SimpleTextChangeLog());

    // then:
    System.out.println(changeLog);
}
</code>```

This is the changelog that is printed:

```<code>commit 3.0, author: hr.manager, 2017-06-06 11:17:17
  changed object: Employee/Bob
    list changed on 'subordinates' property: [(0).added:'Employee/Trainee One', (1).added:'Employee/Trainee Two']
commit 2.0, author: hr.director, 2017-06-06 11:17:17
  changed object: Employee/Bob
    value changed on 'position' property: 'Scrum master' -> 'Team Lead'
    value changed on 'salary' property: '9000' -> '11000'
</code>```

So the change to the age of the first subordinate doesn't show up in the changelog.

Using withChildValueObjects() does not make a difference.

I get the change to the trainee's age when I commit the change to the Employee instance separately, but that is not want I expected (nor what I want).

So my question is: how to get the change to the age show up in the ChangeLog?

I am using JaVers 3.2.0

The Employee class is unchanged from the JaVers examples: https://github.com/javers/javers/tree/master/javers-core/src/test/java/org/javers/core/examples/model

The main() method is simply the Test from https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/ChangeLogExample.java

答:
Ok, a few issues here.
First of all, Empolyee objects are mapped as Entities. So in JaVers, there is no
parent/child relationship between them (in fact any kind of relationship).
That's why withChildValueObjects() filter doesn't apply here.
It works only for ValueObjects owned by Entities, see http://javers.org/documentation/jql-examples/#child-value-objects-filter

Still, there are two ways to improve your query.

Ask directly for the Entity instance you want to trace.

Use the new Shadow API with Query Scopes, see http://javers.org/documentation/jql-examples/#query-for-shadows
It's a new feature and will be improved in the feature.
You can use it already if snapshots of both Entities will be selected by the query.

See code below:

```<code>def "should ... "(){
  given:
  Javers javers = JaversBuilder.javers().build()
  Employee bob = new Employee("Bob", 9_000, "Scrum master" )
  javers.commit("hr.manager", bob)

  // do some changes and commit
  bob.setPosition("Team Lead")
  bob.setSalary(11_000)
  javers.commit("hr.director", bob)

  bob.addSubordinates(new Employee("Trainee One"), new Employee("Trainee Two"))
  javers.commit("hr.manager", bob)

  bob.getSubordinates().get(0).setAge(42) // <<<< This is the change I want to detect
  bob.salary++ // !
  javers.commit("hr.manager", bob)

  when: "ask for the the right Entity instance"
  List changes = javers.findChanges(
          QueryBuilder.byInstanceId("Trainee One", Employee.class).build())

  then:
  println( javers.processChangeList(changes, new SimpleTextChangeLog()) )
  true

  when: "use the new Shadows"
  List shadows = javers.findShadows(
          QueryBuilder.byInstanceId("Bob", Employee.class)
                      .withShadowScopeDeep().build())

  then:
  shadows.each {
      assert it.get() instanceof Employee
  }
  Employee lastBobShadow = shadows[0].get()
  assert shadows[0].commitMetadata.id.majorId == 4
  assert lastBobShadow.subordinates[0].name == "Trainee One"
  assert lastBobShadow.subordinates[0].age == 42
}
</code>```

Body:
I would like to use JaVers to track changes of my Java objects. The basic examples are working fine, but I can't get it to detect changes on objects stored in a collection.

If I extend the ChangeLogExample.class example to change e.g. one of the sub-ordinates:

public static void main(String[] args) {

    Javers javers = JaversBuilder.javers().build();
    Employee bob = new Employee("Bob", 9_000, "Scrum master" );
    javers.commit("hr.manager", bob);

    // do some changes and commit
    bob.setPosition("Team Lead");
    bob.setSalary(11_000);
    javers.commit("hr.director", bob);

    bob.addSubordinates(new Employee("Trainee One"), new Employee("Trainee Two"));
    javers.commit("hr.manager", bob);

    bob.getSubordinates().get(0).setAge(42); // <<<< This is the change I want to detect
    javers.commit("hr.manager", bob);

    // when:
    List<Change> changes = javers.findChanges(
        QueryBuilder.byInstanceId("Bob", Employee.class).withChildValueObjects().build());
    String changeLog = javers.processChangeList(changes, new SimpleTextChangeLog());

    // then:
    System.out.println(changeLog);
}

This is the changelog that is printed:

commit 3.0, author: hr.manager, 2017-06-06 11:17:17
  changed object: Employee/Bob
    list changed on 'subordinates' property: [(0).added:'Employee/Trainee One', (1).added:'Employee/Trainee Two']
commit 2.0, author: hr.director, 2017-06-06 11:17:17
  changed object: Employee/Bob
    value changed on 'position' property: 'Scrum master' -> 'Team Lead'
    value changed on 'salary' property: '9000' -> '11000'

So the change to the age of the first subordinate doesn't show up in the changelog.

Using withChildValueObjects() does not make a difference.

I get the change to the trainee's age when I commit the change to the Employee instance separately, but that is not want I expected (nor what I want).

So my question is: how to get the change to the age show up in the ChangeLog?

I am using JaVers 3.2.0

The Employee class is unchanged from the JaVers examples: https://github.com/javers/javers/tree/master/javers-core/src/test/java/org/javers/core/examples/model

The main() method is simply the Test from https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/ChangeLogExample.java

Body:
Ok, a few issues here.
First of all, Empolyee objects are mapped as Entities. So in JaVers, there is no
parent/child relationship between them (in fact any kind of relationship).
That's why withChildValueObjects() filter doesn't apply here.
It works only for ValueObjects owned by Entities, see http://javers.org/documentation/jql-examples/#child-value-objects-filter

Still, there are two ways to improve your query.

Ask directly for the Entity instance you want to trace.

Use the new Shadow API with Query Scopes, see http://javers.org/documentation/jql-examples/#query-for-shadows
It's a new feature and will be improved in the feature.
You can use it already if snapshots of both Entities will be selected by the query.

See code below:

def "should ... "(){
  given:
  Javers javers = JaversBuilder.javers().build()
  Employee bob = new Employee("Bob", 9_000, "Scrum master" )
  javers.commit("hr.manager", bob)

  // do some changes and commit
  bob.setPosition("Team Lead")
  bob.setSalary(11_000)
  javers.commit("hr.director", bob)

  bob.addSubordinates(new Employee("Trainee One"), new Employee("Trainee Two"))
  javers.commit("hr.manager", bob)

  bob.getSubordinates().get(0).setAge(42) // <<<< This is the change I want to detect
  bob.salary++ // !
  javers.commit("hr.manager", bob)

  when: "ask for the the right Entity instance"
  List changes = javers.findChanges(
          QueryBuilder.byInstanceId("Trainee One", Employee.class).build())

  then:
  println( javers.processChangeList(changes, new SimpleTextChangeLog()) )
  true

  when: "use the new Shadows"
  List shadows = javers.findShadows(
          QueryBuilder.byInstanceId("Bob", Employee.class)
                      .withShadowScopeDeep().build())

  then:
  shadows.each {
      assert it.get() instanceof Employee
  }
  Employee lastBobShadow = shadows[0].get()
  assert shadows[0].commitMetadata.id.majorId == 4
  assert lastBobShadow.subordinates[0].name == "Trainee One"
  assert lastBobShadow.subordinates[0].age == 42
}


问:
Delete unused records from oracle table
DB version : 11.2.0.4
OS Solaris 5.10

REQUIREMENT : Delete unused records from table only after finding if the record is being accessed or not.

We have a table employee, which has 100,000 records, if anyone select a particular record/records from employee table then, the respective record's STATUS column should get updated to 'ACTIVE' value.

This is required for auditing purpose, 60 days later we will delete all the records from employee table whose STATUS column value is is NULL. how can this be achieved?

My understanding so far, correct me if I am wrong:

1) Trigger can't be used as there is no SELECT event, we only have UPDATE, INSERT, DELETE event.
2) Oracle FGA (Fine grain auditing) may not solve the purpose. or may be I am not aware, is it doable with FGA?

Table:

```<code>CREATE TABLE EMPLOYEE
(
  EMPID   NUMBER,
  NAME    VARCHAR2(20 BYTE),
  SALARY  NUMBER,
  DEPART  VARCHAR2(100 BYTE),
  STATUS  VARCHAR2(100 BYTE)
)
</code>```

sample records:

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH
</code>```

Example:

If any one issue below statements

query 1: SELECT * from EMPLOYEE where name='MESSI';

the auditing should update the STATUS='ACTIVE' of empid=105

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH
</code>```

query 2: SELECT * from EMPLOYEE where DEPART='TECH';

The auditing should update the STATUS='ACTIVE' for empid=105,106,107,108

```<code>     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH                 'ACTIVE'
       107 TERI                  5000 TECH                 'ACTIVE'
       108 ROBERT                5000 TECH                 'ACTIVE'
</code>```

答:
Sounds like an ambiguous requirement to me.  What happens if one does select * or select count(*)?  That under the specification would make all employee records used.
The view v$SQL would contain "all" SQL statements issued, you could always look in there (going through v$plan_table with the object).  Then use those to reverse engineer if the record was touched.</p>

Title: Delete unused records from oracle table

Body:
DB version : 11.2.0.4
OS Solaris 5.10

REQUIREMENT : Delete unused records from table only after finding if the record is being accessed or not.

We have a table employee, which has 100,000 records, if anyone select a particular record/records from employee table then, the respective record's STATUS column should get updated to 'ACTIVE' value.

This is required for auditing purpose, 60 days later we will delete all the records from employee table whose STATUS column value is is NULL. how can this be achieved?

My understanding so far, correct me if I am wrong:

1) Trigger can't be used as there is no SELECT event, we only have UPDATE, INSERT, DELETE event.
2) Oracle FGA (Fine grain auditing) may not solve the purpose. or may be I am not aware, is it doable with FGA?

Table:

CREATE TABLE EMPLOYEE
(
  EMPID   NUMBER,
  NAME    VARCHAR2(20 BYTE),
  SALARY  NUMBER,
  DEPART  VARCHAR2(100 BYTE),
  STATUS  VARCHAR2(100 BYTE)
)

sample records:

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH

Example:

If any one issue below statements

query 1: SELECT * from EMPLOYEE where name='MESSI';

the auditing should update the STATUS='ACTIVE' of empid=105

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH
       107 TERI                  5000 TECH
       108 ROBERT                5000 TECH

query 2: SELECT * from EMPLOYEE where DEPART='TECH';

The auditing should update the STATUS='ACTIVE' for empid=105,106,107,108

     EMPID NAME                SALARY DEPART               STATUS
---------- --------------- ---------- -------------------- ----------
       101 ALFA                  1000 IT
       102 BETA                  2000 CLERK
       103 PETER                 3000 FINANCE
       104 JOHN                  4000 IT
       105 MESSI                 5000 TECH                 'ACTIVE'
       106 ROMEO                 5000 TECH                 'ACTIVE'
       107 TERI                  5000 TECH                 'ACTIVE'
       108 ROBERT                5000 TECH                 'ACTIVE'


问:
Java UnMarshall XML gives null objects

UnMarshalling XML gives null java objects.

XML :

```<code><?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item Name="John"/>
<Item Name="Jason"/>
</Items>
</code>```

Items class :

```<code>@XmlRootElement(name = "Items")
@XmlAccessorType(XmlAccessType.FIELD)
public class Items{

    @XmlElement
    private List<Item> item;

    public List<Item> getItem() {
    return this.Item;
}

}
</code>```

Item class :

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Item")
public class Item{

    @XmlAttribute
    private String name;

   public String getName() {
    return this.Name;
   }

}
</code>```

Java Code that UnMarshalls : Here result.getBody gives XML String

```<code>ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

        JAXBContext jaxbContext = JAXBContext.newInstance(Items.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        Items itResult =  (Items) jaxbUnmarshaller.unmarshal(new StringReader(result.getBody()));
</code>```

Item object always comes null. How to unmarshall the xml correctly ?
Thanks in Advance. :

答:
Item Class:

```<code>public class Item {
    private String Name;
}
</code>```

Items Class:

```<code>@XmlRootElement(name = "Items")
@XmlAccessorType(XmlAccessType.FIELD)
public class Items {

    @XmlElement(name = "Item")
    private List<Item> items;
}
</code>```

Unmarshall class:

```<code>        JAXBContext jaxbContext;
        Unmarshaller jaxbUnmarshaller;
        try {
            jaxbContext = JAXBContext.newInstance(Items.class);
            jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Items itResult = (Items) jaxbUnmarshaller.unmarshal(file);
            System.out.println(itResult);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

Title: Java UnMarshall XML gives null objects

Body:
UnMarshalling XML gives null java objects.

XML :

<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item Name="John"/>
<Item Name="Jason"/>
</Items>

Items class :

@XmlRootElement(name = "Items")
@XmlAccessorType(XmlAccessType.FIELD)
public class Items{

    @XmlElement
    private List<Item> item;

    public List<Item> getItem() {
    return this.Item;
}

}

Item class :

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Item")
public class Item{

    @XmlAttribute
    private String name;

   public String getName() {
    return this.Name;
   }

}

Java Code that UnMarshalls : Here result.getBody gives XML String

ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

        JAXBContext jaxbContext = JAXBContext.newInstance(Items.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        Items itResult =  (Items) jaxbUnmarshaller.unmarshal(new StringReader(result.getBody()));

Item object always comes null. How to unmarshall the xml correctly ?
Thanks in Advance. :

Body:
Item Class:

public class Item {
    private String Name;
}

Items Class:

@XmlRootElement(name = "Items")
@XmlAccessorType(XmlAccessType.FIELD)
public class Items {

    @XmlElement(name = "Item")
    private List<Item> items;
}

Unmarshall class:

        JAXBContext jaxbContext;
        Unmarshaller jaxbUnmarshaller;
        try {
            jaxbContext = JAXBContext.newInstance(Items.class);
            jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Items itResult = (Items) jaxbUnmarshaller.unmarshal(file);
            System.out.println(itResult);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


问:
In Verilog and VHDL, what exactly is the difference between `logic[19:4]` and `logic[15:0]`?
and of course the equivalent syntax in VHDL?

Is the lower index a minimum bound for indexing? What happens in assignments between signals with differing bounds but the same width?

答:
Assuming you meant the widths to be the same...

...so, in Verilog let's assume you meant

```<code>logic [19:4] v19_4;
logic [15:0] v15_0;
</code>```

In a Verilog simulation, you will not experience any difference unless to try to index the bits.

If you index the bits, you will find that

in the first case, the left hand bit is bit 19 (ie v19_4[19]), whereas in the second case, the left hand bit is bit 15 (ie v15_0[15]);

in the first case, the right hand bit is bit 4 (ie v19_4[4]), whereas in the second case, the right hand bit is bit 0 (ie v15_0[0]).

In Verilog, it is valid to call the left hand bit "the MSB" and the right hand bit "the LSB".

You will experience exactly the same behaviour in VHDL.  In VHDL let's assume you meant

```<code>signal v19_4 : std_logic_vector(19 downto 4);
signal v15_0 : std_logic_vector(15 downto 0);
</code>```

Again, in a VHDL simulation, you will not experience any difference unless to try to index the bits. If you index the bits, you will find that

in the first case, the left hand bit is bit 19 (ie v19_4(19)), whereas in the second case, the left hand bit is bit 15 (ie v15_0(15));

in the first case, the right hand bit is bit 4 (ie v19_4(4)), whereas in the second case, the right hand bit is bit 0 (ie v15_0(0)).

With synthesis you might see a difference. It is generally recommended to index vectors from 0 for synthesis to remove the possibility of synthesising more bits than you need. However, I would think that most synthesisers would optimise away the excess logic.

Body:
Assuming you meant the widths to be the same...

...so, in Verilog let's assume you meant

logic [19:4] v19_4;
logic [15:0] v15_0;

In a Verilog simulation, you will not experience any difference unless to try to index the bits.

If you index the bits, you will find that

in the first case, the left hand bit is bit 19 (ie v19_4[19]), whereas in the second case, the left hand bit is bit 15 (ie v15_0[15]);

in the first case, the right hand bit is bit 4 (ie v19_4[4]), whereas in the second case, the right hand bit is bit 0 (ie v15_0[0]).

In Verilog, it is valid to call the left hand bit "the MSB" and the right hand bit "the LSB".

You will experience exactly the same behaviour in VHDL.  In VHDL let's assume you meant

signal v19_4 : std_logic_vector(19 downto 4);
signal v15_0 : std_logic_vector(15 downto 0);

Again, in a VHDL simulation, you will not experience any difference unless to try to index the bits. If you index the bits, you will find that

in the first case, the left hand bit is bit 19 (ie v19_4(19)), whereas in the second case, the left hand bit is bit 15 (ie v15_0(15));

in the first case, the right hand bit is bit 4 (ie v19_4(4)), whereas in the second case, the right hand bit is bit 0 (ie v15_0(0)).

With synthesis you might see a difference. It is generally recommended to index vectors from 0 for synthesis to remove the possibility of synthesising more bits than you need. However, I would think that most synthesisers would optimise away the excess logic.


问:
Remove quotes from a list of strings (that are supposed to be tuples)
I am pulling out a row from a file. Row looks like this:

```<code>['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']
</code>```

Is there a way to convert those strings into tuples? I tried x.strip() for x in row but it didn`t help.

Thanks in advance.

Body:
I am pulling out a row from a file. Row looks like this:

['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']

Is there a way to convert those strings into tuples? I tried x.strip() for x in row but it didn`t help.

Thanks in advance.

Body:
Would this work for you ?

import ast

string = "['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']"
string = string.replace("'", "")
string = ast.literal_eval(string)

The output is :

In : string
Out:
[(27.0, 168.0),
 (32.0, 550.0),
 (88.0, 835.0),
 (46.0, 660.0),
 (38.0, 430.0),
 (34.0, 285.0),
 (72.0, 701.0),
 (29.0, 434.0),
 (0, 2)]

In : type(string)
Out: list

In : [type(x) for x in string]
Out: [tuple, tuple, tuple, tuple, tuple, tuple, tuple, tuple, tuple]

The ast module evaluates strings which I think is what you're looking for if I understand correctly.


问:
tsql - How to copy data in the same table with new ID and with foreign key relationship
I have 3 tables, All 3 tables have Auto-Increment primary key column with foreign key relationship.

My problem is that I want to copy the related data in same table.

And also to maintain the PK-->FK relationship.

For example I want to copy GoalID = 1.
I have also created variable tables and data as my scenario.

```<code>Declare @tblCompanyGoal Table
(
GoalID int identity(1,1), --PKID
APID int,
Goal nvarchar(500)
)

Declare @tblPMCompanyObjectives Table
(
ObjectID int identity(1,1), --PKID
ApID int,
Objective   nvarchar(500),
GoalID int --FK --> @tblCompanyGoal.GoalID
)

Declare @tblPMCompanyStrategies Table
(
StrgID int identity(1,1), --PKID
Strategies nvarchar(500),
ObjectID int --FK --> @@tblPMCompanyObjectives.ObjectID
)

Insert into @tblCompanyGoal (APID, Goal)Values(500, 'C-Goal1')
Insert into @tblCompanyGoal (APID, Goal)Values(600, 'C-Goal2')

insert into @tblPMCompanyObjectives (ApID, Objective, GoalID)values(500, 'BF', 1)
insert into @tblPMCompanyObjectives (ApID, Objective, GoalID)values(500, 'LF', 1)
insert into @tblPMCompanyObjectives (ApID, Objective, GoalID)values(500, 'BFA', 2)

Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('GTK', 1)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('GTK2', 1)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('ASK', 1)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('WER', 2)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('NFT', 2)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('KRG', 3)
</code>```

How can I accomplish this task? I have tried it with cursor but not succeeded.

答:
After the insert into @tblCompanyGoal Table, use the SCOPE_IDENTITY value. It will automatically contain the new identity ID (for the newly inserted row) from the last insert statement. (You could also make a join like in the last insert, if you prefer without a variable.)

Then use this value in the following insert, as the new foreign key value.

The last join is a little bit tricky, you have to map the old ids with the new ones. I added some comments to help explain the logic.

This will give you a copy of the related data.

```<code>  DECLARE @NewGoalID INT, @OldGoalID INT

  SET @OldGoalID = 1

  INSERT INTO @tblCompanyGoal(APID, Goal)
  SELECT APID, Goal FROM @tblCompanyGoal WHERE GoalID=1

  SET @NewGoalID = SCOPE_IDENTITY()

  INSERT INTO @tblPMCompanyObjectives(ApID, Objective, GoalID)
  SELECT ApID, Objective, @NewGoalID FROM @tblPMCompanyObjectives WHERE GoalID = @OldGoalID

  INSERT INTO @tblPMCompanyStrategies(Strategies, ObjectID)
  SELECT s.Strategies, no.ObjectID
  -- get the old object rows
  FROM @tblPMCompanyStrategies s
  INNER JOIN @tblPMCompanyObjectives oo ON oo.objectid = s.objectid
  INNER JOIN @tblCompanyGoal oc ON oc.GoalID = oo.GoalID AND oc.GoalID = @OldGoalID
  -- get the matching rows new object IDs
  INNER JOIN @tblPMCompanyObjectives no ON no.GoalID = @NewGoalID AND no.ApID=oo.ApID AND no.Objective=oo.Objective
</code>```

Body:
I have 3 tables, All 3 tables have Auto-Increment primary key column with foreign key relationship.

My problem is that I want to copy the related data in same table.

And also to maintain the PK-->FK relationship.

For example I want to copy GoalID = 1.
I have also created variable tables and data as my scenario.

Declare @tblCompanyGoal Table
(
GoalID int identity(1,1), --PKID
APID int,
Goal nvarchar(500)
)

Declare @tblPMCompanyObjectives Table
(
ObjectID int identity(1,1), --PKID
ApID int,
Objective   nvarchar(500),
GoalID int --FK --> @tblCompanyGoal.GoalID
)

Declare @tblPMCompanyStrategies Table
(
StrgID int identity(1,1), --PKID
Strategies nvarchar(500),
ObjectID int --FK --> @@tblPMCompanyObjectives.ObjectID
)

Insert into @tblCompanyGoal (APID, Goal)Values(500, 'C-Goal1')
Insert into @tblCompanyGoal (APID, Goal)Values(600, 'C-Goal2')

insert into @tblPMCompanyObjectives (ApID, Objective, GoalID)values(500, 'BF', 1)
insert into @tblPMCompanyObjectives (ApID, Objective, GoalID)values(500, 'LF', 1)
insert into @tblPMCompanyObjectives (ApID, Objective, GoalID)values(500, 'BFA', 2)

Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('GTK', 1)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('GTK2', 1)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('ASK', 1)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('WER', 2)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('NFT', 2)
Insert into @tblPMCompanyStrategies(Strategies, ObjectID)Values('KRG', 3)

How can I accomplish this task? I have tried it with cursor but not succeeded.

Body:
After the insert into @tblCompanyGoal Table, use the SCOPE_IDENTITY value. It will automatically contain the new identity ID (for the newly inserted row) from the last insert statement. (You could also make a join like in the last insert, if you prefer without a variable.)

Then use this value in the following insert, as the new foreign key value.

The last join is a little bit tricky, you have to map the old ids with the new ones. I added some comments to help explain the logic.

This will give you a copy of the related data.

  DECLARE @NewGoalID INT, @OldGoalID INT

  SET @OldGoalID = 1

  INSERT INTO @tblCompanyGoal(APID, Goal)
  SELECT APID, Goal FROM @tblCompanyGoal WHERE GoalID=1

  SET @NewGoalID = SCOPE_IDENTITY()

  INSERT INTO @tblPMCompanyObjectives(ApID, Objective, GoalID)
  SELECT ApID, Objective, @NewGoalID FROM @tblPMCompanyObjectives WHERE GoalID = @OldGoalID

  INSERT INTO @tblPMCompanyStrategies(Strategies, ObjectID)
  SELECT s.Strategies, no.ObjectID
  -- get the old object rows
  FROM @tblPMCompanyStrategies s
  INNER JOIN @tblPMCompanyObjectives oo ON oo.objectid = s.objectid
  INNER JOIN @tblCompanyGoal oc ON oc.GoalID = oo.GoalID AND oc.GoalID = @OldGoalID
  -- get the matching rows new object IDs
  INNER JOIN @tblPMCompanyObjectives no ON no.GoalID = @NewGoalID AND no.ApID=oo.ApID AND no.Objective=oo.Objective


问:
if statements to look at different worksheets and cells
I have a document with a large amount of data, and various formulas from countif to =if etc.  However, In one particular worksheet cell b2 gets information directly from another cell in another sheet using the simple (='sheet2'!b2) formula.  Now i want the cell underneath to read whats in b2, and dependant upon what it says (either Corrective Actions, Guidance or No Action) for it to look into a final sheet at a cell i want to determine, so if b2 says Corrective action, i want to look in sheet4!B4, if it says Guidance i want to look at sheet4!C4, and of it says No action, to look at Sheet4!D4  I have tried numerous times, but get the error #NAME?  please help</p>

答:
A simple nested if should do that:

```<code>=if(b2="Corrective Actions", Sheet4!B4, if(b2="Guidance", Sheet4!C4, if("No Action", Sheet4!D4, "")))
</code>```

As for your error on your current attempt. It's hard to diagnose without seeing what formula you are using, but #NAME errors mean that whatever formula (if, sum, countif, etc) you are attempting to use, doesn't exist.

Body:
A simple nested if should do that:

=if(b2="Corrective Actions", Sheet4!B4, if(b2="Guidance", Sheet4!C4, if("No Action", Sheet4!D4, "")))

As for your error on your current attempt. It's hard to diagnose without seeing what formula you are using, but #NAME errors mean that whatever formula (if, sum, countif, etc) you are attempting to use, doesn't exist.


问:
Unable to detect back press button click
I have viewpager with couple of fragments inside. I need to get confirmation when user presses back button. However, it doesn't get called unless I visit last page.

```<code>public class Create_Safety_CheckList_MainFragment extends Fragment
        implements View.OnClickListener, Observer {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_create_safety_checklist_pager_main, container, false);
        initializeUI();

        return view;
    }

    private void initializeUI() {
        setHeader(getResources().getString(R.string.safety_check_list_checklist_screen_name));
        addFragments();
        mPager = (ViewPager) view.findViewById(R.id.viewPager_home_screen_activity);
        mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
        mPager.setOffscreenPageLimit(fragmentArrayList.size());
        mPager.setOnPageChangeListener(onPageChangeListener);
        mPager.setAdapter(mPagerAdapter);
//        mPager.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
//                return false;
//            }
//        });

        customTextViewChecklistName = (CustomTextView) view.findViewById(R.id.textView_New_Checklist_Name);
        if (createChecklistObservationModel.getChecklistName() != null)
            customTextViewChecklistName.setText(createChecklistObservationModel.getChecklistName());

    }

    private void addFragments() {
        createChecklistAdditionalTabFragment = new CreateChecklistAdditionalTabFragment();
        fragmentArrayList.add(createChecklistAdditionalTabFragment);

        Bundle bundle = getArguments();
        if (bundle != null) {
            if (bundle.containsKey("***")) {
                String response = spcl_databaseHandler.getSpecificChecklistAdditionals(bundle.getString("checklistID"));
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject dataJsonObject = jsonObject.getJSONObject("Data");

                    JSONArray checkListAdditionalFieldDtoJsonArray = dataJsonObject.getJSONArray("***");
                    int additionalsLength = checkListAdditionalFieldDtoJsonArray.length();
                    if (additionalsLength > 0) {
dataJsonObject.getJSONArray("***").toString());
                        additionalInfoFragment = new Additional_Information_Fragment();
                        fragmentArrayList.add(additionalInfoFragment);
                    }

                    JSONArray jsonGroupsArray = dataJsonObject.getJSONArray("***");
                    int groupsLength = jsonGroupsArray.length();
                    for (int i = 0; i < groupsLength; i++) {
                        JSONObject groupJsonObject = (JSONObject) jsonGroupsArray.get(i);
                        JSONArray questionsJsonArray = groupJsonObject.getJSONArray("Questions");
                        int questionsLength = questionsJsonArray.length();
                        for (int j = 0; j < questionsLength; j++) {
                            checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();
                            checklistGroupsDiscussionQuestionOneFragment.setArguments(bundle1);
                            fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                        }

                        JSONArray subGroupsJsonArray = groupJsonObject.getJSONArray("SubGroups");
                        int subGroupsJsonArrayLength = subGroupsJsonArray.length();
                        for (int j = 0; j < subGroupsJsonArrayLength; j++) {
                            JSONObject subGroupObject = subGroupsJsonArray.getJSONObject(j);
                            JSONArray subGroupQuestionsJsonArray = subGroupObject.getJSONArray("Questions");
                            int subGroupQuestionsJsonArrayLength = subGroupQuestionsJsonArray.length();
                            for (int k = 0; k < subGroupQuestionsJsonArrayLength; k++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();                                fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        questionsFragment = new Other_Questions_Fragment();
        membersFragment = new Inspection_Members_Fragment();

        fragmentArrayList.add(questionsFragment);
        fragmentArrayList.add(membersFragment);
    }

    private void setHeader(String headerTitle) {
    }

    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int pageNumber) {
        }

        @Override
        public void onPageScrolled(int pageNumber, float positionOffset,
                                   int positionOffsetPixels) {
//            mPager.getParent().requestDisallowInterceptTouchEvent(true);
            showArrows(pageNumber);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_Next:
                break;

            case R.id.imageView_Previous:
                break;

            case R.id.textView_Cancel :
                callToCloseDialog();
                break;

            default:
                break;
        }
    }

    private void callToCloseDialog() {
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.cancel_dialog_message))
                .setTitle("Warning");

        builder.setPositiveButton(getResources().getString(R.string.cancel_dialog_yes_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                getActivity().getSupportFragmentManager().popBackStackImmediate(getResources().getString(R.string.new_checklist_fragment), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        });

        builder.setNegativeButton(getResources().getString(R.string.cancel_dialog_no_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked cancel button
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void update(Observable observable, Object o) {
    }

    /**
     * A simple pager adapter that represents 3 objects, in sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentArrayList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentArrayList.size();
        }
    }

    private void showArrows(int pageNumber) {
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                callToCloseDialog();
                return true;
            }
        });
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Subscribe
    public void onEvent(QuestionResponsesModel questionResponsesModel){
    }

}
</code>```

Kept only code for Viewpager & fragments loading.

答:
By Default Fragment Don't have any back Pressed event, so you have to manage it by Activity onBackPressed() method using below code.

Override onBackPressed() method in your Activity and Apply Check for it.

```<code> @Override
    public void onBackPressed() {
      // put condition here
        if("Your Fragment is Visible"){
           //Apply confirmation check here
        }
        else{
            super.onBackPressed();
        }

    }
</code>```

Body:
I have viewpager with couple of fragments inside. I need to get confirmation when user presses back button. However, it doesn't get called unless I visit last page.

public class Create_Safety_CheckList_MainFragment extends Fragment
        implements View.OnClickListener, Observer {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_create_safety_checklist_pager_main, container, false);
        initializeUI();

        return view;
    }

    private void initializeUI() {
        setHeader(getResources().getString(R.string.safety_check_list_checklist_screen_name));
        addFragments();
        mPager = (ViewPager) view.findViewById(R.id.viewPager_home_screen_activity);
        mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
        mPager.setOffscreenPageLimit(fragmentArrayList.size());
        mPager.setOnPageChangeListener(onPageChangeListener);
        mPager.setAdapter(mPagerAdapter);
//        mPager.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
//                return false;
//            }
//        });

        customTextViewChecklistName = (CustomTextView) view.findViewById(R.id.textView_New_Checklist_Name);
        if (createChecklistObservationModel.getChecklistName() != null)
            customTextViewChecklistName.setText(createChecklistObservationModel.getChecklistName());

    }

    private void addFragments() {
        createChecklistAdditionalTabFragment = new CreateChecklistAdditionalTabFragment();
        fragmentArrayList.add(createChecklistAdditionalTabFragment);

        Bundle bundle = getArguments();
        if (bundle != null) {
            if (bundle.containsKey("***")) {
                String response = spcl_databaseHandler.getSpecificChecklistAdditionals(bundle.getString("checklistID"));
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject dataJsonObject = jsonObject.getJSONObject("Data");

                    JSONArray checkListAdditionalFieldDtoJsonArray = dataJsonObject.getJSONArray("***");
                    int additionalsLength = checkListAdditionalFieldDtoJsonArray.length();
                    if (additionalsLength > 0) {
dataJsonObject.getJSONArray("***").toString());
                        additionalInfoFragment = new Additional_Information_Fragment();
                        fragmentArrayList.add(additionalInfoFragment);
                    }

                    JSONArray jsonGroupsArray = dataJsonObject.getJSONArray("***");
                    int groupsLength = jsonGroupsArray.length();
                    for (int i = 0; i < groupsLength; i++) {
                        JSONObject groupJsonObject = (JSONObject) jsonGroupsArray.get(i);
                        JSONArray questionsJsonArray = groupJsonObject.getJSONArray("Questions");
                        int questionsLength = questionsJsonArray.length();
                        for (int j = 0; j < questionsLength; j++) {
                            checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();
                            checklistGroupsDiscussionQuestionOneFragment.setArguments(bundle1);
                            fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                        }

                        JSONArray subGroupsJsonArray = groupJsonObject.getJSONArray("SubGroups");
                        int subGroupsJsonArrayLength = subGroupsJsonArray.length();
                        for (int j = 0; j < subGroupsJsonArrayLength; j++) {
                            JSONObject subGroupObject = subGroupsJsonArray.getJSONObject(j);
                            JSONArray subGroupQuestionsJsonArray = subGroupObject.getJSONArray("Questions");
                            int subGroupQuestionsJsonArrayLength = subGroupQuestionsJsonArray.length();
                            for (int k = 0; k < subGroupQuestionsJsonArrayLength; k++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();                                fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        questionsFragment = new Other_Questions_Fragment();
        membersFragment = new Inspection_Members_Fragment();

        fragmentArrayList.add(questionsFragment);
        fragmentArrayList.add(membersFragment);
    }

    private void setHeader(String headerTitle) {
    }

    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int pageNumber) {
        }

        @Override
        public void onPageScrolled(int pageNumber, float positionOffset,
                                   int positionOffsetPixels) {
//            mPager.getParent().requestDisallowInterceptTouchEvent(true);
            showArrows(pageNumber);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_Next:
                break;

            case R.id.imageView_Previous:
                break;

            case R.id.textView_Cancel :
                callToCloseDialog();
                break;

            default:
                break;
        }
    }

    private void callToCloseDialog() {
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.cancel_dialog_message))
                .setTitle("Warning");

        builder.setPositiveButton(getResources().getString(R.string.cancel_dialog_yes_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                getActivity().getSupportFragmentManager().popBackStackImmediate(getResources().getString(R.string.new_checklist_fragment), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        });

        builder.setNegativeButton(getResources().getString(R.string.cancel_dialog_no_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked cancel button
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void update(Observable observable, Object o) {
    }

    /**
     * A simple pager adapter that represents 3 objects, in sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentArrayList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentArrayList.size();
        }
    }

    private void showArrows(int pageNumber) {
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                callToCloseDialog();
                return true;
            }
        });
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Subscribe
    public void onEvent(QuestionResponsesModel questionResponsesModel){
    }

}

Kept only code for Viewpager & fragments loading.

Body:
By Default Fragment Don't have any back Pressed event, so you have to manage it by Activity onBackPressed() method using below code.

Override onBackPressed() method in your Activity and Apply Check for it.

 @Override
    public void onBackPressed() {
      // put condition here
        if("Your Fragment is Visible"){
           //Apply confirmation check here
        }
        else{
            super.onBackPressed();
        }

    }


问:
Syntax error using => in IE
I have the following line of javascript code

```<code>var res = Object.keys(packages).filter(e => packages[e] === true)
</code>```

The above works well in all the other browser apart from IE. IE complains about Syntax erro at => can someone tell me how to get around this in IE

答:
IE must not support arrow-functions. Just use the old function keyword.

```<code>.filter(function(e){ return packages[e] === true })
</code>```

Side note, but you could also probably write this as:

```<code>.filter(function(e){ return packages[e] })
</code>```

Unless packages[e] must actually be exactly equal to true and not just truthy.

Title: Syntax error using => in IE

Body:
I have the following line of javascript code

var res = Object.keys(packages).filter(e => packages[e] === true)

The above works well in all the other browser apart from IE. IE complains about Syntax erro at => can someone tell me how to get around this in IE

Body:
IE must not support arrow-functions. Just use the old function keyword.

.filter(function(e){ return packages[e] === true })

Side note, but you could also probably write this as:

.filter(function(e){ return packages[e] })

Unless packages[e] must actually be exactly equal to true and not just truthy.


问:
Why does
 seem to be preferred over  for navigation bars?
According to what I've read so far,  seems to be better, but every single example I see on the Internet uses
.

Is it just me seeing things or do people really use
 ?

If so, is there a reason why ?

EDIT : just in case someone was wondering, of course I'm talking about navigation bars, and nav can't replace div in other cases...

Title: Why does <div> seem to be preferred over <nav> for navigation bars?

Body: <nav> is newer. Lots of people haven't caught up yet. (Or are stuck having to cater to versions of Internet Explorer that Microsoft no longer supports)


问:
How to Identify Tapped UIImage in UIImage array in Swift
I am populating UIImage array with code and adding them into UIScrollView successfully. I would like to identify the image tapped so I can run an action accordingly.

I appreciate your guidance and time.

Here is the code I have so far:

```<code>    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
    }

    func loadImagePicker(){

    var contentWidth: CGFloat = 0.0
    let imageWidth: CGFloat = 100.0
    let imageHeight: CGFloat = 100.0

    for x in 0...2 {
        let image = UIImage(named: "item\(x).png")
        let imageView = UIImageView(image: image)
        imageView.isUserInteractionEnabled = true
        myData.images1.append(imageView)

        var newX: CGFloat = 0.0

        newX = 10 + imageWidth * CGFloat(x) + (10 * CGFloat(x))

        contentWidth += newX

        scrollView.addSubview(imageView)

        imageView.frame = CGRect(x: newX, y: scrollView.frame.size.height, width: imageWidth, height: imageHeight)
        imageView.contentMode = .scaleToFill
    }

    print(myData.images1.count)

    scrollView.clipsToBounds = false
    scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.size.height)

    imagePickerView.isHidden = false
}
</code>```

答:
Add gesture recognizer to your imageView just like following:</p>

```<code>    //Instance Variable
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
    tapGestureRecognizer.numberOfTapsRequired = 1
    tapGestureRecognizer.numberOfTouchesRequired = 1

    func loadImagePicker(){

        // .....

        for 0..<2 { //Assuming there are two images

        // .....
        // .....

        imageView.addGestureRecognizer(tapGestureRecognizer)

        }
    }

    func imageTapped(_ sender: UITapGestureRecognizer) {

        let tappedImageView = sender.view as! UIImageView
        let index = tappedImageView.tag // Do anything with the index by using it in your array

    }
</code>```

Body:
I am populating UIImage array with code and adding them into UIScrollView successfully. I would like to identify the image tapped so I can run an action accordingly.

I appreciate your guidance and time.

Here is the code I have so far:

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
    }

    func loadImagePicker(){

    var contentWidth: CGFloat = 0.0
    let imageWidth: CGFloat = 100.0
    let imageHeight: CGFloat = 100.0

    for x in 0...2 {
        let image = UIImage(named: "item\(x).png")
        let imageView = UIImageView(image: image)
        imageView.isUserInteractionEnabled = true
        myData.images1.append(imageView)

        var newX: CGFloat = 0.0

        newX = 10 + imageWidth * CGFloat(x) + (10 * CGFloat(x))

        contentWidth += newX

        scrollView.addSubview(imageView)

        imageView.frame = CGRect(x: newX, y: scrollView.frame.size.height, width: imageWidth, height: imageHeight)
        imageView.contentMode = .scaleToFill
    }

    print(myData.images1.count)

    scrollView.clipsToBounds = false
    scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.size.height)

    imagePickerView.isHidden = false
}

Body:
Add gesture recognizer to your imageView just like following:

    //Instance Variable
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
    tapGestureRecognizer.numberOfTapsRequired = 1
    tapGestureRecognizer.numberOfTouchesRequired = 1

    func loadImagePicker(){

        // .....

        for 0..<2 { //Assuming there are two images

        // .....
        // .....

        imageView.addGestureRecognizer(tapGestureRecognizer)

        }
    }

    func imageTapped(_ sender: UITapGestureRecognizer) {

        let tappedImageView = sender.view as! UIImageView
        let index = tappedImageView.tag // Do anything with the index by using it in your array

    }


问:
Angular4 Material sidenav not working
I am trying to test out the sidenav functionality in angular4 material. From whatever information I could gather from google. I made this plunker.
https://plnkr.co/edit/4VfijY?p=preview

```<code><md-sidenav-container>
  <md-sidenav #sidenav mode="side" opened="true">
    <md-nav-list>
      <a md-list-item>
        Home
      </a>
      <a md-list-item>
        Channels
      </a>
    </md-nav-list>
  </md-sidenav>
</md-sidenav-container>
</code>```

Could someone point out what am I doing wrong ?. I could use another pair of eyes.

Also if someone has successfully made a working sidenav or has a good tutorial could you please share here ?

Thanks a lot.

答:
Structure of your code is wrong. For sidenav to work all your html code should be inside md-sidenav-container. sidenav.open() method is used to open side nav.

this is working plunkr https://plnkr.co/edit/3Oalufvj8ieRzhYPq7RP?p=preview

```<code><md-sidenav-container>
    <md-sidenav #sidenav>
        <md-nav-list>
            <a md-list-item>
        Home
      </a>
            <a md-list-item>
        Channels
      </a>
        </md-nav-list>
    </md-sidenav>

    <!--***** html part of page should be inside sidenav here *****-->
    <div style="height: 700px;">
        <md-toolbar color="primary">
            Angular Material 2 App
        </md-toolbar>
        <div style="text-align: center;">
            <button md-button (click)="sidenav.open()">Open sidenav</button>
            <p>
                <md-slide-toggle>Slide Toggle</md-slide-toggle>
            </p>
        </div>
    </div>

</md-sidenav-container>
</code>```

for more info read this https://material.angular.io/components/component/sidenav

i hope this will help :)

Title: Angular4 Material sidenav not working

Body:
I am trying to test out the sidenav functionality in angular4 material. From whatever information I could gather from google. I made this plunker.
https://plnkr.co/edit/4VfijY?p=preview

<md-sidenav-container>
  <md-sidenav #sidenav mode="side" opened="true">
    <md-nav-list>

        Home

        Channels

    </md-nav-list>
  </md-sidenav>
</md-sidenav-container>

Could someone point out what am I doing wrong ?. I could use another pair of eyes.

Also if someone has successfully made a working sidenav or has a good tutorial could you please share here ?

Thanks a lot.

Body:
Structure of your code is wrong. For sidenav to work all your html code should be inside md-sidenav-container. sidenav.open() method is used to open side nav.

this is working plunkr https://plnkr.co/edit/3Oalufvj8ieRzhYPq7RP?p=preview

<md-sidenav-container>
    <md-sidenav #sidenav>
        <md-nav-list>
            <a md-list-item>
        Home
      </a>
            <a md-list-item>
        Channels
      </a>
        </md-nav-list>
    </md-sidenav>

    <!--***** html part of page should be inside sidenav here *****-->
    <div style="height: 700px;">
        <md-toolbar color="primary">
            Angular Material 2 App
        </md-toolbar>
        <div style="text-align: center;">
            <button md-button (click)="sidenav.open()">Open sidenav</button>
            <p>
                <md-slide-toggle>Slide Toggle</md-slide-toggle>
            </p>
        </div>
    </div>

</md-sidenav-container>

for more info read this https://material.angular.io/components/component/sidenav

i hope this will help :)


问:
converting string representation of a date and time to the System.DateTime
```<code>DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);
</code>```

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?

答: If you know that the string is in DD/MM/YY format, then you can use TryParseExact.</p>

Body:
DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?


问:
Reshaping Pandas Data Frame by Index with Duplicate Indexes
I have a data frame similar to this:

```<code>questions = ['What color?', 'What day?', 'How cold?', 'What color?', 'What color?']
answers = ['red', 'tuesday', '45', 'blue', 'red']
ids = [0, 1, 2, 3, 0]
df = pd.DataFrame({'id': [0, 1, 2, 0, 0], 'questions': questions, 'answers': answers})

 >>> id questions    answers
      0  What color? red
      1  What day?   tuesday
      2  How cold?   45
      0 What color?  blue
      0 What color?  red
</code>```

I want this:

```<code>     How cold? What color?  What day?
id
0       None    red          None
2       None    None         tuesday
3       45      None         None
4       None    blue         None
0       None    red          None
</code>```

I have tried:

```<code>df.pivot(values='answers', index='id', columns='questions')
</code>```

However, pivot always results in an error due to duplicates in the index.

答:
You can achieve that using pivot method :

```<code>df.pivot(columns="questions",values="answers")
</code>```

output

```<code>    How cold?   What color? What day?
0   NaN          red         NaN
1   NaN          NaN     tuesday
2   45           NaN         NaN
3   NaN         blue         NaN
4   NaN         red          NaN
</code>```

EDIT if you want to keep the indexes you had, you can do :

```<code>new_df = df.pivot(columns="questions",values="answers")
new_df.index = df.index
</code>```

Body:
I have a data frame similar to this:

questions = ['What color?', 'What day?', 'How cold?', 'What color?', 'What color?']
answers = ['red', 'tuesday', '45', 'blue', 'red']
ids = [0, 1, 2, 3, 0]
df = pd.DataFrame({'id': [0, 1, 2, 0, 0], 'questions': questions, 'answers': answers})

 >>> id questions    answers
      0  What color? red
      1  What day?   tuesday
      2  How cold?   45
      0 What color?  blue
      0 What color?  red

I want this:

     How cold? What color?  What day?
id
0       None    red          None
2       None    None         tuesday
3       45      None         None
4       None    blue         None
0       None    red          None

I have tried:

df.pivot(values='answers', index='id', columns='questions')

However, pivot always results in an error due to duplicates in the index.

Body:
You can achieve that using pivot method :

df.pivot(columns="questions",values="answers")

output

    How cold?   What color? What day?
0   NaN          red         NaN
1   NaN          NaN     tuesday
2   45           NaN         NaN
3   NaN         blue         NaN
4   NaN         red          NaN

EDIT if you want to keep the indexes you had, you can do :

new_df = df.pivot(columns="questions",values="answers")
new_df.index = df.index


Title: Remove quotes from a list of strings (that are supposed to be tuples)

Body:
I am pulling out a row from a file. Row looks like this:

['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']

Is there a way to convert those strings into tuples? I tried x.strip() for x in row but it didn`t help.

Thanks in advance.

Body:
This should do the trick.

from ast import literal_eval as make_tuple
a = ['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']
b = [make_tuple(x.strip()) for x in a]


问:
Target checked checkbox in jQuery
I have HTML, CSS and jQuery code for a checkbox. But I was recently making some changes in the HTML structure and now the jQuery is no longer working. And since I'm a beginner, I don't know how to fix this.

Can someone take a look and just let me know what jQuery should be targeting instead, so it'll change the styling of the elements when the checkbox is checked?

$('.form-check').click(function(){
        $(this).closest('.list-group-item').find('.incomplete').css('display', (this.checked)?'none':'block')
        $(this).closest('.list-group-item').find('.complete').css('display', (this.checked)?'block':'none')
        $(this).closest('.list-group-item').css('background-color',(this.checked)?'#4CAF50':'')
        $(this).closest('.list-group-item').find('.custom-control-description').css('color', (this.checked)?'#fff':'#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', (this.checked)?'#fff':'#ababab')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}
.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}
.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}
@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}
@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}
input[type=checkbox] + svg {
  display: none;
}
input[type=checkbox]:checked + svg {
  display: block;
}
.form-check {
  position: relative;
}
.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}
.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      Checkbox

pending

done

```

答:
The problem is with your this.isChecked, it is always undefined, so it always evaluates to false. I replaced it with isChecked, getting the value from the checked property of the checkbox belonging to this li item.

$('.form-check').click(function(){
  var isChecked = $(this).find('#checkbox').prop('checked');
  $(this).closest('.list-group-item').find('.incomplete').css('display', isChecked?'none':'block')
  $(this).closest('.list-group-item').find('.complete').css('display', isChecked?'block':'none')
  $(this).closest('.list-group-item').css('background-color',isChecked?'#4CAF50':'')
  $(this).closest('.list-group-item').find('.custom-control-description').css('color', isChecked?'#fff':'#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', isChecked?'#fff':'#ababab')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}
.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}
.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}
@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}
@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}
input[type=checkbox] + svg {
  display: none;
}
input[type=checkbox]:checked + svg {
  display: block;
}
.form-check {
  position: relative;
}
.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}
.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      Checkbox

pending

done

```

Title: Target checked checkbox in jQuery

Body:
I have HTML, CSS and jQuery code for a checkbox. But I was recently making some changes in the HTML structure and now the jQuery is no longer working. And since I'm a beginner, I don't know how to fix this.

Can someone take a look and just let me know what jQuery should be targeting instead, so it'll change the styling of the elements when the checkbox is checked?

$('.form-check').click(function(){
        $(this).closest('.list-group-item').find('.incomplete').css('display', (this.checked)?'none':'block')
        $(this).closest('.list-group-item').find('.complete').css('display', (this.checked)?'block':'none')
        $(this).closest('.list-group-item').css('background-color',(this.checked)?'#4CAF50':'')
        $(this).closest('.list-group-item').find('.custom-control-description').css('color', (this.checked)?'#fff':'#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', (this.checked)?'#fff':'#ababab')
})

.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}
.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}
.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}
@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}
@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}
input[type=checkbox] + svg {
  display: none;
}
input[type=checkbox]:checked + svg {
  display: block;
}
.form-check {
  position: relative;
}
.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}
.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      Checkbox

pending

done

Body:
The problem is with your this.isChecked, it is always undefined, so it always evaluates to false. I replaced it with isChecked, getting the value from the checked property of the checkbox belonging to this li item.

$('.form-check').click(function(){
  var isChecked = $(this).find('#checkbox').prop('checked');
  $(this).closest('.list-group-item').find('.incomplete').css('display', isChecked?'none':'block')
  $(this).closest('.list-group-item').find('.complete').css('display', isChecked?'block':'none')
  $(this).closest('.list-group-item').css('background-color',isChecked?'#4CAF50':'')
  $(this).closest('.list-group-item').find('.custom-control-description').css('color', isChecked?'#fff':'#2c2b2c')
  $(this).closest('.list-group-item').find('.custom-control-description').css('text-decoration-color', isChecked?'#fff':'#ababab')
})

.custom-control-box {
  border-radius: 50%;
  height: 30px;
  width: 30px;
  background-color: #fff;
  border: 1px solid black;
  position: absolute;
  margin-left: -50px;
}

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 3;
  stroke-miterlimit: 10;
  stroke: #1b7e45;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}
.checkmark {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: block;
  stroke-width: 5;
  stroke: #fff;
  stroke-miterlimit: 10;
  box-shadow: inset 0px 0px 0px #1b7e45;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
  border: 1px solid #4c4c4d;
}
.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}
@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}
@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #1b7e45;
  }
}

input[type=checkbox] {
  display: none;
}
input[type=checkbox] + svg {
  display: none;
}
input[type=checkbox]:checked + svg {
  display: block;
}
.form-check {
  position: relative;
}
.form-check label {
  align-items: center;
  justify-content: left;
  padding-left: 50px;
  cursor: pointer;
}
.custom-control-description {
  font-size: 12px;
  line-height: 2.6;
}

.form-check label svg {
  position: absolute;
  top: 0;
  left: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<li class="list-group-item p-4 border-top-0  first-group-item">
  <div class="form-check mb-0">
    <label class="mb-0">
      <span class="custom-control-box align-middle"></span>
      <input type="checkbox" name="item_1" value="item 1" id="checkbox"/>
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
      <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
      <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      <span class="custom-control-description align-middle">Checkbox</span>
    </label>
  </div> <!-- /.form-check -->
  <div class="ml-auto status">
    <p class="mb-0 incomplete">pending</p>
    <p class="mb-0 complete">done</p>
  </div>
</li>