问:
Lisp changes function to lambda expression when stored in function cell
In this post, I ask tangentially why when I declare in SBCL

```<code>(defun a (&rest x)
    x)
</code>```

and then check what the function cell holds

```<code>(describe 'a)
COMMON-LISP-USER::A
  [symbol]

A names a compiled function:
  Lambda-list: (&REST X)
  Derived type: (FUNCTION * (VALUES LIST &OPTIONAL))
  Source form:
    (LAMBDA (&REST X) (BLOCK A X))
</code>```

I see this particular breakdown of the original function. Could someone explain what this output means? I'm especially confused by the last line

```<code> Source form:
        (LAMBDA (&REST X) (BLOCK A X))
</code>```

This is mysterious because for some reason not clear to me Lisp has transformed the original function into a lambda expression. It would also be nice to know the details of how a function broken down like this is then called. This example is SBCL. In Elisp

```<code>(symbol-function 'a)
</code>```

gives

```<code>(lambda (&rest x) x)
</code>```

again, bizarre. As I said in the other post, this is easier to understand in Scheme -- but that created confusion in the answers. So once more I ask, Why has Lisp taken a normal function declaration and seemingly stored it as a lambda expression?

答:
I'm still a bit unclear what you are confused about, but here is an attempt to explain it.  I will stick to CL (and mostly to ANSI CL), because elisp has a lot of historical oddities which just make things hard to understand (there is an appendix on elisp).  Pre-ANSI CL was also a lot less clear on various things.

I'll try to explain things by writing a macro which is a simple version of defun: I'll call this defun/simple, and an example of its use will be

```<code>(defun/simple foo (x)
  (+ x x))
</code>```

So what I need to do is to work out what the expansion of this macro should be, so that it does something broadly equivalent (but simpler than) defun.

The function namespace & fdefinition

First of all I assume you are comfortable with the idea that, in CL (and elisp) the namespace of functions is different than the namespace of variable bindings: both languages are lisp-2s.  So in a form like (f x), f is looked up in the namespace of function bindings, while x is looked up in the namespace of variable bindings.  This means that forms like

```<code>(let ((sin 0.0))
  (sin sin))
</code>```

are fine in CL or elisp, while in Scheme they would be an error, as 0.0 is not a function, because Scheme is a lisp-1.

So we need some way of accessing that namespace, and in CL the most general way of doing that is fdefinition: (fdefinition <function name>) gets the function definition of <function name>, where <function name> is something which names a function, which for our purposes will be a symbol.

fdefinition is what CL calls an accessor: this means that the setf macro knows what to do with it, so that we can mutate the function binding of a symbol by (setf (fdefinition ...) ...).  (This is not true: what we can access and mutate with fdefinition is the top-level function binding of a symbol, we can't access or mutate lexical function bindings, and CL provides no way to do this, but this does not matter here.)

So this tells us what our macro expansion needs to look like: we want to set the (top-level) definition of the name to some function object.  The expansion of the macro should be like this:

```<code>(defun/simple foo (x)
  x)
</code>```

should expand to something involving

```<code>(setf (fdefinition 'foo) <form which makes a function>)
</code>```

So we can write this bit of the macro now:

```<code>(defmacro defun/simple (name arglist &body forms)
  `(progn
     (setf (fdefinition ',name)
           ,(make-function-form name arglist forms))
     ',name))
</code>```

This is the complete definition of this macro.  It uses progn in its expansion so that the result of expanding it is the name of the function being defined, which is the same as defun: the expansion does all its real work by side-effect.

But defun/simple relies on a helper function, called make-function-form, which I haven't defined yet, so you can't actually use it yet.

Function forms

So now we need to write make-function-form.  This function is called at macroexpansion time: it's job is not to make a function: it's to return a bit of source code which will make a function, which I'm calling a 'function form'.

So, what do function forms look like in CL?  Well, there's really only one such form in portable CL (this might be wrong, but I think it is true), which is a form constructed using the special operator function.  So we're going to need to return some form which looks like (function ...).  Well, what can ... be?  There are two cases for function.

(function <name>) denotes the function named by <name> in the current lexical environment.  So (function car) is the function we call when we say (car x).

(function (lambda ...)) denotes a function specified by (lambda ...): a lambda expression.

The second of these is the only (caveats as above) way we can  construct a form which denotes a new function.  So make-function-form is going to need to return this second variety of function form.

So we can write an initial version of make-function-form:

```<code>(defun make-function-form (name arglist forms)
  (declare (ignore name))
  `(function (lambda ,arglist ,@forms)))
</code>```

And this is enough for defun/simple to work:

```<code>> (defun/simple plus/2 (a b)
    (+ a b))
plus/2

> (plus/2 1 2)
3
</code>```

But it's not quite right yet: one of the things that functions defined by defun can do is return from themselves: they know their own name and can use return-from to return from it:

```<code>> (defun silly (x)
    (return-from silly 3)
    (explode-the-world x))
silly

> (silly 'yes)
3
</code>```

defun/simple can't do this, yet.  To do this, make-function-form needs to insert a suitable block around the body of the function:

```<code>(defun make-function-form (name arglist forms)
  `(function (lambda ,arglist
               (block ,name
                 ,@forms))))
</code>```

And now:

```<code>> (defun/simple silly (x)
    (return-from silly 3)
    (explode-the-world x))
silly

> (silly 'yes)
3
</code>```

And all is well.

This is the final definition of defun/simple and its auxiliary function.

Looking at the expansion of defun/simple

We can do this with macroexpand in the usual way:

```<code>(let ((sin 0.0))
  (sin sin))
</code>```0

The only thing that's confusing here is that, because (function ...) is common in source code, there's syntactic sugar for it which is #'...: this is the same reason that quote has special syntax.

It's worth looking at the macroexpansion of real defun forms: they usually have a bunch of implementation-specific stuff in them, but you can find the same thing there.  Here's an example from LW:

```<code>(let ((sin 0.0))
  (sin sin))
</code>```1

Well, there's a lot of extra stuff in here, and LW obviously has some trick around this (declare (lambda-name ...)) form which lets return-from work without an explicit block.  But you can see that basically the same thing is going on.

Conclusion: how you make functions

In conclusion: a macro like defun, or any other function-defining form, needs to expand to a form which, when evaluated, will construct a function.  CL offers exactly one such form: (function (lambda ...)): that's how you make functions in CL.  So something like defun necessarily has to expand to something like this. (To be precise: any portable version of defun: implementations are somewhat free to do implementation-magic & may do so.  However they are not free to add a new special operator.)

What you are seeing when you call describe is that, after SBCL has compiled your function, it's remembered what the source form was, and the source form was exactly the one you would have got from the defun/simple macro given here.

Notes

lambda as a macro

In ANSI CL, lambda is defined as a macro whose expansion is a suitable (function (lambda ...)) form:

```<code>(let ((sin 0.0))
  (sin sin))
</code>```2

This means that you don't have to write (function (lambda ...)) yourself: you can rely on the macro definition of lambda doing it for you.  Historically, lambda wasn't always a macro in CL: I can't find my copy of CLtL1, but I'm pretty certain it was not defined as one there.  I'm reasonably sure that the macro definition of lambda arrived so that it was possible to write ISLisp-compatible programs on top of CL.  It has to be in the language because lambda is in the CL package and so users can't portably define macros for it (although quite often they did define such a macro, or at least I did).  I have not relied on this macro definition above.

defun/simple does not purport to be a proper clone of defun: its only purpose is to show how such a macro can be written.  In particular it doesn't deal with declarations properly, I think: they need to be lifted out of the block & are not.

Elisp

Elisp is much more horrible than CL.  In particular, in CL there is a well-defined function type, which is disjoint from lists:

```<code>> (typep '(lambda ()) 'function)
nil

> (typep '(lambda ()) 'list)
t

> (typep (function (lambda ())) 'function)
t

> (typep (function (lambda ())) 'list)
nil
</code>```

(Note in particular that (function (lambda ())) is a function, not a list: function is doing its job of making a function.)

In elisp, however, an interpreted function is just a list whose car is lambda (caveat: if lexical binding is on this is not the case: it's then a list whose car is closure).  So in elisp (without lexical binding):

```<code>ELISP> (function (lambda (x) x))
(lambda (x)
  x)
</code>```

And

```<code>ELISP> (defun foo (x) x)
foo
ELISP> (symbol-function 'foo)
(lambda (x)
  x)
</code>```

The elisp intepreter then just interprets this list, in just the way you could yourself.  function in elisp is almost the same thing as quote.

But function isn't quite the same as quote in elisp: the byte-compiler knows that, when it comes across a form like (function (lambda ...)) that this is a function form, and it should byte-compile the body.  So, we can look at the expansion of defun in elisp:

```<code>ELISP> (macroexpand '(defun foo (x) x))
(defalias 'foo
  #'(lambda (x)
      x))
</code>```

(It turns out that defalias is the primitive thing now.)

But if I put this definition in a file, which I byte compile and load, then:

```<code>ELISP> (symbol-function 'foo)
#[(x)
  "\207"
  [x]
  1]
</code>```

And you can explore this a bit further: if you put this in a file:

```<code>(fset 'foo '(lambda (x) x))
</code>```

and then byte compile and load that, then

```<code>ELISP> (symbol-function 'foo)
(lambda (x)
  x)
</code>```

So the byte compiler didn't do anything with foo because it didn't get the hint that it should.  But foo is still a fine function:

```<code>(defun/simple foo (x)
  x)
</code>```0

It just isn't compiled.  This is also why, if writing elisp code with anonymous functions in it, you should use function (or equivalently #').  (And finally, of course, (function ...) does the right thing if lexical scoping is on.)

Other ways of making functions in CL

Finally, I've said above that function & specifically (function (lambda ...)) is the only primitive way to make new functions in CL.  I'm not completely sure that's true, especially given CLOS (almost any CLOS will have some kind of class instances of which are functions but which can be subclassed).  But it does not matter: it is a way and that's sufficient.

Body:
In this post, I ask tangentially why when I declare in SBCL

(defun a (&rest x)
    x)

and then check what the function cell holds

(describe 'a)
COMMON-LISP-USER::A
  [symbol]

A names a compiled function:
  Lambda-list: (&REST X)
  Derived type: (FUNCTION * (VALUES LIST &OPTIONAL))
  Source form:
    (LAMBDA (&REST X) (BLOCK A X))

I see this particular breakdown of the original function. Could someone explain what this output means? I'm especially confused by the last line

 Source form:
        (LAMBDA (&REST X) (BLOCK A X))

This is mysterious because for some reason not clear to me Lisp has transformed the original function into a lambda expression. It would also be nice to know the details of how a function broken down like this is then called. This example is SBCL. In Elisp

(symbol-function 'a)

gives

(lambda (&rest x) x)

again, bizarre. As I said in the other post, this is easier to understand in Scheme -- but that created confusion in the answers. So once more I ask, Why has Lisp taken a normal function declaration and seemingly stored it as a lambda expression?

Body:
I'm still a bit unclear what you are confused about, but here is an attempt to explain it.  I will stick to CL (and mostly to ANSI CL), because elisp has a lot of historical oddities which just make things hard to understand (there is an appendix on elisp).  Pre-ANSI CL was also a lot less clear on various things.

I'll try to explain things by writing a macro which is a simple version of defun: I'll call this defun/simple, and an example of its use will be

(defun/simple foo (x)
  (+ x x))

So what I need to do is to work out what the expansion of this macro should be, so that it does something broadly equivalent (but simpler than) defun.

The function namespace & fdefinition

First of all I assume you are comfortable with the idea that, in CL (and elisp) the namespace of functions is different than the namespace of variable bindings: both languages are lisp-2s.  So in a form like (f x), f is looked up in the namespace of function bindings, while x is looked up in the namespace of variable bindings.  This means that forms like

(let ((sin 0.0))
  (sin sin))

are fine in CL or elisp, while in Scheme they would be an error, as 0.0 is not a function, because Scheme is a lisp-1.

So we need some way of accessing that namespace, and in CL the most general way of doing that is fdefinition: (fdefinition <function name>) gets the function definition of <function name>, where <function name> is something which names a function, which for our purposes will be a symbol.

fdefinition is what CL calls an accessor: this means that the setf macro knows what to do with it, so that we can mutate the function binding of a symbol by (setf (fdefinition ...) ...).  (This is not true: what we can access and mutate with fdefinition is the top-level function binding of a symbol, we can't access or mutate lexical function bindings, and CL provides no way to do this, but this does not matter here.)

So this tells us what our macro expansion needs to look like: we want to set the (top-level) definition of the name to some function object.  The expansion of the macro should be like this:

(defun/simple foo (x)
  x)

should expand to something involving

(setf (fdefinition 'foo) <form which makes a function>)

So we can write this bit of the macro now:

(defmacro defun/simple (name arglist &body forms)
  `(progn
     (setf (fdefinition ',name)
           ,(make-function-form name arglist forms))
     ',name))

This is the complete definition of this macro.  It uses progn in its expansion so that the result of expanding it is the name of the function being defined, which is the same as defun: the expansion does all its real work by side-effect.

But defun/simple relies on a helper function, called make-function-form, which I haven't defined yet, so you can't actually use it yet.

Function forms

So now we need to write make-function-form.  This function is called at macroexpansion time: it's job is not to make a function: it's to return a bit of source code which will make a function, which I'm calling a 'function form'.

So, what do function forms look like in CL?  Well, there's really only one such form in portable CL (this might be wrong, but I think it is true), which is a form constructed using the special operator function.  So we're going to need to return some form which looks like (function ...).  Well, what can ... be?  There are two cases for function.

(function <name>) denotes the function named by <name> in the current lexical environment.  So (function car) is the function we call when we say (car x).

(function (lambda ...)) denotes a function specified by (lambda ...): a lambda expression.

The second of these is the only (caveats as above) way we can  construct a form which denotes a new function.  So make-function-form is going to need to return this second variety of function form.

So we can write an initial version of make-function-form:

(defun make-function-form (name arglist forms)
  (declare (ignore name))
  `(function (lambda ,arglist ,@forms)))

And this is enough for defun/simple to work:

> (defun/simple plus/2 (a b)
    (+ a b))
plus/2

> (plus/2 1 2)
3

But it's not quite right yet: one of the things that functions defined by defun can do is return from themselves: they know their own name and can use return-from to return from it:

> (defun silly (x)
    (return-from silly 3)
    (explode-the-world x))
silly

> (silly 'yes)
3

defun/simple can't do this, yet.  To do this, make-function-form needs to insert a suitable block around the body of the function:

(defun make-function-form (name arglist forms)
  `(function (lambda ,arglist
               (block ,name
                 ,@forms))))

And now:

> (defun/simple silly (x)
    (return-from silly 3)
    (explode-the-world x))
silly

> (silly 'yes)
3

And all is well.

This is the final definition of defun/simple and its auxiliary function.

Looking at the expansion of defun/simple

We can do this with macroexpand in the usual way:

> (macroexpand '(defun/simple foo (x) x))
(progn
  (setf (fdefinition 'foo)
        #'(lambda (x)
            (block foo
              x)))
  'foo)
t

The only thing that's confusing here is that, because (function ...) is common in source code, there's syntactic sugar for it which is #'...: this is the same reason that quote has special syntax.

It's worth looking at the macroexpansion of real defun forms: they usually have a bunch of implementation-specific stuff in them, but you can find the same thing there.  Here's an example from LW:

 > (macroexpand '(defun foo (x) x))
(compiler-let ((dspec::*location* '(:inside (defun foo) :listener)))
  (compiler::top-level-form-name (defun foo)
    (dspec:install-defun 'foo
                         (dspec:location)
                         #'(lambda (x)
                             (declare (system::source-level
                                       #<eq Hash Table{0} 42101FCD5B>))
                             (declare (lambda-name foo))
                             x))))
t

Well, there's a lot of extra stuff in here, and LW obviously has some trick around this (declare (lambda-name ...)) form which lets return-from work without an explicit block.  But you can see that basically the same thing is going on.

Conclusion: how you make functions

In conclusion: a macro like defun, or any other function-defining form, needs to expand to a form which, when evaluated, will construct a function.  CL offers exactly one such form: (function (lambda ...)): that's how you make functions in CL.  So something like defun necessarily has to expand to something like this. (To be precise: any portable version of defun: implementations are somewhat free to do implementation-magic & may do so.  However they are not free to add a new special operator.)

What you are seeing when you call describe is that, after SBCL has compiled your function, it's remembered what the source form was, and the source form was exactly the one you would have got from the defun/simple macro given here.

Notes

lambda as a macro

In ANSI CL, lambda is defined as a macro whose expansion is a suitable (function (lambda ...)) form:

> (macroexpand '(lambda (x) x))
#'(lambda (x) x)
t

> (car (macroexpand '(lambda (x) x)))
function

This means that you don't have to write (function (lambda ...)) yourself: you can rely on the macro definition of lambda doing it for you.  Historically, lambda wasn't always a macro in CL: I can't find my copy of CLtL1, but I'm pretty certain it was not defined as one there.  I'm reasonably sure that the macro definition of lambda arrived so that it was possible to write ISLisp-compatible programs on top of CL.  It has to be in the language because lambda is in the CL package and so users can't portably define macros for it (although quite often they did define such a macro, or at least I did).  I have not relied on this macro definition above.

defun/simple does not purport to be a proper clone of defun: its only purpose is to show how such a macro can be written.  In particular it doesn't deal with declarations properly, I think: they need to be lifted out of the block & are not.

Elisp

Elisp is much more horrible than CL.  In particular, in CL there is a well-defined function type, which is disjoint from lists:

> (typep '(lambda ()) 'function)
nil

> (typep '(lambda ()) 'list)
t

> (typep (function (lambda ())) 'function)
t

> (typep (function (lambda ())) 'list)
nil

(Note in particular that (function (lambda ())) is a function, not a list: function is doing its job of making a function.)

In elisp, however, an interpreted function is just a list whose car is lambda (caveat: if lexical binding is on this is not the case: it's then a list whose car is closure).  So in elisp (without lexical binding):

ELISP> (function (lambda (x) x))
(lambda (x)
  x)

And

ELISP> (defun foo (x) x)
foo
ELISP> (symbol-function 'foo)
(lambda (x)
  x)

The elisp intepreter then just interprets this list, in just the way you could yourself.  function in elisp is almost the same thing as quote.

But function isn't quite the same as quote in elisp: the byte-compiler knows that, when it comes across a form like (function (lambda ...)) that this is a function form, and it should byte-compile the body.  So, we can look at the expansion of defun in elisp:

ELISP> (macroexpand '(defun foo (x) x))
(defalias 'foo
  #'(lambda (x)
      x))

(It turns out that defalias is the primitive thing now.)

But if I put this definition in a file, which I byte compile and load, then:

ELISP> (symbol-function 'foo)
#[(x)
  "\207"
  [x]
  1]

And you can explore this a bit further: if you put this in a file:

(fset 'foo '(lambda (x) x))

and then byte compile and load that, then

ELISP> (symbol-function 'foo)
(lambda (x)
  x)

So the byte compiler didn't do anything with foo because it didn't get the hint that it should.  But foo is still a fine function:

ELISP> (foo 1)
1 (#o1, #x1, ?\C-a)

It just isn't compiled.  This is also why, if writing elisp code with anonymous functions in it, you should use function (or equivalently #').  (And finally, of course, (function ...) does the right thing if lexical scoping is on.)

Other ways of making functions in CL

Finally, I've said above that function & specifically (function (lambda ...)) is the only primitive way to make new functions in CL.  I'm not completely sure that's true, especially given CLOS (almost any CLOS will have some kind of class instances of which are functions but which can be subclassed).  But it does not matter: it is a way and that's sufficient.


来源: stackexchange

问:
Get all combinations for arbitrary number of elements
How can I make a method in Java which obtains input integer n, and an array of double x, and returns all combinations of n elements out of values in x.

Where x={1,2,3} and n=2,

the expected returns/combinations are
{1,1},{1,2},{1,3},{2,2},{2,1},{2,3},{3,1},{3,2},{3,3}
(the order is not ignored.) The number should be (int) Math.pow(x.length, n)

e.g.

```<code>static List<Double[]> getAll(int n, double[] x){
 List<Double[]> combinations = new ArrayList<>();
 //number of combinations should be x.length ^ n

 // when n = 1;
 for (int i=0;i<x.length;i++)
   combinations.add({x[i]});

 return combinations;
}

// return patterns[i] is the i th pattern
//which contains num-elements from the input depths,
//  patterns[i][j] is the j th double in patterns[i]
private double[][] void makePatterns(int num, double[] depths) {
    int patternN = (int) Math.pow(depths.length, num);
    double[][] patterns = new double[patternN][num];
    System.out.println(patterns.length);
    int i = 0;
    int k = 0;
    while (i < patternN) {
        for (int j = 0; j < num; j++) {
          //  System.out.println(i+" "+j+" "+(i / (int)Math.pow(depths.length, j))%depths.length);
            patterns[i][j] = x[(i / (int)Math.pow(depths.length, j))%depths.length];
        }
        i++;

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

This makePatterns is where I started...

答:
Here is a recursive way of doing that.

private static void combine(int n, double[] x, List<List<Double>> combinations, List<Double> combination) {
    if (combination.size() == n) {
        combinations.add(combination);
    }
    else {
        for (int i = 0; i < x.length; i++) {
            List<Double> newCombination = new ArrayList<>(combination);
            newCombination.add(x[i]);
            combine(n, x, combinations, newCombination);
        }
    }
}

public static List<List<Double>> getCombinations(int n, double[] x) {
    List<List<Double>> combinations = new ArrayList<>();
    combine(n, x, combinations, new ArrayList<>());
    return combinations;
}

public static void main(String[] args) {
    getCombinations(2, new double[] {1,2,3}).forEach(System.out::println);
}
```

<hr>

<p>The same way but with <code>double[]</code>.</p>

<pre class="lang-java prettyprint-override"><code>private static void combine(int n, double[] x, List<double[]> combinations, double[] combination) {
    if (combination.length == n) {
        combinations.add(combination);
    }
    else {
        for (int i = 0; i < x.length; i++) {
            double[] newCombination = Arrays.copyOf(combination, combination.length + 1);
            newCombination[combination.length] = x[i];
            combine(n, x, combinations, newCombination);
        }
    }
}

public static List<double[]> getCombinations(int n, double[] x) {
    List<double[]> combinations = new ArrayList<>();
    combine(n, x, combinations, new double[] {});
    return combinations;
}

public static void main(String[] args) {
    getCombinations(2, new double[] {1,2,3}).forEach(doubleArray -> {System.out.println(Arrays.toString(doubleArray));});
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I make a method in Java which obtains input integer n, and an array of double x, and returns all combinations of n elements out of values in x.

Where x={1,2,3} and n=2,

the expected returns/combinations are
{1,1},{1,2},{1,3},{2,2},{2,1},{2,3},{3,1},{3,2},{3,3}
(the order is not ignored.) The number should be (int) Math.pow(x.length, n)

e.g.

static List<Double[]> getAll(int n, double[] x){
 List<Double[]> combinations = new ArrayList<>();
 //number of combinations should be x.length ^ n

 // when n = 1;
 for (int i=0;i<x.length;i++)
   combinations.add({x[i]});

 return combinations;
}

// return patterns[i] is the i th pattern
//which contains num-elements from the input depths,
//  patterns[i][j] is the j th double in patterns[i]
private double[][] void makePatterns(int num, double[] depths) {
    int patternN = (int) Math.pow(depths.length, num);
    double[][] patterns = new double[patternN][num];
    System.out.println(patterns.length);
    int i = 0;
    int k = 0;
    while (i < patternN) {
        for (int j = 0; j < num; j++) {
          //  System.out.println(i+" "+j+" "+(i / (int)Math.pow(depths.length, j))%depths.length);
            patterns[i][j] = x[(i / (int)Math.pow(depths.length, j))%depths.length];
        }
        i++;

    }
  return patterns;
}

This makePatterns is where I started...

Body:
Here is a recursive way of doing that.

private static void combine(int n, double[] x, List<List<Double>> combinations, List<Double> combination) {
    if (combination.size() == n) {
        combinations.add(combination);
    }
    else {
        for (int i = 0; i < x.length; i++) {
            List<Double> newCombination = new ArrayList<>(combination);
            newCombination.add(x[i]);
            combine(n, x, combinations, newCombination);
        }
    }
}

public static List<List<Double>> getCombinations(int n, double[] x) {
    List<List<Double>> combinations = new ArrayList<>();
    combine(n, x, combinations, new ArrayList<>());
    return combinations;
}

public static void main(String[] args) {
    getCombinations(2, new double[] {1,2,3}).forEach(System.out::println);
}

The same way but with double[].

private static void combine(int n, double[] x, List<double[]> combinations, double[] combination) {
    if (combination.length == n) {
        combinations.add(combination);
    }
    else {
        for (int i = 0; i < x.length; i++) {
            double[] newCombination = Arrays.copyOf(combination, combination.length + 1);
            newCombination[combination.length] = x[i];
            combine(n, x, combinations, newCombination);
        }
    }
}

public static List<double[]> getCombinations(int n, double[] x) {
    List<double[]> combinations = new ArrayList<>();
    combine(n, x, combinations, new double[] {});
    return combinations;
}

public static void main(String[] args) {
    getCombinations(2, new double[] {1,2,3}).forEach(doubleArray -> {System.out.println(Arrays.toString(doubleArray));});
}


问:
Convert a list of data frames into a single data frame with list name
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

```<code>set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)
</code>```

This results in a data frame format (dfFormat) that looks like this:

```<code>'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...
</code>```

and a list of data frames listFormat that looks like this:

```<code>List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...
</code>```

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

答:
Given that each data.frame has identical ID columns, in base R it's pretty easy.

```<code>as.data.frame(listFormat)

#   A_B.ID   A_B.Age A_B.Points A_C.ID    A_C.Age A_C.Points B_C.ID   B_C.Age B_C.Points
# 1    ID1 0.2655087  0.3981059    ID1 0.67371223  0.4094018    ID1 0.8142518  1.4738812
# 2    ID2 0.3721239 -0.6120264    ID2 0.09485786  1.6888733    ID2 0.9287772  0.6772685
# 3    ID3 0.5728534  0.3411197    ID3 0.49259612  1.5865884    ID3 0.1474810  0.3799627
# 4    ID4 0.9082078 -1.1293631    ID4 0.46155184 -0.3309078    ID4 0.7498217 -0.1927984
# 5    ID5 0.2016819  1.4330237    ID5 0.37521653 -2.2852355    ID5 0.9756573  1.5778918
# 6    ID6 0.8983897  1.9803999    ID6 0.99109922  2.4976616    ID6 0.9747925  0.5962341
</code>```

You get an ID column for each data.frame, but this can then be easily tidied up

In case you need a more general solution for situations where the id columns of each data.frame differ, then you can do the following using library(data.table)

```<code>DTFormat = rbindlist(listFormat, idcol = T)
dcast(DTFormat, ID~.id, value.var = c('Age', 'Points'))
</code>```

Body:
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)

This results in a data frame format (dfFormat) that looks like this:

'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...

and a list of data frames listFormat that looks like this:

List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

Body:
Given that each data.frame has identical ID columns, in base R it's pretty easy.

as.data.frame(listFormat)

#   A_B.ID   A_B.Age A_B.Points A_C.ID    A_C.Age A_C.Points B_C.ID   B_C.Age B_C.Points
# 1    ID1 0.2655087  0.3981059    ID1 0.67371223  0.4094018    ID1 0.8142518  1.4738812
# 2    ID2 0.3721239 -0.6120264    ID2 0.09485786  1.6888733    ID2 0.9287772  0.6772685
# 3    ID3 0.5728534  0.3411197    ID3 0.49259612  1.5865884    ID3 0.1474810  0.3799627
# 4    ID4 0.9082078 -1.1293631    ID4 0.46155184 -0.3309078    ID4 0.7498217 -0.1927984
# 5    ID5 0.2016819  1.4330237    ID5 0.37521653 -2.2852355    ID5 0.9756573  1.5778918
# 6    ID6 0.8983897  1.9803999    ID6 0.99109922  2.4976616    ID6 0.9747925  0.5962341

You get an ID column for each data.frame, but this can then be easily tidied up

In case you need a more general solution for situations where the id columns of each data.frame differ, then you can do the following using library(data.table)

DTFormat = rbindlist(listFormat, idcol = T)
dcast(DTFormat, ID~.id, value.var = c('Age', 'Points'))


问:
Swift: Trying to execute two functions with delegation
I am trying to execute two functions in another view by pressing two buttons. Each button should call one of the functions, that is passed on through delegation.
But it seems like when I am pressing one of the buttons they execute both functions of the protocol simultaneously.
Only when I comment/remove one function it works.

The protocol:

```<code>protocol ManipulateSectionDelegate {
    func addSection()
    func removeSection()
}
</code>```

The MainView:
Here are the functions that should get called, when pressing the buttons in the second View

```<code>extension MainViewController: ManipulateSectionDelegate{

    @objc func showSettingsView(){
        let settingsController = SettingsViewController()
        settingsController.delegateManipuplateSection = self
        navigationController?.pushViewController(settingsController, animated: true)
    }

    func addSection(){
        semesterList.append(Semester.init(subject: [], done: false))
        subjectTableView.reloadData()
        print(semesterList)
    }

    func removeSection(){
        semesterList.removeLast()
        subjectTableView.reloadData()
        print(semesterList)
    }

}
</code>```

The second View:

```<code>class SettingsViewController:UIViewController{

    var delegateManipuplateSection: ManipulateSectionDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        addSectionButton.addTarget(self, action: #selector(addSectionButtonPressed), for: .touchUpInside)

        addSectionButton.addTarget(self, action: #selector(removeSectionButtonPressed), for: .touchUpInside)

    }
}

extension SettingsViewController{

    @objc func addSectionButtonPressed(){
        delegateManipuplateSection?.addSection()
    }

    @objc func removeSectionButtonPressed(){
        delegateManipuplateSection?.removeSection()
    }
}
</code>```

Even though each button is connected to a different function and should execute only one of them, both get executed.
Is this a situation where I would have to use observers and notifications? Did I do something wrong?

答:
You connected two actions to one same button

```<code>    addSectionButton.addTarget(self, action: #selector(addSectionButtonPressed), for: .touchUpInside)

    addSectionButton.addTarget(self, action: #selector(removeSectionButtonPressed), for: .touchUpInside)
</code>```

Body:
I am trying to execute two functions in another view by pressing two buttons. Each button should call one of the functions, that is passed on through delegation.
But it seems like when I am pressing one of the buttons they execute both functions of the protocol simultaneously.
Only when I comment/remove one function it works.

The protocol:

protocol ManipulateSectionDelegate {
    func addSection()
    func removeSection()
}

The MainView:
Here are the functions that should get called, when pressing the buttons in the second View

extension MainViewController: ManipulateSectionDelegate{

    @objc func showSettingsView(){
        let settingsController = SettingsViewController()
        settingsController.delegateManipuplateSection = self
        navigationController?.pushViewController(settingsController, animated: true)
    }

    func addSection(){
        semesterList.append(Semester.init(subject: [], done: false))
        subjectTableView.reloadData()
        print(semesterList)
    }

    func removeSection(){
        semesterList.removeLast()
        subjectTableView.reloadData()
        print(semesterList)
    }

}

The second View:

class SettingsViewController:UIViewController{

    var delegateManipuplateSection: ManipulateSectionDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        addSectionButton.addTarget(self, action: #selector(addSectionButtonPressed), for: .touchUpInside)

        addSectionButton.addTarget(self, action: #selector(removeSectionButtonPressed), for: .touchUpInside)

    }
}

extension SettingsViewController{

    @objc func addSectionButtonPressed(){
        delegateManipuplateSection?.addSection()
    }

    @objc func removeSectionButtonPressed(){
        delegateManipuplateSection?.removeSection()
    }
}

Even though each button is connected to a different function and should execute only one of them, both get executed.
Is this a situation where I would have to use observers and notifications? Did I do something wrong?

Body:
You connected two actions to one same button

    addSectionButton.addTarget(self, action: #selector(addSectionButtonPressed), for: .touchUpInside)

    addSectionButton.addTarget(self, action: #selector(removeSectionButtonPressed), for: .touchUpInside)


问:
PHP Codeigniter Session error: Message: session_cache_limiter(): Cannot change cache limiter when session is active
php -v:7.3.11

codeigniter  -v:3.0.3

```<code>A PHP Error was encountered
Severity: Warning

Message: session_cache_limiter(): Cannot change cache limiter when session is active

Filename: core/MY_Controller.php

Line Number: 24

Backtrace:

File: G:\xamp\htdocs\sales_pro\a\site\application\core\MY_Controller.php
Line: 24
Function: session_cache_limiter

File: G:\xamp\htdocs\sales_pro\a\site\application\controllers\admin\Login.php
Line: 16
Function: __construct

File: G:\xamp\htdocs\sales_pro\a\site\index.php
Line: 309
Function: require_once
</code>```

I tried commenting out the following lines in system/libraries/session/session.php
but not working

```<code>session_start()
ini_set('session.use_trans_sid', 0);
ini_set('session.use_strict_mode', 1);
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.hash_function', 1);
ini_set('session.hash_bits_per_character', 4);
</code>```

I also tried

```<code> if(!isset($_SESSION)){
        session_start();
 }
</code>```

答: swithched codeigniter version to 3.1... And the issue solved</p>

Body:
php -v:7.3.11

codeigniter  -v:3.0.3

A PHP Error was encountered
Severity: Warning

Message: session_cache_limiter(): Cannot change cache limiter when session is active

Filename: core/MY_Controller.php

Line Number: 24

Backtrace:

File: G:\xamp\htdocs\sales_pro\a\site\application\core\MY_Controller.php
Line: 24
Function: session_cache_limiter

File: G:\xamp\htdocs\sales_pro\a\site\application\controllers\admin\Login.php
Line: 16
Function: __construct

File: G:\xamp\htdocs\sales_pro\a\site\index.php
Line: 309
Function: require_once

I tried commenting out the following lines in system/libraries/session/session.php
but not working

session_start()
ini_set('session.use_trans_sid', 0);
ini_set('session.use_strict_mode', 1);
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.hash_function', 1);
ini_set('session.hash_bits_per_character', 4);

I also tried

 if(!isset($_SESSION)){
        session_start();
 }


问:
Writing a simple class with accessors and mutators
I am very much a newbie to Java.  I have been asked to Write a java class for a very simple Course class, named Course, that has the data members name and credit hours (e.g. "Programming and Logic I", 4). Your class needs to include the accessor (i.e. get) and mutator (i.e. set) methods for each attribute and at least one overloaded constructor which initializes the data members name and credit hours.

This is what I have so far, but I believe I am so far off and my brain just doesn't want to work right now.

```<code>public class Course {

public String courseName;
public int creditHours;

public Course(String courseName, int creditHours) {

    this.courseName = courseName;
    this.creditHours = creditHours;

    public String getCourseName() {
        return courseName;
    }
    public int getCreditHours(){
        return creditHours
    }

   public void setCourse(String course)
   {
     this.course = course;
   }

   public void setHours(String hours)
   {
     this.hours = hours;
    }

}
}
</code>```

答:
Your syntax is just a bit off. In Java, constructors are declared as methods of a class almost like any other methods. Try</p>

```<code>public Course {
    private String courseName;
    private int creditHours;

    public Course() {
        courseName = null;
        creditHours = 0;
    }

    public Course(String courseName, int creditHours) {
        this.courseName = courseName;
        this.creditHours = creditHours;
    }

    // ... and your getters and setters, which look fine except for one missing semicolon
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am very much a newbie to Java.  I have been asked to Write a java class for a very simple Course class, named Course, that has the data members name and credit hours (e.g. "Programming and Logic I", 4). Your class needs to include the accessor (i.e. get) and mutator (i.e. set) methods for each attribute and at least one overloaded constructor which initializes the data members name and credit hours.

This is what I have so far, but I believe I am so far off and my brain just doesn't want to work right now.

public class Course {

public String courseName;
public int creditHours;

public Course(String courseName, int creditHours) {

    this.courseName = courseName;
    this.creditHours = creditHours;

    public String getCourseName() {
        return courseName;
    }
    public int getCreditHours(){
        return creditHours
    }

   public void setCourse(String course)
   {
     this.course = course;
   }

   public void setHours(String hours)
   {
     this.hours = hours;
    }

}
}

Body:
Your syntax is just a bit off. In Java, constructors are declared as methods of a class almost like any other methods. Try

public Course {
    private String courseName;
    private int creditHours;

    public Course() {
        courseName = null;
        creditHours = 0;
    }

    public Course(String courseName, int creditHours) {
        this.courseName = courseName;
        this.creditHours = creditHours;
    }

    // ... and your getters and setters, which look fine except for one missing semicolon
}


问:
Get previous page count if text goes more than 2 characters
I am building a load more functionality in v-autocomplete (vuetify's component).

Here is my logic:

-1: Register keyup event function and, if the text goes more than 2 characters, it will call fetch, here's the code:

```<code>// Data
Search = '';
CurrentPage = 1;
Timer;

// Search
search(event) {
  const value = event.target.value;
  if (!!value && value.length > 2) {
    if (this.Timer) {
      clearTimeout(this.Timer);
    }
    this.Timer = setTimeout(() => {
      this.fetch(false);
    }, 500);
  }
</code>```

-2: Here the fetch function which will call the API:

```<code>fetch(IsLoadMore) {
  if (IsLoadMore) {
    this.CurrentPage++;
    API.get(this.Search, this.CurrentPage);
  } else if (!!this.Search && this.Search.length > 2) {
    this.CurrentPage = 1;
    API.get(this.Search, this.CurrentPage);
  }
}
</code>```

-3: And here's the component:

```<code><v-autocomplete
  :search-input.sync="Search"
  cache-items
  @keyup="search"
>
  <template v-slot:append-item>
    <v-btn
      small
      class="pa-0"
      block
      color="success"
      @click="fetch(true)" <!-- Load More -->
    >Load More</v-btn>
</v-autocomplete>
</code>```

Now, I am having some problem here, let's understand it by some sample inputs:

Action => Page Load, CurrentPage = 1, Search = ''

Data comes with page 1 from API.

Action => Load More, CurrentPage = 2, Search = ''

Data comes with page 2 from API.

Action => Load More, CurrentPage = 3, Search = ''

Data comes with page 3 from API.

Action => Load More, CurrentPage = 4, Search = ''

Data comes with page 4 from API.

Action => Keyup, CurrentPage = 4, Search = 'Vu' <= Vu length is < 2

so, Data remains the same

Action => Keyup, CurrentPage = 1, Search = 'Vue' <= Vue length is > 2

so, Data comes with page 1 and query Vue from API.

Action => Keyup, CurrentPage = 1, Search = ''

Nothing happens as search reseted (text < 2), but notice CurrentPage = 1

Action => Load More, CurrentPage = 2, Search = ''

Data comes with page 2 from API, here's the problem begins, because I am using cache-items (which actually caches the data) I don't need to fetch page 2 data again, I need to fetch the page number 5 data as I have data till page 4

I need to take a note of the last page with Search < 3, I have tried some solutions but not working, one of those solution is to make PreviousPage = -1, and if Search === 3, set PreviousPage = CurrentPage, but it doesn't work, and load more accordingly.

Any Suggestions??

答:
Try this:

```<code>fetch(IsLoadMore) {
  if (IsLoadMore) {
    this.CurrentPage++;
    API.get(this.Search, this.CurrentPage);
  } else if (!!this.Search && this.Search.length > 2) {
    if (this.CurrentPage > 1) // <-- here's the trick!
      this.PreviousPage = this.CurrentPage;
    this.CurrentPage = 1;
    API.get(this.Search, this.CurrentPage);
  }
}
</code>```

Make sure you make PreviousPage variable and let me know if it works for you.

Body:
I am building a load more functionality in v-autocomplete (vuetify's component).

Here is my logic:

-1: Register keyup event function and, if the text goes more than 2 characters, it will call fetch, here's the code:

// Data
Search = '';
CurrentPage = 1;
Timer;

// Search
search(event) {
  const value = event.target.value;
  if (!!value && value.length > 2) {
    if (this.Timer) {
      clearTimeout(this.Timer);
    }
    this.Timer = setTimeout(() => {
      this.fetch(false);
    }, 500);
  }

-2: Here the fetch function which will call the API:

fetch(IsLoadMore) {
  if (IsLoadMore) {
    this.CurrentPage++;
    API.get(this.Search, this.CurrentPage);
  } else if (!!this.Search && this.Search.length > 2) {
    this.CurrentPage = 1;
    API.get(this.Search, this.CurrentPage);
  }
}

-3: And here's the component:

<v-autocomplete
  :search-input.sync="Search"
  cache-items
  @keyup="search"
>
  <template v-slot:append-item>
    <v-btn
      small
      class="pa-0"
      block
      color="success"
      @click="fetch(true)"
    >Load More</v-btn>
</v-autocomplete>

Now, I am having some problem here, let's understand it by some sample inputs:

Action => Page Load, CurrentPage = 1, Search = ''

Data comes with page 1 from API.

Action => Load More, CurrentPage = 2, Search = ''

Data comes with page 2 from API.

Action => Load More, CurrentPage = 3, Search = ''

Data comes with page 3 from API.

Action => Load More, CurrentPage = 4, Search = ''

Data comes with page 4 from API.

Action => Keyup, CurrentPage = 4, Search = 'Vu' <= Vu length is < 2

so, Data remains the same

Action => Keyup, CurrentPage = 1, Search = 'Vue' <= Vue length is > 2

so, Data comes with page 1 and query Vue from API.

Action => Keyup, CurrentPage = 1, Search = ''

Nothing happens as search reseted (text < 2), but notice CurrentPage = 1

Action => Load More, CurrentPage = 2, Search = ''

Data comes with page 2 from API, here's the problem begins, because I am using cache-items (which actually caches the data) I don't need to fetch page 2 data again, I need to fetch the page number 5 data as I have data till page 4

I need to take a note of the last page with Search < 3, I have tried some solutions but not working, one of those solution is to make PreviousPage = -1, and if Search === 3, set PreviousPage = CurrentPage, but it doesn't work, and load more accordingly.

Any Suggestions??

Body:
Try this:

fetch(IsLoadMore) {
  if (IsLoadMore) {
    this.CurrentPage++;
    API.get(this.Search, this.CurrentPage);
  } else if (!!this.Search && this.Search.length > 2) {
    if (this.CurrentPage > 1) // <-- here's the trick!
      this.PreviousPage = this.CurrentPage;
    this.CurrentPage = 1;
    API.get(this.Search, this.CurrentPage);
  }
}

Make sure you make PreviousPage variable and let me know if it works for you.


问:
Difference between passing a ReactElement and a function that returns a ReactElement
Whats the difference between passing a ReactElement as a property:

First case

```<code><RenderParam ReactElement={<Counter />} />

function RenderParam({ ReactElement }) {
  return <div>{ReactElement}</div>;
}
</code>```

and passing a function that returns a ReactElement:

Second case

```<code>const instantiatedCounter = () => <Counter />;

<RenderParam ReactElement={instantiatedCounter} />

function RenderParam({ ReactElement }) {
  return <div> <ReactElement /> </div>
}
</code>```

I see there are differences in the lifecycle:

Every time the parent react element updates, the mount cycle of Counter is executed for the second case:

```<code>ReactElement changed (at RenderParam lifecycle)
component did mount (at Counter)
</code>```

Also the second case lose its state every time the parent component renders.

I dont see whats difference between them. Why first case its able to keep its state?

答:
The first example passes a static JSX element <Counter /> as RenderParam prop. The second example uses a function instantiatedCounter, that allows to return a more dynamic JSX element, commonly referred to as Render props.

In the second case you lose state, because React treats the ReactElement prop as a freshly defined component every time, unmounts the old one and mounts it again on every render cycle. What you want to do is call the ReactElement prop to retrieve a JSX element as return value:

```<code>function RenderParam({ ReactElement }) {
  return <div>{ReactElement()}</div>;
  // not: return <div><ReactElement /></div>
}
</code>```

You could as well define it with JSX syntax
<ReactElement />
. But then make sure, instantiatedCounter is a static function and not re-created on every render, so the object reference stays same:

```<code>const instantiatedCounter = () => <Counter />;
// make it static in some way, so object reference doesn't change

export default function App() {
  // .. and remove instantiatedCounter here
  return <RenderParam ReactElement={instantiatedCounter} />
}
</code>```

Body:
Whats the difference between passing a ReactElement as a property:

First case

<RenderParam ReactElement={<Counter />} />

function RenderParam({ ReactElement }) {
  return
{ReactElement}
;
}

and passing a function that returns a ReactElement:

Second case

const instantiatedCounter = () => <Counter />;

<RenderParam ReactElement={instantiatedCounter} />

function RenderParam({ ReactElement }) {
  return
 <ReactElement />

}

I see there are differences in the lifecycle:

Every time the parent react element updates, the mount cycle of Counter is executed for the second case:

ReactElement changed (at RenderParam lifecycle)
component did mount (at Counter)

Also the second case lose its state every time the parent component renders.

I dont see whats difference between them. Why first case its able to keep its state?

Body:
The first example passes a static JSX element <Counter /> as RenderParam prop. The second example uses a function instantiatedCounter, that allows to return a more dynamic JSX element, commonly referred to as Render props.

In the second case you lose state, because React treats the ReactElement prop as a freshly defined component every time, unmounts the old one and mounts it again on every render cycle. What you want to do is call the ReactElement prop to retrieve a JSX element as return value:

function RenderParam({ ReactElement }) {
  return <div>{ReactElement()}</div>;
  // not: return <div><ReactElement /></div>
}

You could as well define it with JSX syntax <div><ReactElement /></div>. But then make sure, instantiatedCounter is a static function and not re-created on every render, so the object reference stays same:

const instantiatedCounter = () => <Counter />;
// make it static in some way, so object reference doesn't change

export default function App() {
  // .. and remove instantiatedCounter here
  return <RenderParam ReactElement={instantiatedCounter} />
}


问:
WPF ListView: Attaching a double-click (on an item) event
I have the following ListView:

```<code><ListView Name="TrackListView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Title" Width="100"
                            HeaderTemplate="{StaticResource BlueHeader}"
                            DisplayMemberBinding="{Binding Name}"/>

            <GridViewColumn Header="Artist" Width="100"
                            HeaderTemplate="{StaticResource BlueHeader}"
                            DisplayMemberBinding="{Binding Album.Artist.Name}" />
        </GridView>
    </ListView.View>
</ListView>
</code>```

How can I attach an event to every bound item that will fire on double-clicking the item?

答:
Alternative that I used is Event To Command,</p>

```<code><ListView ItemsSource="{Binding SelectedTrack}" SelectedItem="{Binding SelectedTrack}" >
    <i:Interaction.Triggers>
         <i:EventTrigger EventName="MouseDoubleClick">
              <i:InvokeCommandAction Command="{Binding SelectTrackCommand}"/>
         </i:EventTrigger>
    </i:Interaction.Triggers>
    ...........
    ...........
</ListView>
</code>```

Body:
I have the following ListView:

<ListView Name="TrackListView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Title" Width="100"
                            HeaderTemplate="{StaticResource BlueHeader}"
                            DisplayMemberBinding="{Binding Name}"/>

            <GridViewColumn Header="Artist" Width="100"
                            HeaderTemplate="{StaticResource BlueHeader}"
                            DisplayMemberBinding="{Binding Album.Artist.Name}" />
        </GridView>
    </ListView.View>
</ListView>

How can I attach an event to every bound item that will fire on double-clicking the item?

Body:
Alternative that I used is Event To Command,

<ListView ItemsSource="{Binding SelectedTrack}" SelectedItem="{Binding SelectedTrack}" >
    <i:Interaction.Triggers>
         <i:EventTrigger EventName="MouseDoubleClick">
              <i:InvokeCommandAction Command="{Binding SelectTrackCommand}"/>
         </i:EventTrigger>
    </i:Interaction.Triggers>
    ...........
    ...........
</ListView>


问:
What makes Haskell's type system more "powerful" than other languages' type systems?
Reading Disadvantages of Scala type system versus Haskell?, I have to ask: what is it, specifically, that makes Haskell's type system more powerful than other languages' type systems (C, C++, Java). Apparently, even Scala can't perform some of the same powers as Haskell's type system. What is it, specifically, that makes Haskell's type system (Hindley–Milner type inference) so powerful? Can you give an example?

答:
What is expressiveness? To my understanding it is what constraint the type system allow us to put on our code, or in other words what properties of code which we can prove. The more expressive a type system is, the more information we can embed at the type level (which can be used at compile time by the type-checker to check our code).

Here are some properties of Haskell's type system that other languages don't have.

Purity.

Purity allows Haskell to distinguish pure code and IO capable code

Paramtricity.

Haskell enforces parametricity for parametrically polymorphic functions so they must obey some laws. (Some languages does let you to express polymorphic function types but they don't enforce parametricity, for example Scala lets you to pattern match on a specific type even if the argument is polymorphic)

ADT

Extensions

Haskell's base type system is a weaker version of λ2 which itself isn't really impressive. But with these extensions it become really powerful (even able to express dependent types with singleton):

existential types

rank-n types (full λ2)

type families

data kinds (allows "typed" programming at type level)

GADT
...

ContentLicense: CC BY-SA 2.5


问:
Unable to catch and handle spring custom events in java
I am trying to set up a custom spring event publisher and listener.
The flow of the process seems to be working fine, I can see the prints before the event publishes,  however, my event listeners do not catch the event.
my main class is:

```<code>public class TestClass {

        public static void main(String[] args) throws Exception {
            testEvents();
        }

        private static void testEvents() throws InterruptedException {
            AnnotationConfigApplicationContext eventPublisherContext = new AnnotationConfigApplicationContext(EventListenerConfig.class);
            CustomSpringEventPublisher eventPublisher = eventPublisherContext.getBean(CustomSpringEventPublisher.class);
            List<CustomSpringEventListener> listenersList = new ArrayList<CustomSpringEventListener>();

            for (int i = 0; i < 5; i++) {
                listenersList.add(new CustomSpringEventListener("LR" + (i + 1)));
            }

            for (int i = 0; i < 10; i++) {
                Thread.sleep(5000);

                LocalDateTime now  = LocalDateTime.now();
                eventPublisher.doStuffAndPublishAnEvent("new event " + now.format(Formats.isolong));
            }
        }
    }
</code>```

here is my custom event class:

```<code>public class CustomSpringEvent extends ApplicationEvent {
    private String message;

    public CustomSpringEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

}
</code>```

here is my custom event publisher class:

```<code>@Component
public class CustomSpringEventPublisher {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void doStuffAndPublishAnEvent(final String message) {
        System.out.println("Publishing custom event --> " + message);
        this.applicationEventPublisher.publishEvent(new CustomSpringEvent(this, message));
    }

}
</code>```

here is my custom event listener class:

```<code>public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    private String name;

    public CustomSpringEventListener(String name) {
        this.name = name;
    }

    @Override
    @EventListener
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println(name + " received spring custom event - " + event.getMessage());
    }

}
</code>```

here is my event listener config class:

```<code>@Configuration
@ComponentScan({"some.local.directory.testCases"})
public class EventListenerConfig {
}
</code>```

What am I missing here? How can I get my listener class to recognize the published event and handle it?
I saw some examples in which the listener class has the @Component, but when I tried to add it I got an error from spring:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate., also I don't see any reason why would the listener class have this annotation in this case.
Any help would be appreciated. Thank you.

答:
In order to call event listeners, Spring needs to know the listener class and have it into its applicationContext, under what is called a Bean.

You do need to annotate your class with @Component. But when you do so, you get an error. Let's clarify this.

Quick overview of Spring

Having a class annotated with @Component will indicate to Spring it needs to "manage" the class himself. By managing, it includes creating all the "dependencies" first, and then calling the "constructor". Let's call this the dependency tree. Once Spring gets to the bottom of it, it can start climbing back up and creating the object and its way back to the top.

Dependencies management

Spring knows your classe's dependencies by analyzing the constructor, setter or attributes annotated by @Autowired. Note that if your class has only one constructor, Spring automatically scans it to know about dependencies, even if there is not @Autowired at the top of it.

In your case, for CustomSpringEventListener, you have one constructor taking in parameter a String. If we build the dependency tree of your CustomSpringEventListener, we get something like that :

```<code>CustomSpringEventListener ---> String
</code>```

So when Spring tries to create your CustomSpringEventListener, it will look for a bean of type String, because, your code is saying : If you ever want to create an object CustomSpringEventListener, you need to give a name which is a String.
But you do not have a bean of type String in your code I guess.

The solution

In a first time, annotate your class CustomSpringEventListener with @Component and remove your attribute and the constructor.

```<code>@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {

    @Override
    @EventListener
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println("Received spring custom event - " + event.getMessage());
    }

}
</code>```

In a second time, find a different way to have a name in your class if you really need it.

Listener with attributes

Let's say you need a more sophisticated Listener, like one using a ServiceA. You can do the following :

```<code>@Service
public class ServiceA { ... }
</code>```

```<code>@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    private ServiceA serviceA;

    public CustomSpringEventListener(ServiceA serviceA) {
        this.serviceA = serviceA;
    }

}
</code>```

Same listener with a name

You can combine @Configuration class to create many times the same Listener.
Let's use your first Listener, with the name attribute.

```<code>public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    private String name;

    public CustomSpringEventListener(String name) {
        this.name = name;
    }

    @Override
    @EventListener
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println(name + " received spring custom event - " + event.getMessage());
    }

}
</code>```

Without the @Component annotation, what you can do is using a @Configuration class to instantiate your Listener:

```<code>@Configuration
public ListenerConfig {

    public CustomSpringEventListener listenerA() {
        return new CustomSpringEventListener("listenerA");
    }

    public CustomSpringEventListener listenerB() {
        return new CustomSpringEventListener("listenerB");
    }

    public CustomSpringEventListener listenerC() {
        return new CustomSpringEventListener("listenerC");
    }

    ...
}
</code>```

You can mix Spring configuration to do whatever configuration you need.

Hope it helps.

Body:
I am trying to set up a custom spring event publisher and listener.
The flow of the process seems to be working fine, I can see the prints before the event publishes,  however, my event listeners do not catch the event.
my main class is:

public class TestClass {

        public static void main(String[] args) throws Exception {
            testEvents();
        }

        private static void testEvents() throws InterruptedException {
            AnnotationConfigApplicationContext eventPublisherContext = new AnnotationConfigApplicationContext(EventListenerConfig.class);
            CustomSpringEventPublisher eventPublisher = eventPublisherContext.getBean(CustomSpringEventPublisher.class);
            List<CustomSpringEventListener> listenersList = new ArrayList<CustomSpringEventListener>();

            for (int i = 0; i < 5; i++) {
                listenersList.add(new CustomSpringEventListener("LR" + (i + 1)));
            }

            for (int i = 0; i < 10; i++) {
                Thread.sleep(5000);

                LocalDateTime now  = LocalDateTime.now();
                eventPublisher.doStuffAndPublishAnEvent("new event " + now.format(Formats.isolong));
            }
        }
    }

here is my custom event class:

public class CustomSpringEvent extends ApplicationEvent {
    private String message;

    public CustomSpringEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

}

here is my custom event publisher class:

@Component
public class CustomSpringEventPublisher {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void doStuffAndPublishAnEvent(final String message) {
        System.out.println("Publishing custom event --> " + message);
        this.applicationEventPublisher.publishEvent(new CustomSpringEvent(this, message));
    }

}

here is my custom event listener class:

public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    private String name;

    public CustomSpringEventListener(String name) {
        this.name = name;
    }

    @Override
    @EventListener
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println(name + " received spring custom event - " + event.getMessage());
    }

}

here is my event listener config class:

@Configuration
@ComponentScan({"some.local.directory.testCases"})
public class EventListenerConfig {
}

What am I missing here? How can I get my listener class to recognize the published event and handle it?
I saw some examples in which the listener class has the @Component, but when I tried to add it I got an error from spring:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate., also I don't see any reason why would the listener class have this annotation in this case.
Any help would be appreciated. Thank you.

Body:
In order to call event listeners, Spring needs to know the listener class and have it into its applicationContext, under what is called a Bean.

You do need to annotate your class with @Component. But when you do so, you get an error. Let's clarify this.

Quick overview of Spring

Having a class annotated with @Component will indicate to Spring it needs to "manage" the class himself. By managing, it includes creating all the "dependencies" first, and then calling the "constructor". Let's call this the dependency tree. Once Spring gets to the bottom of it, it can start climbing back up and creating the object and its way back to the top.

Dependencies management

Spring knows your classe's dependencies by analyzing the constructor, setter or attributes annotated by @Autowired. Note that if your class has only one constructor, Spring automatically scans it to know about dependencies, even if there is not @Autowired at the top of it.

In your case, for CustomSpringEventListener, you have one constructor taking in parameter a String. If we build the dependency tree of your CustomSpringEventListener, we get something like that :

CustomSpringEventListener ---> String

So when Spring tries to create your CustomSpringEventListener, it will look for a bean of type String, because, your code is saying : If you ever want to create an object CustomSpringEventListener, you need to give a name which is a String.
But you do not have a bean of type String in your code I guess.

The solution

In a first time, annotate your class CustomSpringEventListener with @Component and remove your attribute and the constructor.

@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {

    @Override
    @EventListener
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println("Received spring custom event - " + event.getMessage());
    }

}

In a second time, find a different way to have a name in your class if you really need it.

Listener with attributes

Let's say you need a more sophisticated Listener, like one using a ServiceA. You can do the following :

@Service
public class ServiceA { ... }

@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    private ServiceA serviceA;

    public CustomSpringEventListener(ServiceA serviceA) {
        this.serviceA = serviceA;
    }

}

Same listener with a name

You can combine @Configuration class to create many times the same Listener.
Let's use your first Listener, with the name attribute.

public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    private String name;

    public CustomSpringEventListener(String name) {
        this.name = name;
    }

    @Override
    @EventListener
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println(name + " received spring custom event - " + event.getMessage());
    }

}

Without the @Component annotation, what you can do is using a @Configuration class to instantiate your Listener:

@Configuration
public ListenerConfig {

    public CustomSpringEventListener listenerA() {
        return new CustomSpringEventListener("listenerA");
    }

    public CustomSpringEventListener listenerB() {
        return new CustomSpringEventListener("listenerB");
    }

    public CustomSpringEventListener listenerC() {
        return new CustomSpringEventListener("listenerC");
    }

    ...
}

You can mix Spring configuration to do whatever configuration you need.

Hope it helps.


问:
C++ Boost::asio serial communcation with Arduino can't write
I tried to communicate with my Arduino Uno using the Boost Asio library. Somehow I can't send data to my Arduino, and I have no idea what i'm doing wrong. Reading works fine, but writing only works when i open a terminal and say:

```<code>cat /dev/ttyACM0
</code>```

When this terminal window is open, and I run my C++ application it works otherwise it doesn't work.

Code of the test application (C++):

```<code>#include <iostream>
#include <boost/asio.hpp>

char* message;

int main()
{

    boost::asio::io_service ioservice;
    boost::asio::serial_port serial(ioservice, "/dev/ttyACM0");

    serial.set_option(boost::asio::serial_port_base::baud_rate(115200));
    serial.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::none));
    serial.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::none));
    serial.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::one));
    serial.set_option(boost::asio::serial_port::character_size(boost::asio::serial_port::character_size(8)));

    std::string s = "u";
    boost::asio::streambuf b;
    std::ostream os(&b);
    os << s;
    boost::asio::write(serial, b.data());

    if (serial.is_open()) {
        serial.close();
    }

    return 0;
}
</code>```

Code of my Arduino application:

```<code>#include "Servo.h"

Servo servo;
void setup() {
  Serial.begin(115200);
  servo.attach(9);
  servo.write(0);
}

void loop() {
  if(Serial.available()) {
    char c = Serial.read();
    if(c == 'u') {
      servo.write(180);
    } else if (c == 'v') {
      servo.write(0);
    }
  }
}
</code>```

I tried this both on my Ubuntu 18.04 and Debian 10 installation to rule out a permission issue, so I think there is something wrong with my code.

Update:

I found the issue, the Arduino is restarting when making a serial connection. When I add a thread sleep for for example 5 seconds and after that resent the data it works (because then it keeps the serial connection alive). I'm still looking for a permanent solution, so that I don't have to do a write before I really want to write something.

Update 2:

Apparently I don't even have to do a write, but where must be a small delay before I can start writing, because when after opening the port the Arduino is still restarting.

答:
I fixed it with adding a small delay before writing to the serial port. As I also wrote in my comment above, the Arduino is restarting when you start a serial communication.

This can be disabled on several ways: https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection/

Another option is to send a "ready" signal from the Arduino to know in your application that the Arduino is rebooted. So then start in your application with reading, and when you received that message, you can start writing.

Body:
I tried to communicate with my Arduino Uno using the Boost Asio library. Somehow I can't send data to my Arduino, and I have no idea what i'm doing wrong. Reading works fine, but writing only works when i open a terminal and say:

cat /dev/ttyACM0

When this terminal window is open, and I run my C++ application it works otherwise it doesn't work.

Code of the test application (C++):

#include <iostream>
#include <boost/asio.hpp>

char* message;

int main()
{

    boost::asio::io_service ioservice;
    boost::asio::serial_port serial(ioservice, "/dev/ttyACM0");

    serial.set_option(boost::asio::serial_port_base::baud_rate(115200));
    serial.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::none));
    serial.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::none));
    serial.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::one));
    serial.set_option(boost::asio::serial_port::character_size(boost::asio::serial_port::character_size(8)));

    std::string s = "u";
    boost::asio::streambuf b;
    std::ostream os(&b);
    os << s;
    boost::asio::write(serial, b.data());

    if (serial.is_open()) {
        serial.close();
    }

    return 0;
}

Code of my Arduino application:

#include "Servo.h"

Servo servo;
void setup() {
  Serial.begin(115200);
  servo.attach(9);
  servo.write(0);
}

void loop() {
  if(Serial.available()) {
    char c = Serial.read();
    if(c == 'u') {
      servo.write(180);
    } else if (c == 'v') {
      servo.write(0);
    }
  }
}

I tried this both on my Ubuntu 18.04 and Debian 10 installation to rule out a permission issue, so I think there is something wrong with my code.

Update:

I found the issue, the Arduino is restarting when making a serial connection. When I add a thread sleep for for example 5 seconds and after that resent the data it works (because then it keeps the serial connection alive). I'm still looking for a permanent solution, so that I don't have to do a write before I really want to write something.

Update 2:

Apparently I don't even have to do a write, but where must be a small delay before I can start writing, because when after opening the port the Arduino is still restarting.


问:
Redshift: splitting a time duration row by 24 hour period
I'm also trying to split a row by 24 hours period ranges between FromDate, Todate.

For example, if a time row has given as below, (Range between FromDate, Todate is 4 days, so I want 4 rows)

```<code>ID---FromDate---Todate
1---2014-04-01 08:00:00.000---2014-04-04 12:00:00.000
</code>```

The result I want to see would be like this:

```<code>ID---FromDate---Todate---DateDiff(HH)
1---2014-04-01 08:00:00.000---2014-04-01 23:59:59.000---15
1---2014-04-02 00:00:00.000---2014-04-02 23:59:59.000---23
1---2014-04-03 00:00:00.000---2014-04-03 23:59:59.000---23
1---2014-04-04 00:00:00.000---2014-04-04 12:00:00.000---12
</code>```

I have found a solution to this, but it just does not work using Redshift when I iterate inside my own auxiliary table (different from the solution using SQL Server!)

I am not sure if this could be possible using Redshift or if I should look for another way to solve it (like a custom function or something like that).

Thanks!

答:
Redshift has one painful "feature".  It is a pain to generate a derived table.  Let me assume that you have a table big enough to generate a tally or numbers table.

Then, the rest is date arithmetic . . . but a bit complicated.  I don't have Redshift on hand -- and it has a weird combination of date syntax from SQL Server and Postgres

```<code>with numbers as (
      select row_number() over () - 1 as n
      from t
     )
select t.id,
       greatest(date_trunc('day', t.fromdate) + n.n * interval '1 day', t.fromdate)  as fromdate,
       least(date_trunc('day', t.fromdate) + (n.n + 1) * interval '1 day', t.todate) as todate
       datediff(hour,
                greatest(date_trunc('day', t.fromdate) + n.n * interval '1 day', t.fromdate),
                least(date_trunc('day', t.fromdate) + (n.n + 1) * interval '1 day', todate)
               ) as hours
from t join
     numbers n
     on todate > date_trunc('day', t.fromdate) + n.n * interval '1 day';
</code>```

Here is a db<>fiddle using Postgres that illustrates the main ideas behind this.

Body:
I'm also trying to split a row by 24 hours period ranges between FromDate, Todate.

For example, if a time row has given as below, (Range between FromDate, Todate is 4 days, so I want 4 rows)

ID---FromDate---Todate
1---2014-04-01 08:00:00.000---2014-04-04 12:00:00.000

The result I want to see would be like this:

ID---FromDate---Todate---DateDiff(HH)
1---2014-04-01 08:00:00.000---2014-04-01 23:59:59.000---15
1---2014-04-02 00:00:00.000---2014-04-02 23:59:59.000---23
1---2014-04-03 00:00:00.000---2014-04-03 23:59:59.000---23
1---2014-04-04 00:00:00.000---2014-04-04 12:00:00.000---12

I have found a solution to this, but it just does not work using Redshift when I iterate inside my own auxiliary table (different from the solution using SQL Server!)

I am not sure if this could be possible using Redshift or if I should look for another way to solve it (like a custom function or something like that).

Thanks!

Body:
Redshift has one painful "feature".  It is a pain to generate a derived table.  Let me assume that you have a table big enough to generate a tally or numbers table.

Then, the rest is date arithmetic . . . but a bit complicated.  I don't have Redshift on hand -- and it has a weird combination of date syntax from SQL Server and Postgres

with numbers as (
      select row_number() over () - 1 as n
      from t
     )
select t.id,
       greatest(date_trunc('day', t.fromdate) + n.n * interval '1 day', t.fromdate)  as fromdate,
       least(date_trunc('day', t.fromdate) + (n.n + 1) * interval '1 day', t.todate) as todate
       datediff(hour,
                greatest(date_trunc('day', t.fromdate) + n.n * interval '1 day', t.fromdate),
                least(date_trunc('day', t.fromdate) + (n.n + 1) * interval '1 day', todate)
               ) as hours
from t join
     numbers n
     on todate > date_trunc('day', t.fromdate) + n.n * interval '1 day';

Here is a db<>fiddle using Postgres that illustrates the main ideas behind this.


问:
Border around a range of cells in a sorted WPF ListBox
I have a horizontal ListBox of items, each of which has two properties: Name, and Parent. Several items have the same Parent, and some items have no parent.

I would like to present the list with items ordered by Parent if they have one, otherwise by Name. That will leave us with a list similar to the following (Parent represented as letter, Name as digit):

```<code> 1   A1   A2   C1   C2   C3   2   3
</code>```

Now I would like to put a border around each group of ListItems belonging to each parent, like so:

```<code>    /-A-----\  /-C----------\
1   |A1   A2|  |C1   C2   C3|  2   3
    \-------/  \------------/
</code>```

How can I accomplish this?

答: In theory you might be able to use a CollectionView to group the items and then specify a GroupStyle to draw borders around groups, if the documentation does not provide enough information for you to work with i might be able to help out, but not now.

Body:
I have a horizontal ListBox of items, each of which has two properties: Name, and Parent. Several items have the same Parent, and some items have no parent.

I would like to present the list with items ordered by Parent if they have one, otherwise by Name. That will leave us with a list similar to the following (Parent represented as letter, Name as digit):

 1   A1   A2   C1   C2   C3   2   3

Now I would like to put a border around each group of ListItems belonging to each parent, like so:

    /-A-----\  /-C----------\
1   |A1   A2|  |C1   C2   C3|  2   3
    \-------/  \------------/

How can I accomplish this?


问:
header redirect not working on server but working on localhost
I'm using bluehost as my webhost, I'm having a few problems. The code below is my point of confusion.

```<code><?php
include '../init.php';
error_reporting(0);
?>
<div class='container'>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/bootstrap/css/responsive.css">
<link rel="stylesheet" type="text/css" href="/bootstrap/css/responsive.min.css">
<script language="JavaScript" type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="SignIn.css">
<title>SoundBooth - Sign in</title>
<link rel="icon" href="../Images/Logo.png" type="image/x-icon"/>
</head>
<body  background="../Images/BGMain.png">
<div class='signinLabel'>Sign in</div>
<div class='bg'></div>
<div class='user'>Username</div>
<div class='pass'>Password</div>
<form action="index.php" method='POST'>
  <input name='Username' autocomplete="off"class='usr' type="text" style='height:34px;'/>
  <input name='Password' autocomplete="off"class='pas'type="password" style='height:34px;'/>

  <input type='submit' class='submit' value='Log in' ></input>
</form>
<a class='forgotPass' href="#">(Forgot password)</a>
<div class='no-account-label'>Don't have an account? |</div>
<a class='no-account-button' href="/signup">Sign up</a>
<?php
 if (empty($_POST) === false){
    $username = $_POST['Username'];
    $password = $_POST['Password'];

    if (empty($username) || empty($password)){ ?>
            <div style="float:left;margin:-415px 200px;width:500px;text-indent:100px;"class="alert alert-error">You need to enter a username and password!</div>
            <?php
        }elseif (user_exists($username) === false){?>
            <div style="float:left;margin:-415px 170px;width:500px;text-indent:100px;"class="alert alert-error">We can't find that username! Have you <a style='color: rgb(185, 74, 72);' href='../HTML/signup.html'>registered?</a></div>
            <?php
        }elseif (user_active($username) === false){ ?>
            <div style="float:left;margin:-415px 200px;width:500px;text-indent:100px;"class="alert alert-error">You haven't activated your account!</div> <!--Remove this-->
            <?php
        }else{

            $login = login($username, $password);
            if ($login === false){ ?>
            <div style="float:left;margin:-415px 200px;width:500px;text-indent:100px;"class="alert alert-error">The username or password you have entered is incorrect!</div>
            <?php
            }else{
                $errors[] = 'Logging In...';
                $_SESSION['user_id'] = $login;
                if (isset($_SESSION['user_id'])){
                mysql_query("UPDATE `users` SET `online_offline`='1' WHERE `user_id`='$_SESSION[user_id]'");
                }
                header("Location: http://sound-booth.com/");
                exit();
            }
        }
    }
    echo output_errors($errors)
?>
</div>
</body>
</html>
</code>```

is the link to the script. It works in localhost, but not in my actual server. Not even the header() redirect works.

Could somebody please explain this?

Solution:

```<code>ob_start();
</code>```

答:
I think ob_start() function calling is the best idea for this problem. The header function can be call his attribute just after a logical statement. This is passing the value just taking it's previous value.

Refer: https://www.php.net/manual/en/function.ob-start.php

Body:
I'm using bluehost as my webhost, I'm having a few problems. The code below is my point of confusion.

<?php
include '../init.php';
error_reporting(0);
?>

<link rel="stylesheet" type="text/css" href="/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/bootstrap/css/responsive.css">
<link rel="stylesheet" type="text/css" href="/bootstrap/css/responsive.min.css">

<link rel="stylesheet" type="text/css" href="SignIn.css">
<title>SoundBooth - Sign in</title>
<link rel="icon" href="../Images/Logo.png" type="image/x-icon"/>

Sign in

Username

Password

<form action="index.php" method='POST'>
  <input name='Username' autocomplete="off"class='usr' type="text" style='height:34px;'/>
  <input name='Password' autocomplete="off"class='pas'type="password" style='height:34px;'/>

  <input type='submit' class='submit' value='Log in' ></input>
</form>
(Forgot password)

Don't have an account? |

Sign up
<?php
 if (empty($_POST) === false){
    $username = $_POST['Username'];
    $password = $_POST['Password'];

    if (empty($username) || empty($password)){ ?>

You need to enter a username and password!

            <?php
        }elseif (user_exists($username) === false){?>

We can't find that username! Have you registered?

            <?php
        }elseif (user_active($username) === false){ ?>

You haven't activated your account!

            <?php
        }else{

            $login = login($username, $password);
            if ($login === false){ ?>

The username or password you have entered is incorrect!

            <?php
            }else{
                $errors[] = 'Logging In...';
                $_SESSION['user_id'] = $login;
                if (isset($_SESSION['user_id'])){
                mysql_query("UPDATE `users` SET `online_offline`='1' WHERE `user_id`='$_SESSION[user_id]'");
                }
                header("Location: http://sound-booth.com/");
                exit();
            }
        }
    }
    echo output_errors($errors)
?>

is the link to the script. It works in localhost, but not in my actual server. Not even the header() redirect works.

Could somebody please explain this?

Solution:

ob_start();


问:
Modal does not close, when clicked
So I have a menu, where models pop-up on click. In each model, there's a close button, marked by an "x". Only problem is, that the model does not close, when the "x" is clicked.

I have tried multiple ways of filing this seemingly simple problem. But with no luck.

I have tried, using a z-index property, I have tried fiddling with the divs. I have tried to link to bootstrap external links. I have tried different kind of "close" button. I have tried to modifying the javascript code. Still I have not arrived at the desired outcome. Can anyone help ?

Here's my code

window.onload = function () {
  list = document.querySelectorAll(".Project");
  for (let i = 0; i < list.length; i++) {
    list[i].addEventListener("click", function (e) {
        e.preventDefault();
        let currentElement = e.target.parentNode;
        let modalId = currentElement.dataset.modal;
        let modal = document.getElementById(modalId);
        modal.style.display = "block";
    });
  }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}</code>```

     Wer Baut Der Stadt
     2019

        Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.

        ×

 Some text in the Modal..1

```

答:
It is very easy to use modal in Bootstrap.
You just have to make sure that, as in the example below, jquery.js, popper.js and bootstrap.js are placed in order.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

Modal title

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

          ...

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>

```

Title: Modal does not close, when clicked

Body:
So I have a menu, where models pop-up on click. In each model, there's a close button, marked by an "x". Only problem is, that the model does not close, when the "x" is clicked.

I have tried multiple ways of filing this seemingly simple problem. But with no luck.

I have tried, using a z-index property, I have tried fiddling with the divs. I have tried to link to bootstrap external links. I have tried different kind of "close" button. I have tried to modifying the javascript code. Still I have not arrived at the desired outcome. Can anyone help ?

Here's my code

window.onload = function () {
  list = document.querySelectorAll(".Project");
  for (let i = 0; i < list.length; i++) {
    list[i].addEventListener("click", function (e) {
        e.preventDefault();
        let currentElement = e.target.parentNode;
        let modalId = currentElement.dataset.modal;
        let modal = document.getElementById(modalId);
        modal.style.display = "block";
    });
  }
};

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

     Wer Baut Der Stadt
     2019

        Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.

        ×

 Some text in the Modal..1

Body:
It is very easy to use modal in Bootstrap.
You just have to make sure that, as in the example below, jquery.js, popper.js and bootstrap.js are placed in order.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>