问:
How can I run a function at specific time & date (React)?
I need to remove React elements (a button) and change text at a certain time and day and I was wondering if there is a way to do it dynamically so that way i don't have to set an alarm and change it manually. </p>

答:
There are probably multiple ways to do this but i would do this:

Check current time in componentDidMount

Set component hidden or visible by using this.setState

Use setTimeout to setup a function to change visibility of the button when needed again.


来源: stackexchange

问:
What is wrong with my Scheme using vector-set implementation?
I was wondering what I am doing wrong here with vector-set

```<code>(define foo0
  (lambda (vec)
    (let* ((newvec (vector vec))
           (l      (vector-length vec))
           (norm   (norm0 vec)))
      (do ((i 0(+ i 1)))
        ((= i l))
        (vector-set*! newvec  i (/(vector-ref vec i) norm))) newvec)))
</code>```

I am trying to set each element of the vector to be divided by norm (an integer from another predicate).

The error I keep getting is

```<code>  vector-set!: index is out of range
  index: 1
  valid range: [0, 0]
  vector: '#(3/4)
</code>```

So I am finding the first solution, however, the newvec gets reset to size 1, so the index goes out of range.

答:
vector makes a mutable vector with the elements given as arguments, thus:

```<code>(vector 4)      ; a vector of one element
(vector 1 2 3)  ; a vector of 3 elements
</code>```

SO lets say you need a 20 element vector that you are going to mutate and work with. Using vector is out of the question since then you would have to have 20 dummy arguments. Instead you use make-vector It takes two arguments, the size and an optional initial value for all the elements:

```<code>(make-vector 20 0)
; ==> #(0 0 ... 0), a vector of 20 elements, all 0
</code>```

Now with the knowledge that you can get the length of the passed vector with vector-length you can pass that to make-vector to make a same size vector that you can copy values to to make a shallow copy. However you can do it much easier by using vector-copy

ContentLicense: CC BY-SA 3.0

Body:
I was wondering what I am doing wrong here with vector-set

(define foo0
  (lambda (vec)
    (let* ((newvec (vector vec))
           (l      (vector-length vec))
           (norm   (norm0 vec)))
      (do ((i 0(+ i 1)))
        ((= i l))
        (vector-set*! newvec  i (/(vector-ref vec i) norm))) newvec)))

I am trying to set each element of the vector to be divided by norm (an integer from another predicate).

The error I keep getting is

  vector-set!: index is out of range
  index: 1
  valid range: [0, 0]
  vector: '#(3/4)

So I am finding the first solution, however, the newvec gets reset to size 1, so the index goes out of range.

Body:
vector makes a mutable vector with the elements given as arguments, thus:

(vector 4)      ; a vector of one element
(vector 1 2 3)  ; a vector of 3 elements

SO lets say you need a 20 element vector that you are going to mutate and work with. Using vector is out of the question since then you would have to have 20 dummy arguments. Instead you use make-vector It takes two arguments, the size and an optional initial value for all the elements:

(make-vector 20 0)
; ==> #(0 0 ... 0), a vector of 20 elements, all 0

Now with the knowledge that you can get the length of the passed vector with vector-length you can pass that to make-vector to make a same size vector that you can copy values to to make a shallow copy. However you can do it much easier by using vector-copy


问:
How do I skip a txt file when iterating over a directory?
Alright, so I'm trying to write a simple shell script to check for updates or just update all packages, including homebrew itself. I am trying to echo the executable filenames into a txt file, and source the txt file at the end. The problem is that in my script, no matter what I do, it always includes the name of the text file in the text file it creates. How do I either skip over the text file, or remove the entire line containing pkg.txt? Keep in mind that it won't be as simple as just removing the last line, because the packages are listed alphabetically and if I ever install any package starting with a letter that's greater than p, it will delete that line instead.

Here's my code so far.

```<code>for FILE in $HOME/.brew/bin/* ; do
  TRIM=$(basename $FILE)
  if [ "$FILE" != "*.txt" ] ; then
    echo "brew upgrade \c" >>  pkg.txt ; echo $TRIM >> pkg.txt
  fi
done
</code>```

Not sure if it matters, but I'm currently running zsh in iTerm2.

答:
Use case to match a pattern.

```<code>for FILE in "$HOME"/.brew/bin/* ; do
  TRIM=$(basename "$FILE")
  case "$FILE" in
    *.txt) ;;
    *) echo "brew upgrade '$TRIM'" >> pkg.txt ;;
  esac
done
</code>```

Body:
Alright, so I'm trying to write a simple shell script to check for updates or just update all packages, including homebrew itself. I am trying to echo the executable filenames into a txt file, and source the txt file at the end. The problem is that in my script, no matter what I do, it always includes the name of the text file in the text file it creates. How do I either skip over the text file, or remove the entire line containing pkg.txt? Keep in mind that it won't be as simple as just removing the last line, because the packages are listed alphabetically and if I ever install any package starting with a letter that's greater than p, it will delete that line instead.

Here's my code so far.

for FILE in $HOME/.brew/bin/* ; do
  TRIM=$(basename $FILE)
  if [ "$FILE" != "*.txt" ] ; then
    echo "brew upgrade \c" >>  pkg.txt ; echo $TRIM >> pkg.txt
  fi
done

Not sure if it matters, but I'm currently running zsh in iTerm2.

Body:
Use case to match a pattern.

for FILE in "$HOME"/.brew/bin/* ; do
  TRIM=$(basename "$FILE")
  case "$FILE" in
    *.txt) ;;
    *) echo "brew upgrade '$TRIM'" >> pkg.txt ;;
  esac
done


问:
Filter/query list of users that not being blocked
I have a list off users in the app, I show that users list in an tableview, now I want to query that list of users to show only the users that have not being blocked by me as an user... So my database structure I'm thinking of is something like this;

users

usersid-987545

name: String

description: String

blocked

userid-767438: true

usersid-767438

name: String

description: String

But this is a problem when I want to query list of users or later to search for a user with name and exclude a blocked user by that user... Whats a more scalable structure? Can you query a list of users and filter out the blocked users by that user?

答:
try to nest your data

DATABASE / Users / USERIDS / personal data

DATABASE / BLOCKS / USERID / blocked users

DATABASE / FRIENDS / USERID / listed friends

then
get the list of peeople blocked under the uid you are looking for (yours for example)
then
get all the friends
get all the blocked users
compare and exclude

Another solution would be to remove the blocked user from the friends list or to make a separate DATABASE / AUTHORIZED / USERID/ list of authorized people

Structuring data is really important and makes firebase so powerfull.


问:
C++ text animation Error C2397
I writted this code from a youtube video (from Husam Haj):
https://www.youtube.com/watch?v=C2k-xiLmNSQ

This code is supposed to Animate Text (See the video) using C++, but the thing is that this code doesn't work since I got the following message from visual studio 2017:

"error C2397: conversion from 'int' to 'SHORT' requires a narrowing conversion"

I was researching in the internet and I found that someone already asked for help with this same code, but not solution:
http://www.dreamincode.net/forums/topic/358635-i-need-some-help/

I would appreciate any help

Below is the code:

```<code>#include "stdafx.h"
#include <string>
#include <string.h>
#include <windows.h>
#include <iostream>

using namespace std;

void Display(string[], const int);

int main()
{
const int arr_size = 12;
string myInfo[arr_size] = { " Animated text example",
  "     Brooklyn College",
  "  Pre-Engineering Program",
 };

 Display(myInfo, arr_size);

 return 0;
}

void Display(string arr_string[], int arr_size)
{
 HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);

COORD pos[18] = { { 0,6 },{ 0,7 },{ 0,9 },{ 0,11 },{ 0,13 },{ 0,15 },
 { 0,17 },{ 0,19 },{ 0,21 },{ 0,23 },{ 0,25 },{ 0,27 },
 { 0,29 },{ 0,31 },{ 0,33 },{ 0,35 },{ 0,37 },{ 0,39 } };

 for (int k = 0; k<arr_size; k++)
{
  for (int j = arr_string[k].size(); j >= 0; j--)
{
   for (int i = 0; i <= j; i = i++)
{
    SetConsoleCursorPosition(screen, pos[k]);
    cout << " " << endl;
    pos[k].X++;

    SetConsoleCursorPosition(screen, pos[k]);
    cout << arr_string[k][j] << endl;
    Sleep(1);
}
pos[k] = {0,k+1}; //HERE THE MISTAKE!
}
}
}
</code>```

答:
pos is an array of COORD. When I press F12 (go to definition), it shows me:

```<code>typedef struct _COORD {
    SHORT X;
    SHORT Y;
} COORD, *PCOORD;
</code>```

SHORT is just a typedef for short.

You assign k + 1 which is of type int to COORD::y which is of type short. A variable of type short is shorter (having a smaller range of possible values) than int so the compiler rightfully complains.

To fix the error, either declare short k or use static_cast which does the "narrowing conversion" the compiler likes to have:

```<code>pos[k] = {0, static_cast<SHORT>(k+1)};
</code>```

This only works correctly because console screen coordinates are in a sufficiently small range to fit into a short.

Title: C++ text animation Error C2397

Body:
I writted this code from a youtube video (from Husam Haj):
https://www.youtube.com/watch?v=C2k-xiLmNSQ

This code is supposed to Animate Text (See the video) using C++, but the thing is that this code doesn't work since I got the following message from visual studio 2017:

"error C2397: conversion from 'int' to 'SHORT' requires a narrowing conversion"

I was researching in the internet and I found that someone already asked for help with this same code, but not solution:
http://www.dreamincode.net/forums/topic/358635-i-need-some-help/

I would appreciate any help

Below is the code:

#include "stdafx.h"
#include <string>
#include <string.h>
#include <windows.h>
#include <iostream>

using namespace std;

void Display(string[], const int);

int main()
{
const int arr_size = 12;
string myInfo[arr_size] = { " Animated text example",
  "     Brooklyn College",
  "  Pre-Engineering Program",
 };

 Display(myInfo, arr_size);

 return 0;
}

void Display(string arr_string[], int arr_size)
{
 HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);

COORD pos[18] = { { 0,6 },{ 0,7 },{ 0,9 },{ 0,11 },{ 0,13 },{ 0,15 },
 { 0,17 },{ 0,19 },{ 0,21 },{ 0,23 },{ 0,25 },{ 0,27 },
 { 0,29 },{ 0,31 },{ 0,33 },{ 0,35 },{ 0,37 },{ 0,39 } };

 for (int k = 0; k<arr_size; k++)
{
  for (int j = arr_string[k].size(); j >= 0; j--)
{
   for (int i = 0; i <= j; i = i++)
{
    SetConsoleCursorPosition(screen, pos[k]);
    cout << " " << endl;
    pos[k].X++;

    SetConsoleCursorPosition(screen, pos[k]);
    cout << arr_string[k][j] << endl;
    Sleep(1);
}
pos[k] = {0,k+1}; //HERE THE MISTAKE!
}
}
}

Body:
pos is an array of COORD. When I press F12 (go to definition), it shows me:

typedef struct _COORD {
    SHORT X;
    SHORT Y;
} COORD, *PCOORD;

SHORT is just a typedef for short.

You assign k + 1 which is of type int to COORD::y which is of type short. A variable of type short is shorter (having a smaller range of possible values) than int so the compiler rightfully complains.

To fix the error, either declare short k or use static_cast which does the "narrowing conversion" the compiler likes to have:

pos[k] = {0, static_cast<SHORT>(k+1)};

This only works correctly because console screen coordinates are in a sufficiently small range to fit into a short.


问:
Multiple TYPO3s behind nginx issue
I want to host several TYPO3s behind an nginx reverse proxy using the following structure:

Internal server (apache):

```<code>http://some.internal.ip/site1
http://some.internal.ip/site2
http://some.internal.ip/site3
</code>```

External server (nginx, reverse proxy):

```<code>http://site1.mydomain.com
http://site2.mydomain.com
http://site3.mydomain.com
</code>```

So here're the relevant parts of my nginx.conf

```<code>http {
    ...
    server {
        listen 80;
        server_name site1.mydomain.com;
        location / {
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded_For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded_Proto $scheme;
            proxy_pass              http://some.internal.ip/site1$request_uri;
        }
    }
    ...
    server {
        (like above with site2 and so on)
        ...
    }
</code>```

(I quickly rewrote the configuration from https to http in order not to make things more complicated then necessary.)

Now, the nginx-Part of this seems to work - it's the Typo3 that seems to cause the trouble as all elements on the site are referred to as

```<code>http://some.internal.ip/site1/example.php
</code>```

instead of

```<code>http://site1.mydomain.com/example.php
</code>```

I'm aware of

```<code>[SYS][reverseProxyIP]
</code>```

and

```<code>[SYS][reverseProxyHeaderMultiValue]
</code>```

which I set accordingly, but that doesn't seem to work - which in turn is what should be expected based on my understanding.

Is there another way to approach this issue or am I simply trying something that simply can't be done this way?

答:
Are you using config.baseUrl = http://some.internal.ip/site1/ on your website?

If you are, I recommend you to use config.absRefPrefix = / instead.

See also Søren Mallings article from 2013 which is still correct.

Title: Multiple TYPO3s behind nginx issue

Body:
I want to host several TYPO3s behind an nginx reverse proxy using the following structure:

Internal server (apache):

http://some.internal.ip/site1
http://some.internal.ip/site2
http://some.internal.ip/site3

External server (nginx, reverse proxy):

http://site1.mydomain.com
http://site2.mydomain.com
http://site3.mydomain.com

So here're the relevant parts of my nginx.conf

http {
    ...
    server {
        listen 80;
        server_name site1.mydomain.com;
        location / {
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded_For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded_Proto $scheme;
            proxy_pass              http://some.internal.ip/site1$request_uri;
        }
    }
    ...
    server {
        (like above with site2 and so on)
        ...
    }

(I quickly rewrote the configuration from https to http in order not to make things more complicated then necessary.)

Now, the nginx-Part of this seems to work - it's the Typo3 that seems to cause the trouble as all elements on the site are referred to as

http://some.internal.ip/site1/example.php

instead of

http://site1.mydomain.com/example.php

I'm aware of

[SYS][reverseProxyIP]

and

[SYS][reverseProxyHeaderMultiValue]

which I set accordingly, but that doesn't seem to work - which in turn is what should be expected based on my understanding.

Is there another way to approach this issue or am I simply trying something that simply can't be done this way?


问:
Tkinter - Images is not display
I am  new on Tkinter. I was trying to display two images on my canvas but I couldn't. I tried to achieve this by creating two different files. One will contain all logic behind and the other one will handle the gui. Here is my code so far:

file1.py

```<code>from file2 import *

import tkinter as tk

import random

# global variables
w = 'initial'

class start_gui(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self,parent, *args, **kwargs)
        # create canvas
        self.canvas = tk.Canvas(parent, width=800, height=800, background="green")
        self.canvas.pack()

        c = Display(self.canvas)
        c.current_play(w)

    if __name__ == "__main__":
      # create main window
      root = tk.Tk()
      root.geometry("800x800")
      start_gui(root)
      root.mainloop()
</code>```

file2.py

```<code>import tkinter as tk
from functools import partial
from PIL import ImageTk
from PIL import Image

class Display:

    def __init__(self, canv):
        self.canvas = canv

    def current_play(self, option):
        if (option == 'initial'):
            self.initial_display()
        elif (option == 'n' or option == 's'):
            self.ns_display()

    def initial_display(self):
        # display cat image
        self.im = Image.open("cat.gif")
        self.photo_image = ImageTk.PhotoImage(self.im)
        self.demo = self.canvas.create_image(400, 400, image=self.photo_image, anchor='center')

        self.canvas.create_rectangle(50, 25, 150, 75, fill="blue")

        self.temp_image = tk.PhotoImage(file="cat.gif")
        self.demo2 = self. canvas.create_image(600, 600, image =  self.temp_image, anchor='center')
</code>```

The problem here is that the two image items I created do not show up on the canvas but only the rectangle. Can someone help me with this?

PS: I am using python v 3.4

答:
Another solution: We can make Display inherit from class tk.Canvas

```<code>import tkinter as tk
from PIL import ImageTk
from PIL import Image

import random

# global variables
w = 'initial'

class Display(tk.Canvas):
    def __init__(self,  parent, *args, **kwargs):
        tk.Canvas.__init__(self, parent, *args, **kwargs)

    def current_play(self, option):
        if option == 'initial':
            self.initial_display()
        elif option == 'n' or option == 's':
            self.ns_display()

    def initial_display(self):
        # display cat image
        self.im = Image.open("cat.gif")
        self.photo_image = ImageTk.PhotoImage(self.im)
        self.demo = self.create_image(400, 400, image=self.photo_image, anchor='center')
        self.create_rectangle(50, 25, 150, 75, fill="blue")

        self.temp_image = tk.PhotoImage(file="cat.gif")
        self.demo2 = self.create_image(600, 600, image = self.temp_image, anchor='center')

class start_gui(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self,parent, *args, **kwargs)
        # create canvas
        self.canvas = Display(parent, width=800, height=800, background="green")
        self.canvas.pack()
        self.canvas.current_play(w)

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("800x800")
    start_gui(root)
    root.mainloop()
</code>```

Title: Tkinter - Images is not display

Body:
I am  new on Tkinter. I was trying to display two images on my canvas but I couldn't. I tried to achieve this by creating two different files. One will contain all logic behind and the other one will handle the gui. Here is my code so far:

file1.py

from file2 import *

import tkinter as tk

import random

# global variables
w = 'initial'

class start_gui(tk.Frame):

    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self,parent, *args, **kwargs)
        # create canvas
        self.canvas = tk.Canvas(parent, width=800, height=800, background="green")
        self.canvas.pack()

        c = Display(self.canvas)
        c.current_play(w)

    if __name__ == "__main__":
      # create main window
      root = tk.Tk()
      root.geometry("800x800")
      start_gui(root)
      root.mainloop()

file2.py

import tkinter as tk
from functools import partial
from PIL import ImageTk
from PIL import Image

class Display:

    def __init__(self, canv):
        self.canvas = canv

    def current_play(self, option):
        if (option == 'initial'):
            self.initial_display()
        elif (option == 'n' or option == 's'):
            self.ns_display()

    def initial_display(self):
        # display cat image
        self.im = Image.open("cat.gif")
        self.photo_image = ImageTk.PhotoImage(self.im)
        self.demo = self.canvas.create_image(400, 400, image=self.photo_image, anchor='center')

        self.canvas.create_rectangle(50, 25, 150, 75, fill="blue")

        self.temp_image = tk.PhotoImage(file="cat.gif")
        self.demo2 = self. canvas.create_image(600, 600, image =  self.temp_image, anchor='center')

The problem here is that the two image items I created do not show up on the canvas but only the rectangle. Can someone help me with this?

PS: I am using python v 3.4

Body:
Another solution: We can make Display inherit from class tk.Canvas

import tkinter as tk
from PIL import ImageTk
from PIL import Image

import random

# global variables
w = 'initial'

class Display(tk.Canvas):
    def __init__(self,  parent, *args, **kwargs):
        tk.Canvas.__init__(self, parent, *args, **kwargs)

    def current_play(self, option):
        if option == 'initial':
            self.initial_display()
        elif option == 'n' or option == 's':
            self.ns_display()

    def initial_display(self):
        # display cat image
        self.im = Image.open("cat.gif")
        self.photo_image = ImageTk.PhotoImage(self.im)
        self.demo = self.create_image(400, 400, image=self.photo_image, anchor='center')
        self.create_rectangle(50, 25, 150, 75, fill="blue")

        self.temp_image = tk.PhotoImage(file="cat.gif")
        self.demo2 = self.create_image(600, 600, image = self.temp_image, anchor='center')

class start_gui(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self,parent, *args, **kwargs)
        # create canvas
        self.canvas = Display(parent, width=800, height=800, background="green")
        self.canvas.pack()
        self.canvas.current_play(w)

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("800x800")
    start_gui(root)
    root.mainloop()


问:
Make VBA DateDif behave and round down like Excel DATEDIFF
```<code>DateDiff("m", "06/14/1982", "09,01,1982") = 3

A1 = 06/14/1982
A2 = 09/01/1982
=DATEDIF(A1, A2, "m") = 2
</code>```

If I need DateDiff to round down like DATEDIF does, how do I accomplish this?

答:
```<code>  = Application.WorksheetFunction.RoundDown(DateDiff("d", a1, a2) / 30, 0)
</code>```

Body:
DateDiff("m", "06/14/1982", "09,01,1982") = 3

A1 = 06/14/1982
A2 = 09/01/1982
=DATEDIF(A1, A2, "m") = 2

If I need DateDiff to round down like DATEDIF does, how do I accomplish this?


问:
Stack overflow in recursive method
I'm writing a program that allows a user to input a set of integers into an array and characteristics of those numbers will be displayed once a zero is entered. I am having an issue with one method:findMaxOfLessThanFirst. Which, of course, finds the maximum number in the array that is also less than the first number entered. Here is the full code:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];

        InputStreamReader inRead = new InputStreamReader(System.in);
        BufferedReader buffRead = new BufferedReader(inRead);
        String line = buffRead.readLine();

        try {
            while (!line.equals("0") && index < 100) {
                numbers[index] = Integer.parseInt(line);
                index++;
                line = buffRead.readLine();
            }
        } catch (IOException exception) {
            System.out.println("Array index out of bound");
        }
        int min = findMin(numbers, 0);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        int maxLessThanFirst = findMaxOfLessThanFirst(numbers, 1, numbers.length - 1, numbers[0]);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println(
                "The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
    }

    public static int findMin(int[] numbers, int index) {
        if (index == numbers.length - 1) {
            return numbers[index];
        } else {
            return Math.min(numbers[index], findMin(numbers, index + 1));
        }
    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else
                return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return +2;
            } else {
                return 1;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

    private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
        if (startIndex == endIndex) {
            if (numbers[endIndex] <= firstNumber)
                return numbers[startIndex];
        }
        int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
        if (max >= numbers[endIndex] && max <= firstNumber) {
            return max;
        }
        return numbers[endIndex];
    }
}
</code>```

I am sure I'm missing something really elementary here. I just started learning the concept of recursion. So, please be gentle.

答:
You’re running into an infinite recursion (this is usually the case when one gets StackOverflowError in a recursive program). You tried this code to stop the recursion:

```<code>    if (startIndex == endIndex) {
        if (numbers[endIndex] <= firstNumber)
            return numbers[startIndex];
    }
</code>```

However, when startIndex == endIndex (your only chance), if numbers[endIndex] > firstNumber, this doesn’t stop the recursion, so it goes on — not infinitely, “only” until you hit a StackOverflowError.

Title: Stack overflow in recursive method

Body:
I'm writing a program that allows a user to input a set of integers into an array and characteristics of those numbers will be displayed once a zero is entered. I am having an issue with one method:findMaxOfLessThanFirst. Which, of course, finds the maximum number in the array that is also less than the first number entered. Here is the full code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Assignment9 {
    public static void main(String[] args) throws IOException {
        int index = 0;
        int[] numbers;
        numbers = new int[100];

        InputStreamReader inRead = new InputStreamReader(System.in);
        BufferedReader buffRead = new BufferedReader(inRead);
        String line = buffRead.readLine();

        try {
            while (!line.equals("0") && index < 100) {
                numbers[index] = Integer.parseInt(line);
                index++;
                line = buffRead.readLine();
            }
        } catch (IOException exception) {
            System.out.println("Array index out of bound");
        }
        int min = findMin(numbers, 0);
        int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
        int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
        int maxLessThanFirst = findMaxOfLessThanFirst(numbers, 1, numbers.length - 1, numbers[0]);
        System.out.println("The minimum number is " + min);
        System.out.println("The sum of numbers at even indexes is " + sumAtEven);
        System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
        System.out.println(
                "The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
    }

    public static int findMin(int[] numbers, int index) {
        if (index == numbers.length - 1) {
            return numbers[index];
        } else {
            return Math.min(numbers[index], findMin(numbers, index + 1));
        }
    }

    public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (startIndex % 2 == 0) {
                return numbers[startIndex];
            } else
                return 0;
        } else {
            if (endIndex % 2 == 0) {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
            } else {
                return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
            }
        }
    }

    public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
        if (startIndex == endIndex) {
            if (numbers[startIndex] % 3 == 0) {
                return +2;
            } else {
                return 1;
            }
        } else {
            if (numbers[endIndex] == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
            if (numbers[endIndex] % 3 == 0) {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
            } else {
                return countDivisibleBy3(numbers, startIndex, endIndex - 1);
            }
        }
    }

    private static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {
        if (startIndex == endIndex) {
            if (numbers[endIndex] <= firstNumber)
                return numbers[startIndex];
        }
        int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);
        if (max >= numbers[endIndex] && max <= firstNumber) {
            return max;
        }
        return numbers[endIndex];
    }
}

I am sure I'm missing something really elementary here. I just started learning the concept of recursion. So, please be gentle.

Body:
You’re running into an infinite recursion (this is usually the case when one gets StackOverflowError in a recursive program). You tried this code to stop the recursion:

    if (startIndex == endIndex) {
        if (numbers[endIndex] <= firstNumber)
            return numbers[startIndex];
    }

However, when startIndex == endIndex (your only chance), if numbers[endIndex] > firstNumber, this doesn’t stop the recursion, so it goes on — not infinitely, “only” until you hit a StackOverflowError.


问:
JSP compilation fails when using dynamic classpath generated by IntelliJ IDEA on Windows
I have a Spring/MVC/Tomcat website project that I am attempting to run with IntelliJ IDEA. Because I am running on Windows, there is a command-line size limit, which is exceeded by the large classpath. I use IntelliJ's dynamic classpath feature which puts the classpath in a jar file to shorten the command line. Java runs with -classpath <classpath.jar>.

When I try to view a page, the JSP compilation fails with an error to this effect:

```<code>org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: [-1] in the generated java file: [<removed>.java]
    [javac] <removed>.java:11: error: package javax.servlet does not exist
    [javac] import javax.servlet.*;
    [javac] ^
</code>```

I ran it in debug and stepped into where the java compilation was being done and found the javac command line used. It was put together in org.apache.tools.ant.taskdefs.compilers.JavacExternal. I ran the javac command myself, with -verbose, and noticed that the dependency path from the search path for class files: log line shows up like:

```<code>C:\Users\<removed>\AppData\Local\Temp\file:\C:\Users\<removed>\lib\servlet-api-3.0.jar
</code>```

Note that it seems like the absolute URI path is being treated as a relative path, resulting in an invalid path. I believe this is why it's not compiling properly.

Intellij's generated pathing jar's MANIFEST.MF lists the classpath with entries that are absolute paths that look like:

```<code>file:/C:/Program%20Files/Java/jdk1.8.0_121/jre/lib/charsets.jar file:/C:/Program%20Files/Java/jdk1.8.0_121/jre/lib/deploy.jar [...]
</code>```

This problem doesn't happen on Mac, using dynamic classpath jar (even though it's not necessary because the command line too long error does not happen) so I believe something about the Windows path or the way that IntelliJ generates the classpath jar on Windows is messing up the JSP compilation.

Also, using an Ant build task that generates a pathing jar with relative paths works too, but I am interested in avoiding the use of Ant here.

How can I get this working, or what else do I need to investigate to get to the root cause?

答:
This is a known bug in JDK.

Javac incorrectly handles absolute paths in manifest classpath headers. It has been fixed in JDK9.

Body:
I have a Spring/MVC/Tomcat website project that I am attempting to run with IntelliJ IDEA. Because I am running on Windows, there is a command-line size limit, which is exceeded by the large classpath. I use IntelliJ's dynamic classpath feature which puts the classpath in a jar file to shorten the command line. Java runs with -classpath <classpath.jar>.

When I try to view a page, the JSP compilation fails with an error to this effect:

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: [-1] in the generated java file: [<removed>.java]
    [javac] <removed>.java:11: error: package javax.servlet does not exist
    [javac] import javax.servlet.*;
    [javac] ^

I ran it in debug and stepped into where the java compilation was being done and found the javac command line used. It was put together in org.apache.tools.ant.taskdefs.compilers.JavacExternal. I ran the javac command myself, with -verbose, and noticed that the dependency path from the search path for class files: log line shows up like:

C:\Users\<removed>\AppData\Local\Temp\file:\C:\Users\<removed>\lib\servlet-api-3.0.jar

Note that it seems like the absolute URI path is being treated as a relative path, resulting in an invalid path. I believe this is why it's not compiling properly.

Intellij's generated pathing jar's MANIFEST.MF lists the classpath with entries that are absolute paths that look like:

file:/C:/Program%20Files/Java/jdk1.8.0_121/jre/lib/charsets.jar file:/C:/Program%20Files/Java/jdk1.8.0_121/jre/lib/deploy.jar [...]

This problem doesn't happen on Mac, using dynamic classpath jar (even though it's not necessary because the command line too long error does not happen) so I believe something about the Windows path or the way that IntelliJ generates the classpath jar on Windows is messing up the JSP compilation.

Also, using an Ant build task that generates a pathing jar with relative paths works too, but I am interested in avoiding the use of Ant here.

How can I get this working, or what else do I need to investigate to get to the root cause?


问:
IDataService is already registered in MVVM Light Project
I'm trying to adjust my WP8 project from self made MVVM implementation to MVVM Light. I've successfully worked through this example and it worked perfectly. I've then started to repeat the same steps for my own project.

The application compiles without errors, but when I open my MainPage.xaml in Expression Blend, I will get this error:

Class project.Services.IDataService is already registered. App.xaml,
  Line 6, Column 5

If I look it up, it's the line where the ViewModelLocator is registered:

```<code><Application.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</Application.Resources>
</code>```

My ViewModelLocator.cs:

```<code>        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (ViewModelBase.IsInDesignModeStatic)
            {
                // Create design time view services and models
                // see: http://developingux.com/2012/06/10/how-to-fix-error-design-time-data-in-blend-with-mvvm-light/
                if (!SimpleIoc.Default.IsRegistered<IDataService>())
                {
                    SimpleIoc.Default.Register<IDataService, DesignDataService>();
                }
            }
            else
            {
                // Create run time view services and models
                if (!SimpleIoc.Default.IsRegistered<IDataService>())
                {
                    SimpleIoc.Default.Register<IDataService, DataService>();
                }
            }

            // only one ViewModel for the MainPage
            SimpleIoc.Default.Register<MainViewModel>();
        }
</code>```

As you can see from my code comment, I've already tried the fix supposed here, but I'm still getting this error in Blend. There is no other place left where I could register the IDataService, so what could be the problem? Other questions here on SO are especially for desktop applications and does also only contain some kind of the above fix where there's first a check before the ViewModelLocator is registered.

Any ideas? :)

Update 1:
I've managed to display my design time in Visual Studio. I was still manually referencing the DataContext in my Code Behind File. However, I still need to solve the problem that I cannot display the design time data in Blend. Judging from Visual Studios behavior it should work though?!

答:
Old question, but still relevant, and I don't think the cause has been explained yet, nor a direct answer to it.

When in design time, it seems that Visual Studio likes to instantiate resources multiple times.

This causes a view model locator, which is presumably defined in your App.xaml, or some other resource, to be constructed multiple times, in the same static application instance.

The SimpleIoc.Default exist as a single instance across these 2 view model locator instances, causing any new registrations to be duplicate registrations.

It might seem to work at first after restarting Visual Studio, reloading your project, or killing XDesProc.exe (host process for the XAML designer in Visual Studio), but if you close a window designer, and open it again, you'll get the design time error, because it's trying to re-create the resources linked to that window.

I've tried several solutions, like making a static boolean in the view model locator, that I'd set to true on the first call, and if it's true before that, return, and don't register anything.

But unfortunately, this doesn't seem to help, as the boolean got re-instantiated along with the view model locator.

One could try to put it in a separate class that isn't being re-constructed every time a view is opened, but this seemed slightly silly.

Finally, I decided to use the .Reset() method on SimpleIoc in order to remove all previously registered services, instances and factories.

```<code>public ViewModelLocator()
{
    SimpleIoc.Default.Reset();

    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<IExampleService, ExampleServiceImplementation>();
    // Register the rest of your services
}
</code>```

This seems to solve the issue, and should have no effect in runtime, as the view model locator will only get instantiated once.

Body:
I'm trying to adjust my WP8 project from self made MVVM implementation to MVVM Light. I've successfully worked through this example and it worked perfectly. I've then started to repeat the same steps for my own project.

The application compiles without errors, but when I open my MainPage.xaml in Expression Blend, I will get this error:

Class project.Services.IDataService is already registered. App.xaml,
  Line 6, Column 5

If I look it up, it's the line where the ViewModelLocator is registered:

<Application.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</Application.Resources>

My ViewModelLocator.cs:

        ///
        /// Initializes a new instance of the ViewModelLocator class.
        ///
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (ViewModelBase.IsInDesignModeStatic)
            {
                // Create design time view services and models
                // see: http://developingux.com/2012/06/10/how-to-fix-error-design-time-data-in-blend-with-mvvm-light/
                if (!SimpleIoc.Default.IsRegistered<IDataService>())
                {
                    SimpleIoc.Default.Register<IDataService, DesignDataService>();
                }
            }
            else
            {
                // Create run time view services and models
                if (!SimpleIoc.Default.IsRegistered<IDataService>())
                {
                    SimpleIoc.Default.Register<IDataService, DataService>();
                }
            }

            // only one ViewModel for the MainPage
            SimpleIoc.Default.Register<MainViewModel>();
        }

As you can see from my code comment, I've already tried the fix supposed here, but I'm still getting this error in Blend. There is no other place left where I could register the IDataService, so what could be the problem? Other questions here on SO are especially for desktop applications and does also only contain some kind of the above fix where there's first a check before the ViewModelLocator is registered.

Any ideas? :)

Update 1:
I've managed to display my design time in Visual Studio. I was still manually referencing the DataContext in my Code Behind File. However, I still need to solve the problem that I cannot display the design time data in Blend. Judging from Visual Studios behavior it should work though?!

Body:
Old question, but still relevant, and I don't think the cause has been explained yet, nor a direct answer to it.

When in design time, it seems that Visual Studio likes to instantiate resources multiple times.

This causes a view model locator, which is presumably defined in your App.xaml, or some other resource, to be constructed multiple times, in the same static application instance.

The SimpleIoc.Default exist as a single instance across these 2 view model locator instances, causing any new registrations to be duplicate registrations.

It might seem to work at first after restarting Visual Studio, reloading your project, or killing XDesProc.exe (host process for the XAML designer in Visual Studio), but if you close a window designer, and open it again, you'll get the design time error, because it's trying to re-create the resources linked to that window.

I've tried several solutions, like making a static boolean in the view model locator, that I'd set to true on the first call, and if it's true before that, return, and don't register anything.

But unfortunately, this doesn't seem to help, as the boolean got re-instantiated along with the view model locator.

One could try to put it in a separate class that isn't being re-constructed every time a view is opened, but this seemed slightly silly.

Finally, I decided to use the .Reset() method on SimpleIoc in order to remove all previously registered services, instances and factories.

public ViewModelLocator()
{
    SimpleIoc.Default.Reset();

    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<IExampleService, ExampleServiceImplementation>();
    // Register the rest of your services
}

This seems to solve the issue, and should have no effect in runtime, as the view model locator will only get instantiated once.


问:
Remove Words Less Than 4 Characters from Pandas Series
I am trying to remove all words with less than 4 characters from each scalar value in a Pandas Series. What is the best way to do it? Here is my failed attempt:

```<code>df['text'] = df['text'].str.join(word for word in df['text'].str.split() if len(word)>3)
</code>```

I receive the following error message:

AttributeError: 'generator' object has no attribute 'join'

I based my attempt off of this post regarding the same in a string: Remove small words using Python

Side note: If its better to tokenize my words before removing with less than 4 characters please let me know.

EDIT: Each scalar value contains sentences so I want to remove for any words less than a length of 4 within the value.

答:
Try

df.test.apply(lambda i: ' '.join(filter(lambda j: len(j) > 3, i.split())))

Body:
I am trying to remove all words with less than 4 characters from each scalar value in a Pandas Series. What is the best way to do it? Here is my failed attempt:

df['text'] = df['text'].str.join(word for word in df['text'].str.split() if len(word)>3)

I receive the following error message:

AttributeError: 'generator' object has no attribute 'join'

I based my attempt off of this post regarding the same in a string: Remove small words using Python

Side note: If its better to tokenize my words before removing with less than 4 characters please let me know.

EDIT: Each scalar value contains sentences so I want to remove for any words less than a length of 4 within the value.


问:
Paypal IPN callback not working since migrating website
We have migrated a bespoke php website to a new server on a new IP address. Since then the Paypal IPN system does not callback to the website so orders don't get updated etc. Could someone please give me some ideas of what to check on the webserver. Why would this stop working once the website has been moved to a new IP?</p>

答: Ok it seems to be working now. It must have been related to the domain IP change taking time to propogate through the internet.</p>


问:
2 Java Strings in different encoding?
I have a problem. I thought Java-Strings are always encoded as UTF-16? Now I have a file with the text "TEST", which is encoded in UTF-8 with BOM. When I read from the file with Files.newBufferedReader(test_file) it gives me a String with UTF-8 with BOM encoding.

```<code>try (BufferedReader reader = Files.newBufferedReader( test_file )){
    reader.lines().forEach(
        s -> {
            System.out.println( Arrays.toString( s.getBytes() ) );
            System.out.println( Arrays.toString( "TEST".getBytes()) );
            System.out.println( s.equals("TEST") );
        } );
} catch( Exception e ) {}
</code>```

I don't specify any encoding here. But the strange thing is, the output looks like this:

```<code>[-17, -69, -65, 84, 69, 83, 84]
[84, 69, 83, 84]
false
</code>```

How is this possible? It looks like I have two String with different encoding in Java...

The problem is, I need "s" as a key for a HashMap<String, String>. But the key is "TEST" and s.equals("TEST") returns false and therefore the HashMap returns null, when I try mymap.get(s).

答: The problem is that the BufferedReader is reading your BOM. The sequence -17, -69, -65 is simply the BOM of UTF-8. But the literal "Test" does not contain the BOM and so the strings aren't equal.

Title: 2 Java Strings in different encoding?

Body:
I have a problem. I thought Java-Strings are always encoded as UTF-16? Now I have a file with the text "TEST", which is encoded in UTF-8 with BOM. When I read from the file with Files.newBufferedReader(test_file) it gives me a String with UTF-8 with BOM encoding.

try (BufferedReader reader = Files.newBufferedReader( test_file )){
    reader.lines().forEach(
        s -> {
            System.out.println( Arrays.toString( s.getBytes() ) );
            System.out.println( Arrays.toString( "TEST".getBytes()) );
            System.out.println( s.equals("TEST") );
        } );
} catch( Exception e ) {}

I don't specify any encoding here. But the strange thing is, the output looks like this:

[-17, -69, -65, 84, 69, 83, 84]
[84, 69, 83, 84]
false

How is this possible? It looks like I have two String with different encoding in Java...

The problem is, I need "s" as a key for a HashMap<String, String>. But the key is "TEST" and s.equals("TEST") returns false and therefore the HashMap returns null, when I try mymap.get(s).


问:
Run a lot of similar parse servers on AWS Elastic Beanstalk
I have been running a lot of similar parse server apps on AWS Elastic Beanstock. I do not need a lot of computing power just a way to run a lot of parse servers on AWS without having to pay for a separate server for each one. Would there be a way to run multiple apps on one of the parse servers or would there be a way to put multiple parse servers on one instance somehow in Elastic Beanstock? An example of the kind of server I am running can be found at the Parse GitHub page. Thanks!</p>

答:
The way I do it is by putting each parse-server app into its own docker container and then deploying a bunch of different containers on a single "beanstalk" each running on their own port.

In some cases I use the same code base for multiple apps and in some the code is different. I use https://www.npmjs.com/package/config to manage configuration in all cases, but in cases where the code is the same, I use the env var NODE_APP_INSTANCE to have different config value for different apps.

simple Dockerfile

```<code>FROM node

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 5000

CMD [ "npm", "start" ]
</code>```

and a simple Dockerrun.aws.json

```<code>{
  "AWSEBDockerrunVersion": 2,
  "volumes": [ ],
  "containerDefinitions":
    [
      {
        "name": "app1",
        "image": "xxx.dkr.ecr.us-east-1.amazonaws.com/boo/app1:latest",
        "essential": true,
        "memory": 1536,
        "entryPoint": ["node", "index.js"],
        "portMappings":
          [
            {
              "hostPort": 9091,
              "containerPort": 9091
            }
          ],
        "environment":
        [
          {
            "name": "NODE_ENV",
            "value": "production"
          }
        ]
     },
     {
        "name": "app2",
        "image": "xxx.dkr.ecr.us-east-1.amazonaws.com/boo/app2:latest",
        "essential": true,
        "memory": 512,
        "entryPoint": ["node", "index.js"],
        "portMappings":
          [
            {
              "hostPort": 9092,
              "containerPort": 9092
            }
          ],
        "environment":
        [
          {
            "name": "NODE_ENV",
            "value": "production"
          },
          { "name": "NODE_APP_INSTANCE",
            "value": "app2"
          }
        ]
     },
    ...
}
</code>```

Body:
The way I do it is by putting each parse-server app into its own docker container and then deploying a bunch of different containers on a single "beanstalk" each running on their own port.

In some cases I use the same code base for multiple apps and in some the code is different. I use https://www.npmjs.com/package/config to manage configuration in all cases, but in cases where the code is the same, I use the env var NODE_APP_INSTANCE to have different config value for different apps.

simple Dockerfile

FROM node

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 5000

CMD [ "npm", "start" ]

and a simple Dockerrun.aws.json

{
  "AWSEBDockerrunVersion": 2,
  "volumes": [ ],
  "containerDefinitions":
    [
      {
        "name": "app1",
        "image": "xxx.dkr.ecr.us-east-1.amazonaws.com/boo/app1:latest",
        "essential": true,
        "memory": 1536,
        "entryPoint": ["node", "index.js"],
        "portMappings":
          [
            {
              "hostPort": 9091,
              "containerPort": 9091
            }
          ],
        "environment":
        [
          {
            "name": "NODE_ENV",
            "value": "production"
          }
        ]
     },
     {
        "name": "app2",
        "image": "xxx.dkr.ecr.us-east-1.amazonaws.com/boo/app2:latest",
        "essential": true,
        "memory": 512,
        "entryPoint": ["node", "index.js"],
        "portMappings":
          [
            {
              "hostPort": 9092,
              "containerPort": 9092
            }
          ],
        "environment":
        [
          {
            "name": "NODE_ENV",
            "value": "production"
          },
          { "name": "NODE_APP_INSTANCE",
            "value": "app2"
          }
        ]
     },
    ...
}


答:
Consider @juanpa.arrivillaga's dataframe df

```<code>df = pd.DataFrame({'text':["The quick brown fox", "jumped over the lazy dog"]})
</code>```

Then we can

```<code>t = df.text.str.split(expand=True).stack()
t.loc[t.str.len() >= 4].groupby(level=0).apply(' '.join)

0         quick brown
1    jumped over lazy
dtype: object
</code>```

Title: Remove Words Less Than 4 Characters from Pandas Series

Body:
Consider @juanpa.arrivillaga's dataframe df

df = pd.DataFrame({'text':["The quick brown fox", "jumped over the lazy dog"]})

Then we can

t = df.text.str.split(expand=True).stack()
t.loc[t.str.len() >= 4].groupby(level=0).apply(' '.join)

0         quick brown
1    jumped over lazy
dtype: object


问:
Error while upgrading Asterisk to 14 - PJSIP undeclared
I am trying to upgrade asterisk 11 to 14 on Debian (8.7) and I got the following error when I do make install.

The error is as below

```<code>res_pjsip_transport_management.c: In function ‘monitored_transport_state_callback’:
res_pjsip_transport_management.c:190:8: error: ‘PJSIP_TP_STATE_SHUTDOWN’ undeclared (first use in this function)
   case PJSIP_TP_STATE_SHUTDOWN:
        ^
res_pjsip_transport_management.c:190:8: note: each undeclared identifier is reported only once for each function it appears in
/root/asterisk-14.3.0/Makefile.rules:149: recipe for target 'res_pjsip_transport_management.o' failed
make[1]: *** [res_pjsip_transport_management.o] Error 1
Makefile:401: recipe for target 'res' failed
make: *** [res] Error 2
</code>```

The commands I used are as follow

```<code>tar -zxvf asterisk-14-current.tar.gz
/etc/init.d/asterisk stop
cd asterisk-14.3.0/
./configure
rm -f /usr/lib/asterisk/modules/*
make install
</code>```

I tried some solutions from the internet and it didn't fix....

答:
pjsip version not match.

Never tried 14*(it is not LTS), for 13.* such error mean you have more then one pjsip or pjsip is not 2.4.

Before rebuilding pjsip do check

```<code>yum remove -y pjsip
rm -f `find / -name *pjsip*`
</code>```

Body:
I am trying to upgrade asterisk 11 to 14 on Debian (8.7) and I got the following error when I do make install.

The error is as below

res_pjsip_transport_management.c: In function ‘monitored_transport_state_callback’:
res_pjsip_transport_management.c:190:8: error: ‘PJSIP_TP_STATE_SHUTDOWN’ undeclared (first use in this function)
   case PJSIP_TP_STATE_SHUTDOWN:
        ^
res_pjsip_transport_management.c:190:8: note: each undeclared identifier is reported only once for each function it appears in
/root/asterisk-14.3.0/Makefile.rules:149: recipe for target 'res_pjsip_transport_management.o' failed
make[1]: *** [res_pjsip_transport_management.o] Error 1
Makefile:401: recipe for target 'res' failed
make: *** [res] Error 2

The commands I used are as follow

tar -zxvf asterisk-14-current.tar.gz
/etc/init.d/asterisk stop
cd asterisk-14.3.0/
./configure
rm -f /usr/lib/asterisk/modules/*
make install

I tried some solutions from the internet and it didn't fix....

Body:
pjsip version not match.

Never tried 14*(it is not LTS), for 13.* such error mean you have more then one pjsip or pjsip is not 2.4.

Before rebuilding pjsip do check

yum remove -y pjsip
rm -f `find / -name *pjsip*`


问:
URL regex validation
i made that:

```<code> /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}
</code>```

and checked it with a validator but on my page it is not working:

```<code>var re = /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1};
if (!re.test(url)) {
    alert("url error");
    return false;
}
</code>```

i get this error

```<code>Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Timestamp: Tue, 30 Nov 2010 14:23:10 UTC

Message: Expected ')' in regular expression
Line: 781
Char: 23
Code: 0
URI: http://*************************
</code>```

答:
As said Nick you have to escape \ and . unless you're using another delimitor so your regex will become :

```<code>var re = '~(https?)://)?(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}\.?~';
</code>```

But be aware that your regex will match url like:

```<code>http://....aa.
</code>```

ContentLicense: CC BY-SA 2.5

Title: URL regex validation

Body:
i made that:

 /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}

and checked it with a validator but on my page it is not working:

var re = /^(http[s]?://){0,1}(www.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1};
if (!re.test(url)) {
    alert("url error");
    return false;
}

i get this error

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Timestamp: Tue, 30 Nov 2010 14:23:10 UTC

Message: Expected ')' in regular expression
Line: 781
Char: 23
Code: 0
URI: http://*************************

Body:
As said Nick you have to escape \ and . unless you're using another delimitor so your regex will become :

var re = '~(https?)://)?(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}\.?~';

But be aware that your regex will match url like:

http://....aa.


问:
Create group ID for runs of non-zero values
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

```<code>   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3
</code>```

答:
Using rle(). First create a new vector replacing the zeros with NA.

```<code>x <- match(value != 0, TRUE)
with(rle(!is.na(x)), {
    lv <- lengths[values]
    replace(x, !is.na(x), rep(seq_along(lv), lv))
})
# [1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to find contiguous runs of non-zero elements in a vector (separated by at least one zero), and to assign an ID to each group (subsequent integer).

Toy vector:

value <- c(1, 1, 2, 3, 4, 3,   0, 0, 0,   1, 2, 3, 9, 8,   0, 0,   3, 2)

In this example, there are three runs of non-zero values: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], separated by chunks of one or more zeros.

Each non-zero run should have a unique ID: 1, 2, 3... Runs of zero should have NA as ID:

   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3

Body:
Using rle(). First create a new vector replacing the zeros with NA.

x <- match(value != 0, TRUE)
with(rle(!is.na(x)), {
    lv <- lengths[values]
    replace(x, !is.na(x), rep(seq_along(lv), lv))
})
# [1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3


问:
Python Dict Transform
I've been having some strange difficulty trying to transform a dataset that I have.

I currently have a dictionary coming from a form as follows:

```<code>data['content']['answers']
</code>```

I would like to have the ['answers'] appended to the first element of a list like so:

```<code>data['content'][0]['answers']
</code>```

However when I try to create it as so, I get an empty dataset.

```<code>data['content'] = [data['content']['answers']]
</code>```

I can't for the life of me figure out what I am doing wrong.

EDIT: Here is the opening JSON

I have:

```<code>{
"content" : {
              "answers" : {
                "3" : {
</code>```

But I need it to be:

```<code>    {
"content" : [
              {
                 "answers" : {
                  "3" : {
</code>```

thanks

答:
If I've understood the question correctly, it sounds like you need data['contents'] to be equal to a list where each element is a dictionary that was previously contained in data['contents']?

I believe this might work (works in Python 2.7 and 3.6):

```<code># assuming that data['content'] is equal to {'answers': {'3':'stuff'}}

data['content'] = [{key:contents} for key,contents in data['content'].items()]

>>> [{'answers': {'3': 'stuff'}}]
</code>```

The list comprehension will preserve the dictionary content for each dictionary that was in contents originally and will return the dictionaries as a list.

Python 2 doc: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Python 3 doc:
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Title: Python Dict Transform

Body:
I've been having some strange difficulty trying to transform a dataset that I have.

I currently have a dictionary coming from a form as follows:

data['content']['answers']

I would like to have the ['answers'] appended to the first element of a list like so:

data['content'][0]['answers']

However when I try to create it as so, I get an empty dataset.

data['content'] = [data['content']['answers']]

I can't for the life of me figure out what I am doing wrong.

EDIT: Here is the opening JSON

I have:

{
"content" : {
              "answers" : {
                "3" : {

But I need it to be:

    {
"content" : [
              {
                 "answers" : {
                  "3" : {

thanks

Body:
If I've understood the question correctly, it sounds like you need data['contents'] to be equal to a list where each element is a dictionary that was previously contained in data['contents']?

I believe this might work (works in Python 2.7 and 3.6):

# assuming that data['content'] is equal to {'answers': {'3':'stuff'}}

data['content'] = [{key:contents} for key,contents in data['content'].items()]

>>> [{'answers': {'3': 'stuff'}}]

The list comprehension will preserve the dictionary content for each dictionary that was in contents originally and will return the dictionaries as a list.

Python 2 doc: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Python 3 doc:
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions


问:
MongoDB why db.auth does not switch user?
I have an admin user in the DB myNewDB

```<code>[admin] user: root>use myNewDB
switched to db myNewDB
[myNewDB] user: root>show users
{
"_id" : "myNewDB.superAdmin",
"user" : "superAdmin",
"db" : "myNewDB",
"roles" : [
    {
        "role" : "userAdmin",
        "db" : "myNewDB"
    },
    {
        "role" : "readWrite",
        "db" : "myNewDB"
    },
    {
        "role" : "dbAdmin",
        "db" : "myNewDB"
    }
    ]
}
</code>```

when I try to authenticate as superAdmin: it seems to work

```<code>[myNewDB] user: root>db.auth("superAdmin","superAdmin123")
1
[myNewDB] user: root>
</code>```

but I'm still connected as user 'root', should I not be authenticated as :

```<code>[myNewDB] user: superAdmin>
</code>```

UPDATE

here is my monger.js

```<code> prompt = function() {
     database = db.getName()
    user = db.runCommand({connectionStatus :
     1}).authInfo.authenticatedUsers[0]
    if (user) {
        return "["+ database +"] " + "user: " + user.user + ">"
     }
     return "["+ database +"] " + ">"
 }
</code>```

答:
I assume that you are using the mongo shell, and you are presumably using a .mongorc.js file which is how you're getting the customized prompt with a display of the current user and database.

I would suggest that you look at your .mongorc.js file and/or share it here. The prompt should change when you authenticate. See this thread for an example .mongorc.js file.

EDIT:
Looking further, I suspect that you're running into the case where you can be authenticated against multiple databases. And your .mongorc.js is probably naively just grabbing the first user. Try running your example again and run db.runCommand({connectionStatus : 1}) which would show multiple users.

Body:
I have an admin user in the DB myNewDB

[admin] user: root>use myNewDB
switched to db myNewDB
[myNewDB] user: root>show users
{
"_id" : "myNewDB.superAdmin",
"user" : "superAdmin",
"db" : "myNewDB",
"roles" : [
    {
        "role" : "userAdmin",
        "db" : "myNewDB"
    },
    {
        "role" : "readWrite",
        "db" : "myNewDB"
    },
    {
        "role" : "dbAdmin",
        "db" : "myNewDB"
    }
    ]
}

when I try to authenticate as superAdmin: it seems to work

[myNewDB] user: root>db.auth("superAdmin","superAdmin123")
1
[myNewDB] user: root>

but I'm still connected as user 'root', should I not be authenticated as :

[myNewDB] user: superAdmin>

UPDATE

here is my monger.js

 prompt = function() {
     database = db.getName()
    user = db.runCommand({connectionStatus :
     1}).authInfo.authenticatedUsers[0]
    if (user) {
        return "["+ database +"] " + "user: " + user.user + ">"
     }
     return "["+ database +"] " + ">"
 }


问:
Create a time series with a row every 15 minutes
I'm having trouble creating a time series (POSIXct or dttm column) with a row every 15 minutes.

Something that will look like this for every 15 minutes between Jan 1st 2015 and Dec 31st 2016 (here as month/day/year hour:minutes):

```<code>1/15/2015 0:00
1/15/2015 0:15
1/15/2015 0:30
1/15/2015 0:45
1/15/2015 1:00
</code>```

A loop starting date of 01/01/2015 0:00 and then adding 15 minutes until 12/31/2016 23:45?

Does anyone has an idea of how this can be done easily?

Body:
I'm having trouble creating a time series (POSIXct or dttm column) with a row every 15 minutes.

Something that will look like this for every 15 minutes between Jan 1st 2015 and Dec 31st 2016 (here as month/day/year hour:minutes):

1/15/2015 0:00
1/15/2015 0:15
1/15/2015 0:30
1/15/2015 0:45
1/15/2015 1:00

A loop starting date of 01/01/2015 0:00 and then adding 15 minutes until 12/31/2016 23:45?

Does anyone has an idea of how this can be done easily?

Body:
intervals.15.min <- 0 : (366 * 24 * 60 * 60 / 15 / 60)
res <- as.POSIXct("2015-01-01","GMT") + intervals.15.min * 15 * 60
res <- res[res < as.POSIXct("2016-01-01 00:00:00 GMT")]
head(res)
# "2015-01-01 00:00:00 GMT" "2015-01-01 00:15:00 GMT" "2015-01-01 00:30:00 GMT"
tail(res)
# "2015-12-31 23:15:00 GMT" "2015-12-31 23:30:00 GMT" "2015-12-31 23:45:00 GMT"


问:
limited text chunks splitted by new line
I have string in python containing a large text file (over 1MiB).
I need to split it to chunks.

Constrains:

chunks can be splited only by newline character, and

len(chunk) must be as big as possbile but smaller than LIMIT (i.e. 100KiB)

Lines longer than LIMIT can be ommited.

Any idea how to implement this nicely in python?

Thank you in advance.

答:
Here is my not-so-pythonic solution:</p>

```<code>def line_chunks(lines, chunk_limit):
    chunks = []
    chunk = []
    chunk_len = 0
    for line in lines:
        if len(line) + chunk_len < chunk_limit:
            chunk.append(line)
            chunk_len += len(line)
        else:
            chunks.append(chunk)
            chunk = [line]
            chunk_len = len(line)
    chunks.append(chunk)
    return chunks

chunks = line_chunks(data.split('\n'), 150)
print '\n---new-chunk---\n'.join(['\n'.join(chunk) for chunk in chunks])
</code>```

Body:
Here is my not-so-pythonic solution:

def line_chunks(lines, chunk_limit):
    chunks = []
    chunk = []
    chunk_len = 0
    for line in lines:
        if len(line) + chunk_len < chunk_limit:
            chunk.append(line)
            chunk_len += len(line)
        else:
            chunks.append(chunk)
            chunk = [line]
            chunk_len = len(line)
    chunks.append(chunk)
    return chunks

chunks = line_chunks(data.split('\n'), 150)
print '\n---new-chunk---\n'.join(['\n'.join(chunk) for chunk in chunks])


问:
How to get Target name?
We know that Xcode maintains environment variable of ${TARGET_NAME} but how to access this variable in objective-C code ?

What I have tried ?

I have added "TARGET_NAME=${TARGET_NAME}" this in Preprocessor macros section of Build Settings. But now I am not sure how to use this variable "TARGET_NAME" as a string in objective-C code.

In my case product name and target name are different so, no chance to use that.

I tried to access using

```<code>#ifdef TARGET_NAME
 NSLog(@"TargetIdentifier %@",TARGET_NAME);
#endif
</code>```

This code is giving error like "Use of undeclared identifier 'myapptargetname'"

答:
In Xcode 7.3.1</p>

```<code>if let targetName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? String{
    print(targetName)
}
</code>```

Title: How to get Target name?

Body:
We know that Xcode maintains environment variable of ${TARGET_NAME} but how to access this variable in objective-C code ?

What I have tried ?

I have added "TARGET_NAME=${TARGET_NAME}" this in Preprocessor macros section of Build Settings. But now I am not sure how to use this variable "TARGET_NAME" as a string in objective-C code.

In my case product name and target name are different so, no chance to use that.

I tried to access using

#ifdef TARGET_NAME
 NSLog(@"TargetIdentifier %@",TARGET_NAME);
#endif

This code is giving error like "Use of undeclared identifier 'myapptargetname'"

Body:
In Xcode 7.3.1

if let targetName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? String{
    print(targetName)
}


问:
How to measures script execution and *parsing* time?
As far as I know, scripts are downloaded and executed synchronously in javascript.
Hence if we write the following code:

```<code><script type='text/javascript'>console.time('core')</script>
<script type='text/javascript' src="guicore.js"></script>
<script type='text/javascript'>console.timeEnd('core')</script>
</code>```

we'll see in console total time for download, parse and execute js.
How we can exclude parsing time? Just add similar file, but with all code commented out. More or less, this technique should work.

The problem is this just doesn't work =)

I optimized that code, reduce execution time from 90ms to 25ms, but see the same ~100±10ms time for Chrome and ~160±15ms for Firefox.

Ok, I know I could use profiler, but the question is: "how to measure js parsing time correctly" and what did I measured btw. Research.reverse-engineering is very fun, but maybe there's someone who knows that field in depth.

答:
Very old question with a relatively new answer.

Date.now() returns a timestamp with millisecond accuracy. For an application to run at 60FPS, it must update the frame every 16ms. Our millisecond meter may not be accurate enough.

Introducing the Performace API in modern JS browsers, this allows for floating-point timestamps accurate to the microsecond.

Instead of Date.now() use window.performance.now() for measurements, there's a good guide on using the Performance API on HTML5Rocks.

Body:
As far as I know, scripts are downloaded and executed synchronously in javascript.
Hence if we write the following code:

we'll see in console total time for download, parse and execute js.
How we can exclude parsing time? Just add similar file, but with all code commented out. More or less, this technique should work.

The problem is this just doesn't work =)

I optimized that code, reduce execution time from 90ms to 25ms, but see the same ~100±10ms time for Chrome and ~160±15ms for Firefox.

Ok, I know I could use profiler, but the question is: "how to measure js parsing time correctly" and what did I measured btw. Research.reverse-engineering is very fun, but maybe there's someone who knows that field in depth.


问:
Gist: How are images uploaded to a gist?
Here is the image file:
https://gist.github.com/mbostock/5503544#file-thumbnail-png

I tried to drag-and-drop the image file in the edit mode of a gist.  That didn't seem to work in Chrome and FireFox.

Update: After back and forth emails with GitHub, this feature (drag-and-drop binary files, including images) isn't supported.

答:
Create a gist or reuse one of your gists.

Clone your gist:

```<code>git clone https://gist.github.com/<hash>.git
</code>```

Add your image to your gist's repository:

```<code>git add my-image.jpg
</code>```

Commit the image:

```<code>git commit -m "adding my image to my gist"
</code>```

Update gist by pushing you modifications:

```<code>git push origin master
</code>```

Body:
Create a gist or reuse one of your gists.

Clone your gist:

git clone https://gist.github.com/<hash>.git

Add your image to your gist's repository:

git add my-image.jpg

Commit the image:

git commit -m "adding my image to my gist"

Update gist by pushing you modifications:

git push origin master


问:
junitparameter exception method should have no parameter
By using JUnitParameter for testing a methode I have an exception. My code is similar to lot of example on JUnitParameter:

```<code>    private Object parametersForTestSetDistanceFormated() {
    return new Object[][]{
        {100,   "_1,__ km"},
        {100,   "1_,__ km"},
        {1100,  "11,__ km"},
        {110,   "1_,1_ km"},
        {111,   "1_,11 km"}};
}
/**
 * Test of setDistanceFormated method, of class ClientFormated.
 */
@Test
@Parameters
public void testSetDistanceFormated(final int exptDist, final String  distFormated) {
    System.out.println("setDistanceFormated");
    ClientFormated instance = new ClientFormated();

    instance.setDistanceFormated(distFormated);
    assertEquals(exptDist, (long) instance.getDistance());
}
</code>```

and then I obtain the following exception:

```<code>java.lang.RuntimeException: java.lang.Exception: Method testSetDistanceFormated should have no parameters
    at junitparams.JUnitParamsRunner.verifyMethodCanBeRunByStandardRunner(JUnitParamsRunner.java:429)
    at junitparams.JUnitParamsRunner.runChild(JUnitParamsRunner.java:420)
    at junitparams.JUnitParamsRunner.runChild(JUnitParamsRunner.java:386)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.Exception: Method testSetDistanceFormated should have no parameters
    at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:76)
    at junitparams.JUnitParamsRunner.verifyMethodCanBeRunByStandardRunner(JUnitParamsRunner.java:427)
    ... 20 more
</code>```

I haven't found related on the web...

My whole classe:

```<code>import com.entities.Client;
import junitparams.JUnitParamsRunner;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized.Parameters;

@RunWith(JUnitParamsRunner.class)
public class ClientFormatedTest {

private Object parametersForTestSetDistanceFormated() {
    return new Object[][]{
        {100,   "_1,__ km"},
        {100,   "1_,__ km"},
        {1100,  "11,__ km"},
        {110,   "1_,1_ km"},
        {111,   "1_,11 km"}};
}

/**
 * Test of setDistanceFormated method, of class ClientFormated.
 */
@Test
@Parameters
public void testSetDistanceFormated(final int exptDist, final String  distFormated) {
    System.out.println("setDistanceFormated");
    ClientFormated instance = new ClientFormated();

    instance.setDistanceFormated(distFormated);
    assertEquals(exptDist, (long) instance.getDistance());
}
</code>```

答:
This error may show up when your test method(having @Test annotation) have any arguments

For anyone else who came here because of the same error they are seeing but not with JUitParameter.

I hit this same error, in my code.

```<code>java.lang.Exception: Method assertResult() should be public

at org.junit.runners.model.FrameworkMethod.validatePublicVoid(FrameworkMethod.java:96)
at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:74)
at org.junit.runners.ParentRunner.validatePublicVoidNoArgMethods(ParentRunner.java:155)
at org.junit.runners.BlockJUnit4ClassRunner.validateTestMethods(BlockJUnit4ClassRunner.java:208)
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:188)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

The error was because for a method with argument, I had accidentally added a @Test tag. (Added it when I was testing just that method and then forgot to remove it). Silly me.
Worked fine when I removed the @Test.
If you want the @Test, then the method shouldn't have any arguments

```<code>@Test
void assertResult(String result) {
    Assert.assertTrue(!"403".equals(result) && !"404".equals(result) && !"400".equals(result));
    Assert.assertNotNull(result);
}
</code>```

Body:
By using JUnitParameter for testing a methode I have an exception. My code is similar to lot of example on JUnitParameter:

    private Object parametersForTestSetDistanceFormated() {
    return new Object[][]{
        {100,   "_1,__ km"},
        {100,   "1_,__ km"},
        {1100,  "11,__ km"},
        {110,   "1_,1_ km"},
        {111,   "1_,11 km"}};
}
/**
 * Test of setDistanceFormated method, of class ClientFormated.
 */
@Test
@Parameters
public void testSetDistanceFormated(final int exptDist, final String  distFormated) {
    System.out.println("setDistanceFormated");
    ClientFormated instance = new ClientFormated();

    instance.setDistanceFormated(distFormated);
    assertEquals(exptDist, (long) instance.getDistance());
}

and then I obtain the following exception:

java.lang.RuntimeException: java.lang.Exception: Method testSetDistanceFormated should have no parameters
    at junitparams.JUnitParamsRunner.verifyMethodCanBeRunByStandardRunner(JUnitParamsRunner.java:429)
    at junitparams.JUnitParamsRunner.runChild(JUnitParamsRunner.java:420)
    at junitparams.JUnitParamsRunner.runChild(JUnitParamsRunner.java:386)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.Exception: Method testSetDistanceFormated should have no parameters
    at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:76)
    at junitparams.JUnitParamsRunner.verifyMethodCanBeRunByStandardRunner(JUnitParamsRunner.java:427)
    ... 20 more

I haven't found related on the web...

My whole classe:

import com.entities.Client;
import junitparams.JUnitParamsRunner;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized.Parameters;

@RunWith(JUnitParamsRunner.class)
public class ClientFormatedTest {

private Object parametersForTestSetDistanceFormated() {
    return new Object[][]{
        {100,   "_1,__ km"},
        {100,   "1_,__ km"},
        {1100,  "11,__ km"},
        {110,   "1_,1_ km"},
        {111,   "1_,11 km"}};
}

/**
 * Test of setDistanceFormated method, of class ClientFormated.
 */
@Test
@Parameters
public void testSetDistanceFormated(final int exptDist, final String  distFormated) {
    System.out.println("setDistanceFormated");
    ClientFormated instance = new ClientFormated();

    instance.setDistanceFormated(distFormated);
    assertEquals(exptDist, (long) instance.getDistance());
}

Body:
This error may show up when your test method(having @Test annotation) have any arguments

For anyone else who came here because of the same error they are seeing but not with JUitParameter.

I hit this same error, in my code.

java.lang.Exception: Method assertResult() should be public

at org.junit.runners.model.FrameworkMethod.validatePublicVoid(FrameworkMethod.java:96)
at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:74)
at org.junit.runners.ParentRunner.validatePublicVoidNoArgMethods(ParentRunner.java:155)
at org.junit.runners.BlockJUnit4ClassRunner.validateTestMethods(BlockJUnit4ClassRunner.java:208)
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:188)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

The error was because for a method with argument, I had accidentally added a @Test tag. (Added it when I was testing just that method and then forgot to remove it). Silly me.
Worked fine when I removed the @Test.
If you want the @Test, then the method shouldn't have any arguments

@Test
void assertResult(String result) {
    Assert.assertTrue(!"403".equals(result) && !"404".equals(result) && !"400".equals(result));
    Assert.assertNotNull(result);
}


问:
Alternatives to Windows Workflow Foundation?
I've been using WWF for a while as part of an internal call center application (ASP.NET), and while learning it was a good practice in understanding how a state machine based workflow system should work, I am definitely not in love with WWF itself. In my opinion it is:

Overly complex, especially for use within web apps (all that threaded runtime stuff)

Immature (ever worked with that horrible designer?)

Anemic in its current feature set

Does anyone have a suggestion for a better .NET based workflow framework?  Specifically, I am looking for the following features:

State machine based (mapping states to available actions)

A focus on user permissions (controlling who has access to what actions)

The ability to run workflows as timed background tasks (for example, to send out reminders for items that have been sitting in a certain state for x days)

That's really all I need. I don't need to be able to "drag and drop" any activities or visually design the flow. I am perfectly comfortable writing actual code once a particular action is triggered.

答:
First of all you should look for a engine supporting BPMN. BPMN is a standard in Workflow and Process management and well supported from a lot of projects.
Second you should think about the requirements to thus an engine.
When you look for a BPMN Engine, there are two different approaches:

Task-Orientated

These engines (e.g. JBoss BPM - jbpm) are designed to process an input data by a well defined process model. Each task in the model gives the control to a piece of code - either a standard or an individual implementation. The process ends when the process-token reaches the end of the process model (End-Event). This kind of processing takes milliseconds. The engine can be used for batch jobs or processing data with a complex process orientated flow.

Event-Driven

Human-Centric workflow engines are event driven (e.g. Imixs-Workflow). This is a kind of state machine but offers typically much more functionality. You can start a new processinstance by assigning your business object with the initial task (defined by the start event). Than the workflow engine allows you to trigger events assigned to each task, defined in your model. Each event (Intermediate CatchEvent) triggers the workflow engine to transfer the running processinstance to the next task (state). Until no new event is triggered, the processinstance 'waits' in the current task (state). An approval process is an typical example for this kind of human-centric workflow.

You can find a list of engines here.

OwnerDisplayName: Jeremy McCollum


问:
Expanding an array in JSX
I want to return multiple elements from my helper render functions, but I don't want to add keys to each element. For example:

```<code>class Foo extends React.Component {
  _renderBar() {
    return [
      'hello ',
      <b>world</b>,
    ]
  }

  render() {
    return (
      <div>
        {this._renderBar()}
      </div>
    );
  }
}
</code>```

Since JSX compiles to React.createElement calls, and React.createElement accepts elements as it's third and higher arguments, I want to spread the array returned by _renderBar when React.createElement is called.

For example, my code currently compiles to something like this:

```<code>React.createElement(
  'div',
  null,
  ['hello ', React.createElement(
    'b',
    null,
    'world'
  )]
);
</code>```

Since I don't have keys on the array elements, I get a warning. I want it to be something like this:

```<code>React.createElement(
  "div",
  null,
  "hello ",
  React.createElement(
    "b",
    null,
    "world"
  )
);
</code>```

I tried doing {...this._renderBar()}, but it doesn't work.

答:
I don't think there is a way to do this with JSX. The simplest solution would be to call React.createElement directly:

```<code>React.createElement(
  'div',
  null,
  ...this._renderBar()
);
</code>```

Title: Expanding an array in JSX

Body:
I want to return multiple elements from my helper render functions, but I don't want to add keys to each element. For example:

class Foo extends React.Component {
  _renderBar() {
    return [
      'hello ',
      world,
    ]
  }

  render() {
    return (

        {this._renderBar()}

    );
  }
}

Since JSX compiles to React.createElement calls, and React.createElement accepts elements as it's third and higher arguments, I want to spread the array returned by _renderBar when React.createElement is called.

For example, my code currently compiles to something like this:

React.createElement(
  'div',
  null,
  ['hello ', React.createElement(
    'b',
    null,
    'world'
  )]
);

Since I don't have keys on the array elements, I get a warning. I want it to be something like this:

React.createElement(
  "div",
  null,
  "hello ",
  React.createElement(
    "b",
    null,
    "world"
  )
);

I tried doing {...this._renderBar()}, but it doesn't work.

Body:
I don't think there is a way to do this with JSX. The simplest solution would be to call React.createElement directly:

React.createElement(
  'div',
  null,
  ...this._renderBar()
);


问:
Which function of V8 engine print informations to stdout？
I add flag “--print-opt-code” to V8 engine, then v8 could print the compiled code to stdout. And now I what to print these information to specific files, then which function should I modify?
Thank you very much~~</p>

答:
Try this: --redirect-code-traces-to=<filename> ;-)

Generally speaking: follow the FLAG_print_opt_code through the source and see what it does.

Depending on where you run V8 (in d8? in Chrome? in node.js?), it might be easiest to just use shell redirection: .../d8 test.js --print-opt-code > output.txt


问:
JAVA making time to decrease to zero by swing timer
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

```<code>        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();
</code>```

is it possible?

答:
```<code>final Timer t = new Timer(1000, new ActionListener() {
    private long time = 10 * 1000; //10 seconds, for example

    public void actionPerformed(ActionEvent e) {
        if (time >= 0) {
            long s = ((time / 1000) % 60);
            long m = (((time / 1000) / 60) % 60);
            long h = ((((time / 1000) / 60) / 60) % 60);
            timing.setText(h + " hours, " + m + " minutes " + s + " seconds");
            time -= 1000;
        }
    }
});
t.start();
</code>```

Body:
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();

is it possible?


问:
Real-Life Use of Level Order Traversal
Can somebody please suggest me when would I need a Level-Order Traversal (to solve some practical/real-life scenario)?</p>

答:
Google Map Direction is using Level Order Traversal (BFS) all the time.

Algorithms repeat the same method choosing the node nearest to the intersection points, eventually selecting the route with the shortest length.

http://blog.hackerearth.com/breadth-first-search-algorithm-example-working-of-gps-navigation

Title: Real-Life Use of Level Order Traversal


问:
User-defined function returns non-formattable dates Excel VBA
I created a UDF in Excel VBA that returns an multi-dimensional array of dates and doubles. The problem is that I cannot format the dates that are returned.

Here is a simplified example:

```<code>Function test(dates as Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function
</code>```

The transpose at the end is just for convenience to have an column output (I press Ctrl+Shift+enter). I you use this simplified example, you will not be able to format the output and it will not be considered as dates stricto sensu.

Any ideas?

答:
You may try something like this.</p>

```<code>Results(i) = CDate(dates.Cells(i).Value)
</code>```

Body:
I created a UDF in Excel VBA that returns an multi-dimensional array of dates and doubles. The problem is that I cannot format the dates that are returned.

Here is a simplified example:

Function test(dates as Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function

The transpose at the end is just for convenience to have an column output (I press Ctrl+Shift+enter). I you use this simplified example, you will not be able to format the output and it will not be considered as dates stricto sensu.

Any ideas?

Body:
You may try something like this.

Results(i) = CDate(dates.Cells(i).Value)