问:
Jquery Mobile Swipe events are not firing
Im using bootstrap and want to enable swipe gestures to an img carousel. Im registering on swipe handlers for the carousel items like:

```<code>    $(".carousel-inner").on( "swipe", ".item",  function () {
        console.log("swiped");
    });
</code>```

Doing the same to register a click event handler works fine so the selection of elements seems to work. Also ($.mobile) returns true so jquery mobile is loaded properly.

I have my smartphone connected via usb cable and track the debugging via chrome developer tools. Click on the device triggers the click event but swipe wont do anything.

Any guesses why now swipe events are fired?

答: It turned out jquery mobile was not loaded properly due to incompatible version of jquery core (version 3.1.1.). Changed the version to 1.11.1 and now everything is working fine.</p>

Body:
Im using bootstrap and want to enable swipe gestures to an img carousel. Im registering on swipe handlers for the carousel items like:

    $(".carousel-inner").on( "swipe", ".item",  function () {
        console.log("swiped");
    });

Doing the same to register a click event handler works fine so the selection of elements seems to work. Also ($.mobile) returns true so jquery mobile is loaded properly.

I have my smartphone connected via usb cable and track the debugging via chrome developer tools. Click on the device triggers the click event but swipe wont do anything.

Any guesses why now swipe events are fired?


来源: stackexchange

问:
'Insert' Cursor for Terminal on Mac OS
My terminal is using the 'insert' cursor, like a block instead of a line, and I want to change it back to a normal cursor. This just randomly started happening and I don't know how to fix it - pressing 'Insert' on the keyboard doesn't do anything.

What my cursor looks like in terminal (problem):

What my cursor looks like everywhere else (how I want it in terminal too):

答:
Try the Settings window: command + ,

In the Cursor section select Vertical Bar:

ContentLicense: CC BY-SA 3.0

Title: 'Insert' Cursor for Terminal on Mac OS


问:
NLTK is not working in docker
I want to run a nltk service in docker. However I always get the error message "'nltk' is not a package". Are you able to figure out what is going wrong? During build everything works fine, the nltk version is printed. When starting the container with docker-compose up nltk I get

$ docker-compose up nltk

```<code>Recreating nltk
Attaching to nltk
nltk          | Traceback (most recent call last):
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          | ModuleNotFoundError: No module named 'nltk.corpus'; 'nltk' is not a package
</code>```

docker-compose.yml

```<code>nltk:
    build: docker/nltk
    container_name: nltk
    volumes:
      - ./volumes/nltk/var/www/nltk.py:/var/www/nltk.py
    environment:
      HOME: /var/www
</code>```

Dockerfile

```<code>FROM python:3.6

RUN mkdir /var/www
ENV HOME /var/www
WORKDIR /var/www
RUN pip install -U nltk
RUN pip install -U numpy
RUN python -m nltk.downloader -d $HOME/nltk_data all
RUN python -c "import nltk"
RUN python -c "import nltk; print(nltk.__version__)"

EXPOSE 80

CMD [ "python", "/var/www/nltk.py" ]
</code>```

nltk.py

```<code>import nltk
from nltk.corpus import brown

brown.words()
</code>```

答:
final Dockerfile

```<code>FROM python:3.6

ENV NLTK_DATA /usr/share/nltk_data

RUN pip install -U nltk
RUN pip install -U numpy
RUN python -m nltk.downloader -d /usr/share/nltk_data all

EXPOSE 80

WORKDIR /var/www

CMD [ "python", "/var/www/main.py" ]
</code>```

final docker-compose

```<code>nltk:
    build: docker/nltk
    container_name: nltk
    volumes:
      - ./volumes/nltk/var/www/main.py:/var/www/main.py
</code>```

Title: NLTK is not working in docker

Body:
I want to run a nltk service in docker. However I always get the error message "'nltk' is not a package". Are you able to figure out what is going wrong? During build everything works fine, the nltk version is printed. When starting the container with docker-compose up nltk I get

$ docker-compose up nltk

Recreating nltk
Attaching to nltk
nltk          | Traceback (most recent call last):
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          | ModuleNotFoundError: No module named 'nltk.corpus'; 'nltk' is not a package

docker-compose.yml

nltk:
    build: docker/nltk
    container_name: nltk
    volumes:
      - ./volumes/nltk/var/www/nltk.py:/var/www/nltk.py
    environment:
      HOME: /var/www

Dockerfile

FROM python:3.6

RUN mkdir /var/www
ENV HOME /var/www
WORKDIR /var/www
RUN pip install -U nltk
RUN pip install -U numpy
RUN python -m nltk.downloader -d $HOME/nltk_data all
RUN python -c "import nltk"
RUN python -c "import nltk; print(nltk.__version__)"

EXPOSE 80

CMD [ "python", "/var/www/nltk.py" ]

nltk.py

import nltk
from nltk.corpus import brown

brown.words()

Body:
final Dockerfile

FROM python:3.6

ENV NLTK_DATA /usr/share/nltk_data

RUN pip install -U nltk
RUN pip install -U numpy
RUN python -m nltk.downloader -d /usr/share/nltk_data all

EXPOSE 80

WORKDIR /var/www

CMD [ "python", "/var/www/main.py" ]

final docker-compose

nltk:
    build: docker/nltk
    container_name: nltk
    volumes:
      - ./volumes/nltk/var/www/main.py:/var/www/main.py


问:
Bad request when trying to delete from the dead-letter queue
I am trying to delete messages from the dead-letter queue using this code:

```<code>QueueDescription qd = _queueManager.GetQueue(queueID);
QueueClient qc = _senderFactory.CreateQueueClient(queueID, ReceiveMode.ReceiveAndDelete);

received = qc.ReceiveBatch(deadMessageCount);
while (received != null && received.Count<BrokeredMessage>() > 0)
  received = qc.ReceiveBatch(deadMessageCount); // just in case
</code>```

And keep getting:

The remote server returned an error: (400) Bad Request. The specified HTTP verb (GET) is not valid. TrackingId:104cc11d-21b5-440c-adde-e9ce9afb0603_G25,TimeStamp:1/24/2015 8:44:10 AM

What is wrong here?

答:
I ran into this same problem trying to get the count from the dead letter queue. It looks like the deadletterqueue doesn't allow you to get a count directly, you get it from the MessageCountDetails of the normal Queue.

Doesn't Work

```<code>NamespaceManager nsmgr = Microsoft.ServiceBus.NamespaceManager
    .CreateFromConnectionString(connectionString);
return  nsmgr.GetQueue(QueueClient.FormatDeadLetterPath(QueueName))
    .MessageCountDetails.DeadLetterMessageCount;
</code>```

Does Work

```<code>return nsmgr.GetQueue(QueueName).MessageCountDetails.DeadLetterMessageCount;
</code>```

Remember to perform operations on the deadletterqueue you still need to specify the correct p it in the queue client.

```<code>QueueClient.CreateFromConnectionString(connectionString,
    QueueClient.FormatDeadLetterPath(QueueName));
</code>```

Body:
I am trying to delete messages from the dead-letter queue using this code:

QueueDescription qd = _queueManager.GetQueue(queueID);
QueueClient qc = _senderFactory.CreateQueueClient(queueID, ReceiveMode.ReceiveAndDelete);

received = qc.ReceiveBatch(deadMessageCount);
while (received != null && received.Count<BrokeredMessage>() > 0)
  received = qc.ReceiveBatch(deadMessageCount); // just in case

And keep getting:

The remote server returned an error: (400) Bad Request. The specified HTTP verb (GET) is not valid. TrackingId:104cc11d-21b5-440c-adde-e9ce9afb0603_G25,TimeStamp:1/24/2015 8:44:10 AM

What is wrong here?

Body:
I ran into this same problem trying to get the count from the dead letter queue. It looks like the deadletterqueue doesn't allow you to get a count directly, you get it from the MessageCountDetails of the normal Queue.

Doesn't Work

NamespaceManager nsmgr = Microsoft.ServiceBus.NamespaceManager
    .CreateFromConnectionString(connectionString);
return  nsmgr.GetQueue(QueueClient.FormatDeadLetterPath(QueueName))
    .MessageCountDetails.DeadLetterMessageCount;

Does Work

return nsmgr.GetQueue(QueueName).MessageCountDetails.DeadLetterMessageCount;

Remember to perform operations on the deadletterqueue you still need to specify the correct p it in the queue client.

QueueClient.CreateFromConnectionString(connectionString,
    QueueClient.FormatDeadLetterPath(QueueName));


问:
How to rotate X-axis labels in bokeh figure?
I'm just starting to use Bokeh. Below I create some args I use for the rect figure.

```<code>x_length = var_results.index * 5.5
</code>```

Multiplying the index by 5.5 gave me more room between labels.

```<code>names = var_results.Feature.tolist()
y_length = var_results.Variance
y_center = var_results.Variance/2
</code>```

var_results is a Pandas dataframe that has a typical, sequential, non-repeating index. var_results also has a column Features that is strings of non-repeated, names, and finally it has a column Variance which is dtype float.

```<code>r = figure(x_range = names,
           y_range = (-0.05,.3),
           active_scroll = 'wheel_zoom',
           x_axis_label = 'Features',
           y_axis_label = 'Variance')

r.rect(x_length,
       y_center,
       width=1,
       height=y_length,
       color = "#ff1200")
output_notebook()
show(r)
</code>```

I'm essentially making a bar chart with rectangles. Bokeh seems to be very customizable. But my graph looks rough around the edges, literally.

As you can see there is an ugly smudge just below the chart and above the x-axis title 'Features'. This is the label titles (technically the rectangle titles). How do I create space for and perhaps rotate to 45 degrees the labels so that they are readable and not just an overlapping mess?

答:
In order to rotate the labels e.g. by 90 degrees to the left, you can set major_label_orientation to π/2. This can be done either when creating the axis element (as a kwarg to the axis constructor if you are using low level plotting) or also after you have created a plot/figure, for instance by:

```<code>p.xaxis.major_label_orientation = math.pi/2

# or alternatively:
p.xaxis.major_label_orientation = "vertical"
</code>```

See also this example in the documentation.

Body:
I'm just starting to use Bokeh. Below I create some args I use for the rect figure.

x_length = var_results.index * 5.5

Multiplying the index by 5.5 gave me more room between labels.

names = var_results.Feature.tolist()
y_length = var_results.Variance
y_center = var_results.Variance/2

var_results is a Pandas dataframe that has a typical, sequential, non-repeating index. var_results also has a column Features that is strings of non-repeated, names, and finally it has a column Variance which is dtype float.

r = figure(x_range = names,
           y_range = (-0.05,.3),
           active_scroll = 'wheel_zoom',
           x_axis_label = 'Features',
           y_axis_label = 'Variance')

r.rect(x_length,
       y_center,
       width=1,
       height=y_length,
       color = "#ff1200")
output_notebook()
show(r)

I'm essentially making a bar chart with rectangles. Bokeh seems to be very customizable. But my graph looks rough around the edges, literally.

As you can see there is an ugly smudge just below the chart and above the x-axis title 'Features'. This is the label titles (technically the rectangle titles). How do I create space for and perhaps rotate to 45 degrees the labels so that they are readable and not just an overlapping mess?

Body:
In order to rotate the labels e.g. by 90 degrees to the left, you can set major_label_orientation to π/2. This can be done either when creating the axis element (as a kwarg to the axis constructor if you are using low level plotting) or also after you have created a plot/figure, for instance by:

p.xaxis.major_label_orientation = math.pi/2

# or alternatively:
p.xaxis.major_label_orientation = "vertical"

See also this example in the documentation.

ContentLicense: CC BY-SA 4.0


问:
Count lowercase letters till the input is string
I wrote a short code in C which count the lowercase letters (only letters) and it'll stop working when I enter a number or something else. Here is the code:

```<code>char letter;
int num=0;
do
    if(islower(letter = getchar()))
       num++;
while(isalpha(letter));
printf("%d", num);
return 0;
</code>```

My problem is that it isn't working properly (only print "1" as result).
And it has to be stopped when the next character isn't alphabetical letter. Not sure that part is right.

Any idea what did I wrong? Thanks.

答:
The problem is that, after inputting a single character, the subsequent call to getchar() returns a newline character, as the '\n' from the return key is buffered. So, the first iteration of

```<code> do
    if (islower(letter = getchar()))
        num++;
 while (isalpha(letter));
</code>```

works, but the program displays "1" as the islower() call returns false when the newline is processed.

To fix this, use a while loop to eat away the extra newlines. You could do it as such:

```<code>do {
    while ((letter = getchar()) == '\n')
        ;

    if (islower(letter))
        num++;
} while (isalpha(letter));
</code>```

Body:
I wrote a short code in C which count the lowercase letters (only letters) and it'll stop working when I enter a number or something else. Here is the code:

char letter;
int num=0;
do
    if(islower(letter = getchar()))
       num++;
while(isalpha(letter));
printf("%d", num);
return 0;

My problem is that it isn't working properly (only print "1" as result).
And it has to be stopped when the next character isn't alphabetical letter. Not sure that part is right.

Any idea what did I wrong? Thanks.

Body:
The problem is that, after inputting a single character, the subsequent call to getchar() returns a newline character, as the '\n' from the return key is buffered. So, the first iteration of

 do
    if (islower(letter = getchar()))
        num++;
 while (isalpha(letter));

works, but the program displays "1" as the islower() call returns false when the newline is processed.

To fix this, use a while loop to eat away the extra newlines. You could do it as such:

do {
    while ((letter = getchar()) == '\n')
        ;

    if (islower(letter))
        num++;
} while (isalpha(letter));


问:
wield behavior of Element.scrollIntoView()
I'm using Element.scrollIntoView(). The scrolling is working, but it breaks the layout of my whole page at the same time. Following is the demo:

* {
  margin: 0;
  padding: 0;
}

html, body {
  width: 100%;
  height: 100%;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: lightgray;
}

ul {
  position: absolute;
  width: 100%;
  height: 300px;
  left: 0;
  bottom: 0;
  background-color: gray;
  overflow-y: scroll;
}

li {
  list-style: none;
}

#div {
  position: absolute;
  width: 100%;
  height: 300px;
  left: 0;
  bottom: -300px;
  background-color: darkgray;
}

button {
  position: absolute;
  right: 0;
  bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=content>
  <!-- it's the ul to scroll, staying at the bottom of the page -->
  <ul>
    <li id=li>abc</li>
    <li>def</li>
  </ul>
  <!-- it's the div hidden under the bottom edge of the page -->
  <div id=div>i should stay hidden.</div>
  <button onclick=li.scrollIntoView();>scrollIntoView</button>
</div></code>```

I hide a
 under the bottom edge of the page. When I scrollIntoView the 1st
 in
, the hidden
 is pulled out. Not only the
, the whole content of the page is pulled up for 300px.

I expect it to simply scroll the
 into view of
. Why is it affecting the layout of the whole page?

答:
I think I find the answer myself. See this answer. It's about anchors, but scrollIntoView share the same mechanism internally I think.

The browser will try best to ensure the element is visible. When it's in a container, it will first scroll the container to a position with best visibility, so the contents are pulled up.

Body:
I'm using Element.scrollIntoView(). The scrolling is working, but it breaks the layout of my whole page at the same time. Following is the demo:

* {
  margin: 0;
  padding: 0;
}

html, body {
  width: 100%;
  height: 100%;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: lightgray;
}

ul {
  position: absolute;
  width: 100%;
  height: 300px;
  left: 0;
  bottom: 0;
  background-color: gray;
  overflow-y: scroll;
}

li {
  list-style: none;
}

#div {
  position: absolute;
  width: 100%;
  height: 300px;
  left: 0;
  bottom: -300px;
  background-color: darkgray;
}

button {
  position: absolute;
  right: 0;
  bottom: 0;
}

abc

def

i should stay hidden.

  <button onclick=li.scrollIntoView();>scrollIntoView</button>

I hide a
 under the bottom edge of the page. When I scrollIntoView the 1st
 in
, the hidden
 is pulled out. Not only the
, the whole content of the page is pulled up for 300px.

I expect it to simply scroll the
 into view of
. Why is it affecting the layout of the whole page?


问:
DataMaps.js - Network Weather-map (inbound and outbound arcs)
I am trying to use Datamaps using the arcs and circles option to create a network weathermap.

The basic issue I'm hitting is that there are inbound and outbound connections in a network and I'd like to be able to visualize them as separate entities. To avoid the incoming and outgoing overlapping, I tried doing a simple longitude and latitude offset (- .2 each) to "offset" the path. What I'm seeing is that they cross-over each other.

Any ideas on how I might be able to do this?

Current Map Image

答:
I had the same issue take a look at https://github.com/cpmarvin/d3js_weathermap. If you have parallel links then you need get the nr of links btw nodes and do an offset. Take a look at https://github.com/cpmarvin/d3js

Hope it helps.

```<code>.attr("d", function(d) {
    //find middle value of the link and calculate path
    var dx = d.target.x - d.source.x,
        dy = d.target.y - d.source.y,
        dr = Math.sqrt(dx * dx + dy * dy);

    var endX = (d.target.x + d.source.x) / 2;
    var endY = (d.target.y + d.source.y) / 2;

    var len = dr - ((dr/2) * Math.sqrt(3));
    endX = endX + (1 * len/dr);
    endY = endY + (-1 * len/dr);

    return "M" + d.source.x + "," + d.source.y + "L" + endX + "," + endY;
} )
</code>```

this is based on :

Display an arrow head in the middle of D3 force layout link

Body:
I had the same issue take a look at https://github.com/cpmarvin/d3js_weathermap. If you have parallel links then you need get the nr of links btw nodes and do an offset. Take a look at https://github.com/cpmarvin/d3js

Hope it helps.

.attr("d", function(d) {
    //find middle value of the link and calculate path
    var dx = d.target.x - d.source.x,
        dy = d.target.y - d.source.y,
        dr = Math.sqrt(dx * dx + dy * dy);

    var endX = (d.target.x + d.source.x) / 2;
    var endY = (d.target.y + d.source.y) / 2;

    var len = dr - ((dr/2) * Math.sqrt(3));
    endX = endX + (1 * len/dr);
    endY = endY + (-1 * len/dr);

    return "M" + d.source.x + "," + d.source.y + "L" + endX + "," + endY;
} )

this is based on :

Display an arrow head in the middle of D3 force layout link


问:
git checkout .(dot) interactive
I know git checkout . is one of the most dangerous commands in the git universe (rightfully so). Is there a way to make it interactive? Like how the rm command works with -i option.

I am looking for something along the lines of

```<code>git checkout . -i
</code>```

答:
git checkout (and git add as well) support the -p option, which will ask you for every hunk, like this:

```<code>diff --git a/post.so b/post.so
index b111bdd..ddba6b1 100644
--- a/post.so
+++ b/post.so
@@ -1 +1,3 @@
-`git checkout` (and `git add` as well) support the `-p` option.
+`git checkout` (and `git add` as well) support the `-p` option, which will ask you for every hunk, like this:
+
+foo bar
Discard this hunk from worktree [y,n,q,a,d,/,e,?]?
</code>```

For every hunk you can answer:

```<code>y - discard this hunk from worktree
n - do not discard this hunk from worktree
q - quit; do not discard this hunk or any of the remaining ones
a - discard this hunk and all later hunks in the file
d - do not discard this hunk or any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
</code>```

Title: git checkout .(dot) interactive

Body:
I know git checkout . is one of the most dangerous commands in the git universe (rightfully so). Is there a way to make it interactive? Like how the rm command works with -i option.

I am looking for something along the lines of

git checkout . -i

Body:
git checkout (and git add as well) support the -p option, which will ask you for every hunk, like this:

diff --git a/post.so b/post.so
index b111bdd..ddba6b1 100644
--- a/post.so
+++ b/post.so
@@ -1 +1,3 @@
-`git checkout` (and `git add` as well) support the `-p` option.
+`git checkout` (and `git add` as well) support the `-p` option, which will ask you for every hunk, like this:
+
+foo bar
Discard this hunk from worktree [y,n,q,a,d,/,e,?]?

For every hunk you can answer:

y - discard this hunk from worktree
n - do not discard this hunk from worktree
q - quit; do not discard this hunk or any of the remaining ones
a - discard this hunk and all later hunks in the file
d - do not discard this hunk or any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help


问:
Is it possible to use boost accumulators with vectors?
I wanted to use boost accumulators to calculate statistics of a variable that is a vector. Is there a simple way to do this. I think it's not possible to use the dumbest thing:

```<code>  using namespace boost::accumulators;
  //stuff...

  accumulator_set<vector<double>, stats<tag::mean> > acc;
  vector<double> some_vetor;
  //stuff
  some_vector = doStuff();
  acc(some_vector);
</code>```

maybe this is obvious, but I tried anyway. :P

What I wanted was to have an accumulator that would calculate a vector which is the mean of the components of many vectors. Is there an easy way out?

EDIT:

I don't know if I was thoroughly clear. I don't want this:

```<code> for_each(vec.begin(), vec.end(),acc);
</code>```

This would calculate the mean of the entries of a given vector. What I need is different. I have a function that will spit vectors:

```<code> vector<double> doSomething();
 // this is a monte carlo simulation;
</code>```

And I need to run this many times and calculate the vectorial mean of those vectors:

```<code>  for(int i = 0; i < numberOfMCSteps; i++){
  vec = doSomething();
  acc(vec);
  }
  cout << mean(acc);
</code>```

And I want mean(acc) to be a vector itself, whose entry [i] would be the means of the entries [i] of the accumulated vectors.

Theres a hint about this in the docs of Boost, but nothing explicit. And I'm a bit dumb. :P

答:
And what about the documentation?</p>

```<code>// The data for which we wish to calculate statistical properties:
std::vector< double > data( /* stuff */ );

// The accumulator set which will calculate the properties for us:
accumulator_set< double, features< tag::min, tag::mean > > acc;

// Use std::for_each to accumulate the statistical properties:
acc = std::for_each( data.begin(), data.end(), acc );
</code>```

Body:
I wanted to use boost accumulators to calculate statistics of a variable that is a vector. Is there a simple way to do this. I think it's not possible to use the dumbest thing:

  using namespace boost::accumulators;
  //stuff...

  accumulator_set<vector<double>, stats<tag::mean> > acc;
  vector<double> some_vetor;
  //stuff
  some_vector = doStuff();
  acc(some_vector);

maybe this is obvious, but I tried anyway. :P

What I wanted was to have an accumulator that would calculate a vector which is the mean of the components of many vectors. Is there an easy way out?

EDIT:

I don't know if I was thoroughly clear. I don't want this:

 for_each(vec.begin(), vec.end(),acc);

This would calculate the mean of the entries of a given vector. What I need is different. I have a function that will spit vectors:

 vector<double> doSomething();
 // this is a monte carlo simulation;

And I need to run this many times and calculate the vectorial mean of those vectors:

  for(int i = 0; i < numberOfMCSteps; i++){
  vec = doSomething();
  acc(vec);
  }
  cout << mean(acc);

And I want mean(acc) to be a vector itself, whose entry [i] would be the means of the entries [i] of the accumulated vectors.

Theres a hint about this in the docs of Boost, but nothing explicit. And I'm a bit dumb. :P

Body:
And what about the documentation?

// The data for which we wish to calculate statistical properties:
std::vector< double > data( /* stuff */ );

// The accumulator set which will calculate the properties for us:
accumulator_set< double, features< tag::min, tag::mean > > acc;

// Use std::for_each to accumulate the statistical properties:
acc = std::for_each( data.begin(), data.end(), acc );

ContentLicense: CC BY-SA 2.5


问:
laravel 5.4 eloquent model loading , porting from 4.1 project
I am currently porting an old site using laravel 4.1 to laravel 5.4. Already implemented a lot of minor changes (error logs helps) but I am stuck with the following model usage:

```<code>namespace App;

class navire extends Eloquent
{
protected $table = 'navire';

public function user()
{
    return $this->belongsTo('user');
}

public function getId()
{
    return $this->id;
}

}
</code>```

I m trying to call it from a controller :

```<code>namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;

use App\navire;

class UserController extends Controller
{
   public function somefunc()
   {
      // ....

      $navire = \navire::where('user_id',$user->id)->get()->take(1);

    }

}
</code>```

Tried many thing using "use ..." or calling it with a \ at beginning , nothing has worked so far

exemples of errors :

```<code>local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:30

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:30

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:32

 local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:32
</code>```

I already called dumpautoload.

答:
either use $navire = \App\navire::where('user_id',$user->id)->get()->take(1);
or as you have already imported the model use $navire = navire::where('user_id',$user->id)->get()->take(1); i.e. with out the slash in front.

Another thing, you can just use first() instead of ->get()->take(1). Like this $navire = \App\navire::where('user_id',$user->id)->first();

Body:
I am currently porting an old site using laravel 4.1 to laravel 5.4. Already implemented a lot of minor changes (error logs helps) but I am stuck with the following model usage:

namespace App;

class navire extends Eloquent
{
protected $table = 'navire';

public function user()
{
    return $this->belongsTo('user');
}

public function getId()
{
    return $this->id;
}

}

I m trying to call it from a controller :

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;

use App\navire;

class UserController extends Controller
{
   public function somefunc()
   {
      // ....

      $navire = \navire::where('user_id',$user->id)->get()->take(1);

    }

}

Tried many thing using "use ..." or calling it with a \ at beginning , nothing has worked so far

exemples of errors :

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:30

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:30

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:32

 local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'navire' not found' in /home/user/www/app/Http/Controllers/UserController.php:32

I already called dumpautoload.


问:
Avoiding the rounding of double numbers
I'm trying to write a function that calculates the regression line from a data sheet with the least squares methode, but I encountered some serious problem with my code.

My first issue is that I don't know why my "linear regression" function is rounding the result of the iterations, even when I'm trying to use other "bigger" types.

My second issue is that the last part of my code is giving me the wrong results for the y intercept (b) and the slope (a), and I think that it could be a problem of conversion but I'm not really sure. If it is the case what should I do to avoid it?

```<code>void RegLin (const vector<double>& valuesX, const vector<double>& valuesY, vector<double>& PenOrd) {

unsigned int N=valuesX.size();

long double SomXi{0};
    for (unsigned i=0; i<N; ++i){
    SomXi+=valuesX.at(i);
    }

long double SomXiXi{0};
    for (unsigned i=0; i<N; ++i){              //Here is a problem (number rounded) Expected value: 937352,25 / Given value: 937352
    SomXiXi+=(valuesX.at(i))*(valuesX.at(i));
    }

long double SomYi{0};
    for (unsigned i=0; i<N; ++i){
    SomYi+=valuesY.at(i);
    }

long double SomXiYi{0};
    for (unsigned i=0; i<N; ++i){              //Here is the same problem Excepted value: 334107,41 / Given value: 334107
    SomXiYi+=(valuesX.at(i))*(valuesY.at(i));
    }

long double a=(SomYi*SomXiXi-SomXi*SomXiYi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

long double b=(N*SomXiYi-SomYi*SomXi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

PenOrd.push_back(a);
PenOrd.push_back(b);

return;
}
</code>```

Thank you in advance for your support

P.S: I'm using g++ and the 2011 C++ standard.

答:
there are serveral points with your effort. I'm a theoretical physics and numerical maths guy. So let me share some best practices with you.

First, I never encountered the need for using long double. Stick with double, because if that would not suffice, then you should go about considering working log-log plots to further analyse your data.

Second, you are using unsigned int instead of int. You should never do regression work with that much values (i.e., value-pairs) that it isn't sufficient to use int or best std::size_t for your integer counters. Using too many values can degrade accuracy because of accumulating numerical roundoff issues. So do not use use more than say 10000 to 1 Million of values until you have a very good reason to do so.

Third, it quickly becomes necessary to not bluntly add your squares (e.g., for SumXiXi and so forth) but to sort your contributions to the sum before actually summing them up. You correctly sum them up starting with the tiniest of values proceeding with your ever growing contributions to your sums. That is the only way to stay on top of accumulating roundoff issues.

Fourth, control of results. A good sign of reliability of results is achievable, if you to your work twice, one time as you did go about (i.e., using x_iy_i - xy_i - x_iy + xy formuae) and then as a second approach using the still un-multiplicated (x_i - x)(y_i - y) formulae. Good quality calculations would yield very comparable results using either formulae.

So, maybe that was quite a detour about doing numerical regression work, hope it might help a little.

Regards, Micha

Title: Avoiding the rounding of double numbers

Body:
I'm trying to write a function that calculates the regression line from a data sheet with the least squares methode, but I encountered some serious problem with my code.

My first issue is that I don't know why my "linear regression" function is rounding the result of the iterations, even when I'm trying to use other "bigger" types.

My second issue is that the last part of my code is giving me the wrong results for the y intercept (b) and the slope (a), and I think that it could be a problem of conversion but I'm not really sure. If it is the case what should I do to avoid it?

void RegLin (const vector<double>& valuesX, const vector<double>& valuesY, vector<double>& PenOrd) {

unsigned int N=valuesX.size();

long double SomXi{0};
    for (unsigned i=0; i<N; ++i){
    SomXi+=valuesX.at(i);
    }

long double SomXiXi{0};
    for (unsigned i=0; i<N; ++i){              //Here is a problem (number rounded) Expected value: 937352,25 / Given value: 937352
    SomXiXi+=(valuesX.at(i))*(valuesX.at(i));
    }

long double SomYi{0};
    for (unsigned i=0; i<N; ++i){
    SomYi+=valuesY.at(i);
    }

long double SomXiYi{0};
    for (unsigned i=0; i<N; ++i){              //Here is the same problem Excepted value: 334107,41 / Given value: 334107
    SomXiYi+=(valuesX.at(i))*(valuesY.at(i));
    }

long double a=(SomYi*SomXiXi-SomXi*SomXiYi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

long double b=(N*SomXiYi-SomYi*SomXi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

PenOrd.push_back(a);
PenOrd.push_back(b);

return;
}

Thank you in advance for your support

P.S: I'm using g++ and the 2011 C++ standard.


问:
Drawing real-time graphics in cartesian coordinates with GUI in Java?
I'm searching a way to draw dots in Cartesian coordinates in real-time when entering a value to a JTable. When I enter 2 to first column and 3 to second columns, without clicking a button, the point should be at (2,3) in coordinates.  What are some ways to do this in Java?

答:
It sounds like you want to create a scatter plot that reflects the current entries in a two column JTable. One approach would be to add a TableModelListener to your JTable, as shown here. In your implementation of tableChanged(), update the plot. Using jfreechart, you would update the XYSeries contained in an XYSeriesCollection used to create a scatter plot, as shown here. The listening chart will update itself in response. In the brute force approach, you could clear() the series and iterate through the table's TableModel, adding current values to the series as you go. Alternatively, identify the row that changed and update() the corresponding entry in the series.

Starting from the first example cited, you could simply replace the JList on the right with the ChartPanel used in the second example. The TableModelListener obviates the need for a button to generate the update.


问:
How can I retrieve data from Meteor collection on the client side with React?
I'm trying to retrieve my server data of a collection with the code bellow, but it just return undefined.

import { Posts } from '../../../api/posts.js';

class FeedUnit extends Component {

  constructor(props) {
      super(props);

      this.state = {
          open: true,
          emojis: false,
          isOver: false,
          likes: this.setLike(),
      };
  }

    setLike(){
    let self = this;
    let like;

    let post = Posts.findOne({ external_id: this.props.data.id });
    console.log(Posts.findOne({}))
    return like;
  }
  ```
</div>
</div>
</p>

<p>I already search on the data base manually and there I had the correct return using the command:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>db.posts.findOne({external_id: '1402366059774445_1503319816345735'})</code>```

答:
I found the solution in the comment of @mostafiz rahman, I should put the publish and subscribe, like this:

if (Meteor.isServer) {
  // This code only runs on the server
  // This is necessary to reatrieve data on the client side
  Meteor.publish('posts', function tasksPublication() {
    return Posts.find();
  });
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  componentDidMount() {
    Meteor.subscribe('posts');
  }</code>```

Body:
I'm trying to retrieve my server data of a collection with the code bellow, but it just return undefined.

import { Posts } from '../../../api/posts.js';

class FeedUnit extends Component {

  constructor(props) {
      super(props);

      this.state = {
          open: true,
          emojis: false,
          isOver: false,
          likes: this.setLike(),
      };
  }

    setLike(){
    let self = this;
    let like;

    let post = Posts.findOne({ external_id: this.props.data.id });
    console.log(Posts.findOne({}))
    return like;
  }

I already search on the data base manually and there I had the correct return using the command:

db.posts.findOne({external_id: '1402366059774445_1503319816345735'})

Body:
I found the solution in the comment of @mostafiz rahman, I should put the publish and subscribe, like this:

if (Meteor.isServer) {
  // This code only runs on the server
  // This is necessary to reatrieve data on the client side
  Meteor.publish('posts', function tasksPublication() {
    return Posts.find();
  });
}

  componentDidMount() {
    Meteor.subscribe('posts');
  }


问:
High Volume, High Speed Textbox in .Net
I am writing an application that will display serial/USB data at a rate of up to 250kb/sec. I am using the .net SerialPort class and reacting to the DataReceived event. For early implementations of this software, I simply stored the incoming data in a WinForms RichTextBox. This solution works fine until there are 50k - 100k lines in the control, at which point the application bogs down. Since then, I've tried accomplishing my goals with WPF and found the same problem. I tried, at one point, to keep only the currently visible text in the textbox, and store the rest in a large List<string> but this solution required a huge number of workarounds and, in the end, was abandoned - I'd rather not reinvent the wheel.

Now I come to you for a thread of hope - I am willing to try anything! Should I use a custom control (both pay and free controls are welcome)? SQLite? Virtualization as described above? Should I try polling the SerialPort instead of reacting to events?

答:
If the data is largely line oriented (ReadLine) then put it in a ListBox. It is the fastest control for putting lots of text onscreen.

But you will find that all UI controls are geared toward human interaction, not to the speed of a Port. Best thing to do would be to rethink your design. What is that data for anyway?

Title: High Volume, High Speed Textbox in .Net


问:
Can't make my aspect run
Basically I have a normal Java app, with a main. I use Intelij Ultimate. I have the following pom

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>88</groupId>
    <artifactId>SpaceX</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.4</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

So I also have a LoggingAspect which I just cant figure out how to run. I tried this too http://confluence.jetbrains.com/display/~roman.shevchenko/AspectJ+Support+Plugin

And manually downloaded the jar but I also downloaded the Intelij plugins for Aspects. Like AspectJ Support and Spring Aspect.

My aspect class looks like this:

```<code>public aspect LoggingAspect {
    pointcut tracing():call(public * com.company..*.*(..)) && !within(LoggingAspect);

    private Logger logger= Logger.getLogger("com.company");

    public LoggingAspect() {
        PropertyConfigurator.configure("logging.properties");
    }

    before(): tracing(){
        logger.info("Entering: "+ thisJoinPointStaticPart.getSignature());
    }

    after():tracing(){
        logger.info("Exiting: "+ thisJoinPointStaticPart.getSignature());
    }
}
</code>```

As you can see. I want to use the java.util.logging.Logger and I have a logging.properties file where I set up the output file. I tried compiling the app like in the link I pasted above, running the app normally, nothing seems to be working. My aspect is not working at all/ it's not being used. Any advice? Am I missing something?

I dont want to use Spring Aspect with annotations yet. I can't figure out how to make this one work first

I changed my compiler to ajc and tested the connection, everything is fine. I have added Aspectjrt to dependencies... it still doesn't do anything when I try to run the program. It just runs normaly without applying the aspects.
Any ideas?

答:
This is a solution for compile-time weaving. Because all major IDEs can import and update projects from Maven, it works in Eclipse, IntelliJ IDEA and probably also NetBeans (never tried).

Maven POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>88</groupId>
  <artifactId>SpaceX</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.source-target.version>1.8</java.source-target.version>
    <aspectj.version>1.8.10</aspectj.version>
  </properties>

  <build>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.5.1</version>
          <configuration>
            <source>${java.source-target.version}</source>
            <target>${java.source-target.version}</target>

            <useIncrementalCompilation>false</useIncrementalCompilation>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>aspectj-maven-plugin</artifactId>
          <version>1.10</version>
          <configuration>

            <source>${java.source-target.version}</source>
            <target>${java.source-target.version}</target>
            <Xlint>ignore</Xlint>
            <complianceLevel>${java.source-target.version}</complianceLevel>
            <encoding>${project.build.sourceEncoding}</encoding>

          </configuration>
          <executions>
            <execution>

              <phase>process-sources</phase>
              <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
              </goals>
            </execution>
          </executions>
          <dependencies>
            <dependency>
              <groupId>org.aspectj</groupId>
              <artifactId>aspectjtools</artifactId>
              <version>${aspectj.version}</version>
            </dependency>
            <dependency>
              <groupId>org.aspectj</groupId>
              <artifactId>aspectjweaver</artifactId>
              <version>${aspectj.version}</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
      </plugin>
    </plugins>

  </build>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
      </dependency>
      <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901.jdbc4</version>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
      </dependency>
      <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
      </dependency>
  </dependencies>

</project>
```

<p><strong>Log4J config file:</strong></p>

<pre class="lang-none prettyprint-override"><code># Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
</code>```

Driver application:

package com.company.app;

public class Application {
  public static void main(String[] args) {
    new Application().doSomething("foo", 11);
  }

  public String doSomething(String string, int i) {
    return "blah";
  }
}
```

<p><strong>Improved aspect:</strong></p>

<p>The way you load <code>logging.properties</code> only works from within a JAR, but not when running code from your IDE. I suggest you rely on the classpath being correctly imported from the Maven project, putting the config file under <code>src/main/resources</code> and then opening it via <code>ClassLoader.getResourceAsStream(..)</code>.</p>

<pre class="lang-java prettyprint-override"><code>package com.company.aspect;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public aspect LoggingAspect {
  private static final Logger logger = Logger.getLogger("com.company");

  public LoggingAspect() {
    PropertyConfigurator.configure(
      Thread
        .currentThread()
        .getContextClassLoader()
        .getResourceAsStream("logging.properties")
    );
  }

  pointcut tracing() :
    call(public * com.company..*.*(..)) &&
    !within(LoggingAspect);

  before() : tracing() {
    logger.info("Entering: " + thisJoinPointStaticPart.getSignature());
  }

  after() : tracing() {
    logger.info("Exiting: " + thisJoinPointStaticPart.getSignature());
  }
}
</code>```

Console log:

2017-04-02 17:58:06 INFO  company:23 - Entering: String com.company.app.Application.doSomething(String, int)
2017-04-02 17:58:06 INFO  company:27 - Exiting: String com.company.app.Application.doSomething(String, int)
```

Title: Can't make my aspect run

Body:
Basically I have a normal Java app, with a main. I use Intelij Ultimate. I have the following pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>88</groupId>
    <artifactId>SpaceX</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.4</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

So I also have a LoggingAspect which I just cant figure out how to run. I tried this too http://confluence.jetbrains.com/display/~roman.shevchenko/AspectJ+Support+Plugin

And manually downloaded the jar but I also downloaded the Intelij plugins for Aspects. Like AspectJ Support and Spring Aspect.

My aspect class looks like this:

public aspect LoggingAspect {
    pointcut tracing():call(public * com.company..*.*(..)) && !within(LoggingAspect);

    private Logger logger= Logger.getLogger("com.company");

    public LoggingAspect() {
        PropertyConfigurator.configure("logging.properties");
    }

    before(): tracing(){
        logger.info("Entering: "+ thisJoinPointStaticPart.getSignature());
    }

    after():tracing(){
        logger.info("Exiting: "+ thisJoinPointStaticPart.getSignature());
    }
}

As you can see. I want to use the java.util.logging.Logger and I have a logging.properties file where I set up the output file. I tried compiling the app like in the link I pasted above, running the app normally, nothing seems to be working. My aspect is not working at all/ it's not being used. Any advice? Am I missing something?

I dont want to use Spring Aspect with annotations yet. I can't figure out how to make this one work first

I changed my compiler to ajc and tested the connection, everything is fine. I have added Aspectjrt to dependencies... it still doesn't do anything when I try to run the program. It just runs normaly without applying the aspects.
Any ideas?

Body:
This is a solution for compile-time weaving. Because all major IDEs can import and update projects from Maven, it works in Eclipse, IntelliJ IDEA and probably also NetBeans (never tried).

Maven POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>88</groupId>
  <artifactId>SpaceX</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.source-target.version>1.8</java.source-target.version>
    <aspectj.version>1.8.10</aspectj.version>
  </properties>

  <build>

    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.5.1</version>
          <configuration>
            <source>${java.source-target.version}</source>
            <target>${java.source-target.version}</target>
            <!-- IMPORTANT -->
            <useIncrementalCompilation>false</useIncrementalCompilation>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>aspectj-maven-plugin</artifactId>
          <version>1.10</version>
          <configuration>
            <!--<showWeaveInfo>true</showWeaveInfo> -->
            <source>${java.source-target.version}</source>
            <target>${java.source-target.version}</target>
            <Xlint>ignore</Xlint>
            <complianceLevel>${java.source-target.version}</complianceLevel>
            <encoding>${project.build.sourceEncoding}</encoding>
            <!--<verbose>true</verbose> -->
            <!--<warn>constructorName,packageDefaultMethod,deprecation,maskedCatchBlocks,unusedLocals,unusedArguments,unusedImport</warn> -->
          </configuration>
          <executions>
            <execution>
              <!-- IMPORTANT -->
              <phase>process-sources</phase>
              <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
              </goals>
            </execution>
          </executions>
          <dependencies>
            <dependency>
              <groupId>org.aspectj</groupId>
              <artifactId>aspectjtools</artifactId>
              <version>${aspectj.version}</version>
            </dependency>
            <dependency>
              <groupId>org.aspectj</groupId>
              <artifactId>aspectjweaver</artifactId>
              <version>${aspectj.version}</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </pluginManagement>

    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
      </plugin>
    </plugins>

  </build>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
      </dependency>
      <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901.jdbc4</version>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
      </dependency>
      <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
      </dependency>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
      </dependency>
  </dependencies>

</project>

Log4J config file:

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Driver application:

package com.company.app;

public class Application {
  public static void main(String[] args) {
    new Application().doSomething("foo", 11);
  }

  public String doSomething(String string, int i) {
    return "blah";
  }
}

Improved aspect:

The way you load logging.properties only works from within a JAR, but not when running code from your IDE. I suggest you rely on the classpath being correctly imported from the Maven project, putting the config file under src/main/resources and then opening it via ClassLoader.getResourceAsStream(..).

package com.company.aspect;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public aspect LoggingAspect {
  private static final Logger logger = Logger.getLogger("com.company");

  public LoggingAspect() {
    PropertyConfigurator.configure(
      Thread
        .currentThread()
        .getContextClassLoader()
        .getResourceAsStream("logging.properties")
    );
  }

  pointcut tracing() :
    call(public * com.company..*.*(..)) &&
    !within(LoggingAspect);

  before() : tracing() {
    logger.info("Entering: " + thisJoinPointStaticPart.getSignature());
  }

  after() : tracing() {
    logger.info("Exiting: " + thisJoinPointStaticPart.getSignature());
  }
}

Console log:

2017-04-02 17:58:06 INFO  company:23 - Entering: String com.company.app.Application.doSomething(String, int)
2017-04-02 17:58:06 INFO  company:27 - Exiting: String com.company.app.Application.doSomething(String, int)


问:
Elegant BFS in ocaml
I would like to repair my bfs function, its problem is that when it receives non-existant nodes it prints them as visited too.

And this function is already huge so adding a check like :

if node not in graph then ... would also bloat my function even more, which I would like to avoid because I want to see a shorter function which is "eye-debuggable".

Furthermore, I chose Hashtable because as opposed to the  Set :

It's mutable

It's an array but the Set is a balanced binary tree

(If your personal preference is to go with the Set please let me know why)

```<code>    type 'a graph = Gr of ('a * 'a list) list

    let get_neighbors node (Gr g) =
        try List.assoc node g with Not_found -> []

    let bfs start g =
        let v = Hashtbl.create 100 in (*ideally it should be the # of distinct nodes*)
        let q = Queue.create () in    (*v is for visited nodes*)

        let rec bfs' cur_n acc =
                get_neighbors cur_n g |>
                List.iter
                (fun n ->
                    try Hashtbl.find v n
                    with Not_found ->
                        Hashtbl.add v n ();
                        Queue.push n q);
                Hashtbl.add v cur_n ();
                try bfs' (Queue.pop q) (cur_n::acc)
                with Queue.Empty -> List.rev (cur_n::acc) in
                bfs' start []
</code>```

Example :

```<code>    let g =
        Gr [
             ('a', ['e'; 'b'; 'c']);
             ('b', ['e'; 'd']);
             ('e', ['d'; 'f']);
             ('g', ['t';'s'])
           ]

    # bfs 'a' g;;
    - : char list = ['a'; 'e'; 'b'; 'c'; 'd'; 'f']
    # bfs 'z' g;;
    - : char list = ['z'] (*doesn't make sense, g doesn't have 'z' node*)
</code>```

答:
It seems to me that the Not_found exception in get_neighbors indicates a nonexistent node. But your code is treating this case is if it indicates a node with no successors.

If your graph is well structured, the neighbor lists shouldn't contain any nonexistent nodes. So the only place this node can come from is the initial call.

So I would move the handling of this Not_found exception out to the outermost level.

Title: Elegant BFS in ocaml

Body:
I would like to repair my bfs function, its problem is that when it receives non-existant nodes it prints them as visited too.

And this function is already huge so adding a check like :

if node not in graph then ... would also bloat my function even more, which I would like to avoid because I want to see a shorter function which is "eye-debuggable".

Furthermore, I chose Hashtable because as opposed to the  Set :

It's mutable

It's an array but the Set is a balanced binary tree

(If your personal preference is to go with the Set please let me know why)

    type 'a graph = Gr of ('a * 'a list) list

    let get_neighbors node (Gr g) =
        try List.assoc node g with Not_found -> []

    let bfs start g =
        let v = Hashtbl.create 100 in (*ideally it should be the # of distinct nodes*)
        let q = Queue.create () in    (*v is for visited nodes*)

        let rec bfs' cur_n acc =
                get_neighbors cur_n g |>
                List.iter
                (fun n ->
                    try Hashtbl.find v n
                    with Not_found ->
                        Hashtbl.add v n ();
                        Queue.push n q);
                Hashtbl.add v cur_n ();
                try bfs' (Queue.pop q) (cur_n::acc)
                with Queue.Empty -> List.rev (cur_n::acc) in
                bfs' start []

Example :

    let g =
        Gr [
             ('a', ['e'; 'b'; 'c']);
             ('b', ['e'; 'd']);
             ('e', ['d'; 'f']);
             ('g', ['t';'s'])
           ]

    # bfs 'a' g;;
    - : char list = ['a'; 'e'; 'b'; 'c'; 'd'; 'f']
    # bfs 'z' g;;
    - : char list = ['z'] (*doesn't make sense, g doesn't have 'z' node*)


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Clear case, the loop. Specifically looping in Gwbasic. Just for fun I wanted to print all the numbers from 0 to 100 on the screen. So I started:

```<code>10 print 1
20 print 2
30 print 3
40 print 4
</code>```

At some point I thought WTF or something similar. There must be a better way. So I asked someone (perhaps a teacher or some fellow pupil) who then introduced me to the magics of variables and the loop. That must have been the moment I got hooked.

```<code>10 SET i = 0
20 IF i > 100 THEN GOTO 60
30 PRINT i
40 SET I = I + 1
50 GOTO 20
60 REM END LOOP
</code>```

Thats 6 lines instead of 100!!! That was just so much better. Sorry if I got the syntax not exactly right. :-) I am really fond of that moment.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body:
Clear case, the loop. Specifically looping in Gwbasic. Just for fun I wanted to print all the numbers from 0 to 100 on the screen. So I started:

10 print 1
20 print 2
30 print 3
40 print 4

At some point I thought WTF or something similar. There must be a better way. So I asked someone (perhaps a teacher or some fellow pupil) who then introduced me to the magics of variables and the loop. That must have been the moment I got hooked.

10 SET i = 0
20 IF i > 100 THEN GOTO 60
30 PRINT i
40 SET I = I + 1
50 GOTO 20
60 REM END LOOP

Thats 6 lines instead of 100!!! That was just so much better. Sorry if I got the syntax not exactly right. :-) I am really fond of that moment.

OwnerDisplayName: pi


问:
using unallocated memory without error?
Why does that work?

```<code>#include <iostream>
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = new float[3-i];
        i++;
    }

    cout << tab[2][7] << endl;
    tab[2][7] = 6.87;
    cout << tab[2][7] << endl;

    i = 0;
    while(i < 3)
        delete[] tab[i];
}
</code>```

while this one doesn't?

```<code>#include <iostream>
using namespace std;

int main() {
    float* tab = new float[3];

    cout << tab[7] << endl;
    tab[7] = 6.87;
    cout << tab[7] << endl;

    delete[] tab;
}
</code>```

I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).

I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.

Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?

I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?

答:
While the other answers, with the exception of Mark's, are not wrong they are not exactly right either.  What you are doing by accessing data past the end of what you've explicitly allocated in your program is causing "undefined behavior".  It can do anything, including "work".

Steve's answer didn't exist when I began writing this.

Title: using unallocated memory without error?

Body:
Why does that work?

#include <iostream>
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = new float[3-i];
        i++;
    }

    cout << tab[2][7] << endl;
    tab[2][7] = 6.87;
    cout << tab[2][7] << endl;

    i = 0;
    while(i < 3)
        delete[] tab[i];
}

while this one doesn't?

#include <iostream>
using namespace std;

int main() {
    float* tab = new float[3];

    cout << tab[7] << endl;
    tab[7] = 6.87;
    cout << tab[7] << endl;

    delete[] tab;
}

I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).

I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.

Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?

I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?


问:
How to add close and minimize button to processing program
I made a program with processing and arduino to control RGB led using processing
then I made application .exe from my processing code
the problem is the application work without close and minimize button .
how can i add it for my application ?

答:
You need to make sure the "Presentation Mode" checkbox is unchecked:

If this is checked, your sketch is displayed in full screen. If it's unchecked, your sketch is displayed in a window.


问:
UITableView leaking?
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}
</code>```

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?

答:
As has been pointed out by other answers, your problem is the line:

```<code>[self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];
</code>```

It will create a new UITableView object and it will not modify self.tableView which means that line is totally pointless. It only creates the leak you are experiencing. Remove it and you should be fine.

Title: UITableView leaking?

Body:
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?

Body:
As has been pointed out by other answers, your problem is the line:

[self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

It will create a new UITableView object and it will not modify self.tableView which means that line is totally pointless. It only creates the leak you are experiencing. Remove it and you should be fine.


问:
How to align tkinter widgets?
How do I align my Radiobuttons? I can add spaces to test4 but that solution doesn't seem proper. Here's what it looks like at the moment—as you can see text111111 has extra chars. I've tried using padx.

My code:

```<code>from tkinter import *

class GUI:
    def __init__(self, master):

        self.iconnum = IntVar()
        self.master = master
        self.master.title('test')
        self.master.resizable(width=False, height=False)
        self.master.maxsize(500, 250)
        self.master.minsize(500, 250)

        self.test1 = Radiobutton(master, text="test11111111", variable=self.iconnum,
                                 value=1, )
        self.test2 = Radiobutton(master, text="test2", variable=0, value=2, )
        self.test3 = Radiobutton(master, text="test3", variable=0, value=3, )
        self.test4 = Radiobutton(master, text="test4", variable=0, value=4)
        self.test1.grid(row=2, columnspan=1)
        self.test2.grid(row=2, columnspan=2)
        self.test3.grid(row=2, column=1)
        self.test4.grid(row=3, columnspan=1)

        self.Checker = Radiobutton(master, text="test5", indicatoron=0, height=1, width=35,
                                   value=0, command=self.icon_switcher) #var=Selection)
        self.Turbo = Radiobutton(master, text="test6", indicatoron=0, height=1, width=35,
                                 value=1, command=self.icon_switcher) #var#=Selection)

        self.Checker.grid(row=1)
        self.Turbo.grid(row=1, column=1,   )

    def icon_switcher(self):
        print("Hello")

root = Tk()
gui = GUI(root)

root.mainloop()
</code>```

答: You can use sticky=W inside your .grid for all your buttons to make them align on the left side. And you can also include pady = 20 to make it not go all the way to the left.

Title: How to align tkinter widgets?

Body:
How do I align my Radiobuttons? I can add spaces to test4 but that solution doesn't seem proper. Here's what it looks like at the moment—as you can see text111111 has extra chars. I've tried using padx.

My code:

from tkinter import *

class GUI:
    def __init__(self, master):

        self.iconnum = IntVar()
        self.master = master
        self.master.title('test')
        self.master.resizable(width=False, height=False)
        self.master.maxsize(500, 250)
        self.master.minsize(500, 250)

        self.test1 = Radiobutton(master, text="test11111111", variable=self.iconnum,
                                 value=1, )
        self.test2 = Radiobutton(master, text="test2", variable=0, value=2, )
        self.test3 = Radiobutton(master, text="test3", variable=0, value=3, )
        self.test4 = Radiobutton(master, text="test4", variable=0, value=4)
        self.test1.grid(row=2, columnspan=1)
        self.test2.grid(row=2, columnspan=2)
        self.test3.grid(row=2, column=1)
        self.test4.grid(row=3, columnspan=1)

        self.Checker = Radiobutton(master, text="test5", indicatoron=0, height=1, width=35,
                                   value=0, command=self.icon_switcher) #var=Selection)
        self.Turbo = Radiobutton(master, text="test6", indicatoron=0, height=1, width=35,
                                 value=1, command=self.icon_switcher) #var#=Selection)

        self.Checker.grid(row=1)
        self.Turbo.grid(row=1, column=1,   )

    def icon_switcher(self):
        print("Hello")

root = Tk()
gui = GUI(root)

root.mainloop()


问:
Android Sliding Menu Options cannot be checked
In my App I have a sliding menu.

My activity.xml looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/sliding_menu_options" />
</android.support.v4.widget.DrawerLayout>
</code>```

The sliding_menu_options.xml looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black"
            android:title="@string/home"/>
        <item
            android:id="@+id/nav_recently"
            android:icon="@drawable/ic_file_upload"
            android:title="@string/recent"/>
    </group>

    <group
        android:checkableBehavior="single">
        <item
            android:id="@+id/otherItem"
            android:title="Other">
            <menu>
                <item
                    android:id="@+id/nav_about_us"
                    android:icon="@drawable/ic_info_black"
                    android:title="@string/about"/>
                <item
                    android:id="@+id/nav_licences"
                    android:icon="@drawable/ic_description_black"
                    android:title="@string/licences"/>
            </menu>
        </item>
    </group>
</menu>
</code>```

This picture shows the tutorial I used for my slidin menu and how the two groups should roughly look like. Other should be something like the headline or description for the second group:

When the user selects one of the four options, I want to mark the option in the sliding menu as checked. For the first two options it works fine with this piece of code:

```<code>navigationView = (NavigationView) findViewById(R.id.nav_view);
 navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

               navigationView.getMenu().findItem(menuItem.getItemId()).setChecked(true);

                return true;
            }
        });
</code>```

Unfortuantely the Menu withing NavigationView contains only two Items (nav_home and nav_recently) instead of all four. So it does not work for nav_about_us and nav_licences to mark them as checked.

How can I check the other two options while still having two groups?

答:
Looks ike there is a problem in sliding_menu_options.xml ,try following modified code .

```<code>    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black"
            android:title="@string/home"/>
        <item
            android:id="@+id/nav_recently"
            android:icon="@drawable/ic_file_upload"
            android:title="@string/recent"/>
    </group>

<item
            android:id="@+id/otherItem"
            android:title="Other">
</item>

    <group
        android:checkableBehavior="single">

                <item
                    android:id="@+id/nav_about_us"
                    android:icon="@drawable/ic_info_black"
                    android:title="@string/about"/>
                <item
                    android:id="@+id/nav_licences"
                    android:icon="@drawable/ic_description_black"
                    android:title="@string/licences"/>

    </group>
</menu>
</code>```

Body:
In my App I have a sliding menu.

My activity.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/sliding_menu_options" />
</android.support.v4.widget.DrawerLayout>

The sliding_menu_options.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black"
            android:title="@string/home"/>
        <item
            android:id="@+id/nav_recently"
            android:icon="@drawable/ic_file_upload"
            android:title="@string/recent"/>
    </group>

    <group
        android:checkableBehavior="single">
        <item
            android:id="@+id/otherItem"
            android:title="Other">
            <menu>
                <item
                    android:id="@+id/nav_about_us"
                    android:icon="@drawable/ic_info_black"
                    android:title="@string/about"/>
                <item
                    android:id="@+id/nav_licences"
                    android:icon="@drawable/ic_description_black"
                    android:title="@string/licences"/>
            </menu>
        </item>
    </group>
</menu>

This picture shows the tutorial I used for my slidin menu and how the two groups should roughly look like. Other should be something like the headline or description for the second group:

When the user selects one of the four options, I want to mark the option in the sliding menu as checked. For the first two options it works fine with this piece of code:

navigationView = (NavigationView) findViewById(R.id.nav_view);
 navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

               navigationView.getMenu().findItem(menuItem.getItemId()).setChecked(true);

                return true;
            }
        });

Unfortuantely the Menu withing NavigationView contains only two Items (nav_home and nav_recently) instead of all four. So it does not work for nav_about_us and nav_licences to mark them as checked.

How can I check the other two options while still having two groups?

Body:
Looks ike there is a problem in sliding_menu_options.xml ,try following modified code .

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black"
            android:title="@string/home"/>
        <item
            android:id="@+id/nav_recently"
            android:icon="@drawable/ic_file_upload"
            android:title="@string/recent"/>
    </group>

<item
            android:id="@+id/otherItem"
            android:title="Other">
</item>

    <group
        android:checkableBehavior="single">

                <item
                    android:id="@+id/nav_about_us"
                    android:icon="@drawable/ic_info_black"
                    android:title="@string/about"/>
                <item
                    android:id="@+id/nav_licences"
                    android:icon="@drawable/ic_description_black"
                    android:title="@string/licences"/>

    </group>
</menu>


问:
comparing temporal sequences
I'm trying to wrap my head around this task and wondering if there is a standard way of doing this or some libraries that would be useful.

Certain events are tracked and timed at several data sources S1 ... SN. The recorded information is the event type and timestamp. There may be several events of the same type sequentially or they may be intermittent. There could be "missing" events - i.e. when one of the sources misses it, and, vice versa, when a source introduces a "false positive". There is typically a time difference between observations of the same event at different sources. This time difference has a constant component due to physical location of the sources but may also have a varying component introduced by network latency and other factors.

I need to find an algorithm that would find the optimal maximum time interval that should be used to group the observations at all sources in a single "observed event" and allow detection of the missing events and false positives.

I am wondering if the solution is really somewhere in the statistics field rather than algoritghms. Any input would be much appreciated.

答: Sounds like you're building an attendance system :-) In the system I'm building currently this kind of grouping observations is also necessary. In my case there's employees that have a pass that they will put in front off a passreader to register their attendance. First the system will select all attendances from one employee. Then it will put them in boxes of one day, ordered by registration time. Every registration will be assessed on whether it's a start or stop. If the first registration is a start registration, then the system will search for a stop registration up to maximally 12 hours later. If the stop doesn't come a stop is inserted. Additional intelligence can be put into place when the planning is known. Perhapse you could use statistics, but in my case it was a question of algorithms, combined with knowledge of the organisation.</p>

Title: comparing temporal sequences


问:
Menu module in joomla not showing all menu items added
Please I need help with this. I am using joomla version 3.6.5 and installed greenlife template. I want to add menu module to the site. I added two menu modules. One is menu prinicipal and the other is les attractions. I also created two menus which are main menu and main menu2. i added main menu to menu principal menu module and main menu2 to les atrractions menu module. It display on the site correctly. But my problem now is only two menu items is showing on each menu module. I have more than two menu items in each menu which are main menu and main menu2 Please help me.

答:
Try to use default Joomla template (protostar). Do you solve the issue?
If you unpublish first two menu items, do you see other menu items or menu disappear completely?</p>


问:
HTML - What does data-remote="true" do?
I was just working on a project that was sending an extra request and it was because of data-remote="true". I've seen this line plenty of times before, but I guess I don't really know what it does. I tried Googling it but all that comes up are specific examples where data-remote isn't working for the question asker.

I just want to know what the purpose of data-remote="true"/"false" is to get a better understanding of it.

答:
I was told that data-remote="true" is an HTML version of JavaScript's preventDefault() method, in that it simply prevents the form from being submitted to the server.

Rails applications along with the jQuery gem generates the global listener:

```<code>$(document).on("click", "a[data-remote=true]", function(e){
    e.preventDefault();
    $.getScript($(this).href())
});
</code>```

Feel free to correct me if I'm wrong :)

Title: HTML - What does data-remote="true" do?

Body:
I was told that data-remote="true" is an HTML version of JavaScript's preventDefault() method, in that it simply prevents the form from being submitted to the server.

Rails applications along with the jQuery gem generates the global listener:

$(document).on("click", "a[data-remote=true]", function(e){
    e.preventDefault();
    $.getScript($(this).href())
});

Feel free to correct me if I'm wrong :)


问:
Calling a different class in the same src folder will not work
I am trying to call the class, "CarFuel", from the same src folder. It is not working and shows an error.

Code for class with methods for main:

```<code>public class CarFuel {

    int CarFuel = 5; //Gallons of fuel starting in car

    public CarFuel(int FuelAmount){ //Constructor for defined staring fuel amount
        CarFuel = FuelAmount;
    }

    public void GetGasoline(int amount){ //Filling up gasoline, amount = how much gasoline filled up
        CarFuel = CarFuel + amount;
    }

    public void DrainGasoline(int amount){ //Driving car, amount = how much gasoline drained
        CarFuel = CarFuel - amount;
    }

    public int GetGasoline(){ //returns how much gasoline is left in the end
        return CarFuel;
    }

}

//MAIN EXEX IN CarFuelExec
</code>```

Here is the main class that uses these methods:

```<code>public class CarFuelExec {

    public static void main(String[] args){

        CarFuel.car = new CarFuel(0);
        car.GetGasoline(36);
        car.DrainGasoline(5);
         System.out.println("The remaining fuel in your car is: " + car.GetGasoline + " gallons");

    }
}
</code>```

Could anybody tell me why CarFuel.car = new Carfuel(0); is not calling the other class and is outputting an error?

答:
```<code>public class CarFuelExec {
    public static void main(String[] args){
        CarFuel car = new CarFuel(0);//make object of Car_Fuel
        car.GetGasoline(36);
        car.DrainGasoline(5);
        System.out.println("The remaining fuel in your car is: " + car.GetGasoline() + " gallons"); //method GetGasoline need parenparenthesis
    }
}
</code>```

try this code it will work.....

Body:
I am trying to call the class, "CarFuel", from the same src folder. It is not working and shows an error.

Code for class with methods for main:

public class CarFuel {

    int CarFuel = 5; //Gallons of fuel starting in car

    public CarFuel(int FuelAmount){ //Constructor for defined staring fuel amount
        CarFuel = FuelAmount;
    }

    public void GetGasoline(int amount){ //Filling up gasoline, amount = how much gasoline filled up
        CarFuel = CarFuel + amount;
    }

    public void DrainGasoline(int amount){ //Driving car, amount = how much gasoline drained
        CarFuel = CarFuel - amount;
    }

    public int GetGasoline(){ //returns how much gasoline is left in the end
        return CarFuel;
    }

}

//MAIN EXEX IN CarFuelExec

Here is the main class that uses these methods:

public class CarFuelExec {

    public static void main(String[] args){

        CarFuel.car = new CarFuel(0);
        car.GetGasoline(36);
        car.DrainGasoline(5);
         System.out.println("The remaining fuel in your car is: " + car.GetGasoline + " gallons");

    }
}

Could anybody tell me why CarFuel.car = new Carfuel(0); is not calling the other class and is outputting an error?

Body:
public class CarFuelExec {
    public static void main(String[] args){
        CarFuel car = new CarFuel(0);//make object of Car_Fuel
        car.GetGasoline(36);
        car.DrainGasoline(5);
        System.out.println("The remaining fuel in your car is: " + car.GetGasoline() + " gallons"); //method GetGasoline need parenparenthesis
    }
}

try this code it will work.....


问:
Apache Spark - java.lang.NoSuchMethodError: breeze.linalg.Vector$.scalarOf()Lbreeze/linalg/support/ScalarOf
Here is the error:

```<code>Exception in thread "main" java.lang.NoSuchMethodError: breeze.linalg.Vector$.scalarOf()Lbreeze/linalg/support/ScalarOf;
at org.apache.spark.ml.knn.Leaf$$anonfun$4.apply(MetricTree.scala:95)
at org.apache.spark.ml.knn.Leaf$$anonfun$4.apply(MetricTree.scala:93)
at scala.collection.IndexedSeqOptimized$class.foldl(IndexedSeqOptimized.scala:57)
at scala.collection.IndexedSeqOptimized$class.foldLeft(IndexedSeqOptimized.scala:66)
at scala.collection.mutable.ArrayBuffer.foldLeft(ArrayBuffer.scala:48)
at org.apache.spark.ml.knn.Leaf$.apply(MetricTree.scala:93)
at org.apache.spark.ml.knn.MetricTree$.build(MetricTree.scala:169)
at org.apache.spark.ml.knn.KNN.fit(KNN.scala:388)
at org.apache.spark.ml.classification.KNNClassifier.train(KNNClassifier.scala:109)
at org.apache.spark.ml.classification.KNNClassifier.fit(KNNClassifier.scala:117)
at SparkKNN$.main(SparkKNN.scala:23)
at SparkKNN.main(SparkKNN.scala)
</code>```

Here is the program that is triggering the error:

```<code>object SparkKNN {
    def main(args: Array[String]) {
        val spark = SparkSession.builder().master("local").config("spark.sql.warehouse.dir", "file:///c:/tmp/spark-warehouse").getOrCreate()
        val sc = spark.sparkContext
        import spark.implicits._
        //read in raw label and features
        val training = spark.read.format("com.databricks.spark.csv").option("header", true).load("E:/Machine Learning/knn_input.csv")
        var df = training.selectExpr("cast(label as double) label", "cast(feature1 as int) feature1","cast(feature2 as int) feature2","cast(feature3 as int) feature3")
        val assembler = new VectorAssembler().setInputCols(Array("feature1","feature2","feature3")).setOutputCol("features")
        df = assembler.transform(df)
        //MLUtils.loadLibSVMFile(sc, "C:/Program Files (x86)/spark-2.0.0-bin-hadoop2.7/data/mllib/sample_libsvm_data.txt").toDF()

        val knn = new KNNClassifier()
            .setTopTreeSize(df.count().toInt / 2)
            .setK(10)
        val splits = df.randomSplit(Array(0.7, 0.3))
        val (trainingData, testData) = (splits(0), splits(1))
        val knnModel = knn.fit(trainingData)

        val predicted = knnModel.transform(testData)
        predicted.show()
    }
}
</code>```

I am using Apache spark 2.0 with scala version 2.11.8. It looks like a version difference issue. Any ideas?

答:
Spark MLLib 2.0 brings in this version of Breeze:

"org.scalanlp" % "breeze_2.11" % "0.11.2"

You must have another library in your classpath that also has a dependency on Breeze but a different version, and that's the one being loaded. As a result, MLLib is operating with a different version of Breeze at runtime than was around at compile-time.

You have multiple options. You can find that undesirable transitive dependency on Breeze and exclude it. You can add a direct dependency on the version of that library that has the same Breeze dependency MLLib does. Or you can add a direct dependency on the Breeze version MLLib needs.

Body:
Here is the error:

Exception in thread "main" java.lang.NoSuchMethodError: breeze.linalg.Vector$.scalarOf()Lbreeze/linalg/support/ScalarOf;
at org.apache.spark.ml.knn.Leaf$$anonfun$4.apply(MetricTree.scala:95)
at org.apache.spark.ml.knn.Leaf$$anonfun$4.apply(MetricTree.scala:93)
at scala.collection.IndexedSeqOptimized$class.foldl(IndexedSeqOptimized.scala:57)
at scala.collection.IndexedSeqOptimized$class.foldLeft(IndexedSeqOptimized.scala:66)
at scala.collection.mutable.ArrayBuffer.foldLeft(ArrayBuffer.scala:48)
at org.apache.spark.ml.knn.Leaf$.apply(MetricTree.scala:93)
at org.apache.spark.ml.knn.MetricTree$.build(MetricTree.scala:169)
at org.apache.spark.ml.knn.KNN.fit(KNN.scala:388)
at org.apache.spark.ml.classification.KNNClassifier.train(KNNClassifier.scala:109)
at org.apache.spark.ml.classification.KNNClassifier.fit(KNNClassifier.scala:117)
at SparkKNN$.main(SparkKNN.scala:23)
at SparkKNN.main(SparkKNN.scala)

Here is the program that is triggering the error:

object SparkKNN {
    def main(args: Array[String]) {
        val spark = SparkSession.builder().master("local").config("spark.sql.warehouse.dir", "file:///c:/tmp/spark-warehouse").getOrCreate()
        val sc = spark.sparkContext
        import spark.implicits._
        //read in raw label and features
        val training = spark.read.format("com.databricks.spark.csv").option("header", true).load("E:/Machine Learning/knn_input.csv")
        var df = training.selectExpr("cast(label as double) label", "cast(feature1 as int) feature1","cast(feature2 as int) feature2","cast(feature3 as int) feature3")
        val assembler = new VectorAssembler().setInputCols(Array("feature1","feature2","feature3")).setOutputCol("features")
        df = assembler.transform(df)
        //MLUtils.loadLibSVMFile(sc, "C:/Program Files (x86)/spark-2.0.0-bin-hadoop2.7/data/mllib/sample_libsvm_data.txt").toDF()

        val knn = new KNNClassifier()
            .setTopTreeSize(df.count().toInt / 2)
            .setK(10)
        val splits = df.randomSplit(Array(0.7, 0.3))
        val (trainingData, testData) = (splits(0), splits(1))
        val knnModel = knn.fit(trainingData)

        val predicted = knnModel.transform(testData)
        predicted.show()
    }
}

I am using Apache spark 2.0 with scala version 2.11.8. It looks like a version difference issue. Any ideas?