问:
Add custom html after the last child of my list using javascript
I'm trying to use javascript to add a custom div after my last child of a unordered list, the result should basically look like this.

```<code><ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <div>custom div</div>
<ul>
</code>```

I am getting this far, but don't know if it's close to be the right solution.
I cant get it to work

```<code>$( document ).ready(function() {
document.getElementByClassName("myList").lastChild.innerHTML = "<h1>test</h1>";
}
</code>```

答:
You can use jquery and append the div though this is not a valid markup.append() dynamically add child element.

$(function(){
  //this is valid child of

  $('.mylist').append('
custom content 1

custom content 2
');

  //this is invalid markup but you asked for though
  $('.mylist').append('
 custom content 1

 custom content 2
');
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
<ul></code>```

Body:
I'm trying to use javascript to add a custom div after my last child of a unordered list, the result should basically look like this.

 content

 content

 content

 content

custom div

I am getting this far, but don't know if it's close to be the right solution.
I cant get it to work

$( document ).ready(function() {
document.getElementByClassName("myList").lastChild.innerHTML = "
test
";
}

Body:
You can use jquery and append the div though this is not a valid markup.append() dynamically add child element.

$(function(){
  //this is valid child of <ul>
  $('.mylist').append('<li>custom content 1</li><li>custom content 2</li>');

  //this is invalid markup but you asked for though
  $('.mylist').append('<div> custom content 1 </div><div> custom content 2</div>');
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="mylist">
 <li> content </li>
 <li> content </li>
 <li> content </li>
 <li> content </li>
<ul>


来源: stackexchange

问:
Google Places Search Results
I am using google's places API to search for certain outlets.

Taking the outlet called 'Sangkaya' as an example (note: Sangkaya is an ice cream franchise), when I enter the following query, 8 Sangkaya outlets are returned.

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=3.081213,101.5844108&radius=50000&type=store&keyword=sangkaya&key=YourAPIKey

In the above query, I have passed 'store' to the type parameter, and 'sangkaya' to the keyword parameter.

However, when I use this next query, where I still pass 'store' to the type parameter, but without passing 'sangkaya' to the keyword parameter, the query results do not contain any Sangkaya outlets:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=3.081213,101.5844108&radius=50000&type=store&key=YourAPIKey

The values contained in the 'types' key for each outlet contains the value 'store'.

My question here is, why arent the 8 Sangkaya outlets being returned in the second query?

答:
Your second query does not return Sangkaya outlets because it has no reason to return them, it just returns "stores" within 50 km of 3.081213,101.5844108 without any preference in particular.

If you want to find the nearest results, use rankby=distance with either types or keyword, and beware the maximum radius is 7000 m.

ContentLicense: CC BY-SA 3.0

Title: Google Places Search Results


问:
Getting text in python scrapy
I get this code from a website:

```<code>import scrapy

class BrickSetSpider(scrapy.Spider):
    name = "brickset_spider"
    start_urls = ['http://brickset.com/sets/year-2016']

    def parse(self, response):
        SET_SELECTOR = '.set'
        for brickset in response.css(SET_SELECTOR):

            NAME_SELECTOR = 'h1 a ::text'
            yield {
                'name': brickset.css(NAME_SELECTOR).extract(),
            }
</code>```

I use the code for crawling data. This is a sample result when I run the code:

The name is the result of extract() method. This is the inspect element (in chrome):

I want to ask about the way to get the result for name is 10805: Around the World or only Around the World. How to do that?

答:
To get "10805: Around the World" change your yield to:

```<code> yield {
            'name': " ".join(brickset.css(NAME_SELECTOR).extract()),
        }
</code>```

To get "Around the World" change your yield to:

```<code>yield {
            'name': brickset.css(NAME_SELECTOR).extract()[-1],
        }
</code>```

Title: Getting text in python scrapy

Body:
I get this code from a website:

import scrapy

class BrickSetSpider(scrapy.Spider):
    name = "brickset_spider"
    start_urls = ['http://brickset.com/sets/year-2016']

    def parse(self, response):
        SET_SELECTOR = '.set'
        for brickset in response.css(SET_SELECTOR):

            NAME_SELECTOR = 'h1 a ::text'
            yield {
                'name': brickset.css(NAME_SELECTOR).extract(),
            }

I use the code for crawling data. This is a sample result when I run the code:

The name is the result of extract() method. This is the inspect element (in chrome):

I want to ask about the way to get the result for name is 10805: Around the World or only Around the World. How to do that?

Body:
To get "10805: Around the World" change your yield to:

 yield {
            'name': " ".join(brickset.css(NAME_SELECTOR).extract()),
        }

To get "Around the World" change your yield to:

yield {
            'name': brickset.css(NAME_SELECTOR).extract()[-1],
        }


问:
Prolog print out 2 dimension table
i have  a square with start and finish points, also places where i can't go. And my program must find a way to reach finish:

```<code>ar_galima([], _, _):-!.
ar_galima([Prad|Galas],Kelias, X) :- not(Prad == X), not(member(X, Kelias)), ar_galima(Galas, Kelias, X).

gener(Stac_M, Stac_K, k(A,B), k(Y,B)) :-  Y is A + 1, Y > 0, Y =< Stac_M, B =< Stac_K.
gener(Stac_M, Stac_K, k(A,B), k(Y,B)) :-  Y is A - 1, Y > 0, Y =< Stac_M, B =< Stac_K.
gener(Stac_M, Stac_K, k(A,B), k(A,Y)) :-  Y is B + 1, Y > 0, Y =< Stac_K, A =< Stac_M.
gener(Stac_M, Stac_K, k(A,B), k(A,Y)) :-  Y is B - 1, Y > 0, Y =< Stac_K, A =< Stac_M.

paieska(_, _,_,Tikslas,Tikslas,[], _):-!.
paieska(Stac_M, Stac_K, Draudziama, Prad, Tikslas, [K|Kelias], Kelias2) :-
      gener(Stac_M, Stac_K, Prad, K), ar_galima(Draudziama, Kelias2, K),
      paieska(Stac_M, Stac_K, Draudziama, K, Tikslas, Kelias, [K|Kelias2]).

trasa(Ilgis, Aukstis, Draudziama, k(X,Y), Tikslas, Kelias) :-
      paieska(Ilgis,Aukstis, Draudziama, k(X,Y), Tikslas,Kelias, []).
</code>```

i find routes to finish and now i'm stuck outputing the route (a list) into 2 dimension table in terminal (well, a simple graphic show of the route).

example of list to output:X = [k(2, 1), k(3, 1), k(4, 1), k(4, 2), k(4, 3), k(4, 4)] ;

Could someone suggesst me how should i output a 2 dimension table into terminal?

EDIT:

X should be printed:

```<code> + + + *
 + + + *
 + + + *
 + * * *
</code>```

print perdicate could look like this:

printTable(N, M, X) :- ...

where N is number of rows, M is number of columns and X is list of coordinates.

答:
You can do it with something like this:</p>

```<code>print_table(H, W, L):-
  succ(W, W1),
  print_table(4, 1, H, W1, L).

print_table(1, W, _, W, _):- !.
print_table(Y, W, H, W, L):-
  succ(NY, Y),
  nl,
  !,
  print_table(NY, 1, H, W, L).
print_table(Y, X, H, W, L):-
  (member(k(X, Y), L)->C='* ';C='+ '),
  write(C),
  succ(X, NX),
  !,
  print_table(Y, NX, H, W, L).
</code>```

ContentLicense: CC BY-SA 2.5

Title: Prolog print out 2 dimension table

Body:
i have  a square with start and finish points, also places where i can't go. And my program must find a way to reach finish:

ar_galima([], _, _):-!.
ar_galima([Prad|Galas],Kelias, X) :- not(Prad == X), not(member(X, Kelias)), ar_galima(Galas, Kelias, X).

gener(Stac_M, Stac_K, k(A,B), k(Y,B)) :-  Y is A + 1, Y > 0, Y =< Stac_M, B =< Stac_K.
gener(Stac_M, Stac_K, k(A,B), k(Y,B)) :-  Y is A - 1, Y > 0, Y =< Stac_M, B =< Stac_K.
gener(Stac_M, Stac_K, k(A,B), k(A,Y)) :-  Y is B + 1, Y > 0, Y =< Stac_K, A =< Stac_M.
gener(Stac_M, Stac_K, k(A,B), k(A,Y)) :-  Y is B - 1, Y > 0, Y =< Stac_K, A =< Stac_M.

paieska(_, _,_,Tikslas,Tikslas,[], _):-!.
paieska(Stac_M, Stac_K, Draudziama, Prad, Tikslas, [K|Kelias], Kelias2) :-
      gener(Stac_M, Stac_K, Prad, K), ar_galima(Draudziama, Kelias2, K),
      paieska(Stac_M, Stac_K, Draudziama, K, Tikslas, Kelias, [K|Kelias2]).

trasa(Ilgis, Aukstis, Draudziama, k(X,Y), Tikslas, Kelias) :-
      paieska(Ilgis,Aukstis, Draudziama, k(X,Y), Tikslas,Kelias, []).

i find routes to finish and now i'm stuck outputing the route (a list) into 2 dimension table in terminal (well, a simple graphic show of the route).

example of list to output:X = [k(2, 1), k(3, 1), k(4, 1), k(4, 2), k(4, 3), k(4, 4)] ;

Could someone suggesst me how should i output a 2 dimension table into terminal?

EDIT:

X should be printed:

 + + + *
 + + + *
 + + + *
 + * * *

print perdicate could look like this:

printTable(N, M, X) :- ...

where N is number of rows, M is number of columns and X is list of coordinates.

Body:
You can do it with something like this:

print_table(H, W, L):-
  succ(W, W1),
  print_table(4, 1, H, W1, L).

print_table(1, W, _, W, _):- !.
print_table(Y, W, H, W, L):-
  succ(NY, Y),
  nl,
  !,
  print_table(NY, 1, H, W, L).
print_table(Y, X, H, W, L):-
  (member(k(X, Y), L)->C='* ';C='+ '),
  write(C),
  succ(X, NX),
  !,
  print_table(Y, NX, H, W, L).


问:
Android studio how search into database using multiple words
After i split the sentence into each words (ex. im a boy (im a boy)). now im thinking now if  i can use those splitted words to search the words to my database?

Now idont have any codes , And i dont knwo how to do , can you guys give some hints how i can make it possible?

答:
According to your comment you are going to use SQL lite . So you can use the "LIKE" option to search.

Sample Query

```<code>Select * from table where
  columnname like'%David%' and
  columnname like '%Moses%' and columnname like'%Robi%'
</code>```

Hope it will help you...

Body:
According to your comment you are going to use SQL lite . So you can use the "LIKE" option to search.

Sample Query

Select * from table where
  columnname like'%David%' and
  columnname like '%Moses%' and columnname like'%Robi%'

Hope it will help you...


问:
2006 xaml schemas no longer accessible
i'm currently working on a legacy application using WPF. i downloaded it from our git but when building the project i'm getting the following errors.

```<code>The tag 'Ribbon' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon'.

The property 'KeyTipService.KeyTip' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'.
</code>```

i tried looking in for the links described, but they both fail with a 404
so what am i doing wrong?

答:
If you are targeting .NET Framework 4.5 or later, you should add a reference to System.Windows.Controls.Ribbon.dll.

You will find it under Project->Add Reference->Framework->Assemblies in Visual Studio.

Title: 2006 xaml schemas no longer accessible

Body:
i'm currently working on a legacy application using WPF. i downloaded it from our git but when building the project i'm getting the following errors.

The tag 'Ribbon' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon'.

The property 'KeyTipService.KeyTip' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'.

i tried looking in for the links described, but they both fail with a 404
so what am i doing wrong?


问:
Dependent javascript object properties
How can I do something like this in javascript?

```<code>obj = {
    prop1 = 0;
    prop2 = 0;
    prop3 = prop1 + prop2;
}
</code>```

So when obj.prop1 is updated so will obj.prop3 automatically.

答:
Try to make prop3 getter/setter, see example

var obj = {
    prop1: 1,
    prop2: 4,
    get prop3() {
      return this.prop1 + this.prop2;
    }
};

console.log(obj.prop3);
obj.prop1 = 6;
console.log(obj.prop3);```

Title: Dependent javascript object properties

Body:
How can I do something like this in javascript?

obj = {
    prop1 = 0;
    prop2 = 0;
    prop3 = prop1 + prop2;
}

So when obj.prop1 is updated so will obj.prop3 automatically.


问:
Laravel 5.2 proper foreach syntax
what is the difference between the following syntax ?

```<code>foreach($products as $product) {
// loop body
}
</code>```

and

```<code>foreach($product as $product) {
 //loop body
}
</code>```

got error some time when second one is used.
Thanks

答:
This syntax is wrong

```<code> foreach($product as $product) {
 //loop body
 }
</code>```

As we loop through the $products and get out every single $product of it
so we pass the array first then we follow it by the name of the single variable we want to use later  your foreach loop should be like this:

```<code>foreach($products as $product){
 //loop body
}
</code>```

Title: Laravel 5.2 proper foreach syntax

Body:
what is the difference between the following syntax ?

foreach($products as $product) {
// loop body
}

and

foreach($product as $product) {
 //loop body
}

got error some time when second one is used.
Thanks

Body:
This syntax is wrong

 foreach($product as $product) {
 //loop body
 }

As we loop through the $products and get out every single $product of it
so we pass the array first then we follow it by the name of the single variable we want to use later  your foreach loop should be like this:

foreach($products as $product){
 //loop body
}


问:
Why ZooKeeper needs majority to run?
I've been wondering why ZooKeeper needs a majority of the machines in the ensemble to work at all. Lets say we have a very simple ensemble of 3 machines - A,B,C.

When A fails, new leader is elected - fine, everything works. When another one dies, lets say B, service is unavailable. Does it make sense? Why machine C cannot handle everything alone, until A and B are up again?

Since one machine is enough to do all the work (for example single machine ensemble works fine)...

Is there any particular reason why ZooKeeper is designed in this way? Is there a way to configure ZooKeeper that, for example ensemble is available always when at least one of N is up?

Edit:
Maybe there is a way to apply a custom algorithm of leader selection? Or define a size of quorum?

Thanks in advance.

答:
Let’s look at an example that shows how things can go wrong if the quorum (majority of running servers) is too small.

Say we have five servers and a quorum can be any set of two servers. Now say that servers s1 and s2 acknowledge that they have replicated a request to create a znode /z. The service returns to the client saying that the znode has been created. Now suppose servers s1  and s2  are partitioned away from the other servers and from clients for an arbitrarily long time, before they have a chance to replicate the new znode to the other servers. The service in this state is able to make progress because there are three servers available and it really needs only two according to our assumptions, but these three servers have never seen the new znode /z. Consequently, the request to create /z is not durable.

This is an example of the split-brain scenario. To avoid this problem, in this example the size of the quorum must be at least three, which is a majority out of the five servers in the ensemble. To make progress, the ensemble needs at least three servers available. To confirm that a request to update the state has completed successfully, this ensemble also requires that at least three servers acknowledge that they have replicated it.

Title: Why ZooKeeper needs majority to run?


问:
PHP include in JavaScript is not working
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

```<code>outputEl.innerHTML = '<?php include "./change/ud1.php";?>';
</code>```

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

答:
Try this

```<code>$("#output1").load("change/ud1.php");
</code>```

Body:
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

outputEl.innerHTML = '<?php include "./change/ud1.php";?>';

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

Body:
Try this

$("#output1").load("change/ud1.php");


问:
How can I connect to ElasticSearch running in the official Docker image using TransportClient?
(First, I'm aware of Can not connect to elasticsearch container in docker.  My problem remains.)

I am kicking the tires on ElasticSearch.

I've run the official Docker image from the command line as described in the official documentation, specifying the cluster.name as elasticsearch (the documentation claims that is the default, but inspection reveals it to actually be docker-cluster by default):

```<code>$ docker run -p 9200:9200 -p 9300:9300 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" -e "xpack.security.enabled=false" -e "cluster.name=elasticsearch" docker.elastic.co/elasticsearch/elasticsearch:5.4.2
</code>```

You'll note that I've disabled the X-Pack security, following official documentation.

You'll note that I've exposed both port 9200 and port 9300.

The result of pointing a browser at http://localhost:9200/_cat/health is:

```<code>1498166019 21:13:39 docker-cluster yellow 1 1 3 3 0 0 3 0 - 50.0%
</code>```

…which doesn't fill me with confidence, but that's what you get, I guess, when you run things by following the official documentation.

At any rate, next, using Java, I've built the Client like so:

```<code>this.client = new PreBuiltTransportClient(Settings.builder()
                                          .put("cluster.name", "elasticsearch")
                                          .put("client.transport.sniff", true)
                                          .build())
  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
</code>```

You'll note I've specified 127.0.0.1 as the hostname (matching the transport.host property) and 9300 as the port (matching the exposed port).

Then I run: this.client.prepareGet("argle", "bargle", "1").get();.  I'm expecting to see some kind of "hey, dummy, argle doesn't exist" error.

Instead, this results in the dreaded:

```<code>NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{q00tH2RKTlCkXut03lYHOg}{127.0.0.1}{127.0.0.1:9300}]]
</code>```

What am I doing wrong?  What part of the official documentation is incorrect?

答:
In my case, "xpack.security.enabled=false" was the solution.</p>

```<code>elasticsearch:
  image: docker.elastic.co/elasticsearch/elasticsearch:5.4.1
  ports:
    - 9200:9200
    - 9300:9300
  container_name: elasticsearch
  ulimits:
    memlock:
      soft: -1
      hard: -1
  mem_limit: 1g
  environment:
    - cluster.name=docker-cluster
    - node.name=one
    - bootstrap.memory_lock=false
    - xpack.security.enabled=false
    - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    - network.publish_host=192.168.99.100
    - transport.publish_port=9300
  volumes:
    - /usr/share/elasticsearch/data

elasticsearch2:
  image: docker.elastic.co/elasticsearch/elasticsearch:5.4.1
  ports:
    - 9201:9200
    - 9301:9300
  container_name: elasticsearch2
  ulimits:
    memlock:
      soft: -1
      hard: -1
  mem_limit: 1g
  environment:
    - cluster.name=docker-cluster
    - node.name=two
    - bootstrap.memory_lock=false
    - xpack.security.enabled=false
    - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    - network.publish_host=192.168.99.100
    - transport.publish_port=9301
    - "discovery.zen.ping.unicast.hosts=192.168.99.100"
    - "discovery.zen.minimum_master_nodes=2"
  volumes:
    - /usr/share/elasticsearch/data
</code>```

Body:
(First, I'm aware of Can not connect to elasticsearch container in docker.  My problem remains.)

I am kicking the tires on ElasticSearch.

I've run the official Docker image from the command line as described in the official documentation, specifying the cluster.name as elasticsearch (the documentation claims that is the default, but inspection reveals it to actually be docker-cluster by default):

$ docker run -p 9200:9200 -p 9300:9300 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" -e "xpack.security.enabled=false" -e "cluster.name=elasticsearch" docker.elastic.co/elasticsearch/elasticsearch:5.4.2

You'll note that I've disabled the X-Pack security, following official documentation.

You'll note that I've exposed both port 9200 and port 9300.

The result of pointing a browser at http://localhost:9200/_cat/health is:

1498166019 21:13:39 docker-cluster yellow 1 1 3 3 0 0 3 0 - 50.0%

…which doesn't fill me with confidence, but that's what you get, I guess, when you run things by following the official documentation.

At any rate, next, using Java, I've built the Client like so:

this.client = new PreBuiltTransportClient(Settings.builder()
                                          .put("cluster.name", "elasticsearch")
                                          .put("client.transport.sniff", true)
                                          .build())
  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

You'll note I've specified 127.0.0.1 as the hostname (matching the transport.host property) and 9300 as the port (matching the exposed port).

Then I run: this.client.prepareGet("argle", "bargle", "1").get();.  I'm expecting to see some kind of "hey, dummy, argle doesn't exist" error.

Instead, this results in the dreaded:

NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{q00tH2RKTlCkXut03lYHOg}{127.0.0.1}{127.0.0.1:9300}]]

What am I doing wrong?  What part of the official documentation is incorrect?

Body:
In my case, "xpack.security.enabled=false" was the solution.

elasticsearch:
  image: docker.elastic.co/elasticsearch/elasticsearch:5.4.1
  ports:
    - 9200:9200
    - 9300:9300
  container_name: elasticsearch
  ulimits:
    memlock:
      soft: -1
      hard: -1
  mem_limit: 1g
  environment:
    - cluster.name=docker-cluster
    - node.name=one
    - bootstrap.memory_lock=false
    - xpack.security.enabled=false
    - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    - network.publish_host=192.168.99.100
    - transport.publish_port=9300
  volumes:
    - /usr/share/elasticsearch/data

elasticsearch2:
  image: docker.elastic.co/elasticsearch/elasticsearch:5.4.1
  ports:
    - 9201:9200
    - 9301:9300
  container_name: elasticsearch2
  ulimits:
    memlock:
      soft: -1
      hard: -1
  mem_limit: 1g
  environment:
    - cluster.name=docker-cluster
    - node.name=two
    - bootstrap.memory_lock=false
    - xpack.security.enabled=false
    - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    - network.publish_host=192.168.99.100
    - transport.publish_port=9301
    - "discovery.zen.ping.unicast.hosts=192.168.99.100"
    - "discovery.zen.minimum_master_nodes=2"
  volumes:
    - /usr/share/elasticsearch/data


问:
SQL data returned in a comma-delimited list
Here are my tables:

```<code>-----------------------------------------
Hotels
-----------------------------------------
HotelID | HotelName
-----------------------------------------

-----------------------------------------
HotelImages
-----------------------------------------
HotelImageID | HotelID | Filename
-----------------------------------------
</code>```

I'd like to create a SELECT statement that will return the data like so:

```<code>HotelID | HotelName | Images
-----------------------------------------
1 | Hotel1 | Image1,Image2,Image3
2 | Hotel2 | Image4,Image5,Image6
</code>```

How can I modify my query to do this? I have:

```<code>SELECT H.HotelID, H.HotelName, '' AS Images
FROM Hotels H
</code>```

I know I can use COALESCE to create a comma-delimited list:

```<code>DECLARE @Images varchar(500)
SELECT @Images = COALESCE(@Images + ',', '') + CAST(Filename AS varchar(100)) FROM HotelImages WHERE HotelID = 1
SELECT @Images
</code>```

But I don't know how to integrate that into my current query so that the list can be returned with the rest of the hotel data.

I should mention I'm using SQL Server 2000.

答:
COALESCE does not do what you suggest.  It returns the first non-NULL value from a list.  It does not aggregate values across rows. (Although I agree that it sounds like it does the aggregation).

SQL Server does not have direct support for string-concatenation aggregation (MySQL, for instance, has GROUP_CONCAT).  I've seen several solutions posted that provide this kind of functionality, but I'm pretty sure they're for SQL-2005 and above.  Google (or search here) on "GROUP_CONCAT FOR SQL SERVER".

Body:
Here are my tables:

-----------------------------------------
Hotels
-----------------------------------------
HotelID | HotelName
-----------------------------------------

-----------------------------------------
HotelImages
-----------------------------------------
HotelImageID | HotelID | Filename
-----------------------------------------

I'd like to create a SELECT statement that will return the data like so:

HotelID | HotelName | Images
-----------------------------------------
1 | Hotel1 | Image1,Image2,Image3
2 | Hotel2 | Image4,Image5,Image6

How can I modify my query to do this? I have:

SELECT H.HotelID, H.HotelName, '' AS Images
FROM Hotels H

I know I can use COALESCE to create a comma-delimited list:

DECLARE @Images varchar(500)
SELECT @Images = COALESCE(@Images + ',', '') + CAST(Filename AS varchar(100)) FROM HotelImages WHERE HotelID = 1
SELECT @Images

But I don't know how to integrate that into my current query so that the list can be returned with the rest of the hotel data.

I should mention I'm using SQL Server 2000.


问:
Convert Nested JSON Object into data Frame in R
I am fetching the data from Twitter API. Converting a Data from JSON object to Data Frame and load into Data Warehouse. Find below input and code snippet.

I am very new to R Programming.

```<code> stats_campaign.data <- content(stats_campaign.request)
 print(stats_campaign.data)
</code>```

O/P:

```<code>`{
 "data_type": [ "stats" ],
 "time_series_length": [ 1 ],
 "data": [
 {
  "id": [ "XXXXX" ],
  "id_data": [
    {
      "segment": {},
      "metrics": {
        "impressions": {},
        "tweets_send": {},
        "qualified_impressions": {},
        "follows": {},
        "app_clicks": {},
        "retweets": {},
        "likes": {},
        "engagements": {},
        "clicks": {},
        "card_engagements": {},
        "replies": {},
        "url_clicks": {},
        "carousel_swipes": {}
      }
    }
   ]
   },

   {
   "id": [ "XXXX1" ],
   "id_data": [
    {
      "segment": {},
      "metrics": {
        "impressions": {},
        "tweets_send": {},
        "qualified_impressions": {},
        "follows": {},
        "app_clicks": {},
        "retweets": {},
        "likes": {},
        "engagements": {},
        "clicks": {},
        "card_engagements": {},
        "replies": {},
        "url_clicks": {},
        "carousel_swipes": {}
      }
    }
    ]
    },`
</code>```

When I am reading this JSON value ,

```<code>    stats_json_file <- sprintf("P:/R Repos/R
               Applications/TwitterAPIData/stats_test_data-%s.json", TODAY)
    jsonlite::fromJSON(stats_json_file)

   **Result :**
       id                                      id_data
    1  5wcaz                                         NULL
    2  5ub2u                                         NULL
    3  5wb8x                                         NULL
    4  5wb1j                                         NULL
    5  5yqwj                                         NULL
    6  5pq5i                                         NULL
    7  5u197                                         NULL
    8  5z2js                                         NULL
    9  6fqh0   333250, 4, 9, 19, 111, 3189, 3156, 5, 1091
    10 5tvr1                                         NULL
    11 5yqw4                                         NULL
    12 5qqps                                         NULL
    13 5yqvw                                         NULL
    14 5ygom                                         NULL
    15 5nc88                                         NULL
    16 5yg94                                         NULL
    17 65t9e                                         NULL
    18 5peck                                         NULL
    19 63pg1 247283, 17, 22, 35, 297, 5514, 5450, 6, 2971
    20 6cdvy        156705, 1, 2, 6, 112, 10933, 605, 170

   From my JSON file I want Id and whole "metrics": {
        "impressions": {},
        "tweets_send": {},
        "qualified_impressions": {},
        "follows": {},
        "app_clicks": {},
        "retweets": {},
        "likes": {},
        "engagements": {},
        "clicks": {},
        "card_engagements": {},
        "replies": {},
        "url_clicks": {},
        "carousel_swipes": {}
      }
      and convert to Data Frame to load into Data Base. Plzz Help..!
</code>```

How can I parsed this JSON Object. I want to retrieve Id & whole Metrics object. Then want to convert into Data Frame to load into SQL Table.

To read the multiple Id's & Metrics value I used below code,

```<code>`test <- list()
 for(i in 1:len)
 { test <- unlist(stats_campaign.data$data[[i]])
 print(test)}`

 **Output:**
      id
  "5wcaz"
      id
   "5ub2u"
      id
  "5wb8x"
      id
 "5wb1j"
      id
 "5yqwj"
      id
  "5pq5i"
      id
  "5u197"
      id
  "5z2js"
      id
  "5tvr1"
      id
  "5yqw4"
      id
  "5qqps"
      id
  "5yqvw"
      id
  "5ygom"
      id
  "5nc88"
      id
  "5yg94"
      id
  "65t9e"
      id
  "5peck"
                     id id_data.metrics.impressions
                   "63pg1"                    "133227"
                      id_data.metrics.tweets_send     id_data.metrics.follows
                   "10"                         "9"
                      id_data.metrics.retweets       id_data.metrics.likes
                   "17"                        "96"
                    id_data.metrics.engagements      id_data.metrics.clicks
                 "2165"                      "2134"
                    id_data.metrics.replies  id_data.metrics.url_clicks
                    "5"                      "1204"
                     id id_data.metrics.impressions
                "6cdvy"                    "176164"
     id_data.metrics.tweets_send    id_data.metrics.retweets
                    "2"                        "10"
    id_data.metrics.likes id_data.metrics.engagements
                  "121"                      "9708"
    id_data.metrics.clicks  id_data.metrics.url_clicks
                  "620"                       "160"
</code>```

Within a for I have to used list or something else to append the value each time, how can I do that ..?? Am I using a right Approach.?? Is there any alternative way I can parsed nested JSON object and directly put into Data Frame..?

Please Help..! Thanks In Advance..!

答:
As mentioned in the comments, a bit more information about what output you are looking for would be helpful.  In any case, I am hopeful that the following will provide a helpful direction.  The tidyjson README provides a bit of helpful overview.

Unfortunately, the lack of data in your JSON object makes it difficult to illustrate what might be present in your data (what to expect in the null objects), and I am having difficulty determining what part of the Twitter API you are looking at.  tidyjson gives you the ability to produce a consistent data.frame output, even when you have no data, though!  The key verbs are gather and spread, much like tidyr, but with JSON flavor.

```<code>str <- "{\"data_type\":[\"stats\"],\"time_series_length\":[1],\"data\":[{\"id\":[\"XXXXX\"],\"id_data\":[{\"segment\":{},\"metrics\":{\"impressions\":{},\"tweets_send\":{},\"qualified_impressions\":{},\"follows\":{},\"app_clicks\":{},\"retweets\":{},\"likes\":{},\"engagements\":{},\"clicks\":{},\"card_engagements\":{},\"replies\":{},\"url_clicks\":{},\"carousel_swipes\":{}}}]},{\"id\":[\"XXXX1\"],\"id_data\":[{\"segment\":{},\"metrics\":{\"impressions\":{},\"tweets_send\":{},\"qualified_impressions\":{},\"follows\":{},\"app_clicks\":{},\"retweets\":{},\"likes\":{},\"engagements\":{},\"clicks\":{},\"card_engagements\":{},\"replies\":{},\"url_clicks\":{},\"carousel_swipes\":{}}}]}]} "

library(dplyr)
library(tidyjson)

prep <- as.tbl_json(str) %>% enter_object("data") %>% gather_array("objid")

p1 <- prep %>% enter_object("id") %>%
  gather_array("idnum") %>% append_values_string("id")

p2 <- prep %>% enter_object("id_data") %>% gather_array("datanum") %>%
enter_object("metrics") %>%
spread_values(
 impressions = jstring("impressions", "value")
 , tweets_send = jnumber("tweets_send", "somekey")
)

p1 %>% tbl_df() %>% left_join(p2 %>% tbl_df(), by = c("document.id", "objid"))
#> # A tibble: 2 x 7
#>   document.id objid idnum    id datanum impressions tweets_send
#>         <int> <int> <int> <chr>   <int>       <chr>       <dbl>
#> 1           1     1     1 XXXXX       1        <NA>          NA
#> 2           1     2     1 XXXX1       1        <NA>          NA
</code>```

Body:
I am fetching the data from Twitter API. Converting a Data from JSON object to Data Frame and load into Data Warehouse. Find below input and code snippet.

I am very new to R Programming.

 stats_campaign.data <- content(stats_campaign.request)
 print(stats_campaign.data)

O/P:

`{
 "data_type": [ "stats" ],
 "time_series_length": [ 1 ],
 "data": [
 {
  "id": [ "XXXXX" ],
  "id_data": [
    {
      "segment": {},
      "metrics": {
        "impressions": {},
        "tweets_send": {},
        "qualified_impressions": {},
        "follows": {},
        "app_clicks": {},
        "retweets": {},
        "likes": {},
        "engagements": {},
        "clicks": {},
        "card_engagements": {},
        "replies": {},
        "url_clicks": {},
        "carousel_swipes": {}
      }
    }
   ]
   },

   {
   "id": [ "XXXX1" ],
   "id_data": [
    {
      "segment": {},
      "metrics": {
        "impressions": {},
        "tweets_send": {},
        "qualified_impressions": {},
        "follows": {},
        "app_clicks": {},
        "retweets": {},
        "likes": {},
        "engagements": {},
        "clicks": {},
        "card_engagements": {},
        "replies": {},
        "url_clicks": {},
        "carousel_swipes": {}
      }
    }
    ]
    },`

When I am reading this JSON value ,

    stats_json_file <- sprintf("P:/R Repos/R
               Applications/TwitterAPIData/stats_test_data-%s.json", TODAY)
    jsonlite::fromJSON(stats_json_file)

   **Result :**
       id                                      id_data
    1  5wcaz                                         NULL
    2  5ub2u                                         NULL
    3  5wb8x                                         NULL
    4  5wb1j                                         NULL
    5  5yqwj                                         NULL
    6  5pq5i                                         NULL
    7  5u197                                         NULL
    8  5z2js                                         NULL
    9  6fqh0   333250, 4, 9, 19, 111, 3189, 3156, 5, 1091
    10 5tvr1                                         NULL
    11 5yqw4                                         NULL
    12 5qqps                                         NULL
    13 5yqvw                                         NULL
    14 5ygom                                         NULL
    15 5nc88                                         NULL
    16 5yg94                                         NULL
    17 65t9e                                         NULL
    18 5peck                                         NULL
    19 63pg1 247283, 17, 22, 35, 297, 5514, 5450, 6, 2971
    20 6cdvy        156705, 1, 2, 6, 112, 10933, 605, 170

   From my JSON file I want Id and whole "metrics": {
        "impressions": {},
        "tweets_send": {},
        "qualified_impressions": {},
        "follows": {},
        "app_clicks": {},
        "retweets": {},
        "likes": {},
        "engagements": {},
        "clicks": {},
        "card_engagements": {},
        "replies": {},
        "url_clicks": {},
        "carousel_swipes": {}
      }
      and convert to Data Frame to load into Data Base. Plzz Help..!

How can I parsed this JSON Object. I want to retrieve Id & whole Metrics object. Then want to convert into Data Frame to load into SQL Table.

To read the multiple Id's & Metrics value I used below code,

`test <- list()
 for(i in 1:len)
 { test <- unlist(stats_campaign.data$data[[i]])
 print(test)}`

 **Output:**
      id
  "5wcaz"
      id
   "5ub2u"
      id
  "5wb8x"
      id
 "5wb1j"
      id
 "5yqwj"
      id
  "5pq5i"
      id
  "5u197"
      id
  "5z2js"
      id
  "5tvr1"
      id
  "5yqw4"
      id
  "5qqps"
      id
  "5yqvw"
      id
  "5ygom"
      id
  "5nc88"
      id
  "5yg94"
      id
  "65t9e"
      id
  "5peck"
                     id id_data.metrics.impressions
                   "63pg1"                    "133227"
                      id_data.metrics.tweets_send     id_data.metrics.follows
                   "10"                         "9"
                      id_data.metrics.retweets       id_data.metrics.likes
                   "17"                        "96"
                    id_data.metrics.engagements      id_data.metrics.clicks
                 "2165"                      "2134"
                    id_data.metrics.replies  id_data.metrics.url_clicks
                    "5"                      "1204"
                     id id_data.metrics.impressions
                "6cdvy"                    "176164"
     id_data.metrics.tweets_send    id_data.metrics.retweets
                    "2"                        "10"
    id_data.metrics.likes id_data.metrics.engagements
                  "121"                      "9708"
    id_data.metrics.clicks  id_data.metrics.url_clicks
                  "620"                       "160"

Within a for I have to used list or something else to append the value each time, how can I do that ..?? Am I using a right Approach.?? Is there any alternative way I can parsed nested JSON object and directly put into Data Frame..?

Please Help..! Thanks In Advance..!

Body:
As mentioned in the comments, a bit more information about what output you are looking for would be helpful.  In any case, I am hopeful that the following will provide a helpful direction.  The tidyjson README provides a bit of helpful overview.

Unfortunately, the lack of data in your JSON object makes it difficult to illustrate what might be present in your data (what to expect in the null objects), and I am having difficulty determining what part of the Twitter API you are looking at.  tidyjson gives you the ability to produce a consistent data.frame output, even when you have no data, though!  The key verbs are gather and spread, much like tidyr, but with JSON flavor.

str <- "{\"data_type\":[\"stats\"],\"time_series_length\":[1],\"data\":[{\"id\":[\"XXXXX\"],\"id_data\":[{\"segment\":{},\"metrics\":{\"impressions\":{},\"tweets_send\":{},\"qualified_impressions\":{},\"follows\":{},\"app_clicks\":{},\"retweets\":{},\"likes\":{},\"engagements\":{},\"clicks\":{},\"card_engagements\":{},\"replies\":{},\"url_clicks\":{},\"carousel_swipes\":{}}}]},{\"id\":[\"XXXX1\"],\"id_data\":[{\"segment\":{},\"metrics\":{\"impressions\":{},\"tweets_send\":{},\"qualified_impressions\":{},\"follows\":{},\"app_clicks\":{},\"retweets\":{},\"likes\":{},\"engagements\":{},\"clicks\":{},\"card_engagements\":{},\"replies\":{},\"url_clicks\":{},\"carousel_swipes\":{}}}]}]} "

library(dplyr)
library(tidyjson)

prep <- as.tbl_json(str) %>% enter_object("data") %>% gather_array("objid")

p1 <- prep %>% enter_object("id") %>%
  gather_array("idnum") %>% append_values_string("id")

p2 <- prep %>% enter_object("id_data") %>% gather_array("datanum") %>%
enter_object("metrics") %>%
spread_values(
 impressions = jstring("impressions", "value")
 , tweets_send = jnumber("tweets_send", "somekey")
)

p1 %>% tbl_df() %>% left_join(p2 %>% tbl_df(), by = c("document.id", "objid"))
#> # A tibble: 2 x 7
#>   document.id objid idnum    id datanum impressions tweets_send
#>         <int> <int> <int> <chr>   <int>       <chr>       <dbl>
#> 1           1     1     1 XXXXX       1        <NA>          NA
#> 2           1     2     1 XXXX1       1        <NA>          NA


问:
Return view on html button click
I'm on ASP.NET and I want to navigate to another view when clicking on a button on the HTML page.

```<code><input type="button" value="Back"  class="btn btn-default" />
</code>```

That's my button and I want to make a:

```<code>return View();
</code>```

答:
Your button needs to post back some data?

As the most basic response for your question is :

```<code><input type="button" value="Back"  class="btn btn-default" onclick='window.location.href = @Url.Action("action","controller")' />
</code>```

Which will redirect your page to your action.

Title: Return view on html button click

Body:
I'm on ASP.NET and I want to navigate to another view when clicking on a button on the HTML page.

<input type="button" value="Back"  class="btn btn-default" />

That's my button and I want to make a:

return View();

Body:
Your button needs to post back some data?

As the most basic response for your question is :

<input type="button" value="Back"  class="btn btn-default" onclick='window.location.href = @Url.Action("action","controller")' />

Which will redirect your page to your action.


问:
Error on adding a number into a table
i want to get the date of this website and i can get it but it returns an error adding to the column.
Print: http://prntscr.com/fsav5h

Code:

```<code>page = urllib2.urlopen('https://www.meetup.com/find/events/career-business/?allMeetups=false&radius=50&userFreeform=London&mcId=c1012717&change=yes')
soup = BeautifulSoup(page, 'html.parser')

events = soup.find('div', class_='unit size5of7 ')

A = []

try:
    conn = psycopg2.connect("dbname='meetup' user='postgres' host='localhost' password='root'")
except:
    print 'Unable to connect to the database.'

cur = conn.cursor()

for event in events.findAll('ul', class_="searchResults resetList clearfix"):
    date = event.findAll('li', class_="date-indicator")
    if len(date) != 0:
        A.append(date[0].find(text = True))
        cur.execute("""UPDATE events SET event_date = %s WHERE event_date = '' """ % tuple(A) )
        conn.commit()
        del A[:]
</code>```

答:
Try this    </p>

```<code>cur.execute("""UPDATE events SET event_date = '%s' WHERE event_date = '' """, (tuple(A)))
</code>```

Title: Error on adding a number into a table

Body:
i want to get the date of this website and i can get it but it returns an error adding to the column.
Print: http://prntscr.com/fsav5h

Code:

page = urllib2.urlopen('https://www.meetup.com/find/events/career-business/?allMeetups=false&radius=50&userFreeform=London&mcId=c1012717&change=yes')
soup = BeautifulSoup(page, 'html.parser')

events = soup.find('div', class_='unit size5of7 ')

A = []

try:
    conn = psycopg2.connect("dbname='meetup' user='postgres' host='localhost' password='root'")
except:
    print 'Unable to connect to the database.'

cur = conn.cursor()

for event in events.findAll('ul', class_="searchResults resetList clearfix"):
    date = event.findAll('li', class_="date-indicator")
    if len(date) != 0:
        A.append(date[0].find(text = True))
        cur.execute("""UPDATE events SET event_date = %s WHERE event_date = '' """ % tuple(A) )
        conn.commit()
        del A[:]

Body:
Try this

cur.execute("""UPDATE events SET event_date = '%s' WHERE event_date = '' """, (tuple(A)))


问:
MySQL event schedule not working
I have a event schedule in mySql which needs to run on 15th of every month at 2:00PM. i have written it as follows:

```<code>create event asdb.e_monthly
on schedule
every 1 month
starts '2013-07-15 13:59:59'
do
INSERT INTO asdb.abc_test values('monthly','monthly');
</code>```

but its not inserting values to the abc_tes table. Am I missing something?

Thanks

答:
Verify if the event_scheduler is ON - execute the following command:

```<code>SHOW PROCESSLIST;
</code>```

It'll output a table/entries, you must look for an entry with User event_scheduler, and Command Daemon:

```<code>Id           User         Host      db  Command Time    State            Info
22870   event_scheduler localhost   \N   Daemon  23    Waiting for next activation  \N
</code>```

OR, you can also verify using the following command:

```<code>SELECT @@global.event_scheduler;
</code>```

The result should be ON, otherwise set it off (will get 0 for the command), as stated in the next section.

If you don't have any such entry (as above), you may start the event scheduler using the following command:

```<code>SET GLOBAL event_scheduler = ON;
</code>```

Once done, you can verify if it has been executed properly using the SHOW PROCESSLIST command, as mentioned above.

Title: MySQL event schedule not working

Body:
I have a event schedule in mySql which needs to run on 15th of every month at 2:00PM. i have written it as follows:

create event asdb.e_monthly
on schedule
every 1 month
starts '2013-07-15 13:59:59'
do
INSERT INTO asdb.abc_test values('monthly','monthly');

but its not inserting values to the abc_tes table. Am I missing something?

Thanks

Body:
Verify if the event_scheduler is ON - execute the following command:

SHOW PROCESSLIST;

It'll output a table/entries, you must look for an entry with User event_scheduler, and Command Daemon:

Id           User         Host      db  Command Time    State            Info
22870   event_scheduler localhost   \N   Daemon  23    Waiting for next activation  \N

OR, you can also verify using the following command:

SELECT @@global.event_scheduler;

The result should be ON, otherwise set it off (will get 0 for the command), as stated in the next section.

If you don't have any such entry (as above), you may start the event scheduler using the following command:

SET GLOBAL event_scheduler = ON;

Once done, you can verify if it has been executed properly using the SHOW PROCESSLIST command, as mentioned above.


问:
Get metalsmith, contentful and markdown to work together
I am trying to use Metalsmith to render content from the Contentful platform (using the metalsmith-contentful platform and metalsmith-layout as per the example here).

One of my contentful fields is markdown text, so I want to render it as HTML in the final template. My initial setup was similar to the example above but only read the markdown text as plain text.

I am now trying to convert the markdown in a handlebars helper, i.e.

```<code> handlebars.registerHelper('markdown', function(object) {
 var text = marked(object);
 return new handlebars.SafeString(text);
 })
</code>```

and calling with {{{ markdown mycontentfulobject}}}

but this doesn't work either.

Any ideas?

答:
Do you get any exceptions?

I've got exactly the same setup right now. And I think you're really close already.

What I do is, I call registerHelper.

```<code>const marked = require( 'marked' )

handlebars.registerHelper('marked', function (text) {
  return marked(text);
})
</code>```

And I use it in my templates like that.

```<code><section>{{#marked fields.excerpt}}{{/marked}}</section>
</code>```

This works pretty well for me. :)

You can find an example project here  https://github.com/stefanjudis/stefan-judis-website/blob/master/build.js#L22-L25

Body:
I am trying to use Metalsmith to render content from the Contentful platform (using the metalsmith-contentful platform and metalsmith-layout as per the example here).

One of my contentful fields is markdown text, so I want to render it as HTML in the final template. My initial setup was similar to the example above but only read the markdown text as plain text.

I am now trying to convert the markdown in a handlebars helper, i.e.

 handlebars.registerHelper('markdown', function(object) {
 var text = marked(object);
 return new handlebars.SafeString(text);
 })

and calling with {{{ markdown mycontentfulobject}}}

but this doesn't work either.

Any ideas?

Body:
Do you get any exceptions?

I've got exactly the same setup right now. And I think you're really close already.

What I do is, I call registerHelper.

const marked = require( 'marked' )

handlebars.registerHelper('marked', function (text) {
  return marked(text);
})

And I use it in my templates like that.

<section>{{#marked fields.excerpt}}{{/marked}}</section>

This works pretty well for me. :)

You can find an example project here  https://github.com/stefanjudis/stefan-judis-website/blob/master/build.js#L22-L25


问:
Using Do/Catch in Swift
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

```<code>func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}
</code>```

It would be very nice if somebody could help me.

答:
A good practice in swift would be to use correctly the throws errors

This is an example inspired from yours :

```<code>enum Errors: Error {
  case noData
  case unknownError
}

func progress(data: String?) throws -> String {

  guard let data = data else {
    // Data is missing
    throw Errors.noData
  }

  // Do other things, and throw if necessary

  result = data

  return result
}

do {
  try process(data: "A data to process")
} catch {
  print("An error occurred: \(error)")
}
</code>```

You can try this code as is in a Swift Playgound

Title: Using Do/Catch in Swift

Body:
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}

It would be very nice if somebody could help me.

Body:
A good practice in swift would be to use correctly the throws errors

This is an example inspired from yours :

enum Errors: Error {
  case noData
  case unknownError
}

func progress(data: String?) throws -> String {

  guard let data = data else {
    // Data is missing
    throw Errors.noData
  }

  // Do other things, and throw if necessary

  result = data

  return result
}

do {
  try process(data: "A data to process")
} catch {
  print("An error occurred: \(error)")
}

You can try this code as is in a Swift Playgound


问:
Java Static
Duplicate: What does the 'static' keyword do in a class?

I've read this post already.

What does the "static" keyword in a method do?

I remember being told that static != clingy...but that is pretty much all I know about this keyword.

答:
A static method belongs to the Class it is defined in and not to instances of objects of that Class, as non-static methods do.  As a side-effect of not belonging to the instances of a Class, it's a compile error to try and access non-static fields in a static method.  There's no "this" for the static methods to get access of the non-static fields from.

The Java Math class is a great example because it's loaded with static methods.  You never create an instance of the Math class, you just call methods directly from the class.

```<code>Math.abs(3.14);
</code>```

OwnerDisplayName: koldfyre

Title: Java Static

LastEditorDisplayName: nemo

Body:
A static method belongs to the Class it is defined in and not to instances of objects of that Class, as non-static methods do.  As a side-effect of not belonging to the instances of a Class, it's a compile error to try and access non-static fields in a static method.  There's no "this" for the static methods to get access of the non-static fields from.

The Java Math class is a great example because it's loaded with static methods.  You never create an instance of the Math class, you just call methods directly from the class.

Math.abs(3.14);

OwnerDisplayName: Bill the Lizard


问:
Correct syntax in php
I'am tryig to print an id this way

```<code><form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >
</code>```

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?

答:
Yes it is incorrect structure.
You should code like that:</p>

```<code>echo isset($_REQUEST['code']) ?  'id="csv-form"' : 'id="edit-form"';
</code>```

Title: Correct syntax in php

Body:
I'am tryig to print an id this way

<form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?

Body:
Yes it is incorrect structure.
You should code like that:

echo isset($_REQUEST['code']) ?  'id="csv-form"' : 'id="edit-form"';


问:
IBM Watson Knowledge Studio - Entities with Role attribute and extracting it from NLU api
I have created a custom Entity Type system using Watson Knowledge Studio following these guidelines: https://www.ibm.com/watson/developercloud/doc/wks/typesystem.html

For each entity type, the annotator can add attributes to a mention, e.g. role, subtype, class, type, etc.

I am specifically using the "role" attribute, to annotate a mention in different contexts.  For example, here is a subset of my entity type system:

Entities - AREA, SYMPTOM, RESOLUTION, CUSTOMER, FAULT, COMPLAINT

Thus, for a mention annotated as AREA, I assign the role CUSTOMER, FAULT or COMPLAINT, depending on the context of the mention.

When the model is sufficiently trained, I would like to use Natural Language Understanding to extract entity types (https://www.ibm.com/watson/developercloud/natural-language-understanding/api/v1/)

The problem is the API does not expose any of the entity attributes, e.g. role, class, type, etc.

My question is therefore, how does one extract the entity attributes when you've trained your model and wish to extract entities and relations from an unseen text?  What is the point of role, class and mention type if NLU cannot extract it (unless you can, but I've missed it somehow)?

答: Currently, as you mentioned, entity attributes cannot be extracted in NLU and the only way to extract entity attributes from an unseen text would be to run ML annotator as pre-annotator within WKS. We are investigating to enhance this in future.</p>


问:
Alignment issue in context menu

The tickmark should be aligned with the text.

Styles :

```<code>   {
content: '\2713';
display: inline-block;
color: #990000;
float:right;
vertical-align: middle;

/*padding: 0 6px 0 0;
position: absolute;
right: 0;
top: 10px;*/
  }
</code>```

How can I make the correct alignment ?

答:
Change the css like this :</p>

```<code>content: '\2713';
display: inline-block;
color: #990000;
float:right;
position: relative;
transform: translateY(-100%);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Alignment issue in context menu

Body:
The tickmark should be aligned with the text.

Styles :

   {
content: '\2713';
display: inline-block;
color: #990000;
float:right;
vertical-align: middle;

/*padding: 0 6px 0 0;
position: absolute;
right: 0;
top: 10px;*/
  }

How can I make the correct alignment ?

Body:
Change the css like this :

content: '\2713';
display: inline-block;
color: #990000;
float:right;
position: relative;
transform: translateY(-100%);


问:
Normalize data range of "180 - 360" to the range "0 - 100" - jQuery/JS
I have a image that I am rotating, but it can only rotate between 180deg and 360deg. But I need the targetValue that is entered to be between 0 - 100.

So if you enter a targetValue of 20, it will then rotate the image 20% of the range 180deg - 360deg.

I have attached a snippet of the code that I have already -

Any help would be appreciated!

CODE -

var targetValue = 100; //CAN ONLY BE BETWEEN 0 & 100

console.log(targetValue);

function targetChange(){
    $('#target').css('transform', 'rotate(' + targetValue + 'deg' + ')');
    console.log('hello');
}
targetChange();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.target {
    position: absolute;
 width: 100%;
    height: 100%;
    z-index: 2;
    transform: rotate(180deg);
}</code>```

```

答:
Check this out:</p>

```<code>var targetValue = 100; //CAN ONLY BE BETWEEN 0 & 100

var normalizedValue = (targetValue / 100 * 180) + 180

console.log(targetValue);

function targetChange(){
    $('#target').css('transform', 'rotate(' + normalizedValue + 'deg' + ')');
    console.log('hello');
}
targetChange();
</code>```

Body:
I have a image that I am rotating, but it can only rotate between 180deg and 360deg. But I need the targetValue that is entered to be between 0 - 100.

So if you enter a targetValue of 20, it will then rotate the image 20% of the range 180deg - 360deg.

I have attached a snippet of the code that I have already -

Any help would be appreciated!

CODE -

var targetValue = 100; //CAN ONLY BE BETWEEN 0 & 100

console.log(targetValue);

function targetChange(){
    $('#target').css('transform', 'rotate(' + targetValue + 'deg' + ')');
    console.log('hello');
}
targetChange();

.target {
    position: absolute;
 width: 100%;
    height: 100%;
    z-index: 2;
    transform: rotate(180deg);
}

Body:
Check this out:

var targetValue = 100; //CAN ONLY BE BETWEEN 0 & 100

var normalizedValue = (targetValue / 100 * 180) + 180

console.log(targetValue);

function targetChange(){
    $('#target').css('transform', 'rotate(' + normalizedValue + 'deg' + ')');
    console.log('hello');
}
targetChange();


问:
C# and ASP.NET custom property attributes and determining if properties changed
I am working on a project where we want to keep a history of a particular object. On save I want a method on the object that will determine if it has changed so that I can call a method to save its current state to history. E.g. I populate a form from an object the user makes changes (or possibly not) and submits the from. I want to take my original object and a copy of that object that has been updated from the form and determine if it has changed at all. Additionally I may decide at some point that certain properties don't matter (e.g. if Name changes I won't track it).

I'm thinking the easiest/most flexible way to accomplish this would be if I could give the properties I care about a custom attribute [ChangeTracked] and then I could use reflection to get a list of all properties with that attribute and loop through them comparing A.property == B.property to determine if any have changed.

Would this work? Is there a significantly better/easier way to handle this, like some sort of built in method you can add to an object to determine if the values of any properties have changed? Whatever the solution some psudo code would be appreciated. Just as a point of clarification the solution needs to determine if the value I care about has actually changed not just if it has been assigned since it was created i.e. if I set Name="bob" and it was already "bob" before my assignment this does not count as a change.

答:
It ain't fancy, but this is the tried and true brute force method. Just add a private property to the object named IsDirty. For properties that you want to track, just add IsDirty=True to the property Set routine. For more complicated "do I care" rules, just code them into the property set.

The page button's click event can fire a Save event that writes all the values from the textboxes and dropdowns into the object properties, then calls the object Save method, which tests the IsDirty property before doing anything.


问:
Feature selection in python
I am trying to perform feature selection in python using several techniques. The first technique that I am trying to apply is selecting features using only the varience of the features. My code is the following:

```<code>def feature_selection_technique(train, test, lbls, technique):
   if technique == "variance":
        sel = VarianceThreshold(threshold=(0.00010 * (1 - .15)))
        model1 = sel1.fit_transform(face_train)
        new_train = model1.transform(train)
        new_test = model1.transform(test)

    return new_train, new_test
</code>```

Actually I want to calculate the selected features using the train dataset and then to apply it to the test dataset. It seems that the transform method cannot be aoolied in that case. What can I do in that case?

答:
I think that there is a problem in the syntax you are using. See documentation and example here. The correct syntax is as follows:

```<code>def feature_selection_technique(train, test, lbls, technique):
   if technique == "variance":
        sel = VarianceThreshold(threshold=(0.00010 * (1 - .15)))
        new_train=sel.fit_transform(train)
        new_test = sel.transform(test)

    return new_train, new_test
</code>```

That is, you should initialize sel, then fit it to the training data and transform it, and then transform the test data.

Title: Feature selection in python

Body:
I am trying to perform feature selection in python using several techniques. The first technique that I am trying to apply is selecting features using only the varience of the features. My code is the following:

def feature_selection_technique(train, test, lbls, technique):
   if technique == "variance":
        sel = VarianceThreshold(threshold=(0.00010 * (1 - .15)))
        model1 = sel1.fit_transform(face_train)
        new_train = model1.transform(train)
        new_test = model1.transform(test)

    return new_train, new_test

Actually I want to calculate the selected features using the train dataset and then to apply it to the test dataset. It seems that the transform method cannot be aoolied in that case. What can I do in that case?

Body:
I think that there is a problem in the syntax you are using. See documentation and example here. The correct syntax is as follows:

def feature_selection_technique(train, test, lbls, technique):
   if technique == "variance":
        sel = VarianceThreshold(threshold=(0.00010 * (1 - .15)))
        new_train=sel.fit_transform(train)
        new_test = sel.transform(test)

    return new_train, new_test

That is, you should initialize sel, then fit it to the training data and transform it, and then transform the test data.


问:
How to execute my command every 4 hours in crontab in ubuntu(forever module nodejs)?
I am executing the below command first,

```<code>crontab -u user_name -e

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for this particular task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
</code>```

The above file gets displayed.
And i have added my command to the next line in the above file

```<code>0 */4 * * * forever restart /var/www/html/app.js
</code>```

But the above command is not executing.
The file path for my app.js file is '/var/www/html/'.
What i actually need is my web services in nodejs  are going down frequently after 8 hours after it getting started(This is not the db issue as my db is not going idle) so i am prefering to restart it every 4 hours after it gets started using crontab.

答: Reading this answer have you tried to use /usr/local/bin/forever instead of 'forever'?

Body:
I am executing the below command first,

crontab -u user_name -e

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for this particular task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

The above file gets displayed.
And i have added my command to the next line in the above file

0 */4 * * * forever restart /var/www/html/app.js

But the above command is not executing.
The file path for my app.js file is '/var/www/html/'.
What i actually need is my web services in nodejs  are going down frequently after 8 hours after it getting started(This is not the db issue as my db is not going idle) so i am prefering to restart it every 4 hours after it gets started using crontab.


问:
Changing SelectedItem property of a ListView programatically
I have a 2 ListViews with same items in both of them. What I want to do is that when a selection is made in one ListView, the same selection should be reflected in the other ListView also. The two ListViews are bound to two different ViewModels but both the ViewModels implement the same interface.
I've overridden the Equals methods in both ViewModels.

The two ListViews are on different XAML pages. The first ListView say LV1 is in Page1.xaml and LV2 is in Page2.xaml. What I want is that when I am changing the selection in LV2 the selection in LV1 should also change( one way only ). I've set x:FieldModifier="public" on LV1 and exposing through a static property of Page1 like this:

```<code>public sealed partial class Page1 : Page
{
    public static Page1 page1 { get; private set; }
}
</code>```

And on Page2, I have this :

```<code>private async void LV2_ItemClick(object sender, ItemClickEventArgs e)
{
    var selected = e.ClickedItem as ISomeCommonInterface;
    //Comparision is successful --> Contains() always returns corect value;
    if (Page1.page1.LV1.Items.ToList().Contains(selected))
    {
        Page1.page1.LV1.SelectedItem = null; // this works
        Page1.page1.LV1.SelectedItem = selected; // this doesn't work
    }
}
</code>```

I've found that inside the if condition, assignment to null changes the SelectedItem of LV1 to null but the next line doesn't change it to selected ( it remains null ).

答:
add after assignment: </p>

```<code>Page1.page1.LV1.Select();
</code>```

Body:
I have a 2 ListViews with same items in both of them. What I want to do is that when a selection is made in one ListView, the same selection should be reflected in the other ListView also. The two ListViews are bound to two different ViewModels but both the ViewModels implement the same interface.
I've overridden the Equals methods in both ViewModels.

The two ListViews are on different XAML pages. The first ListView say LV1 is in Page1.xaml and LV2 is in Page2.xaml. What I want is that when I am changing the selection in LV2 the selection in LV1 should also change( one way only ). I've set x:FieldModifier="public" on LV1 and exposing through a static property of Page1 like this:

public sealed partial class Page1 : Page
{
    public static Page1 page1 { get; private set; }
}

And on Page2, I have this :

private async void LV2_ItemClick(object sender, ItemClickEventArgs e)
{
    var selected = e.ClickedItem as ISomeCommonInterface;
    //Comparision is successful --> Contains() always returns corect value;
    if (Page1.page1.LV1.Items.ToList().Contains(selected))
    {
        Page1.page1.LV1.SelectedItem = null; // this works
        Page1.page1.LV1.SelectedItem = selected; // this doesn't work
    }
}

I've found that inside the if condition, assignment to null changes the SelectedItem of LV1 to null but the next line doesn't change it to selected ( it remains null ).

Body:
add after assignment:

Page1.page1.LV1.Select();


答:
Your function needs to be explicit about returning something with e.g. -> String Also do-catch is for methods that can throw an error. It seems like you need to take a look at how to use optionals. Optionals can have a value or they can have no value.

```<code>fun processData(data: String) -> String {
   var result: String?
   // Do some processing and assign the result to result variable

  guard let result = result else { return "Not Found" }

  return result
}
</code>```

Title: Using Do/Catch in Swift

Body:
Your function needs to be explicit about returning something with e.g. -> String Also do-catch is for methods that can throw an error. It seems like you need to take a look at how to use optionals. Optionals can have a value or they can have no value.

fun processData(data: String) -> String {
   var result: String?
   // Do some processing and assign the result to result variable

  guard let result = result else { return "Not Found" }

  return result
}


问:
TokenMismatchException after moving user model inside custom directory in laravel 5.4
First, I moved user model inside folder App/Models/Frontend. After that:

I update namespace of user model to namespace App\Models\Frontend

Then after, update config/auth to

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\Frontend\User::class,
    ],

Also, I had already tried php artisan config:cache and php artisan cache:clear. I have not modified composer.json file but still tries the luck with composer autoload but no sign seen.

Errors:

```<code>(1/1) TokenMismatchException
in VerifyCsrfToken.php (line 68)
at VerifyCsrfToken->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ShareErrorsFromSession.php (line 49)
at ShareErrorsFromSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in StartSession.php (line 64)
at StartSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in AddQueuedCookiesToResponse.php (line 37)
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in EncryptCookies.php (line 59)
at EncryptCookies->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Router.php (line 576)
at Router->runRouteWithinStack(object(Route), object(Request))
in Router.php (line 535)
at Router->dispatchToRoute(object(Request))
in Router.php (line 513)
at Router->dispatch(object(Request))
in Kernel.php (line 176)
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ValidatePostSize.php (line 27)
at ValidatePostSize->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in CheckForMaintenanceMode.php (line 46)
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Kernel.php (line 151)
at Kernel->sendRequestThroughRouter(object(Request))
in Kernel.php (line 116)
at Kernel->handle(object(Request))
in index.php (line 53)
at require_once('C:\\wamp64\\www\\birthday_notifier\\public\\index.php')
in server.php (line 21)
</code>```

Any suggestion would be appreciable.

答:
I finally found the answer. In case if you too are in similar situation. You need to update following files too in addition to config/auth.php

app/Http/Controllers/RegisterController.php

config/services.php

database/factories/ModelFactory.php

Body:
First, I moved user model inside folder App/Models/Frontend. After that:

I update namespace of user model to namespace App\Models\Frontend

Then after, update config/auth to

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\Frontend\User::class,
    ],

Also, I had already tried php artisan config:cache and php artisan cache:clear. I have not modified composer.json file but still tries the luck with composer autoload but no sign seen.

Errors:

(1/1) TokenMismatchException
in VerifyCsrfToken.php (line 68)
at VerifyCsrfToken->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ShareErrorsFromSession.php (line 49)
at ShareErrorsFromSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in StartSession.php (line 64)
at StartSession->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in AddQueuedCookiesToResponse.php (line 37)
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in EncryptCookies.php (line 59)
at EncryptCookies->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Router.php (line 576)
at Router->runRouteWithinStack(object(Route), object(Request))
in Router.php (line 535)
at Router->dispatchToRoute(object(Request))
in Router.php (line 513)
at Router->dispatch(object(Request))
in Kernel.php (line 176)
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
in Pipeline.php (line 30)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in ValidatePostSize.php (line 27)
at ValidatePostSize->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in CheckForMaintenanceMode.php (line 46)
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing\{closure}(object(Request))
in Pipeline.php (line 102)
at Pipeline->then(object(Closure))
in Kernel.php (line 151)
at Kernel->sendRequestThroughRouter(object(Request))
in Kernel.php (line 116)
at Kernel->handle(object(Request))
in index.php (line 53)
at require_once('C:\\wamp64\\www\\birthday_notifier\\public\\index.php')
in server.php (line 21)

Any suggestion would be appreciable.


问:
No connection string named 'MyEntities' could be found in the application config file
I am using entity framework and ASP.NET MVC 4 to build an application

My solution is split into two projects;

A class library that includes my data model (.edmx) file and a few custom interfaces

The 'container' MVC project that references the class library above

My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error:

No connection string named 'MyEntities' could be found in the
  application config file.

I guess the problem has something to do with the fact that connection string lies within the app.config of the class library rather than the MVC project.

Does anyone have any suggestions?

答:
Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:

```<code> <connectionStrings>

  <add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />

  </connectionStrings>
</code>```

If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:

```<code>MyEntities: DbContext
 {
   public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
 }
</code>```

Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).

Body:
Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:

 <connectionStrings>

  <add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />

  </connectionStrings>

If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:

MyEntities: DbContext
 {
   public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
 }

Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).


问:
Echo the bottom line of a CSV
I am attempting to echo the bottom line only of a .csv file. I echo the file in reverse order (as shown below) but I'm not sure how to only echo the top line of this. Please note that the csv variable, constantly changing.

Here is my php:

<?php
$file = file("file.csv");
$file = array_reverse($file);
foreach($file as $f){
    echo $f."
";
}
?>```

答:
Maybe try the end function see http://php.net/manual/en/function.end.php

```<code><?php
$file = file("file.csv"); // You take care of reading all the lines.
$lastline = end($file);
?>
</code>```

Title: Echo the bottom line of a CSV

Body:
Maybe try the end function see http://php.net/manual/en/function.end.php

<?php
$file = file("file.csv"); // You take care of reading all the lines.
$lastline = end($file);
?>


问:
How to compare to List<WebElement> in webdriver?
I am trying to automate Dual list Box testing. I want to compare the selected values(left side) vs moved values (into right side list). Here is the code.

```<code>Select allFromListData = new Select(listData);
    // values selection
    allFromListData.selectByIndex(0);
    allFromListData.selectByVisibleText("Helena");
    List<WebElement> selectedList=allFromListData.getAllSelectedOptions();
    //clicking on add button

    for(int i=0;i<selectedList.size();i++)
        System.out.println(selectedList.get(i).getText());
    WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
    addButton.click();

    //Verification of selected content...
    WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
    Select allToListData = new Select(toListData);
    List<WebElement> movedData=allToListData.getOptions();
</code>```

Question is how to compare the data between List<WebElement> selectedList=allFromListData.getAllSelectedOptions(); and List<WebElement> movedData=allToListData.getOptions();

答:
I assume, you want to compare the list of selected items string not the list of web elements as getOptions() method will return list of web elements. Logic is simple, first take the list of values from the list before and after move. Then sort the both of the list of values and compare/assert for equality as given below.</p>

```<code> Select allFromListData = new Select(listData);
    // values selection
    allFromListData.selectByIndex(0);
    allFromListData.selectByVisibleText("Helena");
    List<WebElement> selectedList=allFromListData.getAllSelectedOptions();

    //add selected Items to list
    List<String> lstSelectedItem=new ArrayList<String>();
    for(int i=0;i<selectedList.size();i++){
        System.out.println(selectedList.get(i).getText());
        lstSelectedItem.add(selectedList.get(i).getText());
    }

    //clicking on add button
    WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
    addButton.click();

    //Verification of selected content...
    WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
    Select allToListData = new Select(toListData);
    List<WebElement> movedData=allToListData.getOptions();

    //add moved Items to list
    List<String> lstMovedItem=new ArrayList<String>();
    for(int i=0;i<movedData.size();i++){
        System.out.println(movedData.get(i).getText());
        lstMovedItem.add(movedData.get(i).getText());
    }

    //sort the items
    Collections.sort(lstSelectedItem);
    Collections.sort(lstMovedItem);

    //verify the lists are equal
    Assert.assertEquals(lstSelectedItem, lstMovedItem);
</code>```

Body:
I am trying to automate Dual list Box testing. I want to compare the selected values(left side) vs moved values (into right side list). Here is the code.

Select allFromListData = new Select(listData);
    // values selection
    allFromListData.selectByIndex(0);
    allFromListData.selectByVisibleText("Helena");
    List<WebElement> selectedList=allFromListData.getAllSelectedOptions();
    //clicking on add button

    for(int i=0;i<selectedList.size();i++)
        System.out.println(selectedList.get(i).getText());
    WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
    addButton.click();

    //Verification of selected content...
    WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
    Select allToListData = new Select(toListData);
    List<WebElement> movedData=allToListData.getOptions();

Question is how to compare the data between List<WebElement> selectedList=allFromListData.getAllSelectedOptions(); and List<WebElement> movedData=allToListData.getOptions();

Body:
I assume, you want to compare the list of selected items string not the list of web elements as getOptions() method will return list of web elements. Logic is simple, first take the list of values from the list before and after move. Then sort the both of the list of values and compare/assert for equality as given below.

 Select allFromListData = new Select(listData);
    // values selection
    allFromListData.selectByIndex(0);
    allFromListData.selectByVisibleText("Helena");
    List<WebElement> selectedList=allFromListData.getAllSelectedOptions();

    //add selected Items to list
    List<String> lstSelectedItem=new ArrayList<String>();
    for(int i=0;i<selectedList.size();i++){
        System.out.println(selectedList.get(i).getText());
        lstSelectedItem.add(selectedList.get(i).getText());
    }

    //clicking on add button
    WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
    addButton.click();

    //Verification of selected content...
    WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
    Select allToListData = new Select(toListData);
    List<WebElement> movedData=allToListData.getOptions();

    //add moved Items to list
    List<String> lstMovedItem=new ArrayList<String>();
    for(int i=0;i<movedData.size();i++){
        System.out.println(movedData.get(i).getText());
        lstMovedItem.add(movedData.get(i).getText());
    }

    //sort the items
    Collections.sort(lstSelectedItem);
    Collections.sort(lstMovedItem);

    //verify the lists are equal
    Assert.assertEquals(lstSelectedItem, lstMovedItem);


问:
Null parameter in controller from ajax
When a user clicks a save button, a JavaScript function uses AJAX to call the Controller and send over JSON data about the objects.

JavaScript Function

```<code>$.ajax({
        url: "/Data/sendFridgeItems?items=" + JSON.stringify($scope.items.data),
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });
</code>```

Controller

```<code>[HttpPost]
    public ActionResult SendFridgeItems(string items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items);
        foreach (fridge item in fridgeItems)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }
</code>```

It works, but I don't think the way of sending my data through the url parameter is correct in my situation, because the data will be big enough. I wanted to know if there is a better way to send my data to the controller?

I tried to send it this way, but the controller receives null value.

```<code>$.ajax({
        url: "/Data/sendFridgeItems",
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });
</code>```

JSON of $scope.items.data

```<code>[{"id":2,"name":"Item1","count":2,"type":"pcs.","purchased":"12/09/2017","wasted":"15/10/2017","cam":"Freezer","comment":"no comment","$$hashKey":"object:38"},{"id":3,"name":"Item2","count":30,"type":"g.","purchased":"15/01/1880","wasted":"21/03/1882","cam":"Cooler","comment":"commented","$$hashKey":"object:39"}]
</code>```

$scope.items

```<code>$scope.items = {
    "count": 2,
    "data": [
      {
          "name": "Item1",
          "count": 2,
          "type": "pcs.",
          "purchased": "12/09/2017",
          "wasted": "15/10/2017",
          "cam": "Freezer",
          "comment": "no comment"
      },
  {
          "name": "Item2",
          "count": 30,
          "type": "g.",
          "purchased": "15/01/1880",
          "wasted": "21/03/1882",
          "cam": "Cooler",
          "comment": "Commented"
      }
    ]
};
</code>```

Fixed Controller For N.Ivanov's solution (this controller+ N.Ivanov's ajax = solution)

```<code>public ActionResult SendFridgeItems(fridge[] items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items.ToString());
        foreach (fridge item in items)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }
</code>```

答:
The data field in ajax takes in an Object, you are giving it a string. Try and supply only your object, assuming that $scope.items.data is an object. If you give a bit more information on what $scope variable is, then I can give you a better answer.

Code:

$.ajax({
        url: "/Data/sendFridgeItems",
        type: "POST",
        d̶a̶t̶a̶:̶ ̶$̶s̶c̶o̶p̶e̶.̶i̶t̶e̶m̶s̶.̶d̶a̶t̶a̶,̶
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

Hope this helps!

EDIT:

Further inspection after you have provided the contents of $scope.items.data led me to notice that $scope.items.data is an array of objects. So in order for the ajax to work and actually supply valid JSON, try the following code:
$.ajax({
        url: "/Data/sendFridgeItems",
        type: "POST",
        data: { "items": $scope.items.data },
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

I have verified that { "item": $scope.items.data } is a valid JSON through JSONLint

Hope this solves your problem!

Title: Null parameter in controller from ajax

Body:
When a user clicks a save button, a JavaScript function uses AJAX to call the Controller and send over JSON data about the objects.

JavaScript Function

$.ajax({
        url: "/Data/sendFridgeItems?items=" + JSON.stringify($scope.items.data),
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

Controller

[HttpPost]
    public ActionResult SendFridgeItems(string items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items);
        foreach (fridge item in fridgeItems)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }

It works, but I don't think the way of sending my data through the url parameter is correct in my situation, because the data will be big enough. I wanted to know if there is a better way to send my data to the controller?

I tried to send it this way, but the controller receives null value.

$.ajax({
        url: "/Data/sendFridgeItems",
        type: "POST",
        data: JSON.stringify($scope.items.data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            console.log("good!");
        },
        error: function () {
            console.log("error");
        }
    });

JSON of $scope.items.data

[{"id":2,"name":"Item1","count":2,"type":"pcs.","purchased":"12/09/2017","wasted":"15/10/2017","cam":"Freezer","comment":"no comment","$$hashKey":"object:38"},{"id":3,"name":"Item2","count":30,"type":"g.","purchased":"15/01/1880","wasted":"21/03/1882","cam":"Cooler","comment":"commented","$$hashKey":"object:39"}]

$scope.items

$scope.items = {
    "count": 2,
    "data": [
      {
          "name": "Item1",
          "count": 2,
          "type": "pcs.",
          "purchased": "12/09/2017",
          "wasted": "15/10/2017",
          "cam": "Freezer",
          "comment": "no comment"
      },
  {
          "name": "Item2",
          "count": 30,
          "type": "g.",
          "purchased": "15/01/1880",
          "wasted": "21/03/1882",
          "cam": "Cooler",
          "comment": "Commented"
      }
    ]
};

Fixed Controller For N.Ivanov's solution (this controller+ N.Ivanov's ajax = solution)

public ActionResult SendFridgeItems(fridge[] items)
    {
        fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items.ToString());
        foreach (fridge item in items)
        {
            bool exists = cookDB.fridges.AsEnumerable()
                .Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
            if (!exists)
            {
                cookDB.fridges.Add(item);
                cookDB.SaveChangesAsync();
            }
        }
        return null;
    }


问:
Reverse Engineering C++ code using "Enterprise Architect"
It is again a sort of "how to do it properly" question. Sorry if someone is annoyed.

I've got to understand ca 150 TLOCs of C/C++ mixture. I've imported the code in UML-Tool "Enterprise Architect" and got a messy chart. Many Structs and Enums had anonymous names because of this C-ish constructs: typedef struct/enum {...} MyType;

In second run I've converted  it to C++ form: struct/enum  MyType{...}; but got a bunch of unrelated structs. Unfortunately, Enterprise Architect doesn't resolve typedefs. e.g. no relations between A, B and C were recognized:

```<code>struct A;
struct B;
typedef A *PtrA;
typedef List<B> BList;
struct C{ PtrA pA; BList lB; };
</code>```

Thanks to throughout naming convention, I was able to replace all typedefs by original type like this:

```<code>struct C{ A pA; B lB; };
</code>```

Now importing source-code in "Enterprise Architect" gave a nice diagram with all relations.
Of cause, the code doesn't compile, and is not the same. All changes in code require an annoying conversion for making this "pseudo" code understandable by EA again. Therefore my questions:

Is there any possibility to teach EA
recognizing the original types?

Do other UML-Tools recognize the types
(and create relations between them)
more robust?

Thank you very much for any advice!
Valentin Heinitz

答: I have Enterprise Architect, and almost invariably for doing what you are attempting on a large code body I use doxygen instead.  It generates both class and call graphs. Use it with GraphViz and "UML-style" class diagrams, and you have a reasonably good code navigation and comprehension tool, with flexible configuration to add or exclude detail as necessary.</p>

Body:
It is again a sort of "how to do it properly" question. Sorry if someone is annoyed.

I've got to understand ca 150 TLOCs of C/C++ mixture. I've imported the code in UML-Tool "Enterprise Architect" and got a messy chart. Many Structs and Enums had anonymous names because of this C-ish constructs: typedef struct/enum {...} MyType;

In second run I've converted  it to C++ form: struct/enum  MyType{...}; but got a bunch of unrelated structs. Unfortunately, Enterprise Architect doesn't resolve typedefs. e.g. no relations between A, B and C were recognized:

struct A;
struct B;
typedef A *PtrA;
typedef List BList;
struct C{ PtrA pA; BList lB; };

Thanks to throughout naming convention, I was able to replace all typedefs by original type like this:

struct C{ A pA; B lB; };

Now importing source-code in "Enterprise Architect" gave a nice diagram with all relations.
Of cause, the code doesn't compile, and is not the same. All changes in code require an annoying conversion for making this "pseudo" code understandable by EA again. Therefore my questions:

Is there any possibility to teach EA
recognizing the original types?

Do other UML-Tools recognize the types
(and create relations between them)
more robust?

Thank you very much for any advice!
Valentin Heinitz