问:
remove all fields from 2nd col which is not 5 consecutive numerical digits
```<code> Record | RegistrationID

 41-1|10551
 1-105|5569
  4-7|10043
  78-3|2176
   3-1|19826
   12-1|1981
</code>```

Output file has to

```<code> Record | RegistrationID
1-1|10551
3-1|19826
5-7|10043
</code>```

My file is a Pipe delimited

any number in the 2nd col which is less than or more than 5lenght must be removed i.e only records that have 5 consecutive numbers must remain.I'm with google since an hour to fix this out any advice given would be highly appreciable. thanks in advance

tried this grep -E ' [0-9]{5}$|$' filename   - > not getting any results ,tx to cyrus

答:
If your columns (fields) are |-separated, may contain spaces, and the filtering criteria is exactly 5 digits in the second field, then try this:

```<code>awk -F'|' '$2 ~ /^[ ]*[0-9]{5}[ ]*$/' file
</code>```

Additionally, to pass-through the header (first) line in addition:

```<code>awk -F'|' 'NR==1 || $2 ~ /^[ ]*[0-9]{5}[ ]*$/' file
</code>```

Body:
 Record | RegistrationID

 41-1|10551
 1-105|5569
  4-7|10043
  78-3|2176
   3-1|19826
   12-1|1981

Output file has to

 Record | RegistrationID
1-1|10551
3-1|19826
5-7|10043

My file is a Pipe delimited

any number in the 2nd col which is less than or more than 5lenght must be removed i.e only records that have 5 consecutive numbers must remain.I'm with google since an hour to fix this out any advice given would be highly appreciable. thanks in advance

tried this grep -E ' [0-9]{5}$|$' filename   - > not getting any results ,tx to cyrus

Body:
If your columns (fields) are |-separated, may contain spaces, and the filtering criteria is exactly 5 digits in the second field, then try this:

awk -F'|' '$2 ~ /^[ ]*[0-9]{5}[ ]*$/' file

Additionally, to pass-through the header (first) line in addition:

awk -F'|' 'NR==1 || $2 ~ /^[ ]*[0-9]{5}[ ]*$/' file


来源: stackexchange

问:
What does "&!" (ampersand and exclamation) mean in linux shell
I found that some people run a program in shell like this

```<code>exe > the.log 2>&1 &!
</code>```

I understand the first part, it redirects stderr to stdout also "&" means runs the program in background, but I don't know what does "&!" mean, what does the exclamation mark mean?

答:
Within zsh the command &! is a shortcut for disown, i.e. the program won't get killed upon exiting the invoking shell.

See man zshbuiltins

disown [ job ... ]

job ... &|

job ... &!

Remove the specified jobs from the job table; the shell will no longer report their status, and will not complain if you try to exit an interactive shell with them running or stopped. If no job is specified, disown the current job. If the jobs are currently stopped and the AUTO_CONTINUE option is not set, a warning is printed containing information about how to make them running after they have been disowned. If one of the latter two forms is used, the jobs will automatically be made running, independent of the setting of the AUTO_CONTINUE option.

ContentLicense: CC BY-SA 3.0

Body:
I found that some people run a program in shell like this

exe > the.log 2>&1 &!

I understand the first part, it redirects stderr to stdout also "&" means runs the program in background, but I don't know what does "&!" mean, what does the exclamation mark mean?


问:
how to pass current row into a oracle user defined function
I want to create an inline oracle function which will refer the column values of the current row being fetched and to return a value as per my conditions. I tried the same by passing ROWID into function and in the function body current row will be fetched using ROWID and manipulate the values.

```<code>CREATE FUNCTION CHECK_STATUS(P_ROWID) RETURN VARCHAR2 IS
   V_ROW MY_TBL%TYPE
BEGIN
   SELECT * INTO V_ROW FROM MY_TBL WHERE ROWID=P_ROWID;
   IF V_ROW.COL1 IS NOT NULL AND
       V_ROW.COL2 IS NOT NULL AND
       V_ROW.COL3 IS NOT NULL THEN

       RETURN 'OK';
   ELSE
      RETURN 'INCOMPLETE';
   END IF;
END;
</code>```

This function is further called at various places as

```<code>SELECT A.*,CHECK_STATUS(ROWID) FROM MY_TBL A;
</code>```

it works but slows down the query badly over a thousand records because on each fetch of rows function will again do a select query for getting the column values. I know that this can also be done as

```<code>   CREATE FUNCTION CHECK_STATUS(COL1,COL2,COL3) RETURN VARCHAR2 IS
</code>```

here the problem is that i want to nearly check 9 column values in the function and it looks odd to write the column name during every call of the function. I doubt is there any method that the function can refer the current row being fetched without receiving ROWID/ COLUMNS through parameter something like (THIS.COL1,THIS.COL2,THIS.COL3)

答:
You could add a virtual column for this, using a case expression, and not have a function at all:

```<code>alter table my_tbl add (status generated always as
  (case when column1 is null or column2 is null or column3 is null
    -- etc., all 9 columns or whatever else you want to check
    then 'INCOMPLETE' else 'OK' end) virtual);
</code>```

You can then query it with:

```<code>select column1, column2, ..., status from my_tbl
</code>```

You can also add an index on the virtual column if that's useful for how you'll use it.

You could still use a (deterministic) function if you wanted to, with all the column values passed in - the 'looks odd' part would be hidden in the DDL, so queries wouldn't see it. It doesn't sound like using a function would add much in this case though.

Body:
I want to create an inline oracle function which will refer the column values of the current row being fetched and to return a value as per my conditions. I tried the same by passing ROWID into function and in the function body current row will be fetched using ROWID and manipulate the values.

CREATE FUNCTION CHECK_STATUS(P_ROWID) RETURN VARCHAR2 IS
   V_ROW MY_TBL%TYPE
BEGIN
   SELECT * INTO V_ROW FROM MY_TBL WHERE ROWID=P_ROWID;
   IF V_ROW.COL1 IS NOT NULL AND
       V_ROW.COL2 IS NOT NULL AND
       V_ROW.COL3 IS NOT NULL THEN

       RETURN 'OK';
   ELSE
      RETURN 'INCOMPLETE';
   END IF;
END;

This function is further called at various places as

SELECT A.*,CHECK_STATUS(ROWID) FROM MY_TBL A;

it works but slows down the query badly over a thousand records because on each fetch of rows function will again do a select query for getting the column values. I know that this can also be done as

   CREATE FUNCTION CHECK_STATUS(COL1,COL2,COL3) RETURN VARCHAR2 IS

here the problem is that i want to nearly check 9 column values in the function and it looks odd to write the column name during every call of the function. I doubt is there any method that the function can refer the current row being fetched without receiving ROWID/ COLUMNS through parameter something like (THIS.COL1,THIS.COL2,THIS.COL3)

Body:
You could add a virtual column for this, using a case expression, and not have a function at all:

alter table my_tbl add (status generated always as
  (case when column1 is null or column2 is null or column3 is null
    -- etc., all 9 columns or whatever else you want to check
    then 'INCOMPLETE' else 'OK' end) virtual);

You can then query it with:

select column1, column2, ..., status from my_tbl

You can also add an index on the virtual column if that's useful for how you'll use it.

You could still use a (deterministic) function if you wanted to, with all the column values passed in - the 'looks odd' part would be hidden in the DDL, so queries wouldn't see it. It doesn't sound like using a function would add much in this case though.


问:
json mapping issue c#
unable to create a class to deserailize this json c# cause the number is causing issue while mapping any help is appreciated
inception of creating class itself is the problem</p>

```<code>{//this is the class name
"1504076400": {
    "VenueKey": "the-gazebo",
    "IsShortBook": false,
    "IsSaturday": false,
    "Slots": [{
            "TS": 1504098000,
            "String": "08-30-2017 6:00 AM",
            "IsAvailable": false
        },
        {
            "TS": 1504099800,
            "String": "08-30-2017 6:30 AM",
            "IsAvailable": false
        }
    ]
},//these numbers are causing problem
"1504162800": {
    "VenueKey": "the-gazebo",
    "IsShortBook": false,
    "IsSaturday": false,
    "Slots": [{
            "TS": 1504184400,
            "String": "08-31-2017 6:00 AM",
            "IsAvailable": false
        },
        {
            "TS": 1504186200,
            "String": "08-31-2017 6:30 AM",
            "IsAvailable": false
        }
    ]
}
}
</code>```

答:
I do not see problems neither deserialization nor json. Model classe can look like:

```<code>class Venue
{
    public string VenueKey { get; set; }

    public bool IsShortBook { get; set; }

    public bool IsSaturday { get; set; }

    public Slot[] Slots { get; set; }
}

class Slot
{
    public string TS { get; set; }

    public string @String { get; set; }

    public bool ISAvailable { get; set; }
}
</code>```

And desirialization works fine:
JsonConvert.DeserializeObject<Dictionary<string, Venue>>(json);

Title: json mapping issue c#

Body:
unable to create a class to deserailize this json c# cause the number is causing issue while mapping any help is appreciated
inception of creating class itself is the problem

{//this is the class name
"1504076400": {
    "VenueKey": "the-gazebo",
    "IsShortBook": false,
    "IsSaturday": false,
    "Slots": [{
            "TS": 1504098000,
            "String": "08-30-2017 6:00 AM",
            "IsAvailable": false
        },
        {
            "TS": 1504099800,
            "String": "08-30-2017 6:30 AM",
            "IsAvailable": false
        }
    ]
},//these numbers are causing problem
"1504162800": {
    "VenueKey": "the-gazebo",
    "IsShortBook": false,
    "IsSaturday": false,
    "Slots": [{
            "TS": 1504184400,
            "String": "08-31-2017 6:00 AM",
            "IsAvailable": false
        },
        {
            "TS": 1504186200,
            "String": "08-31-2017 6:30 AM",
            "IsAvailable": false
        }
    ]
}
}

Body:
I do not see problems neither deserialization nor json. Model classe can look like:

class Venue
{
    public string VenueKey { get; set; }

    public bool IsShortBook { get; set; }

    public bool IsSaturday { get; set; }

    public Slot[] Slots { get; set; }
}

class Slot
{
    public string TS { get; set; }

    public string @String { get; set; }

    public bool ISAvailable { get; set; }
}

And desirialization works fine:
JsonConvert.DeserializeObject<Dictionary<string, Venue>>(json);


问:
Computing the nth derivative of a function
To compute a probability, I have to compute derivatives (and then evaluate) like $\frac{\partial^5 f}{\partial x_1^2 \partial x_2^3}$ where $f$ is a polynomial function. The problem is that the order of the derivative is likely to vary as well as the list of variables with respect to which the derivative is computed.

I already tried with rSymPy and Ryacas and it works... until the number of variables becomes to important. So I have to look for a different solution. I tried with the DD() function indicated in the documentation of deriv() and using this function iteratively seems to be fine (and unexpectedly more efficient than with rSymPy and Ryacas).

My problem is to create the DD(DD(DD(...my.expr...,"xi",ni),"xj",nj),"xk",nk) command. I tried the following code:

```<code>step1 <- function(k) paste0(",x", k, ",", r[k]-1, ")", collapse="")
step2 <- function(expr) {
           paste0(paste0(rep.int("DD(",u), collapse=""), expr,
           paste0(sapply(t,f4), collapse=""), collapse="") }
step2(f)
</code>```

where r is a vector indicating the order of derivation for each variable, t a subset of that vector, u <- length(t) and f is an expression object. This solution does not works because quotation marks are missing around variable names. Indeed I get for instance (I dropped the function from the code):

```<code>DD(DD(DD(DD(DD(my.expr,x1,1),x7,1),x9,2),x10,1),x11,1)
</code>```

instead of:

```<code>DD(DD(DD(DD(DD(my.expr,"x1",1),"x7",1),"x9",2),"x10",1),"x11",1)
</code>```

I tried adding \" in my function step1, but I have then a problem with the computation of the derivative. Any suggestion to fix this problem?

PS: it would surely be easier with a loop, but I would like to avoid if possible.

PS2: Sorry for LaTeX code.

答:
I think this extension works.  The trick is to not start going back and forth between expressions and strings ...

```<code>DD <- function(expr, names, order = 1, debug=FALSE) {
    if (any(order>=1)) {  ## do we need to do any more work?
        w <- which(order>=1)[1]  ## find a derivative to compute
        if (debug) {
            cat(names,order,w,"\n")
        }
        ## update order
        order[w] <- order[w]-1
        ## recurse ...
        return(DD(D(expr,names[w]), names, order, debug))
    }
    return(expr)
}
</code>```

Some tests:

```<code>DD(expression(x^2*y^3+z),c("x","y"),c(1,1))
## 2 * x * (3 * y^2)
DD(expression(x^2*y^3+z),c("x","y"),c(2,1))
## 2*3*(y^2)
DD(expression(x^2*y^3+z),c("x","y"),c(2,2))
## 2*(3*(2*y))
DD(expression(x^2*y^3+z),c("x","y"),c(2,3))
## 2*(3*2)
DD(expression(x^2*y^3+z),c("x","y"),c(2,4))
## 0
</code>```

I hadn't noticed previously that you were differentiating a polynomial -- in that special case there's a much simpler answer (hint, represent the polynomial as a sequence of vectors that give the coefficients of orders of different terms).  But you may not need that efficient an answer ...

Body:
To compute a probability, I have to compute derivatives (and then evaluate) like $\frac{\partial^5 f}{\partial x_1^2 \partial x_2^3}$ where $f$ is a polynomial function. The problem is that the order of the derivative is likely to vary as well as the list of variables with respect to which the derivative is computed.

I already tried with rSymPy and Ryacas and it works... until the number of variables becomes to important. So I have to look for a different solution. I tried with the DD() function indicated in the documentation of deriv() and using this function iteratively seems to be fine (and unexpectedly more efficient than with rSymPy and Ryacas).

My problem is to create the DD(DD(DD(...my.expr...,"xi",ni),"xj",nj),"xk",nk) command. I tried the following code:

step1 <- function(k) paste0(",x", k, ",", r[k]-1, ")", collapse="")
step2 <- function(expr) {
           paste0(paste0(rep.int("DD(",u), collapse=""), expr,
           paste0(sapply(t,f4), collapse=""), collapse="") }
step2(f)

where r is a vector indicating the order of derivation for each variable, t a subset of that vector, u <- length(t) and f is an expression object. This solution does not works because quotation marks are missing around variable names. Indeed I get for instance (I dropped the function from the code):

DD(DD(DD(DD(DD(my.expr,x1,1),x7,1),x9,2),x10,1),x11,1)

instead of:

DD(DD(DD(DD(DD(my.expr,"x1",1),"x7",1),"x9",2),"x10",1),"x11",1)

I tried adding \" in my function step1, but I have then a problem with the computation of the derivative. Any suggestion to fix this problem?

PS: it would surely be easier with a loop, but I would like to avoid if possible.

PS2: Sorry for LaTeX code.

Body:
I think this extension works.  The trick is to not start going back and forth between expressions and strings ...

DD <- function(expr, names, order = 1, debug=FALSE) {
    if (any(order>=1)) {  ## do we need to do any more work?
        w <- which(order>=1)[1]  ## find a derivative to compute
        if (debug) {
            cat(names,order,w,"\n")
        }
        ## update order
        order[w] <- order[w]-1
        ## recurse ...
        return(DD(D(expr,names[w]), names, order, debug))
    }
    return(expr)
}

Some tests:

DD(expression(x^2*y^3+z),c("x","y"),c(1,1))
## 2 * x * (3 * y^2)
DD(expression(x^2*y^3+z),c("x","y"),c(2,1))
## 2*3*(y^2)
DD(expression(x^2*y^3+z),c("x","y"),c(2,2))
## 2*(3*(2*y))
DD(expression(x^2*y^3+z),c("x","y"),c(2,3))
## 2*(3*2)
DD(expression(x^2*y^3+z),c("x","y"),c(2,4))
## 0

I hadn't noticed previously that you were differentiating a polynomial -- in that special case there's a much simpler answer (hint, represent the polynomial as a sequence of vectors that give the coefficients of orders of different terms).  But you may not need that efficient an answer ...


问:
data frame names as word in quotation mark
I have two part question, both concerns working with data frames names:

I want to concatenate two dfs names with separator, for example: df1 and df2 to be "df1_&_df2"

I want  make R to read data frame name as character in quotation marks so my df is called df1 and I in certain parts of my code I want it to be "df1".

When it come to 1st part I tried paste but it pasted entire data in both dfs and names concerns column names.

In the 2nd issue, being able to make R understand df name as quotation marked word is very handy in code for more complex charts, I simply put dfs into code and R makes chart title out of it. I understand there is very simple workaround here, I can create list of names manually  list=c("df1", "df2") and then just use function get in places where I need to refer to content of data frame instead of its name, but it seems little inconvenient in the long run. Is there any function in R which output is just df name? Something that looks like GiveMeName(df) and the output is "df"? (I wrote this in normal font intentionally, so no one would thought this is real function)

答:
Adding on to the answer by @Nathan Werth, you can concatenate names using:</p>

```<code>paste(deparse(substitute(df1)), deparse(substitute(df2)), sep="_&_")
</code>```

Body:
Adding on to the answer by @Nathan Werth, you can concatenate names using:

paste(deparse(substitute(df1)), deparse(substitute(df2)), sep="_&_")


问:
use of generic list
```<code>struct node
{
    void *data;
    struct node *link;
};
</code>```

Given such a structure we call it as generic linked list.what is the use of such a list in terms of its real time application use.

答:
You have a service which accepts requests from multiple applications and provides handle to each of them. The service can maintain the contexts per request in a linked list and when its done serving them delete the node from the list. A empty linked list in that case would mean no application has registered to the service.

For Eg, Consider the service built over SIP stack and multiple applications like IM, Presence information can register with the service which uses the SIP stack for signalling. Now the service maintains the data pertaining to each of the application in a linked list(well that is again a question of design but lets assume we have a limit to serve 5 applications). The SIP response has to be redirected to the application sending the request and say you hold the callback pointer as one value of the node it is simple to call it once you find the corresponding node for the response.

Each node saves lot of information about every application and uses it for sending back the response to the application.

Probably you may want to have a look at this.

ContentLicense: CC BY-SA 2.5

Title: use of generic list

Body:
struct node
{
    void *data;
    struct node *link;
};

Given such a structure we call it as generic linked list.what is the use of such a list in terms of its real time application use.


问:
Check for duplicate characters in string using for-in loops in Swift
I did this using while loops but I'm wondering if there's a way to do this with for loops. I'm trying to write this clean so I can write it on a whiteboard for people to understand.</p>
```<code>var str = "Have a nice day"

func unique(_ str: String) -> String {
    var firstIndex = str.startIndex

    while (firstIndex != str.endIndex) {
        var secondIndex = str.index(after: firstIndex)

        while (secondIndex != str.endIndex) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
            secondIndex = str.index(after: secondIndex)
        }
        firstIndex = str.index(after: firstIndex)
    }
    return "All the characters are unique"
}

print("\(unique(str))")
</code>```

答:
You can use the indices of the characters:</p>

```<code>var str = "Have a nice day"

func unique(_ str: String) -> String {
    for firstIndex in str.characters.indices {
        for secondIndex in str.characters.indices.suffix(from: str.index(after: firstIndex)) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}

print("\(unique(str))")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I did this using while loops but I'm wondering if there's a way to do this with for loops. I'm trying to write this clean so I can write it on a whiteboard for people to understand.

var str = "Have a nice day"

func unique(_ str: String) -> String {
    var firstIndex = str.startIndex

    while (firstIndex != str.endIndex) {
        var secondIndex = str.index(after: firstIndex)

        while (secondIndex != str.endIndex) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
            secondIndex = str.index(after: secondIndex)
        }
        firstIndex = str.index(after: firstIndex)
    }
    return "All the characters are unique"
}

print("\(unique(str))")

Body:
You can use the indices of the characters:

var str = "Have a nice day"

func unique(_ str: String) -> String {
    for firstIndex in str.characters.indices {
        for secondIndex in str.characters.indices.suffix(from: str.index(after: firstIndex)) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}

print("\(unique(str))")


问:
ES6 Iterate over class methods
Given this class; how would i iterate over the methods that it includes?

```<code>class Animal {
    constructor(type){
        this.animalType = type;
    }
    getAnimalType(){
        console.log('this.animalType: ', this.animalType );
    }
}

let cat = window.cat = new Animal('cat')
</code>```

What I have tried is the following with no success:

```<code>for (var each in Object.getPrototypeOf(cat) ){
    console.log(each);
}
</code>```

答:
If you need to get superclass methods as well, you can call Object.getPrototypeOf() repeatedly until you find them all.  You'll probably want to stop when you get to Object.prototype, because the methods in there are fundamental and you usually don't want to touch them with any code that uses reflection.

The question Get functions (methods) of a class has an answer that includes a function for doing this, but it had a few shortcomings (including using a loop condition which had a side effect of modifying a function argument, which I figure makes two questionable code style choices in a single line of code...), so I've rewritten it here:

```<code>export function listMethodNames (object, downToClass = Object)
{
    // based on code by Muhammad Umer, https://stackoverflow.com/a/31055217/441899
    let props = [];

    for (let obj = object; obj !== null && obj !== downToClass.prototype; obj = Object.getPrototypeOf(obj))
    {
        props = props.concat(Object.getOwnPropertyNames(obj));
    }

    return props.sort().filter((e, i, arr) => e != arr[i+1] && typeof object[e] == 'function');
}
</code>```

As well as fixing the bug in the original code (which didn't copy the object into another variable for the loop, so by the time it was used for filtering in the return line it was no longer valid) this gives an optional argument to stop the iteration at a configurable class.  It'll default to Object (so Object's methods are excluded; if you want to include them you can use a class that doesn't appear in the inheritance chain... perhaps making a marker class e.g. class IncludeObjectMethods{} might make sense).  I've also changed the do loop to a clearer for loop and rewritten the old-style function ... filter function into an ES6 arrow function to make the code more compact.

Title: ES6 Iterate over class methods

Body:
Given this class; how would i iterate over the methods that it includes?

class Animal {
    constructor(type){
        this.animalType = type;
    }
    getAnimalType(){
        console.log('this.animalType: ', this.animalType );
    }
}

let cat = window.cat = new Animal('cat')

What I have tried is the following with no success:

for (var each in Object.getPrototypeOf(cat) ){
    console.log(each);
}

Body:
If you need to get superclass methods as well, you can call Object.getPrototypeOf() repeatedly until you find them all.  You'll probably want to stop when you get to Object.prototype, because the methods in there are fundamental and you usually don't want to touch them with any code that uses reflection.

The question Get functions (methods) of a class has an answer that includes a function for doing this, but it had a few shortcomings (including using a loop condition which had a side effect of modifying a function argument, which I figure makes two questionable code style choices in a single line of code...), so I've rewritten it here:

export function listMethodNames (object, downToClass = Object)
{
    // based on code by Muhammad Umer, https://stackoverflow.com/a/31055217/441899
    let props = [];

    for (let obj = object; obj !== null && obj !== downToClass.prototype; obj = Object.getPrototypeOf(obj))
    {
        props = props.concat(Object.getOwnPropertyNames(obj));
    }

    return props.sort().filter((e, i, arr) => e != arr[i+1] && typeof object[e] == 'function');
}

As well as fixing the bug in the original code (which didn't copy the object into another variable for the loop, so by the time it was used for filtering in the return line it was no longer valid) this gives an optional argument to stop the iteration at a configurable class.  It'll default to Object (so Object's methods are excluded; if you want to include them you can use a class that doesn't appear in the inheritance chain... perhaps making a marker class e.g. class IncludeObjectMethods{} might make sense).  I've also changed the do loop to a clearer for loop and rewritten the old-style function ... filter function into an ES6 arrow function to make the code more compact.


问:
Appending a Matrix in Python within loop
I have a matrix y with size (3,3). Say it is a 3 by 3 matrix with all elements = 1.

I then have a loop to create multiple (3,3) matrices.
So these are the outputs:

First loop I get this matrix:

```<code> [[  88.    42.5    9. ]
 [ 121.5   76.    42.5]
 [ 167.   121.5   88. ]]
</code>```

The second loop I get:

```<code> [[  88.    42.5   13. ]
 [ 117.5   72.    42.5]
 [ 163.   117.5   88. ]]
</code>```

So what I would like to achieve is essentially

```<code> [[1, 1, 1] [88, 42.5, 9] [88, 42.5, 13],
 [1, 1, 1] [121.5, 76, 42.5] [117.5, 72, 42.5],
 [1, 1, 1] [167, 121.5, 88] [163, 117.5, 88]]
</code>```

This is assuming the loop iterates twice, and I am not sure if I have placed the commas or the spacing etc in the right place but ideally I obtain a 3 by 3 matrix with each element having a list with 3 elements.

My code I have so far for the loop is (Up_xyz,Mid_xyz,Down_xyz outputs in [x,x,x] format)  :

```<code>for i in range (1,len(PeopleName)):
  x = np.vstack((Up_xyz(TempName[i]),Mid_xyz(TempName[i]),Down_xyz(TempName[i])))
restA.append(x)
l+=1
</code>```

Which results in:

```<code>   [array([[  88. ,   42.5,   13. ],
   [ 117.5,   72. ,   42.5],
   [ 163. ,  117.5,   88. ]])]
</code>```

Which is simply the value from the last iteration of the loop.

Also, when I append y to restA with

```<code>print(y.append(restA))
</code>```

I get this error:

```<code>'numpy.ndarray' object has no attribute 'append'
</code>```

I assume this is due to the difference in sizing. But I would appreciate any help, and I am fairly new to Python, so would be open to any other ways that would be more efficient as well. Thanks

答:
It exists np.append, but it is very costly in a loop (if you append one by one). See documentation:

A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

A copy the array is done for each increment of your loop (here it is only 3 increments but I think it is not a good practice to do that, be aware)

Ok you have 3 arrays, and you want to merge each one:

```<code>import numpy as np

a = np.array([[ 1.,  1.,  1.],
              [ 1.,  1.,  1.],
              [ 1.,  1.,  1.]])

b = np.array([[  88.,    42.5,    9. ],
              [ 121.5,   76.,    42.5],
              [ 167.,  121.5,   88. ]])

c = np.array([[  88.,    42.5,   13. ],
              [ 117.5,   72.,    42.5],
              [ 163.,   117.5,  88. ]])

result = np.empty((3,3), dtype=object)

n, p = result.shape
for i in range(n):
      result[i, 0] = a[i,:]
      result[i, 1] = b[i,:]
      result[i, 2] = c[i,:]

print(result)
</code>```

Output:

```<code>array([[array([ 1.,  1.,  1.]), array([ 88. ,  42.5,   9. ]),
       array([ 88. ,  42.5,  13. ])],
       [array([ 1.,  1.,  1.]), array([ 121.5,   76. ,   42.5]),
        array([ 117.5,   72. ,   42.5])],
       [array([ 1.,  1.,  1.]), array([ 167. ,  121.5,   88. ]),
        array([ 163. ,  117.5,   88. ])]], dtype=object)
</code>```

If you want list instead of np.array do:

```<code>n, p = result.shape
for i in range(n):
    result[i, 0] = a[i,:].tolist()
    result[i, 1] = b[i,:].tolist()
    result[i, 2] = c[i,:].tolist()

print(result)
</code>```

Output:

```<code>[[[1.0, 1.0, 1.0] [88.0, 42.5, 9.0] [88.0, 42.5, 13.0]]
 [[1.0, 1.0, 1.0] [121.5, 76.0, 42.5] [117.5, 72.0, 42.5]]
 [[1.0, 1.0, 1.0] [167.0, 121.5, 88.0] [163.0, 117.5, 88.0]]]
</code>```

It is a bit strange to have a 2D array where each element is a 1D array.

You can directly have a 3D array (3,3,3) shape with :

```<code>np.stack([a,b,c])
</code>```

Body:
I have a matrix y with size (3,3). Say it is a 3 by 3 matrix with all elements = 1.

I then have a loop to create multiple (3,3) matrices.
So these are the outputs:

First loop I get this matrix:

 [[  88.    42.5    9. ]
 [ 121.5   76.    42.5]
 [ 167.   121.5   88. ]]

The second loop I get:

 [[  88.    42.5   13. ]
 [ 117.5   72.    42.5]
 [ 163.   117.5   88. ]]

So what I would like to achieve is essentially

 [[1, 1, 1] [88, 42.5, 9] [88, 42.5, 13],
 [1, 1, 1] [121.5, 76, 42.5] [117.5, 72, 42.5],
 [1, 1, 1] [167, 121.5, 88] [163, 117.5, 88]]

This is assuming the loop iterates twice, and I am not sure if I have placed the commas or the spacing etc in the right place but ideally I obtain a 3 by 3 matrix with each element having a list with 3 elements.

My code I have so far for the loop is (Up_xyz,Mid_xyz,Down_xyz outputs in [x,x,x] format)  :

for i in range (1,len(PeopleName)):
  x = np.vstack((Up_xyz(TempName[i]),Mid_xyz(TempName[i]),Down_xyz(TempName[i])))
restA.append(x)
l+=1

Which results in:

   [array([[  88. ,   42.5,   13. ],
   [ 117.5,   72. ,   42.5],
   [ 163. ,  117.5,   88. ]])]

Which is simply the value from the last iteration of the loop.

Also, when I append y to restA with

print(y.append(restA))

I get this error:

'numpy.ndarray' object has no attribute 'append'

I assume this is due to the difference in sizing. But I would appreciate any help, and I am fairly new to Python, so would be open to any other ways that would be more efficient as well. Thanks

Body:
It exists np.append, but it is very costly in a loop (if you append one by one). See documentation:

A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.

A copy the array is done for each increment of your loop (here it is only 3 increments but I think it is not a good practice to do that, be aware)

Ok you have 3 arrays, and you want to merge each one:

import numpy as np

a = np.array([[ 1.,  1.,  1.],
              [ 1.,  1.,  1.],
              [ 1.,  1.,  1.]])

b = np.array([[  88.,    42.5,    9. ],
              [ 121.5,   76.,    42.5],
              [ 167.,  121.5,   88. ]])

c = np.array([[  88.,    42.5,   13. ],
              [ 117.5,   72.,    42.5],
              [ 163.,   117.5,  88. ]])

result = np.empty((3,3), dtype=object)

n, p = result.shape
for i in range(n):
      result[i, 0] = a[i,:]
      result[i, 1] = b[i,:]
      result[i, 2] = c[i,:]

print(result)

Output:

array([[array([ 1.,  1.,  1.]), array([ 88. ,  42.5,   9. ]),
       array([ 88. ,  42.5,  13. ])],
       [array([ 1.,  1.,  1.]), array([ 121.5,   76. ,   42.5]),
        array([ 117.5,   72. ,   42.5])],
       [array([ 1.,  1.,  1.]), array([ 167. ,  121.5,   88. ]),
        array([ 163. ,  117.5,   88. ])]], dtype=object)

If you want list instead of np.array do:

n, p = result.shape
for i in range(n):
    result[i, 0] = a[i,:].tolist()
    result[i, 1] = b[i,:].tolist()
    result[i, 2] = c[i,:].tolist()

print(result)

Output:

[[[1.0, 1.0, 1.0] [88.0, 42.5, 9.0] [88.0, 42.5, 13.0]]
 [[1.0, 1.0, 1.0] [121.5, 76.0, 42.5] [117.5, 72.0, 42.5]]
 [[1.0, 1.0, 1.0] [167.0, 121.5, 88.0] [163.0, 117.5, 88.0]]]

It is a bit strange to have a 2D array where each element is a 1D array.

You can directly have a 3D array (3,3,3) shape with :

np.stack([a,b,c])


问:
How to insert Item to a collectionView ? Swift3
I am creating a chatting app in Xcode 8 with Swift 3 and I am using collectionView for the messages. but I am having an issue with inserting a new item to the collection view when press send:

```<code>msg.append(message) // msg : Messages Array
let item = msg.count - 1
let IndexPath = NSIndexPath(item: item, section: 0)
self.collectionView.insertItems(at: [IndexPath])
</code>```

error show up ( Ambiguous reference to member 'collectionView(_:numberOfItemsInSection:)'

How to solve this issue. and is working with storyboard effecting the work with collectionView because I cannot change the cell size with :

```<code> public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let messageText = msg[indexPath.item].text {
            let size = CGSize(width: 250 , height: 1000)
            let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let esf = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: CGFloat(18))], context: nil)
            print("Changed")
            return CGSize(dictionaryRepresentation: esf as! CFDictionary)!
        }

          print("Not Changed")
        return CGSize(width: view.frame.width, height: CGFloat(100))

    }
</code>```

I have but a break point and it has not been reached!

答:
in my case i reference
self.tableView.SOMEMETHOD
but there is no outlet exist with name "tableView".
please review your code, i think it's issue of outlet

Body:
I am creating a chatting app in Xcode 8 with Swift 3 and I am using collectionView for the messages. but I am having an issue with inserting a new item to the collection view when press send:

msg.append(message) // msg : Messages Array
let item = msg.count - 1
let IndexPath = NSIndexPath(item: item, section: 0)
self.collectionView.insertItems(at: [IndexPath])

error show up ( Ambiguous reference to member 'collectionView(_:numberOfItemsInSection:)'

How to solve this issue. and is working with storyboard effecting the work with collectionView because I cannot change the cell size with :

 public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let messageText = msg[indexPath.item].text {
            let size = CGSize(width: 250 , height: 1000)
            let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let esf = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: CGFloat(18))], context: nil)
            print("Changed")
            return CGSize(dictionaryRepresentation: esf as! CFDictionary)!
        }

          print("Not Changed")
        return CGSize(width: view.frame.width, height: CGFloat(100))

    }

I have but a break point and it has not been reached!


问:
Simple regex - ignoring certain characters
I'm trying to use the match method with an argument of a regex to select a valid phone number, by definition, any string with nine digits.

For example:

9347584987 is valid,

(456)322-3456 is valid,

(324)5688890 is valid.

But

(340)HelloWorld is NOT valid and

456748 is NOT valid.

So far, I'm able to use \d{9} to select the example string of 9 digit characters in a row, but I'm not sure how to specifically ignore any character, such as '-' or '(' or ')' in the middle of the sequence.

What kind of Regex could I use here?

答:
Pattern:  (Rubular Demo)

```<code>^\(?\d{3}\)?\d{3}-?\d{4}$   # this makes the expected symbols optional
</code>```

This pattern will ensure that an opening ( at the start of the string is followed by 3 numbers the a closing ).

```<code>^(\(\d{3}\)|\d{3})\d{3}-?\d{4}$
</code>```

On principle, though, I agree with melpomene in advising that you remove all non-digital characters, test for 9 character length, then store/handle the phone numbers in a single/reliable/basic format.

Body:
Pattern:  (Rubular Demo)

^\(?\d{3}\)?\d{3}-?\d{4}$   # this makes the expected symbols optional

This pattern will ensure that an opening ( at the start of the string is followed by 3 numbers the a closing ).

^(\(\d{3}\)|\d{3})\d{3}-?\d{4}$

On principle, though, I agree with melpomene in advising that you remove all non-digital characters, test for 9 character length, then store/handle the phone numbers in a single/reliable/basic format.


问:
navigate SQLite3 data base command
Ok, this is my first ever experience with sql, and I don't really know how to explain this well.

I want to run a command that will bring me to the CHAT database

and within the chat database, I want to get every value under guid and display_name row if the display_name entry is not nothing. In my picture, I would only get the display_name and guid with it for Group I.

What resourse can I use to look up these commands? Or can anyone tell me the commands to get this information?

答:
```<code>SELECT guid, display_name FROM chat WHERE display_name IS NOT ''
</code>```

Title: navigate SQLite3 data base command


问:
When debugging on WinCE, how can I set Visual Studio to always load symbol files it knows about?
I'm debugging a WinCE, C++ program in Visual Studio across an ActiveSync connection.  Every time I start the process it fails to load symbol information.  However, if I right click on the module and hit 'Load Symbols' it correctly locates the symbol information without any further prompting from me.

Is there a way that I can set Visual Studio to either:

(a) automatically load this symbol
information, or

(b) automatically
break the process into the debugger
once it's loaded (similar to what
windbg does)?

I'm guessing there's a setting somewhere, but I've yet to find it.

Update: I forgot to mention in the original question that I'm not debugging with the instance of Visual Studio that created the exe.

答: Visual Studio should be automatically loading symbols.  But this can be disabled.  Go to Tools -> Options -> Debugger -> Symbols.  There should be a check box saying something like "Only Load Symbols from these locations when specifically asked to".  If that box is checked then uncheck it.  </p>

OwnerDisplayName: tsellon

LastEditorDisplayName: tsellon

OwnerDisplayName: JaredPar


问:
Execute multiple statemens in a single STAssert… macro?
I’d like to execute more than one statement in the STAssertXX family of macros, is that possible? Something like:

```<code>STAssertTrue([foo doSomething] && [barDoSomethingElse], @"Should…");
</code>```

The code above works for methods that return booleans, I’d like something similar for void return types:

```<code>STAssertNoThrow({
    [foo doSomething];
    [bar doSomethingElse];
}, @"Should…");
</code>```

Of course, here the preprocessor complains.

答:
Since any valid C code is also valid Objective-C; you can use the , operator from C for a single argument, as long as you use it in parenthesis.

Like this:

```<code>NSAssertNoThrow(([foo doSomething], [bar doSomethingElse]), @"Whatever");
</code>```

The , operator lets you composite several expressions as a single statement returning the value of the last expression.

I would advise strongly against using this in STAssert… statements since you will loose important information about which tests that failed.

Body:
I’d like to execute more than one statement in the STAssertXX family of macros, is that possible? Something like:

STAssertTrue([foo doSomething] && [barDoSomethingElse], @"Should…");

The code above works for methods that return booleans, I’d like something similar for void return types:

STAssertNoThrow({
    [foo doSomething];
    [bar doSomethingElse];
}, @"Should…");

Of course, here the preprocessor complains.

Body:
Since any valid C code is also valid Objective-C; you can use the , operator from C for a single argument, as long as you use it in parenthesis.

Like this:

NSAssertNoThrow(([foo doSomething], [bar doSomethingElse]), @"Whatever");

The , operator lets you composite several expressions as a single statement returning the value of the last expression.

I would advise strongly against using this in STAssert… statements since you will loose important information about which tests that failed.


问:
Validate multiple DropDownList yii2
I'm trying validate a multiple dropdownlist, like this:

view/form:

```<code><?=
$form->field($hours, 'hours_id', ['template' => '{label}{input}<span class="help-block">{hint}{error}</span>'])->dropDownList(Hours::getHierarchy(), ['size' => 10, 'multiple' => 'multiple'], ['prompt' => Yii::t('app', '-- Select --'),
])
?>
</code>```

model rules:

```<code>['hours_id', 'each', 'rule' => ['integer']],
</code>```

Result:

Hour is invalid.

Someone knows what's wrong? I tried to custom validation, and i get the same error.

答:
By default multi select drop down for a field name will send options in following format:

```<code>name=value1&name=value2
</code>```

To be able to receive data as array (as it suspected for each validation) You should use name[] instead of name.

For your case

```<code><?=
    $form->field($hours, 'hours_id[]', ['template' => '{label}{input}<span class="help-block">{hint}{error}</span>'])->dropDownList(Hours::getHierarchy(), ['size' => 10, 'multiple' => 'multiple'], ['prompt' => Yii::t('app', '-- Select --')])
?>
</code>```

Title: Validate multiple DropDownList yii2

Body:
I'm trying validate a multiple dropdownlist, like this:

view/form:

<?=
$form->field($hours, 'hours_id', ['template' => '{label}{input}{hint}{error}'])->dropDownList(Hours::getHierarchy(), ['size' => 10, 'multiple' => 'multiple'], ['prompt' => Yii::t('app', '-- Select --'),
])
?>

model rules:

['hours_id', 'each', 'rule' => ['integer']],

Result:

Hour is invalid.

Someone knows what's wrong? I tried to custom validation, and i get the same error.

Body:
By default multi select drop down for a field name will send options in following format:

name=value1&name=value2

To be able to receive data as array (as it suspected for each validation) You should use name[] instead of name.

For your case

<?=
    $form->field($hours, 'hours_id[]', ['template' => '{label}{input}<span class="help-block">{hint}{error}</span>'])->dropDownList(Hours::getHierarchy(), ['size' => 10, 'multiple' => 'multiple'], ['prompt' => Yii::t('app', '-- Select --')])
?>


问:
putchar and printf not behaving as expected
I'm working through some of the exercises in K&R.  Exercise 1-6 asks for verification that the expression getchar() != EOF is either 0 or 1.  I understand why it is, but the code I wrote to prove it didn't work as expected.  I wrote the following two snippets:

Version 1:

```<code>int main(void)
{
    int c;

    while (c = getchar() != EOF)
    {
        putchar(c);
    }

    printf("%d at EOF\n", c);

    return 0;
}
</code>```

Version 2:

```<code>int main(void)
{
    int c;

    while (c = getchar() != EOF)
    {
         printf("%d\n", c);
    }

    printf("%d at EOF\n", c);

    return 0;
}
</code>```

My questions:

When I type in a character and hit enter with version one, why do I not see either a 0 or 1 on the screen?  Instead, my cursor moves to the first position on next line, which is otherwise empty.  I though putchar would send c to stdout.

While the use of printf in the second version does produce a 0 or 1 appropriately, it duplicates the 1 for each non-EOF character (I see the number 1 on two consecutive lines for each character I input).  Why?

Many thanks in advance for your thoughts.  If there is a reference that you think would help, please send a link.

CLARIFICATION:

I know I'm assigning c a value of either 0 or 1.  That's what I want to do, and it's what the exercise wants.  That's also why I don't have parentheses around c = getchar().  My question deals more with understanding why the output isn't what I had expected.  Sorry for any confusion.

答:
The assignment operator = has lower precedence than the inequality operator !=.

So this:

```<code>while (c = getchar() != EOF)
</code>```

Is parsed as:

```<code>while (c = (getchar() != EOF))
</code>```

So then c is assigned the boolean value 1 if getchar is not EOF and 0 if it does return EOF.

As a result, the first program print the character for the ASCII code 1, which is a non-printable character.  That's why you don't see anything.  The second program, using the %d format specifier to printf, converts the number 1 to its string representation.

You need parenthesis to have the result of getchar assigned to c:

```<code>while ((c = getchar()) != EOF)
</code>```

EDIT:

To further clarify the output you're getting, in both programs the variable c has the value 1 inside of each while loop.  The difference here is that putchar is printing the character with the ASCII value of 1 (an unprintable character), while printf with %d print the textual representation of the value 1, i.e. 1.

If you changed the printf call to this:

```<code>printf("%c", c);
</code>```

You would get the same output as using putchar.

As for the printing of 1 twice for each character, that is because you're actually entering two characters: the key you press, plus the enter key.  When reading from the console, the getchar function doesn't return until the enter key is pressed.

Body:
I'm working through some of the exercises in K&R.  Exercise 1-6 asks for verification that the expression getchar() != EOF is either 0 or 1.  I understand why it is, but the code I wrote to prove it didn't work as expected.  I wrote the following two snippets:

Version 1:

int main(void)
{
    int c;

    while (c = getchar() != EOF)
    {
        putchar(c);
    }

    printf("%d at EOF\n", c);

    return 0;
}

Version 2:

int main(void)
{
    int c;

    while (c = getchar() != EOF)
    {
         printf("%d\n", c);
    }

    printf("%d at EOF\n", c);

    return 0;
}

My questions:

When I type in a character and hit enter with version one, why do I not see either a 0 or 1 on the screen?  Instead, my cursor moves to the first position on next line, which is otherwise empty.  I though putchar would send c to stdout.

While the use of printf in the second version does produce a 0 or 1 appropriately, it duplicates the 1 for each non-EOF character (I see the number 1 on two consecutive lines for each character I input).  Why?

Many thanks in advance for your thoughts.  If there is a reference that you think would help, please send a link.

CLARIFICATION:

I know I'm assigning c a value of either 0 or 1.  That's what I want to do, and it's what the exercise wants.  That's also why I don't have parentheses around c = getchar().  My question deals more with understanding why the output isn't what I had expected.  Sorry for any confusion.

Body:
The assignment operator = has lower precedence than the inequality operator !=.

So this:

while (c = getchar() != EOF)

Is parsed as:

while (c = (getchar() != EOF))

So then c is assigned the boolean value 1 if getchar is not EOF and 0 if it does return EOF.

As a result, the first program print the character for the ASCII code 1, which is a non-printable character.  That's why you don't see anything.  The second program, using the %d format specifier to printf, converts the number 1 to its string representation.

You need parenthesis to have the result of getchar assigned to c:

while ((c = getchar()) != EOF)

EDIT:

To further clarify the output you're getting, in both programs the variable c has the value 1 inside of each while loop.  The difference here is that putchar is printing the character with the ASCII value of 1 (an unprintable character), while printf with %d print the textual representation of the value 1, i.e. 1.

If you changed the printf call to this:

printf("%c", c);

You would get the same output as using putchar.

As for the printing of 1 twice for each character, that is because you're actually entering two characters: the key you press, plus the enter key.  When reading from the console, the getchar function doesn't return until the enter key is pressed.


问:
Android BLE gattcallback issue on read and write
I'm stuck in one weird problem from last week and it will make me mad soon, Stackoverflow is my last hope.
I simply wrote a code to communicate with BLE device. At first i'm just writing a value on characteristic.

```<code>public void writeEnableCredentials(String keysFn) {
    if ( sGattCharList != null) {
        Log.i("Callback WEC Method: ", "Start!!!/n" );
        String val = keysFn.substring(0, 2);
        String val2 = keysFn.substring(2, 4);
        int val_1 = Integer.parseInt(val);
        int val_2 = Integer.parseInt(val2);
        byte[] rk_byte_Value = new byte[1];
        final byte[] rk_byte_Value_2 = new byte[1];
        rk_byte_Value[0] = (byte)(val_1 & 0xFF);
        rk_byte_Value_2[0] = (byte)(val_2 & 0xFF);
        sGattCharList.get(1).setValue(rk_byte_Value);
        boolean ok = sBluetoothGatt.writeCharacteristic(sGattCharList.get(1));
        Log.i("Callback WEC Method: ", "1 Verified = " + ok);
        if(ok) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sGattCharList.get(2).setValue(rk_byte_Value_2);
                    boolean ok = sBluetoothGatt.writeCharacteristic(sGattCharList.get(2));
                    Log.i("Callback WEC Method: ", "2 Verified = " + ok);
                }
            }, 100);
        }
    } else {
           Toast.makeText(activity, "Wait for services", Toast.LENGTH_SHORT).show();
    }
    Log.i("Callback WEC Method: ", "Stop!!!/n" );
}
</code>```

BluetoothGattCallback methods are below:

```<code>private final BluetoothGattCallback sGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            Log.i("CallbackGatt","Connecting with " + sDevice.getsMac());
            sBluetoothGatt.discoverServices();
        }
        else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            sBluetoothGatt.close();
            Log.i("CallbackGatt", "Disconnected from GATT server.");
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        services_List = gatt.getServices();
        sGattCharList = services_List.get(3).getCharacteristics();
        Log.i("CallbackGatt","Characteristic List Found: " + sGattCharList);
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt,
                                      BluetoothGattCharacteristic characteristic, int status) {
        if(status == BluetoothGatt.GATT_SUCCESS) {
            byte[] bytes = characteristic.getValue();
            System.out.println("ON Characteristic WRITE Callback: " + characteristic.getUuid()+"    value: "+bytes);
        }
    }

};
</code>```

ISSUE: This code is working perfectly on API>22. BUT on API<=22 BluetoothGattCallback are not working properly, sometime callback received but after running same build again i don't receive callbacks and characteristic don't wrote.

Debug Log Running build on 5.1.1

```<code>*Trying to write 1st time*
07-04 00:29:28.370 19270-19270/com.example.xxx.xxxx/Callback WEC Method:: Start!!!/n
07-04 00:29:28.371 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 1 Verified = true
07-04 00:29:28.372 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: Stop!!!/n
07-04 00:29:28.472 9115-9185/? E/bt-btif: already has a pending command!!
07-04 00:29:28.472 9115-9185/? E/bt-att: GATTC_Write GATT_BUSY conn_id = 6
07-04 00:29:28.474 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 2 Verified = true

*Trying to write 2nd time*
07-04 00:29:33.371 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: Start!!!/n
07-04 00:29:33.371 9115-9185/? E/bt-att: GATTC_Write GATT_BUSY conn_id = 6
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: GKI_exception(): Task State Table
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: TASK ID [0] task name [BTU] state [1]
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: TASK ID [1] task name [BTIF] state [1]
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: TASK ID [2] task name [A2DP-MEDIA] state [1]
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: GKI_exception 65532 Freeing Linked Buf
07-04 00:29:33.372 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.372 9115-9185/? E/GKI_LINUX: * GKI_exception(): 65532 Freeing Linked Buf
07-04 00:29:33.372 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.372 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 1 Verified = true
07-04 00:29:33.373 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: Stop!!!/n
07-04 00:29:33.474 9115-9185/? E/bt-att: GATTC_Write GATT_BUSY conn_id = 6
07-04 00:29:33.474 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 2 Verified = true
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: GKI_exception(): Task State Table
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: TASK ID [0] task name [BTU] state [1]
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: TASK ID [1] task name [BTIF] state [1]
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: TASK ID [2] task name [A2DP-MEDIA] state [1]
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: GKI_exception 65532 Freeing Linked Buf
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: * GKI_exception(): 65532 Freeing Linked Buf
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.562 339-339/? I/Gobi: vendor/qcom/proprietary/RIDL/RIDLClient/RIDLSQL.cpp:1920: GetTransState() EBADF
07-04 00:29:33.562 339-339/? I/Gobi: vendor/qcom/proprietary/RIDL/RIDLClient/MainCore.cpp:1346: Failed to get TransState, rc
07-04 00:29:33.562 339-339/? I/Gobi: vendor/qcom/proprietary/RIDL/RIDLClient/RIDLSQL.cpp:1920: GetTransState() EBADF
</code>```

kill app=> clear cache=> start app=> make connection=> try to write=> kill app

After do that process 4 time i finally got callback :D

```<code>07-04 00:34:39.144 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: Start!!!/n
07-04 00:34:39.147 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: 1 Verified = true
07-04 00:34:39.147 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: Stop!!!/n
07-04 00:34:39.233 26148-26166/com.example.xxx.xxxx I/System.out: ON Characteristic WRITE Callback: 0000fff2-0000-1000-8000-00805f9b34fb
07-04 00:34:39.247 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: 2 Verified = true
07-04 00:34:39.331 26148-26165/com.example.xxx.xxxx I/System.out: ON Characteristic WRITE Callback: 0000fff3-0000-1000-8000-00805f9b34fb
</code>```

If you guys need any other detail please ask. Also please tell me what is: E/GKI_LINUX: GKI_exception, Thanks.

答: You need to wait for the write callback before you issue a new operation. Simply waiting 100 ms is never guaranteed to work since it may take longer time to get the callback.</p>

Body:
I'm stuck in one weird problem from last week and it will make me mad soon, Stackoverflow is my last hope.
I simply wrote a code to communicate with BLE device. At first i'm just writing a value on characteristic.

public void writeEnableCredentials(String keysFn) {
    if ( sGattCharList != null) {
        Log.i("Callback WEC Method: ", "Start!!!/n" );
        String val = keysFn.substring(0, 2);
        String val2 = keysFn.substring(2, 4);
        int val_1 = Integer.parseInt(val);
        int val_2 = Integer.parseInt(val2);
        byte[] rk_byte_Value = new byte[1];
        final byte[] rk_byte_Value_2 = new byte[1];
        rk_byte_Value[0] = (byte)(val_1 & 0xFF);
        rk_byte_Value_2[0] = (byte)(val_2 & 0xFF);
        sGattCharList.get(1).setValue(rk_byte_Value);
        boolean ok = sBluetoothGatt.writeCharacteristic(sGattCharList.get(1));
        Log.i("Callback WEC Method: ", "1 Verified = " + ok);
        if(ok) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sGattCharList.get(2).setValue(rk_byte_Value_2);
                    boolean ok = sBluetoothGatt.writeCharacteristic(sGattCharList.get(2));
                    Log.i("Callback WEC Method: ", "2 Verified = " + ok);
                }
            }, 100);
        }
    } else {
           Toast.makeText(activity, "Wait for services", Toast.LENGTH_SHORT).show();
    }
    Log.i("Callback WEC Method: ", "Stop!!!/n" );
}

BluetoothGattCallback methods are below:

private final BluetoothGattCallback sGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            Log.i("CallbackGatt","Connecting with " + sDevice.getsMac());
            sBluetoothGatt.discoverServices();
        }
        else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            sBluetoothGatt.close();
            Log.i("CallbackGatt", "Disconnected from GATT server.");
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        services_List = gatt.getServices();
        sGattCharList = services_List.get(3).getCharacteristics();
        Log.i("CallbackGatt","Characteristic List Found: " + sGattCharList);
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt,
                                      BluetoothGattCharacteristic characteristic, int status) {
        if(status == BluetoothGatt.GATT_SUCCESS) {
            byte[] bytes = characteristic.getValue();
            System.out.println("ON Characteristic WRITE Callback: " + characteristic.getUuid()+"    value: "+bytes);
        }
    }

};

ISSUE: This code is working perfectly on API>22. BUT on API<=22 BluetoothGattCallback are not working properly, sometime callback received but after running same build again i don't receive callbacks and characteristic don't wrote.

Debug Log Running build on 5.1.1

*Trying to write 1st time*
07-04 00:29:28.370 19270-19270/com.example.xxx.xxxx/Callback WEC Method:: Start!!!/n
07-04 00:29:28.371 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 1 Verified = true
07-04 00:29:28.372 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: Stop!!!/n
07-04 00:29:28.472 9115-9185/? E/bt-btif: already has a pending command!!
07-04 00:29:28.472 9115-9185/? E/bt-att: GATTC_Write GATT_BUSY conn_id = 6
07-04 00:29:28.474 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 2 Verified = true

*Trying to write 2nd time*
07-04 00:29:33.371 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: Start!!!/n
07-04 00:29:33.371 9115-9185/? E/bt-att: GATTC_Write GATT_BUSY conn_id = 6
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: GKI_exception(): Task State Table
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: TASK ID [0] task name [BTU] state [1]
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: TASK ID [1] task name [BTIF] state [1]
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: TASK ID [2] task name [A2DP-MEDIA] state [1]
07-04 00:29:33.371 9115-9185/? E/GKI_LINUX: GKI_exception 65532 Freeing Linked Buf
07-04 00:29:33.372 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.372 9115-9185/? E/GKI_LINUX: * GKI_exception(): 65532 Freeing Linked Buf
07-04 00:29:33.372 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.372 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 1 Verified = true
07-04 00:29:33.373 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: Stop!!!/n
07-04 00:29:33.474 9115-9185/? E/bt-att: GATTC_Write GATT_BUSY conn_id = 6
07-04 00:29:33.474 19270-19270/com.example.xxx.xxxx I/Callback WEC Method:: 2 Verified = true
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: GKI_exception(): Task State Table
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: TASK ID [0] task name [BTU] state [1]
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: TASK ID [1] task name [BTIF] state [1]
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: TASK ID [2] task name [A2DP-MEDIA] state [1]
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: GKI_exception 65532 Freeing Linked Buf
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: * GKI_exception(): 65532 Freeing Linked Buf
07-04 00:29:33.474 9115-9185/? E/GKI_LINUX: ********************************************************************
07-04 00:29:33.562 339-339/? I/Gobi: vendor/qcom/proprietary/RIDL/RIDLClient/RIDLSQL.cpp:1920: GetTransState() EBADF
07-04 00:29:33.562 339-339/? I/Gobi: vendor/qcom/proprietary/RIDL/RIDLClient/MainCore.cpp:1346: Failed to get TransState, rc
07-04 00:29:33.562 339-339/? I/Gobi: vendor/qcom/proprietary/RIDL/RIDLClient/RIDLSQL.cpp:1920: GetTransState() EBADF

kill app=> clear cache=> start app=> make connection=> try to write=> kill app

After do that process 4 time i finally got callback :D

07-04 00:34:39.144 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: Start!!!/n
07-04 00:34:39.147 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: 1 Verified = true
07-04 00:34:39.147 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: Stop!!!/n
07-04 00:34:39.233 26148-26166/com.example.xxx.xxxx I/System.out: ON Characteristic WRITE Callback: 0000fff2-0000-1000-8000-00805f9b34fb
07-04 00:34:39.247 26148-26148/com.example.xxx.xxxx I/Callback WEC Method:: 2 Verified = true
07-04 00:34:39.331 26148-26165/com.example.xxx.xxxx I/System.out: ON Characteristic WRITE Callback: 0000fff3-0000-1000-8000-00805f9b34fb

If you guys need any other detail please ask. Also please tell me what is: E/GKI_LINUX: GKI_exception, Thanks.


问:
Text expands outside the div it's inside?
I've got this code:

```<code><html>
<head>
<style type="text/css">

body {
    text-align: center;
}

#content {
    width: 60em;
    margin: 0, auto;
    background-color: #CCC;
}

</style>
</head>

<body>
<center>
<div id="content">kdsjlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkhlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkkjdghkdsfjgksdjfhg</div>
</center>
</body>

</html>
</code>```

Why does the text not stay inside the div, but go in a single line until it ends? I want it to have line breaks relative to the div it's inside. How can I do this?

答:
Use the CSS attribute "word-wrap: "

```<code>#content {
width: 60em;
margin: 0, auto;
background-color: #CCC;
word-wrap: break-word;
</code>```

}

This used to be IE only, but I have seen it working in Chrome and Firefox.

Body:
I've got this code:

kdsjlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkhlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkkjdghkdsfjgksdjfhg

Why does the text not stay inside the div, but go in a single line until it ends? I want it to have line breaks relative to the div it's inside. How can I do this?

Body:
Use the CSS attribute "word-wrap: "

#content {
width: 60em;
margin: 0, auto;
background-color: #CCC;
word-wrap: break-word;

}

This used to be IE only, but I have seen it working in Chrome and Firefox.


问:
A counter variable in a php abstract class
If you have an abstract class, is there a way to keep a counter inside the abstract class to count how many times it's used?

Because if I do this:

```<code>abstract class abstractClassName {

    private $counter = 0;

    public function __construct() {
     $this->counter++;
   }

   public function outputCounter() {
     echo $this->counter;
   }

}

class someExtension extends abstractClassName {

  public function __construct() {
    parent::__construct();
  }
}

class someExtensionTwo extends abstractClassName {

  public function __construct() {
    parent::__construct();
  }
}
</code>```

and then

```<code>$class = new someExtension;
$class->outputCounter();
$class2 = new someExtensionTwo;
$class2->outputCounter();
</code>```

I get 1 twice, yet I was expecting to get 1 and then 2 on the last call, and I'm getting confused over how it's all meant to work.

Edit: changed code to reflect the real code more :)

答:
If you are wishing to keep track of how many time the class AbstractClassName has been instantiated, you will need to make use of static variables -- so that the value of $this->counter is persistent, for example:

```<code>abstract class abstractClassName
{
    private static $counter = 0;

    public function __construct() {
      self::$counter++;
    }

    public function outputCounter() {
     echo self::$counter;
    }
}

class someExtension extends abstractClassName
{
   public function __construct() {
     parent::__construct();
   }
 }

class someOtherExtension extends abstractClassName
{
   public function __construct() {
     parent::__construct();
   }
 }

$class = new someExtension;
$class->outputCounter();

$class2 = new someOtherExtension;
$class2->outputCounter();
</code>```

Which would result in an output of: 1 & 2.

Body:
If you have an abstract class, is there a way to keep a counter inside the abstract class to count how many times it's used?

Because if I do this:

abstract class abstractClassName {

    private $counter = 0;

    public function __construct() {
     $this->counter++;
   }

   public function outputCounter() {
     echo $this->counter;
   }

}

class someExtension extends abstractClassName {

  public function __construct() {
    parent::__construct();
  }
}

class someExtensionTwo extends abstractClassName {

  public function __construct() {
    parent::__construct();
  }
}

and then

$class = new someExtension;
$class->outputCounter();
$class2 = new someExtensionTwo;
$class2->outputCounter();

I get 1 twice, yet I was expecting to get 1 and then 2 on the last call, and I'm getting confused over how it's all meant to work.

Edit: changed code to reflect the real code more :)

Body:
If you are wishing to keep track of how many time the class AbstractClassName has been instantiated, you will need to make use of static variables -- so that the value of $this->counter is persistent, for example:

abstract class abstractClassName
{
    private static $counter = 0;

    public function __construct() {
      self::$counter++;
    }

    public function outputCounter() {
     echo self::$counter;
    }
}

class someExtension extends abstractClassName
{
   public function __construct() {
     parent::__construct();
   }
 }

class someOtherExtension extends abstractClassName
{
   public function __construct() {
     parent::__construct();
   }
 }

$class = new someExtension;
$class->outputCounter();

$class2 = new someOtherExtension;
$class2->outputCounter();

Which would result in an output of: 1 & 2.


问:
How to delay Tween.js animation until a button is clicked? (three.js)
I want to make it so the tween animation for my camera only starts when an object is clicked. This object could be an object in my three.js scene, or simply a HTML button. Here is my code for the camera animation, which works:

```<code>            // initial position of camera
            var camposition = { x : 0, y: 0, z:3100 };
            // target position that camera tweens to
            var camtarget = { x : 0, y: 0, z:8500 };
            var tweencam = new TWEEN.Tween(camposition).to(camtarget, 1600);

            tweencam.onUpdate(function(){
                camera.position.x = camposition.x;
                camera.position.y = camposition.y;
                camera.position.z = camposition.z;
            });

            // delay tween animation by three seconds
            tweencam.delay(3000);

            tweencam.easing(TWEEN.Easing.Exponential.InOut);

            tweencam.start();
</code>```

Instead of delaying the animation by three seconds, I want to detect when the mouse1 button has been clicked, and then start the animation. Not sure how to do this, or if there is an easier alternative method?

答:
All you have to do is wrap the start of the tween inside a function, and then call this function on a button click:

```<code>function launchTween() {
  tweencam.start();
}

<button onclick="launchTween()">Launch Tween</button>
</code>```

The entire code would look as follows:

// initial position of camera
var camposition = {
  x: 0,
  y: 0,
  z: 3100
};
// target position that camera tweens to
var camtarget = {
  x: 0,
  y: 0,
  z: 8500
};
var tweencam = new TWEEN.Tween(camposition).to(camtarget, 1600);

tweencam.onUpdate(function() {
  camera.position.x = camposition.x;
  camera.position.y = camposition.y;
  camera.position.z = camposition.z;
});

tweencam.easing(TWEEN.Easing.Exponential.InOut);

function launchTween() {
  tweencam.start();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="launchTween()">Launch Tween</button></code>```

Hope this helps! :)

Body:
I want to make it so the tween animation for my camera only starts when an object is clicked. This object could be an object in my three.js scene, or simply a HTML button. Here is my code for the camera animation, which works:

            // initial position of camera
            var camposition = { x : 0, y: 0, z:3100 };
            // target position that camera tweens to
            var camtarget = { x : 0, y: 0, z:8500 };
            var tweencam = new TWEEN.Tween(camposition).to(camtarget, 1600);

            tweencam.onUpdate(function(){
                camera.position.x = camposition.x;
                camera.position.y = camposition.y;
                camera.position.z = camposition.z;
            });

            // delay tween animation by three seconds
            tweencam.delay(3000);

            tweencam.easing(TWEEN.Easing.Exponential.InOut);

            tweencam.start();

Instead of delaying the animation by three seconds, I want to detect when the mouse1 button has been clicked, and then start the animation. Not sure how to do this, or if there is an easier alternative method?

Body:
All you have to do is wrap the start of the tween inside a function, and then call this function on a button click:

function launchTween() {
  tweencam.start();
}

<button onclick="launchTween()">Launch Tween</button>

The entire code would look as follows:

// initial position of camera
var camposition = {
  x: 0,
  y: 0,
  z: 3100
};
// target position that camera tweens to
var camtarget = {
  x: 0,
  y: 0,
  z: 8500
};
var tweencam = new TWEEN.Tween(camposition).to(camtarget, 1600);

tweencam.onUpdate(function() {
  camera.position.x = camposition.x;
  camera.position.y = camposition.y;
  camera.position.z = camposition.z;
});

tweencam.easing(TWEEN.Easing.Exponential.InOut);

function launchTween() {
  tweencam.start();
}

<button onclick="launchTween()">Launch Tween</button>

Hope this helps! :)


问:
Use nc to write multiple files - how?
I want to use nc as a simple TCP/IP server. So far I run it using:

```<code>$ nc -k -l 3000 > temp.tmp
</code>```

This works, but writes all the received data of all connections into one single file. But, I would like to have individual files.

Basically I get this if I skip the -k switch, but then nc shuts down as soon as the first connection is gone.

How can I keep nc running, but use an individual file for each incoming request? (Or, if this is not possible, is there an alternative *nix tool that is able to do this?)

Please note that I do not want to restart nc, but I want it all with a single running instance.

PS: I know that SO doesn't allow questions on finding tools, but for me this is only the fallback in case nc isn't able to do that by itself. So, sorry for the part in parentheses…

答:
On the receiver:

```<code>$ nc -p 3000 -l | tar -x
</code>```

On the sender:

```<code>$ tar -c * | nc <ip_address> 3000
</code>```

Title: Use nc to write multiple files - how?

Body:
I want to use nc as a simple TCP/IP server. So far I run it using:

$ nc -k -l 3000 > temp.tmp

This works, but writes all the received data of all connections into one single file. But, I would like to have individual files.

Basically I get this if I skip the -k switch, but then nc shuts down as soon as the first connection is gone.

How can I keep nc running, but use an individual file for each incoming request? (Or, if this is not possible, is there an alternative *nix tool that is able to do this?)

Please note that I do not want to restart nc, but I want it all with a single running instance.

PS: I know that SO doesn't allow questions on finding tools, but for me this is only the fallback in case nc isn't able to do that by itself. So, sorry for the part in parentheses…

Body:
On the receiver:

$ nc -p 3000 -l | tar -x

On the sender:

$ tar -c * | nc <ip_address> 3000


问:
rails : how to conditionally assign tag in haml
I'd like to add same content but assign a different tag in haml for the sake of SEO.
More specifically, I want the header to be
 in PostsController#index but to be
 on other pages so I try to use

```<code>-if current_page?(controller: 'top', action: 'index') ? %h2 , %h3
</code>```

but it doesn't work and I think the wrong part in %h2 %h3 part.

答:
You can use the haml_tag helper, something like this:

```<code>- haml_tag current_page?(controller: 'top', action: 'index') ? :h2 : :h3 do
  Content here.
</code>```

Note that the helper arguments are symbols, using : not %.

Body:
I'd like to add same content but assign a different tag in haml for the sake of SEO.
More specifically, I want the header to be
 in PostsController#index but to be
 on other pages so I try to use

-if current_page?(controller: 'top', action: 'index') ? %h2 , %h3

but it doesn't work and I think the wrong part in %h2 %h3 part.

Body:
You can use the haml_tag helper, something like this:

- haml_tag current_page?(controller: 'top', action: 'index') ? :h2 : :h3 do
  Content here.

Note that the helper arguments are symbols, using : not %.


问:
How can I unbind this .click action?
I'm trying to make this switch function so that when the on button is already clicked and the person clicks off, the on buttons CSS goes back to normal. I also want the switch to be set already on default. I've tried that too but had no luck.

HTML:

```<code><!DOCTYPE HTML>
<html>

<head>

    <title>Toggleswitch</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src='script.js' type='text/javascript'></script>

</head>
<body>

    <div class="switch-container">
        <button id="darkmodeon">ON</button>
        <button id="darkmodeoff">OFF</button>

    </div>

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

CSS:

```<code>body{
    background-color: black;
}

.switch-container{
    display: flex;
    justify-content: space-between;
    background-color: white;
    border-radius: 50px;
    padding: 5px;
    width: 135px;

}

#darkmodeon{
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: none;
    color: #a5a5a5;
    font-family:"calibri light";
    font-size: 15px;
    font-weight: bold;
    background-color: #e8e8e8;
}

#darkmodeoff{
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: none;
    color: #a5a5a5;
    font-family:"calibri light";
    font-size: 15px;
    font-weight: bold;
    background-color: #e8e8e8;
}
</code>```

jQuery:

```<code>$(document).ready(function(){

    var darkon = "#darkmodeon";
    var darkoff = "#darkmodeoff";

    $(darkon).click(function(){
        $(this).css({
            "background-color": "#66e86a",
            "color": "white" ,
            "transition": "all 0.3s ease"
        });
    });

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#66e86a",
            "color": "white" ,
            "transition": "all 0.3s ease"
        });
        $(this).unbind('click', darkon);
    });

});
</code>```

答:
.click(handler) is just a surrogate for .on('click', handler). To remove any handler previously bound to any event, on any element, use:

```<code>$(selector).off('eventName', handler)
</code>```

Example:

var whatever = function(){
    // code here
};
$(selector).on('click', whatever); // or $(selector).click(handler);
$(selector).off('click', whatever);
```

<p>While exemplifying how to unbind, the above example doesn't do much, because the function is unbound immediately after it was bound. Typically, you'd unbind based on your app's logic.</p>

<p>For example, if you want to unbind a <code>click</code> after first <code>click</code>, typically you'd use <code>.off()</code> inside the bound function:</p>

<pre class="lang-js prettyprint-override"><code>var whatever = function(){
  $(this).off('click', whatever);
  // code that only runs on first click.
};
$(selector).on('click', whatever); // or $(selector).click(handler);
</code>```

As for your example, why don't you just toggle a class on their parent?

$('.parent button').on('click', function(){
  $(this).closest('.parent').toggleClass('on');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*.parent button,
.parent.on button:first-child {
  display: none;
}
.parent button:first-child,
.parent.on button:last-child {
  display: inline;
}*/

/* if you don't want/like the animation, just use the simple `display` switch above */

.parent {
  position: relative;
  display: inline-block;
}
.parent button {
  transition: opacity .2s linear, transform .3s cubic-bezier(.4,0,.2,1);
}
.parent.on button:first-child {
  opacity: 0;
  transform: translateX(-100%);
}
.parent button:last-child {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  transform: translateX(100%)
}
.parent button:first-child,
.parent.on button:last-child {
  opacity: 1;
  transform: translateX(0)
}</code>```

  <button>On</button>
  <button>Off</button>

```

Title: How can I unbind this .click action?

Body:
I'm trying to make this switch function so that when the on button is already clicked and the person clicks off, the on buttons CSS goes back to normal. I also want the switch to be set already on default. I've tried that too but had no luck.

HTML:

<!DOCTYPE HTML>

    <title>Toggleswitch</title>
    <link rel="stylesheet" type="text/css" href="main.css">

        <button id="darkmodeon">ON</button>
        <button id="darkmodeoff">OFF</button>

CSS:

body{
    background-color: black;
}

.switch-container{
    display: flex;
    justify-content: space-between;
    background-color: white;
    border-radius: 50px;
    padding: 5px;
    width: 135px;

}

#darkmodeon{
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: none;
    color: #a5a5a5;
    font-family:"calibri light";
    font-size: 15px;
    font-weight: bold;
    background-color: #e8e8e8;
}

#darkmodeoff{
    width: 50px;
    height: 50px;
    border-radius: 100%;
    border: none;
    color: #a5a5a5;
    font-family:"calibri light";
    font-size: 15px;
    font-weight: bold;
    background-color: #e8e8e8;
}

jQuery:

$(document).ready(function(){

    var darkon = "#darkmodeon";
    var darkoff = "#darkmodeoff";

    $(darkon).click(function(){
        $(this).css({
            "background-color": "#66e86a",
            "color": "white" ,
            "transition": "all 0.3s ease"
        });
    });

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#66e86a",
            "color": "white" ,
            "transition": "all 0.3s ease"
        });
        $(this).unbind('click', darkon);
    });

});

Body:
.click(handler) is just a surrogate for .on('click', handler). To remove any handler previously bound to any event, on any element, use:

$(selector).off('eventName', handler)

Example:

var whatever = function(){
    // code here
};
$(selector).on('click', whatever); // or $(selector).click(handler);
$(selector).off('click', whatever);

While exemplifying how to unbind, the above example doesn't do much, because the function is unbound immediately after it was bound. Typically, you'd unbind based on your app's logic.

For example, if you want to unbind a click after first click, typically you'd use .off() inside the bound function:

var whatever = function(){
  $(this).off('click', whatever);
  // code that only runs on first click.
};
$(selector).on('click', whatever); // or $(selector).click(handler);

As for your example, why don't you just toggle a class on their parent?

$('.parent button').on('click', function(){
  $(this).closest('.parent').toggleClass('on');
})

/*.parent button,
.parent.on button:first-child {
  display: none;
}
.parent button:first-child,
.parent.on button:last-child {
  display: inline;
}*/

/* if you don't want/like the animation, just use the simple `display` switch above */

.parent {
  position: relative;
  display: inline-block;
}
.parent button {
  transition: opacity .2s linear, transform .3s cubic-bezier(.4,0,.2,1);
}
.parent.on button:first-child {
  opacity: 0;
  transform: translateX(-100%);
}
.parent button:last-child {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  transform: translateX(100%)
}
.parent button:first-child,
.parent.on button:last-child {
  opacity: 1;
  transform: translateX(0)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent">
  <button>On</button>
  <button>Off</button>
</div>


问:
Implementing Fingerprint authentication for Android
I am very interested in learning how to develop an android application which uses fingerprint authentication.

How can i implement that Fingerprint authentication?

答:
I made a short library for this if you want to take a look at it. Here is how to use it :

```<code><uses-permission android:name="android.permission.USE_FINGERPRINT"/>
...

FingerprintDialog dialog = new FingerprintDialog(Context);
dialog.show(R.string.title, R.string.message, new FingerprintCallback() {
    @Override
    public void onFingerprintSuccess() {}

    @Override
    public void onFingerprintCancel() {}
});
</code>```

There is the result :

Github link : https://github.com/omaflak/FingerprintDialog

Body:
I made a short library for this if you want to take a look at it. Here is how to use it :

<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
...

FingerprintDialog dialog = new FingerprintDialog(Context);
dialog.show(R.string.title, R.string.message, new FingerprintCallback() {
    @Override
    public void onFingerprintSuccess() {}

    @Override
    public void onFingerprintCancel() {}
});

There is the result :

Github link : https://github.com/omaflak/FingerprintDialog


问:
jquery ui autocomplete needs additional function
I have such autocomplete code:

```<code>$("input#PickupSpot").autocomplete({
  source: function(request, response){
     $.ajax({
        url: "AjaxSearch.aspx",
        dataType: "jsonp",
        data: {
           a: "getspots",
           c: "updateSpotList",
           q: request.term
        },
        success: function(){
           alert("Success");
        },
        error: function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
        }

     });
  }
</code>```

});

When i try to get data Firebug shows an error: "updateSpotList is not defined".
I need to creat a function called updateSpotList to get response from the server. And the success alert is never invoked.

Why do i need this function? Maybe there are something defined in aspx? It is:

```<code>string response = "";

 string callback = Request.QueryString["c"];
 string action = Request.QueryString["a"];
 string query = Request.QueryString["q"];

  //Ensure action parameter is set
  if(action != null && action.Equals("getspots")){
        //Ensure query parameter is set
        if (query != null && query.Length > 0){
            SpotListRequest request = new SpotListRequest
            {
                FreeText = query,
                Language = "sv-SE"
            };
            IEnumerable<Spot> spots = DataBridge.GetSpotList(null, null, query).OrderBy(i => i.FullName);

            JavaScriptSerializer js = new JavaScriptSerializer();

            string json = js.Serialize(spots.ToArray());

            //Ensure callback parameter is set
            if (callback != null && callback.Length > 0)
            {
                response = String.Format("{0}('{1}')", callback, json);
            }
        }
    }
</code>```

答:
You can specify a URL as the source parameter, instead of the data parameter.

http://jqueryui.com/demos/autocomplete/#option-source

The plugin will make a request to your server, and you should return a JSON array looking like this:

[{label: "Name"}, {label: "Name 2"}]

Change your JavaScript code to this:

```<code>$("input#PickupSpot").autocomplete({
  source: "AjaxSearch.aspx?a=getspots&c=updateSpotList"
});
</code>```

The autocomplete plugin will append a parameter named term to the source URL, with the current value of the input element, so a request would be made to: "AjaxSearch.aspx?a=getspots&c=updateSpotList&term=test" if you wrote test in the input element.

On the server, you want to change q to term.

Body:
I have such autocomplete code:

$("input#PickupSpot").autocomplete({
  source: function(request, response){
     $.ajax({
        url: "AjaxSearch.aspx",
        dataType: "jsonp",
        data: {
           a: "getspots",
           c: "updateSpotList",
           q: request.term
        },
        success: function(){
           alert("Success");
        },
        error: function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
        }

     });
  }

});

When i try to get data Firebug shows an error: "updateSpotList is not defined".
I need to creat a function called updateSpotList to get response from the server. And the success alert is never invoked.

Why do i need this function? Maybe there are something defined in aspx? It is:

string response = "";

 string callback = Request.QueryString["c"];
 string action = Request.QueryString["a"];
 string query = Request.QueryString["q"];

  //Ensure action parameter is set
  if(action != null && action.Equals("getspots")){
        //Ensure query parameter is set
        if (query != null && query.Length > 0){
            SpotListRequest request = new SpotListRequest
            {
                FreeText = query,
                Language = "sv-SE"
            };
            IEnumerable<Spot> spots = DataBridge.GetSpotList(null, null, query).OrderBy(i => i.FullName);

            JavaScriptSerializer js = new JavaScriptSerializer();

            string json = js.Serialize(spots.ToArray());

            //Ensure callback parameter is set
            if (callback != null && callback.Length > 0)
            {
                response = String.Format("{0}('{1}')", callback, json);
            }
        }
    }

Body:
You can specify a URL as the source parameter, instead of the data parameter.

http://jqueryui.com/demos/autocomplete/#option-source

The plugin will make a request to your server, and you should return a JSON array looking like this:

[{label: "Name"}, {label: "Name 2"}]

Change your JavaScript code to this:

$("input#PickupSpot").autocomplete({
  source: "AjaxSearch.aspx?a=getspots&c=updateSpotList"
});

The autocomplete plugin will append a parameter named term to the source URL, with the current value of the input element, so a request would be made to: "AjaxSearch.aspx?a=getspots&c=updateSpotList&term=test" if you wrote test in the input element.

On the server, you want to change q to term.


问:
Staggered Display of Materialized Carousels while displaying them in modals
I was making a display of carousel in the models, but I am facing problems. When I load the page and click on categories, the carousel appears staggered, or disoriented; but when I click inside the modal , it comes to exact shape. I am using the jQuery plugins, but I think I am not able to place them in order.
I am giving my HTML and JavaScript here; I have included jQuery and other CDN stuff properly.

html:

```<code><body>
<div id="modal1"  class="modal bottom-sheet">
    <div class="modal-content">

        <div id="modal2"  class="carousel ">
            <a class="carousel-item" href="#one!"><img src="1.jpg"></a>
            <a class="carousel-item" href="#two!"><img src="1.jpg"></a>
            <a class="carousel-item" href="#three!"><img src="1.jpg"></a>
            <a class="carousel-item" href="#four!"><img src="1.jpg"></a>
            <a class="carousel-item" href="#five!"><img src="1.jpg"></a>
        </div>

    </div>
    <div class="modal-footer">
        <a href="#" class="modal-action modal-close waves-effect waves-green btn-flat">Agree</a>
    </div>
</div>
<header>
<div class="navbar-fixed">
    <ul id="dropdown1" class="dropdown-content">
        <li><a href="#">Profile</a></li>
        <li class="divider"></li>
        <li><a href="#">Settings</a></li>
        <li class="divider"></li>
        <li><a href="#">Logout</a></li>
    </ul>
<nav>
    <div class="nav-wrapper" >
        <div class="brand-logo" href="#" style="height:100%;pointer-events: none;">
            <img src="logo.png" style="height:100%;">
        </div>
        <a href="#" class="brand-logo center" style="color: rgba(0,0,0,0.73);pointer-events: none;"><b>Idea Watch</b></a>
        <ul id="nav-mobile" class="right hide-on-med-and-down">
            <li><a id="cate" href="#modal1" style="color: rgba(0,0,0,0.73);margin-right: 40%">CATEGORIES</a></li>
            <li><a href="#" style="color: rgba(0,0,0,0.73);margin-right: 20%">BOOKMARKS</a></li>
            <li><a class="dropdown-button" href="#" data-activates="dropdown1" style="margin-left: 50%">ME<i class="material-icons right">arrow_drop_down</i></a></li>
        </ul>
    </div>
</nav>
</div>
</header>
</code>```

here is my JS:

```<code>$(document).ready(function () {
    let a = $(".dropdown-button");
    a.dropdown();
    $('.carousel').carousel();
    $('.modal').modal({
        dismissible: true, // Modal can be dismissed by clicking outside of the modal
        opacity: 0,
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%' // Ending top style attribute
    });
    $('.parallax').parallax();
});
</code>```

here is CSS:

```<code>.modal{
    position:absolute;
    overflow:scroll;
}
</code>```

Removing or writing the above css is doing nothing in favour

Please Help!

<----------Edit1------>
Image before click :

Image after click in modal  :

答:
You have to initialize components in the modal in its ready callback.

https://codepen.io/anon/pen/QgrMVd

```<code>$(document).ready(function () {
    let a = $(".dropdown-button");
    a.dropdown();
    $('.modal').modal({
        dismissible: true, // Modal can be dismissed by clicking outside of the modal
        opacity: 0,
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%', // Ending top style attribute
        ready: function(modal, trigger) { // Callback for Modal open. Modal and trigger parameters available.
          $('.carousel').carousel();
        },
    });
    $('.parallax').parallax();
});
</code>```

Body:
I was making a display of carousel in the models, but I am facing problems. When I load the page and click on categories, the carousel appears staggered, or disoriented; but when I click inside the modal , it comes to exact shape. I am using the jQuery plugins, but I think I am not able to place them in order.
I am giving my HTML and JavaScript here; I have included jQuery and other CDN stuff properly.

html:

        Agree

Profile

Settings

Logout

        Idea Watch

CATEGORIES

BOOKMARKS

MEarrow_drop_down

here is my JS:

$(document).ready(function () {
    let a = $(".dropdown-button");
    a.dropdown();
    $('.carousel').carousel();
    $('.modal').modal({
        dismissible: true, // Modal can be dismissed by clicking outside of the modal
        opacity: 0,
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%' // Ending top style attribute
    });
    $('.parallax').parallax();
});

here is CSS:

.modal{
    position:absolute;
    overflow:scroll;
}

Removing or writing the above css is doing nothing in favour

Please Help!

<----------Edit1------>
Image before click :

Image after click in modal  :

Body:
You have to initialize components in the modal in its ready callback.

https://codepen.io/anon/pen/QgrMVd

$(document).ready(function () {
    let a = $(".dropdown-button");
    a.dropdown();
    $('.modal').modal({
        dismissible: true, // Modal can be dismissed by clicking outside of the modal
        opacity: 0,
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%', // Ending top style attribute
        ready: function(modal, trigger) { // Callback for Modal open. Modal and trigger parameters available.
          $('.carousel').carousel();
        },
    });
    $('.parallax').parallax();
});


问:
Rails gem/plugin that gives suggestions how to optimize your DB queries
Some time ago I saw in a screencast showing a gem or plugin, which was able to suggest how to optimize your Rails DB queries, like where to use include or add an index and so on... Now I can't remember which screencast that was, but maybe somebody knows what I am talking about, I mean that gem/plugin.

答: Was it rails_best_practices?</p>

Body: Was it rails_best_practices?