问:
Calculate Nested Yii2 Dynamic Input Form
Halo, I am using Yii2 Dynamic Form wbraganca. I want to calculate nested form into input field in main form.

This is my main dynamic form :

_form.php

```<code><h3>Data Pengeluaran</h3>
<?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_pengeluaran',
    'widgetBody' => '.container-pengeluaran',
    'widgetItem' => '.item-pengeluaran',
    'min' => 1,
    'insertButton' => '.add-item-pengeluaran',
    'deleteButton' => '.remove-item-pengeluaran',
    'model' => $modelPengeluaran[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'tgl_pengeluaran',
        'nama_toko',
        'metode_pembayaran',
        'waktu_pembayaran',
        'jlh_pengeluaran',
        'jlh_bayar',
    ],
]); ?>
<div class="container-pengeluaran"><!-- widgetContainer -->
<?php foreach ($modelPengeluaran as $index => $modelPengeluaran): ?>
    <div class="item-pengeluaran panel panel-default"><!-- widgetBody -->
        <div class="panel-heading">
            <h3 class="panel-title pull-left">Pengeluaran</h3>
            <div class="pull-right">
                <button type="button" class="add-item-pengeluaran btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
                <button type="button" class="remove-item-pengeluaran btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
            </div>
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <?php
                // necessary for update action.
                if (! $modelPengeluaran->isNewRecord) {
                    echo Html::activeHiddenInput($modelPengeluaran, "[{$index}]id");
                }
            ?>
            <div class="row">
                <div class="col-md-12">
                <?= $form->field($modelPengeluaran, "[{$index}]tgl_pengeluaran")->widget(DatePicker::classname(), [
                        'type' => DatePicker::TYPE_COMPONENT_APPEND,
                        'options' => ['placeholder' => '-- Tanggal Pengeluaran --'],
                        'pluginOptions' => [
                            'autoclose'=>true,
                            'format' => 'yyyy-mm-dd',
                            'todayHighlight' => true
                        ]
                    ]);
                ?>

                <?= $form->field($modelPengeluaran, "[{$index}]nama_toko")->textInput(['maxlength' => true]) ?>

                <?= $form->field($modelPengeluaran, "[{$index}]metode_pembayaran")->dropDownList([ 'Tunai' => 'Tunai', 'Hutang' => 'Hutang', ], ['prompt' => '-- Pilih Pembayaran --']) ?>

                <?= $form->field($modelPengeluaran, "[{$index}]waktu_pembayaran")->dropDownList([ 'Berangkat' => 'Berangkat', 'Pulang' => 'Pulang', ], ['prompt' => '-- Pilih Waktu Pembayaran --']) ?>

                <?= $this->render('_form-barang', [
                    'form' => $form,
                    'index' => $index,
                    'modelBarang' => $modelBarang[$index],
                ]) ?>

                <?= $form->field($modelPengeluaran, "[{$index}]jlh_pengeluaran")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>

                <?= $form->field($modelPengeluaran, "[{$index}]jlh_bayar")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>
                </div>
            </div><!-- .row -->
        </div>
    </div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</code>```

And this is my nested dynamic form :

_form-barang.php

```<code><?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_inner',
    'widgetBody' => '.container-barang',
    'widgetItem' => '.item-barang',
    'min' => 1,
    'insertButton' => '.add-barang',
    'deleteButton' => '.remove-barang',
    'model' => $modelBarang[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'jlh_barang',
        'nama_barang',
        'jlh_harga',
    ],
]); ?>
<table class="table">
    <tbody class="container-barang">
    <?php foreach ($modelBarang as $indexBarang => $modelBarang): ?>
        <tr class="item-barang">
            <td class="vcenter">
                <?php
                    // necessary for update action.
                    if (! $modelBarang->isNewRecord) {
                        echo Html::activeHiddenInput($modelBarang, "[{$index}][{$indexBarang}]id");
                    }
                ?>
                <?= $form->field($modelBarang, "[{$index}][{$indexBarang}]jlh_barang")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>
            </td>
            <td>
                <?= $form->field($modelBarang, "[{$index}][{$indexBarang}]nama_barang")->textInput(['maxlength' => true]) ?>
            </td>
            <td>
                <?= $form->field($modelBarang, "[{$index}][{$indexBarang}]jlh_harga")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>
            </td>
            <td class="text-center vcenter" style="width: 90px;">
                <button type="button" class="add-barang btn btn-success btn-xs"><span class="glyphicon glyphicon-plus"></span></button>
                <button type="button" class="remove-barang btn btn-danger btn-xs"><span class="glyphicon glyphicon-minus"></span></button>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<?php DynamicFormWidget::end(); ?>
</code>```

From that, this is the screenshot :

I try follow the code from this question, but I just got the last value from nested form, like on the picture.

This is my script :

```<code>$(document).on('keyup', 'input[id^="barangpengeluaran-"]', function() {
    var index = $(this).attr("id").replace(/[^0-9.]/g, "");
    var index_pengeluaran = index.substring(0,1);
    var index_barang = index.substring(1,2);

    var index_fix = index_pengeluaran+'-'+index_barang;

    var sum = 0;

    $('#barangpengeluaran-'+index_fix+'-jlh_harga').each(function() {
        var harga = $(this).val().replace(/,/g , "");
        sum = parseInt(sum) + parseInt(harga);
    });

    $('#pengeluaran-'+index_pengeluaran+'-jlh_pengeluaran').val(sum);
});
</code>```

答:
You must populate all the nested form child, you can try populate with the delete button id

I notice that you set delete button with id ".remove-barang"

So, the answer will be like this:

$(document).on('keyup', 'input[id^="barangpengeluaran-"]', function () {
  var index = $(this).attr("id").replace(/[^0-9.]/g, "");
  var index_pengeluaran = index.substring(0, 1);
  var index_barang = index.substring(1, 2);

  var index_fix = index_pengeluaran + '-' + index_barang;

  var sum = 0;

  // populate delete button and get the index
  jQuery(".dynamicform_wrapper .remove-barang").each(function (index) {
    // get the value of each column
    var harga = $('#barangpengeluaran-' + index + '-jlh_harga').val().replace(/,/g, "");
    // sum all of harga
    sum += harga;
  });

  $('#pengeluaran-' + index_pengeluaran + '-jlh_pengeluaran').val(sum);
});
```

But I think you must add column subtotal, and I will help you with better solution

Body:
Halo, I am using Yii2 Dynamic Form wbraganca. I want to calculate nested form into input field in main form.

This is my main dynamic form :

_form.php

Data Pengeluaran

<?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_pengeluaran',
    'widgetBody' => '.container-pengeluaran',
    'widgetItem' => '.item-pengeluaran',
    'min' => 1,
    'insertButton' => '.add-item-pengeluaran',
    'deleteButton' => '.remove-item-pengeluaran',
    'model' => $modelPengeluaran[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'tgl_pengeluaran',
        'nama_toko',
        'metode_pembayaran',
        'waktu_pembayaran',
        'jlh_pengeluaran',
        'jlh_bayar',
    ],
]); ?>

<?php foreach ($modelPengeluaran as $index => $modelPengeluaran): ?>

Pengeluaran

                <button type="button" class="add-item-pengeluaran btn btn-success btn-xs"></button>
                <button type="button" class="remove-item-pengeluaran btn btn-danger btn-xs"></button>

            <?php
                // necessary for update action.
                if (! $modelPengeluaran->isNewRecord) {
                    echo Html::activeHiddenInput($modelPengeluaran, "[{$index}]id");
                }
            ?>

                <?= $form->field($modelPengeluaran, "[{$index}]tgl_pengeluaran")->widget(DatePicker::classname(), [
                        'type' => DatePicker::TYPE_COMPONENT_APPEND,
                        'options' => ['placeholder' => '-- Tanggal Pengeluaran --'],
                        'pluginOptions' => [
                            'autoclose'=>true,
                            'format' => 'yyyy-mm-dd',
                            'todayHighlight' => true
                        ]
                    ]);
                ?>

                <?= $form->field($modelPengeluaran, "[{$index}]nama_toko")->textInput(['maxlength' => true]) ?>

                <?= $form->field($modelPengeluaran, "[{$index}]metode_pembayaran")->dropDownList([ 'Tunai' => 'Tunai', 'Hutang' => 'Hutang', ], ['prompt' => '-- Pilih Pembayaran --']) ?>

                <?= $form->field($modelPengeluaran, "[{$index}]waktu_pembayaran")->dropDownList([ 'Berangkat' => 'Berangkat', 'Pulang' => 'Pulang', ], ['prompt' => '-- Pilih Waktu Pembayaran --']) ?>

                <?= $this->render('_form-barang', [
                    'form' => $form,
                    'index' => $index,
                    'modelBarang' => $modelBarang[$index],
                ]) ?>

                <?= $form->field($modelPengeluaran, "[{$index}]jlh_pengeluaran")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>

                <?= $form->field($modelPengeluaran, "[{$index}]jlh_bayar")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>

<?php endforeach; ?>

<?php DynamicFormWidget::end(); ?>

And this is my nested dynamic form :

_form-barang.php

<?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_inner',
    'widgetBody' => '.container-barang',
    'widgetItem' => '.item-barang',
    'min' => 1,
    'insertButton' => '.add-barang',
    'deleteButton' => '.remove-barang',
    'model' => $modelBarang[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'jlh_barang',
        'nama_barang',
        'jlh_harga',
    ],
]); ?>

    <?php foreach ($modelBarang as $indexBarang => $modelBarang): ?>

                <?php
                    // necessary for update action.
                    if (! $modelBarang->isNewRecord) {
                        echo Html::activeHiddenInput($modelBarang, "[{$index}][{$indexBarang}]id");
                    }
                ?>
                <?= $form->field($modelBarang, "[{$index}][{$indexBarang}]jlh_barang")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>

                <?= $form->field($modelBarang, "[{$index}][{$indexBarang}]nama_barang")->textInput(['maxlength' => true]) ?>

                <?= $form->field($modelBarang, "[{$index}][{$indexBarang}]jlh_harga")->widget(\yii\widgets\MaskedInput::className(),
                    [
                        'clientOptions' => [
                            'alias' => 'numeric',
                            'groupSeparator' => '.',
                            'digits' => 0,
                            'autoGroup' => true,
                            'removeMaskOnSubmit' => true,
                            'rightAlign' => false,
                        ],
                        'options' => [
                            'class' => 'form-control',
                            'maxlength' => true,
                        ]
                    ])
                ?>

                <button type="button" class="add-barang btn btn-success btn-xs"></button>
                <button type="button" class="remove-barang btn btn-danger btn-xs"></button>

    <?php endforeach; ?>

<?php DynamicFormWidget::end(); ?>

From that, this is the screenshot :

I try follow the code from this question, but I just got the last value from nested form, like on the picture.

This is my script :

$(document).on('keyup', 'input[id^="barangpengeluaran-"]', function() {
    var index = $(this).attr("id").replace(/[^0-9.]/g, "");
    var index_pengeluaran = index.substring(0,1);
    var index_barang = index.substring(1,2);

    var index_fix = index_pengeluaran+'-'+index_barang;

    var sum = 0;

    $('#barangpengeluaran-'+index_fix+'-jlh_harga').each(function() {
        var harga = $(this).val().replace(/,/g , "");
        sum = parseInt(sum) + parseInt(harga);
    });

    $('#pengeluaran-'+index_pengeluaran+'-jlh_pengeluaran').val(sum);
});

Body:
You must populate all the nested form child, you can try populate with the delete button id

I notice that you set delete button with id ".remove-barang"

So, the answer will be like this:

$(document).on('keyup', 'input[id^="barangpengeluaran-"]', function () {
  var index = $(this).attr("id").replace(/[^0-9.]/g, "");
  var index_pengeluaran = index.substring(0, 1);
  var index_barang = index.substring(1, 2);

  var index_fix = index_pengeluaran + '-' + index_barang;

  var sum = 0;

  // populate delete button and get the index
  jQuery(".dynamicform_wrapper .remove-barang").each(function (index) {
    // get the value of each column
    var harga = $('#barangpengeluaran-' + index + '-jlh_harga').val().replace(/,/g, "");
    // sum all of harga
    sum += harga;
  });

  $('#pengeluaran-' + index_pengeluaran + '-jlh_pengeluaran').val(sum);
});

But I think you must add column subtotal, and I will help you with better solution


来源: stackexchange

问:
How to make a cancel button that will undo what you type on the textfields in angularjs?

Sorry, I'm really new to this. I hope someone would help me understand how to undo a textfield after I put data in it.

I have client.js----

```<code>this.client = {
        id: '',
        firstname: '',
        lastname: '',
        age: '',
        new: true
    };

    function cancel() {
        clientService.cancel(vm.client);
        getClients();
        //clear();
    }
</code>```

and clientService.js

```<code>function cancel(client) {
        //newValue[] = clients;
        //cancel_lagi = function (newvalue, oldvalue) {
        //clients.new = 'New Value :' + clients.newValue;
        //clients.old = 'Old Value :' + $scopes.oldValue;
        //clients.oldvalue = oldvalue;
        //client.newValue = oldvalue;

        //--------This doesn't do anything

        //}
    }
</code>```

and my client.html

```<code> <button type="submit" class="btn btn-warning btn-sm" data-ng-click="cancel()">
</code>```

after the user will try to edit a data from the local storage when he/she clicks the cancel button it will return to its previous value.

答:
Try this is your controller. You are going to copy the data before it's changed and use it to revert back on a cancel.

```<code>angular.module('mymodule').controller('MyController', MyController);

/** @ngInject */
function MyController(MyService) {

   var vm = this;

   // However you get the data from your service, not important
   vm.data = MyService.getData();

   // This is where you will save a copy of your data
   var savedData = null;

   vm.edit = function(data) {
      // This is important: this creates a copy of the
      // data so you my revert back to it on the cancel method
      savedData = angular.copy(data);

      // See HTML below: vm.data.property should be bound to the
      // ng-model attribute of a given form control.
   };

   vm.save = function(data) {
      // However you save your data, not important.
      MyService.save(data);

      // Set savedData to null as we don't need it anymore.
      savedData = null;
   };

   vm.cancel = function(data) {
      // Important: set the data back to original.
      data = angular.copy(savedData);

      // Set savedData to null again
      savedData = null;
   };
}
</code>```

HTML:

```<code><div ng-controller="MyController as vm">

   <button ng-click="vm.edit(vm.data)">Edit</button>

   <form>
      <!--
        the vm.data.firstName is bound here and changes to it
        will be reflected in the controller's vm.data. In fact,
        they are the same.
      -->
      <input type="text" ng-model="vm.data.firstName" />

     <!-- save will save the data to your service -->
     <button ng-click="vm.save(vm.data)">Save</button>

     <-- cancel will revert vm.data back to it's original values -->
     <button ng-click="vm.cancel(vm.data)">Cancel</button>

   </form>

</div>
</code>```

This is not a complete example and probably contains errors, however the take away is to copy the data before you use it in the form, then if you cancel, reset the form data with the copy you made.

ContentLicense: CC BY-SA 3.0

Body:
Sorry, I'm really new to this. I hope someone would help me understand how to undo a textfield after I put data in it.

I have client.js----

this.client = {
        id: '',
        firstname: '',
        lastname: '',
        age: '',
        new: true
    };

    function cancel() {
        clientService.cancel(vm.client);
        getClients();
        //clear();
    }

and clientService.js

function cancel(client) {
        //newValue[] = clients;
        //cancel_lagi = function (newvalue, oldvalue) {
        //clients.new = 'New Value :' + clients.newValue;
        //clients.old = 'Old Value :' + $scopes.oldValue;
        //clients.oldvalue = oldvalue;
        //client.newValue = oldvalue;

        //--------This doesn't do anything

        //}
    }

and my client.html

 <button type="submit" class="btn btn-warning btn-sm" data-ng-click="cancel()">

after the user will try to edit a data from the local storage when he/she clicks the cancel button it will return to its previous value.

Body:
Try this is your controller. You are going to copy the data before it's changed and use it to revert back on a cancel.

angular.module('mymodule').controller('MyController', MyController);

/** @ngInject */
function MyController(MyService) {

   var vm = this;

   // However you get the data from your service, not important
   vm.data = MyService.getData();

   // This is where you will save a copy of your data
   var savedData = null;

   vm.edit = function(data) {
      // This is important: this creates a copy of the
      // data so you my revert back to it on the cancel method
      savedData = angular.copy(data);

      // See HTML below: vm.data.property should be bound to the
      // ng-model attribute of a given form control.
   };

   vm.save = function(data) {
      // However you save your data, not important.
      MyService.save(data);

      // Set savedData to null as we don't need it anymore.
      savedData = null;
   };

   vm.cancel = function(data) {
      // Important: set the data back to original.
      data = angular.copy(savedData);

      // Set savedData to null again
      savedData = null;
   };
}

HTML:

<div ng-controller="MyController as vm">

   <button ng-click="vm.edit(vm.data)">Edit</button>

   <form>
      <!--
        the vm.data.firstName is bound here and changes to it
        will be reflected in the controller's vm.data. In fact,
        they are the same.
      -->
      <input type="text" ng-model="vm.data.firstName" />

     <!-- save will save the data to your service -->
     <button ng-click="vm.save(vm.data)">Save</button>

     <-- cancel will revert vm.data back to it's original values -->
     <button ng-click="vm.cancel(vm.data)">Cancel</button>

   </form>

</div>

This is not a complete example and probably contains errors, however the take away is to copy the data before you use it in the form, then if you cancel, reset the form data with the copy you made.


问:
Turn off textarea resizing
I'm trying to turn off textarea resizing in my site; right now I'm using this method:

```<code>.textarea {
    clear:left;
    min-width: 267px;
    max-width: 267px;
    min-height:150px;
    max-height:150px;
}
</code>```

I know that my method is not correct and I'm searching for a better one in JavaScript. I'm a beginner, so the best solution for me will be HTML5 or jQuery.

答:
As per the question, i have listed the answers in javascript

By Selecting TagName

```<code>document.getElementsByTagName('textarea')[0].style.resize = "none";
</code>```

By Selecting Id

```<code>document.getElementById('textArea').style.resize = "none";
</code>```

Title: Turn off textarea resizing

Body:
I'm trying to turn off textarea resizing in my site; right now I'm using this method:

.textarea {
    clear:left;
    min-width: 267px;
    max-width: 267px;
    min-height:150px;
    max-height:150px;
}

I know that my method is not correct and I'm searching for a better one in JavaScript. I'm a beginner, so the best solution for me will be HTML5 or jQuery.

Body:
As per the question, i have listed the answers in javascript

By Selecting TagName

document.getElementsByTagName('textarea')[0].style.resize = "none";

By Selecting Id

document.getElementById('textArea').style.resize = "none";


问:
How to add Badges on UIBarbutton item?
Hi friends am new to iphone developing. Am struggle with add badge values on UIBarbutton item on right side. I have tried but i can't solve this problem. Can anyone help me.

Thanks in advance!

答:
Updated for Swift 3:

use below simple code to add the badge on UIBarButtonItem;

```<code>// Variable Declartion

var badgeCount = Int()

// Instance Method

    func setUpBadgeCountAndBarButton() {
        // badge label
        let label = UILabel(frame: CGRect(x: 10, y: -05, width: 25, height: 25))
        label.layer.borderColor = UIColor.clear.cgColor
        label.layer.borderWidth = 2
        label.layer.cornerRadius = label.bounds.size.height / 2
        label.textAlignment = .center
        label.layer.masksToBounds = true
        label.textColor = .white
        label.font = label.font.withSize(12)
        label.backgroundColor = .red
        label.text = "\(self.badgeCount)"

        // button
        let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
        rightButton.setBackgroundImage(UIImage(named: "notification_dash"), for: .normal)
        rightButton.addTarget(self, action: #selector(notificationBarButtonClick), for: .touchUpInside)
        rightButton.addSubview(label)

        // Bar button item
        let rightBarButtomItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem = rightBarButtomItem
    }

// Call To Method

self.badgeCount = 11
self.setUpBadgeCountAndBarButton()
</code>```

//Note: Increase your badge as per you received notification.You have to write your code as per your decided your logic i.e. how to maintain that badge count number in database.

Enjoy..!

Title: How to add Badges on UIBarbutton item?

Body:
Updated for Swift 3:

use below simple code to add the badge on UIBarButtonItem;

// Variable Declartion

var badgeCount = Int()

// Instance Method

    func setUpBadgeCountAndBarButton() {
        // badge label
        let label = UILabel(frame: CGRect(x: 10, y: -05, width: 25, height: 25))
        label.layer.borderColor = UIColor.clear.cgColor
        label.layer.borderWidth = 2
        label.layer.cornerRadius = label.bounds.size.height / 2
        label.textAlignment = .center
        label.layer.masksToBounds = true
        label.textColor = .white
        label.font = label.font.withSize(12)
        label.backgroundColor = .red
        label.text = "\(self.badgeCount)"

        // button
        let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 35))
        rightButton.setBackgroundImage(UIImage(named: "notification_dash"), for: .normal)
        rightButton.addTarget(self, action: #selector(notificationBarButtonClick), for: .touchUpInside)
        rightButton.addSubview(label)

        // Bar button item
        let rightBarButtomItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem = rightBarButtomItem
    }

// Call To Method

self.badgeCount = 11
self.setUpBadgeCountAndBarButton()

//Note: Increase your badge as per you received notification.You have to write your code as per your decided your logic i.e. how to maintain that badge count number in database.

Enjoy..!


问:
Fixing render blocking CSS on WP

Hello I am trying to fix render blocking CSS recommendation from Google Page speed.

```<code><style>here goes critical path</style>
<link rel="preload" as="style" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" onload="this.rel='stylesheet'" />
<noscript id="aonoscrcss">
<link type="text/css" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" rel="stylesheet" />
</noscript>
</code>```

I use Autoptimize for this purpose, so I inserted critical path and checked defer CSS. However Google doesn't count this as a fixed recommendation.
From this code part, is there any issues that causing it, or it something else? Any hints on how to troubleshoot this issue?

And also Google shows 2 blocking css files with the same name and url.

答:
Your "critical css" is likely considered insufficient by GPSI @Eng80lvl, you'll have to look into that (regenerating it elsewhere or tweaking it yourself).

"inline all" fixes the "render blocking"-warning, but will (except is you have very little CSS) see GPSI complaining about "prioritize visible content" (as the amount of inlined CSS will cause your actual content to be available later, even if part of the same response).

Title: Fixing render blocking CSS on WP

Body:
Hello I am trying to fix render blocking CSS recommendation from Google Page speed.

<link rel="preload" as="style" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" onload="this.rel='stylesheet'" />

<link type="text/css" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" rel="stylesheet" />

I use Autoptimize for this purpose, so I inserted critical path and checked defer CSS. However Google doesn't count this as a fixed recommendation.
From this code part, is there any issues that causing it, or it something else? Any hints on how to troubleshoot this issue?

And also Google shows 2 blocking css files with the same name and url.


问:
InvocationTargetException when trying to switch scene [JavaFX]
Whenever I try switching my scene, I get this error:

```<code>Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
</code>```

Here is the method when I switch the scene:

```<code>public void changeScene(String sceneID) throws Exception{

    Parent newScene = FXMLLoader.load(getClass().getResource(sceneID));
    Scene scene;
    scene = new Scene(newScene, 800, 600);

    window.setScene(scene);

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

答:
```<code>Parent newScene = FXMLLoader.load(getClass().getResource("/fxml/sceneID.fxml"));
</code>```

//If this URL is wrong or any problem in the fxml at this URL then you get Invocation exception or Nullpointer exception etc

```<code>Scene scene;
scene = new Scene(newScene, 800, 600);

window.setScene(scene);
window.show();
</code>```

try this and if you still have trouble then post your FXML here.

Body:
Whenever I try switching my scene, I get this error:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

Here is the method when I switch the scene:

public void changeScene(String sceneID) throws Exception{

    Parent newScene = FXMLLoader.load(getClass().getResource(sceneID));
    Scene scene;
    scene = new Scene(newScene, 800, 600);

    window.setScene(scene);

    window.show();
}

Body:
Parent newScene = FXMLLoader.load(getClass().getResource("/fxml/sceneID.fxml"));

//If this URL is wrong or any problem in the fxml at this URL then you get Invocation exception or Nullpointer exception etc

Scene scene;
scene = new Scene(newScene, 800, 600);

window.setScene(scene);
window.show();

try this and if you still have trouble then post your FXML here.


问:
create factory girl instance inside of creating another factory girl instance
This is what my data looks like in the database:

```<code>{
    "id": 4,
    "name": "New Sad",
    "open": true,
    "description": "The happiest place on earth!",
    "gps": "133.232, 121.021",
    "regionId": 1,
    "location": "{\"regionName\":\"Bishop\",\"regionId\":1}",
    "updatedAt": "2017-12-06T05:24:44.683Z",
    "createdAt": "2017-12-06T05:24:44.683Z"
}
</code>```

I hava jsonb column, this is for searching reason because query all parent tables on the fly is too slow, which is why I am not using factory.assoc. I cannot use assoc and reference what it creates right away.

To define my factory-girl, I thought I could just do this:

```<code>module.exports = async factory => {
  const region = await factory.create('region');
  const area = factory.define('area', Area, () => {
    return {
      name: factory.chance('first'),
      open: true,
      description: factory.chance('sentence', {words: 5}),
      gps: '122.123, 123.342',
      regionId: factory.assoc('region', 'id'),
      location: JSON.stringify({
        regionName: region.dataValues.name,
        regionId: region.dataValues.id,
      }),
    };
  });
  return area;
};
</code>```

Error message:

(node:49078) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Invalid factory 'region requested
  (node:49078) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

答:
Not sure why it didn't work the first time I tried it, but it works like this now:</p>

```<code>const Area = require('../../src/models').Area;

module.exports = factory => {
  const area = factory.define('area', Area, async () => {
    const region = await factory.create('region');
    return {
      name: factory.chance('first'),
      open: true,
      description: factory.chance('sentence', {words: 5}),
      gps: '122.123, 123.342',
      regionId: region.dataValues.id,
      location: JSON.stringify({
        regionName: region.dataValues.name,
        regionId: region.dataValues.id,
      }),
    };
  });
  return area;
};
</code>```

Body:
This is what my data looks like in the database:

{
    "id": 4,
    "name": "New Sad",
    "open": true,
    "description": "The happiest place on earth!",
    "gps": "133.232, 121.021",
    "regionId": 1,
    "location": "{\"regionName\":\"Bishop\",\"regionId\":1}",
    "updatedAt": "2017-12-06T05:24:44.683Z",
    "createdAt": "2017-12-06T05:24:44.683Z"
}

I hava jsonb column, this is for searching reason because query all parent tables on the fly is too slow, which is why I am not using factory.assoc. I cannot use assoc and reference what it creates right away.

To define my factory-girl, I thought I could just do this:

module.exports = async factory => {
  const region = await factory.create('region');
  const area = factory.define('area', Area, () => {
    return {
      name: factory.chance('first'),
      open: true,
      description: factory.chance('sentence', {words: 5}),
      gps: '122.123, 123.342',
      regionId: factory.assoc('region', 'id'),
      location: JSON.stringify({
        regionName: region.dataValues.name,
        regionId: region.dataValues.id,
      }),
    };
  });
  return area;
};

Error message:

(node:49078) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Invalid factory 'region requested
  (node:49078) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Body:
Not sure why it didn't work the first time I tried it, but it works like this now:

const Area = require('../../src/models').Area;

module.exports = factory => {
  const area = factory.define('area', Area, async () => {
    const region = await factory.create('region');
    return {
      name: factory.chance('first'),
      open: true,
      description: factory.chance('sentence', {words: 5}),
      gps: '122.123, 123.342',
      regionId: region.dataValues.id,
      location: JSON.stringify({
        regionName: region.dataValues.name,
        regionId: region.dataValues.id,
      }),
    };
  });
  return area;
};


问:
Textfield in the keyboard
How do you make a keyboard have a textfield inside like the messages app ?</p>

答: It depends what you're trying to do with it. You could simply create a view that looks like the keyboard section and show it right above the keyboard. If you're trying to actually send SMSs/emails, look up the MessageUI documentation. </p>

ContentLicense: CC BY-SA 2.5

Title: Textfield in the keyboard


问:
Get the txt file into the push() method?
Please help me!
    I have Script:

```<code>var titles =[];
titles.push('I want file txt in here');
</code>```

I can not get the txt file into the titles.push, so I need some help!

```<code>function readTextFile(){
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "text.txt", false);
  rawFile.onreadystatechange = function (){
    if(rawFile.readyState === 4){
      if(rawFile.status === 200 || rawFile.status == 0){
        var allText = rawFile.responseText;
        console.log(allText);
      }
    }
  }
  rawFile.send(null);
}
</code>```

答:
I do not have a text file ready to show so I used what you should be reading about XMLHttpRequest.responseText you do not want to use onreadystatechange but maybe xhr.onload I left some console.log()s in the code so you can play around with it.

var titles =[];
titles.push('I want file txt in here');

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText', true);
xhr.responseType = 'text';

xhr.onload = function () {
    if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) {
            //console.log(xhr.response);
            //console.log(xhr.responseText);

            // not needed but do not want to push the entire page
            // to titles so lets find just one title
            var parser = new DOMParser();
            var doc = parser.parseFromString(xhr.responseText, "text/html");
            var title = doc.querySelector('h1');
            // console.log(title);
            titles.push(title);
            logTitles();
        }
    }
};

xhr.send(null);

function logTitles() {
    console.log(titles);
};```

Body:
Please help me!
    I have Script:

var titles =[];
titles.push('I want file txt in here');

I can not get the txt file into the titles.push, so I need some help!

function readTextFile(){
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "text.txt", false);
  rawFile.onreadystatechange = function (){
    if(rawFile.readyState === 4){
      if(rawFile.status === 200 || rawFile.status == 0){
        var allText = rawFile.responseText;
        console.log(allText);
      }
    }
  }
  rawFile.send(null);
}


问:
SparkConf settings not used when running Spark app in cluster mode on YARN
I wrote a Spark application, which sets sets some configuration stuff via SparkConf instance, like this:

```<code>SparkConf conf = new SparkConf().setAppName("Test App Name");

conf.set("spark.driver.cores", "1");
conf.set("spark.driver.memory", "1800m");

conf.set("spark.yarn.am.cores", "1");
conf.set("spark.yarn.am.memory", "1800m");

conf.set("spark.executor.instances", "30");
conf.set("spark.executor.cores", "3");
conf.set("spark.executor.memory", "2048m");

JavaSparkContext sc = new JavaSparkContext(conf);

JavaRDD<String> inputRDD = sc.textFile(...);
...
</code>```

When I run this application with the command (master=yarn & deploy-mode=client)

```<code>spark-submit --class spark.MyApp --master yarn --deploy-mode client /home/myuser/application.jar
</code>```

everything seems to work fine, the Spark History UI shows correct executor information:

But when running it with (master=yarn & deploy-mode=cluster)

my Spark UI shows wrong executor information (~512 MB instead of ~1400 MB):

Also my App name equals Test App Name when running in client mode, but is spark.MyApp when running in cluster mode. It seems that however some default settings are taken when running in Cluster mode. What am I doing wrong here? How can I make these settings for the Cluster mode?

I'm using Spark 1.6.2 on a HDP 2.5 cluster, managed by YARN.

答:
Just to add on to D. Müller's answer:

Same issue happened to me and I tried the settings with some different combination. I am running Pypark 2.0.0 on YARN cluster.

I found that driver-memory must be written during spark submit but executor-memory can be written in script (i.e. SparkConf) and the application will still work.

My application will die if driver-memory is less than 2g. The error is:

ERROR yarn.ApplicationMaster: RECEIVED SIGNAL TERM

ERROR yarn.ApplicationMaster: User application exited with status 143

CASE 1:
driver & executor both written in SparkConf

```<code>spark = (SparkSession
    .builder
    .appName("driver_executor_inside")
    .enableHiveSupport()
    .config("spark.executor.memory","4g")
    .config("spark.executor.cores","2")
    .config("spark.yarn.executor.memoryOverhead","1024")
    .config("spark.driver.memory","2g")
    .getOrCreate())
</code>```

spark-submit --master yarn --deploy-mode cluster myscript.py

CASE 2:
- driver in spark submit
- executor in SparkConf in script

```<code>spark = (SparkSession
    .builder
    .appName("executor_inside")
    .enableHiveSupport()
    .config("spark.executor.memory","4g")
    .config("spark.executor.cores","2")
    .config("spark.yarn.executor.memoryOverhead","1024")
    .getOrCreate())
</code>```

spark-submit --master yarn --deploy-mode cluster --conf spark.driver.memory=2g myscript.py

The job Finished with succeed status. Executor memory correct.

CASE 3:
- driver in spark submit
- executor not written

```<code>spark = (SparkSession
    .builder
    .appName("executor_not_written")
    .enableHiveSupport()
    .config("spark.executor.cores","2")
    .config("spark.yarn.executor.memoryOverhead","1024")
    .getOrCreate())
</code>```

spark-submit --master yarn --deploy-mode cluster --conf spark.driver.memory=2g myscript.py

Apparently the executor memory is not set. Meaning CASE 2 actually captured executor memory settings despite writing it inside sparkConf.

Body:
I wrote a Spark application, which sets sets some configuration stuff via SparkConf instance, like this:

SparkConf conf = new SparkConf().setAppName("Test App Name");

conf.set("spark.driver.cores", "1");
conf.set("spark.driver.memory", "1800m");

conf.set("spark.yarn.am.cores", "1");
conf.set("spark.yarn.am.memory", "1800m");

conf.set("spark.executor.instances", "30");
conf.set("spark.executor.cores", "3");
conf.set("spark.executor.memory", "2048m");

JavaSparkContext sc = new JavaSparkContext(conf);

JavaRDD<String> inputRDD = sc.textFile(...);
...

When I run this application with the command (master=yarn & deploy-mode=client)

spark-submit --class spark.MyApp --master yarn --deploy-mode client /home/myuser/application.jar

everything seems to work fine, the Spark History UI shows correct executor information:

But when running it with (master=yarn & deploy-mode=cluster)

my Spark UI shows wrong executor information (~512 MB instead of ~1400 MB):

Also my App name equals Test App Name when running in client mode, but is spark.MyApp when running in cluster mode. It seems that however some default settings are taken when running in Cluster mode. What am I doing wrong here? How can I make these settings for the Cluster mode?

I'm using Spark 1.6.2 on a HDP 2.5 cluster, managed by YARN.

Body:
Just to add on to D. Müller's answer:

Same issue happened to me and I tried the settings with some different combination. I am running Pypark 2.0.0 on YARN cluster.

I found that driver-memory must be written during spark submit but executor-memory can be written in script (i.e. SparkConf) and the application will still work.

My application will die if driver-memory is less than 2g. The error is:

ERROR yarn.ApplicationMaster: RECEIVED SIGNAL TERM

ERROR yarn.ApplicationMaster: User application exited with status 143

CASE 1:
driver & executor both written in SparkConf

spark = (SparkSession
    .builder
    .appName("driver_executor_inside")
    .enableHiveSupport()
    .config("spark.executor.memory","4g")
    .config("spark.executor.cores","2")
    .config("spark.yarn.executor.memoryOverhead","1024")
    .config("spark.driver.memory","2g")
    .getOrCreate())

spark-submit --master yarn --deploy-mode cluster myscript.py

CASE 2:
- driver in spark submit
- executor in SparkConf in script

spark = (SparkSession
    .builder
    .appName("executor_inside")
    .enableHiveSupport()
    .config("spark.executor.memory","4g")
    .config("spark.executor.cores","2")
    .config("spark.yarn.executor.memoryOverhead","1024")
    .getOrCreate())

spark-submit --master yarn --deploy-mode cluster --conf spark.driver.memory=2g myscript.py

The job Finished with succeed status. Executor memory correct.

CASE 3:
- driver in spark submit
- executor not written

spark = (SparkSession
    .builder
    .appName("executor_not_written")
    .enableHiveSupport()
    .config("spark.executor.cores","2")
    .config("spark.yarn.executor.memoryOverhead","1024")
    .getOrCreate())

spark-submit --master yarn --deploy-mode cluster --conf spark.driver.memory=2g myscript.py

Apparently the executor memory is not set. Meaning CASE 2 actually captured executor memory settings despite writing it inside sparkConf.


问:
" Google API message " : " This API does not support parsing form-encoded input. "
I have written the following javascript to create a tasklist in google:

postData = {'title':'Netsuite List'};
access_token = 'xxxx';

url = 'https://www.googleapis.com/tasks/v1/users/@me/lists';

headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
```

<p>The response says:</p>

<pre class="lang-javascript prettyprint-override"><code>{ "error":
{ "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." }
}
</code>```

What could be the possible error ?

答:
not working

```<code>contentType: 'application/json; charset=UTF-8',
</code>```

try with this

```<code>var headers = { };

headers["Content-Type"] ="application/json ; charset=UTF-8";
//remove to parsing form-encoded input error

data:JSON.stringify( model),
//this use for remove to parse error
</code>```

Example:

```<code>$.ajax({
    type: 'Post',
    url: postUrl,
    headers: headers,
    dataType: 'json',//not required in some case
    data:JSON.stringify( model),
    success: function (data, sts) {
        alert('success');
    },
    error: function (err, sts) {
        var msg;
    }
});
</code>```

Body:
I have written the following javascript to create a tasklist in google:

postData = {'title':'Netsuite List'};
access_token = 'xxxx';

url = 'https://www.googleapis.com/tasks/v1/users/@me/lists';

headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');

The response says:

{ "error":
{ "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." }
}

What could be the possible error ?

Body:
not working

contentType: 'application/json; charset=UTF-8',

try with this

var headers = { };

headers["Content-Type"] ="application/json ; charset=UTF-8";
//remove to parsing form-encoded input error

data:JSON.stringify( model),
//this use for remove to parse error

Example:

$.ajax({
    type: 'Post',
    url: postUrl,
    headers: headers,
    dataType: 'json',//not required in some case
    data:JSON.stringify( model),
    success: function (data, sts) {
        alert('success');
    },
    error: function (err, sts) {
        var msg;
    }
});


问:
Needless Argument in Ruby optparser
I am facing issue with following code for parsing command line options

```<code>#!/usr/bin/env ruby
require 'optparse'

options = {:username=>nil}
optparse = OptionParser.new do|opts|
    # Define the options, and what they d
    opts.on( "--username", "Cassandra username" ) do |username|
        options[:username] = username
    end

    opts.on( '--password', 'Cassandra password' ) do |password|
        options[:password] = password
    end

    opts.on( '--keyspace', 'Cassandra keyspace' ) do |keyspace|
        options[:keyspace] = keyspace
    end
end
puts ARGV

optparse.parse!(ARGV)

puts options
</code>```

When I run this code from commandline as

```<code>./testopt.rb --username=uuuuu --password=xxxxxx --keyspace=test
</code>```

I get following output

```<code>--username=uuuuu
--password=xxxxxx
--keyspace=test
./testopt.rb:25:in `<main>': needless argument: --username=uuuuu (OptionParser::NeedlessArgument)
</code>```

What am missing?
I am in ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]

Thanks in advance

答:
Remove equal signs. OptParser expects spaces between arg names and args:

```<code>./testopt.rb --username uuuuu --password xxxxxx --keyspace test
</code>```

Title: Needless Argument in Ruby optparser

Body:
I am facing issue with following code for parsing command line options

#!/usr/bin/env ruby
require 'optparse'

options = {:username=>nil}
optparse = OptionParser.new do|opts|
    # Define the options, and what they d
    opts.on( "--username", "Cassandra username" ) do |username|
        options[:username] = username
    end

    opts.on( '--password', 'Cassandra password' ) do |password|
        options[:password] = password
    end

    opts.on( '--keyspace', 'Cassandra keyspace' ) do |keyspace|
        options[:keyspace] = keyspace
    end
end
puts ARGV

optparse.parse!(ARGV)

puts options

When I run this code from commandline as

./testopt.rb --username=uuuuu --password=xxxxxx --keyspace=test

I get following output

--username=uuuuu
--password=xxxxxx
--keyspace=test
./testopt.rb:25:in `': needless argument: --username=uuuuu (OptionParser::NeedlessArgument)

What am missing?
I am in ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]

Thanks in advance

Body:
Remove equal signs. OptParser expects spaces between arg names and args:

./testopt.rb --username uuuuu --password xxxxxx --keyspace test


问:
how to view in table from return JSON value using asp.net mvc
When dropdown onchange id is pass to the database and returning corresponding fields

```<code><div class="col-lg-4">
                        <fieldset class="form-group">
                            <label class="form-label" for="exampleInput">Domain Name</label>
                            @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
                        </fieldset>
                    </div>
</code>```

The returned JSON value we need to view corresponding fields in table.

```<code><script>
        $(document).ready(function () {

            $("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data, function (i, item) {

                            var rows = "<tr>"
                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
            })
        });
    </script>
</code>```

Table code

```<code><table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
                        <thead>
                            <tr>
                                @*<th>S#</th>*@
                                <th>Module Name</th>
                                <th>Url</th>
                                @*<th>Roles</th>
                                <th>Action</th>*@
                            </tr>
                        </thead>
                        <tbody>

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

controller code:

```<code>[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            mymodel.viewRoleModules = type.GetRoleModulesViews(id);
            return Json(mymodel, JsonRequestBehavior.AllowGet);

        }
</code>```

In above code it returns 3 arrays value return Json(mymodel, JsonRequestBehavior.AllowGet);

we are pass to javascript but it shows undefined

In above image you can see there is 3 value but i cannot able to pass item.ModuleName  which is present inside the rows.

When the function success also the value shows undefined.

```<code>public List<ViewRoleModules> GetRoleModulesViews(int id)
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
                {
                    List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                    SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@DomainID", id);
                    SqlDataAdapter da = new SqlDataAdapter(com);
                    DataTable dt = new DataTable();

                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    foreach (DataRow dr in dt.Rows)
                    {

                        EmpList.Add(

                            new ViewRoleModules
                            {
                                ModuleID = Convert.ToInt32(dr["ModuleID"]),
                                CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                                DomainID = Convert.ToInt32(dr["DomainID"]),
                                ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                                ModuleName = Convert.ToString(dr["ModuleName"]),
                                FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                                Url = Convert.ToString(dr["Url"]),
                                TabOrder = Convert.ToInt32(dr["TabOrder"]),
                                Style = Convert.ToString(dr["Style"]),
                                Status = Convert.ToString(dr["Status"]),
                                IsTab = Convert.ToString(dr["IsTab"]),
                                ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                                CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                                CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                                ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                                ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                            }
                        );
                    }

                    return EmpList;
                }
            }
</code>```

答:
try this

```<code> public ActionResult ViewModules(int id)
    {
      Domain_Bind();
      userType type = new userType();
      List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
      return Json(EmpList, JsonRequestBehavior.AllowGet);
    }
</code>```

provide the return type instead of using dynamic

Body:
When dropdown onchange id is pass to the database and returning corresponding fields

                        <fieldset class="form-group">
                            Domain Name
                            @Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { @class = "select2-arrow" })
                        </fieldset>

The returned JSON value we need to view corresponding fields in table.

Table code

                                @*S#	*@
                                Module Name
                                Url
                                @*Roles
                                Action	*@

controller code:

[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            mymodel.viewRoleModules = type.GetRoleModulesViews(id);
            return Json(mymodel, JsonRequestBehavior.AllowGet);

        }

In above code it returns 3 arrays value return Json(mymodel, JsonRequestBehavior.AllowGet);

we are pass to javascript but it shows undefined

In above image you can see there is 3 value but i cannot able to pass item.ModuleName  which is present inside the rows.

When the function success also the value shows undefined.

public List<ViewRoleModules> GetRoleModulesViews(int id)
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
                {
                    List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                    SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@DomainID", id);
                    SqlDataAdapter da = new SqlDataAdapter(com);
                    DataTable dt = new DataTable();

                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    foreach (DataRow dr in dt.Rows)
                    {

                        EmpList.Add(

                            new ViewRoleModules
                            {
                                ModuleID = Convert.ToInt32(dr["ModuleID"]),
                                CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                                DomainID = Convert.ToInt32(dr["DomainID"]),
                                ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                                ModuleName = Convert.ToString(dr["ModuleName"]),
                                FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                                Url = Convert.ToString(dr["Url"]),
                                TabOrder = Convert.ToInt32(dr["TabOrder"]),
                                Style = Convert.ToString(dr["Style"]),
                                Status = Convert.ToString(dr["Status"]),
                                IsTab = Convert.ToString(dr["IsTab"]),
                                ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                                CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                                CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                                ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                                ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                            }
                        );
                    }

                    return EmpList;
                }
            }

Body:
try this

 public ActionResult ViewModules(int id)
    {
      Domain_Bind();
      userType type = new userType();
      List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
      return Json(EmpList, JsonRequestBehavior.AllowGet);
    }

provide the return type instead of using dynamic


问:
Cannot convert value of type 'CLLocationCoordinate2D' to expected argument type 'CLLocationDegrees' (aka 'Double')
I have getting user's current location but getting this error  at this line

let region : MKCoordinateRegion = MKCoordinateSpanMake(myLocation, span)

I am getting error at myLocation in above line

Cannot convert value of type 'CLLocationCoordinate2D' to expected argument type 'CLLocationDegrees' (aka 'Double')

I think there may be type casting problem or similar.

What should I do to handle this error I researched a lot of examples but none helped me.

```<code>import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

let manager = CLLocationManager()

@IBOutlet weak var myMap: MKMapView!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations[0]

    let span : MKCoordinateSpan = MKCoordinateSpanMake(1, 1)
    let myLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region : MKCoordinateRegion = MKCoordinateSpanMake(myLocation, span)

    myMap.setRegion(region, animated: true)

    self.myMap.showsUserLocation = true

}

override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
</code>```

答:
You want MKCoordinateRegionMake, not MKCoordinateSpanMake.

And there's lots of other fixes you should make:

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]

    let span = MKCoordinateSpanMake(0.01, 0.01)
    let myLocation = location.coordinate
    let region = MKCoordinateRegionMake(myLocation, span)

    myMap.setRegion(region, animated: true)

    self.myMap.showsUserLocation = true
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have getting user's current location but getting this error  at this line

let region : MKCoordinateRegion = MKCoordinateSpanMake(myLocation, span)

I am getting error at myLocation in above line

Cannot convert value of type 'CLLocationCoordinate2D' to expected argument type 'CLLocationDegrees' (aka 'Double')

I think there may be type casting problem or similar.

What should I do to handle this error I researched a lot of examples but none helped me.

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

let manager = CLLocationManager()

@IBOutlet weak var myMap: MKMapView!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations[0]

    let span : MKCoordinateSpan = MKCoordinateSpanMake(1, 1)
    let myLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region : MKCoordinateRegion = MKCoordinateSpanMake(myLocation, span)

    myMap.setRegion(region, animated: true)

    self.myMap.showsUserLocation = true

}

override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Body:
You want MKCoordinateRegionMake, not MKCoordinateSpanMake.

And there's lots of other fixes you should make:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]

    let span = MKCoordinateSpanMake(0.01, 0.01)
    let myLocation = location.coordinate
    let region = MKCoordinateRegionMake(myLocation, span)

    myMap.setRegion(region, animated: true)

    self.myMap.showsUserLocation = true
}


问:
How to resize image without loosing image content
I want to resize an image to a smaller image like thumbnail. I have used following options

```<code>Bitmap imageBitmap = Bitmap.createScaledBitmap(mBitmap, 200, 700, false);
</code>```

and

```<code>ThumbnailUtils.extractThumbnail()
</code>```

Both of these options cut parts of images. So they don't look good. I just want to reduce image dimensions and don't want to loose image content.

答:
If you want to resize an image without losing quality and images are from drawable/mipmap then you should try pngquant.

https://pngquant.org/

Body:
I want to resize an image to a smaller image like thumbnail. I have used following options

Bitmap imageBitmap = Bitmap.createScaledBitmap(mBitmap, 200, 700, false);

and

ThumbnailUtils.extractThumbnail()

Both of these options cut parts of images. So they don't look good. I just want to reduce image dimensions and don't want to loose image content.


问:
Chart.js Bar Chart - how to chart bars from 0
I'd like to chart the bars extending from zero so that positive numbers grow upwards (as normal) but negative numbers grow downwards from zero. I get instead all numbers starting from a negative baseline.</p>

答:
```<code>public barChartOptions: any = {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true}
            }]
        },
     }
</code>```


问:
Textfields component number validation React js
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

```<code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (
      <div className={cr.container}>
        <div className ={cr.boton}>
          <Divider/>
          <br/>
        </div>

        <div className={cr.rows}>
          <div>
            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />
          </div>
        </div>

        <div className={cr.botonSet}>
          <div className={cr.botonMargin}>
            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>
          </div>
          <div>
            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />
          </div>
        </div>
      </div>
    );
  }
}
</code>```

Can someone help me on this please.

Thanks in advance.

答:
The TextField component can restrict users to entering text using the JavaScript test method:

```<code><TextField
  onChange={(e) => {
     if(e.target.value == '' || (/\D/.test(e.target.value))) {
         this.setState({and_: e.target.value})}
     }
     else {
         return false;
     }
  }
  value={this.state.and_}
  errorText={this.state.and_error}
  floatingLabelText="And"
/>
</code>```

Body:
I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';

export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }

  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {

    return (

          <Divider/>

            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />

            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />

            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />

            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>

            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />

    );
  }
}

Can someone help me on this please.

Thanks in advance.

Body:
The TextField component can restrict users to entering text using the JavaScript test method:

<TextField
  onChange={(e) => {
     if(e.target.value == '' || (/\D/.test(e.target.value))) {
         this.setState({and_: e.target.value})}
     }
     else {
         return false;
     }
  }
  value={this.state.and_}
  errorText={this.state.and_error}
  floatingLabelText="And"
/>


答:
you have to try like this</p>

```<code>public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}
</code>```

Title: How to resize image without loosing image content

Body:
you have to try like this

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}


问:
How should I get Resources(R.string) in viewModel in Android (MVVM and databinding)
I am currently using databinding and MVVM architecture for android. What would be the best way to get string resources in ViewModel.

I am not using the new AndroidViewModel component, eventbus or RxJava

I was going through the aproach of interfaces where Activity will be responsible for providing resources. But recently I found a similar question with this answer where a single class using application context is providing all resources.

Which would be the better approach? or is there something else that I can try?

答:
You can access the context by implementing AndroidViewModel instead of ViewModel.</p>

```<code>class MainViewModel(application: Application) : AndroidViewModel(application) {
    fun getSomeString(): String? {
        return getApplication<Application>().resources.getString(R.string.some_string)
    }
}
</code>```

Body:
You can access the context by implementing AndroidViewModel instead of ViewModel.

class MainViewModel(application: Application) : AndroidViewModel(application) {
    fun getSomeString(): String? {
        return getApplication<Application>().resources.getString(R.string.some_string)
    }
}


问:
Endless spinning wheel at Woocommerce checkout
I am in the process of building a shop on wordpress using woocommerce. All is well except that at checkout there is an endless spinning wheel blocking the payment processing.

I have checked the error logs - which show no errors
I have disabled all plug ins - which makes no difference
I have reverted to the default woocommerce shopfront theme - which has the same result.
The console shows no errors.

I have also followed the instructions here https://docs.woocommerce.com/document/endless-loadingspinner-on-the-checkout-page/ which assumes its a memory limit issue. This did not work.

So, after a bit of digging I found some reference here https://mikejolley.com/2015/11/12/debugging-unexpected-token-in-woocommerce-2-4/ and here https://www.maxsangster.com/blog/woocommerce-endless-loading-spinner-on-checkout/

Referring to these two pages I have been able to see that the json response from /?wc-ajax=checkout is just returning HTML which I would imagine is where the issue is.

However I am running an Apache server rather than Nginx as has been mentioned in some threads and articles. Assuming there is a server misconfiguration of the server or something that needs changing what might that be? Bearing in mind that I do not have direct access to this, so will need to be asking someone else to sort it out for me.

And finally if there is something else I can try what might that be?

答:
Go to Google Developer Tools, then Go to the Network tab. Click the button and make the request and let that bad boy spin out.

You mentioned the response is returning HTML. Click on the request that goes out that appears to be taking forever (/?wc-ajax=checkout) and then click on the Preview tab to display that HTML. I bet it shows an error or a clue, anyway.


问:
How could I connect a program with interface in python
I want to use tkinter to set a interface for my another program, but I do not know what is my next step.

I do not know how to connect each other.

I do not have that concept.

This is the code of trying to be a interface:

```<code>#!/usr/bin/env python -O
import subprocess
from tkinter import *
subprocess.call('/Users/Tsu-
AngChou/MasterProject/Practice/try_test/TEST5.py')

root = Tk(className ="Documents retriever")
svalue = StringVar() # defines the widget state as string
w = Entry(root,textvariable=svalue) # adds a textarea widget
w.pack()
def act():
    print ("you entered")
    print ('%s' % svalue.get())
foo = Button(root,text="Retrieve", command=act)
foo.pack()
root.mainloop()
</code>```

This is the code of my python script:

```<code>#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"
files = listdir(mypath)
storage = {}
translator = str.maketrans("","",string.punctuation)
for f in files:
  fullpath = join(mypath, f)
  if f == '.DS_Store':
            os.remove(f)
  elif isfile(fullpath):

    print(f)
    for html_cont in range(1):
        response = open(f,'r',encoding='utf-8')
        html_cont = response.read()
        soup = bs(html_cont, 'html.parser')
        regular_string = soup.get_text()
        new_string = regular_string.translate(translator).split()
        new_list = [item[:14] for item in new_string]
        a = dict.fromkeys(new_list, f)
        b = a
        storage.update(a)
        print(a)
        storage.append(new_list)

        wordfreq = []
        for w in new_list:
            wordfreq.append(new_list.count(w))
        print("Frequency:\n" ,list(zip(b,wordfreq)))
</code>```

I want to use the value(a) and value(list(zip(b,wordfreq))
How could I give the Button value?

答:
You have some files.py that have functions and classes.

Then, you have an ifmain in each files to test librairies you built. Because this is what you're doing at your own level.

You use, then, a main file to link all of this together. And in your main file you can add an optional argument that takes your program output, and... well. I guess you know what to do next. :)

Body:
I want to use tkinter to set a interface for my another program, but I do not know what is my next step.

I do not know how to connect each other.

I do not have that concept.

This is the code of trying to be a interface:

#!/usr/bin/env python -O
import subprocess
from tkinter import *
subprocess.call('/Users/Tsu-
AngChou/MasterProject/Practice/try_test/TEST5.py')

root = Tk(className ="Documents retriever")
svalue = StringVar() # defines the widget state as string
w = Entry(root,textvariable=svalue) # adds a textarea widget
w.pack()
def act():
    print ("you entered")
    print ('%s' % svalue.get())
foo = Button(root,text="Retrieve", command=act)
foo.pack()
root.mainloop()

This is the code of my python script:

#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"
files = listdir(mypath)
storage = {}
translator = str.maketrans("","",string.punctuation)
for f in files:
  fullpath = join(mypath, f)
  if f == '.DS_Store':
            os.remove(f)
  elif isfile(fullpath):

    print(f)
    for html_cont in range(1):
        response = open(f,'r',encoding='utf-8')
        html_cont = response.read()
        soup = bs(html_cont, 'html.parser')
        regular_string = soup.get_text()
        new_string = regular_string.translate(translator).split()
        new_list = [item[:14] for item in new_string]
        a = dict.fromkeys(new_list, f)
        b = a
        storage.update(a)
        print(a)
        storage.append(new_list)

        wordfreq = []
        for w in new_list:
            wordfreq.append(new_list.count(w))
        print("Frequency:\n" ,list(zip(b,wordfreq)))

I want to use the value(a) and value(list(zip(b,wordfreq))
How could I give the Button value?


问:
Local notification on application termination
I am working on an application which will not work if terminated. It has some background tasks. I want to show a local notification if the app is terminated. There are applications which do this which means this is doable. But I am not able to find out a way.

I have tried to set up a local notification in applicationWillTerminate: method of appdelegate as well as added a notification of app termination in my viewcontroller but none of the methods get called when app is actually terminated.

```<code>- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"terminated");
    UIApplication * app = [UIApplication sharedApplication];
    NSDate *date = [[NSDate date] dateByAddingTimeInterval:15];
    UILocalNotification *alarm = [[UILocalNotification alloc] init] ;
    if (alarm) {
        alarm.fireDate = [NSDate date];
        alarm.timeZone = [NSTimeZone defaultTimeZone];
        alarm.repeatInterval = 0;
        alarm.alertBody = @"This app does not work if terminated";
        alarm.alertAction = @"Open";
        [app scheduleLocalNotification:alarm];
    }

    [app presentLocalNotificationNow:alarm];
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
</code>```

Any help would be great.

Thanks in Advance !!!

答:
From the app double press on home button and swipe to kill app always calls applicationWillTerminate. If you do single press and send the app in background and then double press again to swipe and kill the app, applicationWillTerminate may not be called every time.

```<code>- (void)applicationWillTerminate:(UIApplication *)application
{
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.userInfo =  [NSDictionary dictionaryWithObject:@"killed.app" forKey:@"Killed"];
        notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:2]; // Give some time for firing the notification at least 2 seconds.
        notification.alertBody = @"App is killed.";
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.timeZone = [NSTimeZone systemTimeZone];
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        sleep(1); // I noticed that adding sleep is required as it makes sure the notification is set before the app exits.
}
</code>```

Body:
I am working on an application which will not work if terminated. It has some background tasks. I want to show a local notification if the app is terminated. There are applications which do this which means this is doable. But I am not able to find out a way.

I have tried to set up a local notification in applicationWillTerminate: method of appdelegate as well as added a notification of app termination in my viewcontroller but none of the methods get called when app is actually terminated.

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"terminated");
    UIApplication * app = [UIApplication sharedApplication];
    NSDate *date = [[NSDate date] dateByAddingTimeInterval:15];
    UILocalNotification *alarm = [[UILocalNotification alloc] init] ;
    if (alarm) {
        alarm.fireDate = [NSDate date];
        alarm.timeZone = [NSTimeZone defaultTimeZone];
        alarm.repeatInterval = 0;
        alarm.alertBody = @"This app does not work if terminated";
        alarm.alertAction = @"Open";
        [app scheduleLocalNotification:alarm];
    }

    [app presentLocalNotificationNow:alarm];
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

Any help would be great.

Thanks in Advance !!!

Body:
From the app double press on home button and swipe to kill app always calls applicationWillTerminate. If you do single press and send the app in background and then double press again to swipe and kill the app, applicationWillTerminate may not be called every time.

- (void)applicationWillTerminate:(UIApplication *)application
{
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.userInfo =  [NSDictionary dictionaryWithObject:@"killed.app" forKey:@"Killed"];
        notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:2]; // Give some time for firing the notification at least 2 seconds.
        notification.alertBody = @"App is killed.";
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.timeZone = [NSTimeZone systemTimeZone];
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        sleep(1); // I noticed that adding sleep is required as it makes sure the notification is set before the app exits.
}


问:
Java - Restricting by what a method can be called
I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:

```<code>if(trace.length<2){
    throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
    throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}
</code>```

Is there something else I should be doing, or should I just not forget how my program works?

答:
Try using access rules.

http://groups.google.com/group/google-web-toolkit/browse_thread/thread/90c424dc44db523e

Body:
I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:

if(trace.length<2){
    throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
    throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}

Is there something else I should be doing, or should I just not forget how my program works?


问:
Scrollview with React Native isn't scrolling
I am currently working on a react native project which requires me to make a profile page.  Im trying to use scrollview to render an image with words underneath it.  Here is my code:

```<code>// @flow

import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';

//import PictureScroller from './PictureScroller';
//import TaggButton from './TaggButton';
import styles from './styles';

//import PropTypes from 'prop-types';

type Props = {
  images: Object,
  name: String,
}

const Profile = (props: Props) => {

    return (
      <ScrollView style={styles.scrollView} contentContainerStyle={{flex:1}}>
        <Image source={props.images}/>
        <Text style={styles.name}>props.name</Text>
      </ScrollView>
      );
    }

export default Profile;
</code>```

Please let me know if I should include additional code.

答: What is the value of styles.scrollView? This should have flex: 1.

Body:
I am currently working on a react native project which requires me to make a profile page.  Im trying to use scrollview to render an image with words underneath it.  Here is my code:

// @flow

import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  TouchableWithoutFeedback,
  FlatList,
} from 'react-native';

//import PictureScroller from './PictureScroller';
//import TaggButton from './TaggButton';
import styles from './styles';

//import PropTypes from 'prop-types';

type Props = {
  images: Object,
  name: String,
}

const Profile = (props: Props) => {

    return (
      <ScrollView style={styles.scrollView} contentContainerStyle={{flex:1}}>
        <Image source={props.images}/>
        <Text style={styles.name}>props.name</Text>
      </ScrollView>
      );
    }

export default Profile;

Please let me know if I should include additional code.


问:
unable to access the var variable, scopes in js
I tried with 2 scenarios , In one I could access data variable and other couldn't. need clarification for clearing my scopes concept
Scenario 1 : data not accessible

function test() {
  var data = "from Test";
  secondFunction();
}

function secondFunction() {
  return function() {
    console.log(data);
  }();
}

test();```
</div>
</div>
</p>

<p>Scenario 2: data is accessible</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function test1() {
  var data = "from Test1";
  var secondFunction1 = function() {
    return function() {
      console.log(data);
    }()
  }
  secondFunction1();
}

test1();</code>```

答:
you need to increase scope of you variable to window object , than it will work.
In your current code scope of variable is limited to the function only. so you cannot access variable outside function.

something like will declare variable at larger scope, in below it declare variable at window object so it get accessible to all functions.

```<code>window.data = 1;
</code>```

if you do like this than it is accessible in given window.

Globals are generally to be avoided. You should define variables within the scope of functions.

In your scenario in second case its working because data is in scope of given function , and in first case data is in scope of first function. that is reason it working in second case but not in first case.

in second case

```<code>function test1() {
  var data = "from Test1";
  var secondFunction1 = function() {
    return function() {
      console.log(data);
    }()
  }
  secondFunction1();
}
</code>```

if you see you secondFuction1 is able to get data because the scope is larger , both are part of  test1() .

Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript. That means function inherits from object . Object instances can contain more instances which can be functions.

so if you go by above statement in OOD way, than in you case test1() is object and in that object you have property called data and function called secondFuction1(), and in OOD function can access property of object , so that is reason its working in you second case.

Body:
I tried with 2 scenarios , In one I could access data variable and other couldn't. need clarification for clearing my scopes concept
Scenario 1 : data not accessible

function test() {
  var data = "from Test";
  secondFunction();
}

function secondFunction() {
  return function() {
    console.log(data);
  }();
}

test();

Scenario 2: data is accessible

function test1() {
  var data = "from Test1";
  var secondFunction1 = function() {
    return function() {
      console.log(data);
    }()
  }
  secondFunction1();
}

test1();

Body:
you need to increase scope of you variable to window object , than it will work.
In your current code scope of variable is limited to the function only. so you cannot access variable outside function.

something like will declare variable at larger scope, in below it declare variable at window object so it get accessible to all functions.

window.data = 1;

if you do like this than it is accessible in given window.

Globals are generally to be avoided. You should define variables within the scope of functions.

In your scenario in second case its working because data is in scope of given function , and in first case data is in scope of first function. that is reason it working in second case but not in first case.

in second case

function test1() {
  var data = "from Test1";
  var secondFunction1 = function() {
    return function() {
      console.log(data);
    }()
  }
  secondFunction1();
}

if you see you secondFuction1 is able to get data because the scope is larger , both are part of  test1() .

Anything that is not a primitive type (undefined, null, number, string, boolean) is an object (or an instance) in JavaScript. That means function inherits from object . Object instances can contain more instances which can be functions.

so if you go by above statement in OOD way, than in you case test1() is object and in that object you have property called data and function called secondFuction1(), and in OOD function can access property of object , so that is reason its working in you second case.


问:
NOT BETWEEN in codeigniter not working
I want to ask why the query builder class does not included NOT BETWEEN. The hack i try was this
->where('"mytable.date" not between '." $min_date ".' AND '. "$max_date").

It built this query AND "mytable"."date" "not" between "2017-5-18" AND 2017-6-7.

How can i effectively used this with the codeigniter query builder class or active records.

I am using postgresql driver.

答:
Please try the code below that will work fine in my code: </p>

```<code>$this->db->where("'mytable.date' NOT BETWEEN  '".$min_date."'  AND '".$max_date."'");
</code>```

Title: NOT BETWEEN in codeigniter not working

Body:
Please try the code below that will work fine in my code:

$this->db->where("'mytable.date' NOT BETWEEN  '".$min_date."'  AND '".$max_date."'");


问:
DispatchEvent for TableView
How do i convert this in javafx using TableView instead of Jtable?</p>

```<code> public static void disPatchTable(JTable tblFee, KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) {
            tblFee.dispatchEvent(evt);
}}
</code>```

答:
try this

```<code>public static void disPatchTable(TableView tblFee, KeyEvent evt) {
    if(evt.getCode() == KeyCode.UP || evt.getCode() == KeyCode.DOWN) {
        Event.fireEvent(tblFee, evt);
    }
}
</code>```

If it is a TableCell and an attempt to select a previous/next cell, it may be more appropriate to use selectAboveCell(), selectBelowCell()

Title: DispatchEvent for TableView

Body:
How do i convert this in javafx using TableView instead of Jtable?

 public static void disPatchTable(JTable tblFee, KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) {
            tblFee.dispatchEvent(evt);
}}

Body:
try this

public static void disPatchTable(TableView tblFee, KeyEvent evt) {
    if(evt.getCode() == KeyCode.UP || evt.getCode() == KeyCode.DOWN) {
        Event.fireEvent(tblFee, evt);
    }
}

If it is a TableCell and an attempt to select a previous/next cell, it may be more appropriate to use selectAboveCell(), selectBelowCell()