问:
Why is 'while controller' not working in 'loop controller'?
I need to implement this use case.
I have to use a while controller test fragment in a loop controller and then run a request. After that, I need to run another request which is in a while loop. It should repeat 2 times.
Loop set to =2.

It runs successfully the first time, but the second time it just skips the while controller request.

答:
While Controller can be "skipped" only in case when the "Condition" is (or becomes) false so maybe your test fragment is setting some variable to false or increments a counter to some specific value.

I would recommend adding a Debug Sampler as a last request in the Test Fragment and put the same expression you use in the While Controller condition as its label. Run your test and check the label using View Results Tree listener.  If it's false - find a way to make it true, otherwise your fragment won't be executed second time.

See Using the While Controller in JMeter article to learn more about implementing "While" loops in JMeter tests.


来源: stackexchange

问:
Angular2 - Debug primeng library
I'm using Angular4 and installed primeng by:

```<code>npm install primeng
</code>```

Now I can use primeng but cannot debug it because node_modules\primeng contains only the js (after ts compilation) files.

What can I do in order to debug primeng typescript in my project?

答: I've cloned primeng lib from github url into another project and managed to debug it.</p>

ContentLicense: CC BY-SA 3.0

Title: Angular2 - Debug primeng library

Body:
I'm using Angular4 and installed primeng by:

npm install primeng

Now I can use primeng but cannot debug it because node_modules\primeng contains only the js (after ts compilation) files.

What can I do in order to debug primeng typescript in my project?


问:
Give default value when viewing data on php
i have try to get data with following code

```<code>$result = $viral->getData("SELECT * FROM preview WHERE id=$id");

foreach ($result as $res) {
  $title = $res['title'];
  $promoted = $res['promoted'];
  $photo = $res['file'];
}
</code>```

and i view query result with this code

```<code><p><?php echo $title;?></p>
</code>```

i want when value $title in database is blank it will automatically replace by my default value.

Can i give default value when variable $title is blank ?

答:
try this </p>

```<code> $title = $res['title'];
 echo "<p>" . (($title == "" || $title == NULL) ? "Default Value" : $title) . "</p>"
</code>```

Body:
i have try to get data with following code

$result = $viral->getData("SELECT * FROM preview WHERE id=$id");

foreach ($result as $res) {
  $title = $res['title'];
  $promoted = $res['promoted'];
  $photo = $res['file'];
}

and i view query result with this code

<?php echo $title;?>

i want when value $title in database is blank it will automatically replace by my default value.

Can i give default value when variable $title is blank ?

Body:
try this

 $title = $res['title'];
 echo "<p>" . (($title == "" || $title == NULL) ? "Default Value" : $title) . "</p>"


问:
Magento 2 Error Message 'This is a required field'
I'm looking to change the generic error message in Magento 2. The default error message when an action is required is 'This is a required field'.

Example;

Configurable Product:
If the add the cart button is clicked without an attribute selected, it returns the error 'This is a required field'.
I'd like it to return ''Please select a {attribute_label}'.
This way it will show, 'Please select a size' or 'Please select a colour'.

E-Mail Input Field:
If the email signup field is left blank, and the subscribe button clicked, it returns 'This is a required field'.
I'd prefer it to return 'Please enter your email'.

Please also help me understand if these error messages are called from a translation/language file, or if each field has its own error message associated with itself.

答:
You can see how validation is implemented for each field type in

lib/web/mage/validation.js

Validation rules applied to field are based on form configuration, for example field with 'required-entry' class will return 'This is a required field.' message as you can see in file mentioned above.

To create solution like you described you need to override default validation.js in your theme and add your own validation rules with custom messages.


问:
Tune Model Hyperparameters Module: tune and cross validate at the same time
suppose I'm using the following configuration with the Tune Model Hyperparameters module with a Boosted Decision Tree Regression:

Does this configuration let me tune the hyperparameters so that I'll have the best Coefficient of Determination, and at the same time it guarantees the lowest cross-validation average error?
If so, does anyone knows what the Tune Model Hyperparameters module do using this configuration in more details?

Thank you.

答:
No need of splitting the dataset as train/test is you going to use cross validation to measure the accuracy of the model. No validation data-set needed as a input for the Tune model hyperparameter too.

Here's a simple configuration built to measure the accuracy of a binary classification. See the properties of the Partition & Sample module has adjusted for 10-fold cross validation with a random split.

The evaluation results, indicates the parameters that produced the best models, and their accuracy. The accuracy metrics are calculated from the cross-validation pass, and may vary slightly depending on how many folds you selected.


问:
Hiding Table Rows with jQuery
I'm trying to hide a bunch of table rows using javascript.
I think i've got most of the code correct, I just don't know why it isn't running the hide.

Any help is appreciated.

The code is:

```<code><script type="text/javascript">
    function hideButton()
    {
    $("#showHideButton").on("click", function (e) {
    var button = e.target;
    var node = $(button).parent().parent().next();

    while (!node.hasClass("service-header")) {
        if ($(node).is(":visible")) {
            $(node).hide();
        } else {
            $(node).show();
        }
        node = node.next();
    }
    })}
    </script>
</code>```

The HTML is:

```<code>for (loopHere)
{
    echo "<tr class='service-header'><th>InfoHere</th><th>" . InfoHere . "<button style='float:right' type='button' id='showHideButton' class='btn btn-default' onclick='hideButton()'><span class='dashicons dashicons-arrow-down-alt2'></span></button></th></tr>";
    echo "<tr><td>More Stuff</td></tr>";
    echo "<tr><td>More Stuff</td></tr>";
}
loop
</code>```

I've got no idea why it won't hide the rows on the click, I have tested it on a table with multiple rows that have the class service-header, but haven't had any luck.

答:
Refer below code as per your requirement I have created below example.Hopefully it will solve your problem

$(document).on("click", ".showHideButton",function () {
debugger;
//console.log("this="+this+" && $(this)="+$(this));
if($(this).parent().parent().hasClass("service-header") && $(this).parent().parent().is(":visible")){
     $(this).parent().parent().hide();
     }
     else{
       $(this).parent().parent().show();
     }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<table border="1">
  <tr class="service-header">
      <td>1 (has class)</td>
      <td>1 (has class)</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
   <tr>
      <td>2</td>
      <td>2</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
   <tr class="service-header">
      <td>3 (has class)</td>
      <td>3 (has class)</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
       <tr class="service-header">
      <td>4 (has class)</td>
      <td>4 (has class)</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
   <tr>
      <td>5 </td>
      <td>5</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
</table></code>```

Title: Hiding Table Rows with jQuery

Body:
I'm trying to hide a bunch of table rows using javascript.
I think i've got most of the code correct, I just don't know why it isn't running the hide.

Any help is appreciated.

The code is:

The HTML is:

for (loopHere)
{
    echo "
InfoHere	" . InfoHere . "<button style='float:right' type='button' id='showHideButton' class='btn btn-default' onclick='hideButton()'></button>
";
    echo "
More Stuff
";
    echo "
More Stuff
";
}
loop

I've got no idea why it won't hide the rows on the click, I have tested it on a table with multiple rows that have the class service-header, but haven't had any luck.

Body:
Refer below code as per your requirement I have created below example.Hopefully it will solve your problem

$(document).on("click", ".showHideButton",function () {
debugger;
//console.log("this="+this+" && $(this)="+$(this));
if($(this).parent().parent().hasClass("service-header") && $(this).parent().parent().is(":visible")){
     $(this).parent().parent().hide();
     }
     else{
       $(this).parent().parent().show();
     }
});

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<table border="1">
  <tr class="service-header">
      <td>1 (has class)</td>
      <td>1 (has class)</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
   <tr>
      <td>2</td>
      <td>2</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
   <tr class="service-header">
      <td>3 (has class)</td>
      <td>3 (has class)</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
       <tr class="service-header">
      <td>4 (has class)</td>
      <td>4 (has class)</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
   <tr>
      <td>5 </td>
      <td>5</td>
      <td><button  type='button'  class='showHideButton btn btn-default'>show/hide</button></td>
   </tr>
</table>


问:
Android Studio: Run/Debug Configurations unable to create application
Hi I'm having a problem in creating a configuration in Android. Last week this one is still working and i can able to run it but opening it today the configuration is unknown already. I didn't do anything for the codes last week I just run it.

Here's the screenshot of my Run/Debug Configurations.

I tried creating new application run/debug configuration but running it display

an icon with cross

also display "Error Running SyncActivity: No JDK specified"

I'm using Android Studio and I'm new in this project android.
Thank you in advance

答:
You need to set the JDK for your project and/or modules.

Open the project settings (File->Project settings...).

Most of the time you just need to set the project sdk (to your java sdk) and configure the modules to use the project sdk.
Probably one of those settings is missing.


问:
.gitignore not ignoring .cs.meta files
All I want is for for git to ignore files that end in .cs.meta.

My .gitignore file includes just this:

```<code># ignore all .cs.meta files
*.cs.meta
</code>```

How can ignore only files that end in .cs.meta?

答:
To make sure any of your ignored file is not present in the index:

```<code>git ls-files --ignored --exclude-standard -z|xargs -0 git rm --cached
git commit -am "Remove ignored files"
</code>```

Then you can check if your files are ignored with:

```<code>git check-ignore -v -- /path/to/a/file.cs.meta
</code>```

It should display your ignore rule now.

Title: .gitignore not ignoring .cs.meta files

Body:
All I want is for for git to ignore files that end in .cs.meta.

My .gitignore file includes just this:

# ignore all .cs.meta files
*.cs.meta

How can ignore only files that end in .cs.meta?

Body:
To make sure any of your ignored file is not present in the index:

git ls-files --ignored --exclude-standard -z|xargs -0 git rm --cached
git commit -am "Remove ignored files"

Then you can check if your files are ignored with:

git check-ignore -v -- /path/to/a/file.cs.meta

It should display your ignore rule now.


问:
Tensorflow Slower on Python 3 vs. Python 2
My tests show that Tensorflow GPU operations are ~6% slower on Python 3 compared to Python 2. Does anyone have any insight on this?

Platform:

Ubuntu 16.04.2 LTS

Virtualenv 15.0.1

Python 2.7.12

Python 3.6.1

TensorFlow 1.1

CUDA Toolkit 8.0.44

CUDNN 5.1

GPU: GTX 980Ti

CPU: i7 4 GHz

RAM: 32 GB

答: When operating Tensorflow from python most code to feed the computational engine with data resides in python domain. There are known differences between python 2/3 when it comes to performance on various tasks. Therefore, I'd guess that the python code you use to feed the net (or TF python layer, which is quite thick) makes heavy use of python features that are (by design) a bit slower in python 3.</p>


问:
why my django site in hosting (alwaysdata) cant show my page
I have deployed Django at alwaysdata.com,

this is my main page on http://zjm1126.alwaysdata.net/ :

i change the index.html to index1.html, this file is not my file ,

my project is like this :

```<code>example_project/
    __init__.py
    manage.py
    public/
        django.fcgi
        .htaccess
        media/
    settings.py
    urls.py
    myapp/
        views.py
        models.py
</code>```

what can i do to show my main page .

thanks

答:
I think that you need to point your subdomain to the right directory : /example_project/public/ where your .htaccess and django.fcgi lives.

alwaysdata has a forum http://forum.alwaysdata.com/ where you can ask question in english. The guys know their job very well and answer very quickly.

I hope it helps

ContentLicense: CC BY-SA 2.5

Body:
I have deployed Django at alwaysdata.com,

this is my main page on http://zjm1126.alwaysdata.net/ :

i change the index.html to index1.html, this file is not my file ,

my project is like this :

example_project/
    __init__.py
    manage.py
    public/
        django.fcgi
        .htaccess
        media/
    settings.py
    urls.py
    myapp/
        views.py
        models.py

what can i do to show my main page .

thanks


问:
How to keep focus after validation when use tab key
I have input text fields in jsp, and I use onChange="validation(this);" to check if null input and so on, but when I use tab key, cursor will be move to next field, how can keep cursor on validation field?</p>

```<code>function validation(id) {
    var obj = document.getElementById(id);
    obj.value = obj.value.toUpperCase();

    if(value == "") {
        obj.focus();
        obj.select();
    }
 }
</code>```

答:
You can add an event on 'blur'. There after check for the keyCode. For tab key it is 0. Using an setTimeout since the current element will loss focus as soon as the is a onblur event. Therefore providing a sufficient time gap before focusing back on the element

var obj = document.getElementById('inputField');
obj.addEventListener('blur', function(event) {
  if (event.which === 0 && event.target.value == '') {
    setTimeout(function(){
    event.target.focus();
  },1000)

  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id='inputField' onchange='validation(this.id)'></code>```

Body:
I have input text fields in jsp, and I use onChange="validation(this);" to check if null input and so on, but when I use tab key, cursor will be move to next field, how can keep cursor on validation field?

function validation(id) {
    var obj = document.getElementById(id);
    obj.value = obj.value.toUpperCase();

    if(value == "") {
        obj.focus();
        obj.select();
    }
 }

Body:
You can add an event on 'blur'. There after check for the keyCode. For tab key it is 0. Using an setTimeout since the current element will loss focus as soon as the is a onblur event. Therefore providing a sufficient time gap before focusing back on the element

var obj = document.getElementById('inputField');
obj.addEventListener('blur', function(event) {
  if (event.which === 0 && event.target.value == '') {
    setTimeout(function(){
    event.target.focus();
  },1000)

  }
})

<input id='inputField' onchange='validation(this.id)'>


问:
Cordova : Unable to install apk after upgrading android to 5.1.1 Nexus 5
Unable to run apk on nexus 5 after upgrading to 5.1.1

Using Cordova: 5.0.0
Device : Nexus 5
Machine : MAC

BUILD SUCCESSFUL

Total time: 8.432 secs
Built the following apk(s):
    /Applications/XAMPP/xamppfiles/htdocs/android/kaljacobs/platforms/android/build/outputs/apk/android-debug.apk
Using apk: /Applications/XAMPP/xamppfiles/htdocs/android/kaljacobs/platforms/android/build/outputs/apk/android-debug.apk
Installing app on device...

/Applications/XAMPP/xamppfiles/htdocs/android/kaljacobs/platforms/android/cordova/node_modules/q/q.js:126
                    throw e;
                          ^
ERROR: Failed to launch application on device: ERROR: Failed to install apk to device:  pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]

ERROR running one or more of the platforms: Error: /Applications/XAMPP/xamppfiles/htdocs/android/kaljacobs/platforms/android/cordova/run: Command failed with exit code 8
You may not have the required environment or OS to run this project
```

答:
Don't worry about that.for NEXUS 5.go to Settings>> apps>> search application.

Well done..


问:
Azure WebJobs Scheduler
Can we have multiple Schedules in a Single web Job of Microsoft Azure.
We have certain functionalities  to happen in a single job within particular time
i.e multiple schedules so we have tried through the timer but i need to know is there any other option.Thank you </p>

答: You can always use CRON expression for web jobs to e.g., let it run at particular times. You can refer to this official doc.</p>

Title: Azure WebJobs Scheduler


问:
jQuery datepicker, Set the date format for knockout observable
Using the jQuery/jQueryUI datepicker, how do I set the date format for a knockout observable that is has a data-bind on the [aforementioned] datepicker?

I have already set the format using:

```<code><input type="text" data-bind="datepicker: ExampleDate, datepickerOptions: { datePattern: 'DD-MM-YYYY', .... }" />
</code>```

But this does not reflect on the knockout variable. The date remains as the JavaScript format which cannot be interpreted by the backend, like C# .Net.

答:
Creating a knockout custombinding for datepicker will allow for this date formatting.

Amending this answer (fixing the "changeDate" error and adding the observable setter) https://stackoverflow.com/a/6613255/712700, the following will do it:

```<code>ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datepickerOptions || {},
            $el = $(element);

        $el.datepicker(options);

        //handle the field changing by registering datepicker's changeDate event
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($el.datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $el.datepicker("destroy");
        });
        var dateValue = $el && $el.length > 0 ? $el[0].value : undefined;
        if (dateValue) {
            valueAccessor()(dateValue);
        }
    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            $el = $(element);

        //handle date data coming via json from Microsoft
        if (String(value).indexOf('/Date(') == 0) {
            value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
        }

        var current = $el.datepicker("getDate");

        if (value - current !== 0) {
            $el.datepicker("setDate", value);
        }
        var dateValue = $el && $el.length > 0 ? $el[0].value : undefined;
        if (dateValue) {
            valueAccessor()(dateValue);
        }
    }
};
</code>```

The part which sets the knockout observable is this:

```<code>var dateValue = $el && $el.length > 0 ? $el[0].value : undefined;
if (dateValue) {
   valueAccessor()(dateValue);
}
</code>```

Note also, if you are using C# .Net and you have some dates coming in (initially) from the backend to JS land, you can format your date at that time so it doesn't become the JavaScript one, and instead it will be a friendly one that the backend will accept if you happen to pass it back. This is how you would do it for Newtonsoft:

```<code>var backendSerialisedModel = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "dd-MM-yyyy" }));
</code>```

Body:
Using the jQuery/jQueryUI datepicker, how do I set the date format for a knockout observable that is has a data-bind on the [aforementioned] datepicker?

I have already set the format using:

<input type="text" data-bind="datepicker: ExampleDate, datepickerOptions: { datePattern: 'DD-MM-YYYY', .... }" />

But this does not reflect on the knockout variable. The date remains as the JavaScript format which cannot be interpreted by the backend, like C# .Net.

Body:
Creating a knockout custombinding for datepicker will allow for this date formatting.

Amending this answer (fixing the "changeDate" error and adding the observable setter) https://stackoverflow.com/a/6613255/712700, the following will do it:

ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datepickerOptions || {},
            $el = $(element);

        $el.datepicker(options);

        //handle the field changing by registering datepicker's changeDate event
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($el.datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $el.datepicker("destroy");
        });
        var dateValue = $el && $el.length > 0 ? $el[0].value : undefined;
        if (dateValue) {
            valueAccessor()(dateValue);
        }
    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            $el = $(element);

        //handle date data coming via json from Microsoft
        if (String(value).indexOf('/Date(') == 0) {
            value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
        }

        var current = $el.datepicker("getDate");

        if (value - current !== 0) {
            $el.datepicker("setDate", value);
        }
        var dateValue = $el && $el.length > 0 ? $el[0].value : undefined;
        if (dateValue) {
            valueAccessor()(dateValue);
        }
    }
};

The part which sets the knockout observable is this:

var dateValue = $el && $el.length > 0 ? $el[0].value : undefined;
if (dateValue) {
   valueAccessor()(dateValue);
}

Note also, if you are using C# .Net and you have some dates coming in (initially) from the backend to JS land, you can format your date at that time so it doesn't become the JavaScript one, and instead it will be a friendly one that the backend will accept if you happen to pass it back. This is how you would do it for Newtonsoft:

var backendSerialisedModel = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "dd-MM-yyyy" }));


问:
What is framework means?
I am new to IT field. I am learning Ruby cucumber for testing. Can anyone explain what is framework means? Why cucumber is called a frame work? What exactly the framework will do?
Please expalin me in layman terms... </p>

答: a framework is an  “Inversion of Control”. If you know what library is then framework is a library that calls your code instead of you calling the library and getting data , a framework as a library makes a call-back to your code. </p>

Title: What is framework means?


问:
ArrayList Database MySQL
Have very limited experience with databases and trying to figure out the best method for creating a growing database of users and keeping track of their growing information when added.

For instance, I have 3 users - Apple, Banana, Cherry. And they all have a list of information associated with them.

```<code>  Apple: [1/1/17, green, 3], [2/4/17, red, 5], [4/19/17, blue, 2]
  Banana: [2/18/17, yellow, 6], [5/14/17, yellow, 5]
  Cherry: [5/21/17, green, 12], [8/2/17, red, 5], [9/29/17, blue, 42],
  [1/1/17, green, 3]
</code>```

Before even getting into working with a growing list, how does this get applied to a database?

Do I create a main database, something like FruitDatabase, and then inside those databases have Apple, Banana, and Cherry as their own tables?

Or does each user get their own database and then their associated information get applied to their own table (that doesn't seem efficient)?

What if I later want to add up all of Apple's number (3+5+2), what's the best method of doing that? It doesn't seem like I can put an ArrayList into a database, do I just convert it into a string and separate the number with a comma? And if I want to add a new user, DragonFruit, is it more efficient to add it as a column or row?

答:
The way this works is that you should have 1 database/schema for your entire application say Fruit_Management. Within that you should have one table called Fruits.
This Fruits table will have 5 columns namely id, type, date, colour and qty.
which will map to 1, Apple, 1/1/17, green, 3. Now if you want to get the total number of apples you write aggregation queries like select count(*) from Fruits where Fruits.type='Apple'.

This way your schema remains flexible and normalized.

Title: ArrayList Database MySQL

Body:
Have very limited experience with databases and trying to figure out the best method for creating a growing database of users and keeping track of their growing information when added.

For instance, I have 3 users - Apple, Banana, Cherry. And they all have a list of information associated with them.

  Apple: [1/1/17, green, 3], [2/4/17, red, 5], [4/19/17, blue, 2]
  Banana: [2/18/17, yellow, 6], [5/14/17, yellow, 5]
  Cherry: [5/21/17, green, 12], [8/2/17, red, 5], [9/29/17, blue, 42],
  [1/1/17, green, 3]

Before even getting into working with a growing list, how does this get applied to a database?

Do I create a main database, something like FruitDatabase, and then inside those databases have Apple, Banana, and Cherry as their own tables?

Or does each user get their own database and then their associated information get applied to their own table (that doesn't seem efficient)?

What if I later want to add up all of Apple's number (3+5+2), what's the best method of doing that? It doesn't seem like I can put an ArrayList into a database, do I just convert it into a string and separate the number with a comma? And if I want to add a new user, DragonFruit, is it more efficient to add it as a column or row?


问:
Will conditionals that are always false be removed by compiler in C#
Say I have the following code snippet in c#

```<code>static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}
</code>```

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

答:
you can define your own constants either at the top of the file:

```<code> #define SUPERDOOPERDEBUG

 using System;

 ....

 #if SUPERDOOPERDEBUG

     // something

 #endif
</code>```

Also, you can set up different build configurations than just 'release' and 'debug' (See the Build -> Configuration menu or define additional Conditional compilation symbols in the Project -> properties menu

OwnerDisplayName: WindyCityEagle

Body:
Say I have the following code snippet in c#

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

LastEditorDisplayName: Dana

Body:
you can define your own constants either at the top of the file:

 #define SUPERDOOPERDEBUG

 using System;

 ....

 #if SUPERDOOPERDEBUG

     // something

 #endif

Also, you can set up different build configurations than just 'release' and 'debug' (See the Build -> Configuration menu or define additional Conditional compilation symbols in the Project -> properties menu

OwnerDisplayName: Jimmy


问:
Separate functions from the same class in multiple files
Is it a good practice to separate the functions of the same class in multiple .cpp files or all the functions should be in the same file?

For example:

foobar.h

```<code>#ifndef FOOBAR_H
#define FOOBAR_H

#include <QDebug>

class FooBar
{
public:
    FooBar();

    void foo();
    void bar();
};

#endif // FOOBAR_H
</code>```

foobar.cpp

```<code>#include "foobar.h"

FooBar::FooBar()
{
    qDebug() << "Constructor";
}
</code>```

foo.cpp

```<code>#include "foobar.h"

void FooBar::foo()
{
    qDebug() << "Foo";
}
</code>```

bar.cpp

```<code>#include "foobar.h"

void FooBar::bar()
{
    qDebug() << "Bar";
}
</code>```

Note: I only added the Qt tag because the example was generated in Qt, but this is a C++ related question.

答:
The machine doesn't care. So the sole driver for your decision will be the human at the center of it all: the developer.

Consider a book. Would you rather have the book as a complete entity, perhaps separated into chapters, or chunked into paragraphs on little pieces of paper? Locality of reference is important, and the implementation of a class should fit into a single file. Implementations of closely related classes could also all go into a single file if the code is easier to maintain that way. Heck, the entire project could go into a single file if it's small enough.

Personally, I find that things get hard to navigate after a single .cpp file is more than 3-4k lines long. But having lots of files with less than 500 lines each in them is just as painful. IDEs reduce some of the pain by providing easier navigation between the uses, declarations and definitions, of course, but files too small are almost never helpful in project comprehension. E.g. Java's insistence on one-public-class-per-file and on a 1:1 relationship between is a scourge in this respect and is at odds with what we know of cognitive psychology.

Body:
Is it a good practice to separate the functions of the same class in multiple .cpp files or all the functions should be in the same file?

For example:

foobar.h

#ifndef FOOBAR_H
#define FOOBAR_H

#include <QDebug>

class FooBar
{
public:
    FooBar();

    void foo();
    void bar();
};

#endif // FOOBAR_H

foobar.cpp

#include "foobar.h"

FooBar::FooBar()
{
    qDebug() << "Constructor";
}

foo.cpp

#include "foobar.h"

void FooBar::foo()
{
    qDebug() << "Foo";
}

bar.cpp

#include "foobar.h"

void FooBar::bar()
{
    qDebug() << "Bar";
}

Note: I only added the Qt tag because the example was generated in Qt, but this is a C++ related question.


问:
getting exception after encrypting password of conf/axis2/axsi2.xml
getting exception after encrypting password of conf/axis2/axsi2.xml , i have used ciphertool.sh to encrypt the password.
i was able to encrypt the other files of /repository/conf dir .

Did anyone faced same issue.
Thanks you.

答:
we have seen problem to Encrypt axis2.xml .But after using below aliases and x-path we were able to encrypt passwords for axis2.xml:
Axis2.Https.Listener.TrustStore.Password=repository/conf/axis2/axis2.xml//axisconfig/transportReceiver[@name='https']/parameter[@name='truststore']/TrustStore/Password,false

Axis2.Https.Listener.KeyStore.Password=repository/conf/axis2/axis2.xml//axisconfig/transportReceiver[@name='https']/parameter[@name='keystore']/KeyStore/Password,false

Axis2.Https.Listener.KeyStore.KeyPassword=repository/conf/axis2/axis2.xml//axisconfig/transportReceiver[@name='https']/parameter[@name='keystore']/KeyStore/KeyPassword,false

Axis2.Https.Sender.TrustStore.Password=repository/conf/axis2/axis2.xml//axisconfig/transportSender[@name='https']/parameter[@name='truststore']/TrustStore/Password,false

Axis2.Https.Sender.KeyStore.Password=repository/conf/axis2/axis2.xml//axisconfig/transportSender[@name='https']/parameter[@name='keystore']/KeyStore/Password,false

Axis2.Https.Sender.KeyStore.KeyPassword=repository/conf/axis2/axis2.xml//axisconfig/transportSender[@name='https']/parameter[@name='keystore']/KeyStore/KeyPassword,false


问:
Multiple file upload validation in laravel
I have multiple input fields with multiple file upload for each field.

```<code><?php for ($i = 0; $i < $total; $i++)
   {
?>
<div class="col-md-3 addedClass">
     <label>Vehicle Images</label>
     <input type="file" name="vehicle_image[{{$i}}][]" multiple="multiple">
     @if($errors->has('vehicle_image'))
          <span class="help-block">
              <strong>{{$errors->first('vehicle_image')}}</strong>
          </span>
     @endif
</div>
<?php } ?>
</code>```

I have got files in the request like this:

```<code>"vehicle_image" => array:2 [▼
    0 => array:2 [▼
      0 => "citizenship.jpg"
      1 => "logo_vehicle.png"
    ]
    1 => array:2 [▼
      0 => "ae backend.jpg"
      1 => "logo_vehicle.png"
    ]
  ]
</code>```

In this case, I have two input fields with 2/2 files. When I have tried to validate mime type for only images like this:

```<code>$this->validate($request,[
           'vehicle_image' => 'mimes:jpeg,png,bmp,tiff |max:4096'
       ],$messages[
            // error messages
      ]);
</code>```

I have got following error:

FatalThrowableError in ReservationController.php line 67: Cannot use [] for reading

Can someone tell me what is wrong with the above code ?
Suggestions are appreciated.

答:
Try removing the blank $messages array and calling the function all() for the  inputs on the request.

```<code>$rules = [
    'vehicle_image' => 'mimes:jpeg,png,bmp,tiff |max:4096'
];
$this->validate($request,$rules);
</code>```

To display the default error message you would throw an exception using something like:

```<code>    if ($validator->fails()) {
        $this->throwValidationException(
            $request, $validator
        );
        return redirect('VIEWPATH.VIEWNAME')->withErrors($validator)->withInput();
    }
</code>```

Then to display the errors you can have something like the following in your blade view or template:

```<code>@if (count($errors) > 0)
  <div class="alert alert-danger alert-dismissable fade in">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
    <h4>
      <i class="icon fa fa-warning fa-fw" aria-hidden="true"></i>
      <strong>Error!</strong> See error messages...
    </h4>
    <ul>
      @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
      @endforeach
    </ul>
  </div>
@endif
</code>```

or

```<code>@if(session()->has('errors'))
    <div class="alert alert-danger fade in">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <h4>Following errors occurred:</h4>
        <ul>
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
</code>```

Body:
I have multiple input fields with multiple file upload for each field.

<?php for ($i = 0; $i < $total; $i++)
   {
?>

     Vehicle Images
     <input type="file" name="vehicle_image[{{$i}}][]" multiple="multiple">
     @if($errors->has('vehicle_image'))

              {{$errors->first('vehicle_image')}}

     @endif

<?php } ?>

I have got files in the request like this:

"vehicle_image" => array:2 [▼
    0 => array:2 [▼
      0 => "citizenship.jpg"
      1 => "logo_vehicle.png"
    ]
    1 => array:2 [▼
      0 => "ae backend.jpg"
      1 => "logo_vehicle.png"
    ]
  ]

In this case, I have two input fields with 2/2 files. When I have tried to validate mime type for only images like this:

$this->validate($request,[
           'vehicle_image' => 'mimes:jpeg,png,bmp,tiff |max:4096'
       ],$messages[
            // error messages
      ]);

I have got following error:

FatalThrowableError in ReservationController.php line 67: Cannot use [] for reading

Can someone tell me what is wrong with the above code ?
Suggestions are appreciated.

Body:
Try removing the blank $messages array and calling the function all() for the  inputs on the request.

$rules = [
    'vehicle_image' => 'mimes:jpeg,png,bmp,tiff |max:4096'
];
$this->validate($request,$rules);

To display the default error message you would throw an exception using something like:

    if ($validator->fails()) {
        $this->throwValidationException(
            $request, $validator
        );
        return redirect('VIEWPATH.VIEWNAME')->withErrors($validator)->withInput();
    }

Then to display the errors you can have something like the following in your blade view or template:

@if (count($errors) > 0)
  <div class="alert alert-danger alert-dismissable fade in">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    <h4>
      <i class="icon fa fa-warning fa-fw" aria-hidden="true"></i>
      <strong>Error!</strong> See error messages...
    </h4>
    <ul>
      @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
      @endforeach
    </ul>
  </div>
@endif

or

@if(session()->has('errors'))
    <div class="alert alert-danger fade in">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <h4>Following errors occurred:</h4>
        <ul>
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif


问:
redux-form, change fields value without changing dirty state
I have a field that shouldn't have effect on form's dirty state.
Is there a way to change it's value without changing it's dirty state?
Can I set it's initial value somehow, without initializing whole form?</p>

答:
Here's my solution; but I warn you, it's not very pretty.

In your reducer.plugin(), you get passed state and action. The form is considered dirty if the state.values object is equal to the state.initial object (they are compared in isPristine.js). The reducer returns the new state, so in the reducer I changed initial.

See what I do to specialField here:

```<code>return {
  ...state,
  /* snip */

  initial: {
    ...state.initial,
    specialField
  }
}
</code>```

Maybe that's subverting something important, but it worked for me.

Hope this helps!

Body:
Here's my solution; but I warn you, it's not very pretty.

In your reducer.plugin(), you get passed state and action. The form is considered dirty if the state.values object is equal to the state.initial object (they are compared in isPristine.js). The reducer returns the new state, so in the reducer I changed initial.

See what I do to specialField here:

return {
  ...state,
  /* snip */

  initial: {
    ...state.initial,
    specialField
  }
}

Maybe that's subverting something important, but it worked for me.

Hope this helps!


问:
jquery click, toggle one or more div block
I am trying to build a jQuery when clicked on div #toggle, span inside div will show and when set to toggle mode, but when I use two or more div blocks, it only shows the first span. please help.

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='toggle'>this clicked
  <span id='show'><p>Show this</p></span>
</div>
<div id='toggle'>
  <span id='show'><p>fhslkjklsfjl</p></span>
</div></code>```

答:
Try This :-

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='toggle'>this clicked
      <span id='show'><p>Show this</p></span>
    </div>
    <div id='toggle'>2 nd button
      <span id='show'><p>fhslkjklsfjl</p></span>
    </div>

       $("div#toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  });
</code>```

https://jsfiddle.net/9oh6yqfn/9/

Body:
I am trying to build a jQuery when clicked on div #toggle, span inside div will show and when set to toggle mode, but when I use two or more div blocks, it only shows the first span. please help.

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});

this clicked

Show this

fhslkjklsfjl

Body:
Try This :-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='toggle'>this clicked
      <span id='show'><p>Show this</p></span>
    </div>
    <div id='toggle'>2 nd button
      <span id='show'><p>fhslkjklsfjl</p></span>
    </div>

       $("div#toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  });

https://jsfiddle.net/9oh6yqfn/9/


问:
OpenAL vs AVAudioPlayer vs other techniques for playing sounds
I know that OpenAL is fast library but it doesn't support any compressed audio format and it's not so easy to use...

AVAudioPlayer is not so fast, but supports wide range file formats, as well as compressed formats like mp3.

Also there is an SKAction class which can play a sound, as well as SystemSoundID...

I have few questions:

What would be a preferred way/player/technique to play :

sound effects(multiple at the time)?

sound effects which can be sometimes repeated after small time delay

background music that loops

Also, is it smart move to use uncompressed audio for sound effects? I suppose this is ok, because those files have small size anyway?

答:
Here's a port of @patrick's solution to Swift 3.</p>

```<code>import AVFoundation

// MARK -
// MARK setup sound

// get a repeating sound
func setupRepeatingSound(file: String, volume: Float) -> AVAudioPlayer? {
    let sound: AVAudioPlayer? = setupSound(file: file, volume: volume)
    sound?.numberOfLoops = -1
    return sound
}

// setup a sound
func setupSound(file: String, volume: Float) -> AVAudioPlayer? {
    var sound: AVAudioPlayer?
    if let path = Bundle.main.path(forResource: file, ofType:nil) {
        let url = NSURL(fileURLWithPath: path)
        do {
            sound = try AVAudioPlayer(contentsOf: url as URL)
        } catch {
            // couldn't load file :(
        }
    }
    sound?.numberOfLoops = 0
    sound?.volume = volume
    sound?.prepareToPlay()
    return sound
}

// MARK sound controls

// play a sound now through GCD
func playSound(_ sound: AVAudioPlayer?) {
    if sound != nil {
        DispatchQueue.global(qos: .default).async {
            sound!.play()
        }
    }
}

// play a sound later through GCD
func playSound(_ sound: AVAudioPlayer?, afterDelay: Float) {
    if sound != nil {
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(afterDelay)) {
            sound!.play()
        }
    }
}

// pause a currently running sound (mostly for background music)
func pauseSound(_ sound: AVAudioPlayer?) {
    sound?.pause()
}
</code>```

Body:
Here's a port of @patrick's solution to Swift 3.

import AVFoundation

// MARK -
// MARK setup sound

// get a repeating sound
func setupRepeatingSound(file: String, volume: Float) -> AVAudioPlayer? {
    let sound: AVAudioPlayer? = setupSound(file: file, volume: volume)
    sound?.numberOfLoops = -1
    return sound
}

// setup a sound
func setupSound(file: String, volume: Float) -> AVAudioPlayer? {
    var sound: AVAudioPlayer?
    if let path = Bundle.main.path(forResource: file, ofType:nil) {
        let url = NSURL(fileURLWithPath: path)
        do {
            sound = try AVAudioPlayer(contentsOf: url as URL)
        } catch {
            // couldn't load file :(
        }
    }
    sound?.numberOfLoops = 0
    sound?.volume = volume
    sound?.prepareToPlay()
    return sound
}

// MARK sound controls

// play a sound now through GCD
func playSound(_ sound: AVAudioPlayer?) {
    if sound != nil {
        DispatchQueue.global(qos: .default).async {
            sound!.play()
        }
    }
}

// play a sound later through GCD
func playSound(_ sound: AVAudioPlayer?, afterDelay: Float) {
    if sound != nil {
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(afterDelay)) {
            sound!.play()
        }
    }
}

// pause a currently running sound (mostly for background music)
func pauseSound(_ sound: AVAudioPlayer?) {
    sound?.pause()
}


问:
Difference between same value in array using only one loop javascript
How to find the difference between the min and max indexes of the same value in an array with one loop with complexity exactly O(N)?

For example, given array A:

```<code>[4, 6, 2, 2, 6, 6, 1];
</code>```

the function returns 4.

答:
I'd use reduce to remember the first index of each value, then update the last value and maximum spread as I went along, e.g.

var data = [4, 6, 2, 2, 6, 6, 1];

function getMaxIndexSpread(data) {
  return data.reduce(function(acc, value, index) {

    if (value in acc) {
      acc[value].lastIndex = index

    } else {
      acc[value] = {firstIndex: index, lastIndex: index};
    }
    var spread = acc[value].lastIndex - acc[value].firstIndex;

    if (acc.maxSpread < spread) acc.maxSpread = spread;

    return acc;
  }, {maxSpread: 0}).maxSpread;
}

console.log(getMaxIndexSpread(data));```
</div>
</div>
</p>

<p>There's likely a funkier way, but this makes sense to me.</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>var data = [4, 6, 2, 2, 6, 6, 1];

console.log(Math.max(...data.map((v,i) => i - data.indexOf(v)))); </code>```

Body:
How to find the difference between the min and max indexes of the same value in an array with one loop with complexity exactly O(N)?

For example, given array A:

[4, 6, 2, 2, 6, 6, 1];

the function returns 4.

Body:
I'd use reduce to remember the first index of each value, then update the last value and maximum spread as I went along, e.g.

var data = [4, 6, 2, 2, 6, 6, 1];

function getMaxIndexSpread(data) {
  return data.reduce(function(acc, value, index) {

    if (value in acc) {
      acc[value].lastIndex = index

    } else {
      acc[value] = {firstIndex: index, lastIndex: index};
    }
    var spread = acc[value].lastIndex - acc[value].firstIndex;

    if (acc.maxSpread < spread) acc.maxSpread = spread;

    return acc;
  }, {maxSpread: 0}).maxSpread;
}

console.log(getMaxIndexSpread(data));

There's likely a funkier way, but this makes sense to me.

var data = [4, 6, 2, 2, 6, 6, 1];

console.log(Math.max(...data.map((v,i) => i - data.indexOf(v))));


问:
How to Set Selected value in Multi-Value Select in Jquery-Select2.?
I am  binding  my  dropdown  with Jquery-Select2.  It's  working  fine  but  now  I  need  to  bind  my  Multi-Value  selectBox   by  using Jquery-Select2.

My DropDown

  <select
    id="drp_Books_Ill_Illustrations"
    class="leaderMultiSelctdropdown Books_Illustrations"
    name="drp_Books_Ill_Illustrations"
    multiple=""
  >
    <option value=" ">No illustrations</option>
    <option value="a">Illustrations</option>
    <option value="b">Maps</option>
    <option value="c">Portraits</option>
  </select>

```
<p>From   this  link  http://ivaynberg.github.com/select2/     I am  using  Multiple  Value  Select  Box,  I  can  bind  my  dropdown  with</p>
<pre class="lang-js prettyprint-override"><code>$("dropdownid").Select2()
</code>```

Its  working  fine,  but  now  I  need  to  get  that  selected  value  into  my  dropdown  on  edit  mode So  I am  using  this  example:

$(".Books_Illustrations").select2("val", ["a", "c"]);
```

It's  working  but  how   can I  fix  my  choice,  because  user  can  choose  anything.  So  I  can't  write  a,c   statically  that's  why  I  need  to  bind  my  Selected  value  on  Edit  mode  dynamically.

I  think  now  you  all  are  clear  with  my  requirements.  Please  let  me  know  if  you  need  further  clearance.

答:
Using select2 jquery library:</p>

```<code>$('#selector').val(arrayOfValues).trigger('change')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am  binding  my  dropdown  with Jquery-Select2.  It's  working  fine  but  now  I  need  to  bind  my  Multi-Value  selectBox   by  using Jquery-Select2.

My DropDown

  <select
    id="drp_Books_Ill_Illustrations"
    class="leaderMultiSelctdropdown Books_Illustrations"
    name="drp_Books_Ill_Illustrations"
    multiple=""
  >
    <option value=" ">No illustrations</option>
    <option value="a">Illustrations</option>
    <option value="b">Maps</option>
    <option value="c">Portraits</option>
  </select>

From   this  link  http://ivaynberg.github.com/select2/     I am  using  Multiple  Value  Select  Box,  I  can  bind  my  dropdown  with

$("dropdownid").Select2()

Its  working  fine,  but  now  I  need  to  get  that  selected  value  into  my  dropdown  on  edit  mode So  I am  using  this  example:

$(".Books_Illustrations").select2("val", ["a", "c"]);

It's  working  but  how   can I  fix  my  choice,  because  user  can  choose  anything.  So  I  can't  write  a,c   statically  that's  why  I  need  to  bind  my  Selected  value  on  Edit  mode  dynamically.

I  think  now  you  all  are  clear  with  my  requirements.  Please  let  me  know  if  you  need  further  clearance.

Body:
Using select2 jquery library:

$('#selector').val(arrayOfValues).trigger('change')


问:
Fixing before pseudo element after clicking
I try to make a dropdown information bar with + or - before it.
I don´t know how is it usually made but I came up with this try

.test{
 width: 150px;
 height: 100px;
 background:gray;
}
.test:before{
 content: "+";
}
.test:active:before{
 content: "-";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></div>
 <div class="test">
 Ahoj
 </div> </code>```

¨

But I want it to stay on minus after clicking it because by clicking on it I rolldown other informations.
Thanks for answers

答:
Without using javascript, you can do something similar using the :target selector.

https://codepen.io/partypete25/pen/xrbZmy

For it to work, the link itself needs to exist within the targeted content area.

```<code>.test:before {
  content: "+";
}

:target .test:before {
  content: "-";
}
</code>```

Body:
I try to make a dropdown information bar with + or - before it.
I don´t know how is it usually made but I came up with this try

.test{
 width: 150px;
 height: 100px;
 background:gray;
}
.test:before{
 content: "+";
}
.test:active:before{
 content: "-";
}

 Ahoj

¨

But I want it to stay on minus after clicking it because by clicking on it I rolldown other informations.
Thanks for answers

Body:
Without using javascript, you can do something similar using the :target selector.

https://codepen.io/partypete25/pen/xrbZmy

For it to work, the link itself needs to exist within the targeted content area.

.test:before {
  content: "+";
}

:target .test:before {
  content: "-";
}


问:
How to throw exception while converting from JsonStr to PojoClassObj if any key/value is missing in the JsonStr?
I tried using @NotNull annotation but it did not work. If any field is missing in the JsonString, it gives null(String) or zero(int). But what I want is if any field is missing in the JsonStr defined in the class should throw an exception.

Add: My PojoClass may have object reference or multilevel object reference. I am using Gson for the conversion of the String to obj.
for more clarification, I have added my code below:

JsonStr:

```<code>{
   "name":"John",
   "id":1,
   "roll":100,
   "c":{
      "city":"Dhaka",
      "school":"B. govt. School"
   }
}
</code>```

Code:

```<code>public class C {

    private String city;
    private String school;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

}
</code>```

ClassB:

```<code>public class B {

    private String name;
    private int id;
    @NotNull
    private int roll;
    private C c;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getRoll() {
        return roll;
    }

    public void setRoll(int roll) {
        this.roll = roll;
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

}
</code>```

MainClass:

```<code>try {
                B obj = new B();
                String str = "{\"name\":\"John\",\"id\":1,\"c\":{\"city\":\"dhaka\",\"school\":\"school\"}}";
                obj = gson.fromJson(str, B.class);

            } catch (RuntimeException e) {
                 System.out.println("exception Message");

            }
</code>```

For the field roll, I used @NotNull to throw an exception if that field is not present in the JsonStr but it gives 0 value without throwing any exception.

How can I implement that?

Please don't say this is duplicate, because I have seen these questions:

GSON throwing null pointer exception when a field is missing in json [duplicate]

What is a NullPointerException, and how do I fix it?

答:
Have you try using Wrapper class instead primitive?

use this:

@NotNull
private Integer roll;

Body:
I tried using @NotNull annotation but it did not work. If any field is missing in the JsonString, it gives null(String) or zero(int). But what I want is if any field is missing in the JsonStr defined in the class should throw an exception.

Add: My PojoClass may have object reference or multilevel object reference. I am using Gson for the conversion of the String to obj.
for more clarification, I have added my code below:

JsonStr:

{
   "name":"John",
   "id":1,
   "roll":100,
   "c":{
      "city":"Dhaka",
      "school":"B. govt. School"
   }
}

Code:

public class C {

    private String city;
    private String school;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

}

ClassB:

public class B {

    private String name;
    private int id;
    @NotNull
    private int roll;
    private C c;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getRoll() {
        return roll;
    }

    public void setRoll(int roll) {
        this.roll = roll;
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

}

MainClass:

try {
                B obj = new B();
                String str = "{\"name\":\"John\",\"id\":1,\"c\":{\"city\":\"dhaka\",\"school\":\"school\"}}";
                obj = gson.fromJson(str, B.class);

            } catch (RuntimeException e) {
                 System.out.println("exception Message");

            }

For the field roll, I used @NotNull to throw an exception if that field is not present in the JsonStr but it gives 0 value without throwing any exception.

How can I implement that?

Please don't say this is duplicate, because I have seen these questions:

GSON throwing null pointer exception when a field is missing in json [duplicate]

What is a NullPointerException, and how do I fix it?


问:
SpriteKit class separation issue
I have a property named ball with two functions - setup() and launch():

```<code>var ball = Ball()
</code>```

After I call ball.launch() I'd like to know where it is on the x-axis using:

```<code>ball.position.x
</code>```

But for some reason, I keep getting zero. Right now, I'm launching the ball from touchesBegan and trying to get the position in touchesEnded. As I said, the launching part works fine. The ball appears, and it bounces around as expected, but nothing I do the the ball property has any effect after that point. Here is the complete code:

Ball.swift

```<code>class Ball: SKSpriteNode {

    var ball: SKSpriteNode!

    func setUp(parentNode: SKNode) {

        ball = SKSpriteNode(imageNamed: "ball2")
        ball.name = "ball"
        ball.position = CGPoint(x: 20, y: 200)
        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width / 2)
        ball.physicsBody?.restitution = 0
        ball.physicsBody?.velocity = CGVector(dx: 0, dy: 0)

        ball.physicsBody?.categoryBitMask = PhysicsCategories.Ball
        ball.physicsBody?.collisionBitMask = PhysicsCategories.Edge
        ball.physicsBody?.contactTestBitMask = PhysicsCategories.Edge
        parentNode.addChild(ball)
    }

    func launch() {
        ball.physicsBody?.applyImpulse(CGVector(dx: 25, dy: 0))
    }

}
</code>```

GameScene.swift

```<code>import SpriteKit
import GameplayKit

struct PhysicsCategories {

    static let Ball:     UInt32 = 0
    static let Edge:     UInt32 = 0b1
}

class GameScene: SKScene, SKPhysicsContactDelegate {

    var ball = Ball()

    override func didMove(to view: SKView) {

        let border = SKPhysicsBody(edgeLoopFrom: self.frame)
        border.friction = 0
        border.restitution = 1
        physicsBody = border
        border.categoryBitMask = PhysicsCategories.Edge
        border.collisionBitMask = PhysicsCategories.Ball
        border.contactTestBitMask = PhysicsCategories.Ball

        physicsWorld.contactDelegate = self
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        ball.setUp(parentNode: self)
        ball.launch()
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print(ball.position.x) //value is always zero
    }

    func didBegin(_ contact: SKPhysicsContact) {
        let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

        switch collision {
        case PhysicsCategories.Ball | PhysicsCategories.Edge:
            ball.removeFromParent() //doesn't get removed
        default:
            break
        }
    }
}
</code>```

答:
The problem is that you are trying to access the wrong property. You are creating a Ball in your gamescene.swift, but do nothing with it except call launch(), but launch() only affects ball.ball, because you have created two ball properties.

The ball you created in your gamescene is never added to the scene and never does anything, hence why it shows that your position never changes.

To rectify this, you want to use the Ball class as a blueprint for creating ball properties by your gamescene.

```<code>class Ball: SKSpriteNode {

  // You don't want to create an object of the type you are creating here...
  // as a property of the class!:
  // var ball: SKSpriteNode!

  func setUp(parentNode: SKNode) {

    self.name = "ball"
    self.position = CGPoint(x: 20, y: 200)
    self.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width / 2)
    self.physicsBody?.restitution = 0
    self.physicsBody?.velocity = CGVector(dx: 0, dy: 0)

    self.physicsBody?.categoryBitMask = PhysicsCategories.Ball
    self.physicsBody?.collisionBitMask = PhysicsCategories.Edge
    self.physicsBody?.contactTestBitMask = PhysicsCategories.Edge
    self.parentNode.addChild(ball)
  }

  func launch() {
    self.physicsBody?.applyImpulse(CGVector(dx: 25, dy: 0))
  }

}
</code>```

Now when you call ball.launch(), the state you are actually modifying is ball, not ball.ball (because I deleted ball.ball and changed it to self =} )

Here is a simple representation of what you are doing, and why it isn't working as expected:

```<code>class Cat {

 var fluffy: Cat!

  var name = "no name"

  func changeName() {
    fluffy = Cat()
    fluffy.name = "Fluffy"
  }

}

var fluffy = Cat()
fluffy.changeName()
print(fluffy.name) // no name
print(fluffy.fluffy.name) // Fluffy
</code>```

Title: SpriteKit class separation issue

Body:
I have a property named ball with two functions - setup() and launch():

var ball = Ball()

After I call ball.launch() I'd like to know where it is on the x-axis using:

ball.position.x

But for some reason, I keep getting zero. Right now, I'm launching the ball from touchesBegan and trying to get the position in touchesEnded. As I said, the launching part works fine. The ball appears, and it bounces around as expected, but nothing I do the the ball property has any effect after that point. Here is the complete code:

Ball.swift

class Ball: SKSpriteNode {

    var ball: SKSpriteNode!

    func setUp(parentNode: SKNode) {

        ball = SKSpriteNode(imageNamed: "ball2")
        ball.name = "ball"
        ball.position = CGPoint(x: 20, y: 200)
        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width / 2)
        ball.physicsBody?.restitution = 0
        ball.physicsBody?.velocity = CGVector(dx: 0, dy: 0)

        ball.physicsBody?.categoryBitMask = PhysicsCategories.Ball
        ball.physicsBody?.collisionBitMask = PhysicsCategories.Edge
        ball.physicsBody?.contactTestBitMask = PhysicsCategories.Edge
        parentNode.addChild(ball)
    }

    func launch() {
        ball.physicsBody?.applyImpulse(CGVector(dx: 25, dy: 0))
    }

}

GameScene.swift

import SpriteKit
import GameplayKit

struct PhysicsCategories {

    static let Ball:     UInt32 = 0
    static let Edge:     UInt32 = 0b1
}

class GameScene: SKScene, SKPhysicsContactDelegate {

    var ball = Ball()

    override func didMove(to view: SKView) {

        let border = SKPhysicsBody(edgeLoopFrom: self.frame)
        border.friction = 0
        border.restitution = 1
        physicsBody = border
        border.categoryBitMask = PhysicsCategories.Edge
        border.collisionBitMask = PhysicsCategories.Ball
        border.contactTestBitMask = PhysicsCategories.Ball

        physicsWorld.contactDelegate = self
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        ball.setUp(parentNode: self)
        ball.launch()
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print(ball.position.x) //value is always zero
    }

    func didBegin(_ contact: SKPhysicsContact) {
        let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

        switch collision {
        case PhysicsCategories.Ball | PhysicsCategories.Edge:
            ball.removeFromParent() //doesn't get removed
        default:
            break
        }
    }
}

Body:
The problem is that you are trying to access the wrong property. You are creating a Ball in your gamescene.swift, but do nothing with it except call launch(), but launch() only affects ball.ball, because you have created two ball properties.

The ball you created in your gamescene is never added to the scene and never does anything, hence why it shows that your position never changes.

To rectify this, you want to use the Ball class as a blueprint for creating ball properties by your gamescene.

class Ball: SKSpriteNode {

  // You don't want to create an object of the type you are creating here...
  // as a property of the class!:
  // var ball: SKSpriteNode!

  func setUp(parentNode: SKNode) {

    self.name = "ball"
    self.position = CGPoint(x: 20, y: 200)
    self.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width / 2)
    self.physicsBody?.restitution = 0
    self.physicsBody?.velocity = CGVector(dx: 0, dy: 0)

    self.physicsBody?.categoryBitMask = PhysicsCategories.Ball
    self.physicsBody?.collisionBitMask = PhysicsCategories.Edge
    self.physicsBody?.contactTestBitMask = PhysicsCategories.Edge
    self.parentNode.addChild(ball)
  }

  func launch() {
    self.physicsBody?.applyImpulse(CGVector(dx: 25, dy: 0))
  }

}

Now when you call ball.launch(), the state you are actually modifying is ball, not ball.ball (because I deleted ball.ball and changed it to self =} )

Here is a simple representation of what you are doing, and why it isn't working as expected:

class Cat {

 var fluffy: Cat!

  var name = "no name"

  func changeName() {
    fluffy = Cat()
    fluffy.name = "Fluffy"
  }

}

var fluffy = Cat()
fluffy.changeName()
print(fluffy.name) // no name
print(fluffy.fluffy.name) // Fluffy


问:
Use numpy with Cython
I want to create .so file from python and execute the .so file in C.
To do it I used cython to convert .pyx to .so

```<code>## print_me.pyx
cimport numpy as cnp
import  numpy as np
cimport cython
cpdef public char* print_me(f):
    # I know this numpy line does nothing
    cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
    return f
</code>```

Then I used setup.py to actually convert .pyx to .so

```<code>## setup.py
from distutils.core import setup
from Cython.Build import cythonize
import numpy as np

setup(
    ext_modules=cythonize("print_me.pyx"),
    include_dirs=[np.get_include()]
)
</code>```

By running the following command line, I was able to create .so file

```<code>python setup.py build_ext --inplace
</code>```

When I tried to run so file using the following C code, I got a Segmentation Fault.

```<code>/* toloadso.c */
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <time.h>
#include <python2.7/Python.h>

int main(void)
{
    // define function
    void *handle;
    char* (*print_me)(PyObject*);
    char *error;

    PyObject* filename = PyString_FromString("hello");

    // load so file
    handle = dlopen("./print_me.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }
    dlerror();

    // get function handler from so file
    print_me = (char* (*)(PyObject*))dlsym(handle, "print_me");

    // check if handler got error
    error = dlerror();
    if (error != NULL) {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }

    // execute loaded function
    printf("%s\n", (char*)(*print_me)(filename));
    dlclose(handle);
    exit(EXIT_SUCCESS);
}
</code>```

I compiled this .c file with following command:

```<code>gcc -fPIC -I/usr/include/ -o toloadso toloadso.c -lpython2.7 -ldl
(It compiled without error or warning)
</code>```

When I tried to run this code, I got a segmentation Fault

```<code>[root@localhost ~]# ./toloadso
Segmentation fault
</code>```

If I comment out the following line in print_me.pyx

```<code>cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
</code>```

My C code runs without error, but once I uncomment this line, it does not work.
I think that trying to use numpy in cython generates an error somehow.

How can I fix it??
I thank you so much for your reply

答:
You must initialize the numpy C API by calling import_array().

Add this line to your cython file:

```<code>cnp.import_array()
</code>```

And as pointed out by @user4815162342 and @DavidW in the comments, you must call Py_Initialize() and Py_Finalize() in main().

Title: Use numpy with Cython

Body:
I want to create .so file from python and execute the .so file in C.
To do it I used cython to convert .pyx to .so

## print_me.pyx
cimport numpy as cnp
import  numpy as np
cimport cython
cpdef public char* print_me(f):
    # I know this numpy line does nothing
    cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)
    return f

Then I used setup.py to actually convert .pyx to .so

## setup.py
from distutils.core import setup
from Cython.Build import cythonize
import numpy as np

setup(
    ext_modules=cythonize("print_me.pyx"),
    include_dirs=[np.get_include()]
)

By running the following command line, I was able to create .so file

python setup.py build_ext --inplace

When I tried to run so file using the following C code, I got a Segmentation Fault.

/* toloadso.c */
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <time.h>
#include <python2.7/Python.h>

int main(void)
{
    // define function
    void *handle;
    char* (*print_me)(PyObject*);
    char *error;

    PyObject* filename = PyString_FromString("hello");

    // load so file
    handle = dlopen("./print_me.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }
    dlerror();

    // get function handler from so file
    print_me = (char* (*)(PyObject*))dlsym(handle, "print_me");

    // check if handler got error
    error = dlerror();
    if (error != NULL) {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }

    // execute loaded function
    printf("%s\n", (char*)(*print_me)(filename));
    dlclose(handle);
    exit(EXIT_SUCCESS);
}

I compiled this .c file with following command:

gcc -fPIC -I/usr/include/ -o toloadso toloadso.c -lpython2.7 -ldl
(It compiled without error or warning)

When I tried to run this code, I got a segmentation Fault

[root@localhost ~]# ./toloadso
Segmentation fault

If I comment out the following line in print_me.pyx

cdef cnp.ndarray[cnp.complex128_t, ndim=3] a = np.zeros((3,3,3), dtype=np.complex128)

My C code runs without error, but once I uncomment this line, it does not work.
I think that trying to use numpy in cython generates an error somehow.

How can I fix it??
I thank you so much for your reply

Body:
You must initialize the numpy C API by calling import_array().

Add this line to your cython file:

cnp.import_array()

And as pointed out by @user4815162342 and @DavidW in the comments, you must call Py_Initialize() and Py_Finalize() in main().


问:
Fastest way to learn Zend Framework?
If you already have a website design in mind and want to just use Zend Framework's modules (mainly the one's for security and performance) how would you go about learning Zend for rapid web development?

答:
For starting refer link:

http://akrabat.com/zend-framework-tutorial/

and download and read Pdf.

Fastest way is up to you how much time to give to learning and depends on your learning capability.
But am  sure above link will give u a good initiation.

Read ZF manuals and get start with sprite that it's very easy. :)

It's manual itself is good resource for learning. and I can be your guide :)

Title: Fastest way to learn Zend Framework?


问:
Angular 2 - Why my all routes are not redirected?
```<code>[{
    path: 'menu',
    component: MenuComponent
  },
  {
    path: 'how',
    component: HowItWorksComponent
  },
  {
    path: '',
    pathMatch: 'prefix',
    redirectTo: 'menu'
  }]
</code>```

Above is my root route config why my all routes are not redirected to the menu because empty string should be a prefix to all routes.
It shows respective components on /how and /menu and perfectly redirects to menu on / but it should always redirect to /menu shouldn't it?

答:
If you want your last path to catch anything that the first two don't, then you'll want:

```<code>{
  path: '**',
  redirectTo: 'menu'
}
</code>```

As explained in the angular docs, ** is a special wildcard route

Body:
[{
    path: 'menu',
    component: MenuComponent
  },
  {
    path: 'how',
    component: HowItWorksComponent
  },
  {
    path: '',
    pathMatch: 'prefix',
    redirectTo: 'menu'
  }]

Above is my root route config why my all routes are not redirected to the menu because empty string should be a prefix to all routes.
It shows respective components on /how and /menu and perfectly redirects to menu on / but it should always redirect to /menu shouldn't it?

Body:
If you want your last path to catch anything that the first two don't, then you'll want:

{
  path: '**',
  redirectTo: 'menu'
}

As explained in the angular docs, ** is a special wildcard route


问:
Can I use Firebase for sending SMS to users without using Twilio?
I used to use Firebase + Twilio to send SMS to any devices,
but I'm not sure that I can send SMS by using Firebase only or not?

Does Firebase have an API for sending SMS?

答: There is no built-in API for sending SMS through Firebase. You will have to use a third-party service (such as you're currently doing with Twilio) to send SMS messages.</p>


问:
How to use PixiJS in web worker
I need to display a quite complex 2D shape in a canvas using PixiJS and to do so I'd like to create and define all graphic elements in a separate thread (web worker) to not block the rest of the UI.

The problem is that when I import PixiJS in the web worker file like this

```<code>importScripts('https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.2/pixi.js');
</code>```

it gives me an error because it accesses DOM elements (like window and document) and this is not allowed in web workers. How can I solve this?

This is the error:

```<code>Uncaught ReferenceError: window is not defined
at Object.179../Math.sign (Object.assign.js:3)
at s (_prelude.js:1)
at _prelude.js:1
at Object.<anonymous> (WebGLPrepare.js:101)
at Object.187../accessibility (index.js:44)
at s (_prelude.js:1)
at e (_prelude.js:1)
at _prelude.js:1
at _prelude.js:1
at _prelude.js:1
</code>```

答:
Philipp is right on his answer, I just want to elaborate this a bit further, from the games and web workers point-of-view.

In my experience, it is ofter hard to take advantage of web workers in games. Especially if you use a library to handle canvas / webGL, since that does most of the number crunching anyway. Web workers are designed for number crunching as philipp mentioned. And passing data between web worker and main thread is quite expensive, so passing data and doing tiny operations on them, will not be beneficial.

Without providing a direct link, I read already long while ago that some game engines (I think construct) used web workers for their pathfinding module. So nothing related to direct graphic handling, but numerical operations.

Also there is a proposal for possibility to use canvases in web worker contexts, so it is clearly an issue with others too. If my memory serves right, I believe it was this: https://developer.mozilla.org/fi/docs/Web/API/OffscreenCanvas

Title: How to use PixiJS in web worker

Body:
I need to display a quite complex 2D shape in a canvas using PixiJS and to do so I'd like to create and define all graphic elements in a separate thread (web worker) to not block the rest of the UI.

The problem is that when I import PixiJS in the web worker file like this

importScripts('https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.5.2/pixi.js');

it gives me an error because it accesses DOM elements (like window and document) and this is not allowed in web workers. How can I solve this?

This is the error:

Uncaught ReferenceError: window is not defined
at Object.179../Math.sign (Object.assign.js:3)
at s (_prelude.js:1)
at _prelude.js:1
at Object.<anonymous> (WebGLPrepare.js:101)
at Object.187../accessibility (index.js:44)
at s (_prelude.js:1)
at e (_prelude.js:1)
at _prelude.js:1
at _prelude.js:1
at _prelude.js:1


问:
How to use GitHub to make a public gist? What is the procedure?
I want to create a public gist in GitHub. I've been on YouTube and in Google search but have not found an answer to this question. And I don't see an answer in Stackoverflow to this question. This my seem trivial to some of you but I'm not so savvy in the tech world. I have a GitHub account. I did the tutorial in the Read Me Guide where I learned about repositories, branch, commit and pull request. I was in StackExchange chat room where someone asked me to make a public gist of my code that I was asking help with. Now I want to create a public gist of my code. On the Gist page I see a place to where I think the code is suppose to go. I see an Add File tab.  But nothing happens when I click on it.The app won't let me just paste in my code. I see a place for a gist description. And I see a place for a file name including extension. But how do I place my code to create a public gist? Where does it go? Somebody help, please. After some more searching I think I got an answer. A Gist is just a repository. Am I right or wrong? </p>

答:
If you want to create public gist repository on github then following steps are there,

There is a GithubHist(https://gist.github.com/) available to share you code publicly over the internet.

One of the advantage to use this is that when you create repository in GithubHist, one same repository will be created on https://bl.ocks.org

This will run your code and show output to the user.

Steps to use GithubHist

Login on Github.

There is a Gist option on top of then menu. Click on this.

It will redirect you on https://gist.github.com/

Here in Gist description give Title of your project.

Now create index.html file. This file runs by default when you go on https://bl.ocks.org with your repository location.

Now you can add as many files that you need in your project here.Just click on add file.

To add License,you need to add license.txt file and add contents of the license.

At last click on “Create public gist” or “Create Secret gist” option at bottom.

To add Background image of your project on https://bl.ocks.org

Get git clone of project to your local machine.

Create file with name “thumbnail.png” with dimension 230px * 120px.

Add this file to your project.

Commit and Push changes.

It’s Done now.

Check your Project with links

https://gist.github.com/yourName/ProjectId Source of project

https://bl.ocks.org/yourName/ProjectId output of project with source

Please see my blog on medium

https://medium.com/@thakkarchintu5/using-githubgist-on-github-f4f0944bbc80

also check gist repository that I have created

https://bl.ocks.org/ChandrakantThakkarDigiCorp


问:
how to call web service(.wsdl) using asp.net
I got .wsdl file from my client. by using this webservice i need validate customer information. So how to achieve this one .if customer is there or not
xml :

```<code> <xs:element name="FetchClubMembershipRequest">
        <xs:annotation>
          <xs:documentation>Request to fetch customers' membership information.</xs:documentation>
        </xs:annotation>
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_ID" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_Code" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Last_Name" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="First_Name" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
</code>```

this is from wsdl.file

答:
In your ASP.NET project in Visual Studio, go to references, Add Service Reference, and add a reference to the live webservice that you need to call in your application. This will automatically generate all of the stub code you need to call the service.

See: How to Consume a Web Service.

Body:
I got .wsdl file from my client. by using this webservice i need validate customer information. So how to achieve this one .if customer is there or not
xml :

 <xs:element name="FetchClubMembershipRequest">
        <xs:annotation>
          <xs:documentation>Request to fetch customers' membership information.</xs:documentation>
        </xs:annotation>
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_ID" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_Code" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Last_Name" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="First_Name" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

this is from wsdl.file


问:
Upload Block Blob to Azure Storage via SDK - Server failed to authenticate the request
From my ASP.Net Core app, I try to upload a block blob to Azure Storage Service.
I took the example from Microsoft:

```<code>    var accountName = "accountname";
    var accountKey = "key";
    //var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myconnectionstring");

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference(Container);

    // Retrieve reference to a blob named "test".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("test");

    // Create or overwrite the "test" blob with contents from a local file.
    using (var fileStream = System.IO.File.OpenRead(@"E:\Drone\N_01004619000008.jpg"))
    {
        await blockBlob.UploadFromStreamAsync(fileStream);
    }
</code>```

This results in the following error:

StorageException: Server failed to authenticate the request. Make sure
  the value of Authorization header is formed correctly including the
  signature.

Using fiddler I could also see this additional error info:

The MAC signature found in the HTTP request 'blankedOutKey' is not the
  same as any computed signature. Server used following string to sign:
  'PUT'

...whereas the 'blankedOutKey' is not the key I actually used for authentication. Not sure where it comes from.
As you can see in my Code Snippet, I tried both using my accountName and accountKey as well as the ConnectionString.

What am I doing wrong?

Edit:
I tried this here:
https://github.com/Azure-Samples/storage-dotnet-sas-getting-started

With the exact same connection string, it worked in the solution from github but when I took over the complete code to my ASP.Net Core 1.1 app, I again faced the issue mentioned. So I double checked the differences. It turns out that the project from github uses the 6.2.0 version of "Microsoft.WindowsAzure.Storage" while my ASP.Net Core app uses the 8.1.3 version.

Furthermore, I double checked the HTTP requests from both solutions in fiddler.
Here is the one from the older SDK which works:

User-Agent: WA-Storage/6.2.0 (.NET CLR 4.0.30319.42000; Win32NT
  6.2.9200.0) x-ms-version: 2015-04-05 x-ms-client-request-id: c1aea889-73f8-4b6b-9a1f-2f2f9e021846 x-ms-date: Sun, 04 Jun 2017
  12:23:37 GMT Authorization: SharedKey
  mystoragename:F5yhOOh2taUBfUE+3wii1cYb0D7L+jZGVfs1xTgTme0=
  Host: mystoragename.blob.core.windows.net Content-Length: 0

The request submitted through the newer SDK which fails:

Connection: Keep-Alive Authorization: SharedKey
  mystoragenamee:IxtXuZFIcPjeKnqjktxvfcQMRLkfHM5SVN9zvQZmBJc=
  User-Agent: Azure-Storage/8.1.3 (.NET Core) x-ms-client-request-id:
  d890d2e0-07af-4695-af1f-8020c9476774 x-ms-version: 2016-05-31
  x-ms-date: Sun, 04 Jun 2017 12:24:49 GMT x-ms-request-root-id:
  428e8e6279f1ff9d-4237b4f7 x-ms-request-id:
  |428e8e6279f1ff9d-4237b4f7.1. Request-Id:
  |428e8e6279f1ff9d-4237b4f7.1. Content-Length: 0 Host:
  mystoragename.blob.core.windows.net

答:
The MAC signature found in the HTTP request 'blankedOutKey' is not the same as any computed signature. Server used following string to sign: 'PUT'

According to the exception, it seems that construct authorization is not correct. But you are using Azure storage SDK. It seems that exception happened in the other code.

Please have a try to create a project and try it again. I can't repro it with you mentioned code in .net core Asp.net project. It works correctly on my side.

The following is my detail steps:

1.Create a .net core project.

2.Add the Azure storage SDK

3.Create the function with you mentioned code.

```<code> public async Task UploadBlobAsync()
        {
            const string myconnctionstring = "DefaultEndpointsProtocol=https;AccountName=accountname;AccountKey=yourkey;EndpointSuffix=core.windows.net";
            //var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(myconnctionstring);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("test");

            container.CreateIfNotExistsAsync().Wait();
            // Retrieve reference to a blob named "test".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("test.jpg");

            // Create or overwrite the "test" blob with contents from a local file.
            using (var fileStream = System.IO.File.OpenRead(@"file path"))
            {
                await blockBlob.UploadFromStreamAsync(fileStream);
            }
        }
</code>```

4.Call the function

```<code>public IActionResult About()
        {
            ViewData["Message"] = "upload blob.";
            UploadBlobAsync().Wait();
            return View();
        }
</code>```

5.Run the project and visit it about page, it works correctly.

6.I also catch it with fiddler.

Body:
From my ASP.Net Core app, I try to upload a block blob to Azure Storage Service.
I took the example from Microsoft:

    var accountName = "accountname";
    var accountKey = "key";
    //var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myconnectionstring");

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference(Container);

    // Retrieve reference to a blob named "test".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("test");

    // Create or overwrite the "test" blob with contents from a local file.
    using (var fileStream = System.IO.File.OpenRead(@"E:\Drone\N_01004619000008.jpg"))
    {
        await blockBlob.UploadFromStreamAsync(fileStream);
    }

This results in the following error:

StorageException: Server failed to authenticate the request. Make sure
  the value of Authorization header is formed correctly including the
  signature.

Using fiddler I could also see this additional error info:

The MAC signature found in the HTTP request 'blankedOutKey' is not the
  same as any computed signature. Server used following string to sign:
  'PUT'

...whereas the 'blankedOutKey' is not the key I actually used for authentication. Not sure where it comes from.
As you can see in my Code Snippet, I tried both using my accountName and accountKey as well as the ConnectionString.

What am I doing wrong?

Edit:
I tried this here:
https://github.com/Azure-Samples/storage-dotnet-sas-getting-started

With the exact same connection string, it worked in the solution from github but when I took over the complete code to my ASP.Net Core 1.1 app, I again faced the issue mentioned. So I double checked the differences. It turns out that the project from github uses the 6.2.0 version of "Microsoft.WindowsAzure.Storage" while my ASP.Net Core app uses the 8.1.3 version.

Furthermore, I double checked the HTTP requests from both solutions in fiddler.
Here is the one from the older SDK which works:

User-Agent: WA-Storage/6.2.0 (.NET CLR 4.0.30319.42000; Win32NT
  6.2.9200.0) x-ms-version: 2015-04-05 x-ms-client-request-id: c1aea889-73f8-4b6b-9a1f-2f2f9e021846 x-ms-date: Sun, 04 Jun 2017
  12:23:37 GMT Authorization: SharedKey
  mystoragename:F5yhOOh2taUBfUE+3wii1cYb0D7L+jZGVfs1xTgTme0=
  Host: mystoragename.blob.core.windows.net Content-Length: 0

The request submitted through the newer SDK which fails:

Connection: Keep-Alive Authorization: SharedKey
  mystoragenamee:IxtXuZFIcPjeKnqjktxvfcQMRLkfHM5SVN9zvQZmBJc=
  User-Agent: Azure-Storage/8.1.3 (.NET Core) x-ms-client-request-id:
  d890d2e0-07af-4695-af1f-8020c9476774 x-ms-version: 2016-05-31
  x-ms-date: Sun, 04 Jun 2017 12:24:49 GMT x-ms-request-root-id:
  428e8e6279f1ff9d-4237b4f7 x-ms-request-id:
  |428e8e6279f1ff9d-4237b4f7.1. Request-Id:
  |428e8e6279f1ff9d-4237b4f7.1. Content-Length: 0 Host:
  mystoragename.blob.core.windows.net

Body:
The MAC signature found in the HTTP request 'blankedOutKey' is not the same as any computed signature. Server used following string to sign: 'PUT'

According to the exception, it seems that construct authorization is not correct. But you are using Azure storage SDK. It seems that exception happened in the other code.

Please have a try to create a project and try it again. I can't repro it with you mentioned code in .net core Asp.net project. It works correctly on my side.

The following is my detail steps:

1.Create a .net core project.

2.Add the Azure storage SDK

3.Create the function with you mentioned code.

 public async Task UploadBlobAsync()
        {
            const string myconnctionstring = "DefaultEndpointsProtocol=https;AccountName=accountname;AccountKey=yourkey;EndpointSuffix=core.windows.net";
            //var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(myconnctionstring);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("test");

            container.CreateIfNotExistsAsync().Wait();
            // Retrieve reference to a blob named "test".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("test.jpg");

            // Create or overwrite the "test" blob with contents from a local file.
            using (var fileStream = System.IO.File.OpenRead(@"file path"))
            {
                await blockBlob.UploadFromStreamAsync(fileStream);
            }
        }

4.Call the function

public IActionResult About()
        {
            ViewData["Message"] = "upload blob.";
            UploadBlobAsync().Wait();
            return View();
        }

5.Run the project and visit it about page, it works correctly.

6.I also catch it with fiddler.


问:
Reading multiple images in keras
I tried to read multiple images in keras(theano), like this

```<code>  import numpy as np

  import os, sys

  import cv2

  my_path='data/train'

  dirs = os.listdir(my_path)

  numpy_int_array=np.array(dirs)

  for i in numpy_int_array:

        input_im=cv2.imread(numpy_int_array[i],1)

        print input_im.shape
</code>```

I am getting below error,

IndexError: only integers, slices (:), ellipsis (...),
numpy.newaxis (None) and integer or boolean arrays are valid indices

Please help me where I am doing wrong.

答:
You are converting to np.array too soon:

```<code>for im_name in os.listdir(my_path):  # no need to convert to np.array yet...
    input_im=cv2.imread(im_name, 1)  # now it's np.array
    print input_im.shape
</code>```

Python's os.listdir() returns a list of file names (strings) and not integers.

Title: Reading multiple images in keras

Body:
I tried to read multiple images in keras(theano), like this

  import numpy as np

  import os, sys

  import cv2

  my_path='data/train'

  dirs = os.listdir(my_path)

  numpy_int_array=np.array(dirs)

  for i in numpy_int_array:

        input_im=cv2.imread(numpy_int_array[i],1)

        print input_im.shape

I am getting below error,

IndexError: only integers, slices (:), ellipsis (...),
numpy.newaxis (None) and integer or boolean arrays are valid indices

Please help me where I am doing wrong.

Body:
You are converting to np.array too soon:

for im_name in os.listdir(my_path):  # no need to convert to np.array yet...
    input_im=cv2.imread(im_name, 1)  # now it's np.array
    print input_im.shape

Python's os.listdir() returns a list of file names (strings) and not integers.


问:
Could not get unknown property 'RELEASE_STORE_PASSWORD' for SigningConfig_Decorated{name=debugY
I've been having this problem recently as I'm searching everywhere, also here in stack, I see a lot of different answers.

Does anybody know how to solve this one?

Error:(46, 0) Could not get unknown property 'RELEASE_STORE_PASSWORD'
  for SigningConfig_Decorated{name=debug, storeFile=C:\Users\— Shahab
  —\Desktop\master\TMessagesProj\config\release.keystore,
  storePassword=android, keyAlias=AndroidDebugKey, keyPassword=android,
  storeType=C:\Users\— Shahab
  —\Desktop\master\TMessagesProj\config\release.keystore,
  v1SigningEnabled=true, v2SigningEnabled=true} of type
  com.android.build.gradle.internal.dsl.SigningConfig. Open File

答:
Can you share your build gradle file?
It seems that there is some problem in your Signing Configs.

Sharing a demo Signing Config code.

```<code>signingConfigs {
    release {
        storeFile file('demo.jks')
        storePassword "demo123"
        keyAlias "demo"
        keyPassword "demo123"
    }
}
</code>```

Body:
Can you share your build gradle file?
It seems that there is some problem in your Signing Configs.

Sharing a demo Signing Config code.

signingConfigs {
    release {
        storeFile file('demo.jks')
        storePassword "demo123"
        keyAlias "demo"
        keyPassword "demo123"
    }
}


问:
Creating iPhone style bubble list view in android
I am creating a chat application the interacts between two users. I want to show the interaction between the users in the form of a iPhone bubble list view...

I found a tutorial that shows to create a bubble list in IOS... Here's the link......

I have seen lot of Android applications that display the bubble list view like Handcent sms etc. I am also sure that some developers here may have a clue about doing it... I would be grateful if any one direct me towards a tutorial or some samples of achieving the task...

答:
You want something like this?

Click on the screen shots.

that is a twitter application that presents tweets in a bubble like format.

You'll have to implement a custom adapter for you ListView, where inside the getView() method, you can control how each row is drawn.

Implement different custom layouts for even-odd rows and you can something like this.

EDIT: You can find a full tutorial here: http://thetechnib.blogspot.com/2010/12/android-tutorial-custom-adapter-for.html


问:
Error 542 - N appears in the dimension of a variable
```<code>program factorial
implicit none
integer:: n1
real:: fact = 1.0
integer:: n = n1
integer, dimension(1:n):: x
integer:: i
print *, "Enter a number:"
read *, n1
x(1) = n1
do i=1,n1-1
  x(i+1) = n1-i
  fact = fact*x(i)
end do
print *, fact
end program factorial
</code>```

I have written a code for calculating factorial of a number. I am asking the user to put in an integer 'n1', after which it will create an array variable containing n1 compartments. I am unsuccessful in compiling this. I keep getting the following error!

factorial.F95(6) : error 542 - N appears in the dimension of a variable, yet is not a dummy argument, a variable available through USE or CONTAINS association, a COMMON variable, a PARAMETER, or a PURE FUNCTION

   Compilation failed.

How can I fix this? I want the array dimension to be equal to the input number. For example, say I want to calculate 5! (5 factorial), I want the x array to be of 5 (row or column) element length. Somehow, I am unable to do that!

答:
The constant n1 needs to be a compile time constant to be used as a static array dimension

```<code>program factorial
implicit none
integer, parameter:: n1
integer, dimension(1:n1):: x
</code>```

or you need to use allocatable arrays.

Body:
program factorial
implicit none
integer:: n1
real:: fact = 1.0
integer:: n = n1
integer, dimension(1:n):: x
integer:: i
print *, "Enter a number:"
read *, n1
x(1) = n1
do i=1,n1-1
  x(i+1) = n1-i
  fact = fact*x(i)
end do
print *, fact
end program factorial

I have written a code for calculating factorial of a number. I am asking the user to put in an integer 'n1', after which it will create an array variable containing n1 compartments. I am unsuccessful in compiling this. I keep getting the following error!

factorial.F95(6) : error 542 - N appears in the dimension of a variable, yet is not a dummy argument, a variable available through USE or CONTAINS association, a COMMON variable, a PARAMETER, or a PURE FUNCTION

   Compilation failed.

How can I fix this? I want the array dimension to be equal to the input number. For example, say I want to calculate 5! (5 factorial), I want the x array to be of 5 (row or column) element length. Somehow, I am unable to do that!

Body:
The constant n1 needs to be a compile time constant to be used as a static array dimension

program factorial
implicit none
integer, parameter:: n1
integer, dimension(1:n1):: x

or you need to use allocatable arrays.