问:
Spinner scrolls to default selection on touching in Android 7.0
I am using a spinner in my application, and a custom adapter to populate entries in the spinner. Everything works fine, like clicking on it, setting selection value, etc., but when I try to scroll on the spinner, the spinner itself moves to the default selection position irrespective of where it is, be it at the top or bottom, as soon as I touch it again to scroll, I am placed to the default selection.

You can find the adapter, spinner declaration and spinner item in the codes below.

Spinner.xml

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingStart="8dp"
android:paddingTop="8dp"
android:paddingBottom="8dp">

    <Spinner
        android:id="@+id/toolbar_spinner"
        style="@style/ToolbarSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

spinner_item.xml

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:background="?attr/selectableItemBackground">

    <View
        android:id="@+id/line_separator"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="@color/divider"
        android:layout_gravity="center"
        android:paddingStart="16dp"
        android:layout_marginLeft="8dp"
        android:visibility="gone"
        tools:visibility="visible"/>

    <TextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|start|left"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"
        android:textColor="@color/black_dropdown"
        android:textSize="18sp"
        android:ellipsize="end"
        android:maxLines="1"
        tools:text="test"
        />
</LinearLayout>
</code>```

Below is the code that shows how I call the spinner adapter.:

```<code>SpinnerAdapter adapter = new SpinnerAdapter(mHelperActivity.getSupportActionBar().getThemedContext(), item_list);
mSpinner.setAdapter(adapter);
mSpinner.setDropDownWidth((Utilities.getScreenWidth(getContext()) * 3) / 4);
mSpinner.setSelection(Caches.getSelectedCategoryPosition());
</code>```

I have tried setting custom theme, custom popuptheme but to no gain.

P.S.: This only happens in Android 7, it works perfectly fine in Android 6 or less.

答:
Try to remove style from spinner

style="@style/ToolbarSpinner"

```<code><Spinner
    android:id="@+id/toolbar_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</code>```

I had the same problem and in my case it was using themes (popupTheme and theme)

```<code>   <Spinner android:id="@+id/spinner"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"
                     android:gravity="bottom"
                     local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                     local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                    >
</code>```

Body:
I am using a spinner in my application, and a custom adapter to populate entries in the spinner. Everything works fine, like clicking on it, setting selection value, etc., but when I try to scroll on the spinner, the spinner itself moves to the default selection position irrespective of where it is, be it at the top or bottom, as soon as I touch it again to scroll, I am placed to the default selection.

You can find the adapter, spinner declaration and spinner item in the codes below.

Spinner.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingStart="8dp"
android:paddingTop="8dp"
android:paddingBottom="8dp">

    <Spinner
        android:id="@+id/toolbar_spinner"
        style="@style/ToolbarSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

spinner_item.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:background="?attr/selectableItemBackground">

    <View
        android:id="@+id/line_separator"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="@color/divider"
        android:layout_gravity="center"
        android:paddingStart="16dp"
        android:layout_marginLeft="8dp"
        android:visibility="gone"
        tools:visibility="visible"/>

    <TextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|start|left"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"
        android:textColor="@color/black_dropdown"
        android:textSize="18sp"
        android:ellipsize="end"
        android:maxLines="1"
        tools:text="test"
        />
</LinearLayout>

Below is the code that shows how I call the spinner adapter.:

SpinnerAdapter adapter = new SpinnerAdapter(mHelperActivity.getSupportActionBar().getThemedContext(), item_list);
mSpinner.setAdapter(adapter);
mSpinner.setDropDownWidth((Utilities.getScreenWidth(getContext()) * 3) / 4);
mSpinner.setSelection(Caches.getSelectedCategoryPosition());

I have tried setting custom theme, custom popuptheme but to no gain.

P.S.: This only happens in Android 7, it works perfectly fine in Android 6 or less.

Body:
Try to remove style from spinner

style="@style/ToolbarSpinner"

<Spinner
    android:id="@+id/toolbar_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

I had the same problem and in my case it was using themes (popupTheme and theme)

   <Spinner android:id="@+id/spinner"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"
                     android:gravity="bottom"
                     local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                     local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                    >


来源: stackexchange

问:
Grouped UITableView with multiple sections creating problem in iPhone SDK
In my iPhone app, I am having a grouped table view. I have used viewForHeaderInSection method to change the font color and size of font of section headers.

I have 4 sections in the tableview.

Problem

If there is no data in Section 0 and section 1 then too Section 2 starts to display in table somewhere near center of the view instead of top of the screen.

I want that when section 0 and section 1 cells are empty the section 2 should come at the top of the view as if it is section 0.

How should I proceed?

答: It is just a suggestion, but you can try to set the height of the view of your headers to 0 if the section is empty.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
PHP to JQuery code conversion [If else]
How can I do it on JQuery? When I click hide, the element will be hidden, same goes for show, the element will be shown. How am I going to do it? Thanks!

```<code><form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="submit" >Show</button>

</form>

<?php

    if (isset($_POST['hidden']) == true){
        echo '*hidden*';
    } else if ($_POST['']) {
        echo 'shown';
    }

?>
</code>```

答:
An equivalent of your code on jQuery would be the next:

$(() => {
    $("#hide-but").on("click", () => $("#result").html("*hidden*"));
    $("#show-but").on("click", () => $("#result").html("shown"));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="button-group">
  <button type="submit" name="hidden" id="hide-but">Hide</button>
  <button type="submit" name="submit" id="show-but">Show</button>
</div>

<div id="result">shown</div></code>```

ContentLicense: CC BY-SA 3.0

Title: PHP to JQuery code conversion [If else]

Body:
How can I do it on JQuery? When I click hide, the element will be hidden, same goes for show, the element will be shown. How am I going to do it? Thanks!

<form method="POST">

<button type="submit" name="hidden" >Hide</button>
<button type="submit" name="submit" >Show</button>

</form>

<?php

    if (isset($_POST['hidden']) == true){
        echo '*hidden*';
    } else if ($_POST['']) {
        echo 'shown';
    }

?>

Body:
An equivalent of your code on jQuery would be the next:

$(() => {
    $("#hide-but").on("click", () => $("#result").html("*hidden*"));
    $("#show-but").on("click", () => $("#result").html("shown"));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="button-group">
  <button type="submit" name="hidden" id="hide-but">Hide</button>
  <button type="submit" name="submit" id="show-but">Show</button>
</div>

<div id="result">shown</div>


问:
Advisory locks scope in postgresql
I am new to postgresql and trying to understand advisory locks. I have the following two scenarios:

With different databases in two different sessions: (Works in expected manner)

Session 1: SELECT pg_advisory_lock(1); Successfully acquires the lock

Session 2 (note in different database): SELECT pg_advisory_lock(1); Successfully acquires the lock

With Different Schemas in same database: When I do the same operation, the second 'session' blocks.

It appears that advisory locks operate at database level rather than (database and schema) combination. Is my assumption correct or is there anything I am missing?

答:
In postgres schema is a namespace. More than just a prefix, but less than another database. in your case two, second session not "blocks", but rather is waiting as per docs:

If another session already holds a lock on the same resource
  identifier, this function will wait until the resource becomes
  available.

Regarding  successful locking on different databases:
After you run SELECT pg_advisory_lock(1); checkout pg_locks, column objid

OID of the lock target within its system catalog, or null if the
  target is not a general database object

So this number is per database - you can reference same 1 for many databases - those will be different OIDs.

Title: Advisory locks scope in postgresql


问:
Styling the html buttons with CSS/Css3?
I want to style the buttons with CSS3. Is there any way to style them? </p>

```<code><input name="button" type="button" class="abt2" onClick="html2entities(this.form.data1)" onMouseOver="this.className='abt2 abt2hov'" onMouseOut="this.className='abt2'" value="Convert">
      <input onMouseOver="this.className='abt3 abt3hov'" onMouseOut="this.className='abt3'" class="abt3" name="Clear" value="  Clear  " type="reset">
</code>```

答:
don't use abt3 abt3hov.

use abt3:hover

.abt3 { background-color: brown; color:red}
.abt3:hover { color:white; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="abt3" name="Clear" value="  Clear  " type="reset"></code>```

Title: Styling the html buttons with CSS/Css3?

Body:
I want to style the buttons with CSS3. Is there any way to style them?

<input name="button" type="button" class="abt2" onClick="html2entities(this.form.data1)" onMouseOver="this.className='abt2 abt2hov'" onMouseOut="this.className='abt2'" value="Convert">
      <input onMouseOver="this.className='abt3 abt3hov'" onMouseOut="this.className='abt3'" class="abt3" name="Clear" value="  Clear  " type="reset">

Body:
don't use abt3 abt3hov.

use abt3:hover

.abt3 { background-color: brown; color:red}
.abt3:hover { color:white; }

<input class="abt3" name="Clear" value="  Clear  " type="reset">


问:
Broadcast dot product in tensorflow
In tensorflow, I have the following problem.

I have a tensor m of shape [batch_size, dim_a, dim_b] and a matrix u of shape [batch_size, dim_b].

```<code>M = tf.constant(shape=[batch_size, sequence_size, embed_dim])
U = tf.constant(shape=[batch_size, embed_dim])
</code>```

What I what to achieve is the dot product of  [i, dim_a, dim_b] x [i, dim_b] for each index of my batch.

```<code>P[i] = tf.matmul(M[i, :, :], tf.expand_dims(U[i, :], 1)) for each i.
</code>```

Basically, broadacast the dot product over the batch axis. Is this possible and how can I achieve it?

答:
This can be achieved with tf.einsum():

```<code>import tensorflow as tf
import numpy as np

batch_size = 2
sequence_size = 3
embed_dim = 4

M = tf.constant(range(batch_size * sequence_size * embed_dim), shape=[batch_size, sequence_size, embed_dim])
U = tf.constant(range(batch_size, embed_dim), shape=[batch_size, embed_dim])

prod = tf.einsum('bse,be->bs', M, U)

with tf.Session():
  print "M"
  print M.eval()
  print
  print "U"
  print U.eval()
  print
  print "einsum result"
  print prod.eval()
  print

  print "numpy, example 0"
  print np.matmul(M.eval()[0], U.eval()[0])
  print
  print "numpy, example 1"
  print np.matmul(M.eval()[1], U.eval()[1])
</code>```

Output:

```<code>M
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

U
[[2 3 3 3]
 [3 3 3 3]]

einsum result
[[ 18  62 106]
 [162 210 258]]

numpy, example 0
[ 18  62 106]

numpy, example 1
[162 210 258]
</code>```

Title: Broadcast dot product in tensorflow

Body:
In tensorflow, I have the following problem.

I have a tensor m of shape [batch_size, dim_a, dim_b] and a matrix u of shape [batch_size, dim_b].

M = tf.constant(shape=[batch_size, sequence_size, embed_dim])
U = tf.constant(shape=[batch_size, embed_dim])

What I what to achieve is the dot product of  [i, dim_a, dim_b] x [i, dim_b] for each index of my batch.

P[i] = tf.matmul(M[i, :, :], tf.expand_dims(U[i, :], 1)) for each i.

Basically, broadacast the dot product over the batch axis. Is this possible and how can I achieve it?

Body:
This can be achieved with tf.einsum():

import tensorflow as tf
import numpy as np

batch_size = 2
sequence_size = 3
embed_dim = 4

M = tf.constant(range(batch_size * sequence_size * embed_dim), shape=[batch_size, sequence_size, embed_dim])
U = tf.constant(range(batch_size, embed_dim), shape=[batch_size, embed_dim])

prod = tf.einsum('bse,be->bs', M, U)

with tf.Session():
  print "M"
  print M.eval()
  print
  print "U"
  print U.eval()
  print
  print "einsum result"
  print prod.eval()
  print

  print "numpy, example 0"
  print np.matmul(M.eval()[0], U.eval()[0])
  print
  print "numpy, example 1"
  print np.matmul(M.eval()[1], U.eval()[1])

Output:

M
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

U
[[2 3 3 3]
 [3 3 3 3]]

einsum result
[[ 18  62 106]
 [162 210 258]]

numpy, example 0
[ 18  62 106]

numpy, example 1
[162 210 258]


问:
ValueError: The given username must be set
I'm trying register a user in my project, but when I try to do it I get next error:

ValueError: The given username must be set

In my project I'm using Django 1.11 and AngularJS 1.6

View.py

```<code>def registrarCliente(request):
    if request.method=='POST':
        usuariosfinales=[]
        nombre=request.POST.get('nombre')
        email=request.POST.get('email')
        password=request.POST.get('password')

        user=User.objects.create_user(email, email, password)
        user.save()

        usermodelo=Usuario(usuario=user, nombre=nombre)
        usermodelo.save()

        userfinal=authenticate(username=email, password=password)
        login(request, userfinal)

        usuariosfinales.append(userfinal)

        data=serializers.serialize('json', usuariosfinales)

        return HttpResponse(data, content_type="application/json")

    return render (request, "login/login.html")
</code>```

login.html

```<code><div class="login-wrap" id="login" ng-app="appLogin" ng-controller="conLogin">
  <div class="login-right striped-bg" ng-show="Registro">
    <div class="login-form">
      <div class="heading">
        ¡Registrate!
      </div>
      <div class="input">

        {% csrf_token %}

        <div class="login-input-group spacer-field">
          <span class="login-input-group-addon">
            <i class="fa fa-user fa-fw"></i>
          </span>
          <input type="text" class="form-control" name="nombre" placeholder="Nombre" ng-model="user.nombre">
        </div>
        <div class="login-input-group spacer-field">
          <span class="login-input-group-addon">
            <i class="fa fa-at fa-fw"></i>
          </span>
          <input type="email" class="form-control" name="email" placeholder="Correo electrónico" ng-model="user.email">
        </div>
        <div class="login-input-group spacer-field">
          <span class="login-input-group-addon">
            <i class="fa fa-key fa-fw"></i>
          </span>
          <input type="password" class="form-control" name="password" placeholder="Contraseña" ng-model="user.password">
        </div>
        <div class="login-input-group">
          <span class="login-input-group-addon">
            <i class="fa fa-key fa-fw"></i>
          </span>
          <input type="password" class="form-control" name="password2" placeholder="Repetir contraseña">
        </div>

        <button class="btn btn-default btn-lg submit" type="submit" ng-click="registrar()">Registrarme</button>
      </div>
    </div>
  </div>
</div>
</code>```

appLogin.js

```<code>(function(angular) {

// body...
angular
    .module('appLogin', [])
    .controller('conLogin', ['$scope', '$http', function($scope, $http){
        //Registro de usuario
        $scope.user = {nombre:'', email:'', password:''};

        $scope.registrar = function(email, password){
            $http({method:'POST',
                url:'/registro/',
                data:{nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password}
            }).then(
                function(response2){
                    window.location.href='';
                },function(response2){
                    $scope.user = response2.data || 'Request failed';
                }
            );
        }

        $scope.Ingreso = true;
        $scope.Registro = false;

        $scope.cambioRegistro = function(){
            $scope.Ingreso = false;
            $scope.Registro = true;
        }

        $scope.cambioIngreso = function(){
            $scope.Ingreso = true;
            $scope.Registro = false;
        }
    }])

var my_app = angular
    .module('appLogin').config(
        function($interpolateProvider, $httpProvider) {
            $interpolateProvider.startSymbol('{$');
            $interpolateProvider.endSymbol('$}');
            $httpProvider.defaults.xsrfCookieName = 'csrftoken';
            $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
            $httpProvider.defaults.withCredentials = true;
            $httpProvider.defaults.cache = true;
        }
    );

})(window.angular);
</code>```

The debug page says me that my error is in:

user=User.objects.create_user(email, email, password)

But I don't understand why.

答:
Take it easy please!

```<code>user = User(email = email, username= email, password =password)
user.save()
</code>```

Just make sure the name SAME AS model you use.

Don't make it hard yo use

Body:
I'm trying register a user in my project, but when I try to do it I get next error:

ValueError: The given username must be set

In my project I'm using Django 1.11 and AngularJS 1.6

View.py

def registrarCliente(request):
    if request.method=='POST':
        usuariosfinales=[]
        nombre=request.POST.get('nombre')
        email=request.POST.get('email')
        password=request.POST.get('password')

        user=User.objects.create_user(email, email, password)
        user.save()

        usermodelo=Usuario(usuario=user, nombre=nombre)
        usermodelo.save()

        userfinal=authenticate(username=email, password=password)
        login(request, userfinal)

        usuariosfinales.append(userfinal)

        data=serializers.serialize('json', usuariosfinales)

        return HttpResponse(data, content_type="application/json")

    return render (request, "login/login.html")

login.html

        ¡Registrate!

        {% csrf_token %}

          <input type="text" class="form-control" name="nombre" placeholder="Nombre" ng-model="user.nombre">

          <input type="email" class="form-control" name="email" placeholder="Correo electrónico" ng-model="user.email">

          <input type="password" class="form-control" name="password" placeholder="Contraseña" ng-model="user.password">

          <input type="password" class="form-control" name="password2" placeholder="Repetir contraseña">

        <button class="btn btn-default btn-lg submit" type="submit" ng-click="registrar()">Registrarme</button>

appLogin.js

(function(angular) {

// body...
angular
    .module('appLogin', [])
    .controller('conLogin', ['$scope', '$http', function($scope, $http){
        //Registro de usuario
        $scope.user = {nombre:'', email:'', password:''};

        $scope.registrar = function(email, password){
            $http({method:'POST',
                url:'/registro/',
                data:{nombre: $scope.user.nombre, email: $scope.user.email, password: $scope.user.password}
            }).then(
                function(response2){
                    window.location.href='';
                },function(response2){
                    $scope.user = response2.data || 'Request failed';
                }
            );
        }

        $scope.Ingreso = true;
        $scope.Registro = false;

        $scope.cambioRegistro = function(){
            $scope.Ingreso = false;
            $scope.Registro = true;
        }

        $scope.cambioIngreso = function(){
            $scope.Ingreso = true;
            $scope.Registro = false;
        }
    }])

var my_app = angular
    .module('appLogin').config(
        function($interpolateProvider, $httpProvider) {
            $interpolateProvider.startSymbol('{$');
            $interpolateProvider.endSymbol('$}');
            $httpProvider.defaults.xsrfCookieName = 'csrftoken';
            $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
            $httpProvider.defaults.withCredentials = true;
            $httpProvider.defaults.cache = true;
        }
    );

})(window.angular);

The debug page says me that my error is in:

user=User.objects.create_user(email, email, password)

But I don't understand why.

Body:
Take it easy please!

user = User(email = email, username= email, password =password)
user.save()

Just make sure the name SAME AS model you use.

Don't make it hard yo use


问:
Prevent thread blocking in Tomcat
I have a Java servlet that acts as a facade to other webservices deployed on the same Tomcat instance. My wrapper servlet creates N more threads, each which invokes a webservice, collates the response and sends it back to the client. The webservices are deployed all on the same Tomcat instance as different applications.

I am seeing thread blocking on this facade wrapper service after a few hours of deployment which brings down the Tomcat instance. All blocked threads are endpoints to this facade webservice (like http://domain/appContext/facadeService)

Is there a way to control such thread-blocking, due to starvation of available threads that actually do the processing? What are the best practices to prevent such deadlocks?

答:
The common solution to this problem is to use the Executor framework. You need to express your web service call as Callable and pass it to the executor either as it stands, or as a Collection<Callable> (see the Javadoc for complete list of options).

You have two choices to control the time. First is to use parameters of an appropriate method of the Executor class where you specify the max web service timeout. Another option is to do get the result (which is expressed as Future<T>) and use .get(long, TimeUnit) to specify the maximum amount of time you can wait for a result.

Title: Prevent thread blocking in Tomcat


问:
Finding the longest border of a string
First, let me tell you what the border of a string is,

```<code>let x = "abacab"
let y = "ababab"
</code>```

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

答:
This simple solution with a single loop works just fine:

```<code>function findLongestBorder($s){
    $a = 0;
    $b = 1;
    $n = strlen($s);

    while($b<$n){
        if($s[$a]==$s[$b]){
            $a++;
        }else{
            $b-= $a;
            $a = 0;
        }
        $b++;
    }

    return substr($s,0,$a);
}
</code>```

Example:

```<code>echo findLongestBorder("abacab")."\n";
echo findLongestBorder("ababab")."\n";
echo findLongestBorder("abcde hgrab abcde")."\n";
echo findLongestBorder("bacab")."\n";
echo findLongestBorder("abacababac")."\n";
</code>```

Output:

```<code>ab
abab
abcde
b
abac
</code>```

See https://eval.in/812640

Title: Finding the longest border of a string

Body:
First, let me tell you what the border of a string is,

let x = "abacab"
let y = "ababab"

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

Body:
This simple solution with a single loop works just fine:

function findLongestBorder($s){
    $a = 0;
    $b = 1;
    $n = strlen($s);

    while($b<$n){
        if($s[$a]==$s[$b]){
            $a++;
        }else{
            $b-= $a;
            $a = 0;
        }
        $b++;
    }

    return substr($s,0,$a);
}

Example:

echo findLongestBorder("abacab")."\n";
echo findLongestBorder("ababab")."\n";
echo findLongestBorder("abcde hgrab abcde")."\n";
echo findLongestBorder("bacab")."\n";
echo findLongestBorder("abacababac")."\n";

Output:

ab
abab
abcde
b
abac

See https://eval.in/812640


问:
Replace array value with new one
I have array of array, where i want to change date format. I am trying to get it as below

```<code>foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}
</code>```

here format gets changed but it is not replacing array value with new one?? Why??

答:
You should use the refrence operator & to change in the original array otherwise PHP treats it as local aary which is diffrent from the original one and the changes in that local array will not reflects to original array.

```<code>foreach ($toReturn as &$value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}
</code>```

Title: Replace array value with new one

Body:
I have array of array, where i want to change date format. I am trying to get it as below

foreach ($toReturn as $value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}

here format gets changed but it is not replacing array value with new one?? Why??

Body:
You should use the refrence operator & to change in the original array otherwise PHP treats it as local aary which is diffrent from the original one and the changes in that local array will not reflects to original array.

foreach ($toReturn as &$value) {

    $start_date = new DateTime($value['start_date']);
    $value['start_date'] = $start_date->format('m-d-Y');

    $end_date = new DateTime($value['end_date']);
    $value['end_date'] = $end_date->format('m-d-Y');
}


问:
Speed up creation of mysql table (from select)
I've got a query that runs in about 1.6 seconds and returns 150Kish rows.  I have been building a memory engine based temp table from this query and this operation takes about 6.5 seconds.  I've sifted through lots of documentation on the mysql site as well as futzed with indexes on the temp table (hardly any difference at all when I have indexes vs not having them) trying to find some way for the table creation to be a bit better performing.  Does anybody have any suggestions with respect to config options that may speed up creating an in memory temp table (or non temp table)?  To clear up what exactly I'm looking for (I think) is some sort of table config options that may increase the speed of the creation.  I've gone through most of the ones listed on the mysql 5.7 site but nothing seems to change the time it takes to create the temp/standard table in memory.  </p>

```<code>CREATE TEMPORARY TABLE
IF NOT EXISTS myTempTable
(ugID INT,stID INT, INDEX st (`st`) )
ENGINE=MEMORY AS
select ugID, stID
from a_complex_query_that_runs_in_under_2_seconds_but_takes_6_to_write_to_a_temptable_with_150k_rows

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived15> ALL NULL    NULL    NULL    NULL    559
1   PRIMARY creatorEntity   eq_ref  PRIMARY PRIMARY 4   creatorAssignment.OwnerObjectID 1   Using index
1   PRIMARY <derived2>  ALL NULL    NULL    NULL    NULL    152580  Using where; Using join buffer
15  DERIVED VMAssignment    ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where
2   DERIVED test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    214 Using where; Using temporary; Using filesort
2   DERIVED cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CustomFieldID   4   testCloud.test_.AssignmentValue 4232    Using where
2   DERIVED ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
3   UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where; Using temporary; Using filesort
3   UNION   cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CFValue 772 func,func   4   Using where
3   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
4   UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
5   UNION   test_   index_merge AssociatedObjectID,AssociatedObject AssociatedObjectID,AssociatedObject 4,6 NULL    1   Using intersect(AssociatedObjectID,AssociatedObject); Using where; Using index; Using temporary; Using filesort
5   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
5   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
6   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.State 1   Using where
7   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
7   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
7   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.Zip   1   Using where
8   UNION   test_   range   AssociatedObjectID,AssociatedObject AssociatedObjectID  4   NULL    150 Using where; Using temporary; Using filesort
8   UNION   entity_ ref PRIMARY,ClassName,Address   Address 456 func,func   4   Using where
8   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
9   UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    203 Using where; Using temporary; Using filesort
9   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
10  UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
11  UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObjectID  4       1   Using where; Using temporary; Using filesort
11  UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
11  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
12  UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObject    2       2902    Using where; Using temporary; Using filesort
12  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
13  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    239 Using where; Using temporary; Using filesort
13  UNION   list_stores ref VMListID,VMStoreID,VMStoreID_2,VMStoreID_3,VMStoreID_4,VMStoreID_5,VMStoreID_6,VMStoreID_7,VMStoreID_8,VMStoreID_9,VMStoreID_10,VMStoreID_11,VMStoreID_12,VMStoreID_13,VMStoreID_14,VMStoreID_15,VMStoreID_16   VMListID    4   testCloud.test_.AssignmentValue 318 Using where
13  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.list_stores.VMStoreID 1   Using index
14  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    70  Using where; Using temporary; Using filesort
14  UNION   sto_    ref PRIMARY,RetailerID  RetailerID  4   testCloud.test_.AssignmentValue 63  Using where; Using index
14  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.sto_.ID   1   Using index
NULL    UNION RESULT    <union2,3,4,5,6,7,8,9,10,11,12,13,14>   ALL NULL    NULL    NULL    NULL    NULL
</code>```

答:
First thing to do is to figure out where the bottleneck is. As others have suggested in the comments, it isn't in filling up the temporary table.

Inserting 150k rows

This takes about 5 seconds. Woah, which leaves me looking foolish, but I will redeem myself later.

```<code>   $dbh->query('CREATE TEMPORARY TABLE IF NOT EXISTS myTempTable (ugID INT,stID INT, INDEX st (`st`) r ');
   $dbh->beginTransaction();

   $stmt = $dbh->prepare("INSERT INTO myTempTable(ugId,stID) values(:u, :s)");

   for ($i=0; $i < 150000 ; $i++) {
       $stmt->execute(array("u"=> $i, "s"=> $i));
   }
   $res = $dbh->query("SELECT COUNT(*) from myTempTable");

   $dbh->commit();
</code>```

CREATE TABLE LIKE

The above experiment is a poor one because it's looping 150k times and indeed it maybe. But what if we created a permanent table as above and then did CREATE TABLE LIKE (this is the original problem after all)

BTW Removing the TEMPORARY keyword from the above code increased the time to about 9 seconds. And now in the mysql console.

```<code>mysql> CREATE TEMPORARY TABLE  IF NOT EXISTS myTempTable  (ugID INT,stID INT, INDEX st (`stId`) )  ENGINE=MEMORY AS (SELECT * FROM ugTable);
Query OK, 150000 rows affected (0.17 sec)
Records: 150000  Duplicates: 0  Warnings: 0
</code>```

Fraction of a second. So clearly what's at fault is the way that the data is loaded rather than the process of filling up the table.

Reduce IO.

Your complex query reads a lot of row. 150k rows in a set of large tables is a lot of IO. You can speed this up a great deal by making sure that the server has enough memory to cache the entire set of tables involved here in memory.

That would be a lot easier, if the size of the data on disk was smaller. Perhaps time to re examine your tables and see if there is a normalization  step you missed. Time to see if some of the indexes can be changed. For example you have some hefty indexes like AssignmentValue 768. Even when these indexes are used, that's still quite a lot of IO.

All this data has to be read on disk before loading up 150k of them into the temporary table which is in memory.

Body:
I've got a query that runs in about 1.6 seconds and returns 150Kish rows.  I have been building a memory engine based temp table from this query and this operation takes about 6.5 seconds.  I've sifted through lots of documentation on the mysql site as well as futzed with indexes on the temp table (hardly any difference at all when I have indexes vs not having them) trying to find some way for the table creation to be a bit better performing.  Does anybody have any suggestions with respect to config options that may speed up creating an in memory temp table (or non temp table)?  To clear up what exactly I'm looking for (I think) is some sort of table config options that may increase the speed of the creation.  I've gone through most of the ones listed on the mysql 5.7 site but nothing seems to change the time it takes to create the temp/standard table in memory.

CREATE TEMPORARY TABLE
IF NOT EXISTS myTempTable
(ugID INT,stID INT, INDEX st (`st`) )
ENGINE=MEMORY AS
select ugID, stID
from a_complex_query_that_runs_in_under_2_seconds_but_takes_6_to_write_to_a_temptable_with_150k_rows

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived15> ALL NULL    NULL    NULL    NULL    559
1   PRIMARY creatorEntity   eq_ref  PRIMARY PRIMARY 4   creatorAssignment.OwnerObjectID 1   Using index
1   PRIMARY <derived2>  ALL NULL    NULL    NULL    NULL    152580  Using where; Using join buffer
15  DERIVED VMAssignment    ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where
2   DERIVED test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    214 Using where; Using temporary; Using filesort
2   DERIVED cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CustomFieldID   4   testCloud.test_.AssignmentValue 4232    Using where
2   DERIVED ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
3   UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObject    2       2902    Using where; Using temporary; Using filesort
3   UNION   cfv_    ref CustomFieldID,EntityID,CFEntity,CFValue,CFEntityValue   CFValue 772 func,func   4   Using where
3   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.cfv_.EntityID 1   Using index
4   UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
5   UNION   test_   index_merge AssociatedObjectID,AssociatedObject AssociatedObjectID,AssociatedObject 4,6 NULL    1   Using intersect(AssociatedObjectID,AssociatedObject); Using where; Using index; Using temporary; Using filesort
5   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
5   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
6   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
6   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.State 1   Using where
7   UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where; Using temporary; Using filesort
7   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
7   UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssignmentValue 768 testCloud.entity_.Zip   1   Using where
8   UNION   test_   range   AssociatedObjectID,AssociatedObject AssociatedObjectID  4   NULL    150 Using where; Using temporary; Using filesort
8   UNION   entity_ ref PRIMARY,ClassName,Address   Address 456 func,func   4   Using where
8   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
9   UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    203 Using where; Using temporary; Using filesort
9   UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
10  UNION   test_   const   PRIMARY PRIMARY 4       1   Using index
11  UNION   test_   ref AssociatedObjectID,AssociatedObject AssociatedObjectID  4       1   Using where; Using temporary; Using filesort
11  UNION   entity_ ref PRIMARY,ClassName   ClassName   2       23326   Using where
11  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.entity_.ID    1   Using index
12  UNION   test_   ref AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObject    2       2902    Using where; Using temporary; Using filesort
12  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.test_.AssignmentValue 1   Using where; Using index
13  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    239 Using where; Using temporary; Using filesort
13  UNION   list_stores ref VMListID,VMStoreID,VMStoreID_2,VMStoreID_3,VMStoreID_4,VMStoreID_5,VMStoreID_6,VMStoreID_7,VMStoreID_8,VMStoreID_9,VMStoreID_10,VMStoreID_11,VMStoreID_12,VMStoreID_13,VMStoreID_14,VMStoreID_15,VMStoreID_16   VMListID    4   testCloud.test_.AssignmentValue 318 Using where
13  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.list_stores.VMStoreID 1   Using index
14  UNION   test_   range   AssignmentValue,AssociatedObjectID,AssociatedObject,assignmentQuery AssociatedObjectID  4   NULL    70  Using where; Using temporary; Using filesort
14  UNION   sto_    ref PRIMARY,RetailerID  RetailerID  4   testCloud.test_.AssignmentValue 63  Using where; Using index
14  UNION   ent_    ref VMStoreID   VMStoreID   4   testCloud.sto_.ID   1   Using index
NULL    UNION RESULT    <union2,3,4,5,6,7,8,9,10,11,12,13,14>   ALL NULL    NULL    NULL    NULL    NULL

Body:
First thing to do is to figure out where the bottleneck is. As others have suggested in the comments, it isn't in filling up the temporary table.

Inserting 150k rows

This takes about 5 seconds. Woah, which leaves me looking foolish, but I will redeem myself later.

   $dbh->query('CREATE TEMPORARY TABLE IF NOT EXISTS myTempTable (ugID INT,stID INT, INDEX st (`st`) r ');
   $dbh->beginTransaction();

   $stmt = $dbh->prepare("INSERT INTO myTempTable(ugId,stID) values(:u, :s)");

   for ($i=0; $i < 150000 ; $i++) {
       $stmt->execute(array("u"=> $i, "s"=> $i));
   }
   $res = $dbh->query("SELECT COUNT(*) from myTempTable");

   $dbh->commit();

CREATE TABLE LIKE

The above experiment is a poor one because it's looping 150k times and indeed it maybe. But what if we created a permanent table as above and then did CREATE TABLE LIKE (this is the original problem after all)

BTW Removing the TEMPORARY keyword from the above code increased the time to about 9 seconds. And now in the mysql console.

mysql> CREATE TEMPORARY TABLE  IF NOT EXISTS myTempTable  (ugID INT,stID INT, INDEX st (`stId`) )  ENGINE=MEMORY AS (SELECT * FROM ugTable);
Query OK, 150000 rows affected (0.17 sec)
Records: 150000  Duplicates: 0  Warnings: 0

Fraction of a second. So clearly what's at fault is the way that the data is loaded rather than the process of filling up the table.

Reduce IO.

Your complex query reads a lot of row. 150k rows in a set of large tables is a lot of IO. You can speed this up a great deal by making sure that the server has enough memory to cache the entire set of tables involved here in memory.

That would be a lot easier, if the size of the data on disk was smaller. Perhaps time to re examine your tables and see if there is a normalization  step you missed. Time to see if some of the indexes can be changed. For example you have some hefty indexes like AssignmentValue 768. Even when these indexes are used, that's still quite a lot of IO.

All this data has to be read on disk before loading up 150k of them into the temporary table which is in memory.


问:
PHP rand from list
What is the best way of doing this ?

```<code>rand('Helloworld','Hi world');
</code>```

I know this is not working as rand needs a min and max number, but what is the solution for this ?

答:
Something likes that:</p>

```<code><?php
$array = array(1, 2, 3);
$array[ mt_rand( 0, count($array) -1 ) ];
?>
</code>```

Title: PHP rand from list

Body:
What is the best way of doing this ?

rand('Helloworld','Hi world');

I know this is not working as rand needs a min and max number, but what is the solution for this ?

Body:
Something likes that:

<?php
$array = array(1, 2, 3);
$array[ mt_rand( 0, count($array) -1 ) ];
?>


问:
required percentage of column
I have three column a,b,c I want to fill true or false in the 'c' column if the value of 'b' column under or above 10% of 'a' column ............
actually, I want to update column 'b' if the value nearest column a </p>

```<code>a   |  b   |  c
100 | 90   | true
100 | 110  | true
100 | 88   | false
</code>```

<p>I want to generate a query in PostgreSQL </p>

答:
I think you can try this  :

```<code>SELECT a, b, CASE WHEN ABS(a-b) <=0.1*a THEN TRUE ELSE FALSE END AS c
FROM yourtable;
</code>```

Output:

```<code>    a   b   c
1   100 90  True
2   100 110 True
3   100 88  False
</code>```

About updating b, you didn't specify which value you want to use for b, but you can use something like this:

```<code>UPDATE yourtable SET b = <your value>
WHERE ABS(a-b) <=0.1*a;
</code>```

Title: required percentage of column

Body:
I have three column a,b,c I want to fill true or false in the 'c' column if the value of 'b' column under or above 10% of 'a' column ............
actually, I want to update column 'b' if the value nearest column a

a   |  b   |  c
100 | 90   | true
100 | 110  | true
100 | 88   | false

I want to generate a query in PostgreSQL

Body:
I think you can try this  :

SELECT a, b, CASE WHEN ABS(a-b) <=0.1*a THEN TRUE ELSE FALSE END AS c
FROM yourtable;

Output:

    a   b   c
1   100 90  True
2   100 110 True
3   100 88  False

About updating b, you didn't specify which value you want to use for b, but you can use something like this:

UPDATE yourtable SET b = <your value>
WHERE ABS(a-b) <=0.1*a;


问:
Android Gridview error , displaying last item incorrectly
i have a grid view, this is how i implement it

```<code><GridView
    android:horizontalSpacing="8dp"
    android:verticalSpacing="8dp"
    android:id="@+id/homeGrid"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:layout_weight="3"
    android:numColumns="auto_fit" />
</code>```

which aim to display 7 items using custom adapter, and this is how i implement the adapter

```<code>private Context mContext;
private final String[] item;
private final int[] imageId;

public GridAdapter(Context c, String[] item, int[] imageId) {
    mContext = c;
    this.item = item;
    this.imageId = imageId;
}

@Override
public int getCount() {
    return item.length;
}

@Override
public Object getItem(int position) {
    return item[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View grid;

    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        grid = inflater.inflate(R.layout.home_grid_layout, null);
        TextView textView = (TextView) grid.findViewById(R.id.grid_text);
        ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
        textView.setText(item[position]);
        imageView.setImageResource(imageId[position]);
    } else {
        grid = convertView;
    }
    return grid;

}
</code>```

}

and then i initiate it in my activity like this

GridAdapter adapter = new GridAdapter(HomePage.this, title, imageId);
        GridView grid = (GridView) findViewById(R.id.homeGrid);

the problem is that the app displaying the last position which is position 6 as position 0, strangly i implement onitemclicklistener to my gridview and i got the correct position when i click the last position.

where is my mistake ?

答:
Try this code.</p>

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) mContext
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.home_grid_layout, null);
    }

    TextView textView = (TextView) convertView.findViewById(R.id.grid_text);
    ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_image);

    textView.setText(item[position]);
    imageView.setImageResource(imageId[position]);

    return convertView;

}
</code>```

Body:
i have a grid view, this is how i implement it

<GridView
    android:horizontalSpacing="8dp"
    android:verticalSpacing="8dp"
    android:id="@+id/homeGrid"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:layout_weight="3"
    android:numColumns="auto_fit" />

which aim to display 7 items using custom adapter, and this is how i implement the adapter

private Context mContext;
private final String[] item;
private final int[] imageId;

public GridAdapter(Context c, String[] item, int[] imageId) {
    mContext = c;
    this.item = item;
    this.imageId = imageId;
}

@Override
public int getCount() {
    return item.length;
}

@Override
public Object getItem(int position) {
    return item[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View grid;

    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        grid = inflater.inflate(R.layout.home_grid_layout, null);
        TextView textView = (TextView) grid.findViewById(R.id.grid_text);
        ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
        textView.setText(item[position]);
        imageView.setImageResource(imageId[position]);
    } else {
        grid = convertView;
    }
    return grid;

}

}

and then i initiate it in my activity like this

GridAdapter adapter = new GridAdapter(HomePage.this, title, imageId);
        GridView grid = (GridView) findViewById(R.id.homeGrid);

the problem is that the app displaying the last position which is position 6 as position 0, strangly i implement onitemclicklistener to my gridview and i got the correct position when i click the last position.

where is my mistake ?

Body:
Try this code.

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) mContext
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.home_grid_layout, null);
    }

    TextView textView = (TextView) convertView.findViewById(R.id.grid_text);
    ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_image);

    textView.setText(item[position]);
    imageView.setImageResource(imageId[position]);

    return convertView;

}


问:
I get an error when I try to install BeautifulSoup4
What is wrong?

here is a screenshot

答:
Run the install command with elevated privileges.

sudo pip install bs4

Body:
What is wrong?

here is a screenshot


问:
Select all affected rows by rowspaned cell on datagridview
I have the below

What I want is, when i select the BOX00099 cell, the three rows right to be selected.
Also, when i select one of those three rows, the other two rows and the BOX00099 to be selected.
So, the idea is to consider all the three rows as a single row.

答:
I solved the problem and for those who may have the same problem as me, that's how I did it:

I used an extended datagridview instead the normal one.

```<code>public partial class DataGridViewEx : DataGridView
{
    public DataGridViewEx()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
    }

    protected override void SetSelectedRowCore(int rowIndex, bool selected)
    {
        this.SuspendLayout();
        base.SetSelectedRowCore(rowIndex, selected);
        int index = rowIndex;
        while (index < this.Rows.Count - 1 && this.Rows[index].Cells["BoxNo"].Value.ToString() == this.Rows[index + 1].Cells["BoxNo"].Value.ToString())
        {
            base.SetSelectedRowCore(index + 1, selected);
            index = index + 1;
        }
        index = rowIndex;
        while (index > 0 && this.Rows[index].Cells["BoxNo"].Value.ToString() == this.Rows[index - 1].Cells["BoxNo"].Value.ToString())
        {
            base.SetSelectedRowCore(index - 1, selected);
            index = index - 1;
        }
        this.ResumeLayout();
    }
}
</code>```

Then I add the columns from this project. The project has a demo, so you have an example how to use it. To span a cell, I use

```<code>var cell = (DataGridViewTextBoxCellEx)dataGridView1[0, index];
            int nr = (int)dataGridView1.Rows[index].Cells["Nr"].Value;
            cell.RowSpan = nr;
</code>```

After that, to go from the "3 spaned row" to another row with the key up/down, I has to press the up/down botton 3 times (selecting every row one by one from the "3 spaned row". To solve this, I use it the key press event as above:

```<code> private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (dataGridView1.Rows.Count > 0)
        {
            int current = dataGridView1.CurrentRow.Index;
            if (e.KeyData == Keys.Down)
            {
                e.Handled = true;
                dataGridView1.SuspendLayout();
                for (int i = current; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.CurrentRow.Cells["BoxNo"].Value.ToString() != dataGridView1.Rows[i].Cells["BoxNo"].Value.ToString())
                    {
                        dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells["BoxNo"];
                        break;
                    }
                }
                dataGridView1.ResumeLayout();
            }
            else if (e.KeyData == Keys.Up)
            {
                e.Handled = true;
                dataGridView1.SuspendLayout();
                for (int i = current; i >= 0; i--)
                {
                    if (dataGridView1.CurrentRow.Cells["BoxNo"].Value.ToString() != dataGridView1.Rows[i].Cells["BoxNo"].Value.ToString())
                    {
                        dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells["BoxNo"];
                        break;
                    }
                }
                dataGridView1.ResumeLayout();
            }
        }
    }
</code>```

Body:
I solved the problem and for those who may have the same problem as me, that's how I did it:

I used an extended datagridview instead the normal one.

public partial class DataGridViewEx : DataGridView
{
    public DataGridViewEx()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
    }

    protected override void SetSelectedRowCore(int rowIndex, bool selected)
    {
        this.SuspendLayout();
        base.SetSelectedRowCore(rowIndex, selected);
        int index = rowIndex;
        while (index < this.Rows.Count - 1 && this.Rows[index].Cells["BoxNo"].Value.ToString() == this.Rows[index + 1].Cells["BoxNo"].Value.ToString())
        {
            base.SetSelectedRowCore(index + 1, selected);
            index = index + 1;
        }
        index = rowIndex;
        while (index > 0 && this.Rows[index].Cells["BoxNo"].Value.ToString() == this.Rows[index - 1].Cells["BoxNo"].Value.ToString())
        {
            base.SetSelectedRowCore(index - 1, selected);
            index = index - 1;
        }
        this.ResumeLayout();
    }
}

Then I add the columns from this project. The project has a demo, so you have an example how to use it. To span a cell, I use

var cell = (DataGridViewTextBoxCellEx)dataGridView1[0, index];
            int nr = (int)dataGridView1.Rows[index].Cells["Nr"].Value;
            cell.RowSpan = nr;

After that, to go from the "3 spaned row" to another row with the key up/down, I has to press the up/down botton 3 times (selecting every row one by one from the "3 spaned row". To solve this, I use it the key press event as above:

 private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (dataGridView1.Rows.Count > 0)
        {
            int current = dataGridView1.CurrentRow.Index;
            if (e.KeyData == Keys.Down)
            {
                e.Handled = true;
                dataGridView1.SuspendLayout();
                for (int i = current; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.CurrentRow.Cells["BoxNo"].Value.ToString() != dataGridView1.Rows[i].Cells["BoxNo"].Value.ToString())
                    {
                        dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells["BoxNo"];
                        break;
                    }
                }
                dataGridView1.ResumeLayout();
            }
            else if (e.KeyData == Keys.Up)
            {
                e.Handled = true;
                dataGridView1.SuspendLayout();
                for (int i = current; i >= 0; i--)
                {
                    if (dataGridView1.CurrentRow.Cells["BoxNo"].Value.ToString() != dataGridView1.Rows[i].Cells["BoxNo"].Value.ToString())
                    {
                        dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells["BoxNo"];
                        break;
                    }
                }
                dataGridView1.ResumeLayout();
            }
        }
    }


问:
Debugging with Pdb file and Source Code File in Visual Studio
I have a web project that posts from client-side code to a method in external dll, which I have source code file and pdb file of this external dll. What I would like to do is to debug external dll using source code file and pdb. Visual studio does not stop to say no symbols are loaded for the module since.</p>

答:
To debug a  a symbol file with the same version is always needed. When you are debugging your own applications you usually don't have to care about this.

But there are things happening in the background. Visual Studio always puts the symbol files in the debug folder when you build your application and also loads them as described under Loading the symbols automatic.

(When you distribute your application you usually do not want to distribute those symbols and therefore they won't be copied to the release directory you change your build configuration to release.)

Loading the symbols manually

If you want to load the symbols manually you can load them with the Modules dialog.

"Debug" -> "Windows" -> "Modules".

You can right click a row and there is the option "Load Symbols" which lets you specify a PDB file to load.

Loading the symbols automatically

Visual studio also loads the symbols automatically when they can be found in one of the the places listed in the Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger documentation:

The location that is specified inside the DLL or the executable file.

(By default, if you have built a DLL or an executable file on your computer, the linker places the full path and file name of the associated .pdb file inside the DLL or the executable file. The debugger first checks to see if the symbol file exists in the location that is specified inside the DLL or the executable file. This is helpful, because you always have symbols available for code that you have compiled on your computer.)

.pdb files that could be present in the same folder as the DLL or executable file.

Any local symbol cache folders.

Any network, internet, or local symbol servers and locations that are specified on, such as the Microsoft symbol server if enabled.

If you want to read more about how the symbols are used with visual studio you can read this article about Understanding symbol files and Visual Studio’s symbol settings.


问:
Which is the better framework to build a HTML survey builder?
I’ve to build a HTML survey builder application with an AJAXified user interface (i.e.Wufoo,...).

The typical survey will be multistep with multi-dependencies between form fields/questions, public access most of the time, and export results to PDF + CSV.

Have been studying/testing some PHP frameworks ( CodeIgniter, Symfony and CakePHP).
I like CakePHP, but I read a lot of good stuff about Django and RoR (especially RoR for form building...)...

...so the question: which is the better framework to build a HTML survey builder?

答:
My personal opinion is that Zend Framework is the best in cases like this one. It's very modular and it also provides nice export components.

You would probably be interested in Zend Ajax and Zend_Pdf components. You can also use most of them as standalone classes.

You can find a list and documentation with examples of all Zend Frameworks components here.

OwnerDisplayName: madlogs

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Maiku Mori


问:
How to enable stacktrace react-native run-android command?
I'm running a react native project via the react-native run-android. But during the build it fails stating that :react-native-device-info:processReleaseResources FAILED. Which doesn't give much info, so I tried running with react-native run-android --stacktrace as suggested but that isn't a recognized command.

How can you enable stacktrace / verbose logging with react-native run-android command?

This is the detail of the error which is too short to figure out at build:

```<code>:react-native-device-info:processReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-device-info:processReleaseResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\Brian\AppData\Local\Android\sdk\build-tools\23.0.1\aapt.exe'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: -12.542 secs
</code>```

Package.json for reference:

```<code>{
  "name": "StarterKit",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "jest": {
    "preset": "react-native",
    "setupFiles": [
      "<rootDir>/jest.setup.js"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|tcomb-form-native|apsl-react-native-button,react-native-device-info|react-clone-referenced-element)"
    ],
    "collectCoverage": true,
    "verbose": true
  },
  "dependencies": {
    "html-entities": "^1.2.0",
    "jwt-decode": "^2.1.0",
    "qs": "^6.3.0",
    "react": "15.4.2",
    "react-addons-shallow-compare": "^15.4.2",
    "react-native": "^0.40.0",
    "react-native-device-info": "^0.9.6",
    "react-native-elements": "^0.9.2",
    "react-native-google-analytics-bridge": "git+https://github.com/mcnamee/react-native-google-analytics-bridge.git",
    "react-native-router-flux": "^3.37.0",
    "react-native-side-menu": "^0.20.1",
    "react-native-tab-view": "0.0.48",
    "react-native-vector-icons": "^4.0.0",
    "react-redux": "^5.0.1",
    "redux": "^3.6.0",
    "redux-logger": "^2.7.0",
    "redux-thunk": "^2.1.0",
    "striptags": "^2.1.1",
    "tcomb-form-native": "^0.6.1"
  },
  "devDependencies": {
    "babel-core": "^6.17.0",
    "babel-eslint": "^7.1.0",
    "babel-jest": "18.0.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react-native": "1.9.1",
    "babel-register": "^6.16.3",
    "eslint": "^3.9.1",
    "eslint-config-airbnb": "^14.0.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^3.0.2",
    "eslint-plugin-react": "^6.4.1",
    "invariant": "^2.2.2",
    "jest": "18.1.0",
    "jest-react-native": "^18.0.0",
    "react-test-renderer": "15.4.2"
  }
}
</code>```

build.gradle file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:2.1.0'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            mavenLocal()
            jcenter()
            maven {
                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                url "$rootDir/../node_modules/react-native/android"
            }
        }
    }
</code>```

答:
@EricHua23's answer is basically correct, except that instead of running ./gradlew assembleDebug --stacktrace, you should run ./gradlew.bat installDebug --stacktrace, as this is the command that's actually run by react-native run-android. (and some of the errors you'd want to get the stack-trace for only occur in the installing/late-build portion, rather than the assembly portion)

Also, make sure you run it in the android folder. (so run cd android in the console before running the gradlew command)

Body:
I'm running a react native project via the react-native run-android. But during the build it fails stating that :react-native-device-info:processReleaseResources FAILED. Which doesn't give much info, so I tried running with react-native run-android --stacktrace as suggested but that isn't a recognized command.

How can you enable stacktrace / verbose logging with react-native run-android command?

This is the detail of the error which is too short to figure out at build:

:react-native-device-info:processReleaseResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-device-info:processReleaseResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\Brian\AppData\Local\Android\sdk\build-tools\23.0.1\aapt.exe'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: -12.542 secs

Package.json for reference:

{
  "name": "StarterKit",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "jest": {
    "preset": "react-native",
    "setupFiles": [
      "<rootDir>/jest.setup.js"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|tcomb-form-native|apsl-react-native-button,react-native-device-info|react-clone-referenced-element)"
    ],
    "collectCoverage": true,
    "verbose": true
  },
  "dependencies": {
    "html-entities": "^1.2.0",
    "jwt-decode": "^2.1.0",
    "qs": "^6.3.0",
    "react": "15.4.2",
    "react-addons-shallow-compare": "^15.4.2",
    "react-native": "^0.40.0",
    "react-native-device-info": "^0.9.6",
    "react-native-elements": "^0.9.2",
    "react-native-google-analytics-bridge": "git+https://github.com/mcnamee/react-native-google-analytics-bridge.git",
    "react-native-router-flux": "^3.37.0",
    "react-native-side-menu": "^0.20.1",
    "react-native-tab-view": "0.0.48",
    "react-native-vector-icons": "^4.0.0",
    "react-redux": "^5.0.1",
    "redux": "^3.6.0",
    "redux-logger": "^2.7.0",
    "redux-thunk": "^2.1.0",
    "striptags": "^2.1.1",
    "tcomb-form-native": "^0.6.1"
  },
  "devDependencies": {
    "babel-core": "^6.17.0",
    "babel-eslint": "^7.1.0",
    "babel-jest": "18.0.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react-native": "1.9.1",
    "babel-register": "^6.16.3",
    "eslint": "^3.9.1",
    "eslint-config-airbnb": "^14.0.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^3.0.2",
    "eslint-plugin-react": "^6.4.1",
    "invariant": "^2.2.2",
    "jest": "18.1.0",
    "jest-react-native": "^18.0.0",
    "react-test-renderer": "15.4.2"
  }
}

build.gradle file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:2.1.0'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            mavenLocal()
            jcenter()
            maven {
                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                url "$rootDir/../node_modules/react-native/android"
            }
        }
    }


问:
ConcatMap interupted when error in one observable
I have the following code:

```<code>Observable.from(modifiedNodes)
    .concatMap(node => {
        return this.Model.setData(node);
    })
    .subscribe(() => {
        NodeSaved++;
    }
</code>```

If setData throws an error for any intermediate node, the next sequence of nodes are not getting resumed. How we can modify it so that even if there is an error for one node, the next sequence of nodes will be executed? I read about onErrorResumeNext but I'm not sure how to use it here.

The method signature for setData is as follows:

```<code>public setData(node: INode): Observable<Object>{}
</code>```

答:
If setData returns an observable, you can use the catch operator. It will receive any errors thrown from within setData and if you return an empty observable, concatMap will move to the next node in the sequence:

import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/catch';

Observable
  .from(modifiedNodes)
  .concatMap(node => this.Model
    .setData(node)
    .catch(error => Observable.empty())
  )
  .subscribe(() => { NodeSaved++; });
```

Body:
I have the following code:

Observable.from(modifiedNodes)
    .concatMap(node => {
        return this.Model.setData(node);
    })
    .subscribe(() => {
        NodeSaved++;
    }

If setData throws an error for any intermediate node, the next sequence of nodes are not getting resumed. How we can modify it so that even if there is an error for one node, the next sequence of nodes will be executed? I read about onErrorResumeNext but I'm not sure how to use it here.

The method signature for setData is as follows:

public setData(node: INode): Observable<Object>{}


问:
How can I add a different legend for different quantiles in the same graph in ggplot2?
```<code>           ggplotRegression <- function (fit) {

            require(ggplot2)

           ggplot(fit$model, aes_string(x = names(fit$model)[2], y =
          names(fit$model)[1])) +
            geom_point() +
            stat_smooth(method = "lm", col = "red") +
            labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared,
              5),
                   "Intercept =",signif(fit$coef[[1]],5 ),
                   " Slope =",signif(fit$coef[[2]], 5),
                   " P =",signif(summary(fit)$coef[2,4], 5)))
</code>```

}

```<code>               taus <-c(0.05  , 0.25, 0.50 , 0.75, 0.90 , 0.95)

                m <- ggplotRegression( lm(formula = BMI ~   height_in_m
                  +weight_in_kg+ Highest_Education_level +
                   wealth_index + age_in_year_groups, data = dat_new))

             m+geom_quantile(quantiles=taus, lwd=1.5 , col="green4",
             fill=taus)
</code>```

Now I want to add specific colours for each quantiles and also add spcific legend for each quantiles .

答:
Many ggplot statistics let you use the results of the calculation enclosed in .., for example with geom_density you can use ..count.. in the aes.

With geom_quantile you can use ..quantile..

```<code>df <- data_frame(x = rnorm(100), y = rnorm(100))
ggplot(df, aes(x, y)) +
  geom_point() +
  geom_quantile(aes(colour = as.factor(..quantile..)))
</code>```

The trick is to find out what these variables are called. Geoms that need to calculate statistics, such as geom_quantile and geom_density, have an associated ggproto object such as StatQuantile and StatDensity which has the code for the calculations in an element called compute_group.

The last command of StatQuantile$compute_group is

```<code>    plyr::ldply(quantiles, quant_pred, data = data, method = method,
    formula = formula, weight = weight, grid = grid, method.args = method.args)
</code>```

The function here, quant_pred - which you can see with ggplot2:::quant_pred, returns a list. The components of this list, including quantile, can be used in the aes.

Body:
           ggplotRegression <- function (fit) {

            require(ggplot2)

           ggplot(fit$model, aes_string(x = names(fit$model)[2], y =
          names(fit$model)[1])) +
            geom_point() +
            stat_smooth(method = "lm", col = "red") +
            labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared,
              5),
                   "Intercept =",signif(fit$coef[[1]],5 ),
                   " Slope =",signif(fit$coef[[2]], 5),
                   " P =",signif(summary(fit)$coef[2,4], 5)))

}

               taus <-c(0.05  , 0.25, 0.50 , 0.75, 0.90 , 0.95)

                m <- ggplotRegression( lm(formula = BMI ~   height_in_m
                  +weight_in_kg+ Highest_Education_level +
                   wealth_index + age_in_year_groups, data = dat_new))

             m+geom_quantile(quantiles=taus, lwd=1.5 , col="green4",
             fill=taus)

Now I want to add specific colours for each quantiles and also add spcific legend for each quantiles .

Body:
Many ggplot statistics let you use the results of the calculation enclosed in .., for example with geom_density you can use ..count.. in the aes.

With geom_quantile you can use ..quantile..

df <- data_frame(x = rnorm(100), y = rnorm(100))
ggplot(df, aes(x, y)) +
  geom_point() +
  geom_quantile(aes(colour = as.factor(..quantile..)))

The trick is to find out what these variables are called. Geoms that need to calculate statistics, such as geom_quantile and geom_density, have an associated ggproto object such as StatQuantile and StatDensity which has the code for the calculations in an element called compute_group.

The last command of StatQuantile$compute_group is

    plyr::ldply(quantiles, quant_pred, data = data, method = method,
    formula = formula, weight = weight, grid = grid, method.args = method.args)

The function here, quant_pred - which you can see with ggplot2:::quant_pred, returns a list. The components of this list, including quantile, can be used in the aes.


问:
I'm unable to setup selenium grid for appium server with two devices on mac
I'm trying to run appium scripts on multiple devices in parallel. For that I tried setup appium server(appium v1.6.3) using selenium grid.

Approach I followed:
1. Created Hub.json file

Created nodeconfig json files for two devices

Placed all of them in one folder along with selenium-server-standalone-2.53.0.jar file

In terminal, run the command:

java -jar selenium-server-standalone-2.53.0.jar -role hub -hubConfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/hub.json

and then run nodeconfig,

node appium --nodeconfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/iPadmini.json -p 4723

I see below error here:

```<code>CH0006s-Mac-mini:lib CH0006$ node appium --nodeconfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/iPadmini.json -p 4040
/Applications/Appium.app/Contents/Resources/node_modules/appium/lib/appium.js:1
(function (exports, require, module, __filename, __dirname) { import _ from 'loads';

SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
</code>```

Note: Appium.js doesn't exist in bin folder, so that I used path of lib folder where appium.js exists.

Configurations:

Hub.json:

```<code>{
"newSessionWaitTimeout" : -1,
"timeout" : 30000,
 "capabilityMatcher" : "org.openga.grid.internal.utils.DefaultCapabilityMatcher",
 "servlets" : [],
  "maxSession" : 5,
  "prioritizer" : null,
"host" : null,
"throwOnCapabilityNotPresent" : true,
  "nodePolling" : 5000,
"CleanUpCycle" : 5000,
"browserTimeout" : 90000,
 "port" : 4444
}
</code>```

device1.json:

```<code>{
"configuration" : {
"registerCycle" : 5000,
"timeout" : 600000,
"maxSession" : 1,
"cleanCycle" : 5000,
"nodeTimeout" : 120,
"hubHost" : "localhost",
"host" : "localhost",
"nodePolling" : 2000,
 "hubPort" : 4444,
"role" : "node",
},
"capabilities" : [
{
"platformName" : "iOS",
 "version" : "10.1.1",
"maxInstances" : 4,
 "deviceName" : "iPad mini",
"browserName" : "iOS",
 "platform" : "MAC"
}
]
}
</code>```

答:
Created Node.json file for each device, create one txt file for each device and place them in one folder

Place selenium-server-standalone-2.53.0.jar in same folder

Run java -jar selenium-server-standalone-2.53.0.jar -role hub in terminal going to that folder where jar is located

In other terminal window - run debug proxy ios_webkit_debug_proxy -c 7f5bc36b71a4d44161c128464c9d516d2ec3af94:27755 -d

In other terminal window - go to path where appium located - and run

node appium --session-override --nodeconfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/node3.json --show-ios-log --tmp /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/device2 -p 4730 --bootstrap-port 4467 --udid 7f5bc36b71a4d44161c128464c9d516d2ec3af94 --webkit-debug-proxy-port 27755 --full-reset --native-instruments-lib --safari > /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/iphone6s.txt

Note: If u r using appium v1.6 or above - better use ./node_modules/.bin/appium instead of node appium (It will find the appium path automatically)

```<code>6. Create one testng xml file in project and write code

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://www.testng.org/testng-1.0.dtd">
    <suite name="Default Suite" parallel="tests">
    <test verbose="2" name="Device1">
    <parameter name="Device_ID" value="6f307db6c72271c87b5936cf08aac61134001cc4" />
    <parameter name="wdaPort" value="8200" />
    <classes>
    <class name="SampleAppTest.SampleAppScan">
    <methods> <include name="ID1Scan"/> </methods>
    </class>
    </classes>
    </test>
</code>```

Create a class and write code to execute

Go to xml and run the test with testNG

Body:
I'm trying to run appium scripts on multiple devices in parallel. For that I tried setup appium server(appium v1.6.3) using selenium grid.

Approach I followed:
1. Created Hub.json file

Created nodeconfig json files for two devices

Placed all of them in one folder along with selenium-server-standalone-2.53.0.jar file

In terminal, run the command:

java -jar selenium-server-standalone-2.53.0.jar -role hub -hubConfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/hub.json

and then run nodeconfig,

node appium --nodeconfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/iPadmini.json -p 4723

I see below error here:

CH0006s-Mac-mini:lib CH0006$ node appium --nodeconfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/iPadmini.json -p 4040
/Applications/Appium.app/Contents/Resources/node_modules/appium/lib/appium.js:1
(function (exports, require, module, __filename, __dirname) { import _ from 'loads';

SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3

Note: Appium.js doesn't exist in bin folder, so that I used path of lib folder where appium.js exists.

Configurations:

Hub.json:

{
"newSessionWaitTimeout" : -1,
"timeout" : 30000,
 "capabilityMatcher" : "org.openga.grid.internal.utils.DefaultCapabilityMatcher",
 "servlets" : [],
  "maxSession" : 5,
  "prioritizer" : null,
"host" : null,
"throwOnCapabilityNotPresent" : true,
  "nodePolling" : 5000,
"CleanUpCycle" : 5000,
"browserTimeout" : 90000,
 "port" : 4444
}

device1.json:

{
"configuration" : {
"registerCycle" : 5000,
"timeout" : 600000,
"maxSession" : 1,
"cleanCycle" : 5000,
"nodeTimeout" : 120,
"hubHost" : "localhost",
"host" : "localhost",
"nodePolling" : 2000,
 "hubPort" : 4444,
"role" : "node",
},
"capabilities" : [
{
"platformName" : "iOS",
 "version" : "10.1.1",
"maxInstances" : 4,
 "deviceName" : "iPad mini",
"browserName" : "iOS",
 "platform" : "MAC"
}
]
}

Body:
Created Node.json file for each device, create one txt file for each device and place them in one folder

Place selenium-server-standalone-2.53.0.jar in same folder

Run java -jar selenium-server-standalone-2.53.0.jar -role hub in terminal going to that folder where jar is located

In other terminal window - run debug proxy ios_webkit_debug_proxy -c 7f5bc36b71a4d44161c128464c9d516d2ec3af94:27755 -d

In other terminal window - go to path where appium located - and run

node appium --session-override --nodeconfig /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/node3.json --show-ios-log --tmp /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/device2 -p 4730 --bootstrap-port 4467 --udid 7f5bc36b71a4d44161c128464c9d516d2ec3af94 --webkit-debug-proxy-port 27755 --full-reset --native-instruments-lib --safari > /Users/CH0006/Proj_Documentation/Testing/Appium/selenium_config/iphone6s.txt

Note: If u r using appium v1.6 or above - better use ./node_modules/.bin/appium instead of node appium (It will find the appium path automatically)

6. Create one testng xml file in project and write code

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://www.testng.org/testng-1.0.dtd">
    <suite name="Default Suite" parallel="tests">
    <test verbose="2" name="Device1">
    <parameter name="Device_ID" value="6f307db6c72271c87b5936cf08aac61134001cc4" />
    <parameter name="wdaPort" value="8200" />
    <classes>
    <class name="SampleAppTest.SampleAppScan">
    <methods> <include name="ID1Scan"/> </methods>
    </class>
    </classes>
    </test>

Create a class and write code to execute

Go to xml and run the test with testNG


问:
How to serve .jasper file with HTTP Server?
I am creating HTTP server with Tomee, i am placed jasper report file (.jasper) in webapp directory. if i access http://localhost:8080/test.jasper in browser, the browser will prompt to download the file.

In my java project i'm creating simple code to access that link and then preview the report. I use async-http-client library for request.

```<code>DefaultAsyncHttpClient client = new DefaultAsyncHttpClient();
BoundRequestBuilder brb = client.prepareGet("http://localhost:8765/qa/test.jasper");
Future<InputStream> f = brb.execute(new AsyncCompletionHandler<InputStream>() {
    @Override
    public InputStream onCompleted(Response resp) {
        try {
            String[][] data = {{"Jakarta"},{"Surabaya"},{"Solo"},{"Denpasar"}};
            String[] columnNames = {"City"};
            DefaultTableModel dtm = new DefaultTableModel(data, columnNames);

            Map<String,Object> params = new HashMap<>();

            JasperPrint jPrint = JasperFillManager.fillReport(
                resp.getResponseBodyAsStream(),
                params,
                new JRTableModelDataSource(dtm)
            );
            JasperViewer jpView = new JasperViewer(jPrint,false);
            jpView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            jpView.setSize(800, 600);
            jpView.setLocationRelativeTo(null);
            jpView.setVisible(true);

        } catch (JRException ex) {
            System.out.println(ex.getMessage());
        }
        return resp.getResponseBodyAsStream();
    }
});
</code>```

From my code above, i got an error Error loading object from InputStream

normally i can use

```<code>InputStream input = MainContext.class.getResourceAsStream(filename);
</code>```

But i want to replace file input stream with http request (stream too).

How exactly i can serve .jasper file with http server...?

答:
Error loading object from InputStream error came from corrupt InputStream, if i download .jasper file normally via browser and execute the report with JRLoader.loadObjectFromFile(path to file) it doesn't works too, because tomee give corrupt file (the source file not corrupt).

My own solution is read source file as stream, convert it to base64 encode, and serve it via HTTP API protocol.

```<code>finput = new FileInputStream(sPath);
byte[] bFile = Base64.getEncoder().encode(IOUtils.toByteArray(finput));

String sFile = new String(bFile);
</code>```

inside client side, i received it as body string, decode the base64 string, convert it to InputStream and Finally execute the report with InputStream.

```<code>byte[] bBody = Base64.getDecoder().decode(sBody);
InputStream mainReport = new ByteArrayInputStream(bBody);
return JasperFillManager.fillReport(mainReport, params);
</code>```

Body:
I am creating HTTP server with Tomee, i am placed jasper report file (.jasper) in webapp directory. if i access http://localhost:8080/test.jasper in browser, the browser will prompt to download the file.

In my java project i'm creating simple code to access that link and then preview the report. I use async-http-client library for request.

DefaultAsyncHttpClient client = new DefaultAsyncHttpClient();
BoundRequestBuilder brb = client.prepareGet("http://localhost:8765/qa/test.jasper");
Future<InputStream> f = brb.execute(new AsyncCompletionHandler<InputStream>() {
    @Override
    public InputStream onCompleted(Response resp) {
        try {
            String[][] data = {{"Jakarta"},{"Surabaya"},{"Solo"},{"Denpasar"}};
            String[] columnNames = {"City"};
            DefaultTableModel dtm = new DefaultTableModel(data, columnNames);

            Map<String,Object> params = new HashMap<>();

            JasperPrint jPrint = JasperFillManager.fillReport(
                resp.getResponseBodyAsStream(),
                params,
                new JRTableModelDataSource(dtm)
            );
            JasperViewer jpView = new JasperViewer(jPrint,false);
            jpView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            jpView.setSize(800, 600);
            jpView.setLocationRelativeTo(null);
            jpView.setVisible(true);

        } catch (JRException ex) {
            System.out.println(ex.getMessage());
        }
        return resp.getResponseBodyAsStream();
    }
});

From my code above, i got an error Error loading object from InputStream

normally i can use

InputStream input = MainContext.class.getResourceAsStream(filename);

But i want to replace file input stream with http request (stream too).

How exactly i can serve .jasper file with http server...?

Body:
Error loading object from InputStream error came from corrupt InputStream, if i download .jasper file normally via browser and execute the report with JRLoader.loadObjectFromFile(path to file) it doesn't works too, because tomee give corrupt file (the source file not corrupt).

My own solution is read source file as stream, convert it to base64 encode, and serve it via HTTP API protocol.

finput = new FileInputStream(sPath);
byte[] bFile = Base64.getEncoder().encode(IOUtils.toByteArray(finput));

String sFile = new String(bFile);

inside client side, i received it as body string, decode the base64 string, convert it to InputStream and Finally execute the report with InputStream.

byte[] bBody = Base64.getDecoder().decode(sBody);
InputStream mainReport = new ByteArrayInputStream(bBody);
return JasperFillManager.fillReport(mainReport, params);


问:
loop for multiple URLs
I am trying to scrape a web page with the following code:-

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs ={'class' :'details-panel'})
hrefs = [link['href'] for link in links]

for urls in hrefs:
    pages = requests.get(urls)
    soup_2 =BeautifulSoup(pages.content, 'html.parser')

    Date = soup_2.find_all('li', attrs ={'class' :'sold-date'})
    Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
    Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
    Address = [Address.text.strip() for Address in Address_1]
</code>```

the above code is returning only the details from the first URL in the hrefs.

```<code>['Mon 05-Jun-17'] ['261 Keilor Road, Essendon, Vic 3040']
</code>```

I need the loop to run through each URL in hrefs & return similar details from each URL in hrefs.
Please suggest what should i add/edit in the above code.
Any help would be highly appreciated.

Thanks

答:
It is behaving in correct manner.
 You need to store the information in an external list and then return it.</p>

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs ={'class' :'details-panel'})
hrefs = [link['href'] for link in links]
Data = []
for urls in hrefs:
    pages = requests.get(urls)
    soup_2 =BeautifulSoup(pages.content, 'html.parser')

    Date = soup_2.find_all('li', attrs ={'class' :'sold-date'})
    Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
    Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
    Address = [Address.text.strip() for Address in Address_1]
    Data.append(Sold_Date + Address)
return Data
</code>```

Title: loop for multiple URLs

Body:
I am trying to scrape a web page with the following code:-

import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs ={'class' :'details-panel'})
hrefs = [link['href'] for link in links]

for urls in hrefs:
    pages = requests.get(urls)
    soup_2 =BeautifulSoup(pages.content, 'html.parser')

    Date = soup_2.find_all('li', attrs ={'class' :'sold-date'})
    Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
    Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
    Address = [Address.text.strip() for Address in Address_1]

the above code is returning only the details from the first URL in the hrefs.

['Mon 05-Jun-17'] ['261 Keilor Road, Essendon, Vic 3040']

I need the loop to run through each URL in hrefs & return similar details from each URL in hrefs.
Please suggest what should i add/edit in the above code.
Any help would be highly appreciated.

Thanks

Body:
It is behaving in correct manner.
 You need to store the information in an external list and then return it.

import requests
from bs4 import BeautifulSoup

page = requests.get("http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical+consulting-other-in-vic/list-1?includePropertiesWithin=includesurrounding&activeSort=list-date&autoSuggest=true")

soup = BeautifulSoup(page.content, 'html.parser')
links = soup.find_all('a', attrs ={'class' :'details-panel'})
hrefs = [link['href'] for link in links]
Data = []
for urls in hrefs:
    pages = requests.get(urls)
    soup_2 =BeautifulSoup(pages.content, 'html.parser')

    Date = soup_2.find_all('li', attrs ={'class' :'sold-date'})
    Sold_Date = [Sold_Date.text.strip() for Sold_Date in Date]
    Address_1 = soup_2.find_all('p', attrs={'class' :'full-address'})
    Address = [Address.text.strip() for Address in Address_1]
    Data.append(Sold_Date + Address)
return Data


问:
on click removing all elements in jquery
I have created a jquery dynamic elements showing As of now when ever I click on single elements it deletes all can anyone help me out why is this happening or is there a way it can be done if I click on 1 element it it will remove 1 only

$(document).on("click", ".rmove", function() {
  $(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="comparision">
  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGIC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">PSMC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGTL</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>
</div></code>```

Fiddle Link

答:
Take a look. https://jsfiddle.net/hk0d5exr/5/

$(this).parent().parent() only access to the parent of the element clicked.

Let me know if help.

Cheers

Body:
I have created a jquery dynamic elements showing As of now when ever I click on single elements it deletes all can anyone help me out why is this happening or is there a way it can be done if I click on 1 element it it will remove 1 only

$(document).on("click", ".rmove", function() {
  $(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});

AGIC

44%

      Remove

PSMC

44%

      Remove

AGTL

44%

      Remove

Fiddle Link


问:
How to optimize building speed in visual studio 2008
Could someone give me tips to increase building speed in visual studio 2008?

I have a large project with many module with full source. Every single time it's built, every files are rebuilt, some of them were not changed. Can i prevent these file to be rebuilt?
I turned the property "Enable Minimum rebuild" /Gm on but the compiler threw this warning

```<code>Command line warning D9030 : '/Gm' is incompatible with multiprocessing; ignoring /MP switch
</code>```

Every tips to increase building speed will help me much.
Thanks,

答:
Can you provide more information on the structure of your project and which files are being rebuilt?

Unchanged C++ files may be rebuilt because they include header files that have been changed, in that case /Gm option will not help

Body:
Could someone give me tips to increase building speed in visual studio 2008?

I have a large project with many module with full source. Every single time it's built, every files are rebuilt, some of them were not changed. Can i prevent these file to be rebuilt?
I turned the property "Enable Minimum rebuild" /Gm on but the compiler threw this warning

Command line warning D9030 : '/Gm' is incompatible with multiprocessing; ignoring /MP switch

Every tips to increase building speed will help me much.
Thanks,