问:
How to run angular tests?
I clone the example project from https://github.com/angular-examples/toh-6.git

received dependencies:

pub get

Try to run tests:

pub run angular_test --test-arg=--tags=aot --test-arg=--platform=dartium  --test-arg=--reporter=expanded --verbose

Outpu:

```<code>PS Z:\Web\Test\dart_angular\external\toh-6> pub run angular_test --test-arg=--tags=aot --test-arg=--platform=dartium  --test-arg=--reporter=expanded --verbose
pub.bat serve test --port=0
Loading source assets...
Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers...
Pub "serve" started on http://localhost:52953
Serving angular_tour_of_heroes test on http://localhost:52953
Finished compilation. Running tests...
pub.bat run test --tags=aot --platform=dartium --reporter=expanded --pub-serve=52953
00:00 +0: test\app_test.dart: (suite)
Skip: AppComponent tests need bootstrap equivalent for the Router init
00:00 +0 ~1: loading test\all_test.dart
00:00 +0 ~1 -1: loading test\all_test.dart [E]
Failed to load "test\all_test.dart":
Failed to run Dartium: РќРµ СѓРґР°РµС‚СЃСЏ РЅР°Р№С‚Рё СѓРєР°Р·Р°РЅРЅС‹Р№ С„Р°Р№Р».

Command: dartium.exe --user-data-dir=C:\Users\k.ponomarev\AppData\Local\Temp\dart_test_e20a0131-da5c-11e7-9d6f-902b34b6196e http://localhost:52953/packages/test/src/runner/browser/static/index.html?managerUrl=ws%3A%2F%2Flocalhost%3A52956%2FmFXmvlRej%252BuoXwBhtyWjm1u67DweMIM9%2F0&debug=false --disable-extensions --disable-popup-blocking --bwsi --no-first-run --no-default-browser-check --disable-default-apps --disable-translate.
dart:async/future_impl.dart 22                             _Completer.completeError
dart:io-patch/process_patch.dart 412                       _ProcessImpl._start.<fn>
package:stack_trace/src/stack_zone_specification.dart 209  StackZoneSpecification._run
package:stack_trace/src/stack_zone_specification.dart 119  StackZoneSpecification._registerCallback.<fn>
dart:async/zone.dart 1116                                  _rootRun
dart:async/zone.dart 1001                                  _CustomZone.run
dart:async/zone.dart 901                                   _CustomZone.runGuarded
dart:async/zone.dart 926                                   _CustomZone.bindCallback.<fn>
package:stack_trace/src/stack_zone_specification.dart 209  StackZoneSpecification._run
package:stack_trace/src/stack_zone_specification.dart 119  StackZoneSpecification._registerCallback.<fn>
dart:async/zone.dart 1120                                  _rootRun
dart:async/zone.dart 1001                                  _CustomZone.run
dart:async/zone.dart 901                                   _CustomZone.runGuarded
dart:async/zone.dart 926                                   _CustomZone.bindCallback.<fn>
dart:async-patch/timer_patch.dart 21                       Timer._createTimer.<fn>
dart:isolate-patch/timer_impl.dart 366                     _Timer._runTimers
dart:isolate-patch/timer_impl.dart 394                     _Timer._handleMessage
dart:isolate-patch/isolate_patch.dart 151                  _RawReceivePortImpl._handleMessage
===== asynchronous gap ===========================
dart:async/zone.dart 1034                                  _CustomZone.registerCallback
dart:async/zone.dart 924                                   _CustomZone.bindCallback
dart:async/timer.dart 52                                   new Timer
dart:async/timer.dart 90                                   Timer.run
dart:io-patch/process_patch.dart 392                       _ProcessImpl._start
dart:io-patch/process_patch.dart 34                        Process.start
package:test/src/runner/browser/dartium.dart 66            new Dartium.<fn>.<fn>
===== asynchronous gap ===========================
dart:async/zone.dart 1034                                  _CustomZone.registerCallback
dart:async/zone.dart 924                                   _CustomZone.bindCallback
dart:async/schedule_microtask.dart 148                     scheduleMicrotask
dart:async/future.dart 182                                 new Future.microtask
package:test/src/runner/browser/dartium.dart 40            new Dartium.<fn>.<fn>
package:test/src/runner/browser/dartium.dart 119           new Dartium.<fn>
===== asynchronous gap ===========================

 ....

[test] GET all_test.dart.browser_test.dart => angular_tour_of_heroes|test/all_test.dart.browser_test.dart
00:00 +0 ~1 -1: Some tests failed.
Shutting down...
`pub serve` w
</code>```

How correctly run angular tests?

答:
I found solution of my problem. Test can not start dartium.exe. To fix it:

Add c:\tools\dartium to the PATH.

Create symbol link dartium.exe to lounche chrome.exe

mklink dartium.exe c:\tools\dartium\chrome.exe

I use two approach to launch tests:

run two command in different console

pub serve

pub run test --pub-serve=8081 -p dartium

As in (example):

pub run angular_test --test-arg=--tags=aot --test-arg=--platform=dartium --test-arg=--reporter=expanded --verbose

Title: How to run angular tests?

Body:
I clone the example project from https://github.com/angular-examples/toh-6.git

received dependencies:

pub get

Try to run tests:

pub run angular_test --test-arg=--tags=aot --test-arg=--platform=dartium  --test-arg=--reporter=expanded --verbose

Outpu:

PS Z:\Web\Test\dart_angular\external\toh-6> pub run angular_test --test-arg=--tags=aot --test-arg=--platform=dartium  --test-arg=--reporter=expanded --verbose
pub.bat serve test --port=0
Loading source assets...
Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers...
Pub "serve" started on http://localhost:52953
Serving angular_tour_of_heroes test on http://localhost:52953
Finished compilation. Running tests...
pub.bat run test --tags=aot --platform=dartium --reporter=expanded --pub-serve=52953
00:00 +0: test\app_test.dart: (suite)
Skip: AppComponent tests need bootstrap equivalent for the Router init
00:00 +0 ~1: loading test\all_test.dart
00:00 +0 ~1 -1: loading test\all_test.dart [E]
Failed to load "test\all_test.dart":
Failed to run Dartium: РќРµ СѓРґР°РµС‚СЃСЏ РЅР°Р№С‚Рё СѓРєР°Р·Р°РЅРЅС‹Р№ С„Р°Р№Р».

Command: dartium.exe --user-data-dir=C:\Users\k.ponomarev\AppData\Local\Temp\dart_test_e20a0131-da5c-11e7-9d6f-902b34b6196e http://localhost:52953/packages/test/src/runner/browser/static/index.html?managerUrl=ws%3A%2F%2Flocalhost%3A52956%2FmFXmvlRej%252BuoXwBhtyWjm1u67DweMIM9%2F0&debug=false --disable-extensions --disable-popup-blocking --bwsi --no-first-run --no-default-browser-check --disable-default-apps --disable-translate.
dart:async/future_impl.dart 22                             _Completer.completeError
dart:io-patch/process_patch.dart 412                       _ProcessImpl._start.<fn>
package:stack_trace/src/stack_zone_specification.dart 209  StackZoneSpecification._run
package:stack_trace/src/stack_zone_specification.dart 119  StackZoneSpecification._registerCallback.<fn>
dart:async/zone.dart 1116                                  _rootRun
dart:async/zone.dart 1001                                  _CustomZone.run
dart:async/zone.dart 901                                   _CustomZone.runGuarded
dart:async/zone.dart 926                                   _CustomZone.bindCallback.<fn>
package:stack_trace/src/stack_zone_specification.dart 209  StackZoneSpecification._run
package:stack_trace/src/stack_zone_specification.dart 119  StackZoneSpecification._registerCallback.<fn>
dart:async/zone.dart 1120                                  _rootRun
dart:async/zone.dart 1001                                  _CustomZone.run
dart:async/zone.dart 901                                   _CustomZone.runGuarded
dart:async/zone.dart 926                                   _CustomZone.bindCallback.<fn>
dart:async-patch/timer_patch.dart 21                       Timer._createTimer.<fn>
dart:isolate-patch/timer_impl.dart 366                     _Timer._runTimers
dart:isolate-patch/timer_impl.dart 394                     _Timer._handleMessage
dart:isolate-patch/isolate_patch.dart 151                  _RawReceivePortImpl._handleMessage
===== asynchronous gap ===========================
dart:async/zone.dart 1034                                  _CustomZone.registerCallback
dart:async/zone.dart 924                                   _CustomZone.bindCallback
dart:async/timer.dart 52                                   new Timer
dart:async/timer.dart 90                                   Timer.run
dart:io-patch/process_patch.dart 392                       _ProcessImpl._start
dart:io-patch/process_patch.dart 34                        Process.start
package:test/src/runner/browser/dartium.dart 66            new Dartium.<fn>.<fn>
===== asynchronous gap ===========================
dart:async/zone.dart 1034                                  _CustomZone.registerCallback
dart:async/zone.dart 924                                   _CustomZone.bindCallback
dart:async/schedule_microtask.dart 148                     scheduleMicrotask
dart:async/future.dart 182                                 new Future.microtask
package:test/src/runner/browser/dartium.dart 40            new Dartium.<fn>.<fn>
package:test/src/runner/browser/dartium.dart 119           new Dartium.<fn>
===== asynchronous gap ===========================

 ....

[test] GET all_test.dart.browser_test.dart => angular_tour_of_heroes|test/all_test.dart.browser_test.dart
00:00 +0 ~1 -1: Some tests failed.
Shutting down...
`pub serve` w

How correctly run angular tests?


来源: stackexchange

问:
Pandas Groupby Sum to Columns
I am doing groupby and can get the sum for a column ok, but how to I get sum of two columns together?

```<code>detail [ 'debit' ] = df.groupby ( 'type' ) [ 'debit' ].sum ()
detail [ 'credit' ] = df.groupby ( 'type' ) [ 'credit' ].sum ()
</code>```

Now I need the (credit - debit) together.

something like this:

```<code>detail [ 'profit' ] = df.groupby ( 'type' ) ( [ 'credit' ] - [ 'debit'  ] ).sum ()
</code>```

obviously that does not work.

Thanks.

答:
Have you tried:

detail [ 'profit' ] = sum(df.groupby ( 'type' ) [ 'credit' ] - df.groupby ( 'type' ) [ 'debit' ])

ContentLicense: CC BY-SA 3.0

Title: Pandas Groupby Sum to Columns

Body:
I am doing groupby and can get the sum for a column ok, but how to I get sum of two columns together?

detail [ 'debit' ] = df.groupby ( 'type' ) [ 'debit' ].sum ()
detail [ 'credit' ] = df.groupby ( 'type' ) [ 'credit' ].sum ()

Now I need the (credit - debit) together.

something like this:

detail [ 'profit' ] = df.groupby ( 'type' ) ( [ 'credit' ] - [ 'debit'  ] ).sum ()

obviously that does not work.

Thanks.


问:
class_weight='auto' for model.fit_generator keras
I have a highly unbalanced dataset and I want to use the class_weight = 'auto' in the model.fit_generator. However, when I do that I see that my model does not learn: training_acc = 0.65 and val_acc = 0.64 starting from epoch 1 up to 50.
If I set the class_weight = 'None' then the model starts learning: training_acc = 0.92 and val_acc = 0.88 at epoch 50.

Did anyone else face this problem? Do I have to define a dictionary to my class weights manually?

答:
For model.fit_generator in keras you can use train_generator.classes for the proper class names for your weighting

Then you simple create a dictionary mapping your classes., e.g.

class_weights = {'wolf':30 , 'fox':18}
```

That gives classes 'wolf' weight 30 and 'fox' weight '18'

ContentLicense: CC BY-SA 4.0

Body:
For model.fit_generator in keras you can use train_generator.classes for the proper class names for your weighting

Then you simple create a dictionary mapping your classes., e.g.

class_weights = {'wolf':30 , 'fox':18}

That gives classes 'wolf' weight 30 and 'fox' weight '18'


问:
Unserialization of configuration schema failed, Yii2
I've broken my mind..

I try to add img in HTML in Yii2.

I load it from db and put into view file, but when I try to return it in HTML tags it throw error.

But the picture is adding perfectly (checked via var_dump)

```<code><?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        [
            'format' => 'html',
            'label' => 'Image',
            'value' => function($data){
                return Html::img($data->getImage(), ['width'=>200]);
            }
        ],
        'id',
        'mark',
        'model',
        'colour',
        'state_num',

        // 'price',
        // 'status',
        // 'foto:ntext',
        // 'description:ntext',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
</code>```

I wanna see a picture in table. What happened with HTMLPurifier?
My img is saving as VARCHAR(255) in db.

PHP User Error – yii\base\ErrorException

Unserialization of configuration schema failed, sha1 of file was
  da39a3ee5e6b4b0d3255bfef95601890afd80709

答: I've changed format to "raw", and it's started to work</p>

Body:
I've broken my mind..

I try to add img in HTML in Yii2.

I load it from db and put into view file, but when I try to return it in HTML tags it throw error.

But the picture is adding perfectly (checked via var_dump)

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        [
            'format' => 'html',
            'label' => 'Image',
            'value' => function($data){
                return Html::img($data->getImage(), ['width'=>200]);
            }
        ],
        'id',
        'mark',
        'model',
        'colour',
        'state_num',

        // 'price',
        // 'status',
        // 'foto:ntext',
        // 'description:ntext',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

I wanna see a picture in table. What happened with HTMLPurifier?
My img is saving as VARCHAR(255) in db.

PHP User Error – yii\base\ErrorException

Unserialization of configuration schema failed, sha1 of file was
  da39a3ee5e6b4b0d3255bfef95601890afd80709


问:
Why do we calculate the margin in SVM?
I'm learning SVM (Support Vector Machine) : there are several points that remain ambiguous : (linearly separable, primal case)

I know how to find the weigth w and the hyperplan equation, but if we can deduce the support vectors from it, why do we calculate the margin ? What do I need to calculate first ? In which case ? (Sorry for those mixed questions, but I'm really lost with it)

I saw in some exemples that the margin is caculated in this manner :

```<code>1 / ||w||
</code>```

while in others, this way :

```<code>2 / ||w||
</code>```

so what is the difference between those two cases ?

Thanks

答:
The margin between the separating hyperplane and the class boundaries of an SVM is an essential feature of this algorithm.

See, you have two hyperplanes (1) w^tx+b>=1, if y=1 and (2) w^tx+b<=-1, if y=-1. This says that any vector with a label y=1 must lie ether on or behind the hyperplane (1). The same applies to the vectors with label y=-1 and hyperplane (2).

Note: If those requirements can be fulfilled, it implicitly means the dataset is linearly separatable. This makes sense because otherwise no such margin can be constructed.

So, what an SVM tries to find is a decision boundary which ist half-way between (1) and (2). Let's define this boundary as (3) w^tx+b=0. What you see here is that (1), (2) and (3) are parallel hyperplanes because they share the same parameters w and b. The parameters w holds the direction of those planes. Recall that a vector always has a direction and a magnitude/length.

The question is now: How can one calculate the hyperplane (3)? The equations (1) and (2) tell us that any vector with a label y=1 which is closest to (3) lies exactly on the hyperplane (1), hence (1) becomes w^tx+b=1 for such x. The similar applies for the closest vectors with a negative label and (2). Those vectors on the planes called 'support vectors' and the decision boundary (3) only depends on those, because one simply can subtract (2) from (1) for the support vectors and gets:

```<code>w^tx+b-w^tx+b=1-(-1) => wt^x-w^tx=2
</code>```

Note: x for the two planes are different support vectors.

Now, we want to get the direction of w but ignoring it's length to get the shortest distance between (3) and the other planes. This distance is a perpendicular line segment from (3) to the others. To do so, one can divide by the length of w to get the norm vector which is perpendicular to (3), hence (wt^x-w^tx)/||w||=2/||w||. By ignoring the left hand site (it's equal) we see that the distance between the two planes is actually 2/||w||. This distance must be maximized.

Edit:
As others state here, use Lagrange multipliers or the SMO algorithm to minimize the term
1/2 ||w||^2
s.t. y(w^tx+b)>=1
This is the convex form of the optimization problem for the primal svm.

Title: Why do we calculate the margin in SVM?

Body:
I'm learning SVM (Support Vector Machine) : there are several points that remain ambiguous : (linearly separable, primal case)

I know how to find the weigth w and the hyperplan equation, but if we can deduce the support vectors from it, why do we calculate the margin ? What do I need to calculate first ? In which case ? (Sorry for those mixed questions, but I'm really lost with it)

I saw in some exemples that the margin is caculated in this manner :

1 / ||w||

while in others, this way :

2 / ||w||

so what is the difference between those two cases ?

Thanks

Body:
The margin between the separating hyperplane and the class boundaries of an SVM is an essential feature of this algorithm.

See, you have two hyperplanes (1) w^tx+b>=1, if y=1 and (2) w^tx+b<=-1, if y=-1. This says that any vector with a label y=1 must lie ether on or behind the hyperplane (1). The same applies to the vectors with label y=-1 and hyperplane (2).

Note: If those requirements can be fulfilled, it implicitly means the dataset is linearly separatable. This makes sense because otherwise no such margin can be constructed.

So, what an SVM tries to find is a decision boundary which ist half-way between (1) and (2). Let's define this boundary as (3) w^tx+b=0. What you see here is that (1), (2) and (3) are parallel hyperplanes because they share the same parameters w and b. The parameters w holds the direction of those planes. Recall that a vector always has a direction and a magnitude/length.

The question is now: How can one calculate the hyperplane (3)? The equations (1) and (2) tell us that any vector with a label y=1 which is closest to (3) lies exactly on the hyperplane (1), hence (1) becomes w^tx+b=1 for such x. The similar applies for the closest vectors with a negative label and (2). Those vectors on the planes called 'support vectors' and the decision boundary (3) only depends on those, because one simply can subtract (2) from (1) for the support vectors and gets:

w^tx+b-w^tx+b=1-(-1) => wt^x-w^tx=2

Note: x for the two planes are different support vectors.

Now, we want to get the direction of w but ignoring it's length to get the shortest distance between (3) and the other planes. This distance is a perpendicular line segment from (3) to the others. To do so, one can divide by the length of w to get the norm vector which is perpendicular to (3), hence (wt^x-w^tx)/||w||=2/||w||. By ignoring the left hand site (it's equal) we see that the distance between the two planes is actually 2/||w||. This distance must be maximized.

Edit:
As others state here, use Lagrange multipliers or the SMO algorithm to minimize the term
1/2 ||w||^2
s.t. y(w^tx+b)>=1
This is the convex form of the optimization problem for the primal svm.


问:
Trigger a "ENTER" in programmatically
It is possible to program a "Enter" after a value is added to a input text box?

If yes, I need help on my code below. It does't trigger the "ENTER" keypress.

My code as below:

```<code>$('#clo_cart').click( function () {

/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;

$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click
</code>```

Pls Help

答:
Just replace the keydown event with keypress event. There are some differences between how they use event.which property. This might be one of the cases where the two of them use different values for event.which.

```<code>var eneterKey = jQuery.Event("keypress");
</code>```

Also note that which property has been deprecated. You can compare with the event.key property. It should have value Enter when the enter key is to be simulated.

```<code>$('#clo_cart').click( function () {

    /*Save ENTER in variable*/
    var eneterKey = jQuery.Event("keydown");
    eneterKey.key = 'Enter';

    $("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}
</code>```

Title: Trigger a "ENTER" in programmatically

Body:
It is possible to program a "Enter" after a value is added to a input text box?

If yes, I need help on my code below. It does't trigger the "ENTER" keypress.

My code as below:

$('#clo_cart').click( function () {

/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;

$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click

Pls Help

Body:
Just replace the keydown event with keypress event. There are some differences between how they use event.which property. This might be one of the cases where the two of them use different values for event.which.

var eneterKey = jQuery.Event("keypress");

Also note that which property has been deprecated. You can compare with the event.key property. It should have value Enter when the enter key is to be simulated.

$('#clo_cart').click( function () {

    /*Save ENTER in variable*/
    var eneterKey = jQuery.Event("keydown");
    eneterKey.key = 'Enter';

    $("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}


问:
ng-change is not working properly with ng-if

1. java script which is called

```<code>this.changeRole=function(user){
    alert(user)
    if(user=='Admin' || user=='Subject Manager'){
     $scope.role=false;
    }
    else{
        $scope.role=true;
    }
  }
</code>```

2. html from that function is called

```<code> <div class="form-group">
    <label class="col-sm-2 control-label">Role
        <span class="text-danger">*</span>
    </label>
    <div class="col-sm-9">
        <select class="form-control" ng-model="uc.newuser.role"
                ng-change="uc.changeRole(uc.newuser.role)" required >
            <option  ng-repeat="role in uc.roles" ng-value="user.name" >
              {{role}}
            </option>
        </select>
    </div>
 </div>
</code>```

```<code><table class="table">
    <thead>
        <tr>
          <th>User Name</th>
          <th>E-mail ID</th>
          <th>Mobile</th>
          <th>User type</th>
          <th ng-if="role=='Admin'">Action</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
          <td>{{user.name}}</td>
          <td>{{user.email}}</td>
          <td>{{user.phone}}</td>
          <td>{{user.role.toString()}}</td>
          <td ng-if="role=='Admin'">
            <button class="btn btn-circle btn-gout1"
                    ng-click="uc.editUser(user.id)"
                    data-toggle="modal"
                    data-target=".bs-register-modal-md">
              <i class="fa fa-pencil"></i>
            </button>
            <button class="btn btn-circle btn-gout"
                    ng-click="uc.deleteUser(user.id)">
              <i class="fa fa-trash"></i>
            </button>
          </td>
        </tr>

    </tbody>
</table>
</code>```

After ng-change the column with ng-if is hiding.

答:
Not exactly sure on what actually is required. However, this is what I think:

The select dropdown decides the role and based on the role the actions should appear on the following set of users.

You could directly use ng-model to do the same.

var app = angular.module('myApp',[]);

app.controller('Ctrl',function($scope){
    $scope.selectedRole = 'ADMIN'
    $scope.roles = ['ADMIN','Subject Manager','Student'];
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="Ctrl">
 <div class="form-group">
    <label class="col-sm-2 control-label">Role
        <span class="text-danger">*</span>
    </label>
    <div class="col-sm-9">
        <select class="form-control" ng-model="selectedRole"required >
            <option  ng-repeat="role in roles" value="{{role}}">
              {{role}}
            </option>
        </select>
    </div>
 </div>
 <table class="table">
    <thead>
        <tr>
          <th>User Name</th>
          <th>E-mail ID</th>
          <th>Mobile</th>
          <th>User type</th>
          <th ng-if="selectedRole === 'ADMIN'">Action</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
          <td>{{user.name}}</td>
          <td>{{user.email}}</td>
          <td>{{user.phone}}</td>
          <td>{{user.role.toString()}}</td>
          <td ng-if="selectedRole==='ADMIN'">
            <button class="btn btn-circle btn-gout1"
                    ng-click="uc.editUser(user.id)"
                    data-toggle="modal"
                    data-target=".bs-register-modal-md">
              <i class="fa fa-pencil"></i>
            </button>
            <button class="btn btn-circle btn-gout"
                    ng-click="uc.deleteUser(user.id)">
              <i class="fa fa-trash"></i>
            </button>
          </td>
        </tr>

    </tbody>
</table>
</body></code>```

Body:
1. java script which is called

this.changeRole=function(user){
    alert(user)
    if(user=='Admin' || user=='Subject Manager'){
     $scope.role=false;
    }
    else{
        $scope.role=true;
    }
  }

2. html from that function is called

    Role
        *

        <select class="form-control" ng-model="uc.newuser.role"
                ng-change="uc.changeRole(uc.newuser.role)" required >
            <option  ng-repeat="role in uc.roles" ng-value="user.name" >
              {{role}}
            </option>
        </select>

          User Name
          E-mail ID
          Mobile
          User type
          Action

          {{user.name}}
          {{user.email}}
          {{user.phone}}
          {{user.role.toString()}}

            <button class="btn btn-circle btn-gout1"
                    ng-click="uc.editUser(user.id)"
                    data-toggle="modal"
                    data-target=".bs-register-modal-md">

            </button>
            <button class="btn btn-circle btn-gout"
                    ng-click="uc.deleteUser(user.id)">

            </button>

After ng-change the column with ng-if is hiding.

Body:
Not exactly sure on what actually is required. However, this is what I think:

The select dropdown decides the role and based on the role the actions should appear on the following set of users.

You could directly use ng-model to do the same.

var app = angular.module('myApp',[]);

app.controller('Ctrl',function($scope){
    $scope.selectedRole = 'ADMIN'
    $scope.roles = ['ADMIN','Subject Manager','Student'];
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="Ctrl">
 <div class="form-group">
    <label class="col-sm-2 control-label">Role
        <span class="text-danger">*</span>
    </label>
    <div class="col-sm-9">
        <select class="form-control" ng-model="selectedRole"required >
            <option  ng-repeat="role in roles" value="{{role}}">
              {{role}}
            </option>
        </select>
    </div>
 </div>
 <table class="table">
    <thead>
        <tr>
          <th>User Name</th>
          <th>E-mail ID</th>
          <th>Mobile</th>
          <th>User type</th>
          <th ng-if="selectedRole === 'ADMIN'">Action</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
          <td>{{user.name}}</td>
          <td>{{user.email}}</td>
          <td>{{user.phone}}</td>
          <td>{{user.role.toString()}}</td>
          <td ng-if="selectedRole==='ADMIN'">
            <button class="btn btn-circle btn-gout1"
                    ng-click="uc.editUser(user.id)"
                    data-toggle="modal"
                    data-target=".bs-register-modal-md">
              <i class="fa fa-pencil"></i>
            </button>
            <button class="btn btn-circle btn-gout"
                    ng-click="uc.deleteUser(user.id)">
              <i class="fa fa-trash"></i>
            </button>
          </td>
        </tr>

    </tbody>
</table>
</body>


问:
How to use multiline flag in python regex?
I want to transform chunks of text into a database of single line entries database with regex. But I don't know why the regex group isn't recognized.
Maybe because the multiline flag isn't properly set.
I am a beginner at python.

```<code>import re
with open("a-j-0101.txt", encoding="cp1252") as f:
    start=1
    ecx=r"(?P<entrcnt>[0-9]{1,3}) célébrités ou évènements"
    ec1=""
    nmx=r"(?P<ename>.+)\r\nAfficher le.*"
    nm1=""
    for line in f:
        if start == 1:
            out = open('AST0101.txt' + ".txt", "w", encoding="cp1252") #utf8 cp1252
            ec1 = re.search(ecx,line)
            out.write(ec1.group("entrcnt"))
            start=0
        out.write(r"\r\n")
        nm1 = re.search(nmx,line, re.M)
        out.write(str(nm1.group("ename")).rstrip('\r\n'))
    out.close()
</code>```

But I get the error:

```<code>File "C:\work-python\transform-asth-b.py", line 16, in <module>
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'
</code>```

here is the input:

```<code>210 célébrités ou évènements ont été trouvés pour la date du 1er janvier.
Création de l'euro
Afficher le...
...
...
...
</code>```

expected output:

```<code>210
Création de l'euro ;...
... ;...
... ;...
</code>```

EDIT: I try to change nmx to match \n or \r\n but no result:

```<code>nmx=r"(?P<ename>.+)(\n|\r\n)Afficher le"
</code>```

best regards

答:
In this statement:

```<code>nm1 = re.search(nmx,line, re.M)
</code>```

you get an NoneType object (nm1 = None), because no matches were found. So make more investigation on the nmx attribute, why you get no matches in the regex.

By the way if it´s possible to get a NoneType object, you can avoid this by preventing a NoneType:

```<code>If nm1 is not None:
   out.write(str(nm1.group("ename")).rstrip('\r\n'))
else:
    #handle your NoneType case
</code>```

Body:
I want to transform chunks of text into a database of single line entries database with regex. But I don't know why the regex group isn't recognized.
Maybe because the multiline flag isn't properly set.
I am a beginner at python.

import re
with open("a-j-0101.txt", encoding="cp1252") as f:
    start=1
    ecx=r"(?P<entrcnt>[0-9]{1,3}) célébrités ou évènements"
    ec1=""
    nmx=r"(?P<ename>.+)\r\nAfficher le.*"
    nm1=""
    for line in f:
        if start == 1:
            out = open('AST0101.txt' + ".txt", "w", encoding="cp1252") #utf8 cp1252
            ec1 = re.search(ecx,line)
            out.write(ec1.group("entrcnt"))
            start=0
        out.write(r"\r\n")
        nm1 = re.search(nmx,line, re.M)
        out.write(str(nm1.group("ename")).rstrip('\r\n'))
    out.close()

But I get the error:

File "C:\work-python\transform-asth-b.py", line 16, in <module>
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'

here is the input:

210 célébrités ou évènements ont été trouvés pour la date du 1er janvier.
Création de l'euro
Afficher le...
...
...
...

expected output:

210
Création de l'euro ;...
... ;...
... ;...

EDIT: I try to change nmx to match \n or \r\n but no result:

nmx=r"(?P<ename>.+)(\n|\r\n)Afficher le"

best regards

Body:
In this statement:

nm1 = re.search(nmx,line, re.M)

you get an NoneType object (nm1 = None), because no matches were found. So make more investigation on the nmx attribute, why you get no matches in the regex.

By the way if it´s possible to get a NoneType object, you can avoid this by preventing a NoneType:

If nm1 is not None:
   out.write(str(nm1.group("ename")).rstrip('\r\n'))
else:
    #handle your NoneType case


问:
Tensorflow CNN filters really detect contrast in images with big white zones?
I'm having problems to understand how a CNN filter is able to give a higher value to perfect fit patchs when you have grayscale images with big white zones.

For example, imagine that I have the next 3x3 filter:

```<code>0-1-0
0-1-0
0-1-0
</code>```

And this filter is applied to one image with big completely white zones. For example, I could to have a patch of that image, like this:

```<code>255-255-255
255-255-255
255-255-255
</code>```

and for this patch, the kernel would return (0*255 + 0*255 + 0*255) + (1*255 + 1*255 + 1*255) + (0*255 + 0*255 + 0*255) = 765

and if I apply the same filter to this patch image:

```<code>0-255-0
0-255-0
0-255-0
</code>```

I would get the same value: (0*0 + 0*0 + 0*0) + (1*255 + 1*255 + 1*255) + (0*0 + 0*0 + 0*0) = 765

But the last one image patch should have got a much better value for kernel, so I am going crazy to understand how this works really

Thanks in advance!

答: Well, after a few days thinking about it, I have found the answer to my question, using negative values in kernel. After see so many kernel examples with 1's and 0's, I didn't think that the values could to be negatives too.</p>

Body:
I'm having problems to understand how a CNN filter is able to give a higher value to perfect fit patchs when you have grayscale images with big white zones.

For example, imagine that I have the next 3x3 filter:

0-1-0
0-1-0
0-1-0

And this filter is applied to one image with big completely white zones. For example, I could to have a patch of that image, like this:

255-255-255
255-255-255
255-255-255

and for this patch, the kernel would return (0*255 + 0*255 + 0*255) + (1*255 + 1*255 + 1*255) + (0*255 + 0*255 + 0*255) = 765

and if I apply the same filter to this patch image:

0-255-0
0-255-0
0-255-0

I would get the same value: (0*0 + 0*0 + 0*0) + (1*255 + 1*255 + 1*255) + (0*0 + 0*0 + 0*0) = 765

But the last one image patch should have got a much better value for kernel, so I am going crazy to understand how this works really

Thanks in advance!


问:
How to eliminate values from list2 (which are common with another list1) in python
Input:

```<code>list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
list3
</code>```

Output:

```<code>list3 = ['gender', 'location']
</code>```

How do I subtract common elements from list?

答:
Use list comprehension,

```<code>In [4]: list3 = [i for i in list1+list2 if i not in list2]

In [5]: list3
Out[5]: ['gender', 'location']
</code>```

OR

```<code>In [23]:  [i for i in list1+list2 if (list1+list2).count(i) == 1]
Out[23]: ['gender', 'location']
</code>```

Body:
Input:

list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
list3

Output:

list3 = ['gender', 'location']

How do I subtract common elements from list?

Body:
Use list comprehension,

In [4]: list3 = [i for i in list1+list2 if i not in list2]

In [5]: list3
Out[5]: ['gender', 'location']

OR

In [23]:  [i for i in list1+list2 if (list1+list2).count(i) == 1]
Out[23]: ['gender', 'location']


问:
Inverting scaling in scikit
```<code>scaler = MinMaxScaler()
scaler.fit(data_train)
data_train = scaler.transform(data_train)
data_test = scaler.transform(data_test)
</code>```

Hello,
I've created a neural network and I'm trying to rescale the output back to original value. How would I do that?

答:
There is a method for that. So if the data you want to change back is x

```<code>scaler.inverse_transform(x)
</code>```

For more information you can have a look at the documentation:
http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html

Title: Inverting scaling in scikit

Body:
scaler = MinMaxScaler()
scaler.fit(data_train)
data_train = scaler.transform(data_train)
data_test = scaler.transform(data_test)

Hello,
I've created a neural network and I'm trying to rescale the output back to original value. How would I do that?

Body:
There is a method for that. So if the data you want to change back is x

scaler.inverse_transform(x)

For more information you can have a look at the documentation:
http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html


问:
XDocument Elements - Remove tags
I'm currently importing the values from a valid XML file into a SQL database. Below is a snippet of the xml.

```<code><Suppliers>
    <SupplierDetails>
      <Name>Some Name</Name>
      <Logo>my-logo.jpg</Logo>
      <ID>4070</ID>
      <DateCertified>14/10/2016 00:00:00</DateCertified>
      <Description>Some description</Description>
      <Brands>Brand1</Brands>
      <Brands>Brand2</Brands>
      <Brands>Brand3</Brands>
      <Brands>Brand4</Brands>
      <SubBrands>SubBrand1</SubBrands>
      <SubBrands>SubBrand2</SubBrands>
      <SubBrands>SubBrand3</SubBrands>
      <SubBrands>HVAC</SubBrands>
    </SupplierDetails>
</Suppliers>
</code>```

The issue i'm having is with the list of Brands and SubBrands. All other values such as Name, Description etc are fine and are returned without their element "tags". However, the Brands / SubBrands look like this.

```<code>  <Brands>Brand1</Brands>
</code>```

I just need the "Brand1" bit.

This is how i'm binding my ViewModel

```<code>var model =
  from xml in xmlDoc.Descendants("SupplierDetails")
            select new SupplierViewModel
            {
                Name            = xml.Element("Name").ToString(),
                Logo            = xml.Element("Logo").ToString(),
                Supplier_Id     = (int)xml.Element("ID"),
                DateCertified   = xml.Element("DateCertified").ToString(),
                Description     = xml.Element("Description").ToString(),
                Brands          = (from b in xml.Elements("Brands") select b.ToString()).ToList(),
                SubBrands       = (from sb in xml.Elements("SubBrands") select sb.ToString()).ToList()
            };
</code>```

And my ViewModel

```<code>public class SupplierViewModel
{
    public int Id { get; set; }

    // XML Elements
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("LOGO")]
    public string Logo { get; set; }

    [XmlElement("ID")]
    public int Supplier_Id { get; set; }

    [XmlElement("DateCertified")]
    public string DateCertified { get; set; }

    [XmlElement("Description")]
    public string Description { get; set; }

    [XmlElement("Brands")]
    public List<string> Brands { get; set; }

    [XmlElement("SubBrands")]
    public List<string> SubBrands { get; set; }
}
</code>```

I know i can use a bit of RegEx to remove the tags but is there any other way of doing this on-the-fly...?

Thanks in advance. :)

答:
Should be enough to read the .Value instead of using .ToString()

```<code>    string xmlString = "<Suppliers><SupplierDetails><Name>Some Name</Name><Brands>Brand1</Brands><Brands>Brand2</Brands></SupplierDetails></Suppliers>";
    var xmlDoc = XDocument.Parse(xmlString);
    var model =
      from xml in xmlDoc.Descendants("SupplierDetails")
      select new SupplierViewModel {
          Name = xml.Element("Name").ToString(),
          Brands = (from b in xml.Elements("Brands") select b.Value).ToList(),
      };
    var YourModel = model.ToList()[0];
</code>```

Title: XDocument Elements - Remove tags

Body:
I'm currently importing the values from a valid XML file into a SQL database. Below is a snippet of the xml.

<Suppliers>
    <SupplierDetails>
      <Name>Some Name</Name>
      <Logo>my-logo.jpg</Logo>
      <ID>4070</ID>
      <DateCertified>14/10/2016 00:00:00</DateCertified>
      <Description>Some description</Description>
      <Brands>Brand1</Brands>
      <Brands>Brand2</Brands>
      <Brands>Brand3</Brands>
      <Brands>Brand4</Brands>
      <SubBrands>SubBrand1</SubBrands>
      <SubBrands>SubBrand2</SubBrands>
      <SubBrands>SubBrand3</SubBrands>
      <SubBrands>HVAC</SubBrands>
    </SupplierDetails>
</Suppliers>

The issue i'm having is with the list of Brands and SubBrands. All other values such as Name, Description etc are fine and are returned without their element "tags". However, the Brands / SubBrands look like this.

  <Brands>Brand1</Brands>

I just need the "Brand1" bit.

This is how i'm binding my ViewModel

var model =
  from xml in xmlDoc.Descendants("SupplierDetails")
            select new SupplierViewModel
            {
                Name            = xml.Element("Name").ToString(),
                Logo            = xml.Element("Logo").ToString(),
                Supplier_Id     = (int)xml.Element("ID"),
                DateCertified   = xml.Element("DateCertified").ToString(),
                Description     = xml.Element("Description").ToString(),
                Brands          = (from b in xml.Elements("Brands") select b.ToString()).ToList(),
                SubBrands       = (from sb in xml.Elements("SubBrands") select sb.ToString()).ToList()
            };

And my ViewModel

public class SupplierViewModel
{
    public int Id { get; set; }

    // XML Elements
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("LOGO")]
    public string Logo { get; set; }

    [XmlElement("ID")]
    public int Supplier_Id { get; set; }

    [XmlElement("DateCertified")]
    public string DateCertified { get; set; }

    [XmlElement("Description")]
    public string Description { get; set; }

    [XmlElement("Brands")]
    public List<string> Brands { get; set; }

    [XmlElement("SubBrands")]
    public List<string> SubBrands { get; set; }
}

I know i can use a bit of RegEx to remove the tags but is there any other way of doing this on-the-fly...?

Thanks in advance. :)

Body:
Should be enough to read the .Value instead of using .ToString()

    string xmlString = "<Suppliers><SupplierDetails><Name>Some Name</Name><Brands>Brand1</Brands><Brands>Brand2</Brands></SupplierDetails></Suppliers>";
    var xmlDoc = XDocument.Parse(xmlString);
    var model =
      from xml in xmlDoc.Descendants("SupplierDetails")
      select new SupplierViewModel {
          Name = xml.Element("Name").ToString(),
          Brands = (from b in xml.Elements("Brands") select b.Value).ToList(),
      };
    var YourModel = model.ToList()[0];


问:
How to capture what parameters are passed to stored procedure inside ssis package runtime
I have a scenario where my client informed me that their sql server agent jobs fail sometimes. On investigation, we found that the sql agent job calls an ssis package, which internally calls an SP with parameters (?,?,?), and the error is being generated in TSQL inside SP as per the error message.

I want to capture the parameters to test SP execution in a new query window, manually. We do not have an SSDT tool in the client environment with which to debug the SSIS package to identify parameters, however we have imported the ssis package in SSMS.

Is there any way I can capture the parameter passed at runtime to SP via the ssis package in SSMS?

答:
This one is easy as you can write code in the SP which you want to debug :</p>

```<code>  1- Create a table for variable capture
  2- in procedure just give insert statement like

 Insert into dbo.VariableLog values (@param1 , @param2 )
</code>```

Body:
This one is easy as you can write code in the SP which you want to debug :

  1- Create a table for variable capture
  2- in procedure just give insert statement like

 Insert into dbo.VariableLog values (@param1 , @param2 )


问:
Allow special characters like (Turkish characters)
I want to give permission my android app. on EditText allow turkish characters as ('ş','ğ','İ',ı).I try to add them in my layout:

```<code><EditText
android:inputType="textFilter"
android:digits="@string/myAlphaNumeric" />
</code>```

And string.xml;

```<code><string name="myAlphaNumeric">abcçdefgğhıijklmnoöpqrsştuüvwxyzABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ0123456789</string>
</code>```

But did not work!!

Also;
edtText.setText("şçüığŞÇÜİĞ") is work.I can see on app screen.
But I just enter that characters on screen nothing show.

答:
Just use inputType as "text" instead of "textFilter":</p>

```<code><EditText
android:inputType="text"/>
</code>```

Body:
I want to give permission my android app. on EditText allow turkish characters as ('ş','ğ','İ',ı).I try to add them in my layout:

<EditText
android:inputType="textFilter"
android:digits="@string/myAlphaNumeric" />

And string.xml;

<string name="myAlphaNumeric">abcçdefgğhıijklmnoöpqrsştuüvwxyzABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ0123456789</string>

But did not work!!

Also;
edtText.setText("şçüığŞÇÜİĞ") is work.I can see on app screen.
But I just enter that characters on screen nothing show.

Body:
Just use inputType as "text" instead of "textFilter":

<EditText
android:inputType="text"/>


问:
Thoughtbot's Clearance gem, overriding url_after_destroy
I was able to successfully override url_after_create, but my url_after_destroy is being ignored.

What am I messing up?

routes:

```<code>  map.resource  :session,
    :controller => 'sessions',
    :only => [:new, :create, :destroy]
</code>```

my Sessions controller:

```<code>class SessionsController < Clearance::SessionsController
  private
    def url_after_create
      puts "************after create****************"  #called on sign in
    end

  def url_after_destroy
    puts "************after destroy****************"  #never called
  end
end
</code>```

答:
The docs say:

You may also need to add code such as
  the following to your routes.rb:

```<code> map.sign_out 'sign_out',
     :controller => 'sessions',
     :action     => 'destroy',
     :method     => :delete
</code>```

That's what I'm missing.  Perhaps 'may' is not the best choice of verb for documentation.

ContentLicense: CC BY-SA 2.5

Body:
I was able to successfully override url_after_create, but my url_after_destroy is being ignored.

What am I messing up?

routes:

  map.resource  :session,
    :controller => 'sessions',
    :only => [:new, :create, :destroy]

my Sessions controller:

class SessionsController < Clearance::SessionsController
  private
    def url_after_create
      puts "************after create****************"  #called on sign in
    end

  def url_after_destroy
    puts "************after destroy****************"  #never called
  end
end

Body:
The docs say:

You may also need to add code such as
  the following to your routes.rb:

 map.sign_out 'sign_out',
     :controller => 'sessions',
     :action     => 'destroy',
     :method     => :delete

That's what I'm missing.  Perhaps 'may' is not the best choice of verb for documentation.


问:
VB.net Increment variables possible?
I am trying to find a better way to write this code but I can't figure out how to make this cleaner.  In other languages I have used in the past I am able to increment the variables with a loop instead  of having to apply the same code to several variables.  I suppose I am looking for something like this where the variable name itself is being changed or created using the loop:

```<code>Dim IP0 As String = ""
    While IP0 < 5
        IP0 = IP0.Remove(index).Trim
        index = IP2.IndexOf(" "c)
        IP0 = IP0 + 1
    End While
</code>```

In the above example, I would like the "+1" to actually add to the variable itself.  So "IP0" would become "IP1", then "IP2" and so on.  This does not compile obviously, is there a way to do this is VB.net?
  Here are a couple snippets of my current project that I would like to apply this logic to:

1

```<code>Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
IP1 = IP1.Remove(index).Trim
index = IP2.IndexOf(" "c)
IP2 = IP2.Remove(index).Trim
index = IP3.IndexOf(" "c)
IP3 = IP3.Remove(index).Trim
index = IP4.IndexOf(" "c)
IP4 = IP4.Remove(index).Trim
index = IP5.IndexOf(" "c)
IP5 = IP5.Remove(index).Trim
index = IP6.IndexOf(" "c)
IP6 = IP6.Remove(index).Trim
index = IP7.IndexOf(" "c)
IP7 = IP7.Remove(index).Trim
index = IP8.IndexOf(" "c)
IP8 = IP8.Remove(index).Trim
index = IP9.IndexOf(" "c)
IP9 = IP9.Remove(index).Trim
</code>```

2

```<code>Using writer As StreamWriter = New StreamWriter("C:\tempFiles\bigBatch.bat")

        writer.Write(
            "ping -a " & IP1 & " -n 1 > c:\tempFiles\IP1.txt" & vbNewLine &
            "ping -a " & IP2 & " -n 1 > c:\tempFiles\IP2.txt" & vbNewLine &
            "ping -a " & IP3 & " -n 1 > c:\tempFiles\IP3.txt" & vbNewLine &
            "ping -a " & IP4 & " -n 1 > c:\tempFiles\IP4.txt" & vbNewLine &
            "ping -a " & IP5 & " -n 1 > c:\tempFiles\IP5.txt" & vbNewLine &
            "ping -a " & IP6 & " -n 1 > c:\tempFiles\IP6.txt" & vbNewLine &
            "ping -a " & IP7 & " -n 1 > c:\tempFiles\IP7.txt" & vbNewLine &
            "ping -a " & IP8 & " -n 1 > c:\tempFiles\IP8.txt" & vbNewLine &
            "ping -a " & IP9 & " -n 1 > c:\tempFiles\IP9.txt" & vbNewLine)
    End Using
</code>```

3

```<code>Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
    IP1 = thisArray(3).Trim
    IP2 = thisArray(4).Trim
    IP3 = thisArray(5).Trim
    IP4 = thisArray(6).Trim
    IP5 = thisArray(7).Trim
    IP6 = thisArray(8).Trim
    IP7 = thisArray(9).Trim
    IP8 = thisArray(10).Trim
    IP9 = thisArray(11).Trim
</code>```

答:
Just store your similar variables in a collection like String() or List(Of String)

```<code>Dim ipList As New List(Of String) From {"IP1", "IP2", "IP3", "IP4", "IP5", "IP6", "IP7", "IP8", "IP9"}

For i As Int32 = 0 To ipList.Count - 1
    Dim ip = ipList(i)
    Dim indexOfSpace = ip.IndexOf(" "c)
    If indexOfSpace >= 0 Then ipList(i) = ip.Remove(indexOfSpace)
Next
</code>```

Title: VB.net Increment variables possible?

Body:
I am trying to find a better way to write this code but I can't figure out how to make this cleaner.  In other languages I have used in the past I am able to increment the variables with a loop instead  of having to apply the same code to several variables.  I suppose I am looking for something like this where the variable name itself is being changed or created using the loop:

Dim IP0 As String = ""
    While IP0 < 5
        IP0 = IP0.Remove(index).Trim
        index = IP2.IndexOf(" "c)
        IP0 = IP0 + 1
    End While

In the above example, I would like the "+1" to actually add to the variable itself.  So "IP0" would become "IP1", then "IP2" and so on.  This does not compile obviously, is there a way to do this is VB.net?
  Here are a couple snippets of my current project that I would like to apply this logic to:

1

Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
IP1 = IP1.Remove(index).Trim
index = IP2.IndexOf(" "c)
IP2 = IP2.Remove(index).Trim
index = IP3.IndexOf(" "c)
IP3 = IP3.Remove(index).Trim
index = IP4.IndexOf(" "c)
IP4 = IP4.Remove(index).Trim
index = IP5.IndexOf(" "c)
IP5 = IP5.Remove(index).Trim
index = IP6.IndexOf(" "c)
IP6 = IP6.Remove(index).Trim
index = IP7.IndexOf(" "c)
IP7 = IP7.Remove(index).Trim
index = IP8.IndexOf(" "c)
IP8 = IP8.Remove(index).Trim
index = IP9.IndexOf(" "c)
IP9 = IP9.Remove(index).Trim

2

Using writer As StreamWriter = New StreamWriter("C:\tempFiles\bigBatch.bat")

        writer.Write(
            "ping -a " & IP1 & " -n 1 > c:\tempFiles\IP1.txt" & vbNewLine &
            "ping -a " & IP2 & " -n 1 > c:\tempFiles\IP2.txt" & vbNewLine &
            "ping -a " & IP3 & " -n 1 > c:\tempFiles\IP3.txt" & vbNewLine &
            "ping -a " & IP4 & " -n 1 > c:\tempFiles\IP4.txt" & vbNewLine &
            "ping -a " & IP5 & " -n 1 > c:\tempFiles\IP5.txt" & vbNewLine &
            "ping -a " & IP6 & " -n 1 > c:\tempFiles\IP6.txt" & vbNewLine &
            "ping -a " & IP7 & " -n 1 > c:\tempFiles\IP7.txt" & vbNewLine &
            "ping -a " & IP8 & " -n 1 > c:\tempFiles\IP8.txt" & vbNewLine &
            "ping -a " & IP9 & " -n 1 > c:\tempFiles\IP9.txt" & vbNewLine)
    End Using

3

Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
    IP1 = thisArray(3).Trim
    IP2 = thisArray(4).Trim
    IP3 = thisArray(5).Trim
    IP4 = thisArray(6).Trim
    IP5 = thisArray(7).Trim
    IP6 = thisArray(8).Trim
    IP7 = thisArray(9).Trim
    IP8 = thisArray(10).Trim
    IP9 = thisArray(11).Trim

Body:
Just store your similar variables in a collection like String() or List(Of String)

Dim ipList As New List(Of String) From {"IP1", "IP2", "IP3", "IP4", "IP5", "IP6", "IP7", "IP8", "IP9"}

For i As Int32 = 0 To ipList.Count - 1
    Dim ip = ipList(i)
    Dim indexOfSpace = ip.IndexOf(" "c)
    If indexOfSpace >= 0 Then ipList(i) = ip.Remove(indexOfSpace)
Next


问:
What is the difference between io.sockets.emit and socket.emit in io.on('connection', function(socket){})?
I noticed if I want to emit a message like

```<code>io.on('connection', function(socket){
    socket.emit('signal')
})
</code>```

Somehow I have to refresh the HTML page to get the ejs file work on the signal. But If I directly emit it like:

```<code>io.sockets.emit('signal')
</code>```

Then I do not have to refresh the html to get the action work.

How come?

答:
In the first case you're waiting for a "connection" event.

With a refresh of your page, you'll be connected again and finally fire your event.

In the second case, the message will be sent to all clients when you'll start your server.

Body:
I noticed if I want to emit a message like

io.on('connection', function(socket){
    socket.emit('signal')
})

Somehow I have to refresh the HTML page to get the ejs file work on the signal. But If I directly emit it like:

io.sockets.emit('signal')

Then I do not have to refresh the html to get the action work.

How come?


问:
Cross browser testing - same browsers differ on mac and pc?
For cross browser testing do I need to test the same versions of browsers on both Mac OS X and Windows?

For instance if a site works fine on Firefox 3.6 on Mac OS X, do I also need to check it on Windows with Firefox 3.6?

答: Same browsers versions for different OS never give an issues unless and until you encounter with animated feature. Color would be a little variant. Also the images may appear stretched in MAC OS. Rest would be good to go !.</p>


答:
An easy way could be to iterate over the larger of the 2 lists, and if the current element is not found within the other list, append to the end result.

Example

```<code>list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
res = []
for l in list1:
    if l not in list2:
        res.append(l)
print res
</code>```

Output: ["gender", "location"]

Hope this helps!

Title: How to eliminate values from list2 (which are common with another list1) in python

Body:
An easy way could be to iterate over the larger of the 2 lists, and if the current element is not found within the other list, append to the end result.

Example

list1 = ['name', 'age', 'gender', 'location']
list2 = ['name', 'age']
res = []
for l in list1:
    if l not in list2:
        res.append(l)
print res

Output: ["gender", "location"]

Hope this helps!


问:
Highchart: Can I use a different variable as the data labels?
I'm trying to build a column chart through highchart in r studio. I've converted the values to % as I want the graph to show %, but I want the data labels to show the value, is there a way of doing this?

My data set has a column with the values for London and the percentages for London, I want the Y axis of the graph to show the % while the data labels show the value.

This is my current code:

```<code>    hc <- highchart() %>%
  hc_title(text= "Gender - London")%>%
  hc_colors('#71599b') %>%
  hc_yAxis(max = 0.7) %>%
  hc_xAxis(categories = Sex$Gender) %>%
  hc_add_series(name = "London", type = "column",
                data = Sex$LON_PERC, dataLabels = list(enabled=TRUE, format={Sex$London}) )
</code>```

So, I've put Sex$LON_PERC (% in London) as the data to plot while Sex$London is the data labels.

But this code puts all the values of London in each data label.

Edit:

This is the data I'm trying to plot, LON_PERC on the Y Axis, Gender on the X axis and London as the Data Labels

```<code>Gender    London    LON_PERC
Declined    5      0.000351247
Female    8230     0.578152441
Male      4640     0.325957148
No Data   1360     0.095539164
</code>```

答:
I am rather uncomfortable working with the ´highcharter´ package, as it requires a commercial license, which I do not have.

The result you want to achieve can be reached with the following - rather straightforward - code using base r or ggplot functionality, both of which are freeware. I will show this with two code fragments below.

```<code>### your data
Sex <- read.table(header = TRUE, text =
            "Gender     London     LON_PERC
             Declined       5      0.000351247
             Female      8230      0.578152441
             Male        4640      0.325957148
            'No Data'    1360      0.095539164
                  ")
</code>```

A Solution using base r

The barplot function returns a vector (when besides is false) with the coordinates of all the midpoints of the bars drawn (if besides is true, it is a matrix). This gives us the X-coordinates for setting text above the bars, the bar-heights we already have in the data we plot, right.

```<code># Draw the barplot and store result in `mp`
mp <- barplot(Sex$LON_PERC,     # height of the bar
    names.arg = Sex$Gender,     # x-axis labels
    ylim = c(0, 0.7),           # limits of y-axis
    col = '#71599b',            # your color
    main = "Gender - London")   # main title

# add text to the barplot using the stored values
text(x = mp,                    # middle of the bars
    y = Sex$LON_PERC,           # height of the bars
    labels = Sex$London,        # text to display
    adj = c(.5, -1.5))          # adjust horizontally and vertically
</code>```

This yields the following plot:

A solution based on ggplot

```<code>library(ggplot2)

ggplot(aes(x = Gender, y =  LON_PERC), data = Sex) +
  geom_bar(stat = "identity", width = .60, fill = "#71599b" ) +
  geom_text(aes(label = London),
            position = position_dodge(width = .9),
            vjust = -.3, size = 3, hjust =  "center") +
  theme_minimal() +
  scale_y_continuous(limits = c(0, 0.7),
            breaks = seq(0.0, 0.7, by = 0.1),
            minor_breaks = NULL) +
  labs(title = "Gender - London") +
  theme(axis.title.y = element_blank(), axis.title.x = element_blank())
</code>```

yielding the following plot:

In both cases, a lot of characteristics may be adapted to your needs/wishes.

I hope you benefit from these examples, even though it is not made with highcharter.

Body:
I'm trying to build a column chart through highchart in r studio. I've converted the values to % as I want the graph to show %, but I want the data labels to show the value, is there a way of doing this?

My data set has a column with the values for London and the percentages for London, I want the Y axis of the graph to show the % while the data labels show the value.

This is my current code:

    hc <- highchart() %>%
  hc_title(text= "Gender - London")%>%
  hc_colors('#71599b') %>%
  hc_yAxis(max = 0.7) %>%
  hc_xAxis(categories = Sex$Gender) %>%
  hc_add_series(name = "London", type = "column",
                data = Sex$LON_PERC, dataLabels = list(enabled=TRUE, format={Sex$London}) )

So, I've put Sex$LON_PERC (% in London) as the data to plot while Sex$London is the data labels.

But this code puts all the values of London in each data label.

Edit:

This is the data I'm trying to plot, LON_PERC on the Y Axis, Gender on the X axis and London as the Data Labels

Gender    London    LON_PERC
Declined    5      0.000351247
Female    8230     0.578152441
Male      4640     0.325957148
No Data   1360     0.095539164

Body:
I am rather uncomfortable working with the ´highcharter´ package, as it requires a commercial license, which I do not have.

The result you want to achieve can be reached with the following - rather straightforward - code using base r or ggplot functionality, both of which are freeware. I will show this with two code fragments below.

### your data
Sex <- read.table(header = TRUE, text =
            "Gender     London     LON_PERC
             Declined       5      0.000351247
             Female      8230      0.578152441
             Male        4640      0.325957148
            'No Data'    1360      0.095539164
                  ")

A Solution using base r

The barplot function returns a vector (when besides is false) with the coordinates of all the midpoints of the bars drawn (if besides is true, it is a matrix). This gives us the X-coordinates for setting text above the bars, the bar-heights we already have in the data we plot, right.

# Draw the barplot and store result in `mp`
mp <- barplot(Sex$LON_PERC,     # height of the bar
    names.arg = Sex$Gender,     # x-axis labels
    ylim = c(0, 0.7),           # limits of y-axis
    col = '#71599b',            # your color
    main = "Gender - London")   # main title

# add text to the barplot using the stored values
text(x = mp,                    # middle of the bars
    y = Sex$LON_PERC,           # height of the bars
    labels = Sex$London,        # text to display
    adj = c(.5, -1.5))          # adjust horizontally and vertically

This yields the following plot:

A solution based on ggplot

library(ggplot2)

ggplot(aes(x = Gender, y =  LON_PERC), data = Sex) +
  geom_bar(stat = "identity", width = .60, fill = "#71599b" ) +
  geom_text(aes(label = London),
            position = position_dodge(width = .9),
            vjust = -.3, size = 3, hjust =  "center") +
  theme_minimal() +
  scale_y_continuous(limits = c(0, 0.7),
            breaks = seq(0.0, 0.7, by = 0.1),
            minor_breaks = NULL) +
  labs(title = "Gender - London") +
  theme(axis.title.y = element_blank(), axis.title.x = element_blank())

yielding the following plot:

In both cases, a lot of characteristics may be adapted to your needs/wishes.

I hope you benefit from these examples, even though it is not made with highcharter.


问:
Need help accessing the assets folder in Code Igniter 3
I am working with Code Igniter 3. I kept all the assets file in the root folder like I normally do. However, I needed to move all the files inside a different folder, let me explain:

BEFORE

user.php was in : %root%\application\views\

admin-panel.php was in : %root%\application\views\

And the assets in: %root%\assets

NOW

user.php file is inside a folder: %root%\application\views\usr\

admin-panel.php was in : %root%\application\views\adm

And the assets is in: %root%\assets

I know I can access the asset files from adm or the usr folders by simply changing assets/anything.extension to ../assets/anything.extension

Or by copy-pasting the assets folder in both the directories (which I don't want to do)

However, I have already finished the designs and it will be very time consuming to do that so I would like to know if there's any other way to let the files in adm or usr access the files inside assets by maybe using route.php or .htaccess something?

答:
Well as your assets folder is in the same folder as index.php which is where the paths have to be "relative" to... You can just get away with something like

```<code><img src="/assets/img/logo.png" alt="">
</code>```

Using HTACCESS
Now I must state that I am only just dangerous when it comes to htaccess stuff.

Trying to redirect assets to /assets seems to mess things up on my server. What I did find that if you rename your assets folder to asset or even move it, this appears to work. So not sure of any side effects this might have but it seems to play ok on my test site.

.htaccess

```<code>RewriteEngine On

# Note - the system assets folder has been renamed to asset
# to make it different. It doesn't like them being the same
# with this implementation. Especially if we match on /assets or assets.

RewriteRule ^/?assets/?$ /asset/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

The /? in ^/?assets/?$ is just in case you do have a leading / which then forces a rename of the folder from assets to asset. Else it goes chasing its tail in a loop...

There will be better ways to do this, that the smarter folks will know, so it's a possible solution but I'm not claiming its the best or even technically correct.

If you do use it, test the stuffing out of it.

My Test setup.

.htaccess file in root folder

Controller called User.php

```<code>class User extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $this->load->view('usr/user_view');
    }
}
</code>```

View called user_view.php which resides under application/views/usr and contains...

```<code><h1>This is the User View</h1>
<img src="assets/images/alien-icon.jpg" width="300" height="300" alt="">
</code>```

And the image resides at /asset/images/ NOTE: it is asset and not assets

So any references to assets/stuff... is being redirected to asset/....

Body:
Well as your assets folder is in the same folder as index.php which is where the paths have to be "relative" to... You can just get away with something like

<img src="/assets/img/logo.png" alt="">

Using HTACCESS
Now I must state that I am only just dangerous when it comes to htaccess stuff.

Trying to redirect assets to /assets seems to mess things up on my server. What I did find that if you rename your assets folder to asset or even move it, this appears to work. So not sure of any side effects this might have but it seems to play ok on my test site.

.htaccess

RewriteEngine On

# Note - the system assets folder has been renamed to asset
# to make it different. It doesn't like them being the same
# with this implementation. Especially if we match on /assets or assets.

RewriteRule ^/?assets/?$ /asset/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

The /? in ^/?assets/?$ is just in case you do have a leading / which then forces a rename of the folder from assets to asset. Else it goes chasing its tail in a loop...

There will be better ways to do this, that the smarter folks will know, so it's a possible solution but I'm not claiming its the best or even technically correct.

If you do use it, test the stuffing out of it.

My Test setup.

.htaccess file in root folder

Controller called User.php

class User extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $this->load->view('usr/user_view');
    }
}

View called user_view.php which resides under application/views/usr and contains...

<h1>This is the User View</h1>
<img src="assets/images/alien-icon.jpg" width="300" height="300" alt="">

And the image resides at /asset/images/ NOTE: it is asset and not assets

So any references to assets/stuff... is being redirected to asset/....


问:
Second CopyPicture in VBA fails with "Automation error"
So I am copying and pasting a bunch of data to another spreadsheet. I thought this last bit was going to be easy since I've done this a bunch of times in this script.

Except it fails. Here's part of my code:

```<code>ProdCK.Worksheets("CK week").Range("A11:AY28").CopyPicture Appearance:=xlScreen
Worksheets("Prod.CK").Paste Destination:=Worksheets("Prod.CK").Range("A1")

ProdCK.Worksheets("CK week").Range("I131:BO148").CopyPicture Appearance:=xlScreen
Worksheets("Prod.CK").Paste Destination:=Worksheets("Prod.CK").Range("A22")
</code>```

The first one works fine, but then the second one crashes on the CopyPicture operation. I've checked that a range is actually present by first storing that in a range, checking if the data is there in the "watch" screen and then calling CopyPicture on that, but nonetheless is still gives a

424 error Object required

Can anyone shine a light on this for me?

UPDATE:

The error is actually

-2147417851 Automation error The server threw an exception

My error handling code had a bug which turned the automation error into the Object required error. What is also interesting is that the error does not happen when I use a visible Excel.Application in this Sub. The only difference between my visible and invisible settings are Visible = True and ScreenUpdating = True.

答:
I haven't been able to figure out why but currently I just set App.Visible = True before these two statements and set it back to App.Visible = False afterwards. This gets things working.

I really dislike it though.

Body:
So I am copying and pasting a bunch of data to another spreadsheet. I thought this last bit was going to be easy since I've done this a bunch of times in this script.

Except it fails. Here's part of my code:

ProdCK.Worksheets("CK week").Range("A11:AY28").CopyPicture Appearance:=xlScreen
Worksheets("Prod.CK").Paste Destination:=Worksheets("Prod.CK").Range("A1")

ProdCK.Worksheets("CK week").Range("I131:BO148").CopyPicture Appearance:=xlScreen
Worksheets("Prod.CK").Paste Destination:=Worksheets("Prod.CK").Range("A22")

The first one works fine, but then the second one crashes on the CopyPicture operation. I've checked that a range is actually present by first storing that in a range, checking if the data is there in the "watch" screen and then calling CopyPicture on that, but nonetheless is still gives a

424 error Object required

Can anyone shine a light on this for me?

UPDATE:

The error is actually

-2147417851 Automation error The server threw an exception

My error handling code had a bug which turned the automation error into the Object required error. What is also interesting is that the error does not happen when I use a visible Excel.Application in this Sub. The only difference between my visible and invisible settings are Visible = True and ScreenUpdating = True.


问:
Vertx thread blocked warnings
I am running a vert.x application on ubuntu server. It has an HTTPServer running on port 3000. Application is working fine but sometimes I am seeing following warnings:

```<code>Dec 08, 2017 1:23:43 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 138013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:44 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 139014 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:45 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 140013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:46 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 141013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:47 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 142013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:48 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 143013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:49 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 144013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:50 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 145013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I am not able to understand what is causing these warnings to appear. At the time of warnings, the server was idle with 0 traffic on the application. Also, I am running a scheduler using vertx periodic, which makes query to mongo every 15 secs.

```<code>vertx.setPeriodic(15000, r -> someService.check()); // Every 15 seconds
</code>```

答:
It seems there is not enough entropy (server idle) to feed the PRNG. So instead of returning quickly the SecureRandom.generateSeed method blocks until it gets enough data.

Depending on your hardware, you may be able to speed up the process with rng-tools.

Title: Vertx thread blocked warnings

Body:
I am running a vert.x application on ubuntu server. It has an HTTPServer running on port 3000. Application is working fine but sometimes I am seeing following warnings:

Dec 08, 2017 1:23:43 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 138013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:44 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 139014 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:45 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 140013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:46 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 141013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:47 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 142013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:48 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 143013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:49 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 144013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:50 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 145013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

I am not able to understand what is causing these warnings to appear. At the time of warnings, the server was idle with 0 traffic on the application. Also, I am running a scheduler using vertx periodic, which makes query to mongo every 15 secs.

vertx.setPeriodic(15000, r -> someService.check()); // Every 15 seconds