答:
use startActivityForResult() to start ListFrom and ListTo Activities and the receive the result from these activities in OnActivityResult() method.

SearchRide as Main Activity code:

```<code>                protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_search_ride);

                etDate=(EditText) findViewById(R.id.etDate);
                TextView tFrom=(TextView) findViewById(R.id.tFrom);
                TextView tTo=(TextView) findViewById(R.id.tTo);
                etFrom=(EditText) findViewById(R.id.etFrom);
                etTo=(EditText) findViewById(R.id.etTo);
                Button bSearch=(Button) findViewById(R.id.bSearch);
                ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
                ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
                final TextView tNumber=(TextView) findViewById(R.id.tNumber);

                tNumber.setText(String.valueOf(p));
                iplussign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(p<=9) {
                            p++;
                            tNumber.setText(String.valueOf(p));
                        }
                    }
                });

                iminussign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(p>=2) {
                            p--;
                            tNumber.setText(String.valueOf(p));
                        }
                    }
                });

                etFrom.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent ListFrom = new Intent(SearchRide.this,ListFrom.class);
                        startActivityForResult(ListFrom,0);
                    }
                });

                etTo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent ToList = new Intent(SearchRide.this,ListTo.class);
                        startActivityForResult(ToList,1);
                    }
                });

                etDate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
                        dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
                        dialog.show();
                    }
                });
            }

            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == 0) {
                    if(resultCode == Activity.RESULT_OK){
                        etFrom.setText(data.getStringExtra("From"));
                    }
                } else if (requestCode == 1) {
                    if(resultCode == Activity.RESULT_OK){
                        etTo.setText(data.getStringExtra("To"));
                    }

                }}
</code>```

ListFrom code:

```<code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_from);

listView=(ListView) findViewById(R.id.listviewFrom);
editText=(EditText) findViewById(R.id.etsearchFrom);

initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String v="";
        switch (position) {
            case 0:
                v = items[0];
                break;
            case 1:
                v = items[1];
                break;
            case 2:
                v = items[2];
                break;
            case 3:
                v = items[3];
                break;
            case 4:
                v = items[4];
                break;
            case 5:
                v = items[5];
                break;
        }
    Intent intent = new Intent();
        intent.putExtra("From",v);
        setResult(Activity.RESULT_OK, intent);
        finish();

    }
});
</code>```

ListTo code:

```<code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_to);

etSearchTo=(EditText) findViewById(R.id.etSearchTo);
listViewTo=(ListView) findViewById(R.id.listViewTo);

initList();
listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String v="";
        switch (position) {
            case 0:
                v = items[0];
                break;
            case 1:
                v = items[1];
                break;
            case 2:
                v = items[2];
                break;
            case 3:
                v = items[3];
                break;
            case 4:
                v = items[4];
                break;
            case 5:
                v = items[5];
                break;
        }
        Intent intent = new Intent();
        intent.putExtra("To",v);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
});
</code>```

Title: How to display both data in Edittext without losing one of them?

Body:
use startActivityForResult() to start ListFrom and ListTo Activities and the receive the result from these activities in OnActivityResult() method.

SearchRide as Main Activity code:

                protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_search_ride);

                etDate=(EditText) findViewById(R.id.etDate);
                TextView tFrom=(TextView) findViewById(R.id.tFrom);
                TextView tTo=(TextView) findViewById(R.id.tTo);
                etFrom=(EditText) findViewById(R.id.etFrom);
                etTo=(EditText) findViewById(R.id.etTo);
                Button bSearch=(Button) findViewById(R.id.bSearch);
                ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
                ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
                final TextView tNumber=(TextView) findViewById(R.id.tNumber);

                tNumber.setText(String.valueOf(p));
                iplussign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(p<=9) {
                            p++;
                            tNumber.setText(String.valueOf(p));
                        }
                    }
                });

                iminussign.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(p>=2) {
                            p--;
                            tNumber.setText(String.valueOf(p));
                        }
                    }
                });

                etFrom.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent ListFrom = new Intent(SearchRide.this,ListFrom.class);
                        startActivityForResult(ListFrom,0);
                    }
                });

                etTo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent ToList = new Intent(SearchRide.this,ListTo.class);
                        startActivityForResult(ToList,1);
                    }
                });

                etDate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
                        dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
                        dialog.show();
                    }
                });
            }

            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == 0) {
                    if(resultCode == Activity.RESULT_OK){
                        etFrom.setText(data.getStringExtra("From"));
                    }
                } else if (requestCode == 1) {
                    if(resultCode == Activity.RESULT_OK){
                        etTo.setText(data.getStringExtra("To"));
                    }

                }}

ListFrom code:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_from);

listView=(ListView) findViewById(R.id.listviewFrom);
editText=(EditText) findViewById(R.id.etsearchFrom);

initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String v="";
        switch (position) {
            case 0:
                v = items[0];
                break;
            case 1:
                v = items[1];
                break;
            case 2:
                v = items[2];
                break;
            case 3:
                v = items[3];
                break;
            case 4:
                v = items[4];
                break;
            case 5:
                v = items[5];
                break;
        }
    Intent intent = new Intent();
        intent.putExtra("From",v);
        setResult(Activity.RESULT_OK, intent);
        finish();

    }
});

ListTo code:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_to);

etSearchTo=(EditText) findViewById(R.id.etSearchTo);
listViewTo=(ListView) findViewById(R.id.listViewTo);

initList();
listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String v="";
        switch (position) {
            case 0:
                v = items[0];
                break;
            case 1:
                v = items[1];
                break;
            case 2:
                v = items[2];
                break;
            case 3:
                v = items[3];
                break;
            case 4:
                v = items[4];
                break;
            case 5:
                v = items[5];
                break;
        }
        Intent intent = new Intent();
        intent.putExtra("To",v);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
});


来源: stackexchange

问:
How can I make Web API serialize DateTime in any object into number of milliseconds since 1970?
In my ASP.NET web service I need all my dates to be serialized to JSON as numbers which represent a number of milliseconds passed since 1970 please. I'm using Newtonsoft.Json serializer. What do I need to do to set it up this way?

UPDATE:
the available documentation (http://www.newtonsoft.com/json/help/html/DatesInJSON.htm) only mentions serializing a single object with custom settings, what i am looking for is the default serialization settings that would govern serialization of any object

答:
Off the top of my head I would get the ticks of the 1970 date subtract it from the ticks of the current date then divide by 10000 since there are 10000 ticks in a milisecond.  This will give you a number which should be easier to serialize.  You could make this an extension method of DateTime.  Ticks on MSDN:
DateTime.Ticks</p>

ContentLicense: CC BY-SA 3.0


问:
Why #' is used before lambda in Common Lisp?
I would like to know why most Common Lisp code I see has things like

(mapcar #'(lambda (x) (* x x)) '(1 2 3))

instead of just

(mapcar (lambda (x) (* x x)) '(1 2 3)),

which seems to work as well. I am beginning to learn Common Lisp, and having some background in Scheme, this intrigues me.

Edit: I know that you need #' with function names because they live in a different namespace than variables. My question is just about #' before lambda, as lambda already returns a function object (I think). The fact that #'-less lambdas work because of a macro expansion just makes it more intriguing...

答:
It is best to avoid #' in most instances because it is "mostly" unnecessary and makes your code more verbose.  There are a few exceptions when some form of quoting is necessary (see Example 4 below).

Note: All the examples in this post have been tested in Emacs Lisp (GNU Emacs 25.2.1), but they should work identically in any ANSI common lisp.  The basic concepts are the same in both dialects.

SIMPLE EXPLANATION

First, let us study a case when it is best to avoid quoting.  Functions are first class objects (e.g. treated like any other object, including the ability to pass them to functions and assign them to variables) that evaluate to themselves.  Anonymous functions (e.g. lambda forms) are one such example. Try the following on Emacs Lisp (M-x ielm RET) or ANY ANSI common lisp.

```<code>((lambda (x) (+ x 10)) 20) -> 30
</code>```

Now, try the quoted version

```<code>(#'(lambda (x) (+ x 10)) 20) -> "function error" or "invalid function..."
</code>```

If you use insist on using #', you have to write

```<code>(funcall #'(lambda (x) (+ x 10)) 20) -> 30
</code>```

DETAILED EXPLANATION

To really understand when quoting is required, one must know how Lisp evaluates expressions.  Read on.  I promise to make this succinct.

You need to know a few basic facts about Lisp:

Lisp "always" evaluates every expression.  Well, unless the expression is quoted, in which case it is returned unevaluated.

Atoms evaluate to themselves.  Atomic expressions are NOT lists. Examples include numbers, strings, hash tables, and vectors.

Symbols (variable names) store two types of values. They can hold regular values and functional definitions.  Hence, Lisp symbols have two slots called cells to store these two types.  Non-functional content is typically held in the symbol's value cell and functions in the function cell.  The ability to hold both non-functional and functional definitions simultaneously place Emacs Lisp and Common Lisp in the 2-Lisp category.  Which of the two cells is used in an expression depends on how the symbol is used -- more specifically its position in a list.  In contrast, symbols in some dialects of Lisp, Scheme being the best known, can hold only one value.  Scheme has no concept of value and function cells.  Such Lisps are collectively called 1-Lisps.

Now, you need a rough understanding of how Lisp evaluates S-expressions (parenthetical expressions).  Every S-expression is evaluated roughly as follows:

If quoted, return it unevaluated

If unquoted, get its CAR (e.g. first element) and evaluate it using the following rules:

a. if an atom, simply return its value (e.g. 3 -> 3, "pablo" -> "pablo")

b. if an S-expression, evaluate it using the same overall procedure

c. if a symbol, return the contents of its function cell

Evaluate each of the elements in the CDR of the S-expression (e.g. all but the first element of the list).

Apply the function obtained from the CAR to the values obtained from each of the elements in the CDR.

The above procedure implies that any symbol in the CAR of an UNQUOTED S-expression must have a valid functional definition in its function cell.

Now, let's go back to the example from the beginning of the post.  Why does

```<code>(#'(lambda (x) (+ x 10)) 20)
</code>```

generate an error?  It does because #'(lambda (x) (+ x 10)), the CAR of the S-expression, is not evaluated by the Lisp interpreter due to the functional quote #'.

```<code>#'(lambda (x) (+ x 10))
</code>```

is not a function, but

```<code>(lambda (x) (+ x 10))
</code>```

is.  Keep in mind that the purpose of quoting is to prevent evaluation.  On the other hand, a lambda form evaluates to itself, a functional form, which is valid as the CAR of an UNQUOTED list.  When Lisp evaluates the CAR of

```<code>((lambda (x) (+ x 10)) 20)
</code>```

it gets (lambda (x) (+ x 20)), which is a function that can be applied to the rest of the arguments in a list (provided the length of the CDR equals the number of arguments allowed by the lambda expression).  Hence,

```<code>((lambda (x) (+ x 10)) 20) -> 30
</code>```

The question is thus when to quote functions or symbols holding functional definitions.  The answer is almost NEVER unless you do things "incorrectly."  By "incorrectly" I mean that you place a functional definition in a symbol's value cell or functional cell when you should do the opposite.  See the following examples to gain a better understanding:

EXAMPLE 1 - Functions Stored in Value Cells

Suppose you need to use apply with a function that expects a variable number of arguments. One such example is the symbol +.  Lisp treats + as a regular symbol.  The functional definition is stored in +'s functional cell. You can assign a value to its value cell if you like using

```<code>(setq + "I am the plus function").
</code>```

If you evaluate

```<code>+ -> "I am the plus function"
</code>```

However, (+ 1 2) still works as expected.

```<code>(+ 1 2) -> 3
</code>```

The function apply is quite useful in recursion. Suppose you want to sum all the elements in a list. You CANNOT write

```<code>(+ '(1 2 3)) -> Wrong type...
</code>```

The reason is that + expects its arguments to be numbers.  apply solves this problem

```<code>(apply #'+ '(1 2 3)) -> (+ 1 2 3) -> 6
</code>```

Why did I quote + above?  Remember the evaluation rules I outlined above. Lisp evaluates the symbol apply by retrieving the value stored in its function cell.  it gets a functional procedure it can apply to a list of arguments.  However, if I do not quote +, Lisp will retrieve the value stored in its value cell because it is NOT the first element in the S-expression. Because we set +'s value cell to "I am the plus function," Lisp does not get the functional definition held in +'s function cell.  Actually, if we had not set its value cell to "I am the plus function," Lisp would have retrieved nil, which is NOT a function, as required by apply.

Is there a way to use + unquoted with apply?  Yes, there is.  You can just evaluate the following code:

```<code>(setq + (symbol-function '+))
(apply + '(1 2 3))
</code>```

This will evaluate to 6, as expected because as Lisp evaluates (apply + '(1 2 3)) it now finds the functional definition of + stored in +'s value cell.

EXAMPLE 2 - Storing Functional Definitions in Value Cells

Suppose you store a functional definition in the symbol's value cell.  This is achieve as follows:

```<code>(setq AFunc (lambda (x) (* 10 x)))
</code>```

Evaluating

```<code>(AFunc 2)
</code>```

generates an error because Lisp cannot find a function in AFunc's function cell. You get around this by using funcall, which tells Lisp to use the value in the symbol's value cell as a functional definition.  You do this using "funcall."

```<code>(funcall AFunc 2)
</code>```

Assuming the functional definition stored in the symbol's value cell is valid,

```<code>(funcall AFunc 2) -> 20
</code>```

You could avoid having using funcall by placing the lambda form in the symbol's function cell using fset:

```<code>(fset 'AFunc (lambda (x) (* 10 x)))
(AFunc 2)
</code>```

This code block will return 20 because lisp finds a functional definition in AFunc's function cell.

EXAMPLE 3 - Local Functions

Say you are writing a function and need a function that won't be used anywhere else.  A typical solution is to define a function valid only inside the scope of the main one.  Try this:

```<code>(defun SquareNumberList (AListOfIntegers)
    "A silly function with an unnecessary
   local function."
  (let ((Square (lambda (ANumber) (* ANumber ANumber))))
    (mapcar Square AListOfIntegers)
    )
  )

(SquareNumberList '(1 2 3))
</code>```

This code block will return

```<code>(1 4 9)
</code>```

The reason Square is not quoted in the above example is that S-expression is evaluated according to the rules I outlined above.  First, Lisp pulls the functional definition of mapcar.  Next, Lisp pulls the contents of its second argument's (e.g. 'Square) value cell.  Finally, it returns (1 2 3) unevaluated for the third argument.

EXAMPLE 4 - Contents of a Symbol's Value and Function Cells

Here is one case when quotes are required.

```<code>(setq ASymbol "Symbol's Value")
(fset 'ASymbol (lambda () "Symbol's Function"))
(progn
  (print (format "Symbol's value -> %s" (symbol-value 'ASymbol)))
  (print (format "Symbol's function -> %s" (symbol-function 'ASymbol)))
  )
</code>```

The above code will evaluate to

```<code>"Symbol's value -> Symbol's Value"
"Symbol's function -> (lambda nil Symbol's Function)"
nil
</code>```

Quote are required in

```<code>(fset 'ASymbol (lambda () "Symbol's Function"))
</code>```

and

```<code>(symbol-value 'ASymbol)
</code>```

and

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

because otherwise Lisp would get the value of ASymbol in each case, preventing fset, symbol-value, and symbol-function from working correctly.

I hope this lengthy post proves useful to someone.

ContentLicense: CC BY-SA 2.5

Body:
It is best to avoid #' in most instances because it is "mostly" unnecessary and makes your code more verbose.  There are a few exceptions when some form of quoting is necessary (see Example 4 below).

Note: All the examples in this post have been tested in Emacs Lisp (GNU Emacs 25.2.1), but they should work identically in any ANSI common lisp.  The basic concepts are the same in both dialects.

SIMPLE EXPLANATION

First, let us study a case when it is best to avoid quoting.  Functions are first class objects (e.g. treated like any other object, including the ability to pass them to functions and assign them to variables) that evaluate to themselves.  Anonymous functions (e.g. lambda forms) are one such example. Try the following on Emacs Lisp (M-x ielm RET) or ANY ANSI common lisp.

((lambda (x) (+ x 10)) 20) -> 30

Now, try the quoted version

(#'(lambda (x) (+ x 10)) 20) -> "function error" or "invalid function..."

If you use insist on using #', you have to write

(funcall #'(lambda (x) (+ x 10)) 20) -> 30

DETAILED EXPLANATION

To really understand when quoting is required, one must know how Lisp evaluates expressions.  Read on.  I promise to make this succinct.

You need to know a few basic facts about Lisp:

Lisp "always" evaluates every expression.  Well, unless the expression is quoted, in which case it is returned unevaluated.

Atoms evaluate to themselves.  Atomic expressions are NOT lists. Examples include numbers, strings, hash tables, and vectors.

Symbols (variable names) store two types of values. They can hold regular values and functional definitions.  Hence, Lisp symbols have two slots called cells to store these two types.  Non-functional content is typically held in the symbol's value cell and functions in the function cell.  The ability to hold both non-functional and functional definitions simultaneously place Emacs Lisp and Common Lisp in the 2-Lisp category.  Which of the two cells is used in an expression depends on how the symbol is used -- more specifically its position in a list.  In contrast, symbols in some dialects of Lisp, Scheme being the best known, can hold only one value.  Scheme has no concept of value and function cells.  Such Lisps are collectively called 1-Lisps.

Now, you need a rough understanding of how Lisp evaluates S-expressions (parenthetical expressions).  Every S-expression is evaluated roughly as follows:

If quoted, return it unevaluated

If unquoted, get its CAR (e.g. first element) and evaluate it using the following rules:

a. if an atom, simply return its value (e.g. 3 -> 3, "pablo" -> "pablo")

b. if an S-expression, evaluate it using the same overall procedure

c. if a symbol, return the contents of its function cell

Evaluate each of the elements in the CDR of the S-expression (e.g. all but the first element of the list).

Apply the function obtained from the CAR to the values obtained from each of the elements in the CDR.

The above procedure implies that any symbol in the CAR of an UNQUOTED S-expression must have a valid functional definition in its function cell.

Now, let's go back to the example from the beginning of the post.  Why does

(#'(lambda (x) (+ x 10)) 20)

generate an error?  It does because #'(lambda (x) (+ x 10)), the CAR of the S-expression, is not evaluated by the Lisp interpreter due to the functional quote #'.

#'(lambda (x) (+ x 10))

is not a function, but

(lambda (x) (+ x 10))

is.  Keep in mind that the purpose of quoting is to prevent evaluation.  On the other hand, a lambda form evaluates to itself, a functional form, which is valid as the CAR of an UNQUOTED list.  When Lisp evaluates the CAR of

((lambda (x) (+ x 10)) 20)

it gets (lambda (x) (+ x 20)), which is a function that can be applied to the rest of the arguments in a list (provided the length of the CDR equals the number of arguments allowed by the lambda expression).  Hence,

((lambda (x) (+ x 10)) 20) -> 30

The question is thus when to quote functions or symbols holding functional definitions.  The answer is almost NEVER unless you do things "incorrectly."  By "incorrectly" I mean that you place a functional definition in a symbol's value cell or functional cell when you should do the opposite.  See the following examples to gain a better understanding:

EXAMPLE 1 - Functions Stored in Value Cells

Suppose you need to use apply with a function that expects a variable number of arguments. One such example is the symbol +.  Lisp treats + as a regular symbol.  The functional definition is stored in +'s functional cell. You can assign a value to its value cell if you like using

(setq + "I am the plus function").

If you evaluate

+ -> "I am the plus function"

However, (+ 1 2) still works as expected.

(+ 1 2) -> 3

The function apply is quite useful in recursion. Suppose you want to sum all the elements in a list. You CANNOT write

(+ '(1 2 3)) -> Wrong type...

The reason is that + expects its arguments to be numbers.  apply solves this problem

(apply #'+ '(1 2 3)) -> (+ 1 2 3) -> 6

Why did I quote + above?  Remember the evaluation rules I outlined above. Lisp evaluates the symbol apply by retrieving the value stored in its function cell.  it gets a functional procedure it can apply to a list of arguments.  However, if I do not quote +, Lisp will retrieve the value stored in its value cell because it is NOT the first element in the S-expression. Because we set +'s value cell to "I am the plus function," Lisp does not get the functional definition held in +'s function cell.  Actually, if we had not set its value cell to "I am the plus function," Lisp would have retrieved nil, which is NOT a function, as required by apply.

Is there a way to use + unquoted with apply?  Yes, there is.  You can just evaluate the following code:

(setq + (symbol-function '+))
(apply + '(1 2 3))

This will evaluate to 6, as expected because as Lisp evaluates (apply + '(1 2 3)) it now finds the functional definition of + stored in +'s value cell.

EXAMPLE 2 - Storing Functional Definitions in Value Cells

Suppose you store a functional definition in the symbol's value cell.  This is achieve as follows:

(setq AFunc (lambda (x) (* 10 x)))

Evaluating

(AFunc 2)

generates an error because Lisp cannot find a function in AFunc's function cell. You get around this by using funcall, which tells Lisp to use the value in the symbol's value cell as a functional definition.  You do this using "funcall."

(funcall AFunc 2)

Assuming the functional definition stored in the symbol's value cell is valid,

(funcall AFunc 2) -> 20

You could avoid having using funcall by placing the lambda form in the symbol's function cell using fset:

(fset 'AFunc (lambda (x) (* 10 x)))
(AFunc 2)

This code block will return 20 because lisp finds a functional definition in AFunc's function cell.

EXAMPLE 3 - Local Functions

Say you are writing a function and need a function that won't be used anywhere else.  A typical solution is to define a function valid only inside the scope of the main one.  Try this:

(defun SquareNumberList (AListOfIntegers)
    "A silly function with an unnecessary
   local function."
  (let ((Square (lambda (ANumber) (* ANumber ANumber))))
    (mapcar Square AListOfIntegers)
    )
  )

(SquareNumberList '(1 2 3))

This code block will return

(1 4 9)

The reason Square is not quoted in the above example is that S-expression is evaluated according to the rules I outlined above.  First, Lisp pulls the functional definition of mapcar.  Next, Lisp pulls the contents of its second argument's (e.g. 'Square) value cell.  Finally, it returns (1 2 3) unevaluated for the third argument.

EXAMPLE 4 - Contents of a Symbol's Value and Function Cells

Here is one case when quotes are required.

(setq ASymbol "Symbol's Value")
(fset 'ASymbol (lambda () "Symbol's Function"))
(progn
  (print (format "Symbol's value -> %s" (symbol-value 'ASymbol)))
  (print (format "Symbol's function -> %s" (symbol-function 'ASymbol)))
  )

The above code will evaluate to

"Symbol's value -> Symbol's Value"
"Symbol's function -> (lambda nil Symbol's Function)"
nil

Quote are required in

(fset 'ASymbol (lambda () "Symbol's Function"))

and

(symbol-value 'ASymbol)

and

(symbol-function 'ASymbol)

because otherwise Lisp would get the value of ASymbol in each case, preventing fset, symbol-value, and symbol-function from working correctly.

I hope this lengthy post proves useful to someone.

ContentLicense: CC BY-SA 4.0


问:
Using static method from generic class
I have problem as above. My code:

```<code>public abstract class BaseFactory<T> where T: class
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }
</code>```

and my question is how can I call

```<code>BaseFactory.UpdateDataBase_static();
</code>```

instead of:

```<code>BaseFactory<SomeClass>.UpdateDataBase_static();
</code>```

Any ideas?

答:
It's not possible to do exactly what you're asking, but since the method doesn't use T at all, you can just use BaseFactory<object>.UpdateDataBase_static(); without specifying any particular class.

But as an editorial comment, in general a method in a generic class that never uses the generic parameter probably shouldn't be there.

Title: Using static method from generic class

Body:
I have problem as above. My code:

public abstract class BaseFactory<T> where T: class
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

and my question is how can I call

BaseFactory.UpdateDataBase_static();

instead of:

BaseFactory<SomeClass>.UpdateDataBase_static();

Any ideas?


问:
ReferenceError while passing multiple parameters Ajax Codeigniter
I'm getting

ReferenceError: Y1ohe1oTVVG6916 is not defined

response when viewing my console. This happens while trying to pass two parameters via Ajax. Y1ohe1oTVVG6916  is the unique identifier for this input.

AJAX:

```<code>function checktickets(val)
{
var myserial = <?= $row['eventserial']?>; //this outputs the unique identifier Y1ohe1oTVVG6916
$.ajax({
type: "POST",
url: "<?php echo base_url();?>welcome/gettickets",
data:{
id:val,
evtsr:myserial
},
beforeSend :function(){
$(".numberoftickets option:gt(0)").remove();
$('.numberoftickets').find("option:eq(0)").html("Please wait..");

},
success: function (data) {
/*get response as json */
$('.numberoftickets').find("option:eq(0)").html("Select Number of Tickets");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
console.log(data);
alert(data);
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.numberoftickets').append(option);
});

/*ends */

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

CONTROLLER:

```<code>public function gettickets() {
$evt =$_POST['evtsr'];
$tkt =$_POST['id'];

$query = $this->db->query("SELECT * FROM events_tickets where event_serial ='$evt' AND tickets_id='$tkt'");

$data=array();
foreach($query->result_array() as $key=> $r)
{
for($i=1; $i<=$r['ticket_max_allowed_buyer']; $i++)
{
$data['value']=$i;
$data['label']=$i;
$json[]=$data;
}
}
echo json_encode($json);
}
</code>```

If I remove the second parameter evtsr:myserial from ajax function and readjust my query from the controller, everything works, but I need this second parameter to be included so as to sort the selection more.

答:
There is only one possible explanation I guess.
Try using the declaration like this :

```<code>var myserial = '<?= $row['eventserial']?>';
</code>```

Please reply if it works. I'm curious whether that is the problem

Body:
I'm getting

ReferenceError: Y1ohe1oTVVG6916 is not defined

response when viewing my console. This happens while trying to pass two parameters via Ajax. Y1ohe1oTVVG6916  is the unique identifier for this input.

AJAX:

function checktickets(val)
{
var myserial = <?= $row['eventserial']?>; //this outputs the unique identifier Y1ohe1oTVVG6916
$.ajax({
type: "POST",
url: "<?php echo base_url();?>welcome/gettickets",
data:{
id:val,
evtsr:myserial
},
beforeSend :function(){
$(".numberoftickets option:gt(0)").remove();
$('.numberoftickets').find("option:eq(0)").html("Please wait..");

},
success: function (data) {
/*get response as json */
$('.numberoftickets').find("option:eq(0)").html("Select Number of Tickets");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
console.log(data);
alert(data);
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.numberoftickets').append(option);
});

/*ends */

}
});
}

CONTROLLER:

public function gettickets() {
$evt =$_POST['evtsr'];
$tkt =$_POST['id'];

$query = $this->db->query("SELECT * FROM events_tickets where event_serial ='$evt' AND tickets_id='$tkt'");

$data=array();
foreach($query->result_array() as $key=> $r)
{
for($i=1; $i<=$r['ticket_max_allowed_buyer']; $i++)
{
$data['value']=$i;
$data['label']=$i;
$json[]=$data;
}
}
echo json_encode($json);
}

If I remove the second parameter evtsr:myserial from ajax function and readjust my query from the controller, everything works, but I need this second parameter to be included so as to sort the selection more.

Body:
There is only one possible explanation I guess.
Try using the declaration like this :

var myserial = '<?= $row['eventserial']?>';

Please reply if it works. I'm curious whether that is the problem


答: You can't, because there is no such method. The closest is to have a non-generic base that the generic class inherits from. Then you can have a method there that doesn't depend on the parameterising type.</p>

Title: Using static method from generic class


问:
CocoaPods linking "clang: error: no such file or directory: 'dynamic_lookup' and 'suppress'"
I'm getting a clang error when my project tries to link.

I can see the following flags in the Pods.debug.xcconfig and Pods.release.xcconfig

```<code>-undefined dynamic_lookup suppress
</code>```

And then the error appears in issue navigator

```<code>clang: error: no such file or directory: 'dynamic_lookup'
clang: error: no such file or directory: 'suppress'
</code>```

I've tried removing the following files incase it was some generated code that was causing the issues

```<code>Pods/
project.xcworkspace
pods.lockfile
</code>```

and re-running pod install to re-generate the workspace and config files. The error is still appearing!

答:
I ran into something similar today with a Cocoapod project after removing it from the podfile. for some reason my workspace still had reference to the framework (now removed) so i manually deleted the references from my Build Settings > Other Linker Flags.

I got this error afterwards and the issue was in the Other Linker Flags it had -framework and on the next line it had -framework again. When i manually deleted the framework i did not remove the corresponding -framework line above it so two -framework lines were in the adjacent rows and it couldn't find the next framework (imported from CocoaPods).

Hope this helps someone some day.

Body:
I'm getting a clang error when my project tries to link.

I can see the following flags in the Pods.debug.xcconfig and Pods.release.xcconfig

-undefined dynamic_lookup suppress

And then the error appears in issue navigator

clang: error: no such file or directory: 'dynamic_lookup'
clang: error: no such file or directory: 'suppress'

I've tried removing the following files incase it was some generated code that was causing the issues

Pods/
project.xcworkspace
pods.lockfile

and re-running pod install to re-generate the workspace and config files. The error is still appearing!


问:
Cascading parameters in SSRS reports doesn't work with one parameter value set to a default value
I'm trying to run an SSRS report with cascading parameters.
I have 2 parameters para1, para2.
I have made para1 as a hidden field and assigned para1 a default value.
I have set para2 to take available values from a dataset.
I'm trying to populate para2 drop-down based on para1's default value.
My query for populating para2 is

SELECT column2 FROM TABLENAME
WHERE (column1 = @para1)

(here column1, column2 from Database refer to respective para1, para2 parameters in report)

I have my query working fine with the database and I see filtered result but gives me an error when I click preview on BIDS.

Error:
The report parameter ‘para2’ has a DefaultValue or a ValidValue that depends on the report parameter “para1”. Forward dependencies are not valid.

I'm unable to figure out where I'm going wrong. Please help me find my mistake. Thank you.

答:
Change the order of your parameters in the parameter list.

On the menu bar click View>Report Data

Then highlight one of the parameters and click the up or down arrow (depending on the highlighted param)

The up and down arrows are located at the top of the Report Data list. You should end up with Para1 being above Para2 in the parameters list.


问:
Laravel 5: Check for Specific Error
I have Password and Confirm Password inputs. I have coded these inputs so that in the event of an error the inputs highlight, like so:

```<code><div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}>
    <label>Password</label>
    <input type="password" name="password" class="form-control">
</div>

<div class="form-group {{ $errors->has('password_confirmation') ? 'has-error' : '' }}>
    <label>Password</label>
    <input type="password" name="password_confirmation" class="form-control">
</div>
</code>```

In my Controller, I validate these inputs as follows:

```<code>$this->validate($request, [
    ....
    'password'                 => 'required|min:8|confirmed',
    'password_confirmation'    => 'required',
    ....
]);
</code>```

When either input is null and/or less than 8 characters, the inputs highlight as expected. However, when the inputs don't match, I would logically expect the Confirm Password input to highlight. However, it is the Password field that highlights, because that is the input that the "confirmed" rule is set to.

The "$errors->has()" method simply checks if an error exists for an input. Is there a way to check if an input has a specific kind of error?

答:
Yes, you can get the array of errors for a given input name by using:

```<code>{{ $errors->get('password') }}
</code>```

So you can check if the password errors array has the confirmation error and then add the additional class to your confirmation input field:

```<code> @if (in_array(trans('validation.confirmed', ['attribute' => 'password']), $errors->get('password'))) has-error @endif
</code>```

And the helper methods may vary between Laravel versions:

Laravel < 5.4: trans('validation.confirmed', ['attribute' => 'password'])

Laravel 5.4: __('validation.confirmed', ['attribute' => 'password'])

Title: Laravel 5: Check for Specific Error

Body:
I have Password and Confirm Password inputs. I have coded these inputs so that in the event of an error the inputs highlight, like so:

has('password') ? 'has-error' : '' }}>
    Password
    <input type="password" name="password" class="form-control">

has('password_confirmation') ? 'has-error' : '' }}>
    Password
    <input type="password" name="password_confirmation" class="form-control">

In my Controller, I validate these inputs as follows:

$this->validate($request, [
    ....
    'password'                 => 'required|min:8|confirmed',
    'password_confirmation'    => 'required',
    ....
]);

When either input is null and/or less than 8 characters, the inputs highlight as expected. However, when the inputs don't match, I would logically expect the Confirm Password input to highlight. However, it is the Password field that highlights, because that is the input that the "confirmed" rule is set to.

The "$errors->has()" method simply checks if an error exists for an input. Is there a way to check if an input has a specific kind of error?

Body:
Yes, you can get the array of errors for a given input name by using:

{{ $errors->get('password') }}

So you can check if the password errors array has the confirmation error and then add the additional class to your confirmation input field:

 @if (in_array(trans('validation.confirmed', ['attribute' => 'password']), $errors->get('password'))) has-error @endif

And the helper methods may vary between Laravel versions:

Laravel < 5.4: trans('validation.confirmed', ['attribute' => 'password'])

Laravel 5.4: __('validation.confirmed', ['attribute' => 'password'])


问:
Changes to DataGridView aren't being reflected in database
I have a DataGridView control and a save button. When the Save button is clicked, I want any changes made to the DataGridView to be reflected in my database via a DataAdapter Update() command. However, after hitting the save button and reloading the form, the updates are not there.

Here is all the code for the Save button currently:

```<code>private void btnSave_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=addtool.database.windows.net;Initial Catalog=AddToolToInventoryDB;User id=kanerbw; Password=Rabaraba!11;");
        DataTable dt = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
        SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);

        con.Open();
        SqlCommandBuilder scb = new SqlCommandBuilder(adapter);
        myBuilder.GetUpdateCommand();
        adapter.UpdateCommand = myBuilder.GetUpdateCommand();
        adapter.Update(dt);
        con.Close();
    }
</code>```

EDIT: I had forgotten to set the datasource of my DGV to the datatable. Here's the working code:

```<code>private void btnSave_Click(object sender, EventArgs e)
    {
        using (var con = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
            SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);

            dgvProductInfo.DataSource = dt;

            adapter.UpdateCommand = myBuilder.GetUpdateCommand();
            adapter.Update(dt);

            dt.Clear();
            adapter.Fill(dt);
        }
    }
</code>```

答:
Your code has several problems:

You are not enclosing the SQLConnection in a using statement. You should always use this pattern so that the connection is properly disposed: using(var connection = new SqlConnection(...)){ rest of statements here }

On the btnSave_Click function, you are getting the data again from the database -see the select * from tbl... code- and you are populating the DataTable again; therefore, it's obvious that there won't be any changes reflected. What you need to do instead is read the Updated DataTable from the page and use it inside the btnSave_Click function to push the updates to the database.

Your question refers to DataGridView which I believe is a User Control on WinForms, but your question is tagged as ASP.NET. Are you referring to a GridView control instead? Either way, both controls should have a way of getting the DataSource bound to them. You should be able to use that DataSource to push the updates to the database.

I hope this pointers are helpful. I cannot be more specific given the code you provided in your question.

Body:
I have a DataGridView control and a save button. When the Save button is clicked, I want any changes made to the DataGridView to be reflected in my database via a DataAdapter Update() command. However, after hitting the save button and reloading the form, the updates are not there.

Here is all the code for the Save button currently:

private void btnSave_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=addtool.database.windows.net;Initial Catalog=AddToolToInventoryDB;User id=kanerbw; Password=Rabaraba!11;");
        DataTable dt = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
        SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);

        con.Open();
        SqlCommandBuilder scb = new SqlCommandBuilder(adapter);
        myBuilder.GetUpdateCommand();
        adapter.UpdateCommand = myBuilder.GetUpdateCommand();
        adapter.Update(dt);
        con.Close();
    }

EDIT: I had forgotten to set the datasource of my DGV to the datatable. Here's the working code:

private void btnSave_Click(object sender, EventArgs e)
    {
        using (var con = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
            SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);

            dgvProductInfo.DataSource = dt;

            adapter.UpdateCommand = myBuilder.GetUpdateCommand();
            adapter.Update(dt);

            dt.Clear();
            adapter.Fill(dt);
        }
    }


问:
How does the StringBuilder decide how large its capacity should be?
I know that the StringBuilder object allocates more memory when you use sb.Append(..) when the sb is already at capacity. But how much does that capacity increase?

```<code>    StringBuilder sb = new StringBuilder(5);
    sb.Append("0123456789");
</code>```

Now what is the capacity of sb and why? What is the multiplier?

Just for clarity. I am asking about capacity and not length.

Thanks!

答:
The capacity doubles each time apart from some special cases:

If doubling is not enough then the capacity is further increased to the exact amount that is required.

There is an upper limit - 0x7fffffff.

You can see the algorithm by using .NET Reflector or downloading the reference source.

I can't post the source code for the official .NET implementation but here's the code for the Mono implementation:

```<code>// Try double buffer, if that doesn't work, set the length as capacity
if (size > capacity) {

    // The first time a string is appended, we just set _cached_str
    // and _str to it. This allows us to do some optimizations.
    // Below, we take this into account.
    if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
        capacity = constDefaultCapacity;

    capacity = capacity << 1;  // This means "capacity *= 2;"

    if (size > capacity)
        capacity = size;

    if (capacity >= Int32.MaxValue || capacity < 0)
        capacity = Int32.MaxValue;

    if (capacity > _maxCapacity && size <= _maxCapacity)
        capacity = _maxCapacity;
}
</code>```

I would also recommend that you don't write code that relies on this specific algorithm as it is an implementation detail, and not something that is guaranteed by the interface.

Body:
I know that the StringBuilder object allocates more memory when you use sb.Append(..) when the sb is already at capacity. But how much does that capacity increase?

    StringBuilder sb = new StringBuilder(5);
    sb.Append("0123456789");

Now what is the capacity of sb and why? What is the multiplier?

Just for clarity. I am asking about capacity and not length.

Thanks!

Body:
The capacity doubles each time apart from some special cases:

If doubling is not enough then the capacity is further increased to the exact amount that is required.

There is an upper limit - 0x7fffffff.

You can see the algorithm by using .NET Reflector or downloading the reference source.

I can't post the source code for the official .NET implementation but here's the code for the Mono implementation:

// Try double buffer, if that doesn't work, set the length as capacity
if (size > capacity) {

    // The first time a string is appended, we just set _cached_str
    // and _str to it. This allows us to do some optimizations.
    // Below, we take this into account.
    if ((object) _cached_str == (object) _str && capacity < constDefaultCapacity)
        capacity = constDefaultCapacity;

    capacity = capacity << 1;  // This means "capacity *= 2;"

    if (size > capacity)
        capacity = size;

    if (capacity >= Int32.MaxValue || capacity < 0)
        capacity = Int32.MaxValue;

    if (capacity > _maxCapacity && size <= _maxCapacity)
        capacity = _maxCapacity;
}

I would also recommend that you don't write code that relies on this specific algorithm as it is an implementation detail, and not something that is guaranteed by the interface.


问:
Draftjs trying to remove an atomic block
I am trying to remove an atomic block from the draftjs editor with Modifier.removeRange. From what I can tell I am passing in all the right arguments, but the SelectionState for removal never gets removed.
Here is my code. This also adds in a new atomic block. That part works fine, it's the removal aspect that returns the same contentState that i pass in.

upload_block_selection_state is the SelectionState object for removal. This object is obtained from editorState.getSelection() when it is rendered. It looks like this.

```<code>upload_block_selection_state = {
 anchorKey: "c1kpk",
 anchorOffset: 0,
 focusKey: "c1kpk",
 focusOffset: 0,
 isBackward: false
}
</code>```

and here is the function that should both remove the upload block and then add a new block. Adding works, removal does nothing.

```<code>function addAndRemoveMediaBlock(
    entityURL,
    entityType,
    editorState,
    setEditorState,
    upload_block_selection_state
){
    const contentBeforeAtomicBlock      = editorState.getCurrentContent();
    const contentAfterSelectionRemoval  = Modifier.removeRange(
        contentBeforeAtomicBlock,
        upload_block_selection_state,
        'forward'
    );

    const contentStateWithEntity        = contentAfterSelectionRemoval.createEntity(entityType, 'IMMUTABLE', { src: entityURL });
    const entityKey                     = contentStateWithEntity.getLastCreatedEntityKey();
    const editorStateAfterAtomicBlock   = AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        entityKey
    );

    /*
        below here relevant only to removing the empty block.
        */
    const selectionStateBeforeAtomicBlock = editorState.getSelection();
    const anchorKeyBeforeAtomicBlock      = selectionStateBeforeAtomicBlock.getAnchorKey();
    const contentAfterAtomicBlock         = editorStateAfterAtomicBlock.getCurrentContent();
    const blockSelectedBefore             = contentAfterAtomicBlock.getBlockForKey(anchorKeyBeforeAtomicBlock);

    const finalEditorState = (() => {
        if(blockSelectedBefore.getLength() === 0){
            const keyBefore                    = blockSelectedBefore.getKey();
            const newBlockMap                  = contentAfterAtomicBlock.blockMap.delete(keyBefore);
            const contentWithoutEmptyBlock     = contentAfterAtomicBlock.set('blockMap', newBlockMap);
            const editorStateWithoutEmptyBlock = EditorState.push(editorStateAfterAtomicBlock, contentWithoutEmptyBlock, 'remove-block');
            return EditorState.forceSelection(editorStateWithoutEmptyBlock, contentWithoutEmptyBlock.getSelectionAfter());
        }else{
            return editorStateAfterAtomicBlock;
        }
    })();
    setEditorState({
        editorState: finalEditorState,
    });
};
</code>```

答:
I figured it out. </p>

```<code>const contentAfterSelectionRemoval  = contentBeforeAtomicBlock.blockMap.delete(blockToRemoveKey);
</code>```

<p>This seems like an anti-pattern within an Immutable state so I ended up approaching the problem from another angle and didn't actually use this working solution. </p>

Body:
I am trying to remove an atomic block from the draftjs editor with Modifier.removeRange. From what I can tell I am passing in all the right arguments, but the SelectionState for removal never gets removed.
Here is my code. This also adds in a new atomic block. That part works fine, it's the removal aspect that returns the same contentState that i pass in.

upload_block_selection_state is the SelectionState object for removal. This object is obtained from editorState.getSelection() when it is rendered. It looks like this.

upload_block_selection_state = {
 anchorKey: "c1kpk",
 anchorOffset: 0,
 focusKey: "c1kpk",
 focusOffset: 0,
 isBackward: false
}

and here is the function that should both remove the upload block and then add a new block. Adding works, removal does nothing.

function addAndRemoveMediaBlock(
    entityURL,
    entityType,
    editorState,
    setEditorState,
    upload_block_selection_state
){
    const contentBeforeAtomicBlock      = editorState.getCurrentContent();
    const contentAfterSelectionRemoval  = Modifier.removeRange(
        contentBeforeAtomicBlock,
        upload_block_selection_state,
        'forward'
    );

    const contentStateWithEntity        = contentAfterSelectionRemoval.createEntity(entityType, 'IMMUTABLE', { src: entityURL });
    const entityKey                     = contentStateWithEntity.getLastCreatedEntityKey();
    const editorStateAfterAtomicBlock   = AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        entityKey
    );

    /*
        below here relevant only to removing the empty block.
        */
    const selectionStateBeforeAtomicBlock = editorState.getSelection();
    const anchorKeyBeforeAtomicBlock      = selectionStateBeforeAtomicBlock.getAnchorKey();
    const contentAfterAtomicBlock         = editorStateAfterAtomicBlock.getCurrentContent();
    const blockSelectedBefore             = contentAfterAtomicBlock.getBlockForKey(anchorKeyBeforeAtomicBlock);

    const finalEditorState = (() => {
        if(blockSelectedBefore.getLength() === 0){
            const keyBefore                    = blockSelectedBefore.getKey();
            const newBlockMap                  = contentAfterAtomicBlock.blockMap.delete(keyBefore);
            const contentWithoutEmptyBlock     = contentAfterAtomicBlock.set('blockMap', newBlockMap);
            const editorStateWithoutEmptyBlock = EditorState.push(editorStateAfterAtomicBlock, contentWithoutEmptyBlock, 'remove-block');
            return EditorState.forceSelection(editorStateWithoutEmptyBlock, contentWithoutEmptyBlock.getSelectionAfter());
        }else{
            return editorStateAfterAtomicBlock;
        }
    })();
    setEditorState({
        editorState: finalEditorState,
    });
};

Body:
I figured it out.

const contentAfterSelectionRemoval  = contentBeforeAtomicBlock.blockMap.delete(blockToRemoveKey);

This seems like an anti-pattern within an Immutable state so I ended up approaching the problem from another angle and didn't actually use this working solution.


问:
Incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Am trying to pass a List<> from an activity to a fragment.

When an imageView is clicked; the onClick event triggers a call to the server that takes the userId of the user that clicked on the imageView and the userId of the users profile you want to see.i have an interface that  that takes the response gotten from the server, which is then sent to a new fragment class. The problem am having is that i cannot pass a List<> through the bundle.

This is the newInstance of the fragment class and the parameter am trying to send across

```<code>  public static HomeUserProfileFragment newInstance(String postTotal, String followersTotal
        , String followingTotal, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putStringArrayList(UPLOAD_POST_LIST,uploadPostList);
    args.putStringArrayList(FOLLOWERS_LIST,followersList);
    args.putStringArrayList(FOLLOWING_LIST, followingList);
    fragment.setArguments(args);
    return fragment;
}
</code>```

While this is the the Activity class that the Above Fragment is been called from.

```<code> @Override
public void onClickUserProfile(String post, String followers, String following, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}
</code>```

So am getting the following errors:

```<code>Error:(56, 50) error: incompatible types: List<UploadPost> cannot be converted to ArrayList<String>
Error:(57, 48) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Error:(58, 49) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
</code>```

答:
That's because you have Lists which are not ArrayLists.

A solution might be to wrap your list into an ArrayList with one of its constructors:

```<code>args.putStringArrayList(UPLOAD_POST_LIST, new ArrayList<>(uploadPostList));
</code>```

Body:
Am trying to pass a List<> from an activity to a fragment.

When an imageView is clicked; the onClick event triggers a call to the server that takes the userId of the user that clicked on the imageView and the userId of the users profile you want to see.i have an interface that  that takes the response gotten from the server, which is then sent to a new fragment class. The problem am having is that i cannot pass a List<> through the bundle.

This is the newInstance of the fragment class and the parameter am trying to send across

  public static HomeUserProfileFragment newInstance(String postTotal, String followersTotal
        , String followingTotal, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putStringArrayList(UPLOAD_POST_LIST,uploadPostList);
    args.putStringArrayList(FOLLOWERS_LIST,followersList);
    args.putStringArrayList(FOLLOWING_LIST, followingList);
    fragment.setArguments(args);
    return fragment;
}

While this is the the Activity class that the Above Fragment is been called from.

 @Override
public void onClickUserProfile(String post, String followers, String following, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}

So am getting the following errors:

Error:(56, 50) error: incompatible types: List<UploadPost> cannot be converted to ArrayList<String>
Error:(57, 48) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Error:(58, 49) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>

Body:
That's because you have Lists which are not ArrayLists.

A solution might be to wrap your list into an ArrayList with one of its constructors:

args.putStringArrayList(UPLOAD_POST_LIST, new ArrayList<>(uploadPostList));


问:
How to segment individual cells from a medical image using Python/OpenCV?
So I am trying to segment individual cells from a loaded image using Python/OpenCV. My code currently is able to mask the cells, but I would like to segment individual cells and save them as separate images.

So the output would be one of those single cells you see in the above (purposes for downstream use with 2D convnet)

```<code>img_dir = '/path'
img = cv2.imread(img_dir, 0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') # swap hot
for gray

# draw a contour image with fixed threshold 50
fig = plt.figure()
ax = fig.add_subplot(111)
ax.contourf(img, levels=[0, 10, 20, 30,  40, 50, 60, 70, 80, 120],
colors='k')
plt.show()

res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation =
cv2.INTER_CUBIC)
</code>```

答:
Actually in this problem, segmentation is the process of separating the cells from the background which you already accomplished.

Being left with a binary image you have to perform a blob detection.
After optionally filtering out everything that is of unwanted size or shape you are left with a list of blobs, each representing a cell I guess.

http://docs.opencv.org/trunk/dd/d49/tutorial_py_contour_features.html

https://www.learnopencv.com/blob-detection-using-opencv-python-c/

You then compute the so bounding rect of each of those blobs and use that rectangle to create a roi to crop the subimages.

How to crop an image in OpenCV using Python

Body:
So I am trying to segment individual cells from a loaded image using Python/OpenCV. My code currently is able to mask the cells, but I would like to segment individual cells and save them as separate images.

So the output would be one of those single cells you see in the above (purposes for downstream use with 2D convnet)

img_dir = '/path'
img = cv2.imread(img_dir, 0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') # swap hot
for gray

# draw a contour image with fixed threshold 50
fig = plt.figure()
ax = fig.add_subplot(111)
ax.contourf(img, levels=[0, 10, 20, 30,  40, 50, 60, 70, 80, 120],
colors='k')
plt.show()

res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation =
cv2.INTER_CUBIC)


问:
Setting NAs with zeros in matrix with lapply seems does not work well?
I have these matrices.

```<code>matr <- list()

matr[[i]] <- c(0, NA, 3, 4, 4,
            0, 0, 3, 4, 1,
            0, 0, 0, NA, 1,
            0, 0, NA, 0, 3,
            0, 0, 0, 0, 0)
matr[[i]] <- matrix(matr[[i]], 5, 5)
</code>```

I want to set NA to zero using the following code:

```<code>x <- lapply(matr,function(x) x[is.na(x) <- 0])
</code>```

Then I got this result:

```<code>> x
[[1]]
numeric(0)

[[2]]
numeric(0)

[[3]]
numeric(0)
</code>```

Why it does not return the matrices? Is my code correct? any help please?

答:
Since lapply works on lists and return lists I think that isn't what you want.
I think using apply here fits better.

Try x <- apply(matr[[1]], 2, function(x){
       x[is.na(x)] <- 0
       x
})

The number 2 here indicates that you want to operate column-wise instead of row-wise (1st margin are rows, and 2nd margin are columns).

Also notice that you had put the <- operator within the brackets which was a wrong sintax.

EDIT:

It seems that I have misunderstood your question.
Here follows a code that works for an entire list:

lapply(matr, function(x){
  apply(x, 2, function(y){
    y[is.na(y)] <- 0
    y
  })
})

Body:
I have these matrices.

matr <- list()

matr[[i]] <- c(0, NA, 3, 4, 4,
            0, 0, 3, 4, 1,
            0, 0, 0, NA, 1,
            0, 0, NA, 0, 3,
            0, 0, 0, 0, 0)
matr[[i]] <- matrix(matr[[i]], 5, 5)

I want to set NA to zero using the following code:

x <- lapply(matr,function(x) x[is.na(x) <- 0])

Then I got this result:

> x
[[1]]
numeric(0)

[[2]]
numeric(0)

[[3]]
numeric(0)

Why it does not return the matrices? Is my code correct? any help please?


问:
Applying css margin to content before images
I have text content and images mixed and want to apply css margin to elements directly before and after images (
, ,  can come before or after the image, but I have no control on which one and where)

I am using the following code to apply margin to the elements before the image

```<code>#single-pg * + img { margin-top: 75px; }
</code>```

Problem is that it adds the margin-top to other images aswell (I want it to apply to all elements EXCEPT images) and I want to add similar to affect content elements after the image

```<code>#single-pg img + * { margin-bottom: 75px; }
</code>```

html (Wordpress)

```<code><div id="single-pg" >
    <?php the_content(); ?>
</div>
</code>```

so the outcome could be (but could also be in any other order based on the author)

```<code><h2>Title</h2>
<image></image>
<image<</image>
<p>text</p>
<p>text</p>
<p>text</p>
<image<</image>
</code>```

答:
Not entirely clear from your description of the issue (and it's hard without seeing your markup); however, if you want margin-top and margin-bottom to apply to every element except for images, I'd make use of the :not selector.

```<code>:not(img) {
    margin-top: 75px;
    margin-bottom: 75px;
}
</code>```

EDIT

To target the paragraphs in a more nuanced way, we'll have to use some scripting. We can use the adjacent sibling selector to add our margin-top value:

```<code>img + p {
  margin-top:75px;
}
</code>```

and then we can use the jQuery .prev() method to target the paragraph immediately preceding each image:

```<code>$("img").prev().css("margin-bottom", "75px");
</code>```

Here is an updated fiddle of an example in action. Let me know if that helps.

Body:
I have text content and images mixed and want to apply css margin to elements directly before and after images (
, ,  can come before or after the image, but I have no control on which one and where)

I am using the following code to apply margin to the elements before the image

#single-pg * + img { margin-top: 75px; }

Problem is that it adds the margin-top to other images aswell (I want it to apply to all elements EXCEPT images) and I want to add similar to affect content elements after the image

#single-pg img + * { margin-bottom: 75px; }

html (Wordpress)

    <?php the_content(); ?>

so the outcome could be (but could also be in any other order based on the author)

Title

<image></image>
<image<</image>

text

text

text

<image<</image>

Body:
Not entirely clear from your description of the issue (and it's hard without seeing your markup); however, if you want margin-top and margin-bottom to apply to every element except for images, I'd make use of the :not selector.

:not(img) {
    margin-top: 75px;
    margin-bottom: 75px;
}

EDIT

To target the paragraphs in a more nuanced way, we'll have to use some scripting. We can use the adjacent sibling selector to add our margin-top value:

img + p {
  margin-top:75px;
}

and then we can use the jQuery .prev() method to target the paragraph immediately preceding each image:

$("img").prev().css("margin-bottom", "75px");

Here is an updated fiddle of an example in action. Let me know if that helps.


问:
How to parse a json having nested json type objects with boost
I have a json which looks like

```<code>{
  "children": [
    {
      "name": "apple",
      "path": "hutchison",
      "state": 16,
      "url": "https://go.gl/",
      "id": "ZXNrb0luZGlh",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "yum"
        }
      ],
      "content": [],
      "createdBy": "00ui3tqahuu6bwMhU0i6",
      "creationDate": 1497348318103,
      "modificationDate": 1499082955407,
      "modifiedBy": "00ui3tqahuu6bwMhU0i6"
    },
    {
      "name": "test",
      "path": "test",
      "state": 13,
      "url": "https://ODE/v0/test",
      "id": "YW5ib3Rlc3Q=",
      "properties": [
        {
          "id": "string",
          "name": "string",
          "propertyType": "string",
          "value": "string"
        }
      ],
      "content": [],
      "createdBy": "00u33355JQXgmzqO90i5",
      "creationDate": 1498463285568,
      "modificationDate": 1498463356176,
      "modifiedBy": "00u33355JQXgmzqO90i5"
    },
    {
      "name": "KE",
      "path": "KE",
      "state": 4,
      "url": "https://full.com/NODE/v0/DEKE",
      "id": "REVLRQ==",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "KE"
        }
      ],
      "content": [],
      "createdBy": "00uy9bswhaVnUggF00i6",
      "creationDate": 1498805345347,
      "modificationDate": 1498805346371,
      "modifiedBy": "00uy9bswhaVnUggF00i6"
    }
]
,
  "name": "",
  "path": "",
  "state": 27,
  "url": "https://go.gl/ODE/v0",
  "id": "ROOT",
  "properties": [],
  "content": [],
  "createdBy": "INITIAL",
  "creationDate": 1497261853581,
  "modificationDate": 1498805345347,
  "modifiedBy": "00uy9bswhaVnUggF00i6"
}
</code>```

I want each and every key-value(s) pair to be traversed once by of course using boost library (any other approach in cpp is also welcomed), to later save them in relevant containers.

答:
The following code snippet traverses each and every key pair and stores it in the relevant collections:

```<code>#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;

int main() {
    ptree pt;
    std::ifstream ifs("input.txt");
    read_json(ifs, pt);
}
</code>```

The collections form a tree. Notably, a Property Tree. This may or may not be what you need, because your objectives weren't given.

Body:
I have a json which looks like

{
  "children": [
    {
      "name": "apple",
      "path": "hutchison",
      "state": 16,
      "url": "https://go.gl/",
      "id": "ZXNrb0luZGlh",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "yum"
        }
      ],
      "content": [],
      "createdBy": "00ui3tqahuu6bwMhU0i6",
      "creationDate": 1497348318103,
      "modificationDate": 1499082955407,
      "modifiedBy": "00ui3tqahuu6bwMhU0i6"
    },
    {
      "name": "test",
      "path": "test",
      "state": 13,
      "url": "https://ODE/v0/test",
      "id": "YW5ib3Rlc3Q=",
      "properties": [
        {
          "id": "string",
          "name": "string",
          "propertyType": "string",
          "value": "string"
        }
      ],
      "content": [],
      "createdBy": "00u33355JQXgmzqO90i5",
      "creationDate": 1498463285568,
      "modificationDate": 1498463356176,
      "modifiedBy": "00u33355JQXgmzqO90i5"
    },
    {
      "name": "KE",
      "path": "KE",
      "state": 4,
      "url": "https://full.com/NODE/v0/DEKE",
      "id": "REVLRQ==",
      "properties": [
        {
          "id": "type",
          "name": "type",
          "propertyType": "string",
          "value": "COMPANY"
        },
        {
          "id": "folderify",
          "name": "folderify",
          "propertyType": "boolean",
          "value": "true"
        },
        {
          "id": "name",
          "name": "name",
          "propertyType": "string",
          "value": "KE"
        }
      ],
      "content": [],
      "createdBy": "00uy9bswhaVnUggF00i6",
      "creationDate": 1498805345347,
      "modificationDate": 1498805346371,
      "modifiedBy": "00uy9bswhaVnUggF00i6"
    }
]
,
  "name": "",
  "path": "",
  "state": 27,
  "url": "https://go.gl/ODE/v0",
  "id": "ROOT",
  "properties": [],
  "content": [],
  "createdBy": "INITIAL",
  "creationDate": 1497261853581,
  "modificationDate": 1498805345347,
  "modifiedBy": "00uy9bswhaVnUggF00i6"
}

I want each and every key-value(s) pair to be traversed once by of course using boost library (any other approach in cpp is also welcomed), to later save them in relevant containers.

Body:
The following code snippet traverses each and every key pair and stores it in the relevant collections:

#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;

int main() {
    ptree pt;
    std::ifstream ifs("input.txt");
    read_json(ifs, pt);
}

The collections form a tree. Notably, a Property Tree. This may or may not be what you need, because your objectives weren't given.


答:
To call BaseFactory.UpdateDataBase_static(); you need a class BaseFactory. Inherite the generic BaseFactory<T> from it.

```<code>public abstract class BaseFactory
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

public abstract class BaseFactory<T>:BaseFactory where T: class
{
    ....
}
</code>```

Title: Using static method from generic class

Body:
I have problem as above. My code:

public abstract class BaseFactory<T> where T: class
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

and my question is how can I call

BaseFactory.UpdateDataBase_static();

instead of:

BaseFactory<SomeClass>.UpdateDataBase_static();

Any ideas?

Body:
To call BaseFactory.UpdateDataBase_static(); you need a class BaseFactory. Inherite the generic BaseFactory<T> from it.

public abstract class BaseFactory
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

public abstract class BaseFactory<T>:BaseFactory where T: class
{
    ....
}


问:
CSS: Liquid Bar with Text Won't Expand
I have a horizontal bar that has been given a width of 100%. Within the horizontal bar, I have text that is left-aligned within a 978px container.  Whenever the browser window is shrunk so that it is less than 978px wide, a scrollbar along the bottom of the page appears.  Whenever I scroll to the right, the bar no longer spans the width of the page but instead, is left behind.  I understand why this happens, but I don't know what to do to fix it.  If you have any ideas, let me know.  Thank you!

An example page

答:
Change:

```<code>width: 978px;
</code>```

to:

```<code>max-width: 978px
</code>```

That seemed to do the trick in FF3, IE7 and chrome.

OwnerDisplayName: John

Title: CSS: Liquid Bar with Text Won't Expand

Body:
Change:

width: 978px;

to:

max-width: 978px

That seemed to do the trick in FF3, IE7 and chrome.

OwnerDisplayName: Chris Missal


问:
Working with block special files/devices to implement a filesystem
I've implemented a basic filesystem using FUSE, with all foreseeable POSIX functionality implemented [naturally I haven't even profiled yet ;)]. Currently I'm able to run the filesystem on a regular file (st_mode & S_IFREG), but the next step in development is to host it on an actual block device. Running my code as is, immediately fails on reading st_size after calling fstat on the device. Of course I don't expect the problems to stop there so:

What changes are required to operate on block devices as opposed to regular files?

What are some special considerations I need to make with regard to performance, limitations, special features and the like?

Are there any tutorials and references with dealing with block special files? Googling has turned up very little useful; I only have background knowledge (ironically from MSDN in my dark past) and some scanty information in the manpages.

Update0

I've pointed out what I mean by "regular file".

I don't want to concentrate on getting the device size, I want general guidelines for differences between regular files and device files with respect to performance and usage.

答:
Currently I'm able to run the
  filesystem on a regularly file, but
  the next step in development is to
  host it on an actual block device

I don't completely understand what you mean - I assume you are saying that "you currently save your filesystem data to a plain file on a normally mounted filesystem - but now wish to use a raw block device for your data storage".

If so - having done this a few times - I'd advise the following:

Never use an "actual" block device for you filesystem. Always use a partition. There are several rarely-used partition-types that you can use to denote that such a filesystem may be your filesystem type, and that your filesystem can check and mount it if it is such. Thus, you will never be running on something like "/dev/sdb", but rather you will store you data on one such as /dev/sdb1, and assign it some partition type. This has obvious advantages, like allowing your filesystem to be co-resident on a single phyiscal disk as another, etc.

If you are implementing any caching in your filesystem (like Linux does with the Page Cache), do all I/Os to the block devices with O_DIRECT. This requires you to pass page-alligned memory to do all I/O, and requires that the requests be sector/block aligned - but will remove a data copy which would otherwise be required when data is moved from the block device to the page cache, then from the page-cache to your user-space [filesystem] reader.

What do you mean that the fstat "fails"? This is an fstat trying to determing the length of the block device? Do you receive an error? What is it?


答: You need to JOIN these tables instead of doing a UNION. The former will put columns side by side, whereas the latter will stack two similar sources together...

Title: Bring information from 2 tables and put it in the same column

Body:
I have this table of articles

---------------------------------------------
|   Article   |   Location    | existence   |
---------------------------------------------
|     200116    |   cc3111      |   1       |
---------------------------------------------
|     200116    |   ee3091      |       1   |
---------------------------------------------

And this count table

----------------------------------------------------
|   Article   |   Location     |   Quantity      |
----------------------------------------------------
|     200116    |   cc3111       |   10            |
----------------------------------------------------
|     200116    |   EE3091       |   8             |
----------------------------------------------------
|     200116    |   EE2102       |   5             |
----------------------------------------------------
|     200116    |   DD5131       |   7             |
----------------------------------------------------

What I'm trying to do is give me one result like the next.

--------------------------------------------------------------------------
|   Article   |   Location    | Existence      |  Quantity |   DIF      |
--------------------------------------------------------------------------
|     200116  |   CC3111      |     1          |     10    |     9       |
--------------------------------------------------------------------------
|     200116  |   EE3091      |     1          |     8     |      7      |
--------------------------------------------------------------------------
|     200116  |   DD5131      |     0          |    7      |     7       |
--------------------------------------------------------------------------
|     200116  |   EE2102      |     0          |    5      |     5      |
----------------------------- -------------------------------------------

But without doing it with a Union since then I have to make another query, I just do not know how to join it without usingUnion.

-SOME HELP TO PERFORM THIS QUERY

-I do not know how to add the location in the same column


答:
This looks like a left join:

```<code>select t2.*, coalesce(t1.existence, 0) as existence,
       (t2.quantity - coalesce(t1.existence, 0)) as dif
from t2 left join
     t1
     on t2.article = t1.article and t2.location = t1.location;
</code>```

Body:
This looks like a left join:

select t2.*, coalesce(t1.existence, 0) as existence,
       (t2.quantity - coalesce(t1.existence, 0)) as dif
from t2 left join
     t1
     on t2.article = t1.article and t2.location = t1.location;


问:
Find value located in the last record using VBA
I know this has probably been asked thousands of times before, but I seem to be having trouble finding an existing question that addresses this question in a wy I can understand.

My question in how can I access a value located in the last record of a table? For example, if this is my table:

```<code>personID personName personNumber
1        Sally      PR32
2        Emily      PR33
3        Joseph     PR34
</code>```

I want to access the value "PR34" (and then be able to manipulate it if possible). I know how to find the last record with Dmax, but I'm struggling to figure out how to find a value within it. I'm ultimately trying to take the value, parse the string down to just the numbers, and increment it by one (and then append the letters back on).

答:
If you're in the DLookUp/DMax workflow, you can just use the following:

This gives you the ID, you already figured this out:

```<code>DMax("PersonID", "MyTable")
</code>```

Then lookup the associated personNumber with that ID:

```<code>DLookUp("personNumber", "MyTable", "personID = " & DMax("PersonID", "MyTable"))
</code>```

But if you want to manipulate it (or just be more efficient), using a recordset is the way to go:

```<code>'Create a recordset
Dim rs As Recordset
'Query the last value, get the personNumber
Set rs = CurrentDb.OpenRecordset("SELECT TOP 1 personNumber FROM MyTable ORDER BY personID DESC")
'Open it up for editing
rs.Edit
'Increment the number by 1
rs.Fields("personNumber").Value = Left(rs.Fields("personNumber").Value, 2) & CInt(Mid(rs.Fields("personNumber").Value, 3, Len(rs.Fields("personNumber").Value) - 2)) + 1
'Update the recordset
rs.Update
</code>```

Body:
I know this has probably been asked thousands of times before, but I seem to be having trouble finding an existing question that addresses this question in a wy I can understand.

My question in how can I access a value located in the last record of a table? For example, if this is my table:

personID personName personNumber
1        Sally      PR32
2        Emily      PR33
3        Joseph     PR34

I want to access the value "PR34" (and then be able to manipulate it if possible). I know how to find the last record with Dmax, but I'm struggling to figure out how to find a value within it. I'm ultimately trying to take the value, parse the string down to just the numbers, and increment it by one (and then append the letters back on).

Body:
If you're in the DLookUp/DMax workflow, you can just use the following:

This gives you the ID, you already figured this out:

DMax("PersonID", "MyTable")

Then lookup the associated personNumber with that ID:

DLookUp("personNumber", "MyTable", "personID = " & DMax("PersonID", "MyTable"))

But if you want to manipulate it (or just be more efficient), using a recordset is the way to go:

'Create a recordset
Dim rs As Recordset
'Query the last value, get the personNumber
Set rs = CurrentDb.OpenRecordset("SELECT TOP 1 personNumber FROM MyTable ORDER BY personID DESC")
'Open it up for editing
rs.Edit
'Increment the number by 1
rs.Fields("personNumber").Value = Left(rs.Fields("personNumber").Value, 2) & CInt(Mid(rs.Fields("personNumber").Value, 3, Len(rs.Fields("personNumber").Value) - 2)) + 1
'Update the recordset
rs.Update


问:
Class not found: Empty test suite when running unit tests in Android Studio
I have a test suite for my Android app, and all unit tests run fine. However, whenever I make a single change in one of my unit test classes (for example, ModelUnitTests), when trying to run that class again, I get this message

```<code>Process finished with exit code 1
Class not found: "xxx.xxxxxx.xxx.ModelUnitTests"Empty test suite.
</code>```

If I do a gradle clean and then run the class tests again, it runs fine (but it takes 4 minutes to do...), but then a new change will break it again.

Any advice on how to fix this? I'm not exactly sure which test configuration should I post. I'm using the Unit Tests artifact and my tests are located on the
module/src/test/package folder

答:
If you are working on a team, check all your build.gradle files to make sure nobody is disabling the test tasks. I had the 'empty test suite' error and eventually found it was caused by the following in build.gradle at the project root:

```<code>gradle.taskGraph.whenReady {
    tasks.each { task ->
        if (task.name.contains("Test"))
        {
            task.enabled = false
        }
    }
}
</code>```

Body:
I have a test suite for my Android app, and all unit tests run fine. However, whenever I make a single change in one of my unit test classes (for example, ModelUnitTests), when trying to run that class again, I get this message

Process finished with exit code 1
Class not found: "xxx.xxxxxx.xxx.ModelUnitTests"Empty test suite.

If I do a gradle clean and then run the class tests again, it runs fine (but it takes 4 minutes to do...), but then a new change will break it again.

Any advice on how to fix this? I'm not exactly sure which test configuration should I post. I'm using the Unit Tests artifact and my tests are located on the
module/src/test/package folder

Body:
If you are working on a team, check all your build.gradle files to make sure nobody is disabling the test tasks. I had the 'empty test suite' error and eventually found it was caused by the following in build.gradle at the project root:

gradle.taskGraph.whenReady {
    tasks.each { task ->
        if (task.name.contains("Test"))
        {
            task.enabled = false
        }
    }
}


问:
Logging level randomly changing and not always writing to file
I have this piece of code to set my logger in Python:

```<code>  #Configure logging
  logging.basicConfig(format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                      datefmt='%m-%d %H:%M',
                      filename= "log.txt",
                      level = logging.getLevelName('DEBUG'))

  print(logging.getLogger().getEffectiveLevel())
</code>```

But the output from the print statement sometimes is this:

```<code>30
</code>```

And other times is this (which is correct):

```<code>10
</code>```

But often even when the the logging level is set to the correct number, it is not logging anything to the file, but other times it works. What do I need to do to make sure my logging level is set correctly?

*Edit: Below is my solution based off the recommendation of @randomir.
**Edit: I had to make a second change where I set the level after I call logging.basicConfig() or else the logging level still was not getting called consistently. The line `logging.getLogger().setLevel(...) now seems to work.

I created a new class: Logger.py.

```<code>import logging

class Logger(object):
   def __init__(self):
     logging.basicConfig(format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                      datefmt='%m-%d %H:%M',
                      filename= "log.txt")

     logging.getLogger().setLevel(logging.getLevelName("DEBUG"))

     print(logging.getLogger().getEffectiveLevel())
</code>```

And now instead of configuring the basic config directly in my startup class I just instantiate the logger class once:

```<code>from Logger import Logger
import logging

class LaunchPython(object):
  #Configure Logging
  Logger()

  logging.info("Application has started")
</code>```

On all subsequent classes that call the logger I just put import logging on the top and then do logging.info(...) or logging.debug(....). There is no need to import the Logger.py class and reinstantiate it.

答:
The logging.basicConfig() creates a root logger for you application (that's a logger with the name root, you can get it with logging.getLogger('root'), or logging.getLogger()).

The trick is that the root logger gets created with defaults (like level=30) on the first call to any logging function (like logging.info()) if it doesn't exist already. So, make sure you call your basicConfig() before any logging in any other part of the application.

You can do that by extracting your logger config to a separate module, like logger.py, and then import that module in each of your modules. Or, if your application has a central entry point, just do the configuration there. Note that the 3rd party functions you call will also create the root logger if it doesn't exist.

Also note, if you application is multi-threaded:

Note
  This function should be called from the main thread before other threads are started. In versions of Python prior to 2.7.1 and 3.2, if this function is called from multiple threads, it is possible (in rare circumstances) that a handler will be added to the root logger more than once, leading to unexpected results such as messages being duplicated in the log.

Body:
I have this piece of code to set my logger in Python:

  #Configure logging
  logging.basicConfig(format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                      datefmt='%m-%d %H:%M',
                      filename= "log.txt",
                      level = logging.getLevelName('DEBUG'))

  print(logging.getLogger().getEffectiveLevel())

But the output from the print statement sometimes is this:

30

And other times is this (which is correct):

10

But often even when the the logging level is set to the correct number, it is not logging anything to the file, but other times it works. What do I need to do to make sure my logging level is set correctly?

*Edit: Below is my solution based off the recommendation of @randomir.
**Edit: I had to make a second change where I set the level after I call logging.basicConfig() or else the logging level still was not getting called consistently. The line `logging.getLogger().setLevel(...) now seems to work.

I created a new class: Logger.py.

import logging

class Logger(object):
   def __init__(self):
     logging.basicConfig(format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                      datefmt='%m-%d %H:%M',
                      filename= "log.txt")

     logging.getLogger().setLevel(logging.getLevelName("DEBUG"))

     print(logging.getLogger().getEffectiveLevel())

And now instead of configuring the basic config directly in my startup class I just instantiate the logger class once:

from Logger import Logger
import logging

class LaunchPython(object):
  #Configure Logging
  Logger()

  logging.info("Application has started")

On all subsequent classes that call the logger I just put import logging on the top and then do logging.info(...) or logging.debug(....). There is no need to import the Logger.py class and reinstantiate it.


问:
Best Practice with jquery functions and ajax
I'm new to ajax and want to best understand how to write my jQuery code so that then a page is called via ajax, my jQuery functions (simple stuff like slideshows and overlays) will still work.

Below is what I'm currently doing to make my jquery work on a stand alone page without ajax.

```<code>$('.microContentWrap').click(function(){

    //perform some functions

});
</code>```

In order to make this same function work when this page has been loaded via ajax, I'm duplicating my code and binding it to a div called "ajax-wrapper" that loads normally on this page. Without this step, the above code was not executing on the ajax page.

```<code>$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});
</code>```

Both of these things work, but is this the most efficient way? Seems repetitive to do this two step process for every single function in my file.

答:
The solution to this was actually very simple, I just didn't understand binding. The problem I was having was that the ajax-wrapper gets destroyed after the microContent comes in. On other non-ajax pages there was no ajax-wrapper which is why I thought there needed to be two functions. By binding to the body, I eliminated the issue.</p>

```<code>$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});
</code>```

Body:
I'm new to ajax and want to best understand how to write my jQuery code so that then a page is called via ajax, my jQuery functions (simple stuff like slideshows and overlays) will still work.

Below is what I'm currently doing to make my jquery work on a stand alone page without ajax.

$('.microContentWrap').click(function(){

    //perform some functions

});

In order to make this same function work when this page has been loaded via ajax, I'm duplicating my code and binding it to a div called "ajax-wrapper" that loads normally on this page. Without this step, the above code was not executing on the ajax page.

$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});

Both of these things work, but is this the most efficient way? Seems repetitive to do this two step process for every single function in my file.

Body:
The solution to this was actually very simple, I just didn't understand binding. The problem I was having was that the ajax-wrapper gets destroyed after the microContent comes in. On other non-ajax pages there was no ajax-wrapper which is why I thought there needed to be two functions. By binding to the body, I eliminated the issue.

$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});