问:
TypeError: Cannot read property 'then' of undefined at m.$scope.profile
I am trying to call a child service function in Main Controller.

But I am getting error on than in profile function.
This is my profile function inside main controller.

```<code>App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {

                if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = getClientResponse[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              });
            }
          }
      };
)};
</code>```

This is Service of another controller whom function "getClient" I am calling in profile function.

```<code>App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});
</code>```

Need Help. cant figure out the Problem. Thanks in advance!

答:
In the else part you can return dummy promise with either resolve($q.resolve()) or reject($q.reject()) status.

JS :

```<code>getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                 ///your rest code
                return promise;
            }else{
                 return $q.reject();
            }

        }
</code>```

With $q.reject() it will call error handler in profile call.So,add error handler callback as second parameter

```<code>ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {
//success code
},
function(){ //add it in your script

//check error here
});
</code>```

Body:
I am trying to call a child service function in Main Controller.

But I am getting error on than in profile function.
This is my profile function inside main controller.

App.controller("globalCtrl", function($scope,$rootScope, $window, $location, $rootScope, $cookieStore, toastr, ClientService,) {
  var theClient = $cookieStore.get('UserData') || {};

  $scope.profile = function(theClient) {

              var getCurrentClient = theClient;
              var getOrganizationId = $rootScope.globalSession.OrganizationId;
            if($rootScope.globalSession.UserRole == "Admin")
             {
               if (getOrganizationId) {

               ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {

                if(getClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {

                        $scope.myprofile = getClientResponse[1];
                        $location.path("/profile");
                }
                else {
                    toastr.warning($scope.USER_MESSAGE.SERVICE_NOT_AVAILABLE, '');
                 }
              });
            }
          }
      };
)};

This is Service of another controller whom function "getClient" I am calling in profile function.

App.factory('ClientService', function($http, $cookieStore, uuid2, API_URL, REQUEST_HEADER, RESPONSE_CODE) {
    var theClient = $cookieStore.get('UserData') || {};

    return {

        getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                function(aGetClientResponse) { //Success Callback

                    return [aGetClientResponse.data.GetClientResponse.Result.ResponseCode, aGetClientResponse.data.GetClientResponse];
                },
                function(aGetClientResponse) { //Error Callback
                    return [aGetClientResponse.status,''];
                });
            }
            return promise;
        },
        setClient: function(aClient) {
            theClient = aClient;
            $cookieStore.put('UserData', theClient);
        }
    }
});

Need Help. cant figure out the Problem. Thanks in advance!

Body:
In the else part you can return dummy promise with either resolve($q.resolve()) or reject($q.reject()) status.

JS :

getClient: function() {

            if(theClient.OrganizationId) {
                //API Call
                var promise = $http.get(API_URL.GET_CLIENT+theClient.OrganizationId+"&CorrelationId="+uuid2.newuuid()+"&ContextOrganizationId=009", REQUEST_HEADER).then(
                 ///your rest code
                return promise;
            }else{
                 return $q.reject();
            }

        }

With $q.reject() it will call error handler in profile call.So,add error handler callback as second parameter

ClientService.getClient(getOrganizationId).then(function(aGetClientResponse) {
//success code
},
function(){ //add it in your script

//check error here
});


来源: stackexchange

问:
passing variable from $(document).ready(function(){} to $(window).load(function() {}
Just imagine if I managed to create percent_pass at document.ready, how can I pass that var to window.load?

$(document).ready(function() {
  jQuery(function() {
    var question_count = $('.question-body').length;
    var question_percent = (1 / question_count) * 100;
    var color_percent = (300 / question_count);
    var percent_pass = 0;

    $('.answers input').click(function() {
      if ($(this).data('clicked') == false) {
        $(this).data('clicked', true);

        var old_height = $('.percent-solve').css('height');
        var new_height = parseInt(old_height) + color_percent;
        percent_pass += question_percent;

        if (percent_pass > 100) {
          percent_pass = 100;
        }
        $(".percentshow").html("%" + percent_pass);
        $('.count').text(percent_pass);
        $('.percent-solve').css('height', new_height + 'px');
        $('.count').each(function() {
          $(this).prop('Counter', percent_pass - question_percent).animate({
            Counter: $(this).text()
          }, {
            duration: 500,
            easing: 'swing',
            step: function(now) {
              $(this).text(Math.ceil(now));
            }
          });
        });
        if (Math.ceil(percent_pass) == 100) {
          $('.end-test').css('color', '#ff9803');
        }
      }

      var q_count = $(this).parents('.question-body').attr("id");
      q_count = parseInt(q_count) + 1;
      $('.question-body').removeClass('open-question');
      $.scrollTo($('#' + q_count), 500, {
        onAfter: function() {
          $('#' + q_count).addClass('open-question');
        }
      });
    });
  });
});

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
});

function init() {
  doughnutWidget.render(data());
}

function data() {
  var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',
    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}```

答: Update the percentage to a  and read it at window.load</p>

ContentLicense: CC BY-SA 3.0


问:
Why can I retrive an image with absolute path in XAML but it doesn't work behind code?
Trying to understand Assembly, Uri and all of those things and there is some stuff I don't understand and hopefully I can ask them here in one go.

I have a solution that contains two "Assembly's" if I understood it correctly like this.

Project Assemblies

Where I want my FetchResources to fetch that image and display it on my MainWindow.

It works without a problem when I do it in xaml like this.

Xaml FetchResources

But in behind-code I use the same Uri but for some reason it won't display the image.

```<code>var uri = new Uri("pack://application,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute);
BitmapImage bmi = new BitmapImage();
bmi.UriSource = uri;
testimage.Source = bmi;
</code>```

I'm not sure if I've understood Assembly correctly nor do I understand Uri to the full extent. I've read Microsofts Pack URIs in WPF but it's not clear to me how it works.

Why Can I reach the image through XAML but not in behind-code?

答:
You are missing a colon (:) after "application". Try this:

```<code>testimage.Source = new BitmapImage(new Uri("pack://application:,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute));
</code>```

And if you don't use the constructor overload that accepts a Uri, you should call the BeginInit() and EndInit() methods before and after you set the UriSource property:

```<code>BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri("pack://application:,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute);
bmi.EndInit();
testimage.Source = bmi;
</code>```

Body:
Trying to understand Assembly, Uri and all of those things and there is some stuff I don't understand and hopefully I can ask them here in one go.

I have a solution that contains two "Assembly's" if I understood it correctly like this.

Project Assemblies

Where I want my FetchResources to fetch that image and display it on my MainWindow.

It works without a problem when I do it in xaml like this.

Xaml FetchResources

But in behind-code I use the same Uri but for some reason it won't display the image.

var uri = new Uri("pack://application,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute);
BitmapImage bmi = new BitmapImage();
bmi.UriSource = uri;
testimage.Source = bmi;

I'm not sure if I've understood Assembly correctly nor do I understand Uri to the full extent. I've read Microsofts Pack URIs in WPF but it's not clear to me how it works.

Why Can I reach the image through XAML but not in behind-code?

Body:
You are missing a colon (:) after "application". Try this:

testimage.Source = new BitmapImage(new Uri("pack://application:,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute));

And if you don't use the constructor overload that accepts a Uri, you should call the BeginInit() and EndInit() methods before and after you set the UriSource property:

BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = new Uri("pack://application:,,,/WPF_UserControll_Test;component/Images/71805972.jpg", UriKind.Absolute);
bmi.EndInit();
testimage.Source = bmi;


问:
XSL - move promote child node to parent node and distinct-value
I have an xml file that contains elements that are parents instead of child, where a child element should be the parent. here is an example:

```<code><root>
 <sub-area number="1">
  <name>West Viking</name>
  <condition>good</condition>
  <area>
   <name>Viking</name>
   <condition>average</condition>
  <area>
 </sub-area>
 <sub-area number="2">
  <name>East Viking</name>
  <condition>good</condition>
  <area>
   <name>Viking</name>
   <condition>average</condition>
  <area>
 </sub-area>
 <sub-area number="3">
  <name>North Viking, South Viking</name>
  <condition>good</condition>
  <area>
   <name>Viking</name>
   <condition>average</condition>
  <area>
 </sub-area>
 <sub-area number="4">
  <name>West Utshire</name>
  <condition>good</condition>
  <area>
   <name>Utshire</name>
   <condition>good</condition>
  <area>
 </sub-area>
 <sub-area number="5">
  <name>East Utshire</name>
  <condition>good</condition>
  <area>
   <name>Utshire</name>
   <condition>good</condition>
  <area>
 </sub-area>
 <sub-area number="6">
  <name>North Utshire, South Utshire</name>
  <condition>average/condition>
  <area>
   <name>Utshire</name>
   <condition>good</condition>
  <area>
 </sub-area>
</root>
</code>```

What I would like to do in simplify this document by sub-areas being child nodes of the area. For example:

```<code><root>
 <area name="Viking">
  <condition>average</condition>
  <sub-area name="West Viking">
   <condition>good</condition>
  </sub-area>
  <condition>average</condition>
  <sub-area name="East Viking">
   <condition>bad</condition>
  </sub-area>
  <condition>average</condition>
  <sub-area name="North Viking">
   <condition>average</condition>
  </sub-area>
  <sub-area name="South Viking">
   <condition>good</condition>
  </sub-area>
 </area>
 <area name="Utshire">
  <condition>good</condition>
  <sub-area name="West Utshire">
   <condition>good</condition>
  </sub-area>
  <condition>average</condition>
  <sub-area name="East Utshire">
   <condition>bad</condition>
  </sub-area>
  <condition>average</condition>
  <sub-area name="North Utshire">
   <condition>good</condition>
  </sub-area>
  <sub-area name="South Utshire">
   <condition>good</condition>
 </area>
</root>
</code>```

Everything I tried failed so far. Looked at doc and forums, I couldn't find anything. I don't know how to approach this. Thank you for your help.

答:
The first thing is to bring your source XML to a proper shape:

add "/" to closing area tags,

change /condition> to </condition> (in 1 place).

And now back to the main business:

Start from groupping sub-area tags on area/name.

Then for each area name create parent (area) tag.

Within this area put sub-area tags - the content of the current group.

And here is a complete solution:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

  <xsl:template match="root">
    <xsl:copy>
      <xsl:for-each-group select="sub-area" group-by="area/name">
        <xsl:element name="area">
          <xsl:attribute name="name" select="current-grouping-key()"/>
          <xsl:sequence select="area/condition"/>
          <xsl:for-each select="current-group()">
            <xsl:element name="sub-area">
              <xsl:attribute name="name" select="name"/>
              <xsl:sequence select="condition"/>
            </xsl:element>
          </xsl:for-each>
        </xsl:element>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>
</xsl:transform>
</code>```

Body:
I have an xml file that contains elements that are parents instead of child, where a child element should be the parent. here is an example:

<root>

  <name>West Viking</name>
  <condition>good</condition>
  <area>
   <name>Viking</name>
   <condition>average</condition>
  <area>

  <name>East Viking</name>
  <condition>good</condition>
  <area>
   <name>Viking</name>
   <condition>average</condition>
  <area>

  <name>North Viking, South Viking</name>
  <condition>good</condition>
  <area>
   <name>Viking</name>
   <condition>average</condition>
  <area>

  <name>West Utshire</name>
  <condition>good</condition>
  <area>
   <name>Utshire</name>
   <condition>good</condition>
  <area>

  <name>East Utshire</name>
  <condition>good</condition>
  <area>
   <name>Utshire</name>
   <condition>good</condition>
  <area>

  <name>North Utshire, South Utshire</name>
  <condition>average/condition>
  <area>
   <name>Utshire</name>
   <condition>good</condition>
  <area>

</root>

What I would like to do in simplify this document by sub-areas being child nodes of the area. For example:

<root>
 <area name="Viking">
  <condition>average</condition>

   <condition>good</condition>

  <condition>average</condition>

   <condition>bad</condition>

  <condition>average</condition>

   <condition>average</condition>

   <condition>good</condition>

 </area>
 <area name="Utshire">
  <condition>good</condition>

   <condition>good</condition>

  <condition>average</condition>

   <condition>bad</condition>

  <condition>average</condition>

   <condition>good</condition>

   <condition>good</condition>
 </area>
</root>

Everything I tried failed so far. Looked at doc and forums, I couldn't find anything. I don't know how to approach this. Thank you for your help.

Body:
The first thing is to bring your source XML to a proper shape:

add "/" to closing area tags,

change /condition> to </condition> (in 1 place).

And now back to the main business:

Start from groupping sub-area tags on area/name.

Then for each area name create parent (area) tag.

Within this area put sub-area tags - the content of the current group.

And here is a complete solution:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

  <xsl:template match="root">
    <xsl:copy>
      <xsl:for-each-group select="sub-area" group-by="area/name">
        <xsl:element name="area">
          <xsl:attribute name="name" select="current-grouping-key()"/>
          <xsl:sequence select="area/condition"/>
          <xsl:for-each select="current-group()">
            <xsl:element name="sub-area">
              <xsl:attribute name="name" select="name"/>
              <xsl:sequence select="condition"/>
            </xsl:element>
          </xsl:for-each>
        </xsl:element>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>
</xsl:transform>


问:
SQL CLR Rights: Call Stored Procedure in CLR Procedure
I have written a (private) stored procedure in T-SQL that is not visible for the user. He has no execute permissions.

```<code>CREATE PROCEDURE [dbo].[GetEntries]
AS
BEGIN
    SELECT * FROM sometable
END
</code>```

Then I wrote a CLR stored procedure, for which the user has the execute permissions. This stored procedure calls my private procedure.

```<code>using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = "context connection=true";
    conn.Open();

    SqlCommand command = new SqlCommand("exec dbo.[GetEntries] ", conn);
...
</code>```

If I call the public CLR stored procedure, an error occured that I have no rights to call the private stored procedure. I think this is because my connection string is "context connection=true" so the stored procedure is in the user context (user connection).

When I write a public (user visible) T-SQL stored procedure, which calls the private stored procedure, I can execute this stored procedure.

```<code>CREATE PROCEDURE [dbo].TSQLPublicSP
AS
BEGIN
    Exec  dbo.[GetEntries]
END
</code>```

So my question is, how can I set the connection string in the SQL-CLR stored procedure like the connection it is from the T-SQL stored procedure. I don't want to set the databasename in the SQL-CLR connection string. It would be ok for me if I could get the database name form the SqlContext:

```<code>SqlConnection("server=LOCALHOST;integrated security=yes;database=" &
  SqlContext.???CurrentDatabase???)
</code>```

答:
Yes, the Context Connection is in the security context of the caller (or of the User specified in the EXECUTE AS clause of the CREATE PROCEDURE statement, but the default is EXECUTE AS CALLER).

The reason that the behavior is different between the SQLCLR stored procedure and the T-SQL stored procedure is:

The T-SQL stored procedure is making use of ownership chaining to imply permissions on related objects of the same owner as the code being executed.

The SQLCLR stored procedure is effectively submitting Dynamic SQL (as there is no way to pre-compile code within SQLCLR objects) which breaks ownership chaining.

If you want special permissions, then you need to use module signing as follows:

Create a Certificate or Asymmetric Key in this Database

Create a User from the Certificate or Asymmetric Key

Grant EXECUTE permission on the "hidden" stored procedure to the Cert-based or Key-based User

Sign the non-"hidden" stored procedure (doesn't matter if the visible one is T-SQL or SQLCLR) using ADD SIGNATURE.

If you ever make any changes to the Assembly that contains the method for this SQLCLR stored procedure, you will need to re-apply the ADD SIGNATURE

Body:
I have written a (private) stored procedure in T-SQL that is not visible for the user. He has no execute permissions.

CREATE PROCEDURE [dbo].[GetEntries]
AS
BEGIN
    SELECT * FROM sometable
END

Then I wrote a CLR stored procedure, for which the user has the execute permissions. This stored procedure calls my private procedure.

using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = "context connection=true";
    conn.Open();

    SqlCommand command = new SqlCommand("exec dbo.[GetEntries] ", conn);
...

If I call the public CLR stored procedure, an error occured that I have no rights to call the private stored procedure. I think this is because my connection string is "context connection=true" so the stored procedure is in the user context (user connection).

When I write a public (user visible) T-SQL stored procedure, which calls the private stored procedure, I can execute this stored procedure.

CREATE PROCEDURE [dbo].TSQLPublicSP
AS
BEGIN
    Exec  dbo.[GetEntries]
END

So my question is, how can I set the connection string in the SQL-CLR stored procedure like the connection it is from the T-SQL stored procedure. I don't want to set the databasename in the SQL-CLR connection string. It would be ok for me if I could get the database name form the SqlContext:

SqlConnection("server=LOCALHOST;integrated security=yes;database=" &
  SqlContext.???CurrentDatabase???)


问:
Prevent browser autofilling hidden fields
We use jQuery to hide fields that aren't relevant, depending on previous answers. It seems somehow the browser (Chrome) has managed to insert the users's email address into it.  Autocomplete is already set to off.  The field id and name are like "field-32", not even anything like "username" or "email".

Is this something out of our control? I suppose could try clearing all hidden fields on submit.... but that would break other stuff where I do need hidden fields.

答: My suggestion is not only to hide the fields, but also to set them as disabled (<code>.attr("disabled", true)</code>). This way they won't be submitted together with the rest of the form. </p>

Body: My suggestion is not only to hide the fields, but also to set them as disabled (.attr("disabled", true)). This way they won't be submitted together with the rest of the form.


问:
php, mysql search for the website
I need a search engine for a website I am building. I decided to try my own using php and mysql. Currently it looks like the viable options is to create three tables.

One for words, one for pages, and one reference table. Then when I am inserting a new article I would scan the text and put the separate words in the words table and refernce those words on the third table.

In the end when a search is made. The script should return the pages with the most indexed words for a given word.

However it looks like this approach can only return results depending on the number of keywords. The more a keyword is used in an article the more higher it will appear on the result page. So an article with less keywords maybe more related to the search but will be placed lower on the results.

The question would be is there a better way to create a custom search engine using php/mysql? Also if you do not have access to server to install search engines like Sphinx what is the best way to tackle this problem?

答:
I've built a search engine in much the same way, but I built a cross table, linking each word to each page in which it occurred. In that table, I also stored the number of times the word appeared in the page in relation to the length of the page. I calculated if you like, the percentage of the words on the page that were that word.
That makes it easier to apply a weight to your search result.
But unfortunately it is hard to determine if a page is more relevant in other ways. Google uses some tricks like the distance between two keywords on a page. If they are close to each other, they are probably related. If a keyword is higher in the page, it is probably more important, and so on.

But also, Google uses a totally different database structure that is better built for these kind of queries. It may be hard to build that in MySQL.

You can try if the FullText indexing of MySQL is any help to you. It indexes your pages and you can query using MATCH which returns a score for each row. I don't know exactly what formulas are used there, but it seems to be pretty smart.

If all of your pages are public you might want to consider using Google Custom Search or something like that. It will save you a lot of time.

ContentLicense: CC BY-SA 2.5

Title: php, mysql search for the website


问:
How to force use of vmovapd instead of vmovupd when programming SIMDed code using intel intrinsics?
I have some simple SIMD code which multiply 2 double arrays using intel intrinsic (using flag /arch:AVX2) and I compare it to standard loop without simd:

```<code>int const N = 67108864;
__declspec(align(32)) double* ar1 = new double[N];
__declspec(align(32)) double* ar2 = new double[N];
__declspec(align(32)) double* ar3 = new double[N];

for (size_t i = 0; i < N; i++)
{
    ar1[0] = 3.0;
    ar2[0] = 2.0;
}

for (int s = 0; s < 20; s++)
{
    auto begin = chrono::steady_clock::now();
    for (size_t i = 0; i < N; i++)
    {
        ar3[i] = ar1[i] * ar2[i];
    }
    cout << "n: " << chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - begin).count() << endl;

    begin = chrono::steady_clock::now();
    for (size_t i = 0; i < N; i+=4)
    {
        __m256d in1 = _mm256_load_pd(&ar1[i]);
        __m256d in2 = _mm256_load_pd(&ar2[i]);

        _mm256_store_pd(&ar3[i], _mm256_mul_pd(in1, in2));
    }
    cout << "s: " << chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - begin).count() << endl;
}
</code>```

but, I can't get any performance improvement for simd version. I looked on assembly and i guess, that it is because of vmovupd instruction when it should use vmovapd. Why it's use mov for unaligned packed data when i am using __declspec(align(32))?

entire simd loop:

```<code>61:         for (size_t i = 0; i < N; i+=4)
62:         {
63:             __m256d in1 = _mm256_load_pd(&ar1[i]);
64:             __m256d in2 = _mm256_load_pd(&ar2[i]);
00007FF62ED612A0  vmovupd     ymm1,ymmword ptr [rax]
65:
66:             _mm256_store_pd(&ar3[i], _mm256_mul_pd(in1, in2));
00007FF62ED612A4  vmulpd      ymm1,ymm1,ymmword ptr [rax+r13]
00007FF62ED612AA  vmovupd     ymmword ptr [rdx+rax],ymm1
00007FF62ED612AF  lea         rax,[rax+20h]
00007FF62ED612B3  sub         rcx,1
00007FF62ED612B7  vzeroupper
00007FF62ED612BA  jne         main+2A0h (07FF62ED612A0h)
67:         }
</code>```

I am new to code vectorisation, so I would be happy for pointer for any common mistakes I am doing.

答:
I have already faced with this problem. I have found following solution:

```<code>inline __m256d Load(const double * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_pd(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_pd(p);
#endif
}
</code>```

Analogous solution for float type:

```<code>inline __m256 Load(const float * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_ps(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_ps(p);
#endif
}
</code>```

I have just checked and it works. But in order to cheat Visual Studio compiler you have to use dynamically allocated pointers. Otherwise compiler doesn't use VMOVDQA instruction.

```<code>#include <immintrin.h>

int main()
{
    float * ps = (float*)_mm_malloc(40, 32);
    double * pd = (double*)_mm_malloc(40, 32);

    __m256 s = Load(ps);
//00007FF79FF81325  vmovdqa     ymm1,ymmword ptr [rdi]
    __m256d d = Load(pd);
//00007FF79FF8132F  vmovdqa     ymm0,ymmword ptr [rax]

    _mm256_storeu_ps(ps, s);
    _mm256_storeu_pd(pd, d);

    _mm_free(ps);
    _mm_free(pd);
}
</code>```

Body:
I have some simple SIMD code which multiply 2 double arrays using intel intrinsic (using flag /arch:AVX2) and I compare it to standard loop without simd:

int const N = 67108864;
__declspec(align(32)) double* ar1 = new double[N];
__declspec(align(32)) double* ar2 = new double[N];
__declspec(align(32)) double* ar3 = new double[N];

for (size_t i = 0; i < N; i++)
{
    ar1[0] = 3.0;
    ar2[0] = 2.0;
}

for (int s = 0; s < 20; s++)
{
    auto begin = chrono::steady_clock::now();
    for (size_t i = 0; i < N; i++)
    {
        ar3[i] = ar1[i] * ar2[i];
    }
    cout << "n: " << chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - begin).count() << endl;

    begin = chrono::steady_clock::now();
    for (size_t i = 0; i < N; i+=4)
    {
        __m256d in1 = _mm256_load_pd(&ar1[i]);
        __m256d in2 = _mm256_load_pd(&ar2[i]);

        _mm256_store_pd(&ar3[i], _mm256_mul_pd(in1, in2));
    }
    cout << "s: " << chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - begin).count() << endl;
}

but, I can't get any performance improvement for simd version. I looked on assembly and i guess, that it is because of vmovupd instruction when it should use vmovapd. Why it's use mov for unaligned packed data when i am using __declspec(align(32))?

entire simd loop:

61:         for (size_t i = 0; i < N; i+=4)
62:         {
63:             __m256d in1 = _mm256_load_pd(&ar1[i]);
64:             __m256d in2 = _mm256_load_pd(&ar2[i]);
00007FF62ED612A0  vmovupd     ymm1,ymmword ptr [rax]
65:
66:             _mm256_store_pd(&ar3[i], _mm256_mul_pd(in1, in2));
00007FF62ED612A4  vmulpd      ymm1,ymm1,ymmword ptr [rax+r13]
00007FF62ED612AA  vmovupd     ymmword ptr [rdx+rax],ymm1
00007FF62ED612AF  lea         rax,[rax+20h]
00007FF62ED612B3  sub         rcx,1
00007FF62ED612B7  vzeroupper
00007FF62ED612BA  jne         main+2A0h (07FF62ED612A0h)
67:         }

I am new to code vectorisation, so I would be happy for pointer for any common mistakes I am doing.

Body:
I have already faced with this problem. I have found following solution:

inline __m256d Load(const double * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_pd(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_pd(p);
#endif
}

Analogous solution for float type:

inline __m256 Load(const float * p)
{
#ifdef _MSC_VER
    return _mm256_castsi256_ps(_mm256_load_si256((__m256i*)p));
#else
    return _mm256_load_ps(p);
#endif
}

I have just checked and it works. But in order to cheat Visual Studio compiler you have to use dynamically allocated pointers. Otherwise compiler doesn't use VMOVDQA instruction.

#include <immintrin.h>

int main()
{
    float * ps = (float*)_mm_malloc(40, 32);
    double * pd = (double*)_mm_malloc(40, 32);

    __m256 s = Load(ps);
//00007FF79FF81325  vmovdqa     ymm1,ymmword ptr [rdi]
    __m256d d = Load(pd);
//00007FF79FF8132F  vmovdqa     ymm0,ymmword ptr [rax]

    _mm256_storeu_ps(ps, s);
    _mm256_storeu_pd(pd, d);

    _mm_free(ps);
    _mm_free(pd);
}


问:
Should a RESTful 'PUT' operation return something....
I was wondering what people's opinions are of a RESTful PUT operation that returns nothing (null) in the response body.

答:
I used RESTful API in my services, and here is my opinion:
First we must get to a common view： PUT is used to update an resource not create or get.

I defined resources with: Stateless resource and Stateful resource:

Stateless resources
For these resources, just return the HttpCode with empty body, it's enough.

Stateful resources
For example: the resource's version. For this kind of resources, you must provide the version when you want to change it, so return the full resource or return the version to the client, so the client need't to send a get request after the update action.

But, for a service or system, keep it simple, clearly, easy to use and maintain is the most important thing.

ContentLicense: CC BY-SA 4.0


问:
Why [dateFormatter stringFormat:[NSDate date]] can not be converted to a number
```<code>//In NSDate category:
+ (NSString *)timeWithFormat:(NSString *)format {
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   formatter.dateFormat = format;
   return [formatter stringFromDate:[NSDate date]];
}

//Swift3.0 invoke method:
let nowHour: Int = Int(NSDate.time(withFormat: "HH"))!//Crash code，I can not be reproduced
</code>```

I think when calling [formatter stringFromDate:[NSDate date]] the [NSDate date] code may be the return value is nil. Is this likely to happen? If so, how to reproduce it ? NSDate date return nil question

Device info:

答:
From looking at your code I think this is a locale issue. Not all locales use 0-9 to represent time.

If I run your code over all the 740 locale identifiers that's available for me, it fails on 60 of them. A subset of the locale identifiers where this code fails is presented below, along with their (American) English name and the string they produce for with the format "HH" for 2 PM:

```<code>ar          Arabic              ١٤
ars         Najdi Arabic        ١٤
as          Assamese            ১৪
bn          Bengali             ১৪
ckb         Central Kurdish     ١٤
dz          Dzongkha            ༡༤
fa          Persian             ۱۴
hi          Hindi               १४
ks          Kashmiri            ۱۴
lrc         Northern Luri       ۱۴
mr          Marathi             १४
my          Burmese             ၁၄
mzn         Mazanderani         ۱۴
ne          Nepali              १४
pa_Arab     Punjabi (Arabic)    ۱۴
ps          Pashto              ۱۴
ur_IN       Urdu (India)        ۱۴
uz_Arab     Uzbek (Arabic)      ۱۴
</code>```

Trying to create a number from these string like Int("१४")! will crash, because the Int constructor returns nil which is then being force unwrapped (!).

If you're interested in getting a numerical value for the hour of a given time, I would recommend that you get the hour date component using an appropriate calendar. For example:

```<code>Calendar.current.component(.hour, from: date)
</code>```

Body:
//In NSDate category:
+ (NSString *)timeWithFormat:(NSString *)format {
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   formatter.dateFormat = format;
   return [formatter stringFromDate:[NSDate date]];
}

//Swift3.0 invoke method:
let nowHour: Int = Int(NSDate.time(withFormat: "HH"))!//Crash code，I can not be reproduced

I think when calling [formatter stringFromDate:[NSDate date]] the [NSDate date] code may be the return value is nil. Is this likely to happen? If so, how to reproduce it ? NSDate date return nil question

Device info:

Body:
From looking at your code I think this is a locale issue. Not all locales use 0-9 to represent time.

If I run your code over all the 740 locale identifiers that's available for me, it fails on 60 of them. A subset of the locale identifiers where this code fails is presented below, along with their (American) English name and the string they produce for with the format "HH" for 2 PM:

ar          Arabic              ١٤
ars         Najdi Arabic        ١٤
as          Assamese            ১৪
bn          Bengali             ১৪
ckb         Central Kurdish     ١٤
dz          Dzongkha            ༡༤
fa          Persian             ۱۴
hi          Hindi               १४
ks          Kashmiri            ۱۴
lrc         Northern Luri       ۱۴
mr          Marathi             १४
my          Burmese             ၁၄
mzn         Mazanderani         ۱۴
ne          Nepali              १४
pa_Arab     Punjabi (Arabic)    ۱۴
ps          Pashto              ۱۴
ur_IN       Urdu (India)        ۱۴
uz_Arab     Uzbek (Arabic)      ۱۴

Trying to create a number from these string like Int("१४")! will crash, because the Int constructor returns nil which is then being force unwrapped (!).

If you're interested in getting a numerical value for the hour of a given time, I would recommend that you get the hour date component using an appropriate calendar. For example:

Calendar.current.component(.hour, from: date)


答:
Plesk instructions

I combined the top two answers here

In Plesk 12, I had nginx running as a reverse proxy (which I think is the default). So the current top answer doesn't work as nginx is also being run as a proxy.

I went to Subscriptions | [subscription domain] | Websites & Domains (tab) | [Virtual Host domain] | Web Server Settings.

Then at the bottom of that page you can set the Additional nginx directives which I set to be a combination of the top two answers here:

```<code>fastcgi_buffers         16  16k;
fastcgi_buffer_size         32k;
proxy_buffer_size          128k;
proxy_buffers            4 256k;
proxy_busy_buffers_size    256k;
</code>```

Title: upstream sent too big header while reading response header from upstream

Body:
Plesk instructions

I combined the top two answers here

In Plesk 12, I had nginx running as a reverse proxy (which I think is the default). So the current top answer doesn't work as nginx is also being run as a proxy.

I went to Subscriptions | [subscription domain] | Websites & Domains (tab) | [Virtual Host domain] | Web Server Settings.

Then at the bottom of that page you can set the Additional nginx directives which I set to be a combination of the top two answers here:

fastcgi_buffers         16  16k;
fastcgi_buffer_size         32k;
proxy_buffer_size          128k;
proxy_buffers            4 256k;
proxy_busy_buffers_size    256k;


问:
Can't bind to 'ng-model' since it isn't a known property of 'input'
Start learning Angular 2 , for this error tried almost all links in stack-overflow but still , please help me understand why still produces error even after import FormsModule

This is my customer.ts file

```<code>export class Customer {

  public CustomerName: string = "asdsad";
  public Code: string = "asdsa";
  public Amount: string = "asdasd";
}
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

import { Customer } from "./Customer"

@Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: './st.html'
})

   export class AppComponent {
customerobj: Customer = new Customer();
   }
</code>```

app.module.ts

```<code>            import { NgModule } from "@angular/core"
            import { BrowserModule } from "@angular/platform-browser"
            import { FormsModule } from '@angular/forms';
            import { AppComponent } from "./app.component"
            @NgModule({
                imports: [BrowserModule, FormsModule ],
                declarations: [AppComponent],
                bootstrap: [AppComponent]
            })

            export class AppModule { }
</code>```

main.ts

```<code>    import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"

    import { AppModule } from "./app.module"

    platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

答: Use [(ngModel)] instead of [(ng-model)]

Body:
Start learning Angular 2 , for this error tried almost all links in stack-overflow but still , please help me understand why still produces error even after import FormsModule

This is my customer.ts file

export class Customer {

  public CustomerName: string = "asdsad";
  public Code: string = "asdsa";
  public Amount: string = "asdasd";
}

app.component.ts

import { Component } from '@angular/core';

import { Customer } from "./Customer"

@Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: './st.html'
})

   export class AppComponent {
customerobj: Customer = new Customer();
   }

app.module.ts

            import { NgModule } from "@angular/core"
            import { BrowserModule } from "@angular/platform-browser"
            import { FormsModule } from '@angular/forms';
            import { AppComponent } from "./app.component"
            @NgModule({
                imports: [BrowserModule, FormsModule ],
                declarations: [AppComponent],
                bootstrap: [AppComponent]
            })

            export class AppModule { }

main.ts

    import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"

    import { AppModule } from "./app.module"

    platformBrowserDynamic().bootstrapModule(AppModule);

Body: Use [(ngModel)] instead of [(ng-model)]


问:
Bootstrap 4: switch between cols on mobile
I've built a standard layout with a sidebar using Bootstrap's grid system (EDIT: I'm using Bootstrap 4 but could still switch). It looks like this:

```<code><div class="row">
  <div class="col-md-3">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>
</code>```

On mobile, the red area would be above the green one. I need to be able to switch between them in a way that is more convenient than scrolling, for example a switch button:

Also note the different oder of elements in the green area.

Is there a smart way to do this? Or do I have to alter the dom with JavaScript? Thanks in advance :)

答:
Bootstrap 4 uses Flexbox, which means you could utilise the order in which things are displayed.

As usual, you can specify how it's displayed on different viewports using classes like order-last and order-sm-unordered.

flexbox/order documentation

Body:
I've built a standard layout with a sidebar using Bootstrap's grid system (EDIT: I'm using Bootstrap 4 but could still switch). It looks like this:

    ...

...

...

...

On mobile, the red area would be above the green one. I need to be able to switch between them in a way that is more convenient than scrolling, for example a switch button:

Also note the different oder of elements in the green area.

Is there a smart way to do this? Or do I have to alter the dom with JavaScript? Thanks in advance :)


问:
Why isn't setTransferListener being triggered in AWS?
I am trying to upload photos from android to S3 and I'm following the latest tutorial of how to on the S3 site but it seems like the TransferObserver isn't being triggered. All my variables are declared globally. When I run this code:

```<code>               credentialsProvider = new CognitoCachingCredentialsProvider(
                        getApplicationContext(),
                        "us-east-SECRET", // Identity Pool ID
                        Regions.US_EAST_1 // Region
                );

                    // Instantiate an S3 Client
                    // Create an S3 client
                    s3 = new AmazonS3Client(credentialsProvider);

                    // Set the region of your s3 bucket
                    s3.setRegion(Region.getRegion(Regions.DEFAULT_REGION));

                    // Instantiate TransferUtility
                    transferUtility = new TransferUtility(s3, getApplicationContext());

                    //Upload a file to amazon s3
                    Log.i("imageFile", imageFile.toString());

                    observer = transferUtility.upload(
                            "foond",     /* The bucket to upload to */
                            "key",    /* The key for the uploaded object */
                            imageFile        /* The file where the data to upload exists */
                    );

                    Log.i("observer", observer.getAbsoluteFilePath());
                    Log.i("observer", observer.toString());
                    Log.i("observer", observer.getState().toString());
                    Log.i("observer", String.valueOf(observer.getBytesTransferred()));

                    observer.setTransferListener(new TransferListener() {
                        @Override
                        public void onStateChanged(int id, TransferState state) {
                            Log.i("id", String.valueOf(id));
                            Log.i("TransferState", String.valueOf(state));
                        }

                        @Override
                        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                            Log.i("id", String.valueOf(id));
                            Log.i("bytesCurrent", String.valueOf(bytesCurrent));
                            Log.i("bytesTotal", String.valueOf(bytesTotal));
                        }

                        @Override
                        public void onError(int id, Exception ex) {
                            Log.e("Error", String.valueOf(ex));
                        }
                    });

                    Log.i("observer", observer.getState().toString());
                    Log.i("observer", String.valueOf(observer.getBytesTransferred()));
</code>```

What I get in the console is

```<code>I/OpenGLRenderer: Initialized EGL, version 1.4
W/art: Suspending all threads took: 21.244ms
D/CognitoCachingCredentialsProvider: Loading credentials from SharedPreferences
I/imageFile: /storage/emulated/0/DCIM/Camera/IMG_20160223_134442.jpg
V/RenderScript: 0x9ab29000 Launching thread(s), CPUs 4
I/observer: /storage/emulated/0/DCIM/Camera/IMG_20160223_134442.jpg
I/observer: com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver@6e1c6df
W/art: Suspending all threads took: 9.843ms
I/observer: WAITING
I/observer: 0
I/observer: WAITING
I/observer: 0
</code>```

It seems to me that none of the logs were printed out in setTransferListener. Why would this be the case? Also, it should be noted that the images are not uploaded onto S3.

Here are the permissions I have for the manifest

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</code>```

Here are my dependencies that I've imported:

```<code>compile 'com.amazonaws:aws-android-sdk-core:2.+'
compile 'com.amazonaws:aws-android-sdk-cognito:2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.+'
compile 'com.amazonaws:aws-android-sdk-ddb:2.+'
</code>```

I know my setup for S3 and cognito are correct because I've used the sample code that was provided in github and I got a file to upload. The problem was that the code did not fit the android version I was running in android studio and I did not want to go through the trouble of downgrading a version.

Here are my configurations in my gradle

```<code>compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "xxxxxxxxx"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
</code>```

TL;DR: TransferObserver observer = transferUtility.upload is not working. And images are not being uploaded.

答:
Just write this in your manifest (mention the service).</p>

```<code><service
    android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
    android:enabled="true" />
</code>```

Body:
I am trying to upload photos from android to S3 and I'm following the latest tutorial of how to on the S3 site but it seems like the TransferObserver isn't being triggered. All my variables are declared globally. When I run this code:

               credentialsProvider = new CognitoCachingCredentialsProvider(
                        getApplicationContext(),
                        "us-east-SECRET", // Identity Pool ID
                        Regions.US_EAST_1 // Region
                );

                    // Instantiate an S3 Client
                    // Create an S3 client
                    s3 = new AmazonS3Client(credentialsProvider);

                    // Set the region of your s3 bucket
                    s3.setRegion(Region.getRegion(Regions.DEFAULT_REGION));

                    // Instantiate TransferUtility
                    transferUtility = new TransferUtility(s3, getApplicationContext());

                    //Upload a file to amazon s3
                    Log.i("imageFile", imageFile.toString());

                    observer = transferUtility.upload(
                            "foond",     /* The bucket to upload to */
                            "key",    /* The key for the uploaded object */
                            imageFile        /* The file where the data to upload exists */
                    );

                    Log.i("observer", observer.getAbsoluteFilePath());
                    Log.i("observer", observer.toString());
                    Log.i("observer", observer.getState().toString());
                    Log.i("observer", String.valueOf(observer.getBytesTransferred()));

                    observer.setTransferListener(new TransferListener() {
                        @Override
                        public void onStateChanged(int id, TransferState state) {
                            Log.i("id", String.valueOf(id));
                            Log.i("TransferState", String.valueOf(state));
                        }

                        @Override
                        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                            Log.i("id", String.valueOf(id));
                            Log.i("bytesCurrent", String.valueOf(bytesCurrent));
                            Log.i("bytesTotal", String.valueOf(bytesTotal));
                        }

                        @Override
                        public void onError(int id, Exception ex) {
                            Log.e("Error", String.valueOf(ex));
                        }
                    });

                    Log.i("observer", observer.getState().toString());
                    Log.i("observer", String.valueOf(observer.getBytesTransferred()));

What I get in the console is

I/OpenGLRenderer: Initialized EGL, version 1.4
W/art: Suspending all threads took: 21.244ms
D/CognitoCachingCredentialsProvider: Loading credentials from SharedPreferences
I/imageFile: /storage/emulated/0/DCIM/Camera/IMG_20160223_134442.jpg
V/RenderScript: 0x9ab29000 Launching thread(s), CPUs 4
I/observer: /storage/emulated/0/DCIM/Camera/IMG_20160223_134442.jpg
I/observer: com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver@6e1c6df
W/art: Suspending all threads took: 9.843ms
I/observer: WAITING
I/observer: 0
I/observer: WAITING
I/observer: 0

It seems to me that none of the logs were printed out in setTransferListener. Why would this be the case? Also, it should be noted that the images are not uploaded onto S3.

Here are the permissions I have for the manifest

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Here are my dependencies that I've imported:

compile 'com.amazonaws:aws-android-sdk-core:2.+'
compile 'com.amazonaws:aws-android-sdk-cognito:2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.+'
compile 'com.amazonaws:aws-android-sdk-ddb:2.+'

I know my setup for S3 and cognito are correct because I've used the sample code that was provided in github and I got a file to upload. The problem was that the code did not fit the android version I was running in android studio and I did not want to go through the trouble of downgrading a version.

Here are my configurations in my gradle

compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "xxxxxxxxx"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}

TL;DR: TransferObserver observer = transferUtility.upload is not working. And images are not being uploaded.

Body:
Just write this in your manifest (mention the service).

<service
    android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
    android:enabled="true" />


问:
Manually typing in text in JavaFX Spinner is not updating the value (unless user presses ENTER)
It seems that the Spinner control does not update a manually typed-in value until the user explicitly presses enter. So, they could type in a value (not press enter) exit the control, and submit the form, and the value displayed in the spinner is NOT the value of the Spinner, it is the old value.

My idea was to add a listener to the lost focus event, but I can't see a way to gain access to the typed-in value?

```<code>spinner.focusedProperty().addListener((observable, oldValue, newValue) ->
{
    //if focus lost
    if(!newValue)
    {
        //somehow get the text the user typed in?
    }
});
</code>```

This is odd behavior, it seems to go against the convention of a GUI spinner control.

答:
Here is an improved variant of Sergio's solution.

The initialize method will attach Sergio's code to all Spinners in the controller.

```<code>public void initialize(URL location, ResourceBundle resources) {
    for (Field field : getClass().getDeclaredFields()) {
        try {
            Object obj = field.get(this);
            if (obj != null && obj instanceof Spinner)
                ((Spinner) obj).focusedProperty().addListener((observable, oldValue, newValue) -> {
                    if (!newValue) {
                        ((Spinner) obj).increment(0);
                    }
                });
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
It seems that the Spinner control does not update a manually typed-in value until the user explicitly presses enter. So, they could type in a value (not press enter) exit the control, and submit the form, and the value displayed in the spinner is NOT the value of the Spinner, it is the old value.

My idea was to add a listener to the lost focus event, but I can't see a way to gain access to the typed-in value?

spinner.focusedProperty().addListener((observable, oldValue, newValue) ->
{
    //if focus lost
    if(!newValue)
    {
        //somehow get the text the user typed in?
    }
});

This is odd behavior, it seems to go against the convention of a GUI spinner control.

Body:
Here is an improved variant of Sergio's solution.

The initialize method will attach Sergio's code to all Spinners in the controller.

public void initialize(URL location, ResourceBundle resources) {
    for (Field field : getClass().getDeclaredFields()) {
        try {
            Object obj = field.get(this);
            if (obj != null && obj instanceof Spinner)
                ((Spinner) obj).focusedProperty().addListener((observable, oldValue, newValue) -> {
                    if (!newValue) {
                        ((Spinner) obj).increment(0);
                    }
                });
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}


问:
String companion object in scala
Given a type which has a "converter", I would like to have automatic conversion on method call using this type's companion object. That is, given the following definition,

```<code>case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit val StringConverter = new Converter[String] {
  def perform = Converted("String")
}
</code>```

make the following code to work:

```<code>implicit def toConverter(a: String.type): Converted =
  implicitly[Converter[String]].perform // Error: `Found String.type, required AnyRef`

def f(needsConverted: Converted) = ???

f(String) // <- That's what I would like to be able to write.
</code>```

But this fails and both attempts for conversion fail. Note that I cannot change f because it is provided by a third-party library and there are many of them.

Can I make f(String) compile using implicits?

If not possible for Strings, what about classes which do have a companion object, can I do this generically like:

```<code>object TheClass

case class TheClass()

implicit val TheClassConverter = new Converter[TheClass] {
  def perform = Converted("TheClass")
}

implicit def toConverter[A: Converter](a: A.type): Converted =
  implicitly[Converter[A]].perform // Error: `Not found value A`

implicit def toConverter(a: TheClass.type): Converted =
  implicitly[Converter[TheClass]].perform // This works but is not generic

f(TheClass) // This works.
</code>```

Can I make the first toConverter to compile ?

答:
Instead of defining an implicit instance for the type MyClass you can define an implicit instance for the companion type MyClass.type.

```<code>implicit val TheClassConverter: Converter[MyClass.type] = new Converted[MyClass.type] {
  def perform = Converted("MyClass")
}
</code>```

Title: String companion object in scala

Body:
Given a type which has a "converter", I would like to have automatic conversion on method call using this type's companion object. That is, given the following definition,

case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit val StringConverter = new Converter[String] {
  def perform = Converted("String")
}

make the following code to work:

implicit def toConverter(a: String.type): Converted =
  implicitly[Converter[String]].perform // Error: `Found String.type, required AnyRef`

def f(needsConverted: Converted) = ???

f(String) // <- That's what I would like to be able to write.

But this fails and both attempts for conversion fail. Note that I cannot change f because it is provided by a third-party library and there are many of them.

Can I make f(String) compile using implicits?

If not possible for Strings, what about classes which do have a companion object, can I do this generically like:

object TheClass

case class TheClass()

implicit val TheClassConverter = new Converter[TheClass] {
  def perform = Converted("TheClass")
}

implicit def toConverter[A: Converter](a: A.type): Converted =
  implicitly[Converter[A]].perform // Error: `Not found value A`

implicit def toConverter(a: TheClass.type): Converted =
  implicitly[Converter[TheClass]].perform // This works but is not generic

f(TheClass) // This works.

Can I make the first toConverter to compile ?

Body:
Instead of defining an implicit instance for the type MyClass you can define an implicit instance for the companion type MyClass.type.

implicit val TheClassConverter: Converter[MyClass.type] = new Converted[MyClass.type] {
  def perform = Converted("MyClass")
}


问:
Check if column value is in other columns in pandas
I have the following dataframe in pandas

```<code>  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge
</code>```

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

答:
You can use drop, isin and any.

drop the target column to have a df with your A, B, C columns only

check if the values isin the target column

and check if any hits are present

That's it.

```<code>df["exists"] = df.drop("target", 1).isin(df["target"]).any(1)
print(df)

    target  A       B       C       exists
0   cat     bridge  cat     brush   True
1   brush   dog     cat     shoe    False
2   bridge  cat     shoe    bridge  True
</code>```

Body:
I have the following dataframe in pandas

  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

Body:
You can use drop, isin and any.

drop the target column to have a df with your A, B, C columns only

check if the values isin the target column

and check if any hits are present

That's it.

df["exists"] = df.drop("target", 1).isin(df["target"]).any(1)
print(df)

    target  A       B       C       exists
0   cat     bridge  cat     brush   True
1   brush   dog     cat     shoe    False
2   bridge  cat     shoe    bridge  True


问:
Angular2 can you subscribe for more than one parameter from same json?
So is it possible to subscribe to more than one json variables?

```<code> this.http.get(this.api_url + "preference")
  .map(response => response.json())
  .subscribe(res => this.limit = res.limit, res => this.sources = res.sources);
</code>```

In this example, the sources is an array of strings.
If you do it like this, only limit will be set.

my json:

```<code>{   "sources":["examplePage"],
    "limit":5
}
</code>```

答:
You can do multiple operations in the subscribe body by using curly braces {} to define the body of the function and then assign the two variables like so:

this.http.get(this.api_url + "preference")
    .map(response => response.json())
    .subscribe(res => {
        this.limit = res.limit;
        this.sources = res.sources;
});
```

As an aside the way subscribe is written in your question the limit will be set when the http request succeeds and the sources will be set when the request fails. subscribe(/* success */, /* error */, /* finished */)

Body:
So is it possible to subscribe to more than one json variables?

 this.http.get(this.api_url + "preference")
  .map(response => response.json())
  .subscribe(res => this.limit = res.limit, res => this.sources = res.sources);

In this example, the sources is an array of strings.
If you do it like this, only limit will be set.

my json:

{   "sources":["examplePage"],
    "limit":5
}

Body:
You can do multiple operations in the subscribe body by using curly braces {} to define the body of the function and then assign the two variables like so:

this.http.get(this.api_url + "preference")
    .map(response => response.json())
    .subscribe(res => {
        this.limit = res.limit;
        this.sources = res.sources;
});

As an aside the way subscribe is written in your question the limit will be set when the http request succeeds and the sources will be set when the request fails. subscribe(/* success */, /* error */, /* finished */)


问:
Could not fetch Places - REQUEST_DENIED
I want to fetch places from google place api, I just download SPGooglePlacesAutocomplete & created new API Key enable place, direction & map api's from Google API Console still i am getting error alert.

Any help very much appreciated.

答:
The Google Places API Web Service enforces a default limit of 1,000 free requests per 24 hour period.

The "status": "REQUEST_DENIED" is returned by the Google Places API Web Service when:

You have not activated the Google Places API Web Service in the Google API Console.

The key parameter is missing from your request. EX.
https://maps.googleapis.com/maps/api/place/add/json?key=YOUR_API_KEY

The key parameter does not match the your API key in the Google API Console.
Your API key has not been correctly set up in the Google API Console:

If you are using a browser-restricted API key, check that your
allowed referer(s) are correct.

If you are using a server-restricted API key, check that your allowed
IP(s) are correct.

API keys with Android or iOS restrictions are not supported. Please

use a generic (unrestricted) API key, or a key with browser or server
restrictions.

The request was not sent as an HTTPS request, HTTPS is required for all Google Places API Web Service requests.

The incorrect HTTP method was used to send the request:

All requests must be sent as a GET request except for Place Add.

All Place Add requests must be sent as a POST request.

Title: Could not fetch Places - REQUEST_DENIED


问:
Unsupported Oracle data type 101 encountered
```<code>OracleDataAdapter oAdp = new OracleDataAdapter("select * from " + TABLE_NAME, SourceConnStr);
oAdp.Fill(dtTable);
</code>```

On execution of this code I get the error:

```<code>Unsupported Oracle data type 101 encountered.
</code>```

So I searched about the same and turns out .NET currently doesn't support or identify binary float/double and one of the columns in the table it is referring to; is of the datatype binary double. Please suggest a way to identify if a column of the table is of the datatype binary float/double and cast it to a different datatype like number or varchar which ever is appropriate.

```<code>Name           Null     Type
-------------- -------- -------------
EMPID          NOT NULL VARCHAR2(20)
EMPNAME        NOT NULL VARCHAR2(50)
EMPTYPE        NOT NULL NUMBER(38)
EMPPHOTO                BINARY_DOUBLE
DATEOFJOINING           DATE
CONTACTNO               VARCHAR2(20)
</code>```

答:
Identify structure:

```<code>select * from all_tab_columns where data_type  like 'BINARY%' ;
</code>```

workaround:
In your select, replace the column with data conversion using e.g. TO_CHAR:

```<code>new OracleDataAdapter("select column_a, column_b, to_char(column_c_binary_smthg) from "
    + TABLE_NAME, SourceConnStr);
</code>```

Body:
OracleDataAdapter oAdp = new OracleDataAdapter("select * from " + TABLE_NAME, SourceConnStr);
oAdp.Fill(dtTable);

On execution of this code I get the error:

Unsupported Oracle data type 101 encountered.

So I searched about the same and turns out .NET currently doesn't support or identify binary float/double and one of the columns in the table it is referring to; is of the datatype binary double. Please suggest a way to identify if a column of the table is of the datatype binary float/double and cast it to a different datatype like number or varchar which ever is appropriate.

Name           Null     Type
-------------- -------- -------------
EMPID          NOT NULL VARCHAR2(20)
EMPNAME        NOT NULL VARCHAR2(50)
EMPTYPE        NOT NULL NUMBER(38)
EMPPHOTO                BINARY_DOUBLE
DATEOFJOINING           DATE
CONTACTNO               VARCHAR2(20)

Body:
Identify structure:

select * from all_tab_columns where data_type  like 'BINARY%' ;

workaround:
In your select, replace the column with data conversion using e.g. TO_CHAR:

new OracleDataAdapter("select column_a, column_b, to_char(column_c_binary_smthg) from "
    + TABLE_NAME, SourceConnStr);


问:
passing variable from $(document).ready(function(){} to $(window).load(function() {}
Just imagine if I managed to create percent_pass at document.ready, how can I pass that var to window.load?

$(document).ready(function() {
  jQuery(function() {
    var question_count = $('.question-body').length;
    var question_percent = (1 / question_count) * 100;
    var color_percent = (300 / question_count);
    var percent_pass = 0;

    $('.answers input').click(function() {
      if ($(this).data('clicked') == false) {
        $(this).data('clicked', true);

        var old_height = $('.percent-solve').css('height');
        var new_height = parseInt(old_height) + color_percent;
        percent_pass += question_percent;

        if (percent_pass > 100) {
          percent_pass = 100;
        }
        $(".percentshow").html("%" + percent_pass);
        $('.count').text(percent_pass);
        $('.percent-solve').css('height', new_height + 'px');
        $('.count').each(function() {
          $(this).prop('Counter', percent_pass - question_percent).animate({
            Counter: $(this).text()
          }, {
            duration: 500,
            easing: 'swing',
            step: function(now) {
              $(this).text(Math.ceil(now));
            }
          });
        });
        if (Math.ceil(percent_pass) == 100) {
          $('.end-test').css('color', '#ff9803');
        }
      }

      var q_count = $(this).parents('.question-body').attr("id");
      q_count = parseInt(q_count) + 1;
      $('.question-body').removeClass('open-question');
      $.scrollTo($('#' + q_count), 500, {
        onAfter: function() {
          $('#' + q_count).addClass('open-question');
        }
      });
    });
  });
});

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
});

function init() {
  doughnutWidget.render(data());
}

function data() {
  var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',
    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}```

答:
EDIT:

I have checked your website... Your problem is completely irrelevant to the variable scope... You are executing a script for a container element, that is non-existant in your HTML DOM, therefore the script fails.

Just use globalscope vars -
https://www.w3schools.com/js/js_scope.asp

//GlobalScope vars
var doughnutWidget = {/*Dummy js object, since i don't know douhnutWidget lib*/
    options: "",
    render: function() {
      return null;
    }
  },
  percent_pass;
//GlobalScope vars

$(document).ready(function() {

  jQuery(function() {

    percent_pass = 0;

  });
});

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
  console.log("see? no errors, fnc data() returns"+data()+" (that should be correct)");
});

function init() {
  doughnutWidget.render(data());
}

function data() {

  var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',

    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}```
<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></code>```

Your updated code

var question_count,question_percent,color_percent,percent_pass;//THESE ARE NOW GLOBAL VARS!

var doughnutWidget={options:"",render:function(){}};//again, dummy object just to prevent console errors
$(document).ready(function() {
  question_count = $('.question-body').length;
  question_percent = (1 / question_count) * 100;
  color_percent = (300 / question_count);
  percent_pass = 0;
  $('.answers input').click(function() {
    if ($(this).data('clicked') == false) {
      $(this).data('clicked', true);
      var old_height = $('.percent-solve').css('height');
      var new_height = parseInt(old_height) + color_percent;
      percent_pass += question_percent;

      if (percent_pass > 100) {
        percent_pass = 100;
      }
      $(".percentshow").html("%" + percent_pass);
      $('.count').text(percent_pass);
      $('.percent-solve').css('height', new_height + 'px');
      $('.count').each(function() {
        $(this).prop('Counter', percent_pass - question_percent).animate({
          Counter: $(this).text()
        }, {
          duration: 500,
          easing: 'swing',
          step: function(now) {
            $(this).text(Math.ceil(now));
          }
        });
      });
      if (Math.ceil(percent_pass) == 100) {
        $('.end-test').css('color', '#ff9803');
      }

    }

    var q_count = $(this).parents('.question-body').attr("id");
    q_count = parseInt(q_count) + 1;
    $('.question-body').removeClass('open-question');
    $.scrollTo($('#' + q_count), 500, {
      onAfter: function() {
        $('#' + q_count).addClass('open-question');
      }
    });
  });
});

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
});

function init() {
  doughnutWidget.render(data());
}

function data() {

  var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',

    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}```
<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></code>```

Body:
EDIT:

I have checked your website... Your problem is completely irrelevant to the variable scope... You are executing a script for a container element, that is non-existant in your HTML DOM, therefore the script fails.

Just use globalscope vars -
https://www.w3schools.com/js/js_scope.asp

//GlobalScope vars
var doughnutWidget = {/*Dummy js object, since i don't know douhnutWidget lib*/
    options: "",
    render: function() {
      return null;
    }
  },
  percent_pass;
//GlobalScope vars

$(document).ready(function() {

  jQuery(function() {

    percent_pass = 0;

  });
});

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
  console.log("see? no errors, fnc data() returns"+data()+" (that should be correct)");
});

function init() {
  doughnutWidget.render(data());
}

function data() {

  var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',

    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}

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

Your updated code

var question_count,question_percent,color_percent,percent_pass;//THESE ARE NOW GLOBAL VARS!

var doughnutWidget={options:"",render:function(){}};//again, dummy object just to prevent console errors
$(document).ready(function() {
  question_count = $('.question-body').length;
  question_percent = (1 / question_count) * 100;
  color_percent = (300 / question_count);
  percent_pass = 0;
  $('.answers input').click(function() {
    if ($(this).data('clicked') == false) {
      $(this).data('clicked', true);
      var old_height = $('.percent-solve').css('height');
      var new_height = parseInt(old_height) + color_percent;
      percent_pass += question_percent;

      if (percent_pass > 100) {
        percent_pass = 100;
      }
      $(".percentshow").html("%" + percent_pass);
      $('.count').text(percent_pass);
      $('.percent-solve').css('height', new_height + 'px');
      $('.count').each(function() {
        $(this).prop('Counter', percent_pass - question_percent).animate({
          Counter: $(this).text()
        }, {
          duration: 500,
          easing: 'swing',
          step: function(now) {
            $(this).text(Math.ceil(now));
          }
        });
      });
      if (Math.ceil(percent_pass) == 100) {
        $('.end-test').css('color', '#ff9803');
      }

    }

    var q_count = $(this).parents('.question-body').attr("id");
    q_count = parseInt(q_count) + 1;
    $('.question-body').removeClass('open-question');
    $.scrollTo($('#' + q_count), 500, {
      onAfter: function() {
        $('#' + q_count).addClass('open-question');
      }
    });
  });
});

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
});

function init() {
  doughnutWidget.render(data());
}

function data() {

  var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',

    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}

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


问:
Smart way to deal with TextBox OnChange Event
I'm looking for a best way to deal with text that moves from right to left.

So, I have this working code:

```<code>// write text for simulation view
File.WriteAllText("text1.txt", textBox1.Text, Encoding.UTF8);
// delete temporary processed video with overlayed text
ProcessFileOperations.deleteFile("text1.avi");

ProcessFileOperations.overlayText(text1ColorButton.BackColor.Name, filePath, 0);
mediaPlayer.URL = "text1.avi";
mediaPlayer.Ctlcontrols.play();
</code>```

This creates a video with overlayed scrolling text and instantly plays it as simulation. The problem arrives when I write text it fast windowmediaplayer is "going down" for a while - black image. How can let to user to put text and update media files with some delay or pause NOT to "freeze" main thread?

答:
this makes the changes run another thread and once completed media player runs with new file</p>

```<code>await Task.Run(()=>{
  // write text for simulation view
    File.WriteAllText("text1.txt", textBox1.Text, Encoding.UTF8);
    // delete temporary processed video with overlayed text
    ProcessFileOperations.deleteFile("text1.avi");

ProcessFileOperations.overlayText(text1ColorButton.BackColor.Name, filePath, 0);
});

mediaPlayer.URL = "text1.avi";
mediaPlayer.Ctlcontrols.play();
</code>```

Body:
I'm looking for a best way to deal with text that moves from right to left.

So, I have this working code:

// write text for simulation view
File.WriteAllText("text1.txt", textBox1.Text, Encoding.UTF8);
// delete temporary processed video with overlayed text
ProcessFileOperations.deleteFile("text1.avi");

ProcessFileOperations.overlayText(text1ColorButton.BackColor.Name, filePath, 0);
mediaPlayer.URL = "text1.avi";
mediaPlayer.Ctlcontrols.play();

This creates a video with overlayed scrolling text and instantly plays it as simulation. The problem arrives when I write text it fast windowmediaplayer is "going down" for a while - black image. How can let to user to put text and update media files with some delay or pause NOT to "freeze" main thread?

Body:
this makes the changes run another thread and once completed media player runs with new file

await Task.Run(()=>{
  // write text for simulation view
    File.WriteAllText("text1.txt", textBox1.Text, Encoding.UTF8);
    // delete temporary processed video with overlayed text
    ProcessFileOperations.deleteFile("text1.avi");

ProcessFileOperations.overlayText(text1ColorButton.BackColor.Name, filePath, 0);
});

mediaPlayer.URL = "text1.avi";
mediaPlayer.Ctlcontrols.play();


问:
Unable to run main method in IntelliJ
When attempting to run the main method in IntelliJ I get the following error:

Error:Cannot run program "C:\Program Files (x86)\Java\jdk1.8.0_121\bin\java" (in directory "C:\Users\MyName\.IntelliJIdea2016.3\system\compile-server"): CreateProcess error=2, The system cannot find the file specified

I'm not entirely sure what to do here, because I do have a JDK installed on my machine.

答:
sometimes you have to do the JDK path
go to the JDK directory in program files then go to bin folder copy the directory adress then. <br/>
go to computer right click on it then property go to advance setting then click on environment variables then choose path then edit it  at the last of the sentence of path enter ; then paste the path we copied </p>

Title: Unable to run main method in IntelliJ

Body:
sometimes you have to do the JDK path
go to the JDK directory in program files then go to bin folder copy the directory adress then.

go to computer right click on it then property go to advance setting then click on environment variables then choose path then edit it  at the last of the sentence of path enter ; then paste the path we copied


问:
How to get the streetname and city when user fills in zip code
I just took a look at www.wehkamp.nl (dutch only). When you try to make an account you can fill in your zip code (postcode) and it will automatically give you your city and street name. I knew this would be possible because most streets have it's own zip code. I have found some examples of automatically filling in country and city name when a user fills in his zip code. But none of street name + city name.

This is what Wehkamp returns when I fill in a zip code.

The bottom text is even telling the user that housenumber 139 does not exist on the filled in zip code.

Does anyone know if there is a special technique for this?

答:
This is not that hard to do. What they use is a postal code database or a postal code API. these options have thing in there like the start and end of the house numbers in that postal code area.

They also store what street that is associated to it and what city. I can see that you are Dutch so I'm guessing that you want the Dutch database.

Here is a link for a free SQL(not MySQL) database.

Here is a link to the a service that sells the API.

Here is a link to buy the database with updates.


问:
How may i use pdf-form gem to create Pdf in Rails
I am working on a project in Rails where i want one form in which user may enter any value he want like pdf form and after that when he submits the form pdf must be generated.I dont know how may i use pdf-form for that purpose.</p>

答:
You need to use wicked_pdf for pdf generation it is dead simple Go through it's documentation and if you find any difficulties implementing comment here. github.com/mileszs/wicked_pdf

And to your second query you need
to import that dump file you need to log-in into your mysql follow these steps:

mysql -u username -p password

show databases;

use your database_name;

source your dump_file_name;


问:
ReportViewer.PrintDialog() throws exception when printing to Adobe PDF
I am working on a WinForms app that uses the ReportViewer control to show a few Reporting Services reports.  On these screens, we allow the user to print the report by calling the PrintDialog() method on the ReportViewer like so:

```<code>_reportViewer.PrintDialog();
</code>```

This works fine in most cases, it brings up the standard windows print dialog, the user chooses what printer they want to print to, and it prints.  However, when the user chooses to print to PDF using "Adobe PDF", it throws a Win32Exception: The specified datatype is invalid.  The file dialog to choose where to save the pdf doesn't even come up.

This only happens with Adobe PDF printer.  I installed NitroPDF and used their PDF printer and it works without a problem.

Does anybody have an idea on what could be causing this to happen?

Edit:

Here is the stack trace:

```<code>at System.Drawing.Printing.StandardPrintController.OnStartPrint(PrintDocument document, PrintEventArgs e)
at System.Windows.Forms.PrintControllerWithStatusDialog.OnStartPrint(PrintDocument document, PrintEventArgs e)
at System.Drawing.Printing.PrintController.Print(PrintDocument document)
at System.Drawing.Printing.PrintDocument.Print()
at Microsoft.Reporting.WinForms.ReportViewer.PrintDialog(PrinterSettings printerSettings)
at Microsoft.Reporting.WinForms.ReportViewer.PrintDialog()
</code>```

答:
This doesn't truly fix the problem but solves it in the users' eyes.

Trap the error thrown by the PDF Printer then invoke the Export to PDF functionality built into Reporting Services.  It doesn't error in Winforms even when printing to the PDF Printer does.  From the user perspective they "printed to pdf" like normal and the experience is identical. It's a work around that works.  :-)

Body:
I am working on a WinForms app that uses the ReportViewer control to show a few Reporting Services reports.  On these screens, we allow the user to print the report by calling the PrintDialog() method on the ReportViewer like so:

_reportViewer.PrintDialog();

This works fine in most cases, it brings up the standard windows print dialog, the user chooses what printer they want to print to, and it prints.  However, when the user chooses to print to PDF using "Adobe PDF", it throws a Win32Exception: The specified datatype is invalid.  The file dialog to choose where to save the pdf doesn't even come up.

This only happens with Adobe PDF printer.  I installed NitroPDF and used their PDF printer and it works without a problem.

Does anybody have an idea on what could be causing this to happen?

Edit:

Here is the stack trace:

at System.Drawing.Printing.StandardPrintController.OnStartPrint(PrintDocument document, PrintEventArgs e)
at System.Windows.Forms.PrintControllerWithStatusDialog.OnStartPrint(PrintDocument document, PrintEventArgs e)
at System.Drawing.Printing.PrintController.Print(PrintDocument document)
at System.Drawing.Printing.PrintDocument.Print()
at Microsoft.Reporting.WinForms.ReportViewer.PrintDialog(PrinterSettings printerSettings)
at Microsoft.Reporting.WinForms.ReportViewer.PrintDialog()