问:
Getting errors when running Rails server with MySQL
```<code>dani@saeedi:~/Desktop/website/myweb$ rails server
/home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/lib/mysql2.rb:31:in `require': libmysqlclient.so.20: cannot open shared object file: No such file or directory - /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/lib/mysql2/mysql2.so (LoadError)
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/lib/mysql2.rb:31:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:82:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:82:in `block (2 levels) in require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:77:in `each'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:77:in `block in require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:66:in `each'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:66:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler.rb:108:in `require'
    from /home/dani/Desktop/website/myweb/config/application.rb:7:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:88:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:88:in `block in server'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:85:in `tap'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:85:in `server'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'
    from /home/dani/Desktop/website/myweb/bin/rails:9:in `require'
    from /home/dani/Desktop/website/myweb/bin/rails:9:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `load'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `call'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client/command.rb:7:in `call'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client.rb:30:in `run'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/bin/spring:49:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `load'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /home/dani/Desktop/website/myweb/bin/spring:15:in `<top (required)>'
    from bin/rails:3:in `load'
    from bin/rails:3:in `<main>'
</code>```

答:
Probably libmysqlclient is not installed in your system. Install it by using this command:

```<code>sudo apt-get install libmysqlclient-dev
</code>```

Cheers!

Body:
dani@saeedi:~/Desktop/website/myweb$ rails server
/home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/lib/mysql2.rb:31:in `require': libmysqlclient.so.20: cannot open shared object file: No such file or directory - /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/lib/mysql2/mysql2.so (LoadError)
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.5/lib/mysql2.rb:31:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:82:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:82:in `block (2 levels) in require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:77:in `each'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:77:in `block in require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:66:in `each'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler/runtime.rb:66:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.15.1/lib/bundler.rb:108:in `require'
    from /home/dani/Desktop/website/myweb/config/application.rb:7:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:88:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:88:in `block in server'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:85:in `tap'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:85:in `server'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'
    from /home/dani/Desktop/website/myweb/bin/rails:9:in `require'
    from /home/dani/Desktop/website/myweb/bin/rails:9:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `load'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client/rails.rb:28:in `call'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client/command.rb:7:in `call'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/client.rb:30:in `run'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/bin/spring:49:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `load'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/spring-2.0.1/lib/spring/binstub.rb:31:in `<top (required)>'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /home/dani/.rbenv/versions/2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /home/dani/Desktop/website/myweb/bin/spring:15:in `<top (required)>'
    from bin/rails:3:in `load'
    from bin/rails:3:in `'

Body:
Probably libmysqlclient is not installed in your system. Install it by using this command:

sudo apt-get install libmysqlclient-dev

Cheers!


来源: stackexchange

问:
Cannot upload files for release in Github
I want ot create a release for my Github project, but when I try to upload my binary (which is a .zip file) to the release, I get the following error message:

Something went really wrong, and we can’t process that file.

I get the same error message if I try to upload some other files (e.g. my readme file). What could be wrong?

答: I got that error due to my companies firewall that prevents all file uploads. Might this be the cause of your problems?</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How to create Google map with multiple addresses dynamically?
I am working on a real-estate website, I have made a PHP CMS for this site. I want to add one function, which works as follows.

I have a section named "Properties" in this website.

In this section, Client can add the property details like address, Image, specialty cost etc, via CMS.

When we add the address via CMS, I want that address to be shown on the google map shown beside.

How is it possible?

答:
The best way to do this is using Google Place Autocomplete. You can ask the admin to enter multiple fields while adding a property. For example:

Property Name, Property Address, Property Locality (Google Place Autocomplete), Pincode, City, State, Country.

With Google Place Autocomplete you can easily get the lat/lng, pincode, city, state, country of the location entered.

There is one more work around but not recommended. In one of my old project I didn't have latitude and longitude of the properties/places. So what I did was simple google map search. If that place has been tagged on google map already you might get proper location on map. You can try embedding the following url.

https://www.google.com/maps/embed/v1/place?key=YOUR_KEY&q=PROPERTY_NAME,PROPERTY_LOCATION


问:
jHipster registry can't compile angular dependencies
So I cloned the jHipster registries, but am getting the following warnings:

```<code>npm WARN angular2-cookie@1.2.6 requires a peer of @angular/common@^2.0.0 but none was installed.
npm WARN angular2-cookie@1.2.6 requires a peer of @angular/core@^2.0.0 but none was installed.
npm WARN ng2-translate@4.2.0 requires a peer of @angular/core@^2.0.0 but none was installed.
npm WARN ng2-translate@4.2.0 requires a peer of @angular/http@^2.0.0 but none was installed.
</code>```

How do I fix this so I can build?

答:
As it's an Angular project, after cloning the jhipster-registry project, you need to:

yarn install (to install all dependencies) or npm install, depending which tool you use

then you can start the registry: ./mvnw

Another solution:

you can download directly the war package at https://github.com/jhipster/jhipster-registry/releases/download/v3.0.1/jhipster-registry-3.0.1.war

then, use java -Djhipster.security.authentication.jwt.secret=xxxx -jar jhipster-registry-3.0.1.war

Body:
So I cloned the jHipster registries, but am getting the following warnings:

npm WARN angular2-cookie@1.2.6 requires a peer of @angular/common@^2.0.0 but none was installed.
npm WARN angular2-cookie@1.2.6 requires a peer of @angular/core@^2.0.0 but none was installed.
npm WARN ng2-translate@4.2.0 requires a peer of @angular/core@^2.0.0 but none was installed.
npm WARN ng2-translate@4.2.0 requires a peer of @angular/http@^2.0.0 but none was installed.

How do I fix this so I can build?


问:
General query regarding web application architecture, especially front end
Our application (initially accessible via web, later via mobile app and/or desktop apps) has an application server, which serves and internal API that'll be driven by all end points (React for web, iOS/Android for mobile in the future. etc). This application server will be accessible to those endpoints at app.<mydomain>.com - Currently this is implemented via a Django-REST-framework powered backend hosted on heroku.

We also have a landing page which will be served by www.<mydomain>.com.

My question is really about the server serving the landing page. Obviously it will be serving static content only, the landing page content, and the static react application JS that'll engage app.<mydomain>.com when it has to make requests and get data.

Obviously in this case I do not need a scripting engine on the backend. What do you recommend I use to serve up the landing page content and the static react app code? Simply apache server? anything else? Our app is U.S. only at this point, does it make sense to deploy via CloudFront or any other CDN?

I'd appreciate any advice.

答:
Static content is best served by a fast http server. My personal preference is nginx because of its simple config and great performance but apache will do as well.

It is as simple as uploading your htmls to the server. That being said, there are several things to keep in mind. Spend some time configuring cache headers for different file types. Automate the deployment process e.g. have Ansible deploy your web content after you push to repo, or turn it imto a docker container.  This should be more then enough to handle many thousands of requests a day. If your scale is bigger, then CDN is a valid point of improvement along with scaling of your web servers and further improvements to caching and compression.
Bonus point: your ngnix can also act as a very effective reverse proxy fronting your rest backend. You can easily setup load balancing and ssl - so that your rest can focus on just speedy business operation.

Happy hacking.


问:
Use Wikipedia API to get the most read articles within a certain time range?
Given some integer n and a date d, I'd like to use the Wikipedia API to obtain the n most viewed articles in the time between d and the current date. Is this possible, and if so, how?

What I have tried so far is the following:

Use https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikipedia/all-access/2017/05/01 . The problems with this approach are that firstly, this seems to support no other value than n = 1000 and secondly, it aggregates views only for a single day and not an arbitrary time range.

Use the query action with list allpages (i.e. https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages) to obtain all articles, but I do not know how to filter the result such that only the most viewed articles are included.

I also checked https://stats.wikimedia.org/ but didn't find anything helpful there.

答:
This feature doesn't appear to be available through the Pageviews API at present. You can find the most-viewed articles for a given day or a given month, but not for an arbitrary time frame. See the REST API docs for the different options available, and also see the Pageviews API page on Wikitech, which gives an example for finding the most viewed articles in a given month. (Slightly worryingly, the most-viewed-articles-per-month syntax doesn't seem to be documented on the API docs page.)

You can also get the pageview data through the Action API (api.php), as Tgr says in his comment below, but the data is the same as for the REST API.

You might want to ask on the wikitech-l email list, which is watched by the Wikimedia devs. They'll be able to tell you if this is possible a different way, and if not, why the feature isn't available.


问:
Angular js stop propagation from Bootstrap "dropdown-toggle" event
I have an Angular JS 1.3 app.

In it I have a table row repeater with an ng-click:

```<code><tr ng-repeat-start="user in users.users" ng-click="showDetails = !showDetails">
 <!-- main row, with the menu td shown below -->
<tr class="row-details" ng-show="showDetails" ng-class="{ 'active': showDetails }">
    <td>this is the row that hows details</td>
</tr>
<tr ng-repeat-end></tr>
</code>```

Which toggles opening a detail view. Works fine.  But now I need to add another item in each of the tds, a Bootstrap button menu:

```<code><td>
<div class="btn-group">
  <div ng-switch on="user.status">
    <button class="btn btn-link btn-gear dropdown-toggle" type="button" data-toggle="dropdown"><i class="fa fa-cog"></i></button>

      <ul class="dropdown-menu dropdown-menu-right" role="menu" ng-switch-when="Inactive">
        <li><a href="" ng-click="users.modals.deleteUser()">Delete</a></li>
      </ul>

      <ul class="dropdown-menu dropdown-menu-right" role="menu" ng-switch-when="Invited">
        <li><a href="" ng-click="users.toast.resendInvite()">Resend invitation</a></li>
        <li><a href="" ng-click="users.modals.deleteUser()">Delete</a></li>
      </ul>

      <ul class="dropdown-menu dropdown-menu-right" role="menu" ng-switch-default>
        <li><a href="" ng-click="users.toast.sentPassword()">Reset password</a></li>
        <li><a href="" ng-click="users.modals.deleteUser()">Delete</a></li>
      </ul>
  </div>
</div>
</td>
</code>```

Problem is, trying to click on this menu button instead triggers the ng-click on the row, toggling the row state but never opening my menu.  How can I prevent this?

答:
With help of dfsq's answer I managed solve same kind of problem in Angular 2. Here is my sample code.</p>

```<code><td class="tablerowdata" (click)="$event.dropdown || onSelect(track)" >

<button (click)="$event.dropdown = true" type="button" class="btn btn-default dropdown-toggle trackbuttons" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
</code>```

Body:
I have an Angular JS 1.3 app.

In it I have a table row repeater with an ng-click:

    this is the row that hows details

Which toggles opening a detail view. Works fine.  But now I need to add another item in each of the tds, a Bootstrap button menu:

    <button class="btn btn-link btn-gear dropdown-toggle" type="button" data-toggle="dropdown"></button>

Delete

Resend invitation

Delete

Reset password

Delete

Problem is, trying to click on this menu button instead triggers the ng-click on the row, toggling the row state but never opening my menu.  How can I prevent this?

Body:
With help of dfsq's answer I managed solve same kind of problem in Angular 2. Here is my sample code.

<td class="tablerowdata" (click)="$event.dropdown || onSelect(track)" >

<button (click)="$event.dropdown = true" type="button" class="btn btn-default dropdown-toggle trackbuttons" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">


问:
Passing XML Paths and evaluating
I'm working on a project where I need to parse an XML file and perform the exact same code on 100s of different XML Paths/Nodes.  My code currently looks like this…

```<code>def items = parser.parseText(inputFile.text)

items.item.each { item ->
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.weight_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.another_node[3].sub_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    // do this a 100 times or so with other item node paths
}
</code>```

Since the 'stuff to do' and the exception 'stuff' is the exact same every time and the only thing that changes is the node I'm working with. Because of this I would rather send the node expression to a method or extend the node class like this…

```<code>def myMethod(currentNode) {
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}

items.item.each { item ->
    myMethod(item.some_node)
    myMethod(item.weight_node)
    myMethod(item.another_node[3].sub_node)
    myMethod(item.some_node)
}

// OR

def myProcess(NodeList n){
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}
NodeList.metaClass.myProcess = { -> myProcess(delegate) }

items.item.each { item ->
    item.some_node.myMethod()
    item.weight_node.myMethod()
    item.another_node[3].sub_node.myMethod()
    item.some_node.myMethod()
}
</code>```

With the method attempt I can't figure out how to pass the XPath to the method and then use it.  With the class extension method it works so long as the node actually exists. If it doesn't I get an error trying to invoke myProcess.

Any ideas?

答:
for the second case

```<code>NodeList.metaClass.myProcess = { -> myProcess(delegate) }

items.item.each { item ->
    item.some_node.myMethod()
    item.weight_node.myMethod()
    ...
}
</code>```

you can use null safe accessor to avoid exception on not-existent nodes:

```<code>items.item.each { item ->
    item?.some_node?.myMethod()
    item?.weight_node?.myMethod()
    ...
}
</code>```

Title: Passing XML Paths and evaluating

Body:
I'm working on a project where I need to parse an XML file and perform the exact same code on 100s of different XML Paths/Nodes.  My code currently looks like this…

def items = parser.parseText(inputFile.text)

items.item.each { item ->
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.weight_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.another_node[3].sub_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    // do this a 100 times or so with other item node paths
}

Since the 'stuff to do' and the exception 'stuff' is the exact same every time and the only thing that changes is the node I'm working with. Because of this I would rather send the node expression to a method or extend the node class like this…

def myMethod(currentNode) {
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}

items.item.each { item ->
    myMethod(item.some_node)
    myMethod(item.weight_node)
    myMethod(item.another_node[3].sub_node)
    myMethod(item.some_node)
}

// OR

def myProcess(NodeList n){
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}
NodeList.metaClass.myProcess = { -> myProcess(delegate) }

items.item.each { item ->
    item.some_node.myMethod()
    item.weight_node.myMethod()
    item.another_node[3].sub_node.myMethod()
    item.some_node.myMethod()
}

With the method attempt I can't figure out how to pass the XPath to the method and then use it.  With the class extension method it works so long as the node actually exists. If it doesn't I get an error trying to invoke myProcess.

Any ideas?

Body:
for the second case

NodeList.metaClass.myProcess = { -> myProcess(delegate) }

items.item.each { item ->
    item.some_node.myMethod()
    item.weight_node.myMethod()
    ...
}

you can use null safe accessor to avoid exception on not-existent nodes:

items.item.each { item ->
    item?.some_node?.myMethod()
    item?.weight_node?.myMethod()
    ...
}


问:
Android Listview select first ten item
In my listview I have a checkbox and when I select the checkbox first 10 rows need to be selected, I did the code like this .. but it is selecting the rest of all rows except the first 10 rows..can anyone help me..what change I need to do here.</p>

```<code>if (checked)
                  {
                     // Toast.makeText(MyList.this, "Checked.", Toast.LENGTH_LONG).show();
                      //for(int i=0; i<lv.getChildCount();i++)
                      for(int i=0; i<lv.getAdapter().getCount();i++)
                      {

                          int m = 1;
                          final int firstListItemPosition = lv.getFirstVisiblePosition();

                          //final int firstListItemPosition = (int) lv.getItemAtPosition(m);
                          final int lastListItemPosition = firstListItemPosition + 9;

                          if (i < firstListItemPosition || i > lastListItemPosition ) {
                              View vii = lv.getAdapter().getView(i, null, lv);
                              //return listView.getAdapter().getView(pos, null, listView);
                              CheckBox cb = (CheckBox)vii.findViewById(R.id.selected);
                              cb.setChecked(true);

                          } else {
                              final int childIndex = i - firstListItemPosition;

                              CheckBox cb = (CheckBox)lv.getChildAt(childIndex).findViewById(R.id.selected);
                              cb.setChecked(true);
                          }
                          //Toast.makeText(MyList.this,s, Toast.LENGTH_LONG).show();

                      }
</code>```

答:
I think the first if thing checks all checkboxes without the ones you wanted.

Try changing the if statement to
i > firstListItemPosition && i < lastListItemPosition

I hope I understand what you want to do correctly.

Title: Android Listview select first ten item

Body:
In my listview I have a checkbox and when I select the checkbox first 10 rows need to be selected, I did the code like this .. but it is selecting the rest of all rows except the first 10 rows..can anyone help me..what change I need to do here.

if (checked)
                  {
                     // Toast.makeText(MyList.this, "Checked.", Toast.LENGTH_LONG).show();
                      //for(int i=0; i<lv.getChildCount();i++)
                      for(int i=0; i<lv.getAdapter().getCount();i++)
                      {

                          int m = 1;
                          final int firstListItemPosition = lv.getFirstVisiblePosition();

                          //final int firstListItemPosition = (int) lv.getItemAtPosition(m);
                          final int lastListItemPosition = firstListItemPosition + 9;

                          if (i < firstListItemPosition || i > lastListItemPosition ) {
                              View vii = lv.getAdapter().getView(i, null, lv);
                              //return listView.getAdapter().getView(pos, null, listView);
                              CheckBox cb = (CheckBox)vii.findViewById(R.id.selected);
                              cb.setChecked(true);

                          } else {
                              final int childIndex = i - firstListItemPosition;

                              CheckBox cb = (CheckBox)lv.getChildAt(childIndex).findViewById(R.id.selected);
                              cb.setChecked(true);
                          }
                          //Toast.makeText(MyList.this,s, Toast.LENGTH_LONG).show();

                      }


问:
how to interpret coefficients in log-log market mix model
I am running a multivariate OLS regression as below using weekly sales and media data. I would like to understand how to calculate the sales contribution when doing log transforms like log-linear, linear-log and log-log.

For example:
Volume_Sales = b0 + b1.TV_GRP + b2.SocialMedia + b3.PaidSearch + e

In this case, the sales contributed by TV is b1 x TV_GRPs (coefficient multiplied by the TV GRP of that month)

Now, my question is: How do we calculate sales contribution for the below cases:

Log-Linear: ln(Volume_Sales) = b0 + b1.TV_GRP + b2.SocialMedia + b3.PaidSearch + e

Linear-Log: Volume_Sales = b0 + b1.TV_GRP) + b2. ln(SocialMedia) + b3. ln(PaidSearch) + e

Log-Log: *ln(Volume_Sales) = b0 + b1.TV_GRP) + b2. ln(SocialMedia) + b3. ln(PaidSearch) + e**

答:
Log-linear means an exponential: ln(y) = a x + b is equivalent to y = exp(a x) * exp(b), which is of the form A^x * B. Likewise, a log-log transform gives a power law: ln(y) = a ln(x) + b is of the form y = B * x^a, with B = exp(b).

On a log-linear plot an exponential will thus be a straight line, and a power law will be on a log-log plot.


问:
how to match two array using foreach

The thing that I want to do is to compare the two arrays, find out if any duplication has been made in the second array versus the first array. Then if there has been any duplication, remove it from the second array so that if they select the same value in both lists that it will only be in the first.

```<code>first array (1,2,3,6,7.9)
second array (4,5,6,9,10,11)
</code>```

```<code>results would be
first array (1,2,3,6,7,9)
second array (4,5,10,11)
</code>```

答:
```<code>    $first = array (1,2,3,6,7,9);
    $second  = array (4,5,10,11);
    foreach ($second as $k=>$v){
        if(in_array($v, $first)){
            unset($second[$k]);
        }
    }
    $second = array_values($second);
    print_r($second); //Output
</code>```

Title: how to match two array using foreach

Body:
The thing that I want to do is to compare the two arrays, find out if any duplication has been made in the second array versus the first array. Then if there has been any duplication, remove it from the second array so that if they select the same value in both lists that it will only be in the first.

first array (1,2,3,6,7.9)
second array (4,5,6,9,10,11)

results would be
first array (1,2,3,6,7,9)
second array (4,5,10,11)


问:
use distinct with multiple columns in laravel
my table structure is as below

```<code>date        seller  unit    price   total
05-06-17    abc     14      700     9800
05-06-17    pqr     12      600     7200
05-06-17    abc     10      520     5200
06-06-17    abc     10      600     6000
06-06-17    pqr     15      520     7800
06-06-17    pqr     16      520     8320
</code>```

I need to fetch record like

```<code>1) 'date' = '05-06-2017', 'seller' = 'abc', 'total' = '15000'
2) 'date' = '05-06-2017', 'seller' = 'pqr', 'total' = '7200'
3) 'date' = '06-06-2017', 'seller' = 'abc', 'total' = '6000'
4) 'date' = '06-06-2017', 'seller' = 'pqr', 'total' = '16120'
</code>```

I need data from database in date wise. seller abc has two entry in a table for date 05-06-2017 so I need total of that day for seller abc as well pqr same things for the second date for all seller

答:
You could try</p>

```<code>DB::table('orders')
    ->select('date', 'seller', DB::raw('SUM(total)'))
    ->groupBy('date')
    ->groupBy('seller')
    ->get();
</code>```

Body:
my table structure is as below

date        seller  unit    price   total
05-06-17    abc     14      700     9800
05-06-17    pqr     12      600     7200
05-06-17    abc     10      520     5200
06-06-17    abc     10      600     6000
06-06-17    pqr     15      520     7800
06-06-17    pqr     16      520     8320

I need to fetch record like

1) 'date' = '05-06-2017', 'seller' = 'abc', 'total' = '15000'
2) 'date' = '05-06-2017', 'seller' = 'pqr', 'total' = '7200'
3) 'date' = '06-06-2017', 'seller' = 'abc', 'total' = '6000'
4) 'date' = '06-06-2017', 'seller' = 'pqr', 'total' = '16120'

I need data from database in date wise. seller abc has two entry in a table for date 05-06-2017 so I need total of that day for seller abc as well pqr same things for the second date for all seller

Body:
You could try

DB::table('orders')
    ->select('date', 'seller', DB::raw('SUM(total)'))
    ->groupBy('date')
    ->groupBy('seller')
    ->get();


问:
UTF-8 Encoding Error when Running External Groovy Script from Grails
I am trying to call an external Groovy script from within a Grails application.  I have the following code:

```<code>def initialSize = 4096
def outStream = new ByteArrayOutputStream(initialSize)
def errStream = new ByteArrayOutputStream(initialSize)
def process ="groovy -cp src/groovy/ src/groovy/externalscript.groovy ".execute()
process.consumeProcessOutput(outStream, errStream)
process.waitFor()
println 'out:\n' + outStream
println 'err:\n' + errStream
println process.exitValue()
</code>```

However, I get the following exception:

Error occurred during initialization of VM java.nio.charset.IllegalCharsetNameException: "UTF-8" at java.nio.charset.Charset.checkName(Charset.java:284) at java.nio.charset.Charset.lookup2(Charset.java:458) at java.nio.charset.Charset.lookup(Charset.java:437) at java.nio.charset.Charset.defaultCharset(Charset.java:579) at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:37) at java.io.OutputStreamWriter.(OutputStreamWriter.java:94) at java.io.PrintStream.(PrintStream.java:100) at java.lang.System.initializeSystemClass(System.java:1092)

The script works fine outside of Grails and I am not sure where the encoding issue is coming from. I have tried saving the externalscript.groovy as UTF-8 but I run into the same issue.

答:
The exception is thrown because the plateform default encoding for the child JVM somehow ended up being "UTF-8" including the quotation marks, which is not a legal charset name. It has nothing to do with the script itself, but with the way Grails spawns the child JVM.

Do you have something like

```<code>file.encoding="UTF-8"
</code>```

anywhere in your Grails configuration? Or code that sets the file.encoding system property?

ContentLicense: CC BY-SA 2.5

Body:
I am trying to call an external Groovy script from within a Grails application.  I have the following code:

def initialSize = 4096
def outStream = new ByteArrayOutputStream(initialSize)
def errStream = new ByteArrayOutputStream(initialSize)
def process ="groovy -cp src/groovy/ src/groovy/externalscript.groovy ".execute()
process.consumeProcessOutput(outStream, errStream)
process.waitFor()
println 'out:\n' + outStream
println 'err:\n' + errStream
println process.exitValue()

However, I get the following exception:

Error occurred during initialization of VM java.nio.charset.IllegalCharsetNameException: "UTF-8" at java.nio.charset.Charset.checkName(Charset.java:284) at java.nio.charset.Charset.lookup2(Charset.java:458) at java.nio.charset.Charset.lookup(Charset.java:437) at java.nio.charset.Charset.defaultCharset(Charset.java:579) at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:37) at java.io.OutputStreamWriter.(OutputStreamWriter.java:94) at java.io.PrintStream.(PrintStream.java:100) at java.lang.System.initializeSystemClass(System.java:1092)

The script works fine outside of Grails and I am not sure where the encoding issue is coming from. I have tried saving the externalscript.groovy as UTF-8 but I run into the same issue.

Body:
The exception is thrown because the plateform default encoding for the child JVM somehow ended up being "UTF-8" including the quotation marks, which is not a legal charset name. It has nothing to do with the script itself, but with the way Grails spawns the child JVM.

Do you have something like

file.encoding="UTF-8"

anywhere in your Grails configuration? Or code that sets the file.encoding system property?


问:
Overhead to using composer-rest-server over JavaScript / Node SDK?
We are trying to figure out best design practice while using hyper-ledger composer. We have following questions :

1) if We are using composer-rest-server, then will have to manage two server side components.
   i) running composer-rest-server ii) running application which will send request to composer-rest-server to communicate to network.

Isn't it overhead? what additional advantages we are getting by using composer-rest-server? in fact, probably client will have to authenticate two times i guess.

2) If we are using JavaScript SDK, then will have to manage only one server side application, kindly correct me in case of misunderstanding.

3) When i generated angularjs application using yo generator, its also asking me information of composer-rest-server, but I am not planning to use composer-rest-server and want to use 'composer-client' and 'composer-admin' only.

答:
Yes, there will be some overhead of running the composer-rest-server in its own process, however it will allow you to secure and scale your rest servers independent of your application. Depending on your scenario that may be an overhead worth paying.

Another option would be to generate a LoopBack application (using the lb tools) that uses the loopback-connector-composer LoopBack connector directly. This may give you access to the underlying Express server and would allow you to merge your application and the REST server.

You are correct, however you would have to build the REST API for your business network yourself, and manage authentication and certificates.

The generated Angular application uses the REST API exposed by the composer-rest-server to interact with HLF.

Here is a DRAFT topology diagram that I am working on for contribution to the documentation.


问:
ionic hide menu button but keep back button
I am working on a ionic framework app, where i need to hide only menu button on a specific template but need to keep back button.

it is showing like

My app.js

```<code>// setup an abstract state for the tabs directive
  .state('app', {
    url: '/app',
    cache: false,
    abstract: true,
    templateUrl: 'templates/menu.html',
  })

  .state('app.home', {
    url: '/home',
    cache: false,
    views: {
      'menuContent': {
        templateUrl: 'templates/home.html',
        controller: 'DashCtrl'
      }
    }
  })

  .state('app.models', {
      url: '/models',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/models.html',
          controller: 'ModelCtrl'
        }
      }
    })

    .state('app.model', {
      url: '/model/:Id',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/models-data.html',
          controller: 'ModeldataCtrl'
        }
      }
    })

    .state('app.models-detail', {
      url: '/models/:Id',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/single-model.html',
          controller: 'ModelDetailCtrl'
        }
      }
    })

  .state('app.about', {
    url: '/about',
    cache: false,
    views: {
        'menuContent': {
          templateUrl: 'templates/about.html',
          controller: 'AboutCtrl'
        }
      }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/home');

});
</code>```

Menu html is:

```<code><ion-side-menus enable-menu-with-back-views="true">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="left">
    <ion-header-bar class="bar-stable">
      <h1 class="title">Rolls</h1>
    </ion-header-bar>
    <ion-content>
      <ion-list>
        <ion-item menu-close href="#/app/home">
          Home
        </ion-item>
        <ion-item menu-close href="#/app/models">
          Models
        </ion-item>
        <ion-item menu-close href="#/app/about">
          About
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>
</code>```

single-model html page where i am getting both menu and back button code are : single-model.html

```<code><ion-view view-title="{{models.title}}">
  <ion-content class="padding" overflow-scroll="true">
    <img ng-src="{{models.image}}" style="width: 64px; height: 64px">
    <p>
      {{models.subtitle}}
    </p>
  </ion-content>
</ion-view>
</code>```

Model and single model controller code is :

```<code>.controller('ModeldataCtrl', function($rootScope,$scope,$ionicLoading,$timeout, $stateParams, Models) {
      $rootScope.dataloarding();
      Models.modeldata($stateParams.Id).success(function(result){
        if(result.success =='1'){
                  $scope.modeldata = result.data;
                  $rootScope.hideloading();
                }

              })
              .error(function(result)
                     {
                      $rootScope.hideloading();
                      $rootScope.showAlert("Internet Connection Error");
              });
})

.controller('ModelDetailCtrl', function($rootScope,$scope,$ionicLoading,$timeout, $stateParams,$ionicSideMenuDelegate, Models) {
      $ionicSideMenuDelegate.canDragContent(false);
      $rootScope.dataloarding();
      Models.singlemodel($stateParams.Id).success(function(result){
        if(result.success =='1'){
                  $scope.models = result.data;
                  $rootScope.hideloading();
                }

              })
              .error(function(result)
                     {
                      $rootScope.hideloading();
                      $rootScope.showAlert("Internet Connection Error");
              });
})
</code>```

i follow this and this but it remove both back button and menu both or back button only.

Is there any solution to remove only menu from single-model html page only ?

答:
You can try this, it works for me. Replace your side menu content with below code

```<code><ion-pane ion-side-menu-content>
<ion-nav-bar class="bar-stable">
  <ion-nav-back-button class="button-clear"><i class="icon ion-chevron-left"></i> Back</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view name="menuContent" animation="slide-left-right"></ion-nav-view>
</code>```

Body:
I am working on a ionic framework app, where i need to hide only menu button on a specific template but need to keep back button.

it is showing like

My app.js

// setup an abstract state for the tabs directive
  .state('app', {
    url: '/app',
    cache: false,
    abstract: true,
    templateUrl: 'templates/menu.html',
  })

  .state('app.home', {
    url: '/home',
    cache: false,
    views: {
      'menuContent': {
        templateUrl: 'templates/home.html',
        controller: 'DashCtrl'
      }
    }
  })

  .state('app.models', {
      url: '/models',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/models.html',
          controller: 'ModelCtrl'
        }
      }
    })

    .state('app.model', {
      url: '/model/:Id',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/models-data.html',
          controller: 'ModeldataCtrl'
        }
      }
    })

    .state('app.models-detail', {
      url: '/models/:Id',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/single-model.html',
          controller: 'ModelDetailCtrl'
        }
      }
    })

  .state('app.about', {
    url: '/about',
    cache: false,
    views: {
        'menuContent': {
          templateUrl: 'templates/about.html',
          controller: 'AboutCtrl'
        }
      }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/home');

});

Menu html is:

<ion-side-menus enable-menu-with-back-views="true">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="left">
    <ion-header-bar class="bar-stable">

Rolls

    </ion-header-bar>
    <ion-content>
      <ion-list>
        <ion-item menu-close href="#/app/home">
          Home
        </ion-item>
        <ion-item menu-close href="#/app/models">
          Models
        </ion-item>
        <ion-item menu-close href="#/app/about">
          About
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>

single-model html page where i am getting both menu and back button code are : single-model.html

<ion-view view-title="{{models.title}}">
  <ion-content class="padding" overflow-scroll="true">

      {{models.subtitle}}

  </ion-content>
</ion-view>

Model and single model controller code is :

.controller('ModeldataCtrl', function($rootScope,$scope,$ionicLoading,$timeout, $stateParams, Models) {
      $rootScope.dataloarding();
      Models.modeldata($stateParams.Id).success(function(result){
        if(result.success =='1'){
                  $scope.modeldata = result.data;
                  $rootScope.hideloading();
                }

              })
              .error(function(result)
                     {
                      $rootScope.hideloading();
                      $rootScope.showAlert("Internet Connection Error");
              });
})

.controller('ModelDetailCtrl', function($rootScope,$scope,$ionicLoading,$timeout, $stateParams,$ionicSideMenuDelegate, Models) {
      $ionicSideMenuDelegate.canDragContent(false);
      $rootScope.dataloarding();
      Models.singlemodel($stateParams.Id).success(function(result){
        if(result.success =='1'){
                  $scope.models = result.data;
                  $rootScope.hideloading();
                }

              })
              .error(function(result)
                     {
                      $rootScope.hideloading();
                      $rootScope.showAlert("Internet Connection Error");
              });
})

i follow this and this but it remove both back button and menu both or back button only.

Is there any solution to remove only menu from single-model html page only ?

Body:
You can try this, it works for me. Replace your side menu content with below code

<ion-pane ion-side-menu-content>
<ion-nav-bar class="bar-stable">
  <ion-nav-back-button class="button-clear"><i class="icon ion-chevron-left"></i> Back</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view name="menuContent" animation="slide-left-right"></ion-nav-view>


问:
PowerShell: How to make email message body to be html fomatted but to contain raw soap response
Using a PowerShell script I invoke a web request and save the response in a variable

```<code>$SOAP_RESP=(Invoke-WebRequest $WEB_SRV_URL -Method Post -ContentType "text/xml" -InFile $SOAP_REQ_FILE_PATH).Content
</code>```

I have email body HTML formatted and I append the earlier obtained SOAP response to it.

```<code>$MESSAGE_BODDY="$($HTML_FORMATTED_MESSAGE)<br><br>$($SOAP_RESP)"
</code>```

Next I want to send an email containing email body from the previous step -BodyAsHtml

```<code>Send-MailMessage -From $SMTP_FROM -To $SMTP_TO -Subject $MESSAGE_SUBJECT -Body $MESSAGE_BODDY -BodyAsHtml -Priority high
</code>```

Obviously, it formats the SOAP response and the email which is delivered is a mess.

Does anyone know how can I deal with this situation? I need SOAP request to be in the email.

[EDIT]
    The soap response is

```<code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xmm="http://namespace.mynamespace/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <SOAP-ENV:Body>
    <m:service_name xmlns:m="urn:com-s-s-rpc:SYSTEM">
      <_INPUT_PARAM>
        <UNIT_ID>0dbghfgd</UNIT_ID>
        <MSG>test</MSG>
      </_INPUT_PARAM>
      <_OUTPUT_PARAM>
        <RETURN_ERROR_MSG>Invalid Format</RETURN_ERROR_MSG>
      </_OUTPUT_PARAM>
    </m:service_name>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

What I get in email is only below string (not entire response)

```<code><_INPUT_PARAM>0dbghfgdtest<_OUTPUT_PARAM>Invalid Format
</code>```

答:
Per the comment from TessellatingHeckler, the ```</code> and <code><code></code> HTML tags both force the contents of those tags to be presented raw and any HTML tags within are not interpreted. Pre stands for Preformatted Text. Code means "This is computer code". </p>

<p>You can use both together for a belt and braces approach:</p>

```$MESSAGE_BODDY="$($HTML_FORMATTED_MESSAGE)

```<code>$($SOAP_RESP)```"
```

Body:
Using a PowerShell script I invoke a web request and save the response in a variable

$SOAP_RESP=(Invoke-WebRequest $WEB_SRV_URL -Method Post -ContentType "text/xml" -InFile $SOAP_REQ_FILE_PATH).Content

I have email body HTML formatted and I append the earlier obtained SOAP response to it.

$MESSAGE_BODDY="$($HTML_FORMATTED_MESSAGE)

$($SOAP_RESP)"

Next I want to send an email containing email body from the previous step -BodyAsHtml

Send-MailMessage -From $SMTP_FROM -To $SMTP_TO -Subject $MESSAGE_SUBJECT -Body $MESSAGE_BODDY -BodyAsHtml -Priority high

Obviously, it formats the SOAP response and the email which is delivered is a mess.

Does anyone know how can I deal with this situation? I need SOAP request to be in the email.

[EDIT]
    The soap response is

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xmm="http://namespace.mynamespace/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <SOAP-ENV:Body>
    <m:service_name xmlns:m="urn:com-s-s-rpc:SYSTEM">
      <_INPUT_PARAM>
        <UNIT_ID>0dbghfgd</UNIT_ID>
        <MSG>test</MSG>
      </_INPUT_PARAM>
      <_OUTPUT_PARAM>
        <RETURN_ERROR_MSG>Invalid Format</RETURN_ERROR_MSG>
      </_OUTPUT_PARAM>
    </m:service_name>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

What I get in email is only below string (not entire response)

<_INPUT_PARAM>0dbghfgdtest<_OUTPUT_PARAM>Invalid Format

Body:
Per the comment from TessellatingHeckler, the <pre> and <code> HTML tags both force the contents of those tags to be presented raw and any HTML tags within are not interpreted. Pre stands for Preformatted Text. Code means "This is computer code".

You can use both together for a belt and braces approach:

$MESSAGE_BODDY="$($HTML_FORMATTED_MESSAGE)<br><br><pre><code>$($SOAP_RESP)</pre></code>"


问:
How to get performance counters/metrics in Service Fabric?
I have a stateless service that listens to an EventHub in Service Fabric, and I want to collect performance metrics like the receive latency, and the cpu and memory usage in the nodes in the cluster. What is the easiest way of doing that? I read a lot about that but most examples I saw were showing how to do it with Cloud services which I found quite different from Service Fabric. I also read that Azure Diagnostics could be used to collect performance counters, but I didn't find a clear way of doing it programmatically from Visual Studio.  </p>

答:
You can use Application Insighs. It is announced at Build 2017 (See the last few minutes) and still in beta but it gives you a very good overview of how the services are doing.

I did make a repo myself that integrates Application Insights with Service Fabric. With some coding you can wire it up using my code as a guideline/example. Just for performance counters per node it is relatively easy.

Another option would be using EventFlow to collect the performance counter data and send it to wherever you want (there are limited build-in options but it is easy to write a sink yourself)

I am sure there are more but I think Application Insights is your best bet as it supports everything from performance counters (per node) to request telemetry and it is extensible as well.


问:
Angular 2 Pagination not working
I am trying to implement angular2-datatable from https://github.com/mariuszfoltak/angular2-datatable/blob/master/README.md in to my application. But for some reason the rowsOnPage is not taking the number I assign to it.

For e.g. when I say show 5 records on a page, it shows all the records. I don't know what I am missing. Can someone please help me resolve it.

        <mfDefaultSorter by="gt">GT</mfDefaultSorter>

        <mfDefaultSorter by="name_e">Name E</mfDefaultSorter>

        <mfDefaultSorter by="name_z">Name Z</mfDefaultSorter>

      {{product.gt}}
      {{product.name_e}}
      {{product.name_z}}

                                Edit

      No Records Found

      No matches

        <mfBootstrapPaginator [rowsOnPageSet]="[5, 10, 15]"></mfBootstrapPaginator>

```

答:
I think you need to change you ngFor. In official example they are using

```<code><tr *ngFor="let item of mf.data">
</code>```

But you have put in ngFor different data

```<code><tr *ngFor="let product of products | SearchPipe : searchText">
</code>```

Have a look on demo from documentation

Title: Angular 2 Pagination not working

Body:
I think you need to change you ngFor. In official example they are using

<tr *ngFor="let item of mf.data">

But you have put in ngFor different data

<tr *ngFor="let product of products | SearchPipe : searchText">

Have a look on demo from documentation


问:
How to upgrade/update makeinfo/texinfo from version 4.8 to 4.13 on macOSX terminal command line?
I have makeinfo 4.8 already installed. Command line typing $ makeinfo --version returns makeinfo (GNU texinfo) 4.8.

I'd like to update the version to the latest 4.13. I've found relevant info here and here. I'm new to command line/bash/git... Please help me out, much appreciated!

答:
Looking at this issue, you shouldn't need dragonfly (or git commands):

```<code>configure: error: You do not seem to have makeinfo >= 4.13, and your
source tree does not seem to have pre-built manuals in the 'info' directory.
Either install a suitable version of makeinfo, or re-run configure
with the '--without-makeinfo' option to build without the manuals.
</code>```

I've tried brew install texinfo and then brew ln texinfo --force and now makeinfo --version shows texi2any (GNU texinfo) 6.3

Note, as commented by jmq::

If you use brew to install, make sure you have /usr/local/opt/texinfo/bin in your path, and it is before /usr/bin.

  Version 4.8 of this tool on the Mac (10.12.6) is located in /usr/bin/makeinfo.

  If this path is in front of the latter, then it will not find the latest version installed by brew.

Body:
Looking at this issue, you shouldn't need dragonfly (or git commands):

configure: error: You do not seem to have makeinfo >= 4.13, and your
source tree does not seem to have pre-built manuals in the 'info' directory.
Either install a suitable version of makeinfo, or re-run configure
with the '--without-makeinfo' option to build without the manuals.

I've tried brew install texinfo and then brew ln texinfo --force and now makeinfo --version shows texi2any (GNU texinfo) 6.3

Note, as commented by jmq::

If you use brew to install, make sure you have /usr/local/opt/texinfo/bin in your path, and it is before /usr/bin.

  Version 4.8 of this tool on the Mac (10.12.6) is located in /usr/bin/makeinfo.

  If this path is in front of the latter, then it will not find the latest version installed by brew.


问:
streaming while processing
I'm working on an application where I receive a large amount of data via the USB from 4 sensors and displaying them in Matlab.

The streaming works perfectly , however, I need to do some processing on the data as it's streaming. I use segments of the incoming data and process them then plot the processed data. The incoming data is taken segment by segment and processed.

My problem is that, if I'm processing 5 seconds' worth of data in every segment. When the processing and plotting is implemented, the streaming stops, therefore when it's time for the next batch to process, I have to wait for the streaming of the next 5 seconds segment. Even if I delay the beginning of the processing to let's say after 20 seconds, the streaming will always stop when the processing starts and I will always have a small pause to read new data. How can I keep the streaming or the data reception from the serial port going even when I'm processing the data?

Thanks

答:
You should use a worker thread to perform your processing. This can be done in matlab using the parfeval command as follows:

```<code>parpool % start a parallel pool (may take some time)

...

nOutputs = 1; % number of outputs
in1 = 1; % first input argument
in2 = 2; % second input argument
f = parfeval(@your_function, nOutputs, in1, in2); % execute your function with two input arguments as example

...

% check regularly if the function is executed
if strcmp(f.State, 'finished') == 1
  output = fetchOutputs(f);
  ... % do something with the output
  delete(f); % empty resources
end
</code>```

As an alternative, you can use the batch command.

Title: streaming while processing

Body:
You should use a worker thread to perform your processing. This can be done in matlab using the parfeval command as follows:

parpool % start a parallel pool (may take some time)

...

nOutputs = 1; % number of outputs
in1 = 1; % first input argument
in2 = 2; % second input argument
f = parfeval(@your_function, nOutputs, in1, in2); % execute your function with two input arguments as example

...

% check regularly if the function is executed
if strcmp(f.State, 'finished') == 1
  output = fetchOutputs(f);
  ... % do something with the output
  delete(f); % empty resources
end

As an alternative, you can use the batch command.


问:
using ESI slower than EAX?
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

```<code>jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1
</code>```

```<code>jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1
</code>```

答:
,Boath pieces of code has more or less the some excecution speed. You can check the execution speed via execution of instruction rdtsc before rutine and after rutine to measure (count) execution CPU clocks. Of course boath rutines must to start with the some value in EAX and ESI register. Do not use a huge loop values becouse the task scheduler can interrupt the current task in the middle of loop execution and you will get wrong result. However if some measiring result deviate a lot than the current task was interrupted by the task scheduler and you must to ignore that result.

EDIT: TESTs

Here I have put both tests, so that everybody can check the results:

```<code>var
  StartTicks                :Int64;
  EndTicks                  :Int64;

    procedure TForm9.ButtonEAXClick(Sender: TObject);
    begin
      asm
        rdtsc
        mov         dword ptr [StartTicks], eax
        mov         dword ptr [StartTicks + 4], edx
    //Start test
        mov         eax, 10000
    @Loop:
        dec         eax
        cmp         eax, 0
        jnz         @Loop
    //End test
        rdtsc
        mov         dword ptr [EndTicks], eax
        mov         dword ptr [EndTicks + 4], edx
      end;
      caption := IntToStr(EndTicks - StartTicks);
    end;

    procedure TForm9.ButtonESIClick(Sender: TObject);
    begin
      asm
        rdtsc
        mov         dword ptr [StartTicks], eax
        mov         dword ptr [StartTicks + 4], edx
    //Start test
        mov         esi, 10000
    @Loop:
        dec         esi
        cmp         esi, 0
        jnz         @Loop
    //End test
        rdtsc
        mov         dword ptr [EndTicks], eax
        mov         dword ptr [EndTicks + 4], edx
      end;
      caption := IntToStr(EndTicks - StartTicks);
    end;
</code>```

10000 loops on modern CPU will not produce any difference between execution of rutine with use EAX or ESI.

Title: using ESI slower than EAX?

Body:
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1

jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1

Body:
,Boath pieces of code has more or less the some excecution speed. You can check the execution speed via execution of instruction rdtsc before rutine and after rutine to measure (count) execution CPU clocks. Of course boath rutines must to start with the some value in EAX and ESI register. Do not use a huge loop values becouse the task scheduler can interrupt the current task in the middle of loop execution and you will get wrong result. However if some measiring result deviate a lot than the current task was interrupted by the task scheduler and you must to ignore that result.

EDIT: TESTs

Here I have put both tests, so that everybody can check the results:

var
  StartTicks                :Int64;
  EndTicks                  :Int64;

    procedure TForm9.ButtonEAXClick(Sender: TObject);
    begin
      asm
        rdtsc
        mov         dword ptr [StartTicks], eax
        mov         dword ptr [StartTicks + 4], edx
    //Start test
        mov         eax, 10000
    @Loop:
        dec         eax
        cmp         eax, 0
        jnz         @Loop
    //End test
        rdtsc
        mov         dword ptr [EndTicks], eax
        mov         dword ptr [EndTicks + 4], edx
      end;
      caption := IntToStr(EndTicks - StartTicks);
    end;

    procedure TForm9.ButtonESIClick(Sender: TObject);
    begin
      asm
        rdtsc
        mov         dword ptr [StartTicks], eax
        mov         dword ptr [StartTicks + 4], edx
    //Start test
        mov         esi, 10000
    @Loop:
        dec         esi
        cmp         esi, 0
        jnz         @Loop
    //End test
        rdtsc
        mov         dword ptr [EndTicks], eax
        mov         dword ptr [EndTicks + 4], edx
      end;
      caption := IntToStr(EndTicks - StartTicks);
    end;

10000 loops on modern CPU will not produce any difference between execution of rutine with use EAX or ESI.


问:
Django DateTimeField was messy with naive and aware timestamp field in PostgreSQL
Version:

Django 1.11

PostgreSQL 9.6 (AWS RDS)

Django settings.py:

TIME_ZONE = 'Asia/Seoul'

USE_TZ = False

My Problem:

In last year, My django app migrated database from MySQL to PostgreSQL. It was fine. But I found big trouble.

Tables that was generated in MySQL have DateTimeField, which correspond to naive timestamp field (without timezone) in PostgreSQL. But tables that was generated in PostgreSQL have DateTimeField, which correspond to aware timestamp field (with timezone). It stores all timestamp in UTC.

So My DB tables was messy with naive and aware timestamp field.

How do I fix this issue at best?

The Followings are solutions I think,

Convert naive timestamp fields to aware timestamp fields.
I think It's best practice. But naive timestamp fields are too many. and I'm afraid that I lost data due to converting.

Convert aware timestamp fields to naive timestamp fields.
I think It's one of easy ways. But I heard naive timestamp fields are not practice.

Nothing changed. Actually, I didn't know timestamp field is messy until I examine DB. Djano application has worked well now. But I worry It's big trouble in the future.

Change timezone setting in AWS RDS. Is it possible and solution?

Sorry for my poor english. Please advice.

答:
Convert naive timestamp fields to aware timestamp fields. I think It's best practice. But naive timestamp fields are too many. and I'm afraid that I lost data due to converting.

You're correct, the best result will be to get all the naive values to timezone-aware values. Perhaps you want to ask a new question about the problem that prevents you from doing this?


问:
cannot read property $key of undefined in ionic 2
I am trying to update data in firebase in my ionic2 app and I get this error :
cannot read property '$key' of undefined

.ts

```<code>onValidate(info): void{
  //console.log(info.$key);
  this.infos.update(info.$key,{
    FirstName : info.FirstName,
    LastName : info.LastName
  })
}
</code>```

.html

```<code><button
  ion-button
  type="submit"
  block
  [disabled]="!f.valid"
  (click)="onValidate(info)">Valider</button>
</code>```

in my html I have an *ngFor = "let info of infos | async" ...

Thank you for your help

答:
I assume you are using firebase here. You would never get the $key from angular ngFor as it is not apart of the structural array, because $key is an identifier, not a property in the firebase data structure.

What you can do it push the $key onto the array when you first get it. Although you do not show how you are getting infos i assume it would be something like.

```<code>this.api.get(`mydatabase/infos`).then(infosData => {
     this.infos = infodata;
});
</code>```

In the returned promise you have access to $key which is where you can then push it into the array used in the view.

```<code>this.api.get(`mydatabase/infos`).then(infosData => {
   infosData.forEach((el,idx) => {
        console.log(el.$key);
        // Use the index as you should be pushing onto an object literal
        // Of course this could be different depending how you have
        // structured the data being returned for firebase which is not
        // specified in your question
        infos[idx].push('key') = el.$key;
    });
});
</code>```

Then your array being used in the view for the ngFor will now have a property info.key which you can use as an identifier in your onValidate(info) method.

Body:
I am trying to update data in firebase in my ionic2 app and I get this error :
cannot read property '$key' of undefined

.ts

onValidate(info): void{
  //console.log(info.$key);
  this.infos.update(info.$key,{
    FirstName : info.FirstName,
    LastName : info.LastName
  })
}

.html

<button
  ion-button
  type="submit"
  block
  [disabled]="!f.valid"
  (click)="onValidate(info)">Valider</button>

in my html I have an *ngFor = "let info of infos | async" ...

Thank you for your help

Body:
I assume you are using firebase here. You would never get the $key from angular ngFor as it is not apart of the structural array, because $key is an identifier, not a property in the firebase data structure.

What you can do it push the $key onto the array when you first get it. Although you do not show how you are getting infos i assume it would be something like.

this.api.get(`mydatabase/infos`).then(infosData => {
     this.infos = infodata;
});

In the returned promise you have access to $key which is where you can then push it into the array used in the view.

this.api.get(`mydatabase/infos`).then(infosData => {
   infosData.forEach((el,idx) => {
        console.log(el.$key);
        // Use the index as you should be pushing onto an object literal
        // Of course this could be different depending how you have
        // structured the data being returned for firebase which is not
        // specified in your question
        infos[idx].push('key') = el.$key;
    });
});

Then your array being used in the view for the ngFor will now have a property info.key which you can use as an identifier in your onValidate(info) method.


问:
Making a Database search engine like Google
I'm new to creating websites.I'm creating a Telephone directory search Engine.(Using PostgreSql,CGI scripts).My Database is having Name,Tel.No,City,State,Address.

Upto now I have created a search field like "google" where I can give any of the above Database entries and search.But now I want to give like "name+city+..." So that I can minimize the output entries.

答:
Do you mean you that you want to search all fields? Then:</p>

```<code>SELECT *
FROM table_name
WHERE
Name LIKE '%query%'
OR Tel.No LIKE '%query%'
OR City LIKE '%query%'
OR State LIKE '%query%'
OR Address LIKE '%query%'
</code>```

Body:
Do you mean you that you want to search all fields? Then:

SELECT *
FROM table_name
WHERE
Name LIKE '%query%'
OR Tel.No LIKE '%query%'
OR City LIKE '%query%'
OR State LIKE '%query%'
OR Address LIKE '%query%'


问:
Count level within group_by hierarchy in dplyr
I have a large data set in R that is organised with multiple records from individual cases, nested within groups. A toy example is here:

```<code>d = data.frame(group = rep(c('control','patient'), each = 5), case = c('a', 'a', 'b', 'c', 'c', 'd','d','d','e','e'))
</code>```

If in a dplyr chain, group_by(group, case) is applied, how can a column be created that numbers each row with the order of its case within the group? e.g. in the example below, in the third column, case 'a' is the first case in the control group, and case 'c' the third, but the numbering resets to 1 for case 'd', the first case in the patient group.

```<code>  group case  number
control  a    1
control  a    1
control  b    2
control  c    3
control  c    3
patient  d    1
patient  d    1
patient  d    1
patient  e    2
patient  e    2
</code>```

I can see how this would be done by counting cases using a 'for' loop, but am wondering if there is a way to achieve this within a standard dplyr-style chain of operations?

答:
One solution would be:</p>

```<code>library(dplyr)
library(tibble)

want<-left_join(d,
                d %>%
                  distinct(case) %>%
                  rownames_to_column(var="number") ,
                by="case")

# .. added later:
want2<-left_join(d,
                 bind_rows(
                   d %>%
                     filter(group=="control") %>%
                     distinct(case) %>%
                     rownames_to_column(var="number"),
                   d %>%
                     filter(group=="patient") %>%
                     distinct(case) %>%
                     rownames_to_column(var="number")),
                   by="case")

# I think this is less readable:
want3<-left_join(d,
                 bind_rows(by(d,d$group,function(x) x %>%
                                distinct(case) %>%
                                rownames_to_column(var="number"))),
                 by="case")
</code>```

Body:
I have a large data set in R that is organised with multiple records from individual cases, nested within groups. A toy example is here:

d = data.frame(group = rep(c('control','patient'), each = 5), case = c('a', 'a', 'b', 'c', 'c', 'd','d','d','e','e'))

If in a dplyr chain, group_by(group, case) is applied, how can a column be created that numbers each row with the order of its case within the group? e.g. in the example below, in the third column, case 'a' is the first case in the control group, and case 'c' the third, but the numbering resets to 1 for case 'd', the first case in the patient group.

  group case  number
control  a    1
control  a    1
control  b    2
control  c    3
control  c    3
patient  d    1
patient  d    1
patient  d    1
patient  e    2
patient  e    2

I can see how this would be done by counting cases using a 'for' loop, but am wondering if there is a way to achieve this within a standard dplyr-style chain of operations?

Body:
One solution would be:

library(dplyr)
library(tibble)

want<-left_join(d,
                d %>%
                  distinct(case) %>%
                  rownames_to_column(var="number") ,
                by="case")

# .. added later:
want2<-left_join(d,
                 bind_rows(
                   d %>%
                     filter(group=="control") %>%
                     distinct(case) %>%
                     rownames_to_column(var="number"),
                   d %>%
                     filter(group=="patient") %>%
                     distinct(case) %>%
                     rownames_to_column(var="number")),
                   by="case")

# I think this is less readable:
want3<-left_join(d,
                 bind_rows(by(d,d$group,function(x) x %>%
                                distinct(case) %>%
                                rownames_to_column(var="number"))),
                 by="case")


Title: Efficient search

Body:
I have written the following code

a<-matrix(0,1,nrow = nrow(x))
for(i in 1:nrow(x)){
  for(j in 1:nrow(y)){
   if((y[j,3] > x[i,2]) & (y[j,2] == x[i,1])){
     a[i,]<- y[j,4]
     i<- i+1
   }
  }

x looks something like:

x1  x2
401 4
401 38
401 142...

and y looks like

 y1 y2   y3    y4
  1 401 10  22.152
  2 401 40  167.986
  3 401 70  393.198
  4 401 100 923
  5 401 120 923
  6 401 140 686.712
  7 401 160 865.774...

I want a to be:

22.152
167.986
865.774...

where nrow(y) > nrow(x) is TRUE. Is it possible to make this more efficient?

Body:
We can merge then filter, using dplyr

library(dplyr)

left_join(x, y, by = c("x1" = "y2")) %>%
  filter(y3 > x2) %>%
  arrange(y3) %>%
  group_by(x1, x2) %>%
  slice(1)

# Source: local data frame [3 x 5]
# Groups: x1, x2 [3]
#
#      x1    x2    y1    y3      y4
#   <int> <int> <int> <int>   <dbl>
# 1   401     4     1    10  22.152
# 2   401    38     2    40 167.986
# 3   401   142     7   160 865.774

data

x <- read.table(text = "
  x1  x2
401 4
401 38
401 142", header = TRUE)

y <- read.table(text = "
y1 y2   y3    y4
1 401 10  22.152
2 401 40  167.986
3 401 70  393.198
4 401 100 923
5 401 120 923
6 401 140 686.712
7 401 160 865.774", header = TRUE)


问:
How to avoid NPE when no values is specified for Spring JPA criteria
I have a Spring JPA search criteria like below. Where area is an Integer. </p>

```<code>cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
</code>```

<p>The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.  </p>

答:
If both values can be null I'd suggest splitting the between query into two predicates and then combining them. This way you can also handle the case when both  of them are null:

```<code>List<Predicate> predicates = new ArrayList<>();
if (searchConstraint.getAreaMin() != null)
    predicates.add(cb.gt(root.get(Property_.area), searchConstraint.getAreaMin()))
if (searchConstraint.getAreaMax() != null)
    predicates.add(cb.lt(root.get(Property_.area), searchConstraint.getAreaMax()))
if (predicates.size() > 0)
    cb.and(predicates.toArray(new Predicate[predicates.size()]))
</code>```

Body:
I have a Spring JPA search criteria like below. Where area is an Integer.

cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())

The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.

Body:
If both values can be null I'd suggest splitting the between query into two predicates and then combining them. This way you can also handle the case when both  of them are null:

List<Predicate> predicates = new ArrayList<>();
if (searchConstraint.getAreaMin() != null)
    predicates.add(cb.gt(root.get(Property_.area), searchConstraint.getAreaMin()))
if (searchConstraint.getAreaMax() != null)
    predicates.add(cb.lt(root.get(Property_.area), searchConstraint.getAreaMax()))
if (predicates.size() > 0)
    cb.and(predicates.toArray(new Predicate[predicates.size()]))


问:
How to change background color in single ZK Grid Cells?
Anyone got any idea how to change the background color of a cell in a ZK grid? Been searching the web for several hours and can't find much. A static cell wouldn't be a problem, but this is a dynamically rendered grid.

Plan is to colour certain cells red or yellow because I want to highlight that specific value.

My Zul:

```<code><?page title="Ergebnis des Clusterings" contentType="text/html;charset=UTF-8"?>
<zk xmlns:n="native" xmlns:c="client">
    <style>body { background-color: #fcfcfc; }</style>
    <image id="image" src="http://i.imgur.com/dL3ahNV.gif"
        style="display: block; width: 300px; margin: 1% auto 0 auto;">
    </image>
    <window id="win" apply="org.zkoss.bind.BindComposer"
        style="margin: 0 auto; background: #ddf4ea; position: relative;"
        viewModel="@id('vm') @init('frontend.ClusteringOutputVM')"
        border="normal" width="1000px" position="center,top"
        mode="embedded">
        <caption label="KaufDort Cluster - Clustering Output"
            style="font-family: Segoe UI; font-style: normal; font-size: 18px; color: #000000; padding: 5px;" />
        <include style="margin-top: 20px; margin-bottom: 20px;"
            src="marketing.zul" />
        <hbox>
            <grid id="grid" model="@load(vm.mapModel)" hflex="max">
                <columns children="@load(vm.columnsModel)">
                    <template name="children">
                        <column hflex="min" label="@load(each)"
                            sort="none"
                            style="background: #ddf4ea; font-family: Segoe UI; font-style: normal; font-size: 18px; color: #000000; font-weight: normal;" />
                    </template>
                </columns>
                <template name="model" var="cur_row">
                    <row
                        children="@load(vm.columnsModel) @template(forEachStatus.index lt (vm.columnsModel.size()- cur_row.value.size()) ? 'fixed' : 'variable')">
                        <template name="fixed">
                            <cell>
                                <button label="@load(cur_row.key)"
                                    style="border: none; border-radius: 0px; background: #7f8c8d; color: white; text-shadow: none; font-size: 18px;"
                                    onClick="@command('showDiagram')" width="100%" />
                            </cell>
                        </template>

                        <template name="variable">
                            <cell>
                                <label
                                    style="text-align: left; font-family: Segoe UI; font-style: normal; font-size: 14px; color: #000000;"
                                    value="@load(cur_row.value[forEachStatus.index- vm.columnsModel.size()+ cur_row.value.size()])" />
                            </cell>
                        </template>
                    </row>
                </template>
            </grid>

            <image id="questionmark" src="Files/QuestionmarkButton.png"
                tooltip="centroid" style="cursor: help" />

        </hbox>
    </window>
    <popup id="centroid" width="300px">
        <html>
            <![CDATA[ Text]]>
        </html>
    </popup>
</zk>
</code>```

My VM:

```<code>public class ClusteringOutputVM {

    private ArrayList<KMeansCluster> clusterList;
    private ArrayList<Feature> featureList;
    private int numOfClusters;
    private ListModelMap data;
    private ListModel columns_model;
    private boolean[][] paintMe;
    @Wire
    private Grid grid;

    public ClusteringOutputVM() {

        data = new ListModelMap();
        columns_model = new ListModelList();

        getSessionGlobalVariables();
        transferDataToListModelMap();
        fillColumnsModel(numOfClusters);
    }

    @AfterCompose
    public void paintCells() {
        for (int i = 0; i < paintMe.length; i++) {
            for (int j = 0; j < paintMe[i].length; j++) {
                if(paintMe[i][j]){
                    grid.getCell(i, j); ?????
                }
            }
        }
    }

    private void transferDataToListModelMap() {
        List<String> valueList = new java.util.ArrayList<String>();
        int featureType = 0;

        for (int i = 0; i < featureList.size(); i++) {
            featureType = featureList.get(i).getFeatureType();
            if (featureType == 0) {
                NumericFeature nf = (NumericFeature) featureList.get(i);
                double mean = nf.getMean();
                double stDev = nf.getStdDev();

                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    String centroidVal = in.toString(i);
                    double value = Double.valueOf(centroidVal);
                    if (value > (mean + stDev) || value < (mean - stDev)) {
                        paintMe[i+1][j+1] = true;
                    }
                    valueList.add(centroidVal);

                }
            } else {
                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    paintMe[i+1][j+1] = false;
                    valueList.add(in.toString(i));
                }

                data.put((featureList.get(i).getFeatureName()), valueList);
                valueList = new ArrayList<String>();
            }
        }

    }

    private void getSessionGlobalVariables() {
        clusterList = (ArrayList<KMeansCluster>) Sessions.getCurrent()
                .getAttribute("finalClusterList");
        featureList = (ArrayList<Feature>) Sessions.getCurrent().getAttribute(
                "finalFeatureList");
        numOfClusters = (int) Sessions.getCurrent().getAttribute(
                "chosenNumOfClusters");
        paintMe = new boolean[featureList.size() + 1][clusterList.size() + 1];
    }

    private void fillColumnsModel(int endValue) {
        ((List) columns_model).add(new String("Feature"));
        for (int i = 1; i <= endValue; ++i)
            ((List) columns_model).add(new String("Cluster " + i));

    }

    public ListModel getColumnsModel() {
        return columns_model;
    }

    public ListModel getMapModel() {
        return data;
    }

    @Command
    public void showDiagram(
            @ContextParam(ContextType.COMPONENT) Component component) {

        Button b = (Button) component;
        String featureChosen = b.getLabel();
        Feature feat = null;
        for (int i = 0; i < featureList.size(); i++) {
            if (featureList.get(i).getFeatureName().equals(featureChosen)) {
                feat = featureList.get(i);
            }
        }
        Sessions.getCurrent().setAttribute("chosenFeature", feat);

        if (feat.getFeatureType() != 0)
            // koennte problematisch werden bei anderen Browsern
            Executions.getCurrent().sendRedirect("stackedColumns.zul");
        else
            Executions.getCurrent().sendRedirect("boxplot.zul");

    }

}
</code>```

答:
First of all,

You are in MVVM so @Wire will not work unless to wire the selectors.

I specific don't say how to do it because it's bad practice to do.

Just work MVVM :

```<code><cell style="@load(each.condition?'some style':'some other style')"/>
</code>```

If you can't acces that, you can always make a wrapper class what contains all the value's in stead of the Boolean[][] separated.

Body:
Anyone got any idea how to change the background color of a cell in a ZK grid? Been searching the web for several hours and can't find much. A static cell wouldn't be a problem, but this is a dynamically rendered grid.

Plan is to colour certain cells red or yellow because I want to highlight that specific value.

My Zul:

<?page title="Ergebnis des Clusterings" contentType="text/html;charset=UTF-8"?>
<zk xmlns:n="native" xmlns:c="client">

    <image id="image" src="http://i.imgur.com/dL3ahNV.gif"
        style="display: block; width: 300px; margin: 1% auto 0 auto;">
    </image>
    <window id="win" apply="org.zkoss.bind.BindComposer"
        style="margin: 0 auto; background: #ddf4ea; position: relative;"
        viewModel="@id('vm') @init('frontend.ClusteringOutputVM')"
        border="normal" width="1000px" position="center,top"
        mode="embedded">

        <include style="margin-top: 20px; margin-bottom: 20px;"
            src="marketing.zul" />
        <hbox>
            <grid id="grid" model="@load(vm.mapModel)" hflex="max">
                <columns children="@load(vm.columnsModel)">
                    <template name="children">
                        <column hflex="min" label="@load(each)"
                            sort="none"
                            style="background: #ddf4ea; font-family: Segoe UI; font-style: normal; font-size: 18px; color: #000000; font-weight: normal;" />
                    </template>
                </columns>
                <template name="model" var="cur_row">
                    <row
                        children="@load(vm.columnsModel) @template(forEachStatus.index lt (vm.columnsModel.size()- cur_row.value.size()) ? 'fixed' : 'variable')">
                        <template name="fixed">
                            <cell>
                                <button label="@load(cur_row.key)"
                                    style="border: none; border-radius: 0px; background: #7f8c8d; color: white; text-shadow: none; font-size: 18px;"
                                    onClick="@command('showDiagram')" width="100%" />
                            </cell>
                        </template>

                        <template name="variable">
                            <cell>

                            </cell>
                        </template>
                    </row>
                </template>
            </grid>

            <image id="questionmark" src="Files/QuestionmarkButton.png"
                tooltip="centroid" style="cursor: help" />

        </hbox>
    </window>
    <popup id="centroid" width="300px">

            <![CDATA[ Text]]>

    </popup>
</zk>

My VM:

public class ClusteringOutputVM {

    private ArrayList<KMeansCluster> clusterList;
    private ArrayList<Feature> featureList;
    private int numOfClusters;
    private ListModelMap data;
    private ListModel columns_model;
    private boolean[][] paintMe;
    @Wire
    private Grid grid;

    public ClusteringOutputVM() {

        data = new ListModelMap();
        columns_model = new ListModelList();

        getSessionGlobalVariables();
        transferDataToListModelMap();
        fillColumnsModel(numOfClusters);
    }

    @AfterCompose
    public void paintCells() {
        for (int i = 0; i < paintMe.length; i++) {
            for (int j = 0; j < paintMe[i].length; j++) {
                if(paintMe[i][j]){
                    grid.getCell(i, j); ?????
                }
            }
        }
    }

    private void transferDataToListModelMap() {
        List<String> valueList = new java.util.ArrayList<String>();
        int featureType = 0;

        for (int i = 0; i < featureList.size(); i++) {
            featureType = featureList.get(i).getFeatureType();
            if (featureType == 0) {
                NumericFeature nf = (NumericFeature) featureList.get(i);
                double mean = nf.getMean();
                double stDev = nf.getStdDev();

                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    String centroidVal = in.toString(i);
                    double value = Double.valueOf(centroidVal);
                    if (value > (mean + stDev) || value < (mean - stDev)) {
                        paintMe[i+1][j+1] = true;
                    }
                    valueList.add(centroidVal);

                }
            } else {
                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    paintMe[i+1][j+1] = false;
                    valueList.add(in.toString(i));
                }

                data.put((featureList.get(i).getFeatureName()), valueList);
                valueList = new ArrayList<String>();
            }
        }

    }

    private void getSessionGlobalVariables() {
        clusterList = (ArrayList<KMeansCluster>) Sessions.getCurrent()
                .getAttribute("finalClusterList");
        featureList = (ArrayList<Feature>) Sessions.getCurrent().getAttribute(
                "finalFeatureList");
        numOfClusters = (int) Sessions.getCurrent().getAttribute(
                "chosenNumOfClusters");
        paintMe = new boolean[featureList.size() + 1][clusterList.size() + 1];
    }

    private void fillColumnsModel(int endValue) {
        ((List) columns_model).add(new String("Feature"));
        for (int i = 1; i <= endValue; ++i)
            ((List) columns_model).add(new String("Cluster " + i));

    }

    public ListModel getColumnsModel() {
        return columns_model;
    }

    public ListModel getMapModel() {
        return data;
    }

    @Command
    public void showDiagram(
            @ContextParam(ContextType.COMPONENT) Component component) {

        Button b = (Button) component;
        String featureChosen = b.getLabel();
        Feature feat = null;
        for (int i = 0; i < featureList.size(); i++) {
            if (featureList.get(i).getFeatureName().equals(featureChosen)) {
                feat = featureList.get(i);
            }
        }
        Sessions.getCurrent().setAttribute("chosenFeature", feat);

        if (feat.getFeatureType() != 0)
            // koennte problematisch werden bei anderen Browsern
            Executions.getCurrent().sendRedirect("stackedColumns.zul");
        else
            Executions.getCurrent().sendRedirect("boxplot.zul");

    }

}

Body:
First of all,

You are in MVVM so @Wire will not work unless to wire the selectors.

I specific don't say how to do it because it's bad practice to do.

Just work MVVM :

<cell style="@load(each.condition?'some style':'some other style')"/>

If you can't acces that, you can always make a wrapper class what contains all the value's in stead of the Boolean[][] separated.


问:
Can not render value with Vuejs, but console log work fine
I getting started with VueJS and must say it works amazing, though trying the Vue-Resource implementation, does only work half the time.

When pulling data from my server, it seems like it wont finalize the data.

An example is the following code, where in I have loaded a request from my server, but it will only load half the data.

The response I am trying to insert into the parser, looks like this.

[{ city: "New York", amount: 8 }, { city: "San Francisco", amount: 18 }]

The issue is when I am logging it to the console it works fine, but rendering removes the amount. Never the city, only the amount from each location.

Can anybody tell me how this happens. I can only find solutions from Vue.js 0.9, but I am using Vue.js 2.3.3 and Vue-resource 1.3.3.

```<code>vm = new Vue({
el: '#devApp',
data: {
    citiesCount: [],
},
mounted: function()
{
    this.getLocationsCityCount();
    this.getLatestLocations();
},
methods: {
    getLocationsCityCount: function(cb)
    {
        var test = this.$http.get('/api/v1/locations/count/cities').then(
            success => {
                console.log(success.body.response);
                this.citiesCount = success.body.response;
            },
            error => {
                console.log('error');
                console.log(error);
            }
        );
    },
}
</code>```

});

答:
the @ @{{ data }} sign is only needed in laravel blade.

and yes you just need to loop through your data to display everyone of it

here's a working sample.

https://jsfiddle.net/khenxi/djcner34/

Body:
I getting started with VueJS and must say it works amazing, though trying the Vue-Resource implementation, does only work half the time.

When pulling data from my server, it seems like it wont finalize the data.

An example is the following code, where in I have loaded a request from my server, but it will only load half the data.

The response I am trying to insert into the parser, looks like this.

[{ city: "New York", amount: 8 }, { city: "San Francisco", amount: 18 }]

The issue is when I am logging it to the console it works fine, but rendering removes the amount. Never the city, only the amount from each location.

Can anybody tell me how this happens. I can only find solutions from Vue.js 0.9, but I am using Vue.js 2.3.3 and Vue-resource 1.3.3.

vm = new Vue({
el: '#devApp',
data: {
    citiesCount: [],
},
mounted: function()
{
    this.getLocationsCityCount();
    this.getLatestLocations();
},
methods: {
    getLocationsCityCount: function(cb)
    {
        var test = this.$http.get('/api/v1/locations/count/cities').then(
            success => {
                console.log(success.body.response);
                this.citiesCount = success.body.response;
            },
            error => {
                console.log('error');
                console.log(error);
            }
        );
    },
}

});


问:
Logger for Unity3d that hooks up nicely with MonoDevelop
I want to write a central logger class for Unity3d project. Its pretty straight-forward if I were to print the console logs only. I would want it to look something like the following :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Consider this class is a Singleton, and is available to all other classes.
//I'm leaving the generic inheritance from something like Singleton<Logger> for simplicity

public class Logger : MonoBehaviour
{
    public enum LogLevel
    {
        Verbose,
        Debug,
        Warn,
        Error
    }

    public bool _enableLogs;

    public LogLevel _logLevel;

    public void Log(LogLevel logType, string msg)
    {
        if (!_enableLogs)
            return;

        // some logic to filter out messages below this "_logLevel".

        // Log the msg to console.
        Debug.Log (msg);
    }
}
</code>```

Normally when you double click a log message, it takes you to that line of code in the MonoDevelop file. How can I modify my code so that it links with the line of code producing it, like in a normal logger? Any help is greatly appreciated.

答:
Filter by LogType, parse logs stack trace and switch to editor if source code file found. It is an Editor loaded class, so it works only there of course.</p>

```<code>using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class ExceptionCatcher
{
    private static readonly Regex StackTraceRegex = new Regex(@"\(at (.*):([0-9]+)\)");

    static ExceptionCatcher()
    {
        // Handle logs
        Application.logMessageReceived += OnLogMessageReceived;
    }

    private static void OnLogMessageReceived(string condition, string stackTrace, LogType type)
    {
        // Check if stack trace has file name and line number
        var matches = StackTraceRegex.Matches(stackTrace);
        foreach (Match match in matches)
        {
            // Get full path file name or VS will open new window
            string filePath = Path.GetDirectoryName(Application.dataPath) + "/" + match.Groups[1].Value;
            int lineNumber = Convert.ToInt32(match.Groups[2].Value);

            // If file exists
            if (File.Exists(filePath))
            {
                // Pause editor
                Debug.Break();

                // Switch to code editor
                UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(filePath, lineNumber);
                break;
            }
        }
    }
}
</code>```

Body:
I want to write a central logger class for Unity3d project. Its pretty straight-forward if I were to print the console logs only. I would want it to look something like the following :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Consider this class is a Singleton, and is available to all other classes.
//I'm leaving the generic inheritance from something like Singleton<Logger> for simplicity

public class Logger : MonoBehaviour
{
    public enum LogLevel
    {
        Verbose,
        Debug,
        Warn,
        Error
    }

    public bool _enableLogs;

    public LogLevel _logLevel;

    public void Log(LogLevel logType, string msg)
    {
        if (!_enableLogs)
            return;

        // some logic to filter out messages below this "_logLevel".

        // Log the msg to console.
        Debug.Log (msg);
    }
}

Normally when you double click a log message, it takes you to that line of code in the MonoDevelop file. How can I modify my code so that it links with the line of code producing it, like in a normal logger? Any help is greatly appreciated.

Body:
Filter by LogType, parse logs stack trace and switch to editor if source code file found. It is an Editor loaded class, so it works only there of course.

using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class ExceptionCatcher
{
    private static readonly Regex StackTraceRegex = new Regex(@"\(at (.*):([0-9]+)\)");

    static ExceptionCatcher()
    {
        // Handle logs
        Application.logMessageReceived += OnLogMessageReceived;
    }

    private static void OnLogMessageReceived(string condition, string stackTrace, LogType type)
    {
        // Check if stack trace has file name and line number
        var matches = StackTraceRegex.Matches(stackTrace);
        foreach (Match match in matches)
        {
            // Get full path file name or VS will open new window
            string filePath = Path.GetDirectoryName(Application.dataPath) + "/" + match.Groups[1].Value;
            int lineNumber = Convert.ToInt32(match.Groups[2].Value);

            // If file exists
            if (File.Exists(filePath))
            {
                // Pause editor
                Debug.Break();

                // Switch to code editor
                UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(filePath, lineNumber);
                break;
            }
        }
    }
}


问:
C++ Partial Template Specialization: Member Functions
I have a template

```<code>template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething();
};
</code>```

which i would like to partially specialize for two special cases of b:

```<code>template<int a>
void MyTemplateClass<a, 2> :: computeSomething()
{
    // Special case for b=2 here
}

template<int a>
void MyTemplateClass<a, 3> :: computeSomething()
{
    // Special case for b=3 here
}
</code>```

However, as far as i know, partial specialization is invalid for member functions. How can i achieve what i want? Is there any other solution? Thank you!

答:
Since the typename of template is known, you can add some implement in computeSomething function, to branch the flow, like this:

```<code>template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething()
    {
        if (b == 2) { computeWith2(); }
        else if (b == 3) { computeWith3(); }
        else { computerNormally(); }
    };
}
</code>```

Body:
I have a template

template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething();
};

which i would like to partially specialize for two special cases of b:

template<int a>
void MyTemplateClass :: computeSomething()
{
    // Special case for b=2 here
}

template<int a>
void MyTemplateClass :: computeSomething()
{
    // Special case for b=3 here
}

However, as far as i know, partial specialization is invalid for member functions. How can i achieve what i want? Is there any other solution? Thank you!

Body:
Since the typename of template is known, you can add some implement in computeSomething function, to branch the flow, like this:

template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething()
    {
        if (b == 2) { computeWith2(); }
        else if (b == 3) { computeWith3(); }
        else { computerNormally(); }
    };
}


问:
How to delete using sparql
I fear this is simple question . . . could someone tell me what the sparql is to delete all of a particular type of resource? Not just an individual triple but an entire set of resources.

thank you

答:
Sounds like you want to delete all triples of resources having some class. Try this

delete {?s ?p ?o}
where {?s a :ClassToDelete; ?p ?o}

Title: How to delete using sparql