问:
View not updating when splicing user from list in AngularJS
I have this problem in my app, when I use slice to remove  the user from the list. However, it does not remove from the list. I am getting the user with a API url call. But for some reason, it does not remove the user from the list. Please, have a look at my code. If, you guys want the full code, I have put it in my github. I hope we both can solve this. Thank you in advance.

Here is my code:

```<code>    <div ng-controller="MyCtrl">
  <div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">

    <a class="back" href="#/lawyer">Back</a>

    <button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
      Edit
    </button>

      <button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>

    <a class="delete" ng-click="confirmClick(); confirmedAction(person);" confirm-click>Confirm</a>

    <div class="people-view">

      <h2 class="name">{{person.firstName}}</h2>

      <h2 class="name">{{person.lastName}}</h2>

      <span class="title">{{person.email}}</span>

      <span class="date">{{person.website}} </span>

    </div>

    <div class="list-view">

      <form>

        <fieldset ng-disabled="inactive">

          <legend>Basic Info</legend>

          <b>First Name:</b>

          <input type="text" ng-model="person.firstName">
          <br>

          <b>Last Name:</b>

          <input type="text" ng-model="person.lastName">
          <br>

          <b>Email:</b>

          <input type="email" ng-model="person.email">
          <br>

          <b>Website:</b>
          <input type="text" ng-model="person.website">
          <br>

        </fieldset>

      </form>

    </div>
  </div>
</div>
</code>```

App.js

```<code> var app = angular.module("Portal", ['ngRoute',  'ui.bootstrap' ]);

  app.controller('MyCtrl', function($scope, $window) {

    $scope.inactive = true;

        $scope.confirmedAction = function (lawyer) {
        $scope.$apply(function () {
            var index = $scope.userInfo.lawyers.indexOf(lawyer);
            console.log($scope.userInfo.lawyers);
            $scope.userInfo.lawyers.splice(index, 1);
            console.log($scope.userInfo.lawyers);
            $window.location.href = '#/lawyer';
        });
    };

});

app.directive('confirmClick', ['$q', 'dialogModal', function($q, dialogModal) {
    return {
        link: function (scope, element, attrs) {
            // ngClick won't wait for our modal confirmation window to resolve,
            // so we will grab the other values in the ngClick attribute, which
            // will continue after the modal resolves.
            // modify the confirmClick() action so we don't perform it again
            // looks for either confirmClick() or confirmClick('are you sure?')
            var ngClick = attrs.ngClick.replace('confirmClick()', 'true')
                .replace('confirmClick(', 'confirmClick(true,');

            // setup a confirmation action on the scope
            scope.confirmClick = function(msg) {
                // if the msg was set to true, then return it (this is a workaround to make our dialog work)
                if (msg===true) {
                    return true;
                }
                // msg can be passed directly to confirmClick('Are you sure you want to confirm?')
                // in ng-click
                // or through the confirm-click attribute on the
                // <a confirm-click="Are you sure you want to confirm?"></a>
                msg = msg || attrs.confirmClick || 'Are you sure you want to confirm?';
                // open a dialog modal, and then continue ngClick actions if it's confirmed
                dialogModal(msg).result.then(function() {
                    scope.$eval(ngClick);
                });
                // return false to stop the current ng-click flow and wait for our modal answer
                return false;
            };
        }
    }
}])

/*
 Modal confirmation dialog window with the UI Bootstrap Modal service.
 This is a basic modal that can display a message with yes or no buttons.
 It returns a promise that is resolved or rejected based on yes/no clicks.
 The following settings can be passed:

 message         the message to pass to the modal body
 title           (optional) title for modal window
 okButton        text for YES button. set false to not include button
 cancelButton    text for NO button. ste false to not include button

 */
.service('dialogModal', ['$modal', function($modal) {
    return function (message, title, okButton, cancelButton) {
        // setup default values for buttons
        // if a button value is set to false, then that button won't be included
        cancelButton = cancelButton===false ? false : (cancelButton || 'No');
        okButton = okButton ===false ? false : (okButton || 'Yes');

        // setup the Controller to watch the click
        var ModalInstanceCtrl = function ($scope, $modalInstance, settings) {
            // add settings to scope
            angular.extend($scope, settings);
            // yes button clicked
            $scope.ok = function () {
               // alert("Lawyer is confirmed");
                $modalInstance.close(true);
            };
            // no button clicked
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        };

        // open modal and return the instance (which will resolve the promise on ok/cancel clicks)
        var modalInstance = $modal.open({
            template: '<div class="dialog-modal"> \
              <div class="modal-header" ng-show="modalTitle"> \
                  <h3 class="modal-title">{{modalTitle}}</h3> \
              </div> \
              <div class="modal-body">{{modalBody}}</div> \
              <div class="modal-footer"> \
                  <button class="btn btn-primary" ng-click="ok()" ng-show="okButton">{{okButton}}</button> \
                  <button class="btn btn-warning" ng-click="cancel()" ng-show="cancelButton">{{cancelButton}}</button> \
              </div> \
          </div>',
            controller: ModalInstanceCtrl,
            resolve: {
                settings: function() {
                    return {
                        modalTitle: title,
                        modalBody: message,
                        okButton: okButton,
                        cancelButton: cancelButton
                    };
                }
            }
        });
        // return the modal instance
        return modalInstance;
    }
}])

  app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
    controller: "HomeController",
    templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
    controller: "LawyerController",
    templateUrl: "partials/about.html"
})
.otherwise({
    redirectTo: '/lawyer'

  });

});
</code>```

答:
But the element is getting deleted from list right?

If yes then, Try this :

```<code>$scope.confirmedAction = function (lawyer) {
    $scope.$apply(function () {
      var index = $scope.userInfo.lawyers.indexOf(lawyer);
      console.log($scope.userInfo.lawyers);
      $scope.userInfo.lawyers.splice(index, 1);
      console.log($scope.userInfo.lawyers);
      $window.location.href = '#/lawyer';
    });
});
</code>```

Or

```<code>$scope.confirmedAction = function (lawyer) {
    $timeout(function () {
      var index = $scope.userInfo.lawyers.indexOf(lawyer);
      console.log($scope.userInfo.lawyers);
      $scope.userInfo.lawyers.splice(index, 1);
      console.log($scope.userInfo.lawyers);
 $state.go($state.current, {}, {reload: true});
      // $window.location.href = '#/lawyer';
    },1100);
});
</code>```

Body:
I have this problem in my app, when I use slice to remove  the user from the list. However, it does not remove from the list. I am getting the user with a API url call. But for some reason, it does not remove the user from the list. Please, have a look at my code. If, you guys want the full code, I have put it in my github. I hope we both can solve this. Thank you in advance.

Here is my code:

    Back

    <button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
      Edit
    </button>

      <button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>

    Confirm

{{person.firstName}}

{{person.lastName}}

      {{person.email}}

      {{person.website}}

      <form>

        <fieldset ng-disabled="inactive">

          <legend>Basic Info</legend>

          First Name:

          <input type="text" ng-model="person.firstName">

          Last Name:

          <input type="text" ng-model="person.lastName">

          Email:

          <input type="email" ng-model="person.email">

          Website:
          <input type="text" ng-model="person.website">

        </fieldset>

      </form>

App.js

 var app = angular.module("Portal", ['ngRoute',  'ui.bootstrap' ]);

  app.controller('MyCtrl', function($scope, $window) {

    $scope.inactive = true;

        $scope.confirmedAction = function (lawyer) {
        $scope.$apply(function () {
            var index = $scope.userInfo.lawyers.indexOf(lawyer);
            console.log($scope.userInfo.lawyers);
            $scope.userInfo.lawyers.splice(index, 1);
            console.log($scope.userInfo.lawyers);
            $window.location.href = '#/lawyer';
        });
    };

});

app.directive('confirmClick', ['$q', 'dialogModal', function($q, dialogModal) {
    return {
        link: function (scope, element, attrs) {
            // ngClick won't wait for our modal confirmation window to resolve,
            // so we will grab the other values in the ngClick attribute, which
            // will continue after the modal resolves.
            // modify the confirmClick() action so we don't perform it again
            // looks for either confirmClick() or confirmClick('are you sure?')
            var ngClick = attrs.ngClick.replace('confirmClick()', 'true')
                .replace('confirmClick(', 'confirmClick(true,');

            // setup a confirmation action on the scope
            scope.confirmClick = function(msg) {
                // if the msg was set to true, then return it (this is a workaround to make our dialog work)
                if (msg===true) {
                    return true;
                }
                // msg can be passed directly to confirmClick('Are you sure you want to confirm?')
                // in ng-click
                // or through the confirm-click attribute on the
                //
                msg = msg || attrs.confirmClick || 'Are you sure you want to confirm?';
                // open a dialog modal, and then continue ngClick actions if it's confirmed
                dialogModal(msg).result.then(function() {
                    scope.$eval(ngClick);
                });
                // return false to stop the current ng-click flow and wait for our modal answer
                return false;
            };
        }
    }
}])

/*
 Modal confirmation dialog window with the UI Bootstrap Modal service.
 This is a basic modal that can display a message with yes or no buttons.
 It returns a promise that is resolved or rejected based on yes/no clicks.
 The following settings can be passed:

 message         the message to pass to the modal body
 title           (optional) title for modal window
 okButton        text for YES button. set false to not include button
 cancelButton    text for NO button. ste false to not include button

 */
.service('dialogModal', ['$modal', function($modal) {
    return function (message, title, okButton, cancelButton) {
        // setup default values for buttons
        // if a button value is set to false, then that button won't be included
        cancelButton = cancelButton===false ? false : (cancelButton || 'No');
        okButton = okButton ===false ? false : (okButton || 'Yes');

        // setup the Controller to watch the click
        var ModalInstanceCtrl = function ($scope, $modalInstance, settings) {
            // add settings to scope
            angular.extend($scope, settings);
            // yes button clicked
            $scope.ok = function () {
               // alert("Lawyer is confirmed");
                $modalInstance.close(true);
            };
            // no button clicked
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        };

        // open modal and return the instance (which will resolve the promise on ok/cancel clicks)
        var modalInstance = $modal.open({
            template: '
 \

 \

{{modalTitle}}
 \

 \

{{modalBody}}
 \

 \
                  <button class="btn btn-primary" ng-click="ok()" ng-show="okButton">{{okButton}}</button> \
                  <button class="btn btn-warning" ng-click="cancel()" ng-show="cancelButton">{{cancelButton}}</button> \

 \

',
            controller: ModalInstanceCtrl,
            resolve: {
                settings: function() {
                    return {
                        modalTitle: title,
                        modalBody: message,
                        okButton: okButton,
                        cancelButton: cancelButton
                    };
                }
            }
        });
        // return the modal instance
        return modalInstance;
    }
}])

  app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
    controller: "HomeController",
    templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
    controller: "LawyerController",
    templateUrl: "partials/about.html"
})
.otherwise({
    redirectTo: '/lawyer'

  });

});

Body:
But the element is getting deleted from list right?

If yes then, Try this :

$scope.confirmedAction = function (lawyer) {
    $scope.$apply(function () {
      var index = $scope.userInfo.lawyers.indexOf(lawyer);
      console.log($scope.userInfo.lawyers);
      $scope.userInfo.lawyers.splice(index, 1);
      console.log($scope.userInfo.lawyers);
      $window.location.href = '#/lawyer';
    });
});

Or

$scope.confirmedAction = function (lawyer) {
    $timeout(function () {
      var index = $scope.userInfo.lawyers.indexOf(lawyer);
      console.log($scope.userInfo.lawyers);
      $scope.userInfo.lawyers.splice(index, 1);
      console.log($scope.userInfo.lawyers);
 $state.go($state.current, {}, {reload: true});
      // $window.location.href = '#/lawyer';
    },1100);
});


来源: stackexchange

问:
How do we clean out JSP's .class files when we re-deploy our application on JBoss?
I'm using JBOss 7.1.3.AS with Java 7.  It is not an option to upgrade at this time.  I notice that when our .jsp files get converted into .class files, they are placed here

```<code>$JBOSS_HOME/standalone/tmp/work/jboss.web/default-host
</code>```

How do we force all the .class files to be removed upon deploying our application (we would like these files re-generated)?  We deploy by running

```<code>touch $JBOSS_HOME/standalone/deployments/myapp.dodeploy
</code>```

but we're open to another method if it solves the problem IL mention above.

答:
In JBoss AS 7.1.x there is no feature to delete the JSP cache under the folder $JBOSS_HOME/standalone/tmp/work/jboss.web/default-localhost/$YOUR_WEB_CONTEXT. In JBoss AS 7.2 new feature is system property is included which will delete JSP cash files when context root of the application is destroyed.

In JBoss AS 7 you can set the system property org.jboss.as.web.deployment.DELETE_WORK_DIR_ONCONTEXTDESTROY to true to delete the JSP cache each time on context destroy. The default for this property is false. You can use this property to remove .java and .class files to ensure that JSP sources are recompiled.

ContentLicense: CC BY-SA 3.0

Body:
I'm using JBOss 7.1.3.AS with Java 7.  It is not an option to upgrade at this time.  I notice that when our .jsp files get converted into .class files, they are placed here

$JBOSS_HOME/standalone/tmp/work/jboss.web/default-host

How do we force all the .class files to be removed upon deploying our application (we would like these files re-generated)?  We deploy by running

touch $JBOSS_HOME/standalone/deployments/myapp.dodeploy

but we're open to another method if it solves the problem IL mention above.


问:
Unable to get an result with only an simple if not null with MySql
```<code>SELECT `a`.`id`   AS `id`,
       `a`.`info` AS `info`,
       `a`.`type` AS `type`,
       `a`.`disp` AS `disp`,
       `a`.`emp`  AS `emp`,
       `a`.`tel`  AS `tel`,
       `a`.`img`  AS `img`,
       `a`.`job`  AS `job`
FROM ((`my_shop` `a`
       LEFT JOIN `my_shop2` `b`
           ON(( `a`.`id` = `b`.`my_shop_id` )))
       JOIN `my_shop3` `c`
           ON(( Ifnull(`b`.`my_shop_id`, `a`.`id`) = `c`.`id` )))
</code>```

<p>I've added a field in my_shop table called "personal_id". And what I want to do is to  get the above information if the personal_id field contains an id. How will I achieve this ? Some example or tips would be great! I would love to hear from you! </p>

答:
Please use below mentioned code which will solve your issue.

```<code>SELECT
    a.id   AS id,
    a.info AS info,
    a.type AS type,
    a.disp AS disp,
    a.emp  AS emp,
    a.tel  AS tel,
    a.img  AS img,
    a.job  AS job
FROM my_shop a
LEFT JOIN my_shop2 b ON a.id = b.my_shop_id
INNER JOIN my_shop3 c ON Ifnull(b.my_shop_id, a.id) = c.id
WHERE a.personal_id IS NOT NULL;
</code>```

and if you want to compare personal_id with specific table column value than use below where command

```<code>WHERE a.personal_id = <tablename.column_name>
</code>```

Try this and let us know.

Body:
SELECT `a`.`id`   AS `id`,
       `a`.`info` AS `info`,
       `a`.`type` AS `type`,
       `a`.`disp` AS `disp`,
       `a`.`emp`  AS `emp`,
       `a`.`tel`  AS `tel`,
       `a`.`img`  AS `img`,
       `a`.`job`  AS `job`
FROM ((`my_shop` `a`
       LEFT JOIN `my_shop2` `b`
           ON(( `a`.`id` = `b`.`my_shop_id` )))
       JOIN `my_shop3` `c`
           ON(( Ifnull(`b`.`my_shop_id`, `a`.`id`) = `c`.`id` )))

I've added a field in my_shop table called "personal_id". And what I want to do is to  get the above information if the personal_id field contains an id. How will I achieve this ? Some example or tips would be great! I would love to hear from you!

Body:
Please use below mentioned code which will solve your issue.

SELECT
    a.id   AS id,
    a.info AS info,
    a.type AS type,
    a.disp AS disp,
    a.emp  AS emp,
    a.tel  AS tel,
    a.img  AS img,
    a.job  AS job
FROM my_shop a
LEFT JOIN my_shop2 b ON a.id = b.my_shop_id
INNER JOIN my_shop3 c ON Ifnull(b.my_shop_id, a.id) = c.id
WHERE a.personal_id IS NOT NULL;

and if you want to compare personal_id with specific table column value than use below where command

WHERE a.personal_id = <tablename.column_name>

Try this and let us know.


问:
SQL - Best practice for a Friendship table

Before you show me duplicates, please note that I've searched through the site an have found some examples but not quite specific to my problem :)

What's the best way to create a Friendship table in SQL, but making sure that each row is unique in the sense that the same UserID and FriendID will never be alowed regardless of which column they belong to?

I have this rough example

```<code>CREATE TABLE [dbo].[Friendship](
    [UserID] [uniqueidentifier] NOT NULL,
    [FriendID] [uniqueidentifier] NOT NULL,
    [FriendshipStatus] [int] NOT NULL
)
</code>```

And there are 2 foreign keys to the Users table, both from UserID and FriendID.

At the moment though, I can insert a Friendship between users twice, thus creating a duplicate. Example

```<code>UserID    FriendID    FriendshipStatus
Guid 123   Guid 789    1
Guid 789   Guid 123    1
</code>```

How do I ensure this integrity is enforced, perhaps 2 PKs? Some sort of a unique Index? Or would you suggest a better table design all together? Also, would you put an autoincrementing FriendshipID? If so, can you explain why?

答:
Quassnoi wrote an article explaining why you might want to have a version of the table with two rows per pair, to make queries easier: http://explainextended.com/2009/03/07/selecting-friends/

(the article talks about MySQL but it is worth bearing in mind as a performance technique for any SQL database)

Body:
Before you show me duplicates, please note that I've searched through the site an have found some examples but not quite specific to my problem :)

What's the best way to create a Friendship table in SQL, but making sure that each row is unique in the sense that the same UserID and FriendID will never be alowed regardless of which column they belong to?

I have this rough example

CREATE TABLE [dbo].[Friendship](
    [UserID] [uniqueidentifier] NOT NULL,
    [FriendID] [uniqueidentifier] NOT NULL,
    [FriendshipStatus] [int] NOT NULL
)

And there are 2 foreign keys to the Users table, both from UserID and FriendID.

At the moment though, I can insert a Friendship between users twice, thus creating a duplicate. Example

UserID    FriendID    FriendshipStatus
Guid 123   Guid 789    1
Guid 789   Guid 123    1

How do I ensure this integrity is enforced, perhaps 2 PKs? Some sort of a unique Index? Or would you suggest a better table design all together? Also, would you put an autoincrementing FriendshipID? If so, can you explain why?

ContentLicense: CC BY-SA 2.5


问:
AsyncTask, LinearLayout Android Update visibility
I am trying to change visibility of a Linear Layout through findViewById() and then SetVisiblity(). But When I debug, I am seeing null values only.

Please find the snippet in the BackgroundMainActivity.java below in the onPostExecute() method.

I commented it. Please help.

MainActivity.java

```<code>button_getUsername.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, v);
            backgroundMainActivity.execute("random", editText_username.getText().toString());
        }
    });
</code>```

BackgroundMainActivity.java

```<code>public class BackgroundMainActivity extends AsyncTask<String, Void , String> {

    public BackgroundMainActivity(Context ct, View view) {
        context = ct;
        rootView = view;
    }

    @Override
    protected String doInBackground(String... params) {
        String login_URL = "some url";
        try {
            String username = params[1];

            URL url = new URL(login_URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String postData = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8");
            bufferedWriter.write(postData);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));

            result = bufferedReader.readLine();

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPreExecute(){

    }

    @Override
    protected void onPostExecute (String result){
        if(result.equals("success")){

//need to make this change
//LinearLayout someLayout = (LinearLayout)rootview.findViewById(R.id.layout_content);
//someLayout.setVisibility(View.VISIBLE);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(result)
                    .setPositiveButton("Ok",null)
                    .show();
        }

    }

    @Override
    protected void onProgressUpdate(Void... values){
        super.onProgressUpdate(values);
    }
}
</code>```

EDIT:

activity_main.xml

ss_layout_questions is gone by default. I want to make it visible once "result.equals( "success") " in BackgroundMainActivity.java.

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.xtremustechnologies.chotu.useractivity.MainActivity">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:background="@color/lightGreen"
        android:layout_gravity="top">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignEnd="@+id/textviewr2"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="30dp"
                    android:text="CHOTU"
                    android:textColor="@color/white"
                    android:textSize="40dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="40dp"
                    android:text="Your Personal Assistant"
                    android:textColor="@color/white"
                    android:textSize="12dp" />
            </LinearLayout>

            <TextView
                android:id="@+id/ss_textview_questions"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="40dp"
                android:text="Security Questions "
                android:textColor="@color/black"
                android:textSize="20dp"
                android:visibility="gone"/>

            <EditText
                android:id="@+id/ss_et_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_gravity="center_horizontal"
                android:hint="Enter Username" />

            <Button
                android:id="@+id/ss_button_getusername"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/ss_et_username"
                android:layout_centerHorizontal="true"
                android:onClick="clickGetUsername"
                android:layout_gravity="center_horizontal"
                android:text="Submit" />

            <LinearLayout
                android:id="@+id/ss_layout_questions"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/textviewr3"
                    android:layout_centerHorizontal="false"
                    android:layout_marginLeft="40dp"
                    android:layout_marginRight="40dp"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/ss_button_dob"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginRight="50dp"
                        android:text="Date of Birth" />

                    <TextView
                        android:id="@+id/ss_textView_dob"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right|center_vertical|center_horizontal"
                        android:layout_weight="1"
                        android:text="TextView"
                        android:textSize="20dp" />
                </LinearLayout>

                <TextView
                    android:id="@+id/ss_textView_question1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <Button
                    android:id="@+id/ss_button_submit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:background="@color/black"
                    android:text="Submit"
                    android:textColor="@color/white" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>
</android.support.constraint.ConstraintLayout>
</code>```

答:
Yes, you should get NPE error. Why? Because look at this code:

```<code>button_getUsername.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, v);
        backgroundMainActivity.execute("random", editText_username.getText().toString());
    }
});
</code>```

Here, you are trying to pass a Button (your button_getUserName) to your AsyncTask. Then when you find the view, of course, there's no layout in your button.

How to resolve it? Actually, it's very easy, just pass your layout in the constructor of the AsyncTask as:

```<code>BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, findViewById(R.id.layout_content));
// do on onPost:v.setVisibility...
</code>```

Body:
I am trying to change visibility of a Linear Layout through findViewById() and then SetVisiblity(). But When I debug, I am seeing null values only.

Please find the snippet in the BackgroundMainActivity.java below in the onPostExecute() method.

I commented it. Please help.

MainActivity.java

button_getUsername.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, v);
            backgroundMainActivity.execute("random", editText_username.getText().toString());
        }
    });

BackgroundMainActivity.java

public class BackgroundMainActivity extends AsyncTask<String, Void , String> {

    public BackgroundMainActivity(Context ct, View view) {
        context = ct;
        rootView = view;
    }

    @Override
    protected String doInBackground(String... params) {
        String login_URL = "some url";
        try {
            String username = params[1];

            URL url = new URL(login_URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String postData = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8");
            bufferedWriter.write(postData);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));

            result = bufferedReader.readLine();

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPreExecute(){

    }

    @Override
    protected void onPostExecute (String result){
        if(result.equals("success")){

//need to make this change
//LinearLayout someLayout = (LinearLayout)rootview.findViewById(R.id.layout_content);
//someLayout.setVisibility(View.VISIBLE);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(result)
                    .setPositiveButton("Ok",null)
                    .show();
        }

    }

    @Override
    protected void onProgressUpdate(Void... values){
        super.onProgressUpdate(values);
    }
}

EDIT:

activity_main.xml

ss_layout_questions is gone by default. I want to make it visible once "result.equals( "success") " in BackgroundMainActivity.java.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.xtremustechnologies.chotu.useractivity.MainActivity">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:background="@color/lightGreen"
        android:layout_gravity="top">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignEnd="@+id/textviewr2"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="30dp"
                    android:text="CHOTU"
                    android:textColor="@color/white"
                    android:textSize="40dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginBottom="40dp"
                    android:text="Your Personal Assistant"
                    android:textColor="@color/white"
                    android:textSize="12dp" />
            </LinearLayout>

            <TextView
                android:id="@+id/ss_textview_questions"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="40dp"
                android:text="Security Questions "
                android:textColor="@color/black"
                android:textSize="20dp"
                android:visibility="gone"/>

            <EditText
                android:id="@+id/ss_et_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_gravity="center_horizontal"
                android:hint="Enter Username" />

            <Button
                android:id="@+id/ss_button_getusername"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/ss_et_username"
                android:layout_centerHorizontal="true"
                android:onClick="clickGetUsername"
                android:layout_gravity="center_horizontal"
                android:text="Submit" />

            <LinearLayout
                android:id="@+id/ss_layout_questions"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/textviewr3"
                    android:layout_centerHorizontal="false"
                    android:layout_marginLeft="40dp"
                    android:layout_marginRight="40dp"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/ss_button_dob"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginRight="50dp"
                        android:text="Date of Birth" />

                    <TextView
                        android:id="@+id/ss_textView_dob"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right|center_vertical|center_horizontal"
                        android:layout_weight="1"
                        android:text="TextView"
                        android:textSize="20dp" />
                </LinearLayout>

                <TextView
                    android:id="@+id/ss_textView_question1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <TextView
                    android:id="@+id/ss_textView_question3"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="30dp" />

                <EditText
                    android:id="@+id/ss_textView_ans3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginTop="10dp"
                    android:hint="Enter your answer here" />

                <Button
                    android:id="@+id/ss_button_submit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:background="@color/black"
                    android:text="Submit"
                    android:textColor="@color/white" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>
</android.support.constraint.ConstraintLayout>

Body:
Yes, you should get NPE error. Why? Because look at this code:

button_getUsername.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, v);
        backgroundMainActivity.execute("random", editText_username.getText().toString());
    }
});

Here, you are trying to pass a Button (your button_getUserName) to your AsyncTask. Then when you find the view, of course, there's no layout in your button.

How to resolve it? Actually, it's very easy, just pass your layout in the constructor of the AsyncTask as:

BackgroundMainActivity backgroundMainActivity = new BackgroundMainActivity(MainActivity.this, findViewById(R.id.layout_content));
// do on onPost:v.setVisibility...


问:
Export Mongodb subdocuments to CSV
I am having problems exporting subdocuments that are stored in MongoDB to a .CSV.

My data: a mongo collection that contains a unique user ID and scores from personality quizzes.

I would like a CSV that has three columns: user_id, name, raw_score. To add a further layer of complexity, within the 'scales' subdocument some users will have more than two entries (some quizzes produced more than 2 personality scores).

An example of my data minus documents that I am not interested in:

```<code>    "assessment":{
    "user_id" : "5839b1a654842f35617ad100",
    "submissions" : {
    "results" : {
            "scales" : [
                {
                    "scale" : {
                        "name" : "Security",
                        "code" : "SEC",
                        "multiplier" : 1
                    },
                    "raw_score" : 2
                },
                {
                    "scale" : {
                        "name" : "Power",
                        "code" : "POW",
                        "multiplier" : -1
                    },
                    "raw_score" : 3
                    }
                ],
            }
        }
    }
}
</code>```

I have tried using mongoexport but this produces a CSV that only has a user_id column.

```<code>rekuss$ mongoexport -d production_hoganx_app -c assessments --type=csv -o app_personality.csv -f user_id,results.scales.scale.name,results.scales.raw_score
</code>```

Any ideas where I am going wrong?

Please let me know if you need anymore information.

Many thanks

答: You should try removing '=' sign from type. You could try --type csv </p>

Title: Export Mongodb subdocuments to CSV

Body:
I am having problems exporting subdocuments that are stored in MongoDB to a .CSV.

My data: a mongo collection that contains a unique user ID and scores from personality quizzes.

I would like a CSV that has three columns: user_id, name, raw_score. To add a further layer of complexity, within the 'scales' subdocument some users will have more than two entries (some quizzes produced more than 2 personality scores).

An example of my data minus documents that I am not interested in:

    "assessment":{
    "user_id" : "5839b1a654842f35617ad100",
    "submissions" : {
    "results" : {
            "scales" : [
                {
                    "scale" : {
                        "name" : "Security",
                        "code" : "SEC",
                        "multiplier" : 1
                    },
                    "raw_score" : 2
                },
                {
                    "scale" : {
                        "name" : "Power",
                        "code" : "POW",
                        "multiplier" : -1
                    },
                    "raw_score" : 3
                    }
                ],
            }
        }
    }
}

I have tried using mongoexport but this produces a CSV that only has a user_id column.

rekuss$ mongoexport -d production_hoganx_app -c assessments --type=csv -o app_personality.csv -f user_id,results.scales.scale.name,results.scales.raw_score

Any ideas where I am going wrong?

Please let me know if you need anymore information.

Many thanks


问:
How to fix null pointer exception when creating a gameHelper with LibGDX and BaseGameUtils?
I am currently working on my first game (which I will NOT shameless promote), but I am trying to set up a leaderboard, but when I try to initialize my GameHelper, I get an exception. I couldn't find any answers and I would appreciate any help.

Code:

```<code>package com.aidanstrong.runner;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
import com.google.example.games.basegameutils.GameHelper.GameHelperListener;

public class AndroidLauncher extends AndroidApplication implements GameHelperListener, PlayServices{

private final static int requestCode = 1;
private GameHelper gameHelper;

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    initialize(new MyGame(this), config);
    gameHelper = new GameHelper(this,GameHelper.CLIENT_ALL);
    gameHelper.enableDebugLog(true);
    gameHelper.setup(this);
}

@Override
public void onStart(){
    super.onStart();
    gameHelper.onStart(this);
}

@Override
public void onStop(){
    super.onStop();
    gameHelper.onStop();
}

@Override
public void onActivityResult(int request, int response, Intent data) {
    super.onActivityResult(request, response, data);
    gameHelper.onActivityResult(request, response, data);
}

@Override
public boolean signIn() {
    return gameHelper.isSignedIn();
}

@Override
public void logIn() {
    try {
        runOnUiThread(new Runnable(){
            public void run() {
                gameHelper.beginUserInitiatedSignIn();
            }
        });
    } catch (final Exception ex) {
    }
}

@Override
public void submitScore(int score) {
    Games.Leaderboards.submitScore(gameHelper.getApiClient(),"CgkIlKy-68IeEAIQAQ",score);
}

@Override
public void getLeaderboard() {
    Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(),"CgkIlKy-68IeEAIQAQ");
}

@Override
public void onSignInFailed() {
}

@Override
public void onSignInSucceeded() {
}
}
</code>```

the error I receive is

"java.lang.RuntimeException: Unable to instantiate activity
  ComponentInfo{com.aidanstrong.runner/com.aidanstrong.runner.AndroidLauncher}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.content.Context
  android.content.Context.getApplicationContext()' on a null object
  reference" on line 21.

EDIT:
I tried it out and got a new error, moving all the statements in the constructor to before gameHelper.setup(this) I get the error

FATAL EXCEPTION: main
                                                                          Process: com.aidanstrong.runner, PID: 11950
                                                                          java.lang.NoSuchMethodError: No direct method
  (Ljava/lang/String;Lcom/google/android/gms/common/api/Api$zza;Lcom/google/android/gms/common/api/Api$zzc;)V
  in class Lcom/google/android/gms/common/api/Api; or its super classes
  (declaration of 'com.google.android.gms.common.api.Api' appears in
  /data/app/com.aidanstrong.runner-1/split_lib_dependencies_apk.apk)
                                                                              at com.google.android.gms.plus.Plus.(Unknown Source)
                                                                              at
  com.google.example.games.basegameutils.GameHelper.createApiClientBuilder(GameHelper.java:276)
                                                                              at
  com.google.example.games.basegameutils.GameHelper.setup(GameHelper.java:309)
                                                                              at
  com.aidanstrong.runner.AndroidLauncher.onCreate(AndroidLauncher.java:32)
                                                                              at android.app.Activity.performCreate(Activity.java:6270)
                                                                              at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
                                                                              at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2395)
                                                                              at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2506)
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                              at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5491)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)'

```<code>    <?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.aidanstrong.runner"
    android:versionCode="6"
    android:versionName="1.22" >
   <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="25" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application

        android:allowBackup="true"
       android:icon="@drawable/secondicon"
        android:label="Jump Man"
        android:theme="@style/GdxTheme" >
        <activity
        android:name="com.aidanstrong.runner.AndroidLauncher"
        android:label="Jump Man"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />
    <meta-data android:name="com.google.android.gms.appstate.APP_ID" android:value="@string/app_id" />
</application>
</code>```

答:
Keep your meta-data inside  <application tag

```<code><meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />
<meta-data android:name="com.google.android.gms.appstate.APP_ID" android:value="@string/app_id" />
</code>```

Remove default constructor of AndroidLauncher

```<code>public class AndroidLauncher extends AndroidApplication implements IGoogleServices {

private GameHelper gameHelper;
private final static int REQUEST_CODE_UNUSED = 9002;
private static final String TAG = "[" + AndroidLauncher.class.getSimpleName() + "]";

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
    gameHelper.enableDebugLog(true);
    GameHelper.GameHelperListener gameHelperListener = new GameHelper.GameHelperListener() {
        @Override
        public void onSignInSucceeded(){}

        @Override
        public void onSignInFailed() {}
    };

    //gameHelper.setMaxAutoSignInAttempts(0);
    gameHelper.setup(gameHelperListener);

    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();

    initialize(new MyGame(this), config);
}

@Override
protected void onStart() {
    super.onStart();
    gameHelper.onStart(this);
}

@Override
protected void onStop() {
    super.onStop();
    gameHelper.onStop();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    gameHelper.onActivityResult(requestCode, resultCode, data);
}

@Override
public void signIn() {
    try {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                gameHelper.beginUserInitiatedSignIn();
            }
        });
    }
    catch (Exception e) {
        Gdx.app.log("MainActivity", "Log in failed: " + e.getMessage() + ".");
    }
}

 @Override
public void signOut() {
    try {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //gameHelper.signOut();
            }
        });
    }
    catch (Exception e) {
        Gdx.app.log("MainActivity", "Log out failed: " + e.getMessage() + ".");
    }
}

 @Override
public void submitScore(long score) {
    if (isSignedIn()) Games.Leaderboards.submitScore(gameHelper.getApiClient(), getString(R.string.leaderboard_id), score);
}

@Override
public void showScores() {
    if(isSignedIn())
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), getString(R.string.leaderboard_id)), REQUEST_CODE_UNUSED);
    else
        signIn();
}

@Override
public boolean isSignedIn() {
    return gameHelper.isSignedIn();
}

@Override
public void start() {
    gameHelper.onStart(this);
}
</code>```

IGoogleServices is an interface in core module that I use for Interfacing with android module.

Body:
I am currently working on my first game (which I will NOT shameless promote), but I am trying to set up a leaderboard, but when I try to initialize my GameHelper, I get an exception. I couldn't find any answers and I would appreciate any help.

Code:

package com.aidanstrong.runner;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
import com.google.example.games.basegameutils.GameHelper.GameHelperListener;

public class AndroidLauncher extends AndroidApplication implements GameHelperListener, PlayServices{

private final static int requestCode = 1;
private GameHelper gameHelper;

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    initialize(new MyGame(this), config);
    gameHelper = new GameHelper(this,GameHelper.CLIENT_ALL);
    gameHelper.enableDebugLog(true);
    gameHelper.setup(this);
}

@Override
public void onStart(){
    super.onStart();
    gameHelper.onStart(this);
}

@Override
public void onStop(){
    super.onStop();
    gameHelper.onStop();
}

@Override
public void onActivityResult(int request, int response, Intent data) {
    super.onActivityResult(request, response, data);
    gameHelper.onActivityResult(request, response, data);
}

@Override
public boolean signIn() {
    return gameHelper.isSignedIn();
}

@Override
public void logIn() {
    try {
        runOnUiThread(new Runnable(){
            public void run() {
                gameHelper.beginUserInitiatedSignIn();
            }
        });
    } catch (final Exception ex) {
    }
}

@Override
public void submitScore(int score) {
    Games.Leaderboards.submitScore(gameHelper.getApiClient(),"CgkIlKy-68IeEAIQAQ",score);
}

@Override
public void getLeaderboard() {
    Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(),"CgkIlKy-68IeEAIQAQ");
}

@Override
public void onSignInFailed() {
}

@Override
public void onSignInSucceeded() {
}
}

the error I receive is

"java.lang.RuntimeException: Unable to instantiate activity
  ComponentInfo{com.aidanstrong.runner/com.aidanstrong.runner.AndroidLauncher}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.content.Context
  android.content.Context.getApplicationContext()' on a null object
  reference" on line 21.

EDIT:
I tried it out and got a new error, moving all the statements in the constructor to before gameHelper.setup(this) I get the error

FATAL EXCEPTION: main
                                                                          Process: com.aidanstrong.runner, PID: 11950
                                                                          java.lang.NoSuchMethodError: No direct method
  (Ljava/lang/String;Lcom/google/android/gms/common/api/Api$zza;Lcom/google/android/gms/common/api/Api$zzc;)V
  in class Lcom/google/android/gms/common/api/Api; or its super classes
  (declaration of 'com.google.android.gms.common.api.Api' appears in
  /data/app/com.aidanstrong.runner-1/split_lib_dependencies_apk.apk)
                                                                              at com.google.android.gms.plus.Plus.(Unknown Source)
                                                                              at
  com.google.example.games.basegameutils.GameHelper.createApiClientBuilder(GameHelper.java:276)
                                                                              at
  com.google.example.games.basegameutils.GameHelper.setup(GameHelper.java:309)
                                                                              at
  com.aidanstrong.runner.AndroidLauncher.onCreate(AndroidLauncher.java:32)
                                                                              at android.app.Activity.performCreate(Activity.java:6270)
                                                                              at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
                                                                              at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2395)
                                                                              at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2506)
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                              at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5491)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)'

    <?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.aidanstrong.runner"
    android:versionCode="6"
    android:versionName="1.22" >
   <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="25" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application

        android:allowBackup="true"
       android:icon="@drawable/secondicon"
        android:label="Jump Man"
        android:theme="@style/GdxTheme" >
        <activity
        android:name="com.aidanstrong.runner.AndroidLauncher"
        android:label="Jump Man"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />
    <meta-data android:name="com.google.android.gms.appstate.APP_ID" android:value="@string/app_id" />
</application>

Body:
Keep your meta-data inside  <application tag

<meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />
<meta-data android:name="com.google.android.gms.appstate.APP_ID" android:value="@string/app_id" />

Remove default constructor of AndroidLauncher

public class AndroidLauncher extends AndroidApplication implements IGoogleServices {

private GameHelper gameHelper;
private final static int REQUEST_CODE_UNUSED = 9002;
private static final String TAG = "[" + AndroidLauncher.class.getSimpleName() + "]";

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
    gameHelper.enableDebugLog(true);
    GameHelper.GameHelperListener gameHelperListener = new GameHelper.GameHelperListener() {
        @Override
        public void onSignInSucceeded(){}

        @Override
        public void onSignInFailed() {}
    };

    //gameHelper.setMaxAutoSignInAttempts(0);
    gameHelper.setup(gameHelperListener);

    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();

    initialize(new MyGame(this), config);
}

@Override
protected void onStart() {
    super.onStart();
    gameHelper.onStart(this);
}

@Override
protected void onStop() {
    super.onStop();
    gameHelper.onStop();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    gameHelper.onActivityResult(requestCode, resultCode, data);
}

@Override
public void signIn() {
    try {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                gameHelper.beginUserInitiatedSignIn();
            }
        });
    }
    catch (Exception e) {
        Gdx.app.log("MainActivity", "Log in failed: " + e.getMessage() + ".");
    }
}

 @Override
public void signOut() {
    try {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //gameHelper.signOut();
            }
        });
    }
    catch (Exception e) {
        Gdx.app.log("MainActivity", "Log out failed: " + e.getMessage() + ".");
    }
}

 @Override
public void submitScore(long score) {
    if (isSignedIn()) Games.Leaderboards.submitScore(gameHelper.getApiClient(), getString(R.string.leaderboard_id), score);
}

@Override
public void showScores() {
    if(isSignedIn())
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), getString(R.string.leaderboard_id)), REQUEST_CODE_UNUSED);
    else
        signIn();
}

@Override
public boolean isSignedIn() {
    return gameHelper.isSignedIn();
}

@Override
public void start() {
    gameHelper.onStart(this);
}

IGoogleServices is an interface in core module that I use for Interfacing with android module.


问:
Page_Load called in Firefox, but not IE
I've been thrown into an ASP.NET project and I've got a page which contains a control that is fetched via AJAX.

The Page_Load function of the control does a little bit of logic necessary to get the correct values from the Query string.

The problem is that the Page_Load function isn't called in IE.

If I put a breakpoint in, I can load the page in FF and watch it stop, but in IE: no deal.

I'm pretty (read: COMPLETELY) new to ASP.NET, but I'm a pretty experienced PHP developer.
So I'm thinking it's probably some funk with the way that IE does the AJAX callback to get the control.

Has anyone got any ideas?

Cheers

答: What is inside the Page_Load? Either EventWireup is set to false on the ASPX page, or it's something in the code. </p>

Title: Page_Load called in Firefox, but not IE

OwnerDisplayName: Bbetances


问:
xml parsing with no browser use
I have read the example for Rss Parsing from the ibm site.(http://www.ibm.com/developerworks/opensource/library/x-android/).

In this example,the rss are shown in a listview and then,if you press one announcement you can see it in the web browser of the device.How could i see them in the app,with no use of the device browser?

Thanks a lot

答:
I'm a little confused but you seem to have answered your own question.

You say you don't want to use the web browser on the device but the example in your question doesn't use the browser. It does exactly what you're asking for.

The idea is that you download the html from the website and then use the parser to break it up into separate "announcements" and store them in list view items in your program.

I have done a bit of this type of thing myself in android. I used jsoup java library, which makes breaking the html into the bits you want to display really easy.

If you want some more help I can give you an example of an app I made that pulls movie times from google.com/movies as an example. here are links to the classes where I did the html download and parse:

ScreenScraper.java

HtmlParser.java

Title: xml parsing with no browser use


问:
How can I display image behind div with bootstrap?
I have 2 rows in my container. In the second row I have 2 elements one and two. Now I am trying to display the image behind those too almost like a background. This is the html:

```<code><div class="container">
  <div class="row">
    <img src="someimageurl" alt="" />
  </div>
  <div class="row">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
</div>
</code>```

codepen

答:
Is background-image what you're looking for?

HTML

```<code><div id=RowDivWithBackground class=row>
</div>
</code>```

CSS

```<code>.RowDivWithBackground {
    background-image: url('url/to/image');
    other-css-do-dads /*Probably some rgba action*/
}
</code>```

Body:
I have 2 rows in my container. In the second row I have 2 elements one and two. Now I am trying to display the image behind those too almost like a background. This is the html:

one

two

codepen

Body:
Is background-image what you're looking for?

HTML

<div id=RowDivWithBackground class=row>
</div>

CSS

.RowDivWithBackground {
    background-image: url('url/to/image');
    other-css-do-dads /*Probably some rgba action*/
}


问:
Application report for application_ (state: ACCEPTED) never ends for Spark Submit (with Spark 1.2.0 on YARN)
I am running kinesis plus spark application
https://spark.apache.org/docs/1.2.0/streaming-kinesis-integration.html

I am running as below

command on ec2 instance :

```<code> ./spark/bin/spark-submit --class org.apache.spark.examples.streaming.myclassname --master yarn-cluster --num-executors 2 --driver-memory 1g --executor-memory 1g --executor-cores 1  /home/hadoop/test.jar
</code>```

I have installed spark on EMR.

```<code>EMR details
Master instance group - 1   Running MASTER  m1.medium
1

Core instance group - 2 Running CORE    m1.medium
</code>```

I am getting below INFO and it never ends.

```<code>15/06/14 11:33:23 INFO yarn.Client: Requesting a new application from cluster with 2 NodeManagers
15/06/14 11:33:23 INFO yarn.Client: Verifying our application has not requested more than the maximum memory capability of the cluster (2048 MB per container)
15/06/14 11:33:23 INFO yarn.Client: Will allocate AM container, with 1408 MB memory including 384 MB overhead
15/06/14 11:33:23 INFO yarn.Client: Setting up container launch context for our AM
15/06/14 11:33:23 INFO yarn.Client: Preparing resources for our AM container
15/06/14 11:33:24 INFO yarn.Client: Uploading resource file:/home/hadoop/.versions/spark-1.3.1.e/lib/spark-assembly-1.3.1-hadoop2.4.0.jar -> hdfs://172.31.13.68:9000/user/hadoop/.sparkStaging/application_1434263747091_0023/spark-assembly-1.3.1-hadoop2.4.0.jar
15/06/14 11:33:29 INFO yarn.Client: Uploading resource file:/home/hadoop/test.jar -> hdfs://172.31.13.68:9000/user/hadoop/.sparkStaging/application_1434263747091_0023/test.jar
15/06/14 11:33:31 INFO yarn.Client: Setting up the launch environment for our AM container
15/06/14 11:33:31 INFO spark.SecurityManager: Changing view acls to: hadoop
15/06/14 11:33:31 INFO spark.SecurityManager: Changing modify acls to: hadoop
15/06/14 11:33:31 INFO spark.SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop)
15/06/14 11:33:31 INFO yarn.Client: Submitting application 23 to ResourceManager
15/06/14 11:33:31 INFO impl.YarnClientImpl: Submitted application application_1434263747091_0023
15/06/14 11:33:32 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:32 INFO yarn.Client:
         client token: N/A
         diagnostics: N/A
         ApplicationMaster host: N/A
         ApplicationMaster RPC port: -1
         queue: default
         start time: 1434281611893
         final status: UNDEFINED
         tracking URL: http://172.31.13.68:9046/proxy/application_1434263747091_0023/
         user: hadoop
15/06/14 11:33:33 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:34 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:35 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:36 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:37 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:38 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:39 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:40 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:41 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
</code>```

Could somebody please let me know as  why it's not working ?

答:
There are three ways we can try to fix this issue.

Check for spark process on your machine and kill it.

Do

```<code>ps aux | grep spark
</code>```

Take all the process id's with spark processes and kill them, like

```<code>sudo kill -9 4567 7865
</code>```

Check for number of spark applications running on your cluster.

To check this, do

```<code>yarn application -list
</code>```

you will get an output similar to this:

```<code>Total number of applications (application-types: [] and states: [SUBMITTED, ACCEPTED, RUNNING]):1
                Application-Id      Application-Name        Application-Type          User       Queue               State         Final-State         Progress                        Tracking-URL
application_1496703976885_00567       ta da                SPARK        cloudera       default             RUNNING           UNDEFINED              20%             http://10.0.52.156:9090
</code>```

Check for the application id's, if they are more than 1, or more than 2, kill them. Your cluster cannot run more than 2 spark applications at the same time. I am not 100% sure about this, but on cluster if you run more than two spark applications, it will start complaining. So, kill them
Do this to kill them:

```<code>yarn application -kill application_1496703976885_00567
</code>```

Check for your spark config parameters.
For example, if you have set more executor memory or driver memory or number of executors on your spark application that may also cause an issue. So, reduce of any of them and run your spark application, that might resolve it.

Body:
I am running kinesis plus spark application
https://spark.apache.org/docs/1.2.0/streaming-kinesis-integration.html

I am running as below

command on ec2 instance :

 ./spark/bin/spark-submit --class org.apache.spark.examples.streaming.myclassname --master yarn-cluster --num-executors 2 --driver-memory 1g --executor-memory 1g --executor-cores 1  /home/hadoop/test.jar

I have installed spark on EMR.

EMR details
Master instance group - 1   Running MASTER  m1.medium
1

Core instance group - 2 Running CORE    m1.medium

I am getting below INFO and it never ends.

15/06/14 11:33:23 INFO yarn.Client: Requesting a new application from cluster with 2 NodeManagers
15/06/14 11:33:23 INFO yarn.Client: Verifying our application has not requested more than the maximum memory capability of the cluster (2048 MB per container)
15/06/14 11:33:23 INFO yarn.Client: Will allocate AM container, with 1408 MB memory including 384 MB overhead
15/06/14 11:33:23 INFO yarn.Client: Setting up container launch context for our AM
15/06/14 11:33:23 INFO yarn.Client: Preparing resources for our AM container
15/06/14 11:33:24 INFO yarn.Client: Uploading resource file:/home/hadoop/.versions/spark-1.3.1.e/lib/spark-assembly-1.3.1-hadoop2.4.0.jar -> hdfs://172.31.13.68:9000/user/hadoop/.sparkStaging/application_1434263747091_0023/spark-assembly-1.3.1-hadoop2.4.0.jar
15/06/14 11:33:29 INFO yarn.Client: Uploading resource file:/home/hadoop/test.jar -> hdfs://172.31.13.68:9000/user/hadoop/.sparkStaging/application_1434263747091_0023/test.jar
15/06/14 11:33:31 INFO yarn.Client: Setting up the launch environment for our AM container
15/06/14 11:33:31 INFO spark.SecurityManager: Changing view acls to: hadoop
15/06/14 11:33:31 INFO spark.SecurityManager: Changing modify acls to: hadoop
15/06/14 11:33:31 INFO spark.SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop)
15/06/14 11:33:31 INFO yarn.Client: Submitting application 23 to ResourceManager
15/06/14 11:33:31 INFO impl.YarnClientImpl: Submitted application application_1434263747091_0023
15/06/14 11:33:32 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:32 INFO yarn.Client:
         client token: N/A
         diagnostics: N/A
         ApplicationMaster host: N/A
         ApplicationMaster RPC port: -1
         queue: default
         start time: 1434281611893
         final status: UNDEFINED
         tracking URL: http://172.31.13.68:9046/proxy/application_1434263747091_0023/
         user: hadoop
15/06/14 11:33:33 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:34 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:35 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:36 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:37 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:38 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:39 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:40 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
15/06/14 11:33:41 INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)

Could somebody please let me know as  why it's not working ?

Body:
There are three ways we can try to fix this issue.

Check for spark process on your machine and kill it.

Do

ps aux | grep spark

Take all the process id's with spark processes and kill them, like

sudo kill -9 4567 7865

Check for number of spark applications running on your cluster.

To check this, do

yarn application -list

you will get an output similar to this:

Total number of applications (application-types: [] and states: [SUBMITTED, ACCEPTED, RUNNING]):1
                Application-Id      Application-Name        Application-Type          User       Queue               State         Final-State         Progress                        Tracking-URL
application_1496703976885_00567       ta da                SPARK        cloudera       default             RUNNING           UNDEFINED              20%             http://10.0.52.156:9090

Check for the application id's, if they are more than 1, or more than 2, kill them. Your cluster cannot run more than 2 spark applications at the same time. I am not 100% sure about this, but on cluster if you run more than two spark applications, it will start complaining. So, kill them
Do this to kill them:

yarn application -kill application_1496703976885_00567

Check for your spark config parameters.
For example, if you have set more executor memory or driver memory or number of executors on your spark application that may also cause an issue. So, reduce of any of them and run your spark application, that might resolve it.


答:
If you really need to use the img-tag, try to use position: fixed and z-index: -1 (or -2, -3, ...)

.container {
  border: 4px solid red;
  position: relative;
}

#imageAsBackground {
  z-index: -1;
  position: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQWTPbXeQy0Sy6xCbSwL_Vc4oQtMS-UNkUPOwRb3TxWHKKNlZ5Ycg" id="imageAsBackground" alt="" />
  </div>
  <div class="row">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
</div></code>```

If you could use the image as a real background, try to use css for this then.

Like

.container{
  border: 4px solid red;
}

.coolBackground {
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQWTPbXeQy0Sy6xCbSwL_Vc4oQtMS-UNkUPOwRb3TxWHKKNlZ5Ycg");
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row coolBackground">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
</div></code>```

background-size: cover; will adjust the image to the width of your div.

Title: How can I display image behind div with bootstrap?

Body:
If you really need to use the img-tag, try to use position: fixed and z-index: -1 (or -2, -3, ...)

.container {
  border: 4px solid red;
  position: relative;
}

#imageAsBackground {
  z-index: -1;
  position: fixed;
}

<div class="container">
  <div class="row">
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQWTPbXeQy0Sy6xCbSwL_Vc4oQtMS-UNkUPOwRb3TxWHKKNlZ5Ycg" id="imageAsBackground" alt="" />
  </div>
  <div class="row">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
</div>

If you could use the image as a real background, try to use css for this then.

Like

.container{
  border: 4px solid red;
}

.coolBackground {
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQWTPbXeQy0Sy6xCbSwL_Vc4oQtMS-UNkUPOwRb3TxWHKKNlZ5Ycg");
  background-size: cover;
}

<div class="container">
  <div class="row coolBackground">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
</div>

background-size: cover; will adjust the image to the width of your div.


问:
Find latitude and longitude of a location
For the application I am developing, for a given latitude and longitude in degrees, I need to find a new lat and long at a distance of 500 meters away from it (any direction i.e. north,south,east,west is fine).
I have found bunch of responses on stack exchange and tried them out but honestly at this point I am really frustrated and tired.
Could somebody dumb it down for me on how do I go about achieving this?

P.S. my application requires small distances that is < 500 meters

答:
In java script your function for generating Random lat-lon will be </p>

```<code>function randomGeo(center_latitude,center_longitude, radius) {
    var y0 = center_latitude;
    var x0 = center_longitude;
    var rd = radius / 111300;

    var u = Math.random();
    var v = Math.random();

    var w = rd * Math.sqrt(u);
    var t = 2 * Math.PI * v;
    var x = w * Math.cos(t);
    var y = w * Math.sin(t);

    //Adjust the x-coordinate for the shrinking of the east-west distances
    var xp = x / Math.cos(y0);

    var newlat = y + y0;
    var newlon = x + x0;
console.log(newlat+","+newlon);
}
</code>```

<p>parameter radius is in meters. Test those function like </p>

```<code> randomGeo(22.541161, 88.355040,50);
</code>```

Body:
In java script your function for generating Random lat-lon will be

function randomGeo(center_latitude,center_longitude, radius) {
    var y0 = center_latitude;
    var x0 = center_longitude;
    var rd = radius / 111300;

    var u = Math.random();
    var v = Math.random();

    var w = rd * Math.sqrt(u);
    var t = 2 * Math.PI * v;
    var x = w * Math.cos(t);
    var y = w * Math.sin(t);

    //Adjust the x-coordinate for the shrinking of the east-west distances
    var xp = x / Math.cos(y0);

    var newlat = y + y0;
    var newlon = x + x0;
console.log(newlat+","+newlon);
}

parameter radius is in meters. Test those function like

 randomGeo(22.541161, 88.355040,50);


问:
detecting native objects with reflection
I am working with a reflection based object translator.

it basically loops through properties of an object, and assigns the values to properties with the same name/type on the translated object.

ObjectA.Name = "Joe"

translates to:

ObjectB.Name = "Joe"

I need to put a special case, for when a property is a custom class such as:

ObjectA.Address

i was hoping i could detect such properties with IsClass flag of PropertyType

```<code>propInfo.PropertyType.IsClass
</code>```

but this flag also appears to return true for string properties.

is there another way i could verify that the property is of a non native type?

答:
I'm assuming you want to determine if the target type is not a primative.  You can probably use TypeCode for that, for instance:

```<code>public bool IsNotCoreType(Type type)
{
    return (type != typeof(object) && Type.GetTypeCode(type) == TypeCode.Object);
}
</code>```

Any non-primitive should return TypeCode.Object as the result of Type.GetTypeCode, so we can check that we get that and that the type itself is not System.Object.

Perhaps that would help?

UPDATE: I've renamed the method to IsNotCoreType to cover both primitives and non-primitives such as String, DateTime, etc. (see comments below).

Body:
I am working with a reflection based object translator.

it basically loops through properties of an object, and assigns the values to properties with the same name/type on the translated object.

ObjectA.Name = "Joe"

translates to:

ObjectB.Name = "Joe"

I need to put a special case, for when a property is a custom class such as:

ObjectA.Address

i was hoping i could detect such properties with IsClass flag of PropertyType

propInfo.PropertyType.IsClass

but this flag also appears to return true for string properties.

is there another way i could verify that the property is of a non native type?

Body:
I'm assuming you want to determine if the target type is not a primative.  You can probably use TypeCode for that, for instance:

public bool IsNotCoreType(Type type)
{
    return (type != typeof(object) && Type.GetTypeCode(type) == TypeCode.Object);
}

Any non-primitive should return TypeCode.Object as the result of Type.GetTypeCode, so we can check that we get that and that the type itself is not System.Object.

Perhaps that would help?

UPDATE: I've renamed the method to IsNotCoreType to cover both primitives and non-primitives such as String, DateTime, etc. (see comments below).


问:
Selenium IDE: Select random from dropdown
I using Selenium IDE for my automated tests.

And right now I have to select a random post from a dropdown.

How do I do that using xpath?

答:
Try following solution :

Command: Select

Target : element Locator eg : id = card

Value : index=1

Hope it will work for you.


问:
doinbackground() method is not called in aync task
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

```<code>private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}
</code>```

Any help is appreciated.
Thank you

答:
You can not directly use the context in doInBackground() because it runs in background and the background thread can not change the UI appearance,
Instead of this, you can make Toast in onPreExecute() or onPostExecute(Result)

If you face error in

Toast.makeText(PostActivity.this,"Error while downloading",Toast.LENGTH_LONG).show();

For that you can also use the  getApplicationContext() method or create context variable.

```<code>Context c;
......
protected void onCreate(Bundle savedInstanceState) {
        ...
        c = this;
        ...
}
......
class Task extends AsyncTask<Void,Void,Void>{
.......
        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(c, "Alert Posted", Toast.LENGTH_LONG).show();
            //OR
            Toast.makeText(getApplicationContext(), "Alert Posted", Toast.LENGTH_LONG).show();
        }
    }
</code>```

Body:
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}

Any help is appreciated.
Thank you

Body:
You can not directly use the context in doInBackground() because it runs in background and the background thread can not change the UI appearance,
Instead of this, you can make Toast in onPreExecute() or onPostExecute(Result)

If you face error in

Toast.makeText(PostActivity.this,"Error while downloading",Toast.LENGTH_LONG).show();

For that you can also use the  getApplicationContext() method or create context variable.

Context c;
......
protected void onCreate(Bundle savedInstanceState) {
        ...
        c = this;
        ...
}
......
class Task extends AsyncTask<Void,Void,Void>{
.......
        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(c, "Alert Posted", Toast.LENGTH_LONG).show();
            //OR
            Toast.makeText(getApplicationContext(), "Alert Posted", Toast.LENGTH_LONG).show();
        }
    }