问:
Two line of text and overflow is dotted
Is there any way to display text in two line and overflow is dotted?
I can use

```<code>white-space: nowrap;
text-overflow: ellipsis;
</code>```

But it show the text in one line. I need to show my text in two line and if overflow text then it should show dotted end.

答:
At css set width of element, white-space to pre

div  {
  font-size: 1em;
  display: inline-block;
  width: 2em;
  white-space: pre;
  text-overflow: ellipsis;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>lines of
breaks</div></code>```

Title: Two line of text and overflow is dotted

Body:
Is there any way to display text in two line and overflow is dotted?
I can use

white-space: nowrap;
text-overflow: ellipsis;

But it show the text in one line. I need to show my text in two line and if overflow text then it should show dotted end.

Body:
At css set width of element, white-space to pre

div  {
  font-size: 1em;
  display: inline-block;
  width: 2em;
  white-space: pre;
  text-overflow: ellipsis;
  overflow: hidden;
}

<div>lines of
breaks</div>


来源: stackexchange

问:
Finding the longest substring in alphabetical order from a given string
Ive been working on a question to find the longest substring in alphabetical order from a given string. I have a lot of experience in C++ but am absolutely new to python. Ive written this code

```<code>s = raw_input("Enter a sentence:")

a=0   #start int
b=0   #end integer
l=0   #length
i=0

for i in range(len(s)-1):
    j=i
    if j!=len(s)-1:
    while s[j]<=s[j+1]:
        j+=1
    if j-i>l:  #length of current longest substring is greater than stored substring
        l=j-i
        a=i
        b=j

print 'Longest alphabetical string is ',s[i:j]
</code>```

But I keep on getting this error

```<code>Traceback (most recent call last):
  File "E:/python/alphabetical.py", line 13, in <module>
    while s[j]<=s[j+1]:
IndexError: string index out of range
</code>```

What am I doing wrong here? Again, I am very new to python!

答:
You can use this simple piece of code to achieve what you want</p>

```<code>s = 'kkocswzjfq'
char = ''
temp = ''
found = ''
for letter in s:
    if letter >= char:
        temp += letter
    else:
        temp = letter
    if len(temp) > len(found):
        found = temp
    char = letter
print(found)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ive been working on a question to find the longest substring in alphabetical order from a given string. I have a lot of experience in C++ but am absolutely new to python. Ive written this code

s = raw_input("Enter a sentence:")

a=0   #start int
b=0   #end integer
l=0   #length
i=0

for i in range(len(s)-1):
    j=i
    if j!=len(s)-1:
    while s[j]<=s[j+1]:
        j+=1
    if j-i>l:  #length of current longest substring is greater than stored substring
        l=j-i
        a=i
        b=j

print 'Longest alphabetical string is ',s[i:j]

But I keep on getting this error

Traceback (most recent call last):
  File "E:/python/alphabetical.py", line 13, in <module>
    while s[j]<=s[j+1]:
IndexError: string index out of range

What am I doing wrong here? Again, I am very new to python!

Body:
You can use this simple piece of code to achieve what you want

s = 'kkocswzjfq'
char = ''
temp = ''
found = ''
for letter in s:
    if letter >= char:
        temp += letter
    else:
        temp = letter
    if len(temp) > len(found):
        found = temp
    char = letter
print(found)


问:
HTML5 exiting video fullscreen
I have a HTML5 video with custom controls in normal screen.
Don't have custom controls at full screen.
I just show default controls at full screen.
But when exiting full screen I need to disable default controls.
How do we know whether the video has exited the full screen mode using JavaScript or jQuery?

答:
Here is an updated code as for now (Jun 4th 2017), works on all browsers:</p>

```<code>if (document.exitFullscreen)
    document.exitFullscreen();
else if (document.webkitExitFullscreen)
    document.webkitExitFullscreen();
else if (document.mozCancelFullScreen)
    document.mozCancelFullScreen();
else if (document.msExitFullscreen)
    document.msExitFullscreen();
</code>```

Title: HTML5 exiting video fullscreen

Body:
Here is an updated code as for now (Jun 4th 2017), works on all browsers:

if (document.exitFullscreen)
    document.exitFullscreen();
else if (document.webkitExitFullscreen)
    document.webkitExitFullscreen();
else if (document.mozCancelFullScreen)
    document.mozCancelFullScreen();
else if (document.msExitFullscreen)
    document.msExitFullscreen();


问:
which is better? using cd and execute or using absolute path?
Suppose I would like to do some operation like touch/rmetc  on a specific directory in shell script.
Firstly, I can do cd to that directory and do it.
Secondly, I can use absolute path to do that.

My question is which one will be better in performance perspective? Which one is faster?

答:
You can time it yourself:

```<code>function timeThis {
    n=0
    path="test/a"
    rm $path
    if [[ "$1" == abs ]]; then
        path="$(pwd)/$path"
    fi
    echo "$path"
    while [[ $n -lt 10000 ]]; do
        touch $path
        let n++
    done
}

echo "absolute"
time timeThis abs
echo "relative"
time timeThis rel
</code>```

with this I get:

```<code>absolute

real    0m5.502s
user    0m3.394s
sys 0m2.398s

relative
real    0m5.492s
user    0m3.599s
sys 0m2.373s
</code>```

so it is almost the same for this many iterations on the path I tried

Body:
You can time it yourself:

function timeThis {
    n=0
    path="test/a"
    rm $path
    if [[ "$1" == abs ]]; then
        path="$(pwd)/$path"
    fi
    echo "$path"
    while [[ $n -lt 10000 ]]; do
        touch $path
        let n++
    done
}

echo "absolute"
time timeThis abs
echo "relative"
time timeThis rel

with this I get:

absolute

real    0m5.502s
user    0m3.394s
sys 0m2.398s

relative
real    0m5.492s
user    0m3.599s
sys 0m2.373s

so it is almost the same for this many iterations on the path I tried


问:
I use regex for removing duplicate words in a string
but it remove white space. I don't want to remove white space! What should I do?

Original text

I like like like this movie, it was so so so good good
  good.

Remove duplicates

I likelike this movie, it was soso goodgood.

Here is my code:

```<code> String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1$1");
</code>```

答:
Your code is correct, but you just need to replace $1$1 with $1.

EDIT: It is also mentioned in the comments, by Dawood ibn Kareem.

Body:
but it remove white space. I don't want to remove white space! What should I do?

Original text

I like like like this movie, it was so so so good good
  good.

Remove duplicates

I likelike this movie, it was soso goodgood.

Here is my code:

 String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1$1");


问:
python, stop variable reassignment in every function call?
Assuming:

```<code>def myfunc(x):
    listv  = []
    listv.append(x)
</code>```

is there a keyword to stop a variable (listv) from being reassigned?
Let's suppose that NRA is a keyword:

```<code>def myfunc(x):
    NRA listv  = []
    listv.append(x)
</code>```

...line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

答: Variables in functions are not supposed to be persistent between function calls. Because functions are meant to be reusable codes that can be called from different context in the program. So to your answer, NO! There's no keyword for making a variable declared in function persistent.</p>

OwnerDisplayName: metazord

Body:
Assuming:

def myfunc(x):
    listv  = []
    listv.append(x)

is there a keyword to stop a variable (listv) from being reassigned?
Let's suppose that NRA is a keyword:

def myfunc(x):
    NRA listv  = []
    listv.append(x)

...line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!


问:
iPhone required device capabilities - multi touch
My application requires multi touch, so I was checking the documentation and could't find the property to require multi touch. Do all versions of iOS devices support multi touch or I am missing something?

Thanks in advance

答: There is no need to configure that. Every iOS device in existence (including the first-gen iPhone) supports multi-touch (unless its screen is defective). A pinch gesture, for example, is considered a multi-touch gesture, and is found in built-in apps like Maps and Mobile Safari.</p>

ContentLicense: CC BY-SA 2.5


问:
Data reshape (from vector to array) in R
I want you to help me about R code.

I have an object, M(list & array). Like this.

```<code>object1 <- array(0, c(2,2,2))
M <- list(object1, object1)
</code>```

Then, I want to reshape m(vector) into M structure.

```<code>m <- c(1:16)
</code>```

When M is list & matrix object, I can use 'relist' function. However, I can't use it to array object. How can I reshape m into M structure??

Body:
I want you to help me about R code.

I have an object, M(list & array). Like this.

object1 <- array(0, c(2,2,2))
M <- list(object1, object1)

Then, I want to reshape m(vector) into M structure.

m <- c(1:16)

When M is list & matrix object, I can use 'relist' function. However, I can't use it to array object. How can I reshape m into M structure??

Body:
We can specify the dims in array and use relist

lapply(relist(m, skeleton = M), array, dim(object1))
#[[1]]
#, , 1

#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4

#, , 2

#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8

#[[2]]
#, , 1

#     [,1] [,2]
#[1,]    9   11
#[2,]   10   12

#, , 2

#     [,1] [,2]
#[1,]   13   15
#[2,]   14   16

Or another option is

lapply(setNames(split(m, (seq_along(m)-1) %/% lengths(M)[1]), NULL), array, dim(object1))
#[[1]]
#, , 1

#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4

#, , 2

#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8

#[[2]]
#, , 1

#     [,1] [,2]
#[1,]    9   11
#[2,]   10   12

#, , 2

#     [,1] [,2]
#[1,]   13   15
#[2,]   14   16

NOTE: Both the solutions are one-line solutions


问:
ORA-12537 when invoking bulk Merge - Oracle.ManagedDataAccess.Client
I'm trying to insert/update many records using ArrayBindCount.

It works just fine for 1 and 2 records, but if I try to insert 3 or more I get a ORA-12537 exception.

I'm using Oracle.ManagedDataAccess.dll version 4.121.1.0.
I tried on OracleXE 11g and Oracle Standard 11g too.

This is the sql I'm using:

```<code>MERGE INTO tb_medidor_ene t1
USING (select :pId cd_medidor, :pDate dt_hr_instante, :pValor vl_eneat_del from dual) t2 ON (t1.cd_medidor = t2.cd_medidor and t1.dt_hr_instante = t2.dt_hr_instante)
WHEN MATCHED THEN update set t1.vl_eneat_del = t2.vl_eneat_del, dt_hr_insercao = :pInsertDate
WHEN NOT MATCHED THEN INSERT (t1.cd_medidor, t1.dt_hr_insercao, t1.dt_hr_instante, t1.vl_eneat_del)
VALUES (t2.cd_medidor, :pInsertDate, t2.dt_hr_instante, t2.vl_eneat_del)
</code>```

And this (simplified) code:

```<code>    int num = 3;
    int index;
    var ids = new int[num];
    var insertDates = new DateTime[num];
    var dates = new DateTime[num];
    var values = new double[num];

    for (index = 0; index < num; index++) {
        ids[index] = 1;
        insertDates[index] = DateTime.Now;
        dates[index] = DateTime.Today.AddMinutes(index * 5);
        values[index] = index;
    }
    using (var conn = new OracleConnection(Program.ConnString)) {
        conn.Open();
        using (var command = conn.CreateCommand()) {
            command.ArrayBindCount = num;
            command.CommandText = sql;
            command.BindByName = true;
            command.Parameters.Add(new OracleParameter("pId", ids));
            command.Parameters.Add(new OracleParameter("pInsertDate", insertDates));
            command.Parameters.Add(new OracleParameter("pDate", dates));
            command.Parameters.Add(new OracleParameter("pValor", values));
            command.ExecuteNonQuery();
        }
    }
</code>```

"An unhandled exception of type 'Oracle.ManagedDataAccess.Client.OracleException' occurred in Oracle.ManagedDataAccess.dll"

{"ORA-12537: Biblioteca de Rede: Fim do arquivo"}

Stack trace:

at Oracle.ManagedDataAccess.Client.OracleException.HandleError(OracleTraceLevel level, OracleTraceTag tag, Exception ex)
   at OracleInternal.TTC.TTCExecuteSql.ReceiveExecuteResponse(Accessor[]& defineAccessors, Accessor[] bindAccessors, Boolean bHasReturningParams, SQLMetaData& sqlMetaData, SqlStatementType statementType, Int64 noOfRowsFetchedLastTime, Int32 noOfRowsToFetch, Int32& noOfRowsFetched, Int64& queryId, Int32 longFetchSize, Int32 initialLOBFetchSize, Int64[] scnFromExecution, Boolean& bAllPureInputBinds, DataUnmarshaller& dataUnmarshaller, MarshalBindParameterValueHelper& marshalBindParamsHelper, Boolean bDefineDone)
   at OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteNonQuery(String commandText, OracleParameterCollection paramColl, CommandType commandType, OracleConnectionImpl connectionImpl, Int32 longFetchSize, Int32 lobPrefetchSize, OracleDependencyImpl orclDependencyImpl, Int64[]& scnFromExecution, OracleParameterCollection& bindByPositionParamColl, Boolean& bBindParamPresent, Boolean isFromEF)
   at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()
   at OraclePlayground.Program.Main(String[] args) in c:\dev\way2\DataIn\OraclePlayground\OraclePlayground\Program.cs:line 114
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

答:
I had a similar issue.  Merged items causing a ORA-12537 error.  It was odd because it worked for a while, then did not.  I eventually narrowed it down to null values in a CLOB field.  It would work if only one value of the CLOB was null, but if there was more than one, it would consistently die.  I resolved it by changing it to put a space into the CLOB (even using '' caused an error). Waste of a space, but at least the error is gone.

This seems like a bug to me.  I am running Oracle 11.2.0.3.0 64-bit locally.  Hope this helps...

Body:
I'm trying to insert/update many records using ArrayBindCount.

It works just fine for 1 and 2 records, but if I try to insert 3 or more I get a ORA-12537 exception.

I'm using Oracle.ManagedDataAccess.dll version 4.121.1.0.
I tried on OracleXE 11g and Oracle Standard 11g too.

This is the sql I'm using:

MERGE INTO tb_medidor_ene t1
USING (select :pId cd_medidor, :pDate dt_hr_instante, :pValor vl_eneat_del from dual) t2 ON (t1.cd_medidor = t2.cd_medidor and t1.dt_hr_instante = t2.dt_hr_instante)
WHEN MATCHED THEN update set t1.vl_eneat_del = t2.vl_eneat_del, dt_hr_insercao = :pInsertDate
WHEN NOT MATCHED THEN INSERT (t1.cd_medidor, t1.dt_hr_insercao, t1.dt_hr_instante, t1.vl_eneat_del)
VALUES (t2.cd_medidor, :pInsertDate, t2.dt_hr_instante, t2.vl_eneat_del)

And this (simplified) code:

    int num = 3;
    int index;
    var ids = new int[num];
    var insertDates = new DateTime[num];
    var dates = new DateTime[num];
    var values = new double[num];

    for (index = 0; index < num; index++) {
        ids[index] = 1;
        insertDates[index] = DateTime.Now;
        dates[index] = DateTime.Today.AddMinutes(index * 5);
        values[index] = index;
    }
    using (var conn = new OracleConnection(Program.ConnString)) {
        conn.Open();
        using (var command = conn.CreateCommand()) {
            command.ArrayBindCount = num;
            command.CommandText = sql;
            command.BindByName = true;
            command.Parameters.Add(new OracleParameter("pId", ids));
            command.Parameters.Add(new OracleParameter("pInsertDate", insertDates));
            command.Parameters.Add(new OracleParameter("pDate", dates));
            command.Parameters.Add(new OracleParameter("pValor", values));
            command.ExecuteNonQuery();
        }
    }

"An unhandled exception of type 'Oracle.ManagedDataAccess.Client.OracleException' occurred in Oracle.ManagedDataAccess.dll"

{"ORA-12537: Biblioteca de Rede: Fim do arquivo"}

Stack trace:

at Oracle.ManagedDataAccess.Client.OracleException.HandleError(OracleTraceLevel level, OracleTraceTag tag, Exception ex)
   at OracleInternal.TTC.TTCExecuteSql.ReceiveExecuteResponse(Accessor[]& defineAccessors, Accessor[] bindAccessors, Boolean bHasReturningParams, SQLMetaData& sqlMetaData, SqlStatementType statementType, Int64 noOfRowsFetchedLastTime, Int32 noOfRowsToFetch, Int32& noOfRowsFetched, Int64& queryId, Int32 longFetchSize, Int32 initialLOBFetchSize, Int64[] scnFromExecution, Boolean& bAllPureInputBinds, DataUnmarshaller& dataUnmarshaller, MarshalBindParameterValueHelper& marshalBindParamsHelper, Boolean bDefineDone)
   at OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteNonQuery(String commandText, OracleParameterCollection paramColl, CommandType commandType, OracleConnectionImpl connectionImpl, Int32 longFetchSize, Int32 lobPrefetchSize, OracleDependencyImpl orclDependencyImpl, Int64[]& scnFromExecution, OracleParameterCollection& bindByPositionParamColl, Boolean& bBindParamPresent, Boolean isFromEF)
   at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()
   at OraclePlayground.Program.Main(String[] args) in c:\dev\way2\DataIn\OraclePlayground\OraclePlayground\Program.cs:line 114
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()


问:
Confusing about P2b proving process in paper Paxos made simple
I'm reading the paper Paxos made simple but got stuck on the proving part for P2b.

Content of rule P2b:

If a proposal with value v is chosen, then every higher-numbered proposal issued by any proposer has value v.

And this is the proving part by Leslie Lamport:

To discover how to satisfy P2b, let’s consider how we would prove that it holds. We would assume that some proposal with number m and value v is chosen and show that any proposal issued with number n > m also has value v. We would make the proof easier by using induction on n, so we can prove that proposal number n has value v under the additional assumption that every proposal issued with a number in m . . (n − 1) has value v , where i . . j denotes the set of numbers from i through j . For the proposal numbered m to be chosen, there must be some set C consisting of a majority of acceptors such that every acceptor in C accepted it. Combining this with the induction assumption, the hypothesis that m is chosen implies:

Every acceptor in C has accepted a proposal with number in m ..(n − 1), and every proposal with number in m ..(n − 1) accepted by any acceptor has value v

So the induction process is:

Base case: proposal m with value v has been chosen

Inductive step: any proposal in number m ..(n-1) have value v

Why it implies that:

Every acceptor in C has accepted a proposal with number in m ..(n − 1)

I just can't bridge the gap, why does every acceptor in C need to accepted a proposal with number in m..(n-1)?

P1 guarantees that acceptor must accept the first proposal received, P2a guarantees that only the higher-numbered proposals with the chosen value could be accepted by acceptors, but I just don't get the point of the implied statement.

答: It's really easy to get hung up on the details given the language in that paper. I suggest trying Understanding Paxos instead. It's far more verbose but it walks through the hows and whys as well as surrounding issues for practical use of the algorithm without set notation or superscripts.</p>


问:
How to add tableview xcode
I am using Xcode 8.3.2. I am following https://www.raywenderlich.com/77974/making-a-gesture-driven-to-do-list-app-like-clear-in-swift-part-1, and it says to "add a table view".

I can't find it when I follow the steps. I also followed https://www.youtube.com/watch?v=fFpMiSsynXM and am not seeing any table view. I don't understand why my xcode doesn't offer this. Am I missing a plugin?

答: you just selected the wrong option just select the third option object library and the start type tableview, once you get result drag and drop tableview in viewController interface and then its done</p>

ContentLicense: CC BY-SA 4.0

Title: How to add tableview xcode


答:
```<code>/**
 *
 * @author Md. Amran Hossain
 */
public class DuplicateWordRemove {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String s = "like like like";
    // TODO code application logic here
    String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1");
    System.out.println(""+result);
}
</code>```

}

Output

Like

Title: I use regex for removing duplicate words in a string

Body:
/**
 *
 * @author Md. Amran Hossain
 */
public class DuplicateWordRemove {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    String s = "like like like";
    // TODO code application logic here
    String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1");
    System.out.println(""+result);
}

}

Output

Like


问:
Back button with ajax and iframe
Here is a situation. We have a search feature which uses ajax so that search results can be updated when user changes one of the search filters. The search results page also has 3 ad units that are using iframes. We are using iframes so that when usees use pagination to go different pages or update search results using search filters, the ads can be refreshed.
Now the problem is if user uses pagination to go to different pages and then try to use browser back button, it does not work properly because when you change iframe source, browser add this in history

I would apprecaite any help on how to solve this issue.

答: Mayby try location.replace("http://yourPage...") to replace the browsers last history entry after iFrame load?</p>

Title: Back button with ajax and iframe


问:
Understanding this complex declaration
```<code>static void (* __set_malloc_handler(void (*__f)()))();
</code>```

I think __set_malloc_handler is a function pointer, and it points to a function which also needs a function pointer. But, I have no idea how to understand the whole statement. How does it work?

答:
It's easier to understand with some aliasing.

```<code>//pointer to function taking no arguments and void return
typedef void(*function_pointer)();

//function taking "function_pointer" and returning "function_pointer"
function_pointer __set_malloc_handler(function_pointer __f);
</code>```

To read something like that, I recommend the right-left rule. It's what I always use. There's also a spiral rule, but I get annoyed when it doesn't form a perfect spiral and I get too distracted by that to focus. You probably won't have that issue.

The explanation on either page is more thorough, but here's a crash course.

Essentially, read these symbols as:

* = "pointer to"

(...) = "function taking ..."

[...] = "array of size ..."

Read to the right until you find a ) that didn't have a matching ( yet. Then read to the left until you find a ( to match it. Start reading right again. If you hit the end of the line on the right, you finish reading to the left.

To the immediate right of the identifier __set_malloc_handler is an open parenthetical (, meaning it is a function. Everything from that to the matching ) is the parameter type. I'd recommend ignoring it at first and coming back to it later. Step by step:

```<code>       __set_malloc_handler(...)    //function taking ...
     (*__set_malloc_handler(...))   //and returning a pointer
     (*__set_malloc_handler(...))() //to a function taking no arguments
void (*__set_malloc_handler(...))() //that returns void
</code>```

Looking at the parameter, we have:

```<code>     (*__f)   //pointer
     (*__f)() //to function taking no arguments
void (*__f)() //and returning void
</code>```

Title: Understanding this complex declaration

Body:
static void (* __set_malloc_handler(void (*__f)()))();

I think __set_malloc_handler is a function pointer, and it points to a function which also needs a function pointer. But, I have no idea how to understand the whole statement. How does it work?

Body:
It's easier to understand with some aliasing.

//pointer to function taking no arguments and void return
typedef void(*function_pointer)();

//function taking "function_pointer" and returning "function_pointer"
function_pointer __set_malloc_handler(function_pointer __f);

To read something like that, I recommend the right-left rule. It's what I always use. There's also a spiral rule, but I get annoyed when it doesn't form a perfect spiral and I get too distracted by that to focus. You probably won't have that issue.

The explanation on either page is more thorough, but here's a crash course.

Essentially, read these symbols as:

* = "pointer to"

(...) = "function taking ..."

[...] = "array of size ..."

Read to the right until you find a ) that didn't have a matching ( yet. Then read to the left until you find a ( to match it. Start reading right again. If you hit the end of the line on the right, you finish reading to the left.

To the immediate right of the identifier __set_malloc_handler is an open parenthetical (, meaning it is a function. Everything from that to the matching ) is the parameter type. I'd recommend ignoring it at first and coming back to it later. Step by step:

       __set_malloc_handler(...)    //function taking ...
     (*__set_malloc_handler(...))   //and returning a pointer
     (*__set_malloc_handler(...))() //to a function taking no arguments
void (*__set_malloc_handler(...))() //that returns void

Looking at the parameter, we have:

     (*__f)   //pointer
     (*__f)() //to function taking no arguments
void (*__f)() //and returning void


问:
DependONGroups annotation testng
I am using DependOnGroups parameter in @test annotation.the code looks like,

```<code>@Test(groups={"datacompare"},dependsOnGroups = {"AzkabanFlow"})
</code>```

Now the requirement is we need to run the test only for the group datacompare which is done by specifying the maven parameter,

```<code>clean test site -DtestGroup=datacompare
</code>```

Since the above group has dependency with the group azkban flow, i am getting the error

```<code>[ERROR] DependencyMap::Method "DataValidationTestSuite.data_Comparison(java.lang.reflect.Method)[pri:0, instance:com.kohls.test.automation.framework.testsuite.DataValidationTestSuite@1608e1a]" depends on nonexistent group "AzkabanFlow"
</code>```

Can someone suggest me a way to run the test for datacompare without removing the parameter DependOnGroups and also not calling the particular group mentioned in dependOnGroup parameter in maven parameter for test run.

答:
You might want to change your @Test annotation to something like below

@Test(groups={"datacompare"},dependsOnGroups = {"AzkabanFlow"}, ignoreMissingDependencies=true)

This would cause TestNG to ignore missing dependencies and hopefully it should solve your problem as well.

Javadocs for the same can be referred here.

Title: DependONGroups annotation testng

Body:
I am using DependOnGroups parameter in @test annotation.the code looks like,

@Test(groups={"datacompare"},dependsOnGroups = {"AzkabanFlow"})

Now the requirement is we need to run the test only for the group datacompare which is done by specifying the maven parameter,

clean test site -DtestGroup=datacompare

Since the above group has dependency with the group azkban flow, i am getting the error

[ERROR] DependencyMap::Method "DataValidationTestSuite.data_Comparison(java.lang.reflect.Method)[pri:0, instance:com.kohls.test.automation.framework.testsuite.DataValidationTestSuite@1608e1a]" depends on nonexistent group "AzkabanFlow"

Can someone suggest me a way to run the test for datacompare without removing the parameter DependOnGroups and also not calling the particular group mentioned in dependOnGroup parameter in maven parameter for test run.


问:
UIApplicationExitOnSuspend for Suspend not Background
I have an application that tends to stay awake in the background due to it playing music; however, on a rare occasion if the music stops between songs for longer than expected(can be relatively short amount of time) due to connectivity issues or the user mutes the music, the application will become suspended. I am aware of UIApplicationExitOnSuspend but unlike the description of it, this actually exits on entering background. I have done a fair amount of research, I am aware there are no system notifications for entering suspending state.

Is there anyway to identify on leaving suspended state that the app was suspended? Alternatively is there anyways to do something similar to UIApplicationExitOnSuspend except only when the application actually is suspended not just when it goes into the background?

答:
You could try using the backgroundtimeremaining property on UIApplication, poll it with a timer on some interval, and should that value get close enough to zero - set a flag, or even a value in userDefaults, which you could then check and unset after coming back to the foreground?

The documentation reads:

This property contains the amount of time the app has to run in the background before it may be forcibly killed by the system. While the app is running in the foreground, the value in this property remains suitably large. If the app starts one or more long-running tasks using the beginBackgroundTask(expirationHandler:) method and then transitions to the background, the value of this property is adjusted to reflect the amount of time the app has left to run.


答: Remove White-space Property and use a height of the element

Title: Two line of text and overflow is dotted


问:
Java HashSet (Long vs Integer)
I was solving this problem, (41 from Project Euler), where I noticed that contains method of HashSet is working differently for Long as compared to Integer (I might be wrong here, please correct me if I am).

The question is -

We shall say that an n-digit number is pandigital if it makes use of
  all the digits 1 to n exactly once. For example, 2143 is a 4-digit
  pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

My code for checking whether the number is Pandigital or not is -

```<code>private static boolean isPan(Long n) {
        HashSet<Long> list = new HashSet<Long>();
        int count = 0;
        while(n != 0){
            list.add(n%10);
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }
</code>```

This code gave me an infinite loop. So, I changed my code like this -

```<code>private static boolean isPan(Long n) {
        HashSet<Integer> list = new HashSet<Integer>();
        int count = 0;
        while(n != 0){
            list.add((int) (n%10));
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }
</code>```

I just changed, HashSet<Long> to HashSet<Integer> and list.add(n%10) to list.add((int) n%10).

This gave me the correct answer, 7652413. So, can anyone explain why the contains method works differently for Long when compared to Integer?

答:
contains(Object o) method doesn't work different for Long vs Integer. It works exactly the same, i.e.

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

Notice however that method accepts Object as parameter type, not E. That means you can call it with any type of object. Of course, any object type other than E would cause it to return false, since equals() would fail for objects of different types (with some exceptions).

So, when you call contains(x), and x is a primitive, it will be auto-boxed, based on the type of x, not on the type of E. So if x is an int and E is Long, it'll always return false.

It is not contains() that suddenly works different, when you change Long to Integer. It is your code that works different, by correctly matching the type of value passed to contains() to the type of elements in the collection.

UPDATE

Your code is not very efficient:

It takes a Long as a parameter, but max n is by nature 9, and and int can store 9-digit numbers without overflow, so use of Long, and use of boxing, is unnecessary.

It allocates a new HashSet for every value being checked, and autoboxes every digit found, plus 9 times for the contains() calls.

Instead, this can be done using bit-manipulation, since as 32-bit int value can easily store 10 boolean values (flags) indicating whether a digit was present.

The code below will establish two bit-masks, found and expected, which will indicate whether a digit is found, and whether a digit was supposed to be found. Since solution should only use digits 1-n, we'll claim digit 0 is present and expected (makes logic simpler, not having to do special checks for 0).

If a digit is presented twice (or digit 0 is presented once), another expected digit will be missing, and found will not equal expected.

```<code>private static boolean isPandigital(int number) {
    int found = 1, expected = 1;
    for (int n = number; n != 0; n /= 10, expected = (expected << 1) | 1)
        found |= 1 << (n % 10);
    return (found == expected);
}
</code>```

Title: Java HashSet (Long vs Integer)

Body:
I was solving this problem, (41 from Project Euler), where I noticed that contains method of HashSet is working differently for Long as compared to Integer (I might be wrong here, please correct me if I am).

The question is -

We shall say that an n-digit number is pandigital if it makes use of
  all the digits 1 to n exactly once. For example, 2143 is a 4-digit
  pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

My code for checking whether the number is Pandigital or not is -

private static boolean isPan(Long n) {
        HashSet<Long> list = new HashSet<Long>();
        int count = 0;
        while(n != 0){
            list.add(n%10);
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }

This code gave me an infinite loop. So, I changed my code like this -

private static boolean isPan(Long n) {
        HashSet<Integer> list = new HashSet<Integer>();
        int count = 0;
        while(n != 0){
            list.add((int) (n%10));
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }

I just changed, HashSet<Long> to HashSet<Integer> and list.add(n%10) to list.add((int) n%10).

This gave me the correct answer, 7652413. So, can anyone explain why the contains method works differently for Long when compared to Integer?

Body:
contains(Object o) method doesn't work different for Long vs Integer. It works exactly the same, i.e.

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

Notice however that method accepts Object as parameter type, not E. That means you can call it with any type of object. Of course, any object type other than E would cause it to return false, since equals() would fail for objects of different types (with some exceptions).

So, when you call contains(x), and x is a primitive, it will be auto-boxed, based on the type of x, not on the type of E. So if x is an int and E is Long, it'll always return false.

It is not contains() that suddenly works different, when you change Long to Integer. It is your code that works different, by correctly matching the type of value passed to contains() to the type of elements in the collection.

UPDATE

Your code is not very efficient:

It takes a Long as a parameter, but max n is by nature 9, and and int can store 9-digit numbers without overflow, so use of Long, and use of boxing, is unnecessary.

It allocates a new HashSet for every value being checked, and autoboxes every digit found, plus 9 times for the contains() calls.

Instead, this can be done using bit-manipulation, since as 32-bit int value can easily store 10 boolean values (flags) indicating whether a digit was present.

The code below will establish two bit-masks, found and expected, which will indicate whether a digit is found, and whether a digit was supposed to be found. Since solution should only use digits 1-n, we'll claim digit 0 is present and expected (makes logic simpler, not having to do special checks for 0).

If a digit is presented twice (or digit 0 is presented once), another expected digit will be missing, and found will not equal expected.

private static boolean isPandigital(int number) {
    int found = 1, expected = 1;
    for (int n = number; n != 0; n /= 10, expected = (expected << 1) | 1)
        found |= 1 << (n % 10);
    return (found == expected);
}


问:
Can I load JavaScript code after the rest of page loads?
I have a section of a webpage that loads a JavaScript file from an external source and then kicks off an Ajax query.

When I load the page, I see the browser saying "waiting for example.com" a lot, so I think the dependency on this external JavaScript is slowing my initial page load.

Is there a way I can load this external JavaScript asynchronously so it doesn't slow the loading of the rest of my page at all?

答:
I wrote a library to asynchronously load javascript files with callbacks for when it loads:

https://github.com/ssoroka/sigma

```<code>Sigma.async_script_load('http://example.com/underscore/underscore-min.js', '_', function() {
  _([1,2,3,2,3,1]).uniq();
});
</code>```

Body:
I wrote a library to asynchronously load javascript files with callbacks for when it loads:

https://github.com/ssoroka/sigma

Sigma.async_script_load('http://example.com/underscore/underscore-min.js', '_', function() {
  _([1,2,3,2,3,1]).uniq();
});


问:
possibilities to play OGG in UWP
I am developing app on Universal Windows Platform to play audio files. I could not find way to play OGG files using MediaElement or AudioGraph. Therefore I was about to first convert the ogg to some supported format. Can you give me a hint what would work on UWP? I tried NAudio to convert from OGG to WAV but the NVorbis part is not yet translated.

Many thanks.

答:
MediaElement or AudioGraph does not support OGG files by default. To play OGG files, you have to implement the corresponding decoder. This won't be a easy task.

One easy way to achieve what you want is using some existing decoders that can be used in UWP such as VLC.MediaElement for UWP. It's very easy to use. Just add the NuGet package to your project and use it as the classic MediaElement.

```<code>xmlns:vlc="using:VLC"
</code>```

```<code><vlc:MediaElement AreTransportControlsEnabled="True" HardwareAcceleration="True"
                  Source="http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_surround-fix.avi">
    <vlc:MediaElement.TransportControls>
        <vlc:MediaTransportControls ControlPanelOpacity="0.8" />
    </vlc:MediaElement.TransportControls>
</vlc:MediaElement>
</code>```

The difference here is that, VLC.MediaElement can only accept a string for the Source property. If you want to play a local file, you need to add the file into FutureAccessList to get the FILE_TOKEN and then set the source with winrt://{FILE_TOKEN} protocol.

```<code>var fileOpenPicker = new FileOpenPicker();
fileOpenPicker.FileTypeFilter.Add("*");
var file = await fileOpenPicker.PickSingleFileAsync();
if (file != null)
{
    var FILE_TOKEN = StorageApplicationPermissions.FutureAccessList.Add(file);
    mediaElement.Source = null;
    mediaElement.Source = $"winrt://{FILE_TOKEN}";
}
</code>```

Title: possibilities to play OGG in UWP

Body:
MediaElement or AudioGraph does not support OGG files by default. To play OGG files, you have to implement the corresponding decoder. This won't be a easy task.

One easy way to achieve what you want is using some existing decoders that can be used in UWP such as VLC.MediaElement for UWP. It's very easy to use. Just add the NuGet package to your project and use it as the classic MediaElement.

xmlns:vlc="using:VLC"

<vlc:MediaElement AreTransportControlsEnabled="True" HardwareAcceleration="True"
                  Source="http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_surround-fix.avi">
    <vlc:MediaElement.TransportControls>
        <vlc:MediaTransportControls ControlPanelOpacity="0.8" />
    </vlc:MediaElement.TransportControls>
</vlc:MediaElement>

The difference here is that, VLC.MediaElement can only accept a string for the Source property. If you want to play a local file, you need to add the file into FutureAccessList to get the FILE_TOKEN and then set the source with winrt://{FILE_TOKEN} protocol.

var fileOpenPicker = new FileOpenPicker();
fileOpenPicker.FileTypeFilter.Add("*");
var file = await fileOpenPicker.PickSingleFileAsync();
if (file != null)
{
    var FILE_TOKEN = StorageApplicationPermissions.FutureAccessList.Add(file);
    mediaElement.Source = null;
    mediaElement.Source = $"winrt://{FILE_TOKEN}";
}


问:
PHP: Why does else-block not work?
I have the following code:

```<code><form action="" method="POST">
    <input id="delete" name="delete" placeholder="Name" type="text"></b>
    <input type="submit" name="deleteButton" value="Go!">
</form>

<?php
if (isset($_POST['deleteButton'])) {
    $temp = $_POST['delete'];
    $deleteSQL = "DELETE FROM `berater` WHERE `Nachname` LIKE '$temp' OR `Vorname` LIKE '$temp' OR CONCAT(Vorname,' ', Nachname) LIKE '%$temp%'";
    $searchSQL = "SELECT FROM `berater` WHERE `Nachname` LIKE '$temp' OR `Vorname` LIKE '$temp' OR CONCAT(Vorname,' ', Nachname) LIKE '%$temp%'";
    $search = mysqli_query($db_link, $searchSQL);
    $loeschen = mysqli_query($db_link, $deleteSQL);

    if (!$search) {
        echo "Kein Datensatz gefunden!";
    } else {
        echo "$temp erfolgreich gelöscht.";
    }
}
</code>```

I am new to PHP and thought the mysqli_query returns false if the name is not found in the database. What am I doing wrong here?

答:
Try using mysqli_num_rows:

```<code>if (mysqli_num_rows($search)==0) {
    echo "Kein Datensatz gefunden!";
} else {
    echo "$temp erfolgreich gelöscht.";
}
</code>```

Title: PHP: Why does else-block not work?

Body:
I have the following code:

<form action="" method="POST">
    <input id="delete" name="delete" placeholder="Name" type="text">
    <input type="submit" name="deleteButton" value="Go!">
</form>

<?php
if (isset($_POST['deleteButton'])) {
    $temp = $_POST['delete'];
    $deleteSQL = "DELETE FROM `berater` WHERE `Nachname` LIKE '$temp' OR `Vorname` LIKE '$temp' OR CONCAT(Vorname,' ', Nachname) LIKE '%$temp%'";
    $searchSQL = "SELECT FROM `berater` WHERE `Nachname` LIKE '$temp' OR `Vorname` LIKE '$temp' OR CONCAT(Vorname,' ', Nachname) LIKE '%$temp%'";
    $search = mysqli_query($db_link, $searchSQL);
    $loeschen = mysqli_query($db_link, $deleteSQL);

    if (!$search) {
        echo "Kein Datensatz gefunden!";
    } else {
        echo "$temp erfolgreich gelöscht.";
    }
}

I am new to PHP and thought the mysqli_query returns false if the name is not found in the database. What am I doing wrong here?

Body:
Try using mysqli_num_rows:

if (mysqli_num_rows($search)==0) {
    echo "Kein Datensatz gefunden!";
} else {
    echo "$temp erfolgreich gelöscht.";
}


答:
According to mysqli_query() documentation:

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
  EXPLAIN queries mysqli_query() will return a mysqli_result object. For
  other successful queries mysqli_query() will return TRUE.

Replace if (!$search) with if (mysqli_num_rows($search) > 0) to check if such row existed.

By the way, this code can not be used in production: it is vulnerable to SQL injection attacks. I advise you to read this article before working with the database: http://php.net/manual/en/security.database.sql-injection.php

Title: PHP: Why does else-block not work?


Body:
Try this.

String result = s.replaceAll("(?i)(\\b\\w+\\b)\\s+\\1", "$1");


问:
/usr/local/lib: file not recognized: Is a directory
When installing justniffer on CentOS 6.5,

```<code>./configure
</code>```

works fine, but make gives the following error:

```<code>libtool: link: g++ -g -O2 -o justniffer justniffer-main.o justniffer-formatter.o justniffer-utilities.o justniffer-regex.o justniffer-prog_read_file.o /usr/local/lib  -L/root/justniffer/lib/libnids-1.21_patched/src -lnids2 -lpcap -L/usr/local/lib -lboost_regex-mt -lboost_program_options -lpython2.6
/usr/local/lib: file not recognized: Is a directory
collect2: ld returned 1 exit status
make[1]: *** [justniffer] Error 1
make[1]: Leaving directory `/root/justniffer/src'
make: *** [all-recursive] Error 1
</code>```

What's the solution for this?

答:
Having not compile program for so long time, made the same silly mistake:

Like CFLAGS, LIBS, GTK_LIBS etc should be flags e.g. -Lpath, not bare paths. What I used to do is relocate all DIRs to CFLAGS=/I/L Another way to

Spaces should be quoted or escaped like LIBS="-L'c/program files/gtk+/lib'"
LIBS="-Lc/program\ files/gtk+/lib"

Body:
When installing justniffer on CentOS 6.5,

./configure

works fine, but make gives the following error:

libtool: link: g++ -g -O2 -o justniffer justniffer-main.o justniffer-formatter.o justniffer-utilities.o justniffer-regex.o justniffer-prog_read_file.o /usr/local/lib  -L/root/justniffer/lib/libnids-1.21_patched/src -lnids2 -lpcap -L/usr/local/lib -lboost_regex-mt -lboost_program_options -lpython2.6
/usr/local/lib: file not recognized: Is a directory
collect2: ld returned 1 exit status
make[1]: *** [justniffer] Error 1
make[1]: Leaving directory `/root/justniffer/src'
make: *** [all-recursive] Error 1

What's the solution for this?


问:
Laravel on some kind of Model Ready method
Well i don't know how to format the title of this post in very clear way, but here's my question:

Say i have

```<code>Posts::find('1);
Photos:find('1');
... and so on, every mode db request
</code>```

now by default i can access db columns, for instance the id: through model->id

```<code>$Photos = Photos::find('1')->first();
echo $Photos->id; // will return 1
</code>```

what i want is that i need all those kind of requests to add a custom field automatically like hashed_id, which is not in the database, which in return will make all models have a hashed_id as well, i know i can add that field to database and then grab it but i need it for different reasons/implementations

i did create a BaseModel and every Model will extend that BaseModel, so Photos extends BaseModel, BaseModel extends Model... and all that etc etc.

but i need some kind of constructor, upon retrieving data to process the data automatically without having to add -let's say- a hash_id() after retrieving the data.

something like, onAfterGet(), onReady()....sort of commands.

i hope my question is clear.

Thanks.

答:
What you're looking for is an Accessor. Accesors can be used to add custom attributes to the model. Combine this with the $appends property and you have exactly what you need. The $appends property adds the custom accessor in every result.

You can do this by creating a base model like you've stated in the question or by using traits. I'll show you an example on how to achieve this using a base model.

Let's create  base model called BaseModel. All other models that need this custom attribute will extend this.

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    protected $appends = ['hashed_id'];

    public function getHashedIdAttribute()
    {
        return some_hash_function($this->id);
    }
}
</code>```

We have a Image model which extends our BaseModel.

```<code><?php

namespace App;

class Image extends BaseModel
{

}
</code>```

Now every result from the Image model will have the hashed_id field added by default.

Accesor documenation https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

Body:
Well i don't know how to format the title of this post in very clear way, but here's my question:

Say i have

Posts::find('1);
Photos:find('1');
... and so on, every mode db request

now by default i can access db columns, for instance the id: through model->id

$Photos = Photos::find('1')->first();
echo $Photos->id; // will return 1

what i want is that i need all those kind of requests to add a custom field automatically like hashed_id, which is not in the database, which in return will make all models have a hashed_id as well, i know i can add that field to database and then grab it but i need it for different reasons/implementations

i did create a BaseModel and every Model will extend that BaseModel, so Photos extends BaseModel, BaseModel extends Model... and all that etc etc.

but i need some kind of constructor, upon retrieving data to process the data automatically without having to add -let's say- a hash_id() after retrieving the data.

something like, onAfterGet(), onReady()....sort of commands.

i hope my question is clear.

Thanks.

Body:
What you're looking for is an Accessor. Accesors can be used to add custom attributes to the model. Combine this with the $appends property and you have exactly what you need. The $appends property adds the custom accessor in every result.

You can do this by creating a base model like you've stated in the question or by using traits. I'll show you an example on how to achieve this using a base model.

Let's create  base model called BaseModel. All other models that need this custom attribute will extend this.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    protected $appends = ['hashed_id'];

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

We have a Image model which extends our BaseModel.

<?php

namespace App;

class Image extends BaseModel
{

}

Now every result from the Image model will have the hashed_id field added by default.

Accesor documenation https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor


问:
How to get old console logs (javascript)
I want to get a list of logs which are sent to browser's console. Is there any way to do it.</p>

```<code>console.log("lol");
console.log("imao");

list
->["lol", "imao"]
</code>```

答: You need to set up preserve logs option on the browser console tab.</p>

Body:
I want to get a list of logs which are sent to browser's console. Is there any way to do it.

console.log("lol");
console.log("imao");

list
->["lol", "imao"]


问:
How to handle JSON.stringify data in Laravel
I am trying to catch data from Ajax in Laravel controller to save it. But I keep getting error as seen image below. What am I doing wrong here?

Laravel Controller@ajaxstore

```<code>public function ajaxstore(Request $request)
{

    //Event::create($request->all());
    //return (gettype($name));
    $data = $request->all();
    //$newdata =array_keys($data);
    $data= json_decode($data,true);
    $event = New Event;
    $event->name = $data['name'];
    $event->description = $data['description'];
    $event->start = $data['start'];
    $event->end = $data['end'];
    $event->color = $data['color'];
    $event->save();
}
</code>```

My jquery

```<code>$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    events: '/admin/event-list/' + roomId.val(),
    //events: JSON.parse(json_events),
    defaultView: 'agendaWeek',
    editable: true,
    selectable: true,
    timezone: 'local',
    select: function(start, end, jsEvent, view) {
        endtime = end.format('LLLL');
        starttime = start.format('LLLL');
        room_id = roomId.val();
        var mywhen = starttime + ' - ' + endtime;
        startTime.val(start);
        endTime.val(end);
        $('#dayClick #when').text(mywhen);
        $("#dayClick").modal("show");
        $('#submitButton').on('click', function(event){
            console.log("clicked");
            if(createEvent.valid()){
                // We don't want this to act as a link so cancel the link action
                if(doSubmit(start, end))
                {

                    $("#dayClick").modal('hide');
                    // remove previous entry
                    $("#createEvent").each(function(){
                        this.reset();
                    });
                    console.log($('#apptStartTime').val());
                    console.log($('#apptEndTime').val());
                    // enter to the calender
                    $("#calendar").fullCalendar('renderEvent',
                        {
                            title: $('#createEvent #event-name').val(),
                            start: new Date($('#apptStartTime').val()),
                            end: new Date($('#apptEndTime').val()),
                        },
                        true);
                    console.log("after renderEvent");

                }
                else
                {
                    console.log("failed");
                };
            }
            event.preventDefault();
        });

        //return eventData;
    },
    eventClick: function(event, jsEvent, view) {
        $('#modalTitle').html(event.name);
        $('#modalBody').html(event.description);
        $('#eventUrl').attr({'href':'event/'+event.id,'target':'_self'});
        $('#fullCalModal').modal("show");
    }
});

function doSubmit(start, end){
    console.log("inside dosubmit");
    eventData.name = eventName.val();
    eventData.description = description.val();
    eventData.capacity = capacity.val();
    eventData.room_id = roomId.val();
    startDate =  moment(start.format("YYYY-MM-DD HH:mm:ss"));
    eventData.start = startDate;
    endDate =  moment(end.format("YYYY-MM-DD HH:mm:ss"));
    eventData.end = endDate;
    eventData.color = color.val();
    console.log("inputdata: " + JSON.stringify(eventData));
    $.ajax({
        type: 'POST',
        url:'/admin/event-ajaxstore',
        //url: '/admin/event-ajaxstore',
        data: JSON.stringify(eventData),
        success: function(response){
            //event.id = response.eventid;
            console.log("returned : " + typeof(response));
            /* $('#calendar').fullCalendar('updateEvent',event); */
            /* //json_events = response; */
            /* console.log("data: " + data); */
            return true;
        }
    });

}
</code>```

When I run this in the contoller;

```<code>    $data = $request->all();
    return (json_decode($data));
</code>```

I get the following error.

local.ERROR: ErrorException: json_decode() expects parameter 1 to be
  string, array given in
  /Users/sokada/Code/backpack-aktiv/app/Http/Controllers/Admin/EventController.php:39

答:
Your issue is that $request->all() already returns an array. So you dont need the json_decode()

```<code>$data = $request->all();
$data= json_decode($data,true);  // remove this, you don't need it here
</code>```

Do keep in mind though that $request->all() is going to return ALL variables. which may or may not be what you expect

If it were me, I would send my data like this:

data: JSON.stringify({eventData:eventData}),

Then I would access it in my controller like this:

$data = $request->input('eventData');

Body:
I am trying to catch data from Ajax in Laravel controller to save it. But I keep getting error as seen image below. What am I doing wrong here?

Laravel Controller@ajaxstore

public function ajaxstore(Request $request)
{

    //Event::create($request->all());
    //return (gettype($name));
    $data = $request->all();
    //$newdata =array_keys($data);
    $data= json_decode($data,true);
    $event = New Event;
    $event->name = $data['name'];
    $event->description = $data['description'];
    $event->start = $data['start'];
    $event->end = $data['end'];
    $event->color = $data['color'];
    $event->save();
}

My jquery

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    events: '/admin/event-list/' + roomId.val(),
    //events: JSON.parse(json_events),
    defaultView: 'agendaWeek',
    editable: true,
    selectable: true,
    timezone: 'local',
    select: function(start, end, jsEvent, view) {
        endtime = end.format('LLLL');
        starttime = start.format('LLLL');
        room_id = roomId.val();
        var mywhen = starttime + ' - ' + endtime;
        startTime.val(start);
        endTime.val(end);
        $('#dayClick #when').text(mywhen);
        $("#dayClick").modal("show");
        $('#submitButton').on('click', function(event){
            console.log("clicked");
            if(createEvent.valid()){
                // We don't want this to act as a link so cancel the link action
                if(doSubmit(start, end))
                {

                    $("#dayClick").modal('hide');
                    // remove previous entry
                    $("#createEvent").each(function(){
                        this.reset();
                    });
                    console.log($('#apptStartTime').val());
                    console.log($('#apptEndTime').val());
                    // enter to the calender
                    $("#calendar").fullCalendar('renderEvent',
                        {
                            title: $('#createEvent #event-name').val(),
                            start: new Date($('#apptStartTime').val()),
                            end: new Date($('#apptEndTime').val()),
                        },
                        true);
                    console.log("after renderEvent");

                }
                else
                {
                    console.log("failed");
                };
            }
            event.preventDefault();
        });

        //return eventData;
    },
    eventClick: function(event, jsEvent, view) {
        $('#modalTitle').html(event.name);
        $('#modalBody').html(event.description);
        $('#eventUrl').attr({'href':'event/'+event.id,'target':'_self'});
        $('#fullCalModal').modal("show");
    }
});

function doSubmit(start, end){
    console.log("inside dosubmit");
    eventData.name = eventName.val();
    eventData.description = description.val();
    eventData.capacity = capacity.val();
    eventData.room_id = roomId.val();
    startDate =  moment(start.format("YYYY-MM-DD HH:mm:ss"));
    eventData.start = startDate;
    endDate =  moment(end.format("YYYY-MM-DD HH:mm:ss"));
    eventData.end = endDate;
    eventData.color = color.val();
    console.log("inputdata: " + JSON.stringify(eventData));
    $.ajax({
        type: 'POST',
        url:'/admin/event-ajaxstore',
        //url: '/admin/event-ajaxstore',
        data: JSON.stringify(eventData),
        success: function(response){
            //event.id = response.eventid;
            console.log("returned : " + typeof(response));
            /* $('#calendar').fullCalendar('updateEvent',event); */
            /* //json_events = response; */
            /* console.log("data: " + data); */
            return true;
        }
    });

}

When I run this in the contoller;

    $data = $request->all();
    return (json_decode($data));

I get the following error.

local.ERROR: ErrorException: json_decode() expects parameter 1 to be
  string, array given in
  /Users/sokada/Code/backpack-aktiv/app/Http/Controllers/Admin/EventController.php:39

Body:
Your issue is that $request->all() already returns an array. So you dont need the json_decode()

$data = $request->all();
$data= json_decode($data,true);  // remove this, you don't need it here

Do keep in mind though that $request->all() is going to return ALL variables. which may or may not be what you expect

If it were me, I would send my data like this:

data: JSON.stringify({eventData:eventData}),

Then I would access it in my controller like this:

$data = $request->input('eventData');


问:
Two line of text and overflow is dotted
Is there any way to display text in two line and overflow is dotted?
I can use

```<code>white-space: nowrap;
text-overflow: ellipsis;
</code>```

But it show the text in one line. I need to show my text in two line and if overflow text then it should show dotted end.

答:
Working CSS solution for Chrome, Safari and Opera is:

```<code>display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
</code>```

You can change 2 to any number. It will show X number of text and dots at the end

line-clamp is not supported by all browsers. https://caniuse.com/#search=line-clamp

Title: Two line of text and overflow is dotted

Body:
Is there any way to display text in two line and overflow is dotted?
I can use

white-space: nowrap;
text-overflow: ellipsis;

But it show the text in one line. I need to show my text in two line and if overflow text then it should show dotted end.

Body:
Working CSS solution for Chrome, Safari and Opera is:

display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;

You can change 2 to any number. It will show X number of text and dots at the end

line-clamp is not supported by all browsers. https://caniuse.com/#search=line-clamp


问:
CSS animation loop fade in & out 1-2-3-1-2-3-1-2
I have text transition with keyframes, have 3 headlines which will fade in & out respectively one after another It is working fine BUT I want it to back to ONE again when all three done keyframes

It should work infinitely after completing on ALL child

Animation sequence

1-2-3-1-2....so on

CSS :

```<code>h2 {
  position: absolute;

  opacity: 0;
  -webkit-animation: fadeOut 3s ease-out forwards;
  animation: fadeOut 3s ease-out forwards;
}

@-webkit-keyframes fadeOut {
    0% { opacity: 0; }
    50% { opacity: 1; }
    100% { opacity: 0; }
}
@keyframes fadeOut {
    0% { opacity: 0; }
    50% { opacity: 1; }
    100% { opacity: 0; }
}

h2:nth-child(1) {animation-delay: 0s;}
h2:nth-child(2) {animation-delay: 3s;}
h2:nth-child(3) {animation-delay: 6s;}
</code>```

Here is HTML :

```<code><h2>Hello Heading 1</h2>
<h2>Heading 2</h2>
<h2>Heading 3</h2>
</code>```

JSFiddle :
https://jsfiddle.net/Lq4w007u/

答:
Use this Code</p>

```<code>setInterval(function(){
    var x = 0;
    for(var i=1; i<=3; i++){
      $("h2:nth-child(i)").css("animation-delay", "x.'s'");

      x = x+3;
    }

$("h2").css({
"animation": "fadeOut",
"animation-duration": "3s",
"animation-timing-function": "ease-out"
})

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

Body:
I have text transition with keyframes, have 3 headlines which will fade in & out respectively one after another It is working fine BUT I want it to back to ONE again when all three done keyframes

It should work infinitely after completing on ALL child

Animation sequence

1-2-3-1-2....so on

CSS :

h2 {
  position: absolute;

  opacity: 0;
  -webkit-animation: fadeOut 3s ease-out forwards;
  animation: fadeOut 3s ease-out forwards;
}

@-webkit-keyframes fadeOut {
    0% { opacity: 0; }
    50% { opacity: 1; }
    100% { opacity: 0; }
}
@keyframes fadeOut {
    0% { opacity: 0; }
    50% { opacity: 1; }
    100% { opacity: 0; }
}

h2:nth-child(1) {animation-delay: 0s;}
h2:nth-child(2) {animation-delay: 3s;}
h2:nth-child(3) {animation-delay: 6s;}

Here is HTML :

Hello Heading 1

Heading 2

Heading 3

JSFiddle :
https://jsfiddle.net/Lq4w007u/

Body:
Use this Code

setInterval(function(){
    var x = 0;
    for(var i=1; i<=3; i++){
      $("h2:nth-child(i)").css("animation-delay", "x.'s'");

      x = x+3;
    }

$("h2").css({
"animation": "fadeOut",
"animation-duration": "3s",
"animation-timing-function": "ease-out"
})

}, 12000);


问:
navigationController.navigationItem vs navigationItem
Just curious, why setting self.navigationItem = ... works, but self.navigationController.navigationItem fails? The same applies for self.toolbarItems vs self.navigationController.toobarItems.

When to use self.navigationController.navigationItem?

Maybe you will say, they point to different things. but why self.navigationController.navigationBarHidden = YES the navigation bar is hidden. doesn't it means self.navigationController.navigationItem point to the bar i wanted?

答:
although set can set this property of a navigation controller: self.navigationController.navigationItem = .. but it won't work.
Mainly because the navigationItem is a UIViewController's property. You can access the property because UINavigationController is inherited from UIViewController. this property is meant for any view controller that is added into a navigation controller to have a navigation bar created for them. Normally a UINavigationController won't be put into another navigation controller, so set this property of a navigation controller normally makes no sense.


问:
Kettle Parallel running meeting error
When i using shell to run multiple kettle transform (Using pan.sh)
meet problem. I using Debug mode to get what caused this error.but finding nothing.

I guess there may not be enough resources, but I am not sure.

Using lsof -p PID to get Usage of fd is enough

Looking for process number and find it enough

But when I ran transformation,  CPU Usage is very high.
But total CPU is lower ,almost of CPU is idle!

答:
Two thing you can try - ktr setting -> miscellaneous -> there are three option normal, single-threaded, single threaded for Hadoop.

Try single threaded as your table may do updates which will throw error wen your try multiple.

Also increase the memory based on number of copies you would like to run in parallel.

Choose tick when this answer is right as it may help others.

Thanks,
Sivasakthi.

Title: Kettle Parallel running meeting error


答: __set_malloc_handler is a function that takes a "function pointer to a void function" and returns a "function pointer to a void function". Keyword static makes it only visible to the current file.

Title: Understanding this complex declaration

Body:
static void (* __set_malloc_handler(void (*__f)()))();

I think __set_malloc_handler is a function pointer, and it points to a function which also needs a function pointer. But, I have no idea how to understand the whole statement. How does it work?


问:
angular 2/ionic2/cordova what to skip source control
I am using ionic 2/angular 2/ cordova for my app building.

Currently my target is IOS.

I have enabled git to source control.

I am not sure from below which locations should I skip source control.

I have checked some generic answers but they are not helpful.

Some key I need to know if i can skip:

```<code><my app>/platforms/ios
<my app>/www/build
</code>```

If there are any additional such locations do let me know please.

one place i saw like below list but seems too generic
node_modules
dist
.tmp
.sass-cache
bower_components

答:
You can use the services from gitignore.io, and combine the content from:
Angular and Cordova:

https://www.gitignore.io/api/angular%2Capachecordova

That will give you one .gitignore file that you need to create before your first git add/git commit.

It seems to cover what was already recommended for an ionic project in the past, including platforms/*.

I don't see www/build/ in it, but if that folder content is generated, it should be ignored as well, as in this ionic-2-sample/.gitignore file.

So you can add that rule www/build/ to your .gitignore fie as well.

Body:
I am using ionic 2/angular 2/ cordova for my app building.

Currently my target is IOS.

I have enabled git to source control.

I am not sure from below which locations should I skip source control.

I have checked some generic answers but they are not helpful.

Some key I need to know if i can skip:

<my app>/platforms/ios
<my app>/www/build

If there are any additional such locations do let me know please.

one place i saw like below list but seems too generic
node_modules
dist
.tmp
.sass-cache
bower_components


问:
pygame.transform.scale not working on a font surface
I am trying to make a function in a pygame program for python 3. The function basically makes the multiple-line process of blitting words onto the screen simpler by making it one function, MakeWord(). It has some parameters to adjust size, font, position, etc. Instead of making the font based on normal font sizes, I wanted it based on pixel sizes so I did pygame.transfom.flip() on a font surface and it did not work. Can someone find the problem please?

```<code>def MakeWord(Phrase, Font, Color, Pos, Size):
    FontType = pygame.font.SysFont(Font, 400) #400 because the size will be changed anyways
    FontSurf = FontType.render(Phrase, True, Color)
    pygame.transform.scale(FontSurf, Size) #Does not work
    FontRect = FontSurf.get_rect()
    FontRect.topleft = Pos
    Display.blit(FontSurf, FontRect)
    return FontRect #For FontRect.collidepoint(pygame.mouse.get_pos) used later
</code>```

答:
pygame.transform.scale returns a new Surface object. Try to assign it to FontSurf:

```<code>FontSurf = pygame.transform.scale(FontSurf, Size)
</code>```

Body:
I am trying to make a function in a pygame program for python 3. The function basically makes the multiple-line process of blitting words onto the screen simpler by making it one function, MakeWord(). It has some parameters to adjust size, font, position, etc. Instead of making the font based on normal font sizes, I wanted it based on pixel sizes so I did pygame.transfom.flip() on a font surface and it did not work. Can someone find the problem please?

def MakeWord(Phrase, Font, Color, Pos, Size):
    FontType = pygame.font.SysFont(Font, 400) #400 because the size will be changed anyways
    FontSurf = FontType.render(Phrase, True, Color)
    pygame.transform.scale(FontSurf, Size) #Does not work
    FontRect = FontSurf.get_rect()
    FontRect.topleft = Pos
    Display.blit(FontSurf, FontRect)
    return FontRect #For FontRect.collidepoint(pygame.mouse.get_pos) used later

Body:
pygame.transform.scale returns a new Surface object. Try to assign it to FontSurf:

FontSurf = pygame.transform.scale(FontSurf, Size)


问:
Trouble passing a JsonSerializerSetting from one assembly via an Action parameter to another assembly
Using Json.Net, I am trying to pass a JsonSerializerSettings object as one of the parameters of an Action.

The SerializerSettings is in assembly A:

```<code>public static class SerializerSettings
{
    public static readonly JsonSerializerSettings Jss = new JsonSerializerSettings
    {
        MissingMemberHandling = MissingMemberHandling.Error,
        NullValueHandling = NullValueHandling.Ignore,
        Converters = new List<JsonConverter>
           { new StringEnumConverter(), new NullStringConverter() }
    };
}
</code>```

(the NullStringConverter is just a custom converter inheriting from JsonConverter)

for brevity:

```<code>public class NullStringConverter : JsonConverter
{}
</code>```

I may not be using the best or proper terminology to describe this but, then from assembly B the method defined below is passed as a pointer to assembly A and there in assembly A it is invoked with its parameters that include the JsonSerializerSettings defined above.

```<code>private static void Investigated<TRequest, TResponse>(string data, JsonSerializerSettings jss) where TRequest : IBaseRequest where TResponse : IBaseResponse
{
    if (string.IsNullOrEmpty(data) || jss == null)
        Console.WriteLine("Bad Data");
    else
    {
        var response = JsonConvert.DeserializeObject<TResponse>(data, jss);
    }
}
</code>```

In debugger i see the data string is good, jss is properly set, but the deserialization completes with all values in the 'response' object being null or default values.

If instead i move the same JsonSerializerSettings local to assembly B, deserialization comes out fine...

I even tried to create a new JsonSerializerSettings FROM the one passed in, but that had the same null/default results.

My first inclination is to suspect it is not possible pass/use a JsonSerializerSettings from one assembly to/in another in this way, a static object as a action's parameter?

Might i be doing anything obviously wrong.

I apologia in advance to anyone feeling my question is not well formed, lacks information, or otherwise answered elsewhere, im trying to follow the rules...

答:
1. JsonConvert returns nulls or defaults

The kind symptoms that you described that results your JsonConvert.DeserializeObject() method returning an object with nulls or defaults, occurs when you do not map your objects properly. Here is a small example to illustrate it.

```<code>class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Bar
{
    public int BarId { get; set; }
    public string BarName { get; set; }
}

void Main()
{
    var foo = new Foo()
    {
        Id = 1,
        Name = "One"
    };
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

    var bar = Newtonsoft.Json.JsonConvert.DeserializeObject<Bar>(json);
}
</code>```

Here is the result of bar:

```<code>bar = { BarId = 0, BarName = null }
</code>```

Incorrect mapping will result in nulls and defaults.

2. Pay attention to details when using a custom JsonConverter

Going further with the example above, when using a JsonConverter you also have to be aware of the mapping as well, as it's more prone to produce the same kind of problems from small typos or other errors.

MyCustomJsonSerializerSettings

```<code>public static class MyCustomJsonSerializerSettings
{
    private static JsonSerializerSettings _jss;

    public static JsonSerializerSettings Jss
    {
        get { return _jss; }
        private set { _jss = value; }
    }

    static MyCustomJsonSerializerSettings()
    {
        _jss = new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Error,
            NullValueHandling = NullValueHandling.Ignore,
            Converters = new List<JsonConverter>
            {
                new FooToBarConverter()
            }
        };
    }
}
</code>```

FooToBarConverter

```<code>public class FooToBarConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        Foo foo = (Foo)value;
        JObject jo = new JObject();
        jo.Add("BarId", new JValue(foo.Id));     // make sure of your mapping!
        jo.Add("BarName", new JValue(foo.Name)); // make sure of your mapping!
        jo.WriteTo(writer);
    }

    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

Make sure that you are properly mapping the object in the custom converter.

Putting it all together...

```<code>void Main()
{
    var foo = new Foo()
    {
        Id = 1,
        Name = "One"
    };

    string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
    var bar = Newtonsoft.Json.JsonConvert.DeserializeObject<Bar>(json); // nulls/defaults

    JsonSerializerSettings jss = MyCustomJsonSerializerSettings.Jss;
    string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(foo, jss); // note jss
    var bar2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Bar>(json2); // as expected!
}
</code>```

3. Portability of the Converter Between Assemblies

To be 100% certain that the converters will get passed along with your settings, you can always do something like this

```<code>public class MyCustomJsonSerializerSettings // not a static class
{
    private static JsonSerializerSettings _jss;

    public static JsonSerializerSettings Jss
    {
        get { return _jss; }
        private set { _jss = value; }
    }

    static MyCustomJsonSerializerSettings()
    {
        _jss = new JsonSerializerSettings { ... };
    }

    private class FooToBarConverter : JsonConverter // note that it is contained within
                                                    // the class
    {
        ...
    }
}
</code>```

Body:
Using Json.Net, I am trying to pass a JsonSerializerSettings object as one of the parameters of an Action.

The SerializerSettings is in assembly A:

public static class SerializerSettings
{
    public static readonly JsonSerializerSettings Jss = new JsonSerializerSettings
    {
        MissingMemberHandling = MissingMemberHandling.Error,
        NullValueHandling = NullValueHandling.Ignore,
        Converters = new List<JsonConverter>
           { new StringEnumConverter(), new NullStringConverter() }
    };
}

(the NullStringConverter is just a custom converter inheriting from JsonConverter)

for brevity:

public class NullStringConverter : JsonConverter
{}

I may not be using the best or proper terminology to describe this but, then from assembly B the method defined below is passed as a pointer to assembly A and there in assembly A it is invoked with its parameters that include the JsonSerializerSettings defined above.

private static void Investigated<TRequest, TResponse>(string data, JsonSerializerSettings jss) where TRequest : IBaseRequest where TResponse : IBaseResponse
{
    if (string.IsNullOrEmpty(data) || jss == null)
        Console.WriteLine("Bad Data");
    else
    {
        var response = JsonConvert.DeserializeObject<TResponse>(data, jss);
    }
}

In debugger i see the data string is good, jss is properly set, but the deserialization completes with all values in the 'response' object being null or default values.

If instead i move the same JsonSerializerSettings local to assembly B, deserialization comes out fine...

I even tried to create a new JsonSerializerSettings FROM the one passed in, but that had the same null/default results.

My first inclination is to suspect it is not possible pass/use a JsonSerializerSettings from one assembly to/in another in this way, a static object as a action's parameter?

Might i be doing anything obviously wrong.

I apologia in advance to anyone feeling my question is not well formed, lacks information, or otherwise answered elsewhere, im trying to follow the rules...

Body:
1. JsonConvert returns nulls or defaults

The kind symptoms that you described that results your JsonConvert.DeserializeObject() method returning an object with nulls or defaults, occurs when you do not map your objects properly. Here is a small example to illustrate it.

class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Bar
{
    public int BarId { get; set; }
    public string BarName { get; set; }
}

void Main()
{
    var foo = new Foo()
    {
        Id = 1,
        Name = "One"
    };
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

    var bar = Newtonsoft.Json.JsonConvert.DeserializeObject<Bar>(json);
}

Here is the result of bar:

bar = { BarId = 0, BarName = null }

Incorrect mapping will result in nulls and defaults.

2. Pay attention to details when using a custom JsonConverter

Going further with the example above, when using a JsonConverter you also have to be aware of the mapping as well, as it's more prone to produce the same kind of problems from small typos or other errors.

MyCustomJsonSerializerSettings

public static class MyCustomJsonSerializerSettings
{
    private static JsonSerializerSettings _jss;

    public static JsonSerializerSettings Jss
    {
        get { return _jss; }
        private set { _jss = value; }
    }

    static MyCustomJsonSerializerSettings()
    {
        _jss = new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Error,
            NullValueHandling = NullValueHandling.Ignore,
            Converters = new List<JsonConverter>
            {
                new FooToBarConverter()
            }
        };
    }
}

FooToBarConverter

public class FooToBarConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        Foo foo = (Foo)value;
        JObject jo = new JObject();
        jo.Add("BarId", new JValue(foo.Id));     // make sure of your mapping!
        jo.Add("BarName", new JValue(foo.Name)); // make sure of your mapping!
        jo.WriteTo(writer);
    }

    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Make sure that you are properly mapping the object in the custom converter.

Putting it all together...

void Main()
{
    var foo = new Foo()
    {
        Id = 1,
        Name = "One"
    };

    string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
    var bar = Newtonsoft.Json.JsonConvert.DeserializeObject<Bar>(json); // nulls/defaults

    JsonSerializerSettings jss = MyCustomJsonSerializerSettings.Jss;
    string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(foo, jss); // note jss
    var bar2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Bar>(json2); // as expected!
}

3. Portability of the Converter Between Assemblies

To be 100% certain that the converters will get passed along with your settings, you can always do something like this

public class MyCustomJsonSerializerSettings // not a static class
{
    private static JsonSerializerSettings _jss;

    public static JsonSerializerSettings Jss
    {
        get { return _jss; }
        private set { _jss = value; }
    }

    static MyCustomJsonSerializerSettings()
    {
        _jss = new JsonSerializerSettings { ... };
    }

    private class FooToBarConverter : JsonConverter // note that it is contained within
                                                    // the class
    {
        ...
    }
}


问:
Different groups of checkbox not working in jquery
I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.

```<code><body>
    <div>
        <input type="checkbox" value="Lion" name="animals" checked />Lion<br>
        <input type="checkbox" value="Tiger" name="animals" />Tiger<br>
        <input type="checkbox" value="Elephant" name="animals" />Elephant<br>
        <input type="checkbox" value="Girafee" name="animals" />Girafee<br>
        <input type="submit" id="__mainAnimals" />
        <br><br><br><br><br><br>
        <input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
        <input type="checkbox" value="Tea" name="drinks" />Tea<br>
        <input type="checkbox" value="Milk" name="drinks" />Milk<br>
        <input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
        <input type="submit" id="__mainDrinks" />
    </div>
    <div id="__DIVresult"></div>

    <script type="text/javascript">
        $(document).ready(function () {
        $('#__mainAnimals').click(function () {
            getSelectedCheckBoxes('animals');
        });

        $('#__mainDrinks').click(function () {
            getSelectedCheckBoxes('drinks');
        });

        var getSelectedCheckBoxes = function (groupName) {
            var result = $('input[name="' + groupName + '"]:checked');
            if (result.length > 0) {
                var resultString = result.length + " checkboxe(s) checked<br/>";
                result.each(function () {
                    resultString += $(this).val() + "<br/>";
                });
                $('__DIVresult').html(resultString);
            }
            else {
                $('__DIVresult').html("No checkbox checked");
            }
        };
    });

    </script>

</body>
</code>```

答:
In your drink and animal section you are not separating the two so when you use your click function it doesn't discriminate between the tow sections. Once you add each one to a class then the button will only call the checked items that are actually checked.

```<code><html>
</code>```

```<code>   <form>
    <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Lion"  />Lion</br>
        <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Tiger" />Tiger</br>
        <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Elephant" />Elephant</br>
        <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Girafee" />Girafee</br>

    <input type="button" id="save_value" name="save_value" value="Save" /></br>
      <textarea id="t"></textarea>
        </form>
</code>```

Body:
I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.

        <input type="checkbox" value="Lion" name="animals" checked />Lion

        <input type="checkbox" value="Tiger" name="animals" />Tiger

        <input type="checkbox" value="Elephant" name="animals" />Elephant

        <input type="checkbox" value="Girafee" name="animals" />Girafee

        <input type="submit" id="__mainAnimals" />

        <input type="checkbox" value="Coffe" name="drinks" checked />Coffe

        <input type="checkbox" value="Tea" name="drinks" />Tea

        <input type="checkbox" value="Milk" name="drinks" />Milk

        <input type="checkbox" value="Mocha" name="drinks" />Mocha

        <input type="submit" id="__mainDrinks" />

Body:
In your drink and animal section you are not separating the two so when you use your click function it doesn't discriminate between the tow sections. Once you add each one to a class then the button will only call the checked items that are actually checked.

<html>

   <form>
    <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Lion"  />Lion</br>
        <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Tiger" />Tiger</br>
        <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Elephant" />Elephant</br>
        <input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Girafee" />Girafee</br>

    <input type="button" id="save_value" name="save_value" value="Save" /></br>
      <textarea id="t"></textarea>
        </form>


问:
How to select data from EAV structure with multiple values
Here is my sql structure

```<code>CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) unsigned NOT NULL,
  `sku` varchar(32) NOT NULL,
  `name` tinytext NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=409 ;

INSERT INTO `products` (`id`, `sku`, `name`, `created_at`, `updated_at`) VALUES
(1, '111', 'Item 1', '', '0000-00-00 00:00:00'),
(2, '222', 'Item 2', '', '0000-00-00 00:00:00'),
(3, '333', 'Item 3', '', '0000-00-00 00:00:00');

CREATE TABLE IF NOT EXISTS `product_attributes` (
`id` int(10) unsigned NOT NULL,
  `attribute_id` int(10) unsigned NOT NULL,
  `value_id` int(10) unsigned NOT NULL,
  `product_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4820 ;

INSERT INTO `product_attributes` (`id`, `attribute_id`, `value_id`, `product_id`) VALUES
(1, 11, 1, 1),
(2, 12, 2, 1),
(3, 13, 3, 1),
(4, 11, 1, 2),
(5, 12, 5, 2),
(6, 13, 6, 2),
(7, 11, 1, 3),
(8, 12, 8, 3),
(9, 13, 3, 3);
</code>```

I want to select products with n selected values. For example ((attribute_id=11 AND value_id=1) AND (attribute_id=13 AND value_id=3)). I expect to get product 1 and 3.

Try this query, but no luck

```<code>select
    p.id,
    p.name,
    pa.attribute_id,
    pa.value_id
FROM products p
JOIN product_attributes pa
ON p.id=pa.product_id
WHERE ((pa.attribute_id=11 AND pa.value_id=1) AND (pa.attribute_id=13 AND pa.value_id=3))
</code>```

答:
You need to use a solution similar to

How to return rows that have the same column values in MySql

but check multiple columns

```<code>SELECT product_id
FROM product_attributes AS pa
GROUP by product_id
HAVING SUM(pa.attribute_id=11 AND pa.value_id=1) > 0
AND SUM(pa.attribute_id=13 AND pa.value_id=3) > 0
</code>```

Another solution is to join the queries for each set of values.

```<code>SELECT pa1.product_id
FROM product_attributes AS pa1
JOIN product_attributes AS pa2 ON pa1.product_id = pa2.product_id
WHERE pa1.attribute_id=11 AND pa1.value_id=1
AND pa2.attribute_id=13 AND pa2.value_id=3
</code>```

Body:
Here is my sql structure

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) unsigned NOT NULL,
  `sku` varchar(32) NOT NULL,
  `name` tinytext NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=409 ;

INSERT INTO `products` (`id`, `sku`, `name`, `created_at`, `updated_at`) VALUES
(1, '111', 'Item 1', '', '0000-00-00 00:00:00'),
(2, '222', 'Item 2', '', '0000-00-00 00:00:00'),
(3, '333', 'Item 3', '', '0000-00-00 00:00:00');

CREATE TABLE IF NOT EXISTS `product_attributes` (
`id` int(10) unsigned NOT NULL,
  `attribute_id` int(10) unsigned NOT NULL,
  `value_id` int(10) unsigned NOT NULL,
  `product_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4820 ;

INSERT INTO `product_attributes` (`id`, `attribute_id`, `value_id`, `product_id`) VALUES
(1, 11, 1, 1),
(2, 12, 2, 1),
(3, 13, 3, 1),
(4, 11, 1, 2),
(5, 12, 5, 2),
(6, 13, 6, 2),
(7, 11, 1, 3),
(8, 12, 8, 3),
(9, 13, 3, 3);

I want to select products with n selected values. For example ((attribute_id=11 AND value_id=1) AND (attribute_id=13 AND value_id=3)). I expect to get product 1 and 3.

Try this query, but no luck

select
    p.id,
    p.name,
    pa.attribute_id,
    pa.value_id
FROM products p
JOIN product_attributes pa
ON p.id=pa.product_id
WHERE ((pa.attribute_id=11 AND pa.value_id=1) AND (pa.attribute_id=13 AND pa.value_id=3))

Body:
You need to use a solution similar to

How to return rows that have the same column values in MySql

but check multiple columns

SELECT product_id
FROM product_attributes AS pa
GROUP by product_id
HAVING SUM(pa.attribute_id=11 AND pa.value_id=1) > 0
AND SUM(pa.attribute_id=13 AND pa.value_id=3) > 0

Another solution is to join the queries for each set of values.

SELECT pa1.product_id
FROM product_attributes AS pa1
JOIN product_attributes AS pa2 ON pa1.product_id = pa2.product_id
WHERE pa1.attribute_id=11 AND pa1.value_id=1
AND pa2.attribute_id=13 AND pa2.value_id=3


问:
Methods vs Computed in Vue
What is the main difference between a method and a computed value in Vue.js?

They seem the same and interchangeable to me.

答:
Computed values and methods are very different in Vue and are definitely not interchangeable in most cases.

Computed Property

A more appropriate name for a computed value is a computed property. In fact, when the Vue is instantiated, computed properties are converted into a property of the Vue with a getter and sometimes a setter. Basically you can think of a computed value as a derived value that will be automatically updated whenever one of the underlying values used to calculate it is updated. You don't call a computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Here's the classic example from the documentation:

```<code>computed: {
  // a computed getter
  reversedMessage: function () {
    // `this` points to the vm instance
    return this.message.split('').reverse().join('')
  }
}
</code>```

Which is referenced in the DOM like this:

```<code><p>Computed reversed message: "{{ reversedMessage }}"</p>
</code>```

Computed values are very valuable for manipulating data that exists on your Vue. Whenever you want to filter or transform your data, typically you will use a computed value for that purpose.

```<code>data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.names.filter(n => n.startsWith("B"))
    }
}

<p v-for="name in startsWithB">{{name}}</p>
</code>```

Computed values are also cached to avoid repetitively calculating a value that doesn't need to be re-calculated when it hasn't changed (as it might not be in a loop for example).

Method

A method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. Like all javascript functions, it accepts parameters and will be re-evaluated every time it's called. Methods are useful in the same situations any function is useful.

```<code>data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.startsWithChar("B")
    },
    startsWithM(){
        return this.startsWithChar("M")
    }
},
methods:{
    startsWithChar(whichChar){
        return this.names.filter(n => n.startsWith(whichChar))
    }
}
</code>```

Vue's documentation is really good and easily accessible. I recommend it.

Title: Methods vs Computed in Vue

Body:
Computed values and methods are very different in Vue and are definitely not interchangeable in most cases.

Computed Property

A more appropriate name for a computed value is a computed property. In fact, when the Vue is instantiated, computed properties are converted into a property of the Vue with a getter and sometimes a setter. Basically you can think of a computed value as a derived value that will be automatically updated whenever one of the underlying values used to calculate it is updated. You don't call a computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Here's the classic example from the documentation:

computed: {
  // a computed getter
  reversedMessage: function () {
    // `this` points to the vm instance
    return this.message.split('').reverse().join('')
  }
}

Which is referenced in the DOM like this:

<p>Computed reversed message: "{{ reversedMessage }}"</p>

Computed values are very valuable for manipulating data that exists on your Vue. Whenever you want to filter or transform your data, typically you will use a computed value for that purpose.

data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.names.filter(n => n.startsWith("B"))
    }
}

<p v-for="name in startsWithB">{{name}}</p>

Computed values are also cached to avoid repetitively calculating a value that doesn't need to be re-calculated when it hasn't changed (as it might not be in a loop for example).

Method

A method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. Like all javascript functions, it accepts parameters and will be re-evaluated every time it's called. Methods are useful in the same situations any function is useful.

data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.startsWithChar("B")
    },
    startsWithM(){
        return this.startsWithChar("M")
    }
},
methods:{
    startsWithChar(whichChar){
        return this.names.filter(n => n.startsWith(whichChar))
    }
}

Vue's documentation is really good and easily accessible. I recommend it.