问:
Confirmation dialog with HTML5 button element
I have a button element like so:

```<code><button name="command" type="submit" form="frmLandUnits" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">
      <span class="glyphicon glyphicon-trash" aria-hidden="true">
    </span></button>
</code>```

It's part of a data entry grid in a table which is inside a form. On each row are other buttons like Update, and there's a new row with an Insert button. The problem is that when clicking OK the form is not submitted. A google search on this turned up nothing that I could find.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form name="frmLandUnits" method="POST" action="https://httpbin.org/post">

<button name="command" type="submit" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">

    </button>

</form>```

The behavior is different than for onclick with an input. That is why in my opinion this is not a duplicate.

答:
```<code><form id="frmLandUnits" method="GET" action="www.microsoft.com" onsubmit="return confirm('Do you really want to submit the form?');"  >

<button name="command" type="submit" form="frmLandUnits" class="btn btn-danger"
title="Delete" value="Delete:1:352404725228987" >
  <span class="glyphicon glyphicon-trash" aria-hidden="true">
</span></button>
</form>
</code>```

Body:
I have a button element like so:

<button name="command" type="submit" form="frmLandUnits" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">

    </button>

It's part of a data entry grid in a table which is inside a form. On each row are other buttons like Update, and there's a new row with an Insert button. The problem is that when clicking OK the form is not submitted. A google search on this turned up nothing that I could find.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form name="frmLandUnits" method="POST" action="https://httpbin.org/post">

<button name="command" type="submit" class="btn btn-danger" title="Delete" value="Delete:1:352404725228987" onclick="return confirm('Are you sure?');">

    </button>

</form>

The behavior is different than for onclick with an input. That is why in my opinion this is not a duplicate.


来源: stackexchange

问:
Alternative to gets?
I used to use gets but then I heard that it got removed from c11 and that its overall very dangerous.
So I did some searching and found out that you can use fgets() to do the same thing.

The problems is that when I do use fgets() it seems to also copy the end of the line aswell, which ends up making an extra unwanted line.

To show you what I mean:

```<code>//if I have
char key[30];
fgets(key, sizeof(key), stdin);

//now if ender for instance: Doggo and do:
printf("The key is:%s|hozaah!\n", key);

//I expect it to print:
The key is:Doggo|hozaah!

//Instead it prints:
The key is:Doggo
|hozaah!
</code>```

Is there a way to get around this? Or is there another function I can use instead?

答:
The answer lies in the fact that fgets reads as many characters as fit into the buffer, including a null terminator, but only up to end of file or a newline, and it will store the newline in the string, too: man 3 fgets

So if you enter input on the terminal, the newline is transmitted to the standard input, too, and read by fgets. This is different from the old gets, which replaces the newline with a null byte.

So if you're reading lines and don't want the potential newline, strip it out. Unfortunately, fgets does not tell you how many characters were read, so you have to scan the string again to work it out:

```<code>char* p = fgets(key, sizeof(key), stdin);

if (!p) { /* error */ }

size_t n = strlen(key);

if (n > 0 && key[n - 1] == '\n') {
  key[n - 1] = '\0';
} else {
  /* buffer too short or EOF reached without newline */
}

printf("The line was: '%s'\n", key);
</code>```

It may be worth considering alternatives: If you only need one input, don't input the newline in the first place. If you need lots of lines, use  fread into a fixed-size buffer and scan for newlines yourself.

ContentLicense: CC BY-SA 3.0

Title: Alternative to gets?

Body:
I used to use gets but then I heard that it got removed from c11 and that its overall very dangerous.
So I did some searching and found out that you can use fgets() to do the same thing.

The problems is that when I do use fgets() it seems to also copy the end of the line aswell, which ends up making an extra unwanted line.

To show you what I mean:

//if I have
char key[30];
fgets(key, sizeof(key), stdin);

//now if ender for instance: Doggo and do:
printf("The key is:%s|hozaah!\n", key);

//I expect it to print:
The key is:Doggo|hozaah!

//Instead it prints:
The key is:Doggo
|hozaah!

Is there a way to get around this? Or is there another function I can use instead?

Body:
The answer lies in the fact that fgets reads as many characters as fit into the buffer, including a null terminator, but only up to end of file or a newline, and it will store the newline in the string, too: man 3 fgets

So if you enter input on the terminal, the newline is transmitted to the standard input, too, and read by fgets. This is different from the old gets, which replaces the newline with a null byte.

So if you're reading lines and don't want the potential newline, strip it out. Unfortunately, fgets does not tell you how many characters were read, so you have to scan the string again to work it out:

char* p = fgets(key, sizeof(key), stdin);

if (!p) { /* error */ }

size_t n = strlen(key);

if (n > 0 && key[n - 1] == '\n') {
  key[n - 1] = '\0';
} else {
  /* buffer too short or EOF reached without newline */
}

printf("The line was: '%s'\n", key);

It may be worth considering alternatives: If you only need one input, don't input the newline in the first place. If you need lots of lines, use  fread into a fixed-size buffer and scan for newlines yourself.


问:
Using bagof/3 only for the side effect
Solving a very simple exercise in Prolog: print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I ended up doing the following:

```<code>fizzbuzz :- forall( between(1, 100, X), fizzbuzz(X) ).
fizzbuzz(X) :- ( write_fb(X) ; write_n(X) ), nl.

write_fb(X) :- bagof(_, fb(X), _).
fb(X) :- X rem 3 =:= 0, write('Fizz').
fb(X) :- X rem 5 =:= 0, write('Buzz').

write_n(X) :- write(X).
</code>```

but isn't there any predicate or a control structure that would avoid using bagof/3 only for its side effect? (I am always a bit unsure with using predicates only for the side effects).

答:
Complementing the existing answers, I would like to show a more relational solution that I hope illustrates some unique benefits of applying a declarative programming paradigm such as logic programming to this question.

First, let us recapitulate the task:

print all numbers from 1 to 100, but instead of the number, print...

 'Fuzz' if number is a multiple of 3

 'Buzz' if multiple of 5

 and 'FizzBuzz' if both.

The tacit assumption, I presume, is that the numbers are limited to integers.

For simplicity, let us first restrict ourselves to a single integer, and let us describe the relation between such integer and the required output.

The three cases mentioned above can be quite directly translated to Prolog, using your Prolog ystem's CLP(FD) constraints for declarative integer arithmetic:

```
integer_output(N, 'Fuzz')     :- N #= 3*_.
integer_output(N, 'Buzz')     :- N #= 5*_.
integer_output(N, 'FizzBuzz') :- N #= 3*_, N #= 5*_.
```

That's not all though, because this yields for example:

```
?- integer_output(4, N).
<b>false.</b>
```

Hence, we need one more case, which we can for example formulate as:

```
integer_output(N, N)          :- N mod 3 #\= 0, N mod 5 #\= 0.
```

This simply states that in the event that none of the other cases applies, we output the number as is. The resulting relation is very general. For example, we can use it for concrete integers:

```
?- integer_output(1, O).
<b>O = 1.</b>

?- integer_output(3, O).
<b>O = 'Fuzz' ;</b>
false.
```

And we can also use it to write unit tests, for example:

```
?- integer_output(5, <b>'Buzz'</b>).
<b>true .</b>
```

Here, the intended output is already specified, and we can use the same relation to ask whether the output will be as required. That's a quite nice property of relations, and would not be so easy if we only wrote the output on the system terminal instead of making it explicit as a predicate argument as we did above.

But there's even more! We can also use the same relation in the other direction, where we ask for example: "Which integers result in the output Buzz?" Here it is:

```
?- integer_output(I, 'Buzz').
5*_680#=I.
```

That's a massive generalization of the earlier test case, and can serve as an additional assurance that we have covered all cases. In fact, we can even generalize this further, resulting in the most general query which asks how answers look like in general:

```
<b>?- integer_output(I, O).</b>
O = 'Fuzz',
3*_742#=I ;
O = 'Buzz',
5*_742#=I ;
O = 'FizzBuzz',
5*_1014#=I,
3*_1038#=I.
```

Let us reason more about the output. Obviously, we expect that the output is uniquely determined for each possible integer, right? Let us ask Prolog whether this is so, by asking for counterexamples of this property:

```
?- <b>dif(O1, O2),
   integer_output(I, O1),
   integer_output(I, O2).</b>
O1 = 'Fuzz',
O2 = 'Buzz',
5*_1046#=I,
3*_1070#=I ;
O1 = 'Fuzz',
O2 = 'FizzBuzz',
5*_1318#=I,
3*_1342#=I,
3*_1366#=I .
```

Now that doesn't look good : From the above, we already suspect that there may be cases of the same integer I yielding two different, equally justifiable, outputs O1 and O2.

And in fact, here's a concrete integer where this problem arises:

```
?- integer_output(<b>15</b>, O).
<b>O = 'Fuzz' ;
O = 'Buzz' ;
O = 'FizzBuzz' ;</b>
false.
```

So, it turns out, that the output is not uniquely determined! Let us follow our natural instinct and ask right away:

WHOSE FAULT IS THIS?

CLP(FD) CONSTRAINTS TO BLAME?

In fact, it turns out that using a declarative formulation has simply exposed an ambiguity in the task formulation. Prematurely committing to one of the solutions does not expose this problem.

What was probably meant was a task description that induces the following relation between an integer and the output:

```
integer_output(N, 'Fuzz')     :- N #= 3*_, <b>N mod 5 #\= 0</b>.
integer_output(N, 'Buzz')     :- N #= 5*_, <b>N mod 3 #\= 0</b>.
integer_output(N, 'FizzBuzz') :- N #= 3*_, N #= 5*_.
integer_output(N, N)          :- N mod 3 #\= 0, N mod 5 #\= 0.
```

This yields:

```
?- integer_output(15, O).
<b>O = 'FizzBuzz' ;</b>
false.
```

The other test cases still work as expected.

Now, using this relation as a building block, it is easy to lift it to lists of integers, using the meta-predicate maplist/3:

```
fizz_buzz(Ls) :-
        numlist(1, 100, Ls0),
        <b>maplist</b>(integer_output, Ls0, Ls).
```

Sample query and answer:

```
?- fizz_buzz(Ls).
<b>Ls = [1, 2, 'Fuzz', 4, 'Buzz', 'Fuzz', 7, 8, 'Fuzz'|...] ;</b>
false.
```

Note that we are not writing anything ourselves: We are using the Prolog toplevel to do the writing for us, and reason about arguments.

The advantage is clear: We can again write test cases for such a predicate. For example, we expect the following to hold, and it does:

```
?- <b>Ls = [1,2|_]</b>, fizz_buzz(Ls).
Ls = [1, 2, 'Fuzz', 4, 'Buzz', 'Fuzz', 7, 8, 'Fuzz'|...] .
```

So far, everything is completely pure and usable in all directions. I leave formatting such solutions as you want as an easy exercise.

If your Prolog system does not provide numlist/3, you can use bagof/3 to obtain the list of integers from 1 to 100 like this:

```
?- <b>bagof</b>(L, (L in 1..100,indomain(L)), Ls).
Ls = [1, 2, 3, 4, 5, 6, 7, 8, 9|...].
```

Thus, bagof/3 can be useful for this task, but I cannot recommend to use it for side-effects.

Title: Using bagof/3 only for the side effect

Body:
Solving a very simple exercise in Prolog: print all numbers from 1 to 100, but instead of the number, print 'Fuzz' if number is a multiple of 3, 'Buzz' if multiple of 5, and 'FizzBuzz' if both.

I ended up doing the following:

fizzbuzz :- forall( between(1, 100, X), fizzbuzz(X) ).
fizzbuzz(X) :- ( write_fb(X) ; write_n(X) ), nl.

write_fb(X) :- bagof(_, fb(X), _).
fb(X) :- X rem 3 =:= 0, write('Fizz').
fb(X) :- X rem 5 =:= 0, write('Buzz').

write_n(X) :- write(X).

but isn't there any predicate or a control structure that would avoid using bagof/3 only for its side effect? (I am always a bit unsure with using predicates only for the side effects).

Body:
Complementing the existing answers, I would like to show a more relational solution that I hope illustrates some unique benefits of applying a declarative programming paradigm such as logic programming to this question.

First, let us recapitulate the task:

print all numbers from 1 to 100, but instead of the number, print...

 'Fuzz' if number is a multiple of 3

 'Buzz' if multiple of 5

 and 'FizzBuzz' if both.

The tacit assumption, I presume, is that the numbers are limited to integers.

For simplicity, let us first restrict ourselves to a single integer, and let us describe the relation between such integer and the required output.

The three cases mentioned above can be quite directly translated to Prolog, using your Prolog ystem's CLP(FD) constraints for declarative integer arithmetic:

integer_output(N, 'Fuzz')     :- N #= 3*_.
integer_output(N, 'Buzz')     :- N #= 5*_.
integer_output(N, 'FizzBuzz') :- N #= 3*_, N #= 5*_.

That's not all though, because this yields for example:

?- integer_output(4, N).
false.

Hence, we need one more case, which we can for example formulate as:

integer_output(N, N)          :- N mod 3 #\= 0, N mod 5 #\= 0.

This simply states that in the event that none of the other cases applies, we output the number as is. The resulting relation is very general. For example, we can use it for concrete integers:

?- integer_output(1, O).
O = 1.

?- integer_output(3, O).
O = 'Fuzz' ;
false.

And we can also use it to write unit tests, for example:

?- integer_output(5, 'Buzz').
true .

Here, the intended output is already specified, and we can use the same relation to ask whether the output will be as required. That's a quite nice property of relations, and would not be so easy if we only wrote the output on the system terminal instead of making it explicit as a predicate argument as we did above.

But there's even more! We can also use the same relation in the other direction, where we ask for example: "Which integers result in the output Buzz?" Here it is:

?- integer_output(I, 'Buzz').
5*_680#=I.

That's a massive generalization of the earlier test case, and can serve as an additional assurance that we have covered all cases. In fact, we can even generalize this further, resulting in the most general query which asks how answers look like in general:

?- integer_output(I, O).
O = 'Fuzz',
3*_742#=I ;
O = 'Buzz',
5*_742#=I ;
O = 'FizzBuzz',
5*_1014#=I,
3*_1038#=I.

Let us reason more about the output. Obviously, we expect that the output is uniquely determined for each possible integer, right? Let us ask Prolog whether this is so, by asking for counterexamples of this property:

?- dif(O1, O2),
   integer_output(I, O1),
   integer_output(I, O2).
O1 = 'Fuzz',
O2 = 'Buzz',
5*_1046#=I,
3*_1070#=I ;
O1 = 'Fuzz',
O2 = 'FizzBuzz',
5*_1318#=I,
3*_1342#=I,
3*_1366#=I .

Now that doesn't look good : From the above, we already suspect that there may be cases of the same integer I yielding two different, equally justifiable, outputs O1 and O2.

And in fact, here's a concrete integer where this problem arises:

?- integer_output(15, O).
O = 'Fuzz' ;
O = 'Buzz' ;
O = 'FizzBuzz' ;
false.

So, it turns out, that the output is not uniquely determined! Let us follow our natural instinct and ask right away:

WHOSE FAULT IS THIS?

CLP(FD) CONSTRAINTS TO BLAME?

In fact, it turns out that using a declarative formulation has simply exposed an ambiguity in the task formulation. Prematurely committing to one of the solutions does not expose this problem.

What was probably meant was a task description that induces the following relation between an integer and the output:

integer_output(N, 'Fuzz')     :- N #= 3*_, N mod 5 #\= 0.
integer_output(N, 'Buzz')     :- N #= 5*_, N mod 3 #\= 0.
integer_output(N, 'FizzBuzz') :- N #= 3*_, N #= 5*_.
integer_output(N, N)          :- N mod 3 #\= 0, N mod 5 #\= 0.

This yields:

?- integer_output(15, O).
O = 'FizzBuzz' ;
false.

The other test cases still work as expected.

Now, using this relation as a building block, it is easy to lift it to lists of integers, using the meta-predicate maplist/3:

fizz_buzz(Ls) :-
        numlist(1, 100, Ls0),
        maplist(integer_output, Ls0, Ls).

Sample query and answer:

?- fizz_buzz(Ls).
Ls = [1, 2, 'Fuzz', 4, 'Buzz', 'Fuzz', 7, 8, 'Fuzz'|...] ;
false.

Note that we are not writing anything ourselves: We are using the Prolog toplevel to do the writing for us, and reason about arguments.

The advantage is clear: We can again write test cases for such a predicate. For example, we expect the following to hold, and it does:

?- Ls = [1,2|_], fizz_buzz(Ls).
Ls = [1, 2, 'Fuzz', 4, 'Buzz', 'Fuzz', 7, 8, 'Fuzz'|...] .

So far, everything is completely pure and usable in all directions. I leave formatting such solutions as you want as an easy exercise.

If your Prolog system does not provide numlist/3, you can use bagof/3 to obtain the list of integers from 1 to 100 like this:

?- bagof(L, (L in 1..100,indomain(L)), Ls).
Ls = [1, 2, 3, 4, 5, 6, 7, 8, 9|...].

Thus, bagof/3 can be useful for this task, but I cannot recommend to use it for side-effects.


问:
How can I create a 2D array with 1 to n in one column and zeros in the other - Python
I tried creating two arrays and then adding them together

```<code>array_nmax = np.arange (100)
array_zeros = np.zeros (100, dtype = np.int)
array_final = np.append (array_nmax,np.zeros, axis = 0)
</code>```

but it says that they're not the same dimensions even though they should be both 100 by 1 arrays.

答:
Slower than @GrigorisG's answer and not so readable, but still a possible solution:

```<code>np.arange(100)[:,None] * [1,0]
</code>```

By the way, there are two problems in your solution. The first one is that, by mistake, the second argument to concatenate is the function np.zeros instead of the newly created array array_zeros. Even after fixing this, the second problem is that the two arrays will be concatenated along their zero-th dimension and the result will be an array of shape (200,). You should use np.column_stack as suggested by @Divakar.

Body:
I tried creating two arrays and then adding them together

array_nmax = np.arange (100)
array_zeros = np.zeros (100, dtype = np.int)
array_final = np.append (array_nmax,np.zeros, axis = 0)

but it says that they're not the same dimensions even though they should be both 100 by 1 arrays.

Body:
Slower than @GrigorisG's answer and not so readable, but still a possible solution:

np.arange(100)[:,None] * [1,0]

By the way, there are two problems in your solution. The first one is that, by mistake, the second argument to concatenate is the function np.zeros instead of the newly created array array_zeros. Even after fixing this, the second problem is that the two arrays will be concatenated along their zero-th dimension and the result will be an array of shape (200,). You should use np.column_stack as suggested by @Divakar.


问:
Code Golf: Leibniz formula for Pi
I recently posted one of my favourite interview whiteboard coding questions in "What's your more controversial programming opinion", which is to write a function that computes Pi using the Leibniz formula.

It can be approached in a number of different ways, and the exit condition takes a bit of thought, so I thought it might make an interesting code golf question. Shortest code wins!

Given that Pi can be estimated using the function 4 * (1 - 1/3 + 1/5 - 1/7 + ...) with more terms giving greater accuracy, write a function that calculates Pi to within 0.00001.

Edit: 3 Jan 2008

As suggested in the comments I changed the exit condition to be within 0.00001 as that's what I really meant (an accuracy 5 decimal places is much harder due to rounding and so I wouldn't want to ask that in an interview, whereas within 0.00001 is an easier to understand and implement exit condition).

Also, to answer the comments, I guess my intention was that the solution should compute the number of iterations, or check when it had done enough, but there's nothing to prevent you from pre-computing the number of iterations and using that number. I really asked the question out of interest to see what people would come up with.

答:
After noting that

```(= (- (/ 4 n)
      (/ 4 (+ n 2)))
   (/ 8 n (+ n 2)))```

or, in a more familiar notation:

```4    4      8
- - --- = ------
n   n+2   n(n+2)```

Common Lisp, with a do* loop (62 essential characters):

```<code>(do* ((n 1 (+ n 4))
      (p 8/3 (+ p (/ 8 n (+ n 2)))))
     ((< (- pi p) 1e-6)
      p)
</code>```

with a tail recursive function (70 essential characters):

```<code>(defun l (n p)
  (if (< (- pi p) 1e-6)
      p
      (l (+ n 4)
          (+ p (/ 8 n (+ n 2))))))
(l 1 0)
</code>```

and with the extended loop (86 essential characters):

```<code>(loop for n from 1 by 4
      sum (/ 8 n (+ n 2)) into p
      until (< (- pi p) 1e-6)
      finally (return p))
</code>```

all under the presumption that preliminary checks how far we have to go to get the desired accuracy are cheating.

OwnerDisplayName: Greg Beech

ContentLicense: CC BY-SA 2.5

Title: Code Golf: Leibniz formula for Pi

LastEditorDisplayName: dreeves

Body:
After noting that

(= (- (/ 4 n)
      (/ 4 (+ n 2)))
   (/ 8 n (+ n 2)))

or, in a more familiar notation:

4    4      8
- - --- = ------
n   n+2   n(n+2)

Common Lisp, with a do* loop (62 essential characters):

(do* ((n 1 (+ n 4))
      (p 8/3 (+ p (/ 8 n (+ n 2)))))
     ((< (- pi p) 1e-6)
      p)

with a tail recursive function (70 essential characters):

(defun l (n p)
  (if (< (- pi p) 1e-6)
      p
      (l (+ n 4)
          (+ p (/ 8 n (+ n 2))))))
(l 1 0)

and with the extended loop (86 essential characters):

(loop for n from 1 by 4
      sum (/ 8 n (+ n 2)) into p
      until (< (- pi p) 1e-6)
      finally (return p))

all under the presumption that preliminary checks how far we have to go to get the desired accuracy are cheating.

OwnerDisplayName: Harleqin

LastEditorDisplayName: Harleqin


问:
Junit Testing methods and constructors in separate classes
I am looking for good practice about testing constructor and methods in Junit. In my currently project, I testing constructor and method in separate test class. For example, I have Monitor class. MonitorTestConstructors class test a constructor for various parameters and validate created object but also check exception witch constructor throw. In MonitorTestMethod class, I test methods but object is created in @Before method. Is it good practice? How do you deal with it? What are your opinions/experiences about that.</p>

答:
A couple tips:

Class naming convention generally is such that test class names are a concatenation of "Test" and the class it is testing, in your case class TestMonitor.

There is no rule that you need to use the @Before annotation anywhere.  That's typically used for initializing dependencies like file paths and other objects that you aren't testing.

Keep the FIRST (FAST, ISOLATED, REPEATABLE, SELF-VALIDATING, THOROUGH) principles in mind, where "ISOLATED" is most pertinent to your question.  You should instantiate a new Monitor() object in each test method, rather than recycling the same instance for each test, because in the case of failures in a complex testing sequence it will be harder than necessary to de-bug.


问:
How to identify which missing Java Libraries to make JAXB to work?
My Tibco BW 6.3.2 project invokes some Java Code that works on my machine, but I'm having issues on the server.

At first, I got this error

```<code> <CausedBy> java.lang.ClassNotFoundException: com.sun.xml.bind.v2.model.annotation.AnnotationReader cannot be found
</code>```

So Googled it and added jaxb-impl.jar and jaxb-core.jar(JAXB v2.2.11). Again, it worked on my machine without adding these to the classpath. But once I added them, I got this error on the server:

```<code><CausedBy> java.lang.RuntimeException: Provider for class javax.xml.parsers.SAXParserFactory cannot be created
<CausedBy> java.util.ServiceConfigurationError: javax.xml.parsers.SAXParserFactory: Provider org.apache.xerces.jaxp.SAXParserFactoryImpl not found
</code>```

Again, I Googled it and added xercesImpl.jar. But now I'm getting this on my machine & server :

```<code><CausedBy> java.lang.ClassCastException: org.apache.xerces.parsers.XIncludeAwareParserConfiguration cannot be cast to org.apache.xerces.xni.parser.XMLParserConfiguration
</code>```

After some google searching, I've determined there are 2 xerces jars in my project, but I can't find the second one. Any thoughts on how to do that? OR does anyone have a different solution?

Side note, the java code works perfectly fine in Eclipse without any of these libraries added to the class path. (All devices are using Sun JDK 1.8.0_92)

答:
EDITED:
I removed all the jaxb libraries I added and defined them in the Module Descriptors -> Dependencies -> Imported Packages.

Body:
My Tibco BW 6.3.2 project invokes some Java Code that works on my machine, but I'm having issues on the server.

At first, I got this error

 <CausedBy> java.lang.ClassNotFoundException: com.sun.xml.bind.v2.model.annotation.AnnotationReader cannot be found

So Googled it and added jaxb-impl.jar and jaxb-core.jar(JAXB v2.2.11). Again, it worked on my machine without adding these to the classpath. But once I added them, I got this error on the server:

<CausedBy> java.lang.RuntimeException: Provider for class javax.xml.parsers.SAXParserFactory cannot be created
<CausedBy> java.util.ServiceConfigurationError: javax.xml.parsers.SAXParserFactory: Provider org.apache.xerces.jaxp.SAXParserFactoryImpl not found

Again, I Googled it and added xercesImpl.jar. But now I'm getting this on my machine & server :

<CausedBy> java.lang.ClassCastException: org.apache.xerces.parsers.XIncludeAwareParserConfiguration cannot be cast to org.apache.xerces.xni.parser.XMLParserConfiguration

After some google searching, I've determined there are 2 xerces jars in my project, but I can't find the second one. Any thoughts on how to do that? OR does anyone have a different solution?

Side note, the java code works perfectly fine in Eclipse without any of these libraries added to the class path. (All devices are using Sun JDK 1.8.0_92)


问:
qemu-native error when building core-image-minimal with yocto
I want to build the core-image-minimal with yocto and it fails. To set everything up I use the following steps:

```<code>sudo apt-get install gawk wget git-core diffstat unzip texinfo gcc-multilib build-essential chrpath socat cpio python python3 python3-pip python3-pexpect cmake
git clone git://git.yoctoproject.org/poky.git poky.git
cd poky.git
git checkout -b morty remotes/origin/morty
. oe-init-build-env
cd ..
git clone https://github.com/altera-opensource/meta-altera.git meta-altera
cd meta-altera
git checkout -b angstrom-v2015.12-yocto2.0 remotes/origin/angstrom-v2015.12-yocto2.0
</code>```

Afterwards I add the path to meta-altera to build/conf/bblayers.conf and MACHINE = "cyclone5" to build/conf/local.conf. I would expect, that now bitbake core-image-minimal would run through, but it stops with the following error:

```<code>WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/openbios-ppc' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/openbios-sparc32' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/openbios-sparc64' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/s390-ccw.img' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/u-boot.e500' from qemu-native was already stripped, this will prevent future debugging!
ERROR: qemu-native-2.7.0-r1 do_populate_sysroot: runstrip: ''strip' --remove-section=.comment --remove-section=.note '/mydirectory/poky.git/build/tmp/work/x86_64-linux/qemu-native/2.7.0-r1/sysroot-destdir/media/sln/Data/yocto/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/palcode-clipper'' strip command failed with 1 (b"strip: Unable to recognise the format of the input file `/mydirectory/poky.git/build/tmp/work/x86_64-linux/qemu-native/2.7.0-r1/sysroot-destdir/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/palcode-clipper'\n")
</code>```

I got rid of the warnings by adding INSANE_SKIP_qemu-native = "already-stripped" to poky.git/meta/recipes-devtools/qemu/qemu.inc but the error remains. I am using Ubunut 16.04 as my build machine. Any help or tipps are appreciated.

If I continue building, I get an error while building gcc-runtime-6.2.0-r0 do_compile and it stops. I assume that this error is based on the qemu error.

Here is the build config shown in bitbake:

```<code>Build Configuration:
BB_VERSION        = "1.32.0"
BUILD_SYS         = "x86_64-linux"
NATIVELSBSTRING   = "universal"
TARGET_SYS        = "arm-poky-linux-gnueabi"
MACHINE           = "cyclone5"
DISTRO            = "poky"
DISTRO_VERSION    = "2.2.1"
TUNE_FEATURES     = "arm armv7a vfp  neon        callconvention-hard"
TARGET_FPU        = "hard"
meta
meta-poky
meta-yocto-bsp    = "morty:924e576b8930fd2268d85f0b151e5f68a3c2afce"
meta-altera       = "angstrom-v2015.12-yocto2.0:3cfd56bb15673795435cf7684ef9c723283a6bce"
</code>```

答:
It looks like you're checking out the Yocto 2.0 branch of the meta-altera layer. Yocto 2.0 was Jethro. You're checking out the Morty branch of Poky which is Yocto 2.2. Try checking out the jethro branch of Poky with by executing the following Git command while in your poky.git folder:</p>

```<code>git checkout -b jethro remotes/origin/jethro
</code>```

Body:
I want to build the core-image-minimal with yocto and it fails. To set everything up I use the following steps:

sudo apt-get install gawk wget git-core diffstat unzip texinfo gcc-multilib build-essential chrpath socat cpio python python3 python3-pip python3-pexpect cmake
git clone git://git.yoctoproject.org/poky.git poky.git
cd poky.git
git checkout -b morty remotes/origin/morty
. oe-init-build-env
cd ..
git clone https://github.com/altera-opensource/meta-altera.git meta-altera
cd meta-altera
git checkout -b angstrom-v2015.12-yocto2.0 remotes/origin/angstrom-v2015.12-yocto2.0

Afterwards I add the path to meta-altera to build/conf/bblayers.conf and MACHINE = "cyclone5" to build/conf/local.conf. I would expect, that now bitbake core-image-minimal would run through, but it stops with the following error:

WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/openbios-ppc' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/openbios-sparc32' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/openbios-sparc64' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/s390-ccw.img' from qemu-native was already stripped, this will prevent future debugging!
WARNING: qemu-native-2.7.0-r1 do_populate_sysroot: File '/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/u-boot.e500' from qemu-native was already stripped, this will prevent future debugging!
ERROR: qemu-native-2.7.0-r1 do_populate_sysroot: runstrip: ''strip' --remove-section=.comment --remove-section=.note '/mydirectory/poky.git/build/tmp/work/x86_64-linux/qemu-native/2.7.0-r1/sysroot-destdir/media/sln/Data/yocto/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/palcode-clipper'' strip command failed with 1 (b"strip: Unable to recognise the format of the input file `/mydirectory/poky.git/build/tmp/work/x86_64-linux/qemu-native/2.7.0-r1/sysroot-destdir/mydirectory/poky.git/build/tmp/sysroots/x86_64-linux/usr/share/qemu/palcode-clipper'\n")

I got rid of the warnings by adding INSANE_SKIP_qemu-native = "already-stripped" to poky.git/meta/recipes-devtools/qemu/qemu.inc but the error remains. I am using Ubunut 16.04 as my build machine. Any help or tipps are appreciated.

If I continue building, I get an error while building gcc-runtime-6.2.0-r0 do_compile and it stops. I assume that this error is based on the qemu error.

Here is the build config shown in bitbake:

Build Configuration:
BB_VERSION        = "1.32.0"
BUILD_SYS         = "x86_64-linux"
NATIVELSBSTRING   = "universal"
TARGET_SYS        = "arm-poky-linux-gnueabi"
MACHINE           = "cyclone5"
DISTRO            = "poky"
DISTRO_VERSION    = "2.2.1"
TUNE_FEATURES     = "arm armv7a vfp  neon        callconvention-hard"
TARGET_FPU        = "hard"
meta
meta-poky
meta-yocto-bsp    = "morty:924e576b8930fd2268d85f0b151e5f68a3c2afce"
meta-altera       = "angstrom-v2015.12-yocto2.0:3cfd56bb15673795435cf7684ef9c723283a6bce"

Body:
It looks like you're checking out the Yocto 2.0 branch of the meta-altera layer. Yocto 2.0 was Jethro. You're checking out the Morty branch of Poky which is Yocto 2.2. Try checking out the jethro branch of Poky with by executing the following Git command while in your poky.git folder:

git checkout -b jethro remotes/origin/jethro


问:
Implementing Total Parsers in Idris Based on a Paper on Agda
I am trying to implement total parsers with Idris, based on this paper. First I tried to implement the more basic recogniser type P:

```<code>Tok : Type
Tok = Char

mutual
  data P : Bool -> Type where
    fail : P False
    empty : P True
    sat : (Tok -> Bool) -> P False
    (<|>) : P n -> P m -> P (n || m)
    (.) : LazyP m n -> LazyP n m -> P (n && m)
    nonempty : P n -> P False
    cast : (n = m) -> P n -> P m

  LazyP : Bool -> Bool -> Type
  LazyP False n = Lazy (P n)
  LazyP True  n = P n

DelayP : P n -> LazyP b n
DelayP {b = False} x = Delay x
DelayP {b = True } x = x

ForceP : LazyP b n -> P n
ForceP {b = False} x = Force x
ForceP {b = True } x = x

Forced : LazyP b n -> Bool
Forced {b = b} _ = b
</code>```

This works fine, but I cannot work out how to define the first example from the paper. In Agda it is:

```<code>left-right : P false
left-right = ♯ left-right . ♯ left-right
</code>```

But I cannot get this to work in Idris:

```<code>lr : P False
lr = (Delay lr . Delay lr)
</code>```

produces

```<code>Can't unify
    Lazy' t (P False)
with
    LazyP n m
</code>```

It will typecheck if you give it some help, like this:

```<code>lr : P False
lr = (the (LazyP False False) (Delay lr)) . (the (LazyP False False) (Delay lr))
</code>```

But this is rejected by the totality checker, as are other variants like

```<code>lr : P False
lr = Delay (the (LazyP True False) lr) . (the (LazyP False False) (Delay lr))
</code>```

It doesn't help that I'm not entirely sure how the ♯ operator binds in Agda.

Can anyone see a way to get define the left-right recogniser in Idris? Is my definition of P wrong, or my attempt at translating the function? Or is Idris's totality checker just not quite up to this coinductive stuff?

答:
Currently trying to port this library myself, it seems like Agda infers different implicits to Idris. These are the missing implicits:</p>

```<code>%default total

mutual
  data P : Bool -> Type where
    Fail : P False
    Empty : P True
    Tok : Char -> P False
    (<|>) : P n -> P m -> P (n || m)
    (.) : {n,m: Bool} -> LazyP m n -> LazyP n m -> P (n && m)

  LazyP : Bool -> Bool -> Type
  LazyP False n = Inf (P n)
  LazyP True  n = P n

lr : P False
lr = (.) {n=False} {m=False} (Delay lr) (Delay lr)
</code>```

Body:
I am trying to implement total parsers with Idris, based on this paper. First I tried to implement the more basic recogniser type P:

Tok : Type
Tok = Char

mutual
  data P : Bool -> Type where
    fail : P False
    empty : P True
    sat : (Tok -> Bool) -> P False
    (<|>) : P n -> P m -> P (n || m)
    (.) : LazyP m n -> LazyP n m -> P (n && m)
    nonempty : P n -> P False
    cast : (n = m) -> P n -> P m

  LazyP : Bool -> Bool -> Type
  LazyP False n = Lazy (P n)
  LazyP True  n = P n

DelayP : P n -> LazyP b n
DelayP {b = False} x = Delay x
DelayP {b = True } x = x

ForceP : LazyP b n -> P n
ForceP {b = False} x = Force x
ForceP {b = True } x = x

Forced : LazyP b n -> Bool
Forced {b = b} _ = b

This works fine, but I cannot work out how to define the first example from the paper. In Agda it is:

left-right : P false
left-right = ♯ left-right . ♯ left-right

But I cannot get this to work in Idris:

lr : P False
lr = (Delay lr . Delay lr)

produces

Can't unify
    Lazy' t (P False)
with
    LazyP n m

It will typecheck if you give it some help, like this:

lr : P False
lr = (the (LazyP False False) (Delay lr)) . (the (LazyP False False) (Delay lr))

But this is rejected by the totality checker, as are other variants like

lr : P False
lr = Delay (the (LazyP True False) lr) . (the (LazyP False False) (Delay lr))

It doesn't help that I'm not entirely sure how the ♯ operator binds in Agda.

Can anyone see a way to get define the left-right recogniser in Idris? Is my definition of P wrong, or my attempt at translating the function? Or is Idris's totality checker just not quite up to this coinductive stuff?

Body:
Currently trying to port this library myself, it seems like Agda infers different implicits to Idris. These are the missing implicits:

%default total

mutual
  data P : Bool -> Type where
    Fail : P False
    Empty : P True
    Tok : Char -> P False
    (<|>) : P n -> P m -> P (n || m)
    (.) : {n,m: Bool} -> LazyP m n -> LazyP n m -> P (n && m)

  LazyP : Bool -> Bool -> Type
  LazyP False n = Inf (P n)
  LazyP True  n = P n

lr : P False
lr = (.) {n=False} {m=False} (Delay lr) (Delay lr)


问:
Has anyone gotten a ruby memcached client working on Windows?
Google'd around.  Getting stuck on installing libmemcached.

UPDATE:
This is the new error log for Ruby 1.9.3

```<code>checking for pthread-config... no
configure: error: could not find libpthread
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.
Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/Ruby193/bin/ruby
extconf.rb:35:in `run': 'env CFLAGS='-fPIC  -O3 -g -Wextra -Wno-unused-parameter -Wno-
        from extconf.rb:53:in `block (2 levels) in check_libmemcached'
        from extconf.rb:52:in `chdir'
        from extconf.rb:52:in `block in check_libmemcached'
        from extconf.rb:49:in `chdir'
        from extconf.rb:49:in `check_libmemcached'
        from extconf.rb:70:in `<main>'
Touching aclocal.m4 in libmemcached.
touch -r libmemcached-0.32/m4/visibility.m4 libmemcached-0.32/configure.ac libmemcache
Configuring libmemcached.
env CFLAGS='-fPIC  -O3 -g -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-lon
Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/memcached-1.3.5
Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/gems/memcached-1.3.5/ext/gem_make.out
</code>```

My installation is Ruby 1.8.7 from rubyinstaller.org. (mingw32 version)
Installed Northscale/membase (membase.org).  Installed fine.

Then tried both

gem install memcached-northscale --no-ri --no-rdoc
and
gem install memcached --no-ri --no-rdoc

Both of them want to install libmemcached and build from source... OK..

C:/Ruby187/bin/ruby.exe extconf.rb

Building libmemcached.

tar xzf libmemcached-0.32.tar.gz 2>&1

Patching libmemcached source.

patch -p1 -Z < libmemcached.patch

patching file libmemcached-0.32/libmemcached/memcached_response.c

Assertion failed: hunk, file ../patch-2.5.9-src/patch.c, line 354

This URL suggested a fix .. Windows handling of CR/CRLF.

http://www.mail-archive.com/gnuwin32-users@lists.sourceforge.net/msg01528.html

But despite altering the .patch files, I still get a failure:

C:\Ruby187\lib\ruby\gems\1.8\gems\memcached-northscale-0.19.5.4\ext>ruby extconf.rb

Building libmemcached.

tar xzf libmemcached-0.32.tar.gz 2>&1

Patching libmemcached source.

patch -p1 -Z < libmemcached.patch

[... snip ...]

Patching libmemcached with SASL support.

patch -p1 -Z < sasl.patch

[... snip ...]

The next patch would create the file libmemcached-0.32/config/config.rpath,

which already exists!  Assume -R? [n]

Apply anyway? [n]

Skipping patch.

1 out of 1 hunk ignored -- saving rejects to file libmemcached-0.32/config/config.rpath.rej

patching file libmemcached-0.32/config.h.in

patching file libmemcached-0.32/configure

patch: ** malformed patch at line 26625: '

* extconf.rb failed *

Any ideas?  Surely someone out there uses Windows, Ruby, and Memcache???

答: The libmemcached support for Windows is in its infancy.  Generally, people use a ruby native client on Windows, just as you've found.</p>

Body:
Google'd around.  Getting stuck on installing libmemcached.

UPDATE:
This is the new error log for Ruby 1.9.3

checking for pthread-config... no
configure: error: could not find libpthread
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.
Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/Ruby193/bin/ruby
extconf.rb:35:in `run': 'env CFLAGS='-fPIC  -O3 -g -Wextra -Wno-unused-parameter -Wno-
        from extconf.rb:53:in `block (2 levels) in check_libmemcached'
        from extconf.rb:52:in `chdir'
        from extconf.rb:52:in `block in check_libmemcached'
        from extconf.rb:49:in `chdir'
        from extconf.rb:49:in `check_libmemcached'
        from extconf.rb:70:in `'
Touching aclocal.m4 in libmemcached.
touch -r libmemcached-0.32/m4/visibility.m4 libmemcached-0.32/configure.ac libmemcache
Configuring libmemcached.
env CFLAGS='-fPIC  -O3 -g -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-lon
Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/memcached-1.3.5
Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/gems/memcached-1.3.5/ext/gem_make.out

My installation is Ruby 1.8.7 from rubyinstaller.org. (mingw32 version)
Installed Northscale/membase (membase.org).  Installed fine.

Then tried both

gem install memcached-northscale --no-ri --no-rdoc
and
gem install memcached --no-ri --no-rdoc

Both of them want to install libmemcached and build from source... OK..

C:/Ruby187/bin/ruby.exe extconf.rb

Building libmemcached.

tar xzf libmemcached-0.32.tar.gz 2>&1

Patching libmemcached source.

patch -p1 -Z < libmemcached.patch

patching file libmemcached-0.32/libmemcached/memcached_response.c

Assertion failed: hunk, file ../patch-2.5.9-src/patch.c, line 354

This URL suggested a fix .. Windows handling of CR/CRLF.

http://www.mail-archive.com/gnuwin32-users@lists.sourceforge.net/msg01528.html

But despite altering the .patch files, I still get a failure:

C:\Ruby187\lib\ruby\gems\1.8\gems\memcached-northscale-0.19.5.4\ext>ruby extconf.rb

Building libmemcached.

tar xzf libmemcached-0.32.tar.gz 2>&1

Patching libmemcached source.

patch -p1 -Z < libmemcached.patch

[... snip ...]

Patching libmemcached with SASL support.

patch -p1 -Z < sasl.patch

[... snip ...]

The next patch would create the file libmemcached-0.32/config/config.rpath,

which already exists!  Assume -R? [n]

Apply anyway? [n]

Skipping patch.

1 out of 1 hunk ignored -- saving rejects to file libmemcached-0.32/config/config.rpath.rej

patching file libmemcached-0.32/config.h.in

patching file libmemcached-0.32/configure

patch: ** malformed patch at line 26625: '

* extconf.rb failed *

Any ideas?  Surely someone out there uses Windows, Ruby, and Memcache???


问:
Static const declaration, constexpr definition of variable, valid c++?
Example:
In header file:

```<code>class Foo
{
     static const int IntArray[];
};
</code>```

In source file:

```<code>constexpr int Foo::IntArray[] = { 1, 2, 3, 4 };
</code>```

This compiles on g++ and allows me to put the initializer list in the source file in stead of the header. (if it were constexpr in the header the compiler requires immediate initialization in the header). While still allowing the array to be used in constexpr evaluations...

Is this valid, portable C++ ?

答:
The Right Way

Before we begin the language-lawyering, the correct approach is to do it the other way around.  In the header file:

```<code>class Foo
{
     static constexpr int IntArray[] = { 1, 2, 3, 4 };
};
</code>```

And then in a source file:

```<code>constexpr int Foo::IntArray[];
</code>```

If you declare a static constexpr class data member in the class definition, you must initialize it then and there.  This is optional for static const data members.  If you use the static constexpr data member anywhere in the program, you must give a definition like the one above, in exactly one source file, with no initializer.

What the (Draft) Standard Says

The example code in the question is bad style, and apparently at least one compiler rejects it, but it does in fact seem to comply with the C++14 draft standard.  [dcl/constexpr] says:

The constexpr specifier shall be applied only to the definition of a variable or variable template, the declaration of a function or function template, or the declaration of a static data member of a literal type.  If any declaration of a function, function template, or variable template has a constexpr specifier, then all its declarations shall contain the constexpr specifier.

Notice whose declarations are, by omission, not all required to contain the constexpr specifier.

Later in the same section:

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized. [...]

But see also [class.static.data]:

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [Note: In both these cases, the member may appear in constant expressions. — end note ] The member shall still be defined in a namespace scope if it is odr-used in the program and the namespace scope definition shall not contain an initializer.

In this context, the odr in “odr-used” stands for the one-definition-rule and means “whose name appears as a potentially-evaluated expression.” ([basic.def.odr])  The last sentence means that, if you declare, static constexpr int foo = 0; in the class definition, and you will later use it in an expression, such as int x = MyClass::foo;, then one and only one source file needs to have a line like constexpr int MyClass::foo; in it, so the linker knows which object file to put it in.

Body:
Example:
In header file:

class Foo
{
     static const int IntArray[];
};

In source file:

constexpr int Foo::IntArray[] = { 1, 2, 3, 4 };

This compiles on g++ and allows me to put the initializer list in the source file in stead of the header. (if it were constexpr in the header the compiler requires immediate initialization in the header). While still allowing the array to be used in constexpr evaluations...

Is this valid, portable C++ ?

Body:
The Right Way

Before we begin the language-lawyering, the correct approach is to do it the other way around.  In the header file:

class Foo
{
     static constexpr int IntArray[] = { 1, 2, 3, 4 };
};

And then in a source file:

constexpr int Foo::IntArray[];

If you declare a static constexpr class data member in the class definition, you must initialize it then and there.  This is optional for static const data members.  If you use the static constexpr data member anywhere in the program, you must give a definition like the one above, in exactly one source file, with no initializer.

What the (Draft) Standard Says

The example code in the question is bad style, and apparently at least one compiler rejects it, but it does in fact seem to comply with the C++14 draft standard.  [dcl/constexpr] says:

The constexpr specifier shall be applied only to the definition of a variable or variable template, the declaration of a function or function template, or the declaration of a static data member of a literal type.  If any declaration of a function, function template, or variable template has a constexpr specifier, then all its declarations shall contain the constexpr specifier.

Notice whose declarations are, by omission, not all required to contain the constexpr specifier.

Later in the same section:

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized. [...]

But see also [class.static.data]:

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [Note: In both these cases, the member may appear in constant expressions. — end note ] The member shall still be defined in a namespace scope if it is odr-used in the program and the namespace scope definition shall not contain an initializer.

In this context, the odr in “odr-used” stands for the one-definition-rule and means “whose name appears as a potentially-evaluated expression.” ([basic.def.odr])  The last sentence means that, if you declare, static constexpr int foo = 0; in the class definition, and you will later use it in an expression, such as int x = MyClass::foo;, then one and only one source file needs to have a line like constexpr int MyClass::foo; in it, so the linker knows which object file to put it in.


问:
Spring Bean injection fails on OpenShift
I added a new Spring Integration configuration with Spring Messaging into our Spring Boot application.
The application deploys and runs properly on my MAC.

However,
when deployed to OpenShift (using OpenJDK) or Docker runtime
deployments fail with the following error:

```<code>Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.messaging.MessageChannel' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations:
{@org.springframework.beans.factory.annotation.Qualifier(value=ftpChannel)}
</code>```

Here is a simplified version of the code failing with the same error:

```<code>import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Service;

@Service
public class FtpService {

    private final MessageChannel ftpClientInboundChannel;

    public FtpService(@Qualifier("ftpChannel") MessageChannel ftpClientInboundChannel) {
        this.ftpClientInboundChannel = ftpClientInboundChannel;
    }
}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

@Configuration
@IntegrationComponentScan
public class FtpClientConfiguration {

    @Bean
    @ServiceActivator(inputChannel = "ftpChannel")
    public MessageHandler ftpPayableHandler() {

        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {

            }
        };
    }

}
</code>```

答:
The issue was resolved by adding of a message channel bean:</p>

```<code>@Bean
public MessageChannel ftpChannel() {
    return new DirectChannel();
}
</code>```

Body:
I added a new Spring Integration configuration with Spring Messaging into our Spring Boot application.
The application deploys and runs properly on my MAC.

However,
when deployed to OpenShift (using OpenJDK) or Docker runtime
deployments fail with the following error:

Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.messaging.MessageChannel' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations:
{@org.springframework.beans.factory.annotation.Qualifier(value=ftpChannel)}

Here is a simplified version of the code failing with the same error:

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Service;

@Service
public class FtpService {

    private final MessageChannel ftpClientInboundChannel;

    public FtpService(@Qualifier("ftpChannel") MessageChannel ftpClientInboundChannel) {
        this.ftpClientInboundChannel = ftpClientInboundChannel;
    }
}

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

@Configuration
@IntegrationComponentScan
public class FtpClientConfiguration {

    @Bean
    @ServiceActivator(inputChannel = "ftpChannel")
    public MessageHandler ftpPayableHandler() {

        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {

            }
        };
    }

}

Body:
The issue was resolved by adding of a message channel bean:

@Bean
public MessageChannel ftpChannel() {
    return new DirectChannel();
}


问:
AngularJS routing always to main
I have the next code:

```<code>var app = angular.module('ForclazApp', ['ngRoute']);

app.config(function($routeProvider){
    $routeProvider
        .when("/", {
            templateUrl: "partials/header.html"
        })
        .when("/motos", {
            templateUrl: "partials/motos.html"
        })
        .when("/repuestos", {
            templateUrl: "partials/repuestos.html"
        })
        .when("/taller", {
            templateUrl: "partials/taller.html"
        })
        .when("/blog", {
            templateUrl: "partials/blog.html"
        })
        .when("/contacto", {
            templateUrl: "partials/contacto.html"
        })
        .otherwise({
            redirectTo: '/'
        });
});
</code>```

Doesn't matter in which link you click, it always redirects to header.html template. I'm using AngularJS 1.6.3.
The console log doesn't show me any error.

The menu's links:

```<code><ul class="nav navbar-nav navbar-right">
    <li class="nav-li"><a href="#/" class="nav-link">Inicio </a></li>
    <li class="nav-li"><a href="#/motos" class="nav-link">Motos </a></li>
    <li class="nav-li"><a href="#/repuestos" class="nav-link">Repuestos </a></li>
    <li class="nav-li"><a href="#/taller" class="nav-link">Taller </a></li>
    <li class="nav-li"><a href="#/blog" class="nav-link">Blog </a></li>
    <li class="nav-li"><a href="#/contacto" class="nav-link">Contacto </a></li>
</ul>
</code>```

答:
```<code> .otherwise({
        redirectTo: '/'
    });
</code>```

Is basically saying that if none of the other options are matched go to to the route /. Which in your case is main. Your .when(.. checks aren't matching the way you want them to.

In your html. Remove the / from all of your links. So it should look like this:

```<code><li class="nav-li"><a href="#contacto" class="nav-link">Contacto </a></li>
</code>```

that will match it the way you want it to.

Title: AngularJS routing always to main

Body:
I have the next code:

var app = angular.module('ForclazApp', ['ngRoute']);

app.config(function($routeProvider){
    $routeProvider
        .when("/", {
            templateUrl: "partials/header.html"
        })
        .when("/motos", {
            templateUrl: "partials/motos.html"
        })
        .when("/repuestos", {
            templateUrl: "partials/repuestos.html"
        })
        .when("/taller", {
            templateUrl: "partials/taller.html"
        })
        .when("/blog", {
            templateUrl: "partials/blog.html"
        })
        .when("/contacto", {
            templateUrl: "partials/contacto.html"
        })
        .otherwise({
            redirectTo: '/'
        });
});

Doesn't matter in which link you click, it always redirects to header.html template. I'm using AngularJS 1.6.3.
The console log doesn't show me any error.

The menu's links:

Inicio

Motos

Repuestos

Taller

Blog

Contacto

Body:
 .otherwise({
        redirectTo: '/'
    });

Is basically saying that if none of the other options are matched go to to the route /. Which in your case is main. Your .when(.. checks aren't matching the way you want them to.

In your html. Remove the / from all of your links. So it should look like this:

<li class="nav-li"><a href="#contacto" class="nav-link">Contacto </a></li>

that will match it the way you want it to.


问:
Dynamic property filter using Jackson 2
I am building a REST service platform in which we have to support following query pattern:

format=summary which means we have to deserialize only the POJO attributes annotated with our custom annotation @Summary

format=detail which means we have to deserialize only the POJO attributes annotated with our custom annotation @Detail

fields=prop1,prop2,prop3 which means we have to deserialize the POJO attributes provided in the query.

I am using Jackson 2 (v2.3.0) I tried followings:

Developed custom annotations (@Summary and @Detail)

Developed a JsonFilter (code shown below) and annotated @JsonFilter to my POJO classes.

Location.java

```<code>@JsonFilter("customFilter")
public class Location implements Serializable {
@Summary
@Detail
private String id;

@Summary
@Detail
private String name;

@Summary
@Detail
private Address address;

// ... getters n setters
</code>```

Address.java

```<code>@JsonFilter("customFilter")
public class Address implements Serializable {

  @Detail
  private String addressLine1;

  @Detail
  private String addressLine2;

  @Detail
  private String addressLine3;

  @Detail
  @Summary
  private String city;

  @Summary
  @Detail
  private String postalCode;

  // ... getters n setters
</code>```

CustomFilter.java

```<code>public class CustomFilter extends SimpleBeanPropertyFilter {
  @Override
  protected boolean include(BeanPropertyWriter propertyWriter) {
    if(logger.isDebugEnabled()) {
      logger.debug("include(BeanPropertyWriter) method called..");
    }

    return this.deserialize(propertyWriter);
  }

  @Override
  protected boolean include(PropertyWriter propertyWriter) {
    if(logger.isDebugEnabled()) {
      logger.debug("include(PropertyWriter) method called..");
    }

    return this.deserialize((BeanPropertyWriter) propertyWriter);
  }

  private boolean deserialize(final BeanPropertyWriter beanPropertyWriter) {
    final String format = (String) AppContext.get("format");

    if(StringUtils.isNotBlank(format)) {
      return deserializeForAnnotation(format, beanPropertyWriter);
    } else {
      @SuppressWarnings("unchecked")
      final Set<String> fieldNames = (Set<String>) AppContext.get("fieldNames");
      if(null != fieldNames && !fieldNames.isEmpty()) {
        final String serializedPropertyName = beanPropertyWriter.getSerializedName().getValue();
        return fieldNames.contains(serializedPropertyName);
      }
    }

    return false;
  }

  private boolean deserializeForAnnotation(final String format, final BeanPropertyWriter beanPropertyWriter) {

    if(StringUtils.equalsIgnoreCase(format, "detail")) {
      return (null != beanPropertyWriter.getAnnotation(Detail.class));
    } else if(StringUtils.equalsIgnoreCase(format, "summary")) {
      return (null != beanPropertyWriter.getAnnotation(Summary.class));
    }

    return false;
  }
}
</code>```

I am getting intended result with annotations, however my 3rd requirement to support property names to filter is not working.

Could someone help; if possible with some examples?

答:
I wrote a library called Squiggly Filter, which selects fields based on a subset of the Facebook Graph API syntax.  For example, to select the zipCode of the address field of the user object, you would use the query string ?fields=address{zipCode}.  One of the advantages of Squiggly Filter is that as long as you have access to the ObjectMapper that renders the json, you do not to have to modify the code of any of your controller methods.

Assuming, you are using the servlet API, you can do the following:

1) Register a filter

```<code><filter>
    <filter-name>squigglyFilter</filter-name>
    <filter-class>com.github.bohnman.squiggly.web.SquigglyRequestFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>squigglyFilter</filter-name>
    <url-pattern>/**</url-pattern>
</filter-mapping>
</code>```

2) Initialize the ObjectMapper

```<code>Squiggly.init(objectMapper, new RequestSquigglyContextProvider());
</code>```

3) You can now filter your json

```<code>curl https://yourhost/path/to/endpoint?fields=field1,field2{nested1,nested2}
</code>```

You can also select fields based on annotations as well.

More information on Squiggly Filter is available on github.

Title: Dynamic property filter using Jackson 2

Body:
I am building a REST service platform in which we have to support following query pattern:

format=summary which means we have to deserialize only the POJO attributes annotated with our custom annotation @Summary

format=detail which means we have to deserialize only the POJO attributes annotated with our custom annotation @Detail

fields=prop1,prop2,prop3 which means we have to deserialize the POJO attributes provided in the query.

I am using Jackson 2 (v2.3.0) I tried followings:

Developed custom annotations (@Summary and @Detail)

Developed a JsonFilter (code shown below) and annotated @JsonFilter to my POJO classes.

Location.java

@JsonFilter("customFilter")
public class Location implements Serializable {
@Summary
@Detail
private String id;

@Summary
@Detail
private String name;

@Summary
@Detail
private Address address;

// ... getters n setters

Address.java

@JsonFilter("customFilter")
public class Address implements Serializable {

  @Detail
  private String addressLine1;

  @Detail
  private String addressLine2;

  @Detail
  private String addressLine3;

  @Detail
  @Summary
  private String city;

  @Summary
  @Detail
  private String postalCode;

  // ... getters n setters

CustomFilter.java

public class CustomFilter extends SimpleBeanPropertyFilter {
  @Override
  protected boolean include(BeanPropertyWriter propertyWriter) {
    if(logger.isDebugEnabled()) {
      logger.debug("include(BeanPropertyWriter) method called..");
    }

    return this.deserialize(propertyWriter);
  }

  @Override
  protected boolean include(PropertyWriter propertyWriter) {
    if(logger.isDebugEnabled()) {
      logger.debug("include(PropertyWriter) method called..");
    }

    return this.deserialize((BeanPropertyWriter) propertyWriter);
  }

  private boolean deserialize(final BeanPropertyWriter beanPropertyWriter) {
    final String format = (String) AppContext.get("format");

    if(StringUtils.isNotBlank(format)) {
      return deserializeForAnnotation(format, beanPropertyWriter);
    } else {
      @SuppressWarnings("unchecked")
      final Set<String> fieldNames = (Set<String>) AppContext.get("fieldNames");
      if(null != fieldNames && !fieldNames.isEmpty()) {
        final String serializedPropertyName = beanPropertyWriter.getSerializedName().getValue();
        return fieldNames.contains(serializedPropertyName);
      }
    }

    return false;
  }

  private boolean deserializeForAnnotation(final String format, final BeanPropertyWriter beanPropertyWriter) {

    if(StringUtils.equalsIgnoreCase(format, "detail")) {
      return (null != beanPropertyWriter.getAnnotation(Detail.class));
    } else if(StringUtils.equalsIgnoreCase(format, "summary")) {
      return (null != beanPropertyWriter.getAnnotation(Summary.class));
    }

    return false;
  }
}

I am getting intended result with annotations, however my 3rd requirement to support property names to filter is not working.

Could someone help; if possible with some examples?

Body:
I wrote a library called Squiggly Filter, which selects fields based on a subset of the Facebook Graph API syntax.  For example, to select the zipCode of the address field of the user object, you would use the query string ?fields=address{zipCode}.  One of the advantages of Squiggly Filter is that as long as you have access to the ObjectMapper that renders the json, you do not to have to modify the code of any of your controller methods.

Assuming, you are using the servlet API, you can do the following:

1) Register a filter

<filter>
    <filter-name>squigglyFilter</filter-name>
    <filter-class>com.github.bohnman.squiggly.web.SquigglyRequestFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>squigglyFilter</filter-name>
    <url-pattern>/**</url-pattern>
</filter-mapping>

2) Initialize the ObjectMapper

Squiggly.init(objectMapper, new RequestSquigglyContextProvider());

3) You can now filter your json

curl https://yourhost/path/to/endpoint?fields=field1,field2{nested1,nested2}

You can also select fields based on annotations as well.

More information on Squiggly Filter is available on github.


问:
How to use the .setVisible() method?
My program is supposed to make an image visible when pressing a button (rbutton1), and I'm supposed to use setVisible(true), but I'm having trouble making the event handler for the rbutton1 work.

The method public static ArrayList<Piece> read( String fileName ) reads the binary file.

package project4;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Project4 extends Application {

    Body b;
    Head head1, head2;
    Hat hat1, hat2;
    Weapon w1, w2, w3;
    Companion c1, c2, c3;

    @Override
    public void start(Stage primaryStage) {
        //fetch objects
        ArrayList<Piece> pieces = read("pieces.dat");

        //parent pane, one row only,
        //contains Pane int he left column for images, and a grid pane in the right for controls
        GridPane root = new GridPane();

        //pane for images
        Pane granny = new Pane();
        root.add(granny, 0, 0);

        //load images
        for (Piece p : pieces) {
            //only the body starts visible
            if (p instanceof Body) {
                granny.getChildren().add(((Body) p).image);
                b = (Body) p;
            } //everything else is added in the right place but is made invisible
            else if (p instanceof Head) {
                granny.getChildren().add(((Head) p).image);
                if (head1 == null) {
                    head1 = (Head) p;
                } else {
                    head2 = (Head) p;
                }
            } else if (p instanceof Hat) {
                granny.getChildren().add(((Hat) p).image);
                if (hat1 == null) {
                    hat1 = (Hat) p;
                } else {
                    hat2 = (Hat) p;
                }
            } else if (p instanceof Weapon) {
                granny.getChildren().add(((Weapon) p).image);
                if (w1 == null) {
                    w1 = (Weapon) p;
                } else if (w2 == null) {
                    w2 = (Weapon) p;
                } else {
                    w3 = (Weapon) p;
                }
            } else if (p instanceof Companion) {
                granny.getChildren().add(((Companion) p).image);
                if (c1 == null) {
                    c1 = (Companion) p;
                } else if (c2 == null) {
                    c2 = (Companion) p;
                } else {
                    c3 = (Companion) p;
                }
            }

        }

        //controls pane
        GridPane controls = new GridPane();
        controls.setAlignment(Pos.TOP_CENTER);
        controls.setPadding(new Insets(10, 10, 10, 10));
        controls.setHgap(15);
        controls.setVgap(15);

        Label headLabel = new Label("Choose Head:");
        RadioButton rbutton1 = new RadioButton("Esme with bees");
        CheckBox check1 = new CheckBox("Face the other way");
        RadioButton rbutton2 = new RadioButton("Esme normal");
        CheckBox check2 = new CheckBox("Face the other way");
        Label hatLabel = new Label("Choose Hat:");
        RadioButton rbutton3 = new RadioButton("Disreputable hat");
        RadioButton rbutton4 = new RadioButton("Hat with pins");
        RadioButton rbutton5 = new RadioButton("No hat");
        Label weaponLabel = new Label("Weapon:");
        ComboBox< String> cbox = new ComboBox<>();
        cbox.getItems().addAll(
                "broom",
                "scythe",
                "stick"
        );
        Label companionLabel = new Label("Companion:");
        ListView<String> clv = new ListView<>();
        clv.getItems().addAll("DEATH of Rats", "Gaspode", "Luggage");
        clv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        clv.setPrefSize(2, 90);

        Button exportButton = new Button("Export Character");
        Label exportFileName = new Label("export.oscar.dat");

        ToggleGroup group = new ToggleGroup();
        rbutton1.setToggleGroup(group);
        rbutton2.setToggleGroup(group);

        ToggleGroup group2 = new ToggleGroup();
        rbutton3.setToggleGroup(group2);
        rbutton4.setToggleGroup(group2);
        rbutton5.setToggleGroup(group2);

        controls.add(headLabel, 1, 5);
        controls.add(rbutton1, 2, 6);
        controls.add(check1, 3, 6);
        controls.add(rbutton2, 2, 7);
        controls.add(check2, 3, 7);
        controls.add(hatLabel, 1, 8);
        controls.add(rbutton3, 2, 9);
        controls.add(rbutton4, 2, 10);
        controls.add(rbutton5, 2, 11);
        controls.add(weaponLabel, 1, 13);
        controls.add(cbox, 2, 14);
        controls.add(companionLabel, 1, 15);
        controls.add(clv, 2, 16);
        controls.add(exportButton, 2, 17);
        controls.add(exportFileName, 3, 17);

        rbutton1.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {

            }

        });

        root.add(controls, 1, 0);

        Scene scene = new Scene(root, 900, 700);

        primaryStage.setScene(scene);

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    /* read the file - Binary I/O
     * input - String fileName
     * returns ArrayList<Piece> of objects
     */
    public static ArrayList<Piece> read( String fileName ) {
        ArrayList<Piece> pieces = new ArrayList<>();
        //try with resources
        try ( ObjectInputStream in = new ObjectInputStream( new FileInputStream( fileName ) ) ) {;
            //flag should keep reading
            boolean go = true;
            //if the flag still gives the go ahead
            while( go ) {
                //try to read
                try{
                    //read, set the image dimensions and position, add to arraylist
                    Piece p = (Piece)in.readObject();
                    p.setImage();
                    pieces.add( p );
                //if there is no more left to read, an IO exception will be thrown
                } catch( IOException ex ) {
                    //set the flag to signal end of file
                    go = false;
                }
            }
        //neede dexception catches for this type of stream
        } catch( IOException ioex ) {
            System.out.println( "Input file is missing. " + ioex.getMessage() );
            System.exit( -1 );
        } catch ( ClassNotFoundException cnfex ) {
            System.out.println( "Incompatible class. " );
            System.exit( -1 );
        }

        //return the list with objects from the file
        return pieces;
    }
```

答:
You don't want to set handler on button, instead set it on group:  </p>

```<code>group1.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){
   @Override
   public void changed(ObservableValue<? extends Toggle> ov, Toggle t, Toggle t1)
       {
       // Do what you want inside

   });
</code>```

Title: How to use the .setVisible() method?

Body:
You don't want to set handler on button, instead set it on group:

group1.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){
   @Override
   public void changed(ObservableValue<? extends Toggle> ov, Toggle t, Toggle t1)
       {
       // Do what you want inside

   });


问:
Windows build and action “Goto was unexpected at this time”
Hoping for some assistance explaining and verifing this script I am getting an error "goto was unexpected at this time" </p>

<p>I attempting to created a script that gets the windows version number...  depending on the version number if its higher or equals then x it has to goto action 1 (FTRDWIN8) and when the version number is less then x it has to goto action 2 </p>

```<code>@echo off

::parsing the output of "ver" to getting windows version number
::excuting.

set strbuild=6.2

for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" geq "%strbuild%" goto FTRDWIN8
if "%version%" lss "%strbuild%" goto FTRDWINXPVI7

:FTRDWIN8
"C:\Windows\write.exe"
exit

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
exit
</code>```

答:
I copied your code and executed, and I cannot reproduce your error, though it gives the wrong result. I have windows 10 (version 10.0.14393), and your IF statement does a string comparison, so "10.0" is less than "6.2"

I cannot see how your code could ever give an error message of "goto was unexpected at this time". If you modify your code to enable delayed expansion and use !var! instead of %var%, then your code could not possibly give that error.

You should remove the ECHO OFF so you can see where the error message is coming from. I suspect it is in some other unrelated code, but can't be sure.

As I stated earlier, (and also pointed out by LotPings) your logic is wrong because your IF statement with quotes and decimal point does a string comparison, not a numeric comparison.

Here is corrected logic that does the comparison in multiple steps - each version node must be tested independently. I don't see any reason to set any environment variable. Also, I like to use EXIT /B instead of EXIT. I suspect that the code may be locale dependent - I'm not sure if the VER command changes its output format depending on the locale.

```<code>@echo off
for /f "tokens=4-5 delims=. " %%A in ('ver') do (
  if %%A gtr 6 goto FTRDWIN8
  if %%A equ 6 if %%B geq 2 goto FTRDWIN8
)

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
exit /b

:FTRDWIN8
"C:\Windows\write.exe"
exit /b
</code>```

Body:
Hoping for some assistance explaining and verifing this script I am getting an error "goto was unexpected at this time"

I attempting to created a script that gets the windows version number...  depending on the version number if its higher or equals then x it has to goto action 1 (FTRDWIN8) and when the version number is less then x it has to goto action 2

@echo off

::parsing the output of "ver" to getting windows version number
::excuting.

set strbuild=6.2

for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" geq "%strbuild%" goto FTRDWIN8
if "%version%" lss "%strbuild%" goto FTRDWINXPVI7

:FTRDWIN8
"C:\Windows\write.exe"
exit

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
exit

Body:
I copied your code and executed, and I cannot reproduce your error, though it gives the wrong result. I have windows 10 (version 10.0.14393), and your IF statement does a string comparison, so "10.0" is less than "6.2"

I cannot see how your code could ever give an error message of "goto was unexpected at this time". If you modify your code to enable delayed expansion and use !var! instead of %var%, then your code could not possibly give that error.

You should remove the ECHO OFF so you can see where the error message is coming from. I suspect it is in some other unrelated code, but can't be sure.

As I stated earlier, (and also pointed out by LotPings) your logic is wrong because your IF statement with quotes and decimal point does a string comparison, not a numeric comparison.

Here is corrected logic that does the comparison in multiple steps - each version node must be tested independently. I don't see any reason to set any environment variable. Also, I like to use EXIT /B instead of EXIT. I suspect that the code may be locale dependent - I'm not sure if the VER command changes its output format depending on the locale.

@echo off
for /f "tokens=4-5 delims=. " %%A in ('ver') do (
  if %%A gtr 6 goto FTRDWIN8
  if %%A equ 6 if %%B geq 2 goto FTRDWIN8
)

:FTRDWINXPVI7
"C:\Windows\notepad.exe"
exit /b

:FTRDWIN8
"C:\Windows\write.exe"
exit /b


问:
Regex, That Matches No more Than n Occurrences
I'm trying to find a Regex, that matches no more than n consecutive, say three, for example, occurrences of a character; in the case of three and character is "a":

abbaa - matches;

ammaaa - doesn't match(three consecutive a's), there is one "a", but whole expression must be discarded because three "a's"

Thank you.

答:
Use the {m,n} syntax (if your environment provides it, which it likely does.

{m,n} allows m to n (inclusive) occurrences of the previous character.

Examples:

/a{0,3}/ matches 0 to 3 occurrences of a.

/a{3,}/ matches 3 or more occurrences.

/a{3}/ matches exactly 3 occurrences.

In the following example I've paired the above syntax with negative lookahead and negative lookbehind.

(?<!a)a{0,3}(?!a) matches 0 to 3 occurrences of a where there is no a before or after those 0-3 occurrences.


问:
Swift open new UIViewController
I'm trying to open new UIViewController when I click on an item inside UICollectionView, but using this code my app crashes and Xcode and simulator restarts so I can't even see where is the problem.

```<code>import UIKit

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: "cellId")
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CustomCell

        cell.imageViewGame.image = UIImage(named: imageArray[indexPath.row])

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width / 2, height: view.frame.width / 2)
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        performSegue(withIdentifier: "postController", sender: title[indexPath.row])
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "postController" {
            let postController = segue.destination as! PostController

            postController.title = sender as! String

        }
    }
}
</code>```

Does anyone know from this code why my app crashes? If it's important, I'm not using storyboard.

答:
Try this:

Make you don't forgot to declare postController identifier in your segue

You just can present it modally with:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

```<code>        let postController = PostController()
        postController.title = title[indexPath.row]
        present(postController, animated: true, completion: nil)
    }
</code>```

Title: Swift open new UIViewController

Body:
I'm trying to open new UIViewController when I click on an item inside UICollectionView, but using this code my app crashes and Xcode and simulator restarts so I can't even see where is the problem.

import UIKit

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: "cellId")
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CustomCell

        cell.imageViewGame.image = UIImage(named: imageArray[indexPath.row])

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width / 2, height: view.frame.width / 2)
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        performSegue(withIdentifier: "postController", sender: title[indexPath.row])
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "postController" {
            let postController = segue.destination as! PostController

            postController.title = sender as! String

        }
    }
}

Does anyone know from this code why my app crashes? If it's important, I'm not using storyboard.

Body:
Try this:

Make you don't forgot to declare postController identifier in your segue

You just can present it modally with:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let postController = PostController()
        postController.title = title[indexPath.row]
        present(postController, animated: true, completion: nil)
    }


问:
Add a spinning wheel while application is searching database
I have an application that searches in a database for some information.

Since the database is quite big, it sometimes takes a lot of time before the application returns the results to the interface.

I want to add some sort of spinning wheel to inform the user that the application is still searching the database and did not freeze. Once the results are returned, the wheel should disappear.

Any idea how to do this or is there a good tutorial explaining how to do this?

答: Find an animated gif of such a spinner, like this one.  Put it in a PictureBox, set its Visible property to True when you start the job.  Beware that you'll have to run the query in a worker thread to keep the animation alive and the user interface responsive.  The BackgroundWorker class is good for that.</p>


问:
inversify: not injectable contrustor arguments
I have a Game class and a Multiplayer class which handle all network players stuff for defined game:

```<code>export interface Multiplayer{
    game: Game
    start()
}
export class WebSocketMultiplayer implements Multiplayer{
    constructor(public game: Game){}
    start(){}
}
</code>```

inversify configuration:

```<code>container.bind<Game>('Game').to(BasicGame)
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer)
</code>```

now I want to create, configure and run game and after that - run multiplayer.

```<code>const game = kernel.get<Game>('Game')
game.run()
const multiplayer = kernel.get<Multiplayer>('Multiplayer')
multiplayer.start()
</code>```

but how should I pass game instance into Multiplayer constructor?
If I will use @inject in WebSocketMultiplayer constructor than it will create another game instance.

Temporary solution I'm using for now is to pass game instance in multiplayer start function

```<code>start(game: Game){
        this.game = game
}
</code>```

but how it suppose to be done with Inversify?

答:
You ca try a few things.

The first options is to use the inSingletonScope method:

```<code>container.bind<Game>('Game').to(BasicGame).inSingletonScope();
</code>```

You can learn more about scope here.

The second option is to use a factory:

```<code>container.bind<Game>('Game').to(BasicGame);
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer);

container.bind<() => Game>("GameFactory").toFactory<Game>((context: interfaces.Context) => {
    const game = context.container.get<Game>("Game");
    game.run();
    return () => game;
});

class WebSocketMultiplayer implements Multiplayer{
    public game: Game;
    constructor(@inject("GameFactory") gameFactory: () => Game){
        this.game = gameFactory();
    }
    start(){}
}
</code>```

If game.run() is asynchronous then you will need an asynchronous factory (AKA provider).

Body:
I have a Game class and a Multiplayer class which handle all network players stuff for defined game:

export interface Multiplayer{
    game: Game
    start()
}
export class WebSocketMultiplayer implements Multiplayer{
    constructor(public game: Game){}
    start(){}
}

inversify configuration:

container.bind<Game>('Game').to(BasicGame)
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer)

now I want to create, configure and run game and after that - run multiplayer.

const game = kernel.get<Game>('Game')
game.run()
const multiplayer = kernel.get<Multiplayer>('Multiplayer')
multiplayer.start()

but how should I pass game instance into Multiplayer constructor?
If I will use @inject in WebSocketMultiplayer constructor than it will create another game instance.

Temporary solution I'm using for now is to pass game instance in multiplayer start function

start(game: Game){
        this.game = game
}

but how it suppose to be done with Inversify?

Body:
You ca try a few things.

The first options is to use the inSingletonScope method:

container.bind<Game>('Game').to(BasicGame).inSingletonScope();

You can learn more about scope here.

The second option is to use a factory:

container.bind<Game>('Game').to(BasicGame);
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer);

container.bind<() => Game>("GameFactory").toFactory<Game>((context: interfaces.Context) => {
    const game = context.container.get<Game>("Game");
    game.run();
    return () => game;
});

class WebSocketMultiplayer implements Multiplayer{
    public game: Game;
    constructor(@inject("GameFactory") gameFactory: () => Game){
        this.game = gameFactory();
    }
    start(){}
}

If game.run() is asynchronous then you will need an asynchronous factory (AKA provider).


答:
you should remove all # . And i think you should use ui-router instead ng-router .  it better for you

https://github.com/angular-ui/ui-router

Title: AngularJS routing always to main


问:
Sublime Text - Change Color of called function
I want to change the color of a function I call from an object from white to something else.

I have changed almost all of the colors, but I can't find the name of this one.
Currently I have the newest version of Sublime

答:
I assume is php. You need to edit desired theme and add this code OR to edit "meta.function-call.object.php" key.

function get_template_with_data($type, $data)

```<code><dict>
      <key>name</key>
      <string>Function Call</string>
      <key>scope</key>
      <string>meta.function-call</string>
      <key>settings</key>
      <dict>
            <key>foreground</key>
            <string>#0000FF</string>
      </dict>
</dict>
</code>```

for this kind of function call:

$this->email->message($message);

```<code><dict>
            <key>name</key>
            <string>Function name</string>
            <key>scope</key>
            <string>variable.function</string>
            <key>settings</key>
            <dict>
                <key>fontStyle</key>
                <string></string>
                <key>foreground</key>
                <string>#0000FF</string>
            </dict>
        </dict>
</code>```

Body:
I assume is php. You need to edit desired theme and add this code OR to edit "meta.function-call.object.php" key.

function get_template_with_data($type, $data)

<dict>
      <key>name</key>
      <string>Function Call</string>
      <key>scope</key>
      <string>meta.function-call</string>
      <key>settings</key>
      <dict>
            <key>foreground</key>
            <string>#0000FF</string>
      </dict>
</dict>

for this kind of function call:

$this->email->message($message);

<dict>
            <key>name</key>
            <string>Function name</string>
            <key>scope</key>
            <string>variable.function</string>
            <key>settings</key>
            <dict>
                <key>fontStyle</key>
                <string></string>
                <key>foreground</key>
                <string>#0000FF</string>
            </dict>
        </dict>


问:
Deleting all keys in a shelve file through terminal/command line
I'm trying to delete all items in a shelve file by allowing the user to type "clear" in terminal.

Based on several threads I've read on this website, shelve files generally behave like dictionaries, so the .clear method and several other approaches should work, and in fact do when I test them out in the interactive shell. But I can't get them to work in my program.

Here's my latest attempt (which worked in the shell):

```<code>elif len(sys.argv) == 3 and sys.argv[1].lower() == 'clear':
    for key in mcbShelf:
        del mcbShelf[key]
</code>```

Just using del on mcbShelf also did not work.

My program also has a "list" feature that lists all of the keys stored in the shell.

```<code>elif len(sys.argv) == 2:
    #list keywords
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
</code>```

When I try python3.5 mcb4.pyw clear in Terminal, then run python3.5 mcb4.pyw list, I believe an empty list should be copied to the clipboard. But the list has objects in it.

Any thoughts?

答:
I found 2 ways to deal with this. One is to create a function to delete the files the other is to pull a condition flag based on a argument and name it the same file. This is verified working code. </p>

```<code>import shelve
import pyperclip
import sys
import os

mcbShelf = shelve.open('mcb')
command = sys.argv[1].lower()

def remove_files():
    mcbShelf.close()
    os.remove('mcb.dat')
    os.remove('mcb.bak')
    os.remove('mcb.dir')

if command == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
elif command == 'list':
    pyperclip.copy(", ".join(mcbShelf.keys()))
elif command == 'del':
    mcbShelf.close()
    # call the flag 'n' Always create a new, empty database
    mcbShelf = shelve.open('mcb', flag= 'n')
    # or delete the files
    remove_files()
else:
    pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()
</code>```

Body:
I'm trying to delete all items in a shelve file by allowing the user to type "clear" in terminal.

Based on several threads I've read on this website, shelve files generally behave like dictionaries, so the .clear method and several other approaches should work, and in fact do when I test them out in the interactive shell. But I can't get them to work in my program.

Here's my latest attempt (which worked in the shell):

elif len(sys.argv) == 3 and sys.argv[1].lower() == 'clear':
    for key in mcbShelf:
        del mcbShelf[key]

Just using del on mcbShelf also did not work.

My program also has a "list" feature that lists all of the keys stored in the shell.

elif len(sys.argv) == 2:
    #list keywords
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))

When I try python3.5 mcb4.pyw clear in Terminal, then run python3.5 mcb4.pyw list, I believe an empty list should be copied to the clipboard. But the list has objects in it.

Any thoughts?

Body:
I found 2 ways to deal with this. One is to create a function to delete the files the other is to pull a condition flag based on a argument and name it the same file. This is verified working code.

import shelve
import pyperclip
import sys
import os

mcbShelf = shelve.open('mcb')
command = sys.argv[1].lower()

def remove_files():
    mcbShelf.close()
    os.remove('mcb.dat')
    os.remove('mcb.bak')
    os.remove('mcb.dir')

if command == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
elif command == 'list':
    pyperclip.copy(", ".join(mcbShelf.keys()))
elif command == 'del':
    mcbShelf.close()
    # call the flag 'n' Always create a new, empty database
    mcbShelf = shelve.open('mcb', flag= 'n')
    # or delete the files
    remove_files()
else:
    pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()